From f38d3f711114f50a33e731040db816e104e230ac Mon Sep 17 00:00:00 2001 From: Jim Thorson <50178738+James-Thorson-NOAA@users.noreply.github.com> Date: Wed, 1 Jul 2026 08:26:13 -0700 Subject: [PATCH 01/37] disambiguate array for new RcppEigen --- src/tinyVAST.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/tinyVAST.cpp b/src/tinyVAST.cpp index 0c5892a2..988228e2 100644 --- a/src/tinyVAST.cpp +++ b/src/tinyVAST.cpp @@ -431,7 +431,7 @@ Type gamma_distribution( vector gamma_k, // distribution/projection for omega template -array omega_distribution( array omega_sc, +tmbutils::array omega_distribution( tmbutils::array omega_sc, vector model_options, Eigen::SparseMatrix Rho_cc, Eigen::SparseMatrix Gamma_cc, @@ -496,7 +496,7 @@ array omega_distribution( array omega_sc, // distribution/projection for xi template Type xi_distribution( vector model_options, - array xi_sl, + tmbutils::array xi_sl, vector log_sigmaxi_l, Eigen::SparseMatrix Q_ss, Type range, @@ -524,7 +524,7 @@ Type xi_distribution( vector model_options, // distribution/projection for epsilon template -array epsilon_distribution( array epsilon_stc, +tmbutils::array epsilon_distribution( tmbutils::array epsilon_stc, vector model_options, Eigen::SparseMatrix Rho_hh, Eigen::SparseMatrix Gamma_hh, @@ -546,7 +546,7 @@ array epsilon_distribution( array epsilon_stc, //if( epsilon_stc.size()>0 ){ // PARALLEL_REGION // Reshape for either model_options - array epsilon_hs( n_h, n_s ); + tmbutils::array epsilon_hs( n_h, n_s ); for( int s=0; s epsilon_distribution( array epsilon_stc, // distribution/projection for epsilon template -array delta_distribution( array delta_tc, +tmbutils::array delta_distribution( tmbutils::array delta_tc, vector model_options, Eigen::SparseMatrix Rho_hh, Eigen::SparseMatrix Gamma_hh, @@ -623,7 +623,7 @@ array delta_distribution( array delta_tc, int h; // Reshape for either model_options - array delta_h1( n_h, 1 ); + tmbutils::array delta_h1( n_h, 1 ); for( int t=0; t -vector multiply_epsilon( matrix A, vector weight, array x, int n_i ){ +vector multiply_epsilon( matrix A, vector weight, tmbutils::array x, int n_i ){ vector out( n_i ); out.setZero(); if( x.size() > 0 ){ @@ -684,7 +684,7 @@ vector multiply_epsilon( matrix A, vector weight, array x return out; } template -vector multiply_omega( matrix A, vector weight, array x, int n_i ){ +vector multiply_omega( matrix A, vector weight, tmbutils::array x, int n_i ){ vector out( n_i ); out.setZero(); if( x.size() > 0 ){ @@ -695,7 +695,7 @@ vector multiply_omega( matrix A, vector weight, array x, return out; } template -vector multiply_xi( Eigen::SparseMatrix A_is, array xi_sl, matrix W_il ){ +vector multiply_xi( Eigen::SparseMatrix A_is, tmbutils::array xi_sl, matrix W_il ){ vector out( W_il.rows() ); out.setZero(); if( xi_sl.size() > 0 ){ @@ -708,7 +708,7 @@ vector multiply_xi( Eigen::SparseMatrix A_is, array xi_sl, mat return out; } template -vector multiply_delta( array delta_tc, vector t_i, vector c_i, int n_i ){ +vector multiply_delta( tmbutils::array delta_tc, vector t_i, vector c_i, int n_i ){ vector delta_i( n_i ); delta_i.setZero(); if( delta_tc.size() > 0 ){ From 28a5d9e5774e947640c08a5ad78d44818b093986 Mon Sep 17 00:00:00 2001 From: Jim Thorson <50178738+James-Thorson-NOAA@users.noreply.github.com> Date: Wed, 1 Jul 2026 08:33:08 -0700 Subject: [PATCH 02/37] update tinyVAST@dev version and NEWS --- DESCRIPTION | 4 ++-- NEWS.md | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 4f39595d..a53e8c45 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,8 +1,8 @@ Type: Package Package: tinyVAST Title: Multivariate Spatio-Temporal Models using Structural Equations -Version: 1.6.1 -Date: 2026-06-30 +Version: 1.6.1.9000 +Date: 2026-07-01 Authors@R: c( person(c("James", "T."), "Thorson", , "James.Thorson@noaa.gov", role = c("aut", "cre"), diff --git a/NEWS.md b/NEWS.md index 84e1d0b6..297a0a0f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,7 @@ +# tinyVAST 1.6.1.9000 + +* Replace array with tmbutils::array in CPP, to disambiguate new array typedef in RcppEigen, following andrjohns in dsem#63 + # tinyVAST 1.6.1 * Fix AR sign in SAR example (was using negative, because I hadn't updated after changing signs in dsem) From 7402f4b92b62fc51742c5f4b81429e6d51aae991 Mon Sep 17 00:00:00 2001 From: Jim Thorson <50178738+James-Thorson-NOAA@users.noreply.github.com> Date: Wed, 1 Jul 2026 09:12:18 -0700 Subject: [PATCH 03/37] move functions to utils.h --- src/tinyVAST.cpp | 1077 +-------------------------------------------- src/utils.h | 1078 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1080 insertions(+), 1075 deletions(-) create mode 100644 src/utils.h diff --git a/src/tinyVAST.cpp b/src/tinyVAST.cpp index 988228e2..8c630de2 100644 --- a/src/tinyVAST.cpp +++ b/src/tinyVAST.cpp @@ -1,1080 +1,6 @@ #define TMB_LIB_INIT R_init_tinyVAST #include //Links in the TMB libraries - -enum valid_family { - gaussian_family = 0, - tweedie_family = 1, - lognormal_family = 2, - poisson_family = 3, - bernoulli_family = 4, - binomial_family = 4, - gamma_family = 5, - nbinom1_family = 6, - nbinom2_family = 7, - student_family = 8 -}; - -enum valid_link { - identity_link = 0, - log_link = 1, - logit_link = 2, - cloglog_link = 3 -}; - -// Old algorithmic constructor for tail-down exponential stream network, copied from VAST -//template -//Eigen::SparseMatrix Q_network( Type log_theta, -// int n_s, -// vector parent_s, -// vector child_s, -// vector dist_s ){ -// -// Eigen::SparseMatrix Q( n_s, n_s ); -// Type theta = exp( log_theta ); -// for(int s=0; s -Eigen::SparseMatrix vectorsToSparseMatrix( vector i, - vector j, - vector x, - int N ){ - - // https://eigen.tuxfamily.org/dox/classEigen_1_1SparseMatrix.html#title35 - using namespace Eigen; - std::vector> tripletList; - for( int index = 0; index < i.size(); index ++ ){ - tripletList.push_back(Triplet( i[index], j[index], x[index]) ); - } - SparseMatrix M( N, N ); - M.setFromTriplets( tripletList.begin(), tripletList.end() ); - - //Eigen::SparseMatrix M( N, N ); - //for(int index=0; index -struct spde_covariates_t{ - int n_s; - //int n_tri; - vector Tri_Area; - matrix E0; - matrix E1; - matrix E2; - matrix V_zk; - matrix TV; - Eigen::SparseMatrix G0; - Eigen::SparseMatrix G0_inv; - - // Define output - spde_covariates_t(SEXP x){ /* x = List passed from R */ - n_s = CppAD::Integer(asVector(getListElement(x,"n_s"))[0]); - //n_tri = CppAD::Integer(asVector(getListElement(x,"n_tri"))[0]); - Tri_Area = asVector(getListElement(x,"Tri_Area")); - E0 = asMatrix(getListElement(x,"E0")); - E1 = asMatrix(getListElement(x,"E1")); - E2 = asMatrix(getListElement(x,"E2")); - V_zk = asMatrix(getListElement(x,"V_zk")); - TV = asMatrix(getListElement(x,"TV")); - G0 = tmbutils::asSparseMatrix(getListElement(x,"G0")); - G0_inv = tmbutils::asSparseMatrix(getListElement(x,"G0_inv")); - } -}; -// make stiffness G1 from covariates in columns of E0, E1, E2 -template -Eigen::SparseMatrix G_spde_covariates( spde_covariates_t spde, - matrix H_jj, - //matrix V_zk, - vector triangle_k ){ - - // TO ADD EDGE COVARIATES: - // 0. add n_e = edge0_tj.rows() - // 1. Add TE, where dim(TE) = n_t \times 3, listing the edge-number for each triangle-edge of n_e edges - // 2. Add A_ek design matrix, where dim(A_ek) = n_e \times n_k (edge-covariates) - - // Extract objects - vector area_t = spde.Tri_Area; - matrix edge0_tj = spde.E0; - matrix edge1_tj = spde.E1; - matrix edge2_tj = spde.E2; - matrix s_tv = spde.TV; // dim = n_t \times n_v - matrix triangle_t1 = spde.V_zk * triangle_k.matrix(); - int n_s = spde.n_s; - int n_t = s_tv.rows(); - int n_v = s_tv.cols(); // number of vertices per triangle - int n_j = edge0_tj.cols(); // number of covariates (default = 2) - - // Output - Eigen::SparseMatrix G_ss(n_s, n_s); - - // Objects to assemble triangle contributions - matrix edges_vj( n_v, n_j ); - matrix Gt_vv( n_v, n_v ); - - // Calculate adjugate of H - //matrix adjH_jj = H_jj.inverse() * H_jj.determinant(); // CAUSES CRASH - matrix adjH_jj = H_jj.adjoint(); - - // Assemble stiffness G - for( int t=0; t Gt_ss( n_s, n_s ); - for(int v1 = 0; v1 < 3; v1++ ){ - for(int v2 = 0; v2 < 3; v2++ ){ - Gt_ss.coeffRef( s_tv(t,v1), s_tv(t,v2) ) = Gt_vv(v1,v2); - }} - G_ss += Gt_ss / ( 4.0 * area_t(t) ); - } - return G_ss; -} - -// Q_SAR( log_kappa, H, n_s, i_z, j_z, delta_z2 ) -// Using a SAR (not standardized) to approximate spatial function -template -Eigen::SparseMatrix Q_SAR( - //Type rho, - Type kappa, - matrix H, - int n_s, - vector i_z, - vector j_z, - matrix delta_z2 ){ - - //Type max_dist = delta_z2.cwiseAbs().maxCoeff(); - - //d_z = sqrt((delta_z2 %*% H)^2 %*% matrix(1,nrow=2,ncol=1))[,1] - matrix deltaprime_z2 = (delta_z2 * H); // / max_dist; - vector dist_z( i_z.size() ); - for( int z = 0; z < i_z.size(); z++ ){ - dist_z(z) = pow( pow(deltaprime_z2(z,0),2.0) + pow(deltaprime_z2(z,1),2.0), 0.5 ); - } - vector weight_z = exp( -kappa * dist_z ); - - // Make weight matrix - Eigen::SparseMatrix W_ss = vectorsToSparseMatrix( - i_z, j_z, weight_z, n_s - ); - - // Row-standardize W_ss - // Does *not* make sense when using anisotropy - //for( int row = 0; row < n_s; row ++ ){ - // Type rowsum = W_ss.row(row).sum(); - // W_ss.row(row) /= rowsum; - //} - - // Assemble - Eigen::SparseMatrix I_ss( n_s, n_s ); - I_ss.setIdentity(); - Eigen::SparseMatrix IminusP_ss = I_ss - W_ss; - Eigen::SparseMatrix Q = IminusP_ss.transpose() * IminusP_ss; - return Q; -} - -// New matrix-notation precision constructor for tail-down exponential stream network -template -Eigen::SparseMatrix Q_network2( Type log_theta, - int n_s, - vector parent_s, - vector child_s, - vector dist_s ){ - - // Compute vectors - Type theta = exp(log_theta); - vector v1_s = exp(-theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); - vector v2_s = exp(-2.0 * theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); - - // Make components - Eigen::SparseMatrix P_ss = vectorsToSparseMatrix( child_s, - parent_s, - v1_s, - n_s ); - Eigen::SparseMatrix D_ss = vectorsToSparseMatrix( child_s, - child_s, - v2_s, - n_s ); - Eigen::SparseMatrix invD_ss( n_s, n_s ); - for( int s=0; s DminusP_ss = D_ss - P_ss; - Eigen::SparseMatrix Q = DminusP_ss.transpose() * invD_ss * DminusP_ss; - return Q; -} - -// Functions to evaluate density for nearest-neighbors Gaussian process -template -vector covariance_function(vector d, Type sigma2, Type inv_range) { - return ((-d.array() * inv_range).exp() * sigma2).matrix(); -} -template -matrix covariance_function(matrix d, Type sigma2, Type inv_range) { - return ((-d.array() * inv_range).exp() * sigma2).matrix(); -} -/** \brief Object containing all data elements of an NNGP */ -template -struct nngp_data_t{ - vector nn_index_flat; - vector nn_len; - vector dist_to_nn_flat; - vector dist_within_nn_flat; - vector gp_order; - - // Define output - nngp_data_t(SEXP x){ /* x = List passed from R */ - nn_index_flat = asVector(getListElement(x,"nn_index_flat")); - nn_len = asVector(getListElement(x,"nn_len")); - dist_to_nn_flat = asVector(getListElement(x,"dist_to_nn_flat")); - dist_within_nn_flat = asVector(getListElement(x,"dist_within_nn_flat")); - gp_order = asVector(getListElement(x,"gp_order")); - } -}; -// Density function .. sigma2 fixed at 1.0 -template -Type NNGP( Type sigma2, - Type range, - vector field_s, - // Data - nngp_data_t nngp_data ){ - - // Using original order and ordered_structure, by calling gp_order(i) and gp_order(nn_ids), because: - // 1. using original version in new order is very slow! presumably the order is terrible for the inner Hessian - // 2. using re-ordered version of field is confusing for users - Type nll = 0.0; - Type inv_range = 1.0 / range; // Multiplication is faster than division - vector nn_index_flat = nngp_data.nn_index_flat; - //vector nn_start = nngp_data.nn_start; - vector nn_len = nngp_data.nn_len; - vector dist_to_nn_flat = nngp_data.dist_to_nn_flat; - vector dist_within_nn_flat = nngp_data.dist_within_nn_flat; - vector gp_order = nngp_data.gp_order; - int n = field_s.size(); - - int pos_mat = 0; - int pos_vec = 0; - for( int i = 0; i < n; i++ ){ - int k = nn_len(i); - - // No neighbors - if(k == 0){ - nll -= dnorm( field_s(gp_order(i)), Type(0.0), sqrt(sigma2), true ); - }else{ - // Extract neighbor indices and distance to neighbors - vector nn_ids(k); - vector dist_iN(k); - for (int j = 0; j < k; j++) { - nn_ids(j) = nn_index_flat(pos_vec); - dist_iN(j) = dist_to_nn_flat(pos_vec); - pos_vec++; - } - - // Extract within-neighbor distance matrix (k x k) ... - matrix dist_NN(k, k); - for (int r = 0; r < k; r++) { - for (int c = 0; c < k; c++) { - dist_NN(r, c) = dist_within_nn_flat(pos_mat); - pos_mat++; - } - } - - // Covariances - matrix Sigma_NN = covariance_function(dist_NN, sigma2, inv_range); - vector Sigma_iN = covariance_function(dist_iN, sigma2, inv_range); - - // Solve - //vector a_i = solve(Sigma_NN, Sigma_iN); - //vector a_i = Sigma_NN.ldlt().solve( Sigma_iN.matrix() ); - //Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > invSigma_NN; - //invSigma_NN.compute(Sigma_NN); - //vector a_i = invSigma_NN.solve(Sigma_iN); - matrix Sigma_NN_inv = atomic::matinv(Sigma_NN); - vector a_i = Sigma_NN_inv * Sigma_iN; - - // Residual variance - Type resid_var = sigma2 - (a_i * Sigma_iN).sum(); // + 1e-12; - - // Conditional mean - Type cond_mean = 0.0; - for (int j = 0; j < k; j++) { - cond_mean += a_i(j) * field_s(gp_order(nn_ids(j))); - } - - // Likelihood - nll -= dnorm( field_s(gp_order(i)), cond_mean, sqrt(resid_var), true ); - } - } - return nll; -} - -// Function to calculate RAM matrices -template -Eigen::SparseMatrix make_ram( matrix ram, - vector ram_start, - vector beta_z, - int n_c, - int what ){ - - Eigen::SparseMatrix out_cc(n_c, n_c); - out_cc.setZero(); - Type tmp; - - for(int r=0; r=1){ - tmp = beta_z(ram(r,3)-1); - }else{ - tmp = ram_start(r); - } - // Rho_cc - if( (ram(r,0)==1) && (what==0) ){ - out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; - } - // Gammainv_cc - if( (ram(r,0)==2) && (what==1) ){ - out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = 1 / tmp; - } - // Gamma_cc - if( (ram(r,0)==2) && (what==2) ){ - out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; - } - } - - return out_cc; -} - -// distribution/projection for gamma -// Based on: -// https://github.com/meganferg/FergusonEtal_20250125_EBS_Beluga_DSM/blob/main/src/te_tw_DSM.cpp#L85C9-L85C40 (Megan Ferguson) -template -Type gamma_distribution( vector gamma_k, - vector Sdims, - vector Sblock, - Eigen::SparseMatrix S_kk, - vector log_lambda ){ - - using namespace density; - Type nll = 0.0; - int start_gamma = 0; // Counter for gamma - int start_k = 0; // counter for columns of S_kk - int index_lambda = 0; - for(int z=0; z gamma_segment = gamma_k.segment(start_gamma, ngamma_z); - start_gamma += ngamma_z; - - // s() splines - if( Sblock(z) == 1 ){ - // Recover S_block - Eigen::SparseMatrix S_block = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i - - /// Quadratic-form GRMF - // GMRF(Q).Quadform(x) caused a problem calculating the log-determinant unnecessarily, resulting in valgrind error - //nll -= Type(0.5)*Type(m_z)*log_lambda(z) - Type(0.5)*exp(log_lambda(z))*GMRF(S_block).Quadform(gamma_segment); - nll -= Type(0.5)*Type(ngamma_z)*log_lambda(index_lambda) - Type(0.5) * exp(log_lambda(index_lambda)) * - (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); - - start_k += ngamma_z; - index_lambda += 1; - } - - // te() / ti() / t2() splines - if( Sblock(z) >= 2 ){ - // Recover S_block ... Eigen::SparseMatrix appears to initialize as empty so no .setZero() equivalent needed - Eigen::SparseMatrix S_block( ngamma_z, ngamma_z ); - for( int block=0; block < Sblock(z); block ++ ){ - Eigen::SparseMatrix S_tmp = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i - S_block += exp(log_lambda(index_lambda)) * S_tmp; - start_k += ngamma_z; - index_lambda++; - } - - /// Quadratic-form GRMF - nll -= 0.5*(atomic::logdet(matrix(S_block))) - 0.5 * - (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); - } - } - return( nll ); -} - -// distribution/projection for omega -template -tmbutils::array omega_distribution( tmbutils::array omega_sc, - vector model_options, - Eigen::SparseMatrix Rho_cc, - Eigen::SparseMatrix Gamma_cc, - Eigen::SparseMatrix Gammainv_cc, - Eigen::SparseMatrix Q_ss, - Type range, - nngp_data_t nngp_data, - Type &nll ){ - - if( omega_sc.size() > 0 ){ - int n_c = omega_sc.dim(1); - using namespace density; - Eigen::SparseMatrix I_cc( n_c, n_c ); - I_cc.setIdentity(); - if( omega_sc.size()>0 ){ // PARALLEL_REGION - Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; - if( model_options(1) == 0 ){ - // Separable precision ... Option-1 - //Eigen::SparseMatrix Linv_cc = Gammainv_cc * ( I_cc - Rho_cc ); - //Eigen::SparseMatrix Q_cc = Linv_cc.transpose() * Linv_cc; - - // Separable precision ... Option-2 - // Only compute Vinv_kk if Gamma_kk is full rank - Eigen::SparseMatrix V_cc = Gamma_cc.transpose() * Gamma_cc; - matrix Vinv_cc = invertSparseMatrix( V_cc ); - Eigen::SparseMatrix Vinv2_cc = asSparseMatrix( Vinv_cc ); - Eigen::SparseMatrix Q_cc = IminusRho_cc.transpose() * Vinv2_cc * IminusRho_cc; - - // GMRF for SEM: separable variable-space - nll += SEPARABLE( GMRF(Q_cc), GMRF(Q_ss) )( omega_sc ); - // Including this line with Makevars below seems to cause a crash: - // PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) - // PKG_CXXFLAGS=$(SHLIB_OPENMP_CXXFLAGS) - }else{ - // Rank-deficient (projection) method - if( model_options(0) == 7 ){ - vector omega_s( omega_sc.rows() ); - for( int ci = 0; ci < omega_sc.cols(); ci++ ){ - omega_s = omega_sc.col(ci); - nll += NNGP( Type(1.0), range, omega_s, nngp_data ); - } - }else{ - nll += SEPARABLE( GMRF(I_cc), GMRF(Q_ss) )( omega_sc ); - } - - // Sparse inverse-product - //Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; - Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_cc; - inverseIminusRho_cc.compute(IminusRho_cc); - - // (I-Rho)^{-1} * Gamma * Epsilon - matrix omega2_cs = Gamma_cc * omega_sc.matrix().transpose(); - matrix omega3_cs = inverseIminusRho_cc.solve(omega2_cs); - omega_sc = omega3_cs.transpose(); - } - } - } - - return omega_sc; -} - -// distribution/projection for xi -template -Type xi_distribution( vector model_options, - tmbutils::array xi_sl, - vector log_sigmaxi_l, - Eigen::SparseMatrix Q_ss, - Type range, - nngp_data_t nngp_data ){ - - Type nll = 0; - if( xi_sl.size() > 0 ){ - int n_l = xi_sl.cols(); - using namespace density; - if( model_options(0) == 7 ){ - vector xi_s( xi_sl.rows() ); - for( int l=0; l -tmbutils::array epsilon_distribution( tmbutils::array epsilon_stc, - vector model_options, - Eigen::SparseMatrix Rho_hh, - Eigen::SparseMatrix Gamma_hh, - Eigen::SparseMatrix Gammainv_hh, - Eigen::SparseMatrix Q_ss, - Type range, - nngp_data_t nngp_data, - Type &nll ){ - - if( epsilon_stc.size() > 0 ){ - int n_s = epsilon_stc.dim(0); - int n_t = epsilon_stc.dim(1); - int n_c = epsilon_stc.dim(2); - int n_h = n_t * n_c; - using namespace density; - Eigen::SparseMatrix I_hh( n_h, n_h ); - I_hh.setIdentity(); - int h; - - //if( epsilon_stc.size()>0 ){ // PARALLEL_REGION - // Reshape for either model_options - tmbutils::array epsilon_hs( n_h, n_s ); - for( int s=0; s IminusRho_hh = I_hh - Rho_hh; - - if( model_options(1) == 0 ){ - // Separable precision ... Option-1 - //Eigen::SparseMatrix Linv_hh = Gammainv_hh * ( I_hh - Rho_hh ); - //Eigen::SparseMatrix Q_hh = Linv_hh.transpose() * Linv_hh; - - // Separable precision ... Option-2 - // Only compute Vinv_kk if Gamma_kk is full rank - Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; - matrix Vinv_hh = invertSparseMatrix( V_hh ); - Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); - Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; - - // GMRF for DSEM: non-separable time-variable, with separable space - nll += SEPARABLE( GMRF(Q_ss), GMRF(Q_hh) )( epsilon_hs ); - }else{ - // Rank-deficient (projection) method - if( model_options(0) == 7 ){ - vector epsilon_s( epsilon_hs.cols() ); - for( int hi = 0; hi < epsilon_hs.rows(); hi++ ){ - epsilon_s = epsilon_hs.matrix().row(hi); - nll += NNGP( Type(1.0), range, epsilon_s, nngp_data ); - } - }else{ - nll += SEPARABLE( GMRF(Q_ss), GMRF(I_hh) )( epsilon_hs ); - } - - // Sparse inverse-product - //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; - Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; - inverseIminusRho_hh.compute(IminusRho_hh); - - // (I-Rho)^{-1} * Gamma * Epsilon - matrix e2_hs = Gamma_hh * epsilon_hs.matrix(); - matrix e3_hs = inverseIminusRho_hh.solve(e2_hs); - - // Transformations - for( int s=0; s -tmbutils::array delta_distribution( tmbutils::array delta_tc, - vector model_options, - Eigen::SparseMatrix Rho_hh, - Eigen::SparseMatrix Gamma_hh, - Eigen::SparseMatrix Gammainv_hh, - Type &nll ){ - - if( delta_tc.size() > 0 ){ - int n_t = delta_tc.dim(0); - int n_c = delta_tc.dim(1); - int n_h = n_t * n_c; - using namespace density; - Eigen::SparseMatrix I_hh( n_h, n_h ); - I_hh.setIdentity(); - int h; - - // Reshape for either model_options - tmbutils::array delta_h1( n_h, 1 ); - for( int t=0; t IminusRho_hh = I_hh - Rho_hh; - - if( model_options(1) == 0 ){ - Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; - matrix Vinv_hh = invertSparseMatrix( V_hh ); - Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); - Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; - - // GMRF for DSEM: non-separable time-variable, with separable space - nll += GMRF(Q_hh)( delta_h1 ); - }else{ - // Rank-deficient (projection) method - nll += GMRF(I_hh)( delta_h1 ); - - // Sparse inverse-product - //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; - Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; - inverseIminusRho_hh.compute(IminusRho_hh); - - // (I-Rho)^{-1} * Gamma * Epsilon - matrix e2_h1 = Gamma_hh * delta_h1.matrix(); - matrix e3_h1 = inverseIminusRho_hh.solve(e2_h1); - - // Transformations - for( int t=0; t -bool isNA(Type x){ - return R_IsNA(asDouble(x)); -} - -// Sparse array * matrix -// NAs in IVECTOR or IMATRIX get converted to -2147483648, so isNA doesn't work ... instead drop NAs from A prior to passing to TMB -template -vector multiply_epsilon( matrix A, vector weight, tmbutils::array x, int n_i ){ - vector out( n_i ); - out.setZero(); - if( x.size() > 0 ){ - for( int z=0; z -vector multiply_omega( matrix A, vector weight, tmbutils::array x, int n_i ){ - vector out( n_i ); - out.setZero(); - if( x.size() > 0 ){ - for( int z=0; z -vector multiply_xi( Eigen::SparseMatrix A_is, tmbutils::array xi_sl, matrix W_il ){ - vector out( W_il.rows() ); - out.setZero(); - if( xi_sl.size() > 0 ){ - matrix xi_il = A_is * xi_sl.matrix(); - for( int i=0; i -vector multiply_delta( tmbutils::array delta_tc, vector t_i, vector c_i, int n_i ){ - vector delta_i( n_i ); - delta_i.setZero(); - if( delta_tc.size() > 0 ){ - for( int i=0; i -Type sign(Type x){ - return x / pow(pow(x,2),0.5); -} - -// dlnorm -template -Type dlnorm( Type x, - Type meanlog, - Type sdlog, - int give_log=0){ - - //return 1/(sqrt(2*M_PI)*sd) * exp(-.5*pow((x-mean)/sd,2)); - Type logres = dnorm( log(x), meanlog, sdlog, true) - log(x); - if(give_log) return logres; else return exp(logres); -} - -// dlnorm -template -Type dbinom_custom( Type x, - Type log_prob, - Type log_one_minus_prob, - Type size, - int give_log = 0 ){ - - // size choose x - Type logres = lgamma(size + 1.0) - lgamma(x + 1.0) - lgamma(size - x + 1.0); - // p^x * (1-p)^(size-x) - logres += x * log_prob + (size-x) * log_one_minus_prob; - if(give_log) return logres; else return exp(logres); -} - -// dlnorm -template -Type devresid_binom( Type y, - Type weight, // weight = size - Type mu ){ - - Type y_weight = y * weight; - Type mu_weight = mu * weight; - Type p1, p2; - if(y_weight == 0){ - p1 = 0.0; - }else{ - p1 = y_weight * log(y_weight / mu_weight); - } - if( (weight - y_weight) == 0 ){ - p2 = 0.0; - }else{ - p2 = (weight - y_weight) * log( (weight - y_weight) / (weight - mu_weight) ); - } - Type devresid = sign(y - mu) * pow(2 * (p1 + p2), 0.5); - return devresid; -} - -// Deviance for the Tweedie -// https://en.wikipedia.org/wiki/Tweedie_distribution#Properties -template -Type devresid_tweedie( Type y, - Type mu, - Type p ){ - - Type c1 = pow( y, 2.0-p ) / (1.0-p) / (2.0-p); - Type c2 = y * pow( mu, 1.0-p ) / (1.0-p); - Type c3 = pow( mu, 2.0-p ) / (2.0-p); - Type deviance = 2 * (c1 - c2 + c3 ); - Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); - return devresid; -} - -// Deviance for the student-T -// from chatGPT (experimental) ... converges on Gaussian as df -> Inf -template -Type devresid_student( Type y, - Type mu, - Type sigma, - Type df ){ - - Type deviance = (df + 1.0) * log( 1.0 + pow(y-mu,2.0) / (df * sigma*sigma) ); - Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); - return devresid; -} - -// COPIED from sdmTMB.cpp in sdmTMB package on Nov. 14, 2025 -template -Type dstudent(Type x, Type mean, Type sigma, Type df, int give_log = 0) { - // from metRology::dt.scaled() - // dt((x - mean)/sd, df, ncp = ncp, log = TRUE) - log(sd) - Type logres = dt((x - mean) / sigma, df, true) - log(sigma); - if (give_log) - return logres; - else - return exp(logres); -} - -// Deviance for the Negative binomial -//template -//Type devresid_nbinom1( Type y, -// Type logmu, -// Type logtheta ){ -// -// // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu -// Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), log(y + Type(1e-10)) + logtheta, true ); -// Type logp2 = dnbinom_robust( y, logmu, logmu + logtheta, true ); -// Type deviance = 2 * (logp1 - logp2); -// Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); -// return devresid; -//} -template -Type devresid_nbinom2( Type y, - Type logmu, - Type logtheta ){ - - // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), Type(2.0) * log(y + Type(1e-10)) - logtheta, true ); - Type logp2 = dnbinom_robust( y, logmu, Type(2.0) * logmu - logtheta, true ); - Type deviance = 2 * (logp1 - logp2); - Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); - return devresid; -} - - -// distribution/projection for epsilon -// deviance = deviance1 + deviance2 -template -Type one_predictor_likelihood( Type &y, - Type p, - Type size, - int link, - int family, - vector log_sigma_segment, - Type &nll, - Type &devresid, - objective_function* of ){ - Type mu, logmu, log_one_minus_mu; - //Type devresid = 0; - - switch( link ){ - case identity_link: - mu = p; - logmu = log( p ); - log_one_minus_mu = log( Type(1.0) - mu ); - break; - case log_link: - mu = exp(p); - logmu = p; - log_one_minus_mu = log( Type(1.0) - mu ); - break; - case logit_link: - mu = invlogit(p); - //logmu = log(mu); - logmu = p - logspace_add( Type(0.0), p ); - //log_one_minus_mu = log( invlogit(-1 * p) ); - log_one_minus_mu = 0.0 - logspace_add( Type(0.0), p ); - break; - case cloglog_link: - mu = Type(1.0) - exp( -1 * exp(p) ); - logmu = logspace_sub( Type(0.0), -1.0 * exp(p) ); - log_one_minus_mu = -1.0 * exp(p); - break; - default: - error("Link not implemented."); - } - if( !R_IsNA(asDouble(y)) ){ - // Distribution - switch( family ){ - case gaussian_family: - nll = -1 * dnorm( y, mu, exp(log_sigma_segment(0)), true ); - devresid = y - mu; - if(isDouble::value && of->do_simulate){ - y = rnorm( mu, exp(log_sigma_segment(0)) ); - } - break; - case tweedie_family: - nll = -1 * dtweedie( y, mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); - devresid = devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); - if(isDouble::value && of->do_simulate){ - y = rtweedie( mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); - } - break; - case lognormal_family: - nll = -1 * dlnorm( y, logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); - devresid = log(y) - ( logmu - 0.5*exp(2.0*log_sigma_segment(0)) ); - if(isDouble::value && of->do_simulate){ - y = exp(rnorm( logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); - } - break; - case poisson_family: - nll = -1 * dpois( y, mu, true ); - devresid = sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); - if(isDouble::value && of->do_simulate){ - y = rpois( mu ); - } - break; - case binomial_family: - //if(y==0){ - // nll = -1 * log_one_minus_mu; - //}else{ - // nll = -1 * logmu; - //} - nll = -1 * dbinom_custom( y * size, logmu, log_one_minus_mu, size, true ); - if(isDouble::value && of->do_simulate){ - y = rbinom( size, mu ); - } - // TODO: Update deviance residual for Trials = size - //devresid = sign(y - mu) * pow(-2*((1-y)*log(1.0-mu) + y*log(mu)), 0.5); - devresid = devresid_binom( y, size, mu ); - break; - case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 - nll = -1 * dgamma( y, exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)), true ); - devresid = sign(y - mu) * pow(2 * ( (y-mu)/mu - log(y/mu) ), 0.5); - if(isDouble::value && of->do_simulate){ - y = rgamma( exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)) ); - } - break; - case nbinom1_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) - // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu - nll = -1 * dnbinom_robust( y, logmu, logmu + log_sigma_segment(0), true); - devresid = devresid_nbinom2( y, logmu, logmu - log_sigma_segment(0) ); // theta = mu / phi - if(isDouble::value && of->do_simulate){ - // rnbinom2( mu, var ) - y = rnbinom2( mu, mu * (Type(1.0) + exp(log_sigma_segment(0))) ); - } - break; - case nbinom2_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) - // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - nll = -1 * dnbinom_robust( y, logmu, Type(2.0) * logmu - log_sigma_segment(0), true); - devresid = devresid_nbinom2( y, logmu, log_sigma_segment(0) ); - if(isDouble::value && of->do_simulate){ - // rnbinom2( mu, var ) - y = rnbinom2( mu, mu * (Type(1.0) + mu / exp(log_sigma_segment(0))) ); - } - break; - case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) - // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - nll = -1 * dstudent( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); - devresid = devresid_student( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)) ); - if(isDouble::value && of->do_simulate){ - y = mu + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); - } - break; - default: - error("Distribution not implemented."); - } - } - - return mu; -} - -// distribution/projection for epsilon -template -Type two_predictor_likelihood( Type &y, - Type p1, - Type p2, - Type size, - vector link, - vector family, - vector log_sigma_segment, - int poislink, - Type &nll, - Type &dev, - objective_function* of ){ - Type mu1, logmu1, mu2, logmu2, log_one_minus_mu1; - - // First link - if( poislink==0 ){ - mu1 = invlogit( p1 ); - logmu1 = log( mu1 ); - log_one_minus_mu1 = log( Type(1.0) - mu1 ); - // second link - switch( link(1) ){ - case identity_link: - mu2 = p2; - logmu2 = log( p2 ); - break; - case log_link: - mu2 = exp(p2); - logmu2 = p2; - break; - default: - error("Link not implemented."); - } - }else{ - mu1 = Type(1.0) - exp( -1.0*exp(p1) ); - logmu1 = logspace_sub( Type(0.0), -1*exp(p1) ); - log_one_minus_mu1 = -1.0*exp(p1); - mu2 = exp( p1 + p2 ) / mu1; - logmu2 = p1 + p2 - logmu1; - } - if( !R_IsNA(asDouble(y)) ){ - // Distribution - if(isDouble::value && of->do_simulate){ - y = rbinom( Type(1), mu1 ); - } - if( y == 0 ){ - nll = -1 * log_one_minus_mu1; - dev = -2 * log_one_minus_mu1; - } - if( y>0 ){ // Not if-else so y>0 triggered when simulating y>0 - nll = -1 * logmu1; - dev = -2 * logmu1; - //deviance1_i(i) = -2 * log_mu1(i); - switch( family(1) ){ - case gaussian_family: - nll -= dnorm( y, mu2, exp(log_sigma_segment(0)), true ); - dev += pow(y - mu2, 2.0); - if(isDouble::value && of->do_simulate){ - y = rnorm( mu2, exp(log_sigma_segment(0)) ); - } - break; - //case tweedie_family: - // nll -= dtweedie( y, mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); - // devresid += devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); - // if(isDouble::value && of->do_simulate){ - // y = rtweedie( mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); - // } - // break; - case lognormal_family: - nll -= dlnorm( y, logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); - dev += pow( log(y) - (logmu2 - 0.5*exp(2.0*log_sigma_segment(0))), 2.0 ); - if(isDouble::value && of->do_simulate){ - y = exp(rnorm( logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); - } - break; - //case poisson_family: - // nll -= dpois( y, mu2, true ); - // devresid += sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); - // if(isDouble::value && of->do_simulate){ - // y = rpois( mu2 ); - // } - // break; - // case 4: // Bernoulli - case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 - nll -= dgamma( y, exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)), true ); - dev += 2 * ( (y-mu2)/mu2 - log(y/mu2) ); - if(isDouble::value && of->do_simulate){ - y = rgamma( exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)) ); - } - break; - case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) - // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - nll -= dstudent( y, mu2, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); - //dev = NAN; - if(isDouble::value && of->do_simulate){ - y = mu2 + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); - } - break; - default: - error("Distribution not implemented."); - } - } - } - - return mu1 * mu2; -} +#include "utils.h" // Coding principles // 1. Don't telescope model features using `map` (which is bug-prone), but @@ -1091,6 +17,7 @@ Type objective_function::operator() (){ //using namespace R_inla; // Not loaded globally, but used below using namespace density; using namespace Eigen; + using namespace tinyVAST; // Settings DATA_IMATRIX( family_ez ); // family diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 00000000..cf5a31f2 --- /dev/null +++ b/src/utils.h @@ -0,0 +1,1078 @@ +namespace tinyVAST { + +enum valid_family { + gaussian_family = 0, + tweedie_family = 1, + lognormal_family = 2, + poisson_family = 3, + bernoulli_family = 4, + binomial_family = 4, + gamma_family = 5, + nbinom1_family = 6, + nbinom2_family = 7, + student_family = 8 +}; + +enum valid_link { + identity_link = 0, + log_link = 1, + logit_link = 2, + cloglog_link = 3 +}; + +// Old algorithmic constructor for tail-down exponential stream network, copied from VAST +//template +//Eigen::SparseMatrix Q_network( Type log_theta, +// int n_s, +// vector parent_s, +// vector child_s, +// vector dist_s ){ +// +// Eigen::SparseMatrix Q( n_s, n_s ); +// Type theta = exp( log_theta ); +// for(int s=0; s +Eigen::SparseMatrix vectorsToSparseMatrix( vector i, + vector j, + vector x, + int N ){ + + // https://eigen.tuxfamily.org/dox/classEigen_1_1SparseMatrix.html#title35 + using namespace Eigen; + std::vector> tripletList; + for( int index = 0; index < i.size(); index ++ ){ + tripletList.push_back(Triplet( i[index], j[index], x[index]) ); + } + SparseMatrix M( N, N ); + M.setFromTriplets( tripletList.begin(), tripletList.end() ); + + //Eigen::SparseMatrix M( N, N ); + //for(int index=0; index +struct spde_covariates_t{ + int n_s; + //int n_tri; + vector Tri_Area; + matrix E0; + matrix E1; + matrix E2; + matrix V_zk; + matrix TV; + Eigen::SparseMatrix G0; + Eigen::SparseMatrix G0_inv; + + // Define output + spde_covariates_t(SEXP x){ /* x = List passed from R */ + n_s = CppAD::Integer(asVector(getListElement(x,"n_s"))[0]); + //n_tri = CppAD::Integer(asVector(getListElement(x,"n_tri"))[0]); + Tri_Area = asVector(getListElement(x,"Tri_Area")); + E0 = asMatrix(getListElement(x,"E0")); + E1 = asMatrix(getListElement(x,"E1")); + E2 = asMatrix(getListElement(x,"E2")); + V_zk = asMatrix(getListElement(x,"V_zk")); + TV = asMatrix(getListElement(x,"TV")); + G0 = tmbutils::asSparseMatrix(getListElement(x,"G0")); + G0_inv = tmbutils::asSparseMatrix(getListElement(x,"G0_inv")); + } +}; +// make stiffness G1 from covariates in columns of E0, E1, E2 +template +Eigen::SparseMatrix G_spde_covariates( spde_covariates_t spde, + matrix H_jj, + //matrix V_zk, + vector triangle_k ){ + + // TO ADD EDGE COVARIATES: + // 0. add n_e = edge0_tj.rows() + // 1. Add TE, where dim(TE) = n_t \times 3, listing the edge-number for each triangle-edge of n_e edges + // 2. Add A_ek design matrix, where dim(A_ek) = n_e \times n_k (edge-covariates) + + // Extract objects + vector area_t = spde.Tri_Area; + matrix edge0_tj = spde.E0; + matrix edge1_tj = spde.E1; + matrix edge2_tj = spde.E2; + matrix s_tv = spde.TV; // dim = n_t \times n_v + matrix triangle_t1 = spde.V_zk * triangle_k.matrix(); + int n_s = spde.n_s; + int n_t = s_tv.rows(); + int n_v = s_tv.cols(); // number of vertices per triangle + int n_j = edge0_tj.cols(); // number of covariates (default = 2) + + // Output + Eigen::SparseMatrix G_ss(n_s, n_s); + + // Objects to assemble triangle contributions + matrix edges_vj( n_v, n_j ); + matrix Gt_vv( n_v, n_v ); + + // Calculate adjugate of H + //matrix adjH_jj = H_jj.inverse() * H_jj.determinant(); // CAUSES CRASH + matrix adjH_jj = H_jj.adjoint(); + + // Assemble stiffness G + for( int t=0; t Gt_ss( n_s, n_s ); + for(int v1 = 0; v1 < 3; v1++ ){ + for(int v2 = 0; v2 < 3; v2++ ){ + Gt_ss.coeffRef( s_tv(t,v1), s_tv(t,v2) ) = Gt_vv(v1,v2); + }} + G_ss += Gt_ss / ( 4.0 * area_t(t) ); + } + return G_ss; +} + +// Q_SAR( log_kappa, H, n_s, i_z, j_z, delta_z2 ) +// Using a SAR (not standardized) to approximate spatial function +template +Eigen::SparseMatrix Q_SAR( + //Type rho, + Type kappa, + matrix H, + int n_s, + vector i_z, + vector j_z, + matrix delta_z2 ){ + + //Type max_dist = delta_z2.cwiseAbs().maxCoeff(); + + //d_z = sqrt((delta_z2 %*% H)^2 %*% matrix(1,nrow=2,ncol=1))[,1] + matrix deltaprime_z2 = (delta_z2 * H); // / max_dist; + vector dist_z( i_z.size() ); + for( int z = 0; z < i_z.size(); z++ ){ + dist_z(z) = pow( pow(deltaprime_z2(z,0),2.0) + pow(deltaprime_z2(z,1),2.0), 0.5 ); + } + vector weight_z = exp( -kappa * dist_z ); + + // Make weight matrix + Eigen::SparseMatrix W_ss = vectorsToSparseMatrix( + i_z, j_z, weight_z, n_s + ); + + // Row-standardize W_ss + // Does *not* make sense when using anisotropy + //for( int row = 0; row < n_s; row ++ ){ + // Type rowsum = W_ss.row(row).sum(); + // W_ss.row(row) /= rowsum; + //} + + // Assemble + Eigen::SparseMatrix I_ss( n_s, n_s ); + I_ss.setIdentity(); + Eigen::SparseMatrix IminusP_ss = I_ss - W_ss; + Eigen::SparseMatrix Q = IminusP_ss.transpose() * IminusP_ss; + return Q; +} + +// New matrix-notation precision constructor for tail-down exponential stream network +template +Eigen::SparseMatrix Q_network2( Type log_theta, + int n_s, + vector parent_s, + vector child_s, + vector dist_s ){ + + // Compute vectors + Type theta = exp(log_theta); + vector v1_s = exp(-theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); + vector v2_s = exp(-2.0 * theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); + + // Make components + Eigen::SparseMatrix P_ss = vectorsToSparseMatrix( child_s, + parent_s, + v1_s, + n_s ); + Eigen::SparseMatrix D_ss = vectorsToSparseMatrix( child_s, + child_s, + v2_s, + n_s ); + Eigen::SparseMatrix invD_ss( n_s, n_s ); + for( int s=0; s DminusP_ss = D_ss - P_ss; + Eigen::SparseMatrix Q = DminusP_ss.transpose() * invD_ss * DminusP_ss; + return Q; +} + +// Functions to evaluate density for nearest-neighbors Gaussian process +template +vector covariance_function(vector d, Type sigma2, Type inv_range) { + return ((-d.array() * inv_range).exp() * sigma2).matrix(); +} +template +matrix covariance_function(matrix d, Type sigma2, Type inv_range) { + return ((-d.array() * inv_range).exp() * sigma2).matrix(); +} +/** \brief Object containing all data elements of an NNGP */ +template +struct nngp_data_t{ + vector nn_index_flat; + vector nn_len; + vector dist_to_nn_flat; + vector dist_within_nn_flat; + vector gp_order; + + // Define output + nngp_data_t(SEXP x){ /* x = List passed from R */ + nn_index_flat = asVector(getListElement(x,"nn_index_flat")); + nn_len = asVector(getListElement(x,"nn_len")); + dist_to_nn_flat = asVector(getListElement(x,"dist_to_nn_flat")); + dist_within_nn_flat = asVector(getListElement(x,"dist_within_nn_flat")); + gp_order = asVector(getListElement(x,"gp_order")); + } +}; +// Density function .. sigma2 fixed at 1.0 +template +Type NNGP( Type sigma2, + Type range, + vector field_s, + // Data + nngp_data_t nngp_data ){ + + // Using original order and ordered_structure, by calling gp_order(i) and gp_order(nn_ids), because: + // 1. using original version in new order is very slow! presumably the order is terrible for the inner Hessian + // 2. using re-ordered version of field is confusing for users + Type nll = 0.0; + Type inv_range = 1.0 / range; // Multiplication is faster than division + vector nn_index_flat = nngp_data.nn_index_flat; + //vector nn_start = nngp_data.nn_start; + vector nn_len = nngp_data.nn_len; + vector dist_to_nn_flat = nngp_data.dist_to_nn_flat; + vector dist_within_nn_flat = nngp_data.dist_within_nn_flat; + vector gp_order = nngp_data.gp_order; + int n = field_s.size(); + + int pos_mat = 0; + int pos_vec = 0; + for( int i = 0; i < n; i++ ){ + int k = nn_len(i); + + // No neighbors + if(k == 0){ + nll -= dnorm( field_s(gp_order(i)), Type(0.0), sqrt(sigma2), true ); + }else{ + // Extract neighbor indices and distance to neighbors + vector nn_ids(k); + vector dist_iN(k); + for (int j = 0; j < k; j++) { + nn_ids(j) = nn_index_flat(pos_vec); + dist_iN(j) = dist_to_nn_flat(pos_vec); + pos_vec++; + } + + // Extract within-neighbor distance matrix (k x k) ... + matrix dist_NN(k, k); + for (int r = 0; r < k; r++) { + for (int c = 0; c < k; c++) { + dist_NN(r, c) = dist_within_nn_flat(pos_mat); + pos_mat++; + } + } + + // Covariances + matrix Sigma_NN = covariance_function(dist_NN, sigma2, inv_range); + vector Sigma_iN = covariance_function(dist_iN, sigma2, inv_range); + + // Solve + //vector a_i = solve(Sigma_NN, Sigma_iN); + //vector a_i = Sigma_NN.ldlt().solve( Sigma_iN.matrix() ); + //Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > invSigma_NN; + //invSigma_NN.compute(Sigma_NN); + //vector a_i = invSigma_NN.solve(Sigma_iN); + matrix Sigma_NN_inv = atomic::matinv(Sigma_NN); + vector a_i = Sigma_NN_inv * Sigma_iN; + + // Residual variance + Type resid_var = sigma2 - (a_i * Sigma_iN).sum(); // + 1e-12; + + // Conditional mean + Type cond_mean = 0.0; + for (int j = 0; j < k; j++) { + cond_mean += a_i(j) * field_s(gp_order(nn_ids(j))); + } + + // Likelihood + nll -= dnorm( field_s(gp_order(i)), cond_mean, sqrt(resid_var), true ); + } + } + return nll; +} + +// Function to calculate RAM matrices +template +Eigen::SparseMatrix make_ram( matrix ram, + vector ram_start, + vector beta_z, + int n_c, + int what ){ + + Eigen::SparseMatrix out_cc(n_c, n_c); + out_cc.setZero(); + Type tmp; + + for(int r=0; r=1){ + tmp = beta_z(ram(r,3)-1); + }else{ + tmp = ram_start(r); + } + // Rho_cc + if( (ram(r,0)==1) && (what==0) ){ + out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; + } + // Gammainv_cc + if( (ram(r,0)==2) && (what==1) ){ + out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = 1 / tmp; + } + // Gamma_cc + if( (ram(r,0)==2) && (what==2) ){ + out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; + } + } + + return out_cc; +} + +// distribution/projection for gamma +// Based on: +// https://github.com/meganferg/FergusonEtal_20250125_EBS_Beluga_DSM/blob/main/src/te_tw_DSM.cpp#L85C9-L85C40 (Megan Ferguson) +template +Type gamma_distribution( vector gamma_k, + vector Sdims, + vector Sblock, + Eigen::SparseMatrix S_kk, + vector log_lambda ){ + + using namespace density; + Type nll = 0.0; + int start_gamma = 0; // Counter for gamma + int start_k = 0; // counter for columns of S_kk + int index_lambda = 0; + for(int z=0; z gamma_segment = gamma_k.segment(start_gamma, ngamma_z); + start_gamma += ngamma_z; + + // s() splines + if( Sblock(z) == 1 ){ + // Recover S_block + Eigen::SparseMatrix S_block = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i + + /// Quadratic-form GRMF + // GMRF(Q).Quadform(x) caused a problem calculating the log-determinant unnecessarily, resulting in valgrind error + //nll -= Type(0.5)*Type(m_z)*log_lambda(z) - Type(0.5)*exp(log_lambda(z))*GMRF(S_block).Quadform(gamma_segment); + nll -= Type(0.5)*Type(ngamma_z)*log_lambda(index_lambda) - Type(0.5) * exp(log_lambda(index_lambda)) * + (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); + + start_k += ngamma_z; + index_lambda += 1; + } + + // te() / ti() / t2() splines + if( Sblock(z) >= 2 ){ + // Recover S_block ... Eigen::SparseMatrix appears to initialize as empty so no .setZero() equivalent needed + Eigen::SparseMatrix S_block( ngamma_z, ngamma_z ); + for( int block=0; block < Sblock(z); block ++ ){ + Eigen::SparseMatrix S_tmp = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i + S_block += exp(log_lambda(index_lambda)) * S_tmp; + start_k += ngamma_z; + index_lambda++; + } + + /// Quadratic-form GRMF + nll -= 0.5*(atomic::logdet(matrix(S_block))) - 0.5 * + (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); + } + } + return( nll ); +} + +// distribution/projection for omega +template +tmbutils::array omega_distribution( tmbutils::array omega_sc, + vector model_options, + Eigen::SparseMatrix Rho_cc, + Eigen::SparseMatrix Gamma_cc, + Eigen::SparseMatrix Gammainv_cc, + Eigen::SparseMatrix Q_ss, + Type range, + nngp_data_t nngp_data, + Type &nll ){ + + if( omega_sc.size() > 0 ){ + int n_c = omega_sc.dim(1); + using namespace density; + Eigen::SparseMatrix I_cc( n_c, n_c ); + I_cc.setIdentity(); + if( omega_sc.size()>0 ){ // PARALLEL_REGION + Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; + if( model_options(1) == 0 ){ + // Separable precision ... Option-1 + //Eigen::SparseMatrix Linv_cc = Gammainv_cc * ( I_cc - Rho_cc ); + //Eigen::SparseMatrix Q_cc = Linv_cc.transpose() * Linv_cc; + + // Separable precision ... Option-2 + // Only compute Vinv_kk if Gamma_kk is full rank + Eigen::SparseMatrix V_cc = Gamma_cc.transpose() * Gamma_cc; + matrix Vinv_cc = invertSparseMatrix( V_cc ); + Eigen::SparseMatrix Vinv2_cc = asSparseMatrix( Vinv_cc ); + Eigen::SparseMatrix Q_cc = IminusRho_cc.transpose() * Vinv2_cc * IminusRho_cc; + + // GMRF for SEM: separable variable-space + nll += SEPARABLE( GMRF(Q_cc), GMRF(Q_ss) )( omega_sc ); + // Including this line with Makevars below seems to cause a crash: + // PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) + // PKG_CXXFLAGS=$(SHLIB_OPENMP_CXXFLAGS) + }else{ + // Rank-deficient (projection) method + if( model_options(0) == 7 ){ + vector omega_s( omega_sc.rows() ); + for( int ci = 0; ci < omega_sc.cols(); ci++ ){ + omega_s = omega_sc.col(ci); + nll += NNGP( Type(1.0), range, omega_s, nngp_data ); + } + }else{ + nll += SEPARABLE( GMRF(I_cc), GMRF(Q_ss) )( omega_sc ); + } + + // Sparse inverse-product + //Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; + Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_cc; + inverseIminusRho_cc.compute(IminusRho_cc); + + // (I-Rho)^{-1} * Gamma * Epsilon + matrix omega2_cs = Gamma_cc * omega_sc.matrix().transpose(); + matrix omega3_cs = inverseIminusRho_cc.solve(omega2_cs); + omega_sc = omega3_cs.transpose(); + } + } + } + + return omega_sc; +} + +// distribution/projection for xi +template +Type xi_distribution( vector model_options, + tmbutils::array xi_sl, + vector log_sigmaxi_l, + Eigen::SparseMatrix Q_ss, + Type range, + nngp_data_t nngp_data ){ + + Type nll = 0; + if( xi_sl.size() > 0 ){ + int n_l = xi_sl.cols(); + using namespace density; + if( model_options(0) == 7 ){ + vector xi_s( xi_sl.rows() ); + for( int l=0; l +tmbutils::array epsilon_distribution( tmbutils::array epsilon_stc, + vector model_options, + Eigen::SparseMatrix Rho_hh, + Eigen::SparseMatrix Gamma_hh, + Eigen::SparseMatrix Gammainv_hh, + Eigen::SparseMatrix Q_ss, + Type range, + nngp_data_t nngp_data, + Type &nll ){ + + if( epsilon_stc.size() > 0 ){ + int n_s = epsilon_stc.dim(0); + int n_t = epsilon_stc.dim(1); + int n_c = epsilon_stc.dim(2); + int n_h = n_t * n_c; + using namespace density; + Eigen::SparseMatrix I_hh( n_h, n_h ); + I_hh.setIdentity(); + int h; + + //if( epsilon_stc.size()>0 ){ // PARALLEL_REGION + // Reshape for either model_options + tmbutils::array epsilon_hs( n_h, n_s ); + for( int s=0; s IminusRho_hh = I_hh - Rho_hh; + + if( model_options(1) == 0 ){ + // Separable precision ... Option-1 + //Eigen::SparseMatrix Linv_hh = Gammainv_hh * ( I_hh - Rho_hh ); + //Eigen::SparseMatrix Q_hh = Linv_hh.transpose() * Linv_hh; + + // Separable precision ... Option-2 + // Only compute Vinv_kk if Gamma_kk is full rank + Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; + matrix Vinv_hh = invertSparseMatrix( V_hh ); + Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); + Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; + + // GMRF for DSEM: non-separable time-variable, with separable space + nll += SEPARABLE( GMRF(Q_ss), GMRF(Q_hh) )( epsilon_hs ); + }else{ + // Rank-deficient (projection) method + if( model_options(0) == 7 ){ + vector epsilon_s( epsilon_hs.cols() ); + for( int hi = 0; hi < epsilon_hs.rows(); hi++ ){ + epsilon_s = epsilon_hs.matrix().row(hi); + nll += NNGP( Type(1.0), range, epsilon_s, nngp_data ); + } + }else{ + nll += SEPARABLE( GMRF(Q_ss), GMRF(I_hh) )( epsilon_hs ); + } + + // Sparse inverse-product + //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; + Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; + inverseIminusRho_hh.compute(IminusRho_hh); + + // (I-Rho)^{-1} * Gamma * Epsilon + matrix e2_hs = Gamma_hh * epsilon_hs.matrix(); + matrix e3_hs = inverseIminusRho_hh.solve(e2_hs); + + // Transformations + for( int s=0; s +tmbutils::array delta_distribution( tmbutils::array delta_tc, + vector model_options, + Eigen::SparseMatrix Rho_hh, + Eigen::SparseMatrix Gamma_hh, + Eigen::SparseMatrix Gammainv_hh, + Type &nll ){ + + if( delta_tc.size() > 0 ){ + int n_t = delta_tc.dim(0); + int n_c = delta_tc.dim(1); + int n_h = n_t * n_c; + using namespace density; + Eigen::SparseMatrix I_hh( n_h, n_h ); + I_hh.setIdentity(); + int h; + + // Reshape for either model_options + tmbutils::array delta_h1( n_h, 1 ); + for( int t=0; t IminusRho_hh = I_hh - Rho_hh; + + if( model_options(1) == 0 ){ + Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; + matrix Vinv_hh = invertSparseMatrix( V_hh ); + Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); + Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; + + // GMRF for DSEM: non-separable time-variable, with separable space + nll += GMRF(Q_hh)( delta_h1 ); + }else{ + // Rank-deficient (projection) method + nll += GMRF(I_hh)( delta_h1 ); + + // Sparse inverse-product + //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; + Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; + inverseIminusRho_hh.compute(IminusRho_hh); + + // (I-Rho)^{-1} * Gamma * Epsilon + matrix e2_h1 = Gamma_hh * delta_h1.matrix(); + matrix e3_h1 = inverseIminusRho_hh.solve(e2_h1); + + // Transformations + for( int t=0; t +bool isNA(Type x){ + return R_IsNA(asDouble(x)); +} + +// Sparse array * matrix +// NAs in IVECTOR or IMATRIX get converted to -2147483648, so isNA doesn't work ... instead drop NAs from A prior to passing to TMB +template +vector multiply_epsilon( matrix A, vector weight, tmbutils::array x, int n_i ){ + vector out( n_i ); + out.setZero(); + if( x.size() > 0 ){ + for( int z=0; z +vector multiply_omega( matrix A, vector weight, tmbutils::array x, int n_i ){ + vector out( n_i ); + out.setZero(); + if( x.size() > 0 ){ + for( int z=0; z +vector multiply_xi( Eigen::SparseMatrix A_is, tmbutils::array xi_sl, matrix W_il ){ + vector out( W_il.rows() ); + out.setZero(); + if( xi_sl.size() > 0 ){ + matrix xi_il = A_is * xi_sl.matrix(); + for( int i=0; i +vector multiply_delta( tmbutils::array delta_tc, vector t_i, vector c_i, int n_i ){ + vector delta_i( n_i ); + delta_i.setZero(); + if( delta_tc.size() > 0 ){ + for( int i=0; i +Type sign(Type x){ + return x / pow(pow(x,2),0.5); +} + +// dlnorm +template +Type dlnorm( Type x, + Type meanlog, + Type sdlog, + int give_log=0){ + + //return 1/(sqrt(2*M_PI)*sd) * exp(-.5*pow((x-mean)/sd,2)); + Type logres = dnorm( log(x), meanlog, sdlog, true) - log(x); + if(give_log) return logres; else return exp(logres); +} + +// dlnorm +template +Type dbinom_custom( Type x, + Type log_prob, + Type log_one_minus_prob, + Type size, + int give_log = 0 ){ + + // size choose x + Type logres = lgamma(size + 1.0) - lgamma(x + 1.0) - lgamma(size - x + 1.0); + // p^x * (1-p)^(size-x) + logres += x * log_prob + (size-x) * log_one_minus_prob; + if(give_log) return logres; else return exp(logres); +} + +// dlnorm +template +Type devresid_binom( Type y, + Type weight, // weight = size + Type mu ){ + + Type y_weight = y * weight; + Type mu_weight = mu * weight; + Type p1, p2; + if(y_weight == 0){ + p1 = 0.0; + }else{ + p1 = y_weight * log(y_weight / mu_weight); + } + if( (weight - y_weight) == 0 ){ + p2 = 0.0; + }else{ + p2 = (weight - y_weight) * log( (weight - y_weight) / (weight - mu_weight) ); + } + Type devresid = sign(y - mu) * pow(2 * (p1 + p2), 0.5); + return devresid; +} + +// Deviance for the Tweedie +// https://en.wikipedia.org/wiki/Tweedie_distribution#Properties +template +Type devresid_tweedie( Type y, + Type mu, + Type p ){ + + Type c1 = pow( y, 2.0-p ) / (1.0-p) / (2.0-p); + Type c2 = y * pow( mu, 1.0-p ) / (1.0-p); + Type c3 = pow( mu, 2.0-p ) / (2.0-p); + Type deviance = 2 * (c1 - c2 + c3 ); + Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); + return devresid; +} + +// Deviance for the student-T +// from chatGPT (experimental) ... converges on Gaussian as df -> Inf +template +Type devresid_student( Type y, + Type mu, + Type sigma, + Type df ){ + + Type deviance = (df + 1.0) * log( 1.0 + pow(y-mu,2.0) / (df * sigma*sigma) ); + Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); + return devresid; +} + +// COPIED from sdmTMB.cpp in sdmTMB package on Nov. 14, 2025 +template +Type dstudent(Type x, Type mean, Type sigma, Type df, int give_log = 0) { + // from metRology::dt.scaled() + // dt((x - mean)/sd, df, ncp = ncp, log = TRUE) - log(sd) + Type logres = dt((x - mean) / sigma, df, true) - log(sigma); + if (give_log) + return logres; + else + return exp(logres); +} + +// Deviance for the Negative binomial +//template +//Type devresid_nbinom1( Type y, +// Type logmu, +// Type logtheta ){ +// +// // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu +// Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), log(y + Type(1e-10)) + logtheta, true ); +// Type logp2 = dnbinom_robust( y, logmu, logmu + logtheta, true ); +// Type deviance = 2 * (logp1 - logp2); +// Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); +// return devresid; +//} +template +Type devresid_nbinom2( Type y, + Type logmu, + Type logtheta ){ + + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), Type(2.0) * log(y + Type(1e-10)) - logtheta, true ); + Type logp2 = dnbinom_robust( y, logmu, Type(2.0) * logmu - logtheta, true ); + Type deviance = 2 * (logp1 - logp2); + Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); + return devresid; +} + + +// distribution/projection for epsilon +// deviance = deviance1 + deviance2 +template +Type one_predictor_likelihood( Type &y, + Type p, + Type size, + int link, + int family, + vector log_sigma_segment, + Type &nll, + Type &devresid, + objective_function* of ){ + Type mu, logmu, log_one_minus_mu; + //Type devresid = 0; + + switch( link ){ + case identity_link: + mu = p; + logmu = log( p ); + log_one_minus_mu = log( Type(1.0) - mu ); + break; + case log_link: + mu = exp(p); + logmu = p; + log_one_minus_mu = log( Type(1.0) - mu ); + break; + case logit_link: + mu = invlogit(p); + //logmu = log(mu); + logmu = p - logspace_add( Type(0.0), p ); + //log_one_minus_mu = log( invlogit(-1 * p) ); + log_one_minus_mu = 0.0 - logspace_add( Type(0.0), p ); + break; + case cloglog_link: + mu = Type(1.0) - exp( -1 * exp(p) ); + logmu = logspace_sub( Type(0.0), -1.0 * exp(p) ); + log_one_minus_mu = -1.0 * exp(p); + break; + default: + error("Link not implemented."); + } + if( !R_IsNA(asDouble(y)) ){ + // Distribution + switch( family ){ + case gaussian_family: + nll = -1 * dnorm( y, mu, exp(log_sigma_segment(0)), true ); + devresid = y - mu; + if(isDouble::value && of->do_simulate){ + y = rnorm( mu, exp(log_sigma_segment(0)) ); + } + break; + case tweedie_family: + nll = -1 * dtweedie( y, mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); + devresid = devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); + if(isDouble::value && of->do_simulate){ + y = rtweedie( mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); + } + break; + case lognormal_family: + nll = -1 * dlnorm( y, logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); + devresid = log(y) - ( logmu - 0.5*exp(2.0*log_sigma_segment(0)) ); + if(isDouble::value && of->do_simulate){ + y = exp(rnorm( logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); + } + break; + case poisson_family: + nll = -1 * dpois( y, mu, true ); + devresid = sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); + if(isDouble::value && of->do_simulate){ + y = rpois( mu ); + } + break; + case binomial_family: + //if(y==0){ + // nll = -1 * log_one_minus_mu; + //}else{ + // nll = -1 * logmu; + //} + nll = -1 * dbinom_custom( y * size, logmu, log_one_minus_mu, size, true ); + if(isDouble::value && of->do_simulate){ + y = rbinom( size, mu ); + } + // TODO: Update deviance residual for Trials = size + //devresid = sign(y - mu) * pow(-2*((1-y)*log(1.0-mu) + y*log(mu)), 0.5); + devresid = devresid_binom( y, size, mu ); + break; + case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 + nll = -1 * dgamma( y, exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)), true ); + devresid = sign(y - mu) * pow(2 * ( (y-mu)/mu - log(y/mu) ), 0.5); + if(isDouble::value && of->do_simulate){ + y = rgamma( exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)) ); + } + break; + case nbinom1_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu + nll = -1 * dnbinom_robust( y, logmu, logmu + log_sigma_segment(0), true); + devresid = devresid_nbinom2( y, logmu, logmu - log_sigma_segment(0) ); // theta = mu / phi + if(isDouble::value && of->do_simulate){ + // rnbinom2( mu, var ) + y = rnbinom2( mu, mu * (Type(1.0) + exp(log_sigma_segment(0))) ); + } + break; + case nbinom2_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + nll = -1 * dnbinom_robust( y, logmu, Type(2.0) * logmu - log_sigma_segment(0), true); + devresid = devresid_nbinom2( y, logmu, log_sigma_segment(0) ); + if(isDouble::value && of->do_simulate){ + // rnbinom2( mu, var ) + y = rnbinom2( mu, mu * (Type(1.0) + mu / exp(log_sigma_segment(0))) ); + } + break; + case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + nll = -1 * dstudent( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); + devresid = devresid_student( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)) ); + if(isDouble::value && of->do_simulate){ + y = mu + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); + } + break; + default: + error("Distribution not implemented."); + } + } + + return mu; +} + +// distribution/projection for epsilon +template +Type two_predictor_likelihood( Type &y, + Type p1, + Type p2, + Type size, + vector link, + vector family, + vector log_sigma_segment, + int poislink, + Type &nll, + Type &dev, + objective_function* of ){ + Type mu1, logmu1, mu2, logmu2, log_one_minus_mu1; + + // First link + if( poislink==0 ){ + mu1 = invlogit( p1 ); + logmu1 = log( mu1 ); + log_one_minus_mu1 = log( Type(1.0) - mu1 ); + // second link + switch( link(1) ){ + case identity_link: + mu2 = p2; + logmu2 = log( p2 ); + break; + case log_link: + mu2 = exp(p2); + logmu2 = p2; + break; + default: + error("Link not implemented."); + } + }else{ + mu1 = Type(1.0) - exp( -1.0*exp(p1) ); + logmu1 = logspace_sub( Type(0.0), -1*exp(p1) ); + log_one_minus_mu1 = -1.0*exp(p1); + mu2 = exp( p1 + p2 ) / mu1; + logmu2 = p1 + p2 - logmu1; + } + if( !R_IsNA(asDouble(y)) ){ + // Distribution + if(isDouble::value && of->do_simulate){ + y = rbinom( Type(1), mu1 ); + } + if( y == 0 ){ + nll = -1 * log_one_minus_mu1; + dev = -2 * log_one_minus_mu1; + } + if( y>0 ){ // Not if-else so y>0 triggered when simulating y>0 + nll = -1 * logmu1; + dev = -2 * logmu1; + //deviance1_i(i) = -2 * log_mu1(i); + switch( family(1) ){ + case gaussian_family: + nll -= dnorm( y, mu2, exp(log_sigma_segment(0)), true ); + dev += pow(y - mu2, 2.0); + if(isDouble::value && of->do_simulate){ + y = rnorm( mu2, exp(log_sigma_segment(0)) ); + } + break; + //case tweedie_family: + // nll -= dtweedie( y, mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); + // devresid += devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); + // if(isDouble::value && of->do_simulate){ + // y = rtweedie( mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); + // } + // break; + case lognormal_family: + nll -= dlnorm( y, logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); + dev += pow( log(y) - (logmu2 - 0.5*exp(2.0*log_sigma_segment(0))), 2.0 ); + if(isDouble::value && of->do_simulate){ + y = exp(rnorm( logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); + } + break; + //case poisson_family: + // nll -= dpois( y, mu2, true ); + // devresid += sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); + // if(isDouble::value && of->do_simulate){ + // y = rpois( mu2 ); + // } + // break; + // case 4: // Bernoulli + case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 + nll -= dgamma( y, exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)), true ); + dev += 2 * ( (y-mu2)/mu2 - log(y/mu2) ); + if(isDouble::value && of->do_simulate){ + y = rgamma( exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)) ); + } + break; + case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + nll -= dstudent( y, mu2, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); + //dev = NAN; + if(isDouble::value && of->do_simulate){ + y = mu2 + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); + } + break; + default: + error("Distribution not implemented."); + } + } + } + + return mu1 * mu2; +} + +} // namespace tinyVAST \ No newline at end of file From 3064348b142547ac58091690ee42da7e1b8d8b18 Mon Sep 17 00:00:00 2001 From: Jim Thorson <50178738+James-Thorson-NOAA@users.noreply.github.com> Date: Fri, 10 Jul 2026 08:14:13 -0700 Subject: [PATCH 04/37] Update rhub.yaml --- .github/workflows/rhub.yaml | 66 ++++++++++++++++++------------------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/.github/workflows/rhub.yaml b/.github/workflows/rhub.yaml index aeecd0ff..dc1ec2c2 100644 --- a/.github/workflows/rhub.yaml +++ b/.github/workflows/rhub.yaml @@ -7,20 +7,24 @@ # It is unlikely that you need to modify this file manually. name: R-hub -run-name: "${{ github.event.inputs.id }}: ${{ github.event.inputs.name || format('Manually run by {0}', github.triggering_actor) }}" +run-name: >- + ${{ github.event.inputs.id || format('Manual run by @{0}', github.triggering_actor) }}: + ${{ github.event.inputs.name || github.event.inputs.config }} on: workflow_dispatch: inputs: config: - description: 'A comma separated list of R-hub platforms to use.' + description: >- + Comma-separated list of R-hub platforms to use. + Full list: https://r-hub.github.io/containers/ type: string default: 'linux,windows,macos' name: - description: 'Run name. You can leave this empty now.' + description: 'Run name. You can leave this empty.' type: string id: - description: 'Unique ID. You can leave this empty now.' + description: 'Unique ID. You can leave this empty.' type: string jobs: @@ -38,36 +42,32 @@ jobs: config: ${{ github.event.inputs.config }} id: rhub-setup -linux-containers: - needs: setup - if: ${{ needs.setup.outputs.containers != '[]' }} - runs-on: ubuntu-latest - name: ${{ matrix.config.label }} - strategy: - fail-fast: false - matrix: - config: ${{ fromJson(needs.setup.outputs.containers) }} - container: - image: ${{ matrix.config.container }} + linux-containers: + needs: setup + if: ${{ needs.setup.outputs.containers != '[]' }} + runs-on: ubuntu-latest + name: ${{ matrix.config.label }} + strategy: + fail-fast: false + matrix: + config: ${{ fromJson(needs.setup.outputs.containers) }} + container: + image: ${{ matrix.config.container }} - steps: - - uses: r-hub/actions/checkout@v1 - - name: Install missing dependencies - run: | - sudo apt-get update - sudo apt-get install -y gawk - - uses: r-hub/actions/platform-info@v1 - with: - token: ${{ secrets.RHUB_TOKEN }} - job-config: ${{ matrix.config.job-config }} - - uses: r-hub/actions/setup-deps@v1 - with: - token: ${{ secrets.RHUB_TOKEN }} - job-config: ${{ matrix.config.job-config }} - - uses: r-hub/actions/run-check@v1 - with: - token: ${{ secrets.RHUB_TOKEN }} - job-config: ${{ matrix.config.job-config }} + steps: + - uses: r-hub/actions/checkout@v1 + - uses: r-hub/actions/platform-info@v1 + with: + token: ${{ secrets.RHUB_TOKEN }} + job-config: ${{ matrix.config.job-config }} + - uses: r-hub/actions/setup-deps@v1 + with: + token: ${{ secrets.RHUB_TOKEN }} + job-config: ${{ matrix.config.job-config }} + - uses: r-hub/actions/run-check@v1 + with: + token: ${{ secrets.RHUB_TOKEN }} + job-config: ${{ matrix.config.job-config }} other-platforms: needs: setup From 25f1bbf1794d9624a72fe61fecbdb71d9ada0394 Mon Sep 17 00:00:00 2001 From: Jim Thorson <50178738+James-Thorson-NOAA@users.noreply.github.com> Date: Fri, 10 Jul 2026 08:20:33 -0700 Subject: [PATCH 05/37] Delete rhub.yaml --- .github/workflows/rhub.yaml | 99 ------------------------------------- 1 file changed, 99 deletions(-) delete mode 100644 .github/workflows/rhub.yaml diff --git a/.github/workflows/rhub.yaml b/.github/workflows/rhub.yaml deleted file mode 100644 index dc1ec2c2..00000000 --- a/.github/workflows/rhub.yaml +++ /dev/null @@ -1,99 +0,0 @@ -# R-hub's generic GitHub Actions workflow file. It's canonical location is at -# https://github.com/r-hub/actions/blob/v1/workflows/rhub.yaml -# You can update this file to a newer version using the rhub2 package: -# -# rhub::rhub_setup() -# -# It is unlikely that you need to modify this file manually. - -name: R-hub -run-name: >- - ${{ github.event.inputs.id || format('Manual run by @{0}', github.triggering_actor) }}: - ${{ github.event.inputs.name || github.event.inputs.config }} - -on: - workflow_dispatch: - inputs: - config: - description: >- - Comma-separated list of R-hub platforms to use. - Full list: https://r-hub.github.io/containers/ - type: string - default: 'linux,windows,macos' - name: - description: 'Run name. You can leave this empty.' - type: string - id: - description: 'Unique ID. You can leave this empty.' - type: string - -jobs: - - setup: - runs-on: ubuntu-latest - outputs: - containers: ${{ steps.rhub-setup.outputs.containers }} - platforms: ${{ steps.rhub-setup.outputs.platforms }} - - steps: - # NO NEED TO CHECKOUT HERE - - uses: r-hub/actions/setup@v1 - with: - config: ${{ github.event.inputs.config }} - id: rhub-setup - - linux-containers: - needs: setup - if: ${{ needs.setup.outputs.containers != '[]' }} - runs-on: ubuntu-latest - name: ${{ matrix.config.label }} - strategy: - fail-fast: false - matrix: - config: ${{ fromJson(needs.setup.outputs.containers) }} - container: - image: ${{ matrix.config.container }} - - steps: - - uses: r-hub/actions/checkout@v1 - - uses: r-hub/actions/platform-info@v1 - with: - token: ${{ secrets.RHUB_TOKEN }} - job-config: ${{ matrix.config.job-config }} - - uses: r-hub/actions/setup-deps@v1 - with: - token: ${{ secrets.RHUB_TOKEN }} - job-config: ${{ matrix.config.job-config }} - - uses: r-hub/actions/run-check@v1 - with: - token: ${{ secrets.RHUB_TOKEN }} - job-config: ${{ matrix.config.job-config }} - - other-platforms: - needs: setup - if: ${{ needs.setup.outputs.platforms != '[]' }} - runs-on: ${{ matrix.config.os }} - name: ${{ matrix.config.label }} - strategy: - fail-fast: false - matrix: - config: ${{ fromJson(needs.setup.outputs.platforms) }} - - steps: - - uses: r-hub/actions/checkout@v1 - - uses: r-hub/actions/setup-r@v1 - with: - job-config: ${{ matrix.config.job-config }} - token: ${{ secrets.RHUB_TOKEN }} - - uses: r-hub/actions/platform-info@v1 - with: - token: ${{ secrets.RHUB_TOKEN }} - job-config: ${{ matrix.config.job-config }} - - uses: r-hub/actions/setup-deps@v1 - with: - job-config: ${{ matrix.config.job-config }} - token: ${{ secrets.RHUB_TOKEN }} - - uses: r-hub/actions/run-check@v1 - with: - job-config: ${{ matrix.config.job-config }} - token: ${{ secrets.RHUB_TOKEN }} From 941f3f83d745d70b75e79dee5f17c33855e81f12 Mon Sep 17 00:00:00 2001 From: Jim Thorson <50178738+James-Thorson-NOAA@users.noreply.github.com> Date: Fri, 10 Jul 2026 08:21:50 -0700 Subject: [PATCH 06/37] Create rhub.yaml --- .github/workflows/rhub.yaml | 99 +++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 .github/workflows/rhub.yaml diff --git a/.github/workflows/rhub.yaml b/.github/workflows/rhub.yaml new file mode 100644 index 00000000..dc1ec2c2 --- /dev/null +++ b/.github/workflows/rhub.yaml @@ -0,0 +1,99 @@ +# R-hub's generic GitHub Actions workflow file. It's canonical location is at +# https://github.com/r-hub/actions/blob/v1/workflows/rhub.yaml +# You can update this file to a newer version using the rhub2 package: +# +# rhub::rhub_setup() +# +# It is unlikely that you need to modify this file manually. + +name: R-hub +run-name: >- + ${{ github.event.inputs.id || format('Manual run by @{0}', github.triggering_actor) }}: + ${{ github.event.inputs.name || github.event.inputs.config }} + +on: + workflow_dispatch: + inputs: + config: + description: >- + Comma-separated list of R-hub platforms to use. + Full list: https://r-hub.github.io/containers/ + type: string + default: 'linux,windows,macos' + name: + description: 'Run name. You can leave this empty.' + type: string + id: + description: 'Unique ID. You can leave this empty.' + type: string + +jobs: + + setup: + runs-on: ubuntu-latest + outputs: + containers: ${{ steps.rhub-setup.outputs.containers }} + platforms: ${{ steps.rhub-setup.outputs.platforms }} + + steps: + # NO NEED TO CHECKOUT HERE + - uses: r-hub/actions/setup@v1 + with: + config: ${{ github.event.inputs.config }} + id: rhub-setup + + linux-containers: + needs: setup + if: ${{ needs.setup.outputs.containers != '[]' }} + runs-on: ubuntu-latest + name: ${{ matrix.config.label }} + strategy: + fail-fast: false + matrix: + config: ${{ fromJson(needs.setup.outputs.containers) }} + container: + image: ${{ matrix.config.container }} + + steps: + - uses: r-hub/actions/checkout@v1 + - uses: r-hub/actions/platform-info@v1 + with: + token: ${{ secrets.RHUB_TOKEN }} + job-config: ${{ matrix.config.job-config }} + - uses: r-hub/actions/setup-deps@v1 + with: + token: ${{ secrets.RHUB_TOKEN }} + job-config: ${{ matrix.config.job-config }} + - uses: r-hub/actions/run-check@v1 + with: + token: ${{ secrets.RHUB_TOKEN }} + job-config: ${{ matrix.config.job-config }} + + other-platforms: + needs: setup + if: ${{ needs.setup.outputs.platforms != '[]' }} + runs-on: ${{ matrix.config.os }} + name: ${{ matrix.config.label }} + strategy: + fail-fast: false + matrix: + config: ${{ fromJson(needs.setup.outputs.platforms) }} + + steps: + - uses: r-hub/actions/checkout@v1 + - uses: r-hub/actions/setup-r@v1 + with: + job-config: ${{ matrix.config.job-config }} + token: ${{ secrets.RHUB_TOKEN }} + - uses: r-hub/actions/platform-info@v1 + with: + token: ${{ secrets.RHUB_TOKEN }} + job-config: ${{ matrix.config.job-config }} + - uses: r-hub/actions/setup-deps@v1 + with: + job-config: ${{ matrix.config.job-config }} + token: ${{ secrets.RHUB_TOKEN }} + - uses: r-hub/actions/run-check@v1 + with: + job-config: ${{ matrix.config.job-config }} + token: ${{ secrets.RHUB_TOKEN }} From 073900451da4b85dca00eaab1101e896c469c448 Mon Sep 17 00:00:00 2001 From: Jim Thorson <50178738+James-Thorson-NOAA@users.noreply.github.com> Date: Fri, 10 Jul 2026 09:05:45 -0700 Subject: [PATCH 07/37] remove dsem check from CRAN --- NEWS.md | 1 + tests/testthat/test-basic-fits.R | 47 +++++++++++++++++++++++--------- 2 files changed, 35 insertions(+), 13 deletions(-) diff --git a/NEWS.md b/NEWS.md index 297a0a0f..8d90c73c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,7 @@ # tinyVAST 1.6.1.9000 * Replace array with tmbutils::array in CPP, to disambiguate new array typedef in RcppEigen, following andrjohns in dsem#63 +* Remove "test-basic-fits.R" test "tinyVAST works as dsem" from CRAN, due to weird and un-reproducible ERROR on CRAN openBLAS check # tinyVAST 1.6.1 diff --git a/tests/testthat/test-basic-fits.R b/tests/testthat/test-basic-fits.R index cb1df02c..e3341710 100644 --- a/tests/testthat/test-basic-fits.R +++ b/tests/testthat/test-basic-fits.R @@ -139,14 +139,15 @@ test_that("formula function poly(.,raw=FALSE) is parsed correctly when fitting a test_that("tinyVAST works as dsem", { + skip_on_cran() data(isle_royale, package="dsem") # Convert to long-form - data = expand.grid( "time"=isle_royale[,1], "var"=colnames(isle_royale[,2:3]) ) - data$logn = unlist(log(isle_royale[2:3])) + data_long = expand.grid( "time"=isle_royale[,1], "var"=colnames(isle_royale[,2:3]) ) + data_long$logn = unlist(log(isle_royale[2:3])) # Define cross-lagged DSEM - dsem = " + dsem_term = " # Link, lag, param_name wolves -> wolves, 1, arW moose -> wolves, 1, MtoW @@ -157,19 +158,39 @@ test_that("tinyVAST works as dsem", { " # fit model ... spacetime_term - fit1 = tinyVAST( spacetime_term = dsem, - data = data, - times = isle_royale[,1], - variables = colnames(isle_royale[,2:3]), - formula = logn ~ 0 + var ) + fit1 = tinyVAST( + spacetime_term = dsem_term, + data = data_long, + times = isle_royale[,1], + variables = colnames(isle_royale[,2:3]), + formula = logn ~ 0 + var + ) # fit model ... time_term - fit2 = tinyVAST( time_term = dsem, - data = data, - times = isle_royale[,1], - variables = colnames(isle_royale[,2:3]), - formula = logn ~ 0 + var ) + fit2 = tinyVAST( + time_term = dsem_term, + data = data_long, + times = isle_royale[,1], + variables = colnames(isle_royale[,2:3]), + formula = logn ~ 0 + var + ) + + # initial build of object + data_ts = ts( log(isle_royale[,2:3]), start=1959) + fit_dsem = dsem( + sem = dsem_term, + tsdata = data_ts, + family = list( + wolves = fixed(), + moose = fixed() + ), + estimate_delta0 = FALSE, + control = dsem_control( + use_REML = FALSE + ) + ) expect_equal( as.numeric(fit1$opt$obj), as.numeric(fit2$opt$obj), tolerance = 1e-3 ) expect_equal( as.numeric(fit1$opt$obj), 5.781919, tolerance = 1e-3 ) + expect_equal( as.numeric(fit1$opt$obj), as.numeric(fit_dsem$opt$obj), tolerance = 1e-3 ) } ) From 892637f66a424043111285778e1372319337d0b5 Mon Sep 17 00:00:00 2001 From: James Thorson Date: Mon, 13 Jul 2026 14:50:26 -0700 Subject: [PATCH 08/37] stage for CRAN update --- DESCRIPTION | 4 ++-- NEWS.md | 2 +- scratch/Upload_to_CRAN.R | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index a53e8c45..e4285fef 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,8 +1,8 @@ Type: Package Package: tinyVAST Title: Multivariate Spatio-Temporal Models using Structural Equations -Version: 1.6.1.9000 -Date: 2026-07-01 +Version: 1.6.2 +Date: 2026-07-13 Authors@R: c( person(c("James", "T."), "Thorson", , "James.Thorson@noaa.gov", role = c("aut", "cre"), diff --git a/NEWS.md b/NEWS.md index 8d90c73c..74d05036 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,4 +1,4 @@ -# tinyVAST 1.6.1.9000 +# tinyVAST 1.6.2 * Replace array with tmbutils::array in CPP, to disambiguate new array typedef in RcppEigen, following andrjohns in dsem#63 * Remove "test-basic-fits.R" test "tinyVAST works as dsem" from CRAN, due to weird and un-reproducible ERROR on CRAN openBLAS check diff --git a/scratch/Upload_to_CRAN.R b/scratch/Upload_to_CRAN.R index ec333888..821a787c 100644 --- a/scratch/Upload_to_CRAN.R +++ b/scratch/Upload_to_CRAN.R @@ -3,8 +3,8 @@ library(devtools) #pandoc::pandoc_install() -setwd( R'(C:\Users\James.Thorson\Desktop\Git\tinyVAST)' ) -#setwd( R'(C:\Users\james\OneDrive\Desktop\Git\tinyVAST)') +#setwd( R'(C:\Users\James.Thorson\Desktop\Git\tinyVAST)' ) +setwd( R'(C:\Users\james\OneDrive\Desktop\Git\tinyVAST)') # Compile if( FALSE ){ @@ -12,7 +12,7 @@ if( FALSE ){ } # Test install -install_local(force=TRUE, dep=TRUE, build_vignettes=TRUE, upgrade=FALSE) +pak::pak(dep=TRUE, upgrade=FALSE) #install_local(force=TRUE, dep=TRUE, build_vignettes=FALSE, upgrade=FALSE) browseVignettes("tinyVAST") From 542564e46f816bcab7e5849527c36b4656c37185 Mon Sep 17 00:00:00 2001 From: James Thorson Date: Mon, 13 Jul 2026 15:02:08 -0700 Subject: [PATCH 09/37] updates to tests --- tests/testthat/test-dsem.R | 1 + tests/testthat/test-index-standardization.R | 6 ++++-- tests/testthat/test-smooths.R | 4 ++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/testthat/test-dsem.R b/tests/testthat/test-dsem.R index 7cc2806a..001c84a3 100644 --- a/tests/testthat/test-dsem.R +++ b/tests/testthat/test-dsem.R @@ -73,6 +73,7 @@ test_that("dsem and tinyVAST give identical results without lags", { test_that("dsem and tinyVAST give identical results with lags", { # Simulate data + library(dsem) set.seed(101) n_rows = 100 X = 1 + rnorm(n_rows - 1) diff --git a/tests/testthat/test-index-standardization.R b/tests/testthat/test-index-standardization.R index 24028f16..73a931f7 100644 --- a/tests/testthat/test-index-standardization.R +++ b/tests/testthat/test-index-standardization.R @@ -74,8 +74,10 @@ test_that("Basic index standardization works", { }) test_that("Index standardization results are identical in VAST, tinyVAST, and sdmTMB", { - skip_if_not(require(VAST)) - skip_if_not(require(sdmTMB)) + skip_if_not_installed("VAST") + skip_if_not_installed("sdmTMB") + library(VAST) + library(sdmTMB) library(fmesher) set.seed(101) options("tinyVAST.verbose" = FALSE) diff --git a/tests/testthat/test-smooths.R b/tests/testthat/test-smooths.R index b401e0bc..6a57785f 100644 --- a/tests/testthat/test-smooths.R +++ b/tests/testthat/test-smooths.R @@ -304,6 +304,6 @@ test_that("A model with s() and a continuous 'by' variable works", { ) pred2 = predict(mytv) - expect_equal( as.numeric(pred1), pred2, tol = 1e-3 ) - expect_equal( pred2[1:5], rep(0,5), tol = 1e-3 ) + expect_equal( as.numeric(pred1), pred2, tolerance = 1e-3 ) + expect_equal( pred2[1:5], rep(0,5), tolerance = 1e-3 ) }) From c4e8fe63e13289926ff136652737f5be1f1d3995 Mon Sep 17 00:00:00 2001 From: James Thorson Date: Mon, 13 Jul 2026 15:11:43 -0700 Subject: [PATCH 10/37] Update test-basic-fits.R --- tests/testthat/test-basic-fits.R | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/testthat/test-basic-fits.R b/tests/testthat/test-basic-fits.R index e3341710..7220c267 100644 --- a/tests/testthat/test-basic-fits.R +++ b/tests/testthat/test-basic-fits.R @@ -140,6 +140,7 @@ test_that("formula function poly(.,raw=FALSE) is parsed correctly when fitting a test_that("tinyVAST works as dsem", { skip_on_cran() + library(dsem) data(isle_royale, package="dsem") # Convert to long-form From 4b88f3815ba0367177b90fb509ab18d22e1dc00b Mon Sep 17 00:00:00 2001 From: James Thorson Date: Mon, 13 Jul 2026 15:51:58 -0700 Subject: [PATCH 11/37] attempt fix for compiler complexity errors --- NEWS.md | 1 + src/utils.h | 20 +++++++++++--------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/NEWS.md b/NEWS.md index 74d05036..9d6b3d5d 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,7 @@ * Replace array with tmbutils::array in CPP, to disambiguate new array typedef in RcppEigen, following andrjohns in dsem#63 * Remove "test-basic-fits.R" test "tinyVAST works as dsem" from CRAN, due to weird and un-reproducible ERROR on CRAN openBLAS check +* Update `epsilon_distribution` to pass arguments using const and pointers (pass-by-const-reference) to avoid compiler errors # tinyVAST 1.6.1 diff --git a/src/utils.h b/src/utils.h index cf5a31f2..9c7fecc1 100644 --- a/src/utils.h +++ b/src/utils.h @@ -522,16 +522,18 @@ Type xi_distribution( vector model_options, } // distribution/projection for epsilon +// Passing const with pointer to simplify compilation (and avoid potential compiler errors during devtools checks) template -tmbutils::array epsilon_distribution( tmbutils::array epsilon_stc, - vector model_options, - Eigen::SparseMatrix Rho_hh, - Eigen::SparseMatrix Gamma_hh, - Eigen::SparseMatrix Gammainv_hh, - Eigen::SparseMatrix Q_ss, - Type range, - nngp_data_t nngp_data, - Type &nll ){ +tmbutils::array epsilon_distribution( + tmbutils::array epsilon_stc, + const vector &model_options, + const Eigen::SparseMatrix &Rho_hh, + const Eigen::SparseMatrix &Gamma_hh, + const Eigen::SparseMatrix &Gammainv_hh, + const Eigen::SparseMatrix &Q_ss, + Type range, + const nngp_data_t &nngp_data, + Type &nll ){ if( epsilon_stc.size() > 0 ){ int n_s = epsilon_stc.dim(0); From 911612002ebbb6b06e29849291d2efd06edd2cfa Mon Sep 17 00:00:00 2001 From: James Thorson Date: Mon, 13 Jul 2026 16:01:17 -0700 Subject: [PATCH 12/37] Update utils.h --- src/utils.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils.h b/src/utils.h index 9c7fecc1..b165ebe8 100644 --- a/src/utils.h +++ b/src/utils.h @@ -1077,4 +1077,4 @@ Type two_predictor_likelihood( Type &y, return mu1 * mu2; } -} // namespace tinyVAST \ No newline at end of file +} // namespace tinyVAST From c48d5754740c7994b1cc6eac216d916e77e7b209 Mon Sep 17 00:00:00 2001 From: James Thorson Date: Mon, 13 Jul 2026 16:19:15 -0700 Subject: [PATCH 13/37] further pass-by-const-reference --- src/utils.h | 185 +++++++++++++++++++++++++++++++--------------------- 1 file changed, 112 insertions(+), 73 deletions(-) diff --git a/src/utils.h b/src/utils.h index b165ebe8..f4af39ad 100644 --- a/src/utils.h +++ b/src/utils.h @@ -48,10 +48,11 @@ enum valid_link { //} template -Eigen::SparseMatrix vectorsToSparseMatrix( vector i, - vector j, - vector x, - int N ){ +Eigen::SparseMatrix vectorsToSparseMatrix( + const vector &i, + const vector &j, + const vector &x, + int N ){ // https://eigen.tuxfamily.org/dox/classEigen_1_1SparseMatrix.html#title35 using namespace Eigen; @@ -101,10 +102,11 @@ struct spde_covariates_t{ }; // make stiffness G1 from covariates in columns of E0, E1, E2 template -Eigen::SparseMatrix G_spde_covariates( spde_covariates_t spde, - matrix H_jj, - //matrix V_zk, - vector triangle_k ){ +Eigen::SparseMatrix G_spde_covariates( + const spde_covariates_t &spde, + const matrix &H_jj, + //matrix V_zk, + const vector &triangle_k ){ // TO ADD EDGE COVARIATES: // 0. add n_e = edge0_tj.rows() @@ -161,13 +163,13 @@ Eigen::SparseMatrix G_spde_covariates( spde_covariates_t spde, // Using a SAR (not standardized) to approximate spatial function template Eigen::SparseMatrix Q_SAR( - //Type rho, - Type kappa, - matrix H, - int n_s, - vector i_z, - vector j_z, - matrix delta_z2 ){ + //Type rho, + Type kappa, + const matrix &H, + int n_s, + const vector &i_z, + const vector &j_z, + const matrix &delta_z2 ){ //Type max_dist = delta_z2.cwiseAbs().maxCoeff(); @@ -201,11 +203,12 @@ Eigen::SparseMatrix Q_SAR( // New matrix-notation precision constructor for tail-down exponential stream network template -Eigen::SparseMatrix Q_network2( Type log_theta, - int n_s, - vector parent_s, - vector child_s, - vector dist_s ){ +Eigen::SparseMatrix Q_network2( + Type log_theta, + int n_s, + const vector &parent_s, + const vector &child_s, + const vector &dist_s ){ // Compute vectors Type theta = exp(log_theta); @@ -607,12 +610,13 @@ tmbutils::array epsilon_distribution( // distribution/projection for epsilon template -tmbutils::array delta_distribution( tmbutils::array delta_tc, - vector model_options, - Eigen::SparseMatrix Rho_hh, - Eigen::SparseMatrix Gamma_hh, - Eigen::SparseMatrix Gammainv_hh, - Type &nll ){ +tmbutils::array delta_distribution( + tmbutils::array delta_tc, + const vector &model_options, + const Eigen::SparseMatrix &Rho_hh, + const Eigen::SparseMatrix &Gamma_hh, + const Eigen::SparseMatrix &Gammainv_hh, + Type &nll ){ if( delta_tc.size() > 0 ){ int n_t = delta_tc.dim(0); @@ -674,7 +678,12 @@ bool isNA(Type x){ // Sparse array * matrix // NAs in IVECTOR or IMATRIX get converted to -2147483648, so isNA doesn't work ... instead drop NAs from A prior to passing to TMB template -vector multiply_epsilon( matrix A, vector weight, tmbutils::array x, int n_i ){ +vector multiply_epsilon( + const matrix &A, + const vector &weight, + const tmbutils::array &x, + int n_i ){ + vector out( n_i ); out.setZero(); if( x.size() > 0 ){ @@ -685,7 +694,12 @@ vector multiply_epsilon( matrix A, vector weight, tmbutils::arr return out; } template -vector multiply_omega( matrix A, vector weight, tmbutils::array x, int n_i ){ +vector multiply_omega( + const matrix &A, + const vector &weight, + const tmbutils::array &x, + int n_i ){ + vector out( n_i ); out.setZero(); if( x.size() > 0 ){ @@ -696,7 +710,11 @@ vector multiply_omega( matrix A, vector weight, tmbutils::array return out; } template -vector multiply_xi( Eigen::SparseMatrix A_is, tmbutils::array xi_sl, matrix W_il ){ +vector multiply_xi( + const Eigen::SparseMatrix &A_is, + const tmbutils::array &xi_sl, + const matrix &W_il ){ + vector out( W_il.rows() ); out.setZero(); if( xi_sl.size() > 0 ){ @@ -709,7 +727,12 @@ vector multiply_xi( Eigen::SparseMatrix A_is, tmbutils::array return out; } template -vector multiply_delta( tmbutils::array delta_tc, vector t_i, vector c_i, int n_i ){ +vector multiply_delta( + const tmbutils::array &delta_tc, + const vector &t_i, + const vector &c_i, + int n_i ){ + vector delta_i( n_i ); delta_i.setZero(); if( delta_tc.size() > 0 ){ @@ -728,10 +751,11 @@ Type sign(Type x){ // dlnorm template -Type dlnorm( Type x, - Type meanlog, - Type sdlog, - int give_log=0){ +Type dlnorm( + Type x, + Type meanlog, + Type sdlog, + int give_log=0){ //return 1/(sqrt(2*M_PI)*sd) * exp(-.5*pow((x-mean)/sd,2)); Type logres = dnorm( log(x), meanlog, sdlog, true) - log(x); @@ -740,11 +764,12 @@ Type dlnorm( Type x, // dlnorm template -Type dbinom_custom( Type x, - Type log_prob, - Type log_one_minus_prob, - Type size, - int give_log = 0 ){ +Type dbinom_custom( + Type x, + Type log_prob, + Type log_one_minus_prob, + Type size, + int give_log = 0 ){ // size choose x Type logres = lgamma(size + 1.0) - lgamma(x + 1.0) - lgamma(size - x + 1.0); @@ -755,9 +780,10 @@ Type dbinom_custom( Type x, // dlnorm template -Type devresid_binom( Type y, - Type weight, // weight = size - Type mu ){ +Type devresid_binom( + Type y, + Type weight, // weight = size + Type mu ){ Type y_weight = y * weight; Type mu_weight = mu * weight; @@ -779,9 +805,10 @@ Type devresid_binom( Type y, // Deviance for the Tweedie // https://en.wikipedia.org/wiki/Tweedie_distribution#Properties template -Type devresid_tweedie( Type y, - Type mu, - Type p ){ +Type devresid_tweedie( + Type y, + Type mu, + Type p ){ Type c1 = pow( y, 2.0-p ) / (1.0-p) / (2.0-p); Type c2 = y * pow( mu, 1.0-p ) / (1.0-p); @@ -794,10 +821,11 @@ Type devresid_tweedie( Type y, // Deviance for the student-T // from chatGPT (experimental) ... converges on Gaussian as df -> Inf template -Type devresid_student( Type y, - Type mu, - Type sigma, - Type df ){ +Type devresid_student( + Type y, + Type mu, + Type sigma, + Type df ){ Type deviance = (df + 1.0) * log( 1.0 + pow(y-mu,2.0) / (df * sigma*sigma) ); Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); @@ -806,7 +834,13 @@ Type devresid_student( Type y, // COPIED from sdmTMB.cpp in sdmTMB package on Nov. 14, 2025 template -Type dstudent(Type x, Type mean, Type sigma, Type df, int give_log = 0) { +Type dstudent( + Type x, + Type mean, + Type sigma, + Type df, + int give_log = 0) { + // from metRology::dt.scaled() // dt((x - mean)/sd, df, ncp = ncp, log = TRUE) - log(sd) Type logres = dt((x - mean) / sigma, df, true) - log(sigma); @@ -830,9 +864,10 @@ Type dstudent(Type x, Type mean, Type sigma, Type df, int give_log = 0) { // return devresid; //} template -Type devresid_nbinom2( Type y, - Type logmu, - Type logtheta ){ +Type devresid_nbinom2( + Type y, + Type logmu, + Type logtheta ){ // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), Type(2.0) * log(y + Type(1e-10)) - logtheta, true ); @@ -846,15 +881,17 @@ Type devresid_nbinom2( Type y, // distribution/projection for epsilon // deviance = deviance1 + deviance2 template -Type one_predictor_likelihood( Type &y, - Type p, - Type size, - int link, - int family, - vector log_sigma_segment, - Type &nll, - Type &devresid, - objective_function* of ){ +Type one_predictor_likelihood( + Type &y, + Type p, + Type size, + int link, + int family, + vector log_sigma_segment, + Type &nll, + Type &devresid, + objective_function* of ){ + Type mu, logmu, log_one_minus_mu; //Type devresid = 0; @@ -972,17 +1009,19 @@ Type one_predictor_likelihood( Type &y, // distribution/projection for epsilon template -Type two_predictor_likelihood( Type &y, - Type p1, - Type p2, - Type size, - vector link, - vector family, - vector log_sigma_segment, - int poislink, - Type &nll, - Type &dev, - objective_function* of ){ +Type two_predictor_likelihood( + Type &y, + Type p1, + Type p2, + Type size, + vector link, + vector family, + vector log_sigma_segment, + int poislink, + Type &nll, + Type &dev, + objective_function* of ){ + Type mu1, logmu1, mu2, logmu2, log_one_minus_mu1; // First link From 257e7a073a36455e0c795d532527aaf78f287fe5 Mon Sep 17 00:00:00 2001 From: James Thorson Date: Mon, 13 Jul 2026 16:42:42 -0700 Subject: [PATCH 14/37] try reverting utils.hpp --- {src => scratch}/utils.h | 11 +- src/tinyVAST.cpp | 1127 +++++++++++++++++++++++++++++++++++++- 2 files changed, 1132 insertions(+), 6 deletions(-) rename {src => scratch}/utils.h (99%) diff --git a/src/utils.h b/scratch/utils.h similarity index 99% rename from src/utils.h rename to scratch/utils.h index f4af39ad..2bf5805d 100644 --- a/src/utils.h +++ b/scratch/utils.h @@ -1,3 +1,6 @@ +// Notes +// don't use pass-by-const-reference for tmbutils::array + namespace tinyVAST { enum valid_family { @@ -681,7 +684,7 @@ template vector multiply_epsilon( const matrix &A, const vector &weight, - const tmbutils::array &x, + tmbutils::array x, int n_i ){ vector out( n_i ); @@ -697,7 +700,7 @@ template vector multiply_omega( const matrix &A, const vector &weight, - const tmbutils::array &x, + tmbutils::array x, int n_i ){ vector out( n_i ); @@ -712,7 +715,7 @@ vector multiply_omega( template vector multiply_xi( const Eigen::SparseMatrix &A_is, - const tmbutils::array &xi_sl, + tmbutils::array xi_sl, const matrix &W_il ){ vector out( W_il.rows() ); @@ -728,7 +731,7 @@ vector multiply_xi( } template vector multiply_delta( - const tmbutils::array &delta_tc, + tmbutils::array delta_tc, const vector &t_i, const vector &c_i, int n_i ){ diff --git a/src/tinyVAST.cpp b/src/tinyVAST.cpp index 8c630de2..40035546 100644 --- a/src/tinyVAST.cpp +++ b/src/tinyVAST.cpp @@ -1,6 +1,6 @@ #define TMB_LIB_INIT R_init_tinyVAST #include //Links in the TMB libraries -#include "utils.h" +//#include "utils.h" // Coding principles // 1. Don't telescope model features using `map` (which is bug-prone), but @@ -12,12 +12,1135 @@ // 4. spatial_graph always has dimension 1+, but DSEM functionality is removed if // sem=NULL such that nrow(ram_spacetime_term)=0 +// Note that moving functions to utils.hpp resulted in Internal Compiler Error (ICE) + +enum valid_family { + gaussian_family = 0, + tweedie_family = 1, + lognormal_family = 2, + poisson_family = 3, + bernoulli_family = 4, + binomial_family = 4, + gamma_family = 5, + nbinom1_family = 6, + nbinom2_family = 7, + student_family = 8 +}; + +enum valid_link { + identity_link = 0, + log_link = 1, + logit_link = 2, + cloglog_link = 3 +}; + +// Old algorithmic constructor for tail-down exponential stream network, copied from VAST +//template +//Eigen::SparseMatrix Q_network( Type log_theta, +// int n_s, +// vector parent_s, +// vector child_s, +// vector dist_s ){ +// +// Eigen::SparseMatrix Q( n_s, n_s ); +// Type theta = exp( log_theta ); +// for(int s=0; s +Eigen::SparseMatrix vectorsToSparseMatrix( + vector i, + vector j, + vector x, + int N ){ + + // https://eigen.tuxfamily.org/dox/classEigen_1_1SparseMatrix.html#title35 + using namespace Eigen; + std::vector> tripletList; + for( int index = 0; index < i.size(); index ++ ){ + tripletList.push_back(Triplet( i[index], j[index], x[index]) ); + } + SparseMatrix M( N, N ); + M.setFromTriplets( tripletList.begin(), tripletList.end() ); + + //Eigen::SparseMatrix M( N, N ); + //for(int index=0; index +struct spde_covariates_t{ + int n_s; + //int n_tri; + vector Tri_Area; + matrix E0; + matrix E1; + matrix E2; + matrix V_zk; + matrix TV; + Eigen::SparseMatrix G0; + Eigen::SparseMatrix G0_inv; + + // Define output + spde_covariates_t(SEXP x){ /* x = List passed from R */ + n_s = CppAD::Integer(asVector(getListElement(x,"n_s"))[0]); + //n_tri = CppAD::Integer(asVector(getListElement(x,"n_tri"))[0]); + Tri_Area = asVector(getListElement(x,"Tri_Area")); + E0 = asMatrix(getListElement(x,"E0")); + E1 = asMatrix(getListElement(x,"E1")); + E2 = asMatrix(getListElement(x,"E2")); + V_zk = asMatrix(getListElement(x,"V_zk")); + TV = asMatrix(getListElement(x,"TV")); + G0 = tmbutils::asSparseMatrix(getListElement(x,"G0")); + G0_inv = tmbutils::asSparseMatrix(getListElement(x,"G0_inv")); + } +}; +// make stiffness G1 from covariates in columns of E0, E1, E2 +template +Eigen::SparseMatrix G_spde_covariates( + spde_covariates_t spde, + matrix H_jj, + //matrix V_zk, + vector triangle_k ){ + + // TO ADD EDGE COVARIATES: + // 0. add n_e = edge0_tj.rows() + // 1. Add TE, where dim(TE) = n_t \times 3, listing the edge-number for each triangle-edge of n_e edges + // 2. Add A_ek design matrix, where dim(A_ek) = n_e \times n_k (edge-covariates) + + // Extract objects + vector area_t = spde.Tri_Area; + matrix edge0_tj = spde.E0; + matrix edge1_tj = spde.E1; + matrix edge2_tj = spde.E2; + matrix s_tv = spde.TV; // dim = n_t \times n_v + matrix triangle_t1 = spde.V_zk * triangle_k.matrix(); + int n_s = spde.n_s; + int n_t = s_tv.rows(); + int n_v = s_tv.cols(); // number of vertices per triangle + int n_j = edge0_tj.cols(); // number of covariates (default = 2) + + // Output + Eigen::SparseMatrix G_ss(n_s, n_s); + + // Objects to assemble triangle contributions + matrix edges_vj( n_v, n_j ); + matrix Gt_vv( n_v, n_v ); + + // Calculate adjugate of H + //matrix adjH_jj = H_jj.inverse() * H_jj.determinant(); // CAUSES CRASH + matrix adjH_jj = H_jj.adjoint(); + + // Assemble stiffness G + for( int t=0; t Gt_ss( n_s, n_s ); + for(int v1 = 0; v1 < 3; v1++ ){ + for(int v2 = 0; v2 < 3; v2++ ){ + Gt_ss.coeffRef( s_tv(t,v1), s_tv(t,v2) ) = Gt_vv(v1,v2); + }} + G_ss += Gt_ss / ( 4.0 * area_t(t) ); + } + return G_ss; +} + +// Q_SAR( log_kappa, H, n_s, i_z, j_z, delta_z2 ) +// Using a SAR (not standardized) to approximate spatial function +template +Eigen::SparseMatrix Q_SAR( + //Type rho, + Type kappa, + matrix H, + int n_s, + vector i_z, + vector j_z, + matrix delta_z2 ){ + + //Type max_dist = delta_z2.cwiseAbs().maxCoeff(); + + //d_z = sqrt((delta_z2 %*% H)^2 %*% matrix(1,nrow=2,ncol=1))[,1] + matrix deltaprime_z2 = (delta_z2 * H); // / max_dist; + vector dist_z( i_z.size() ); + for( int z = 0; z < i_z.size(); z++ ){ + dist_z(z) = pow( pow(deltaprime_z2(z,0),2.0) + pow(deltaprime_z2(z,1),2.0), 0.5 ); + } + vector weight_z = exp( -kappa * dist_z ); + + // Make weight matrix + Eigen::SparseMatrix W_ss = vectorsToSparseMatrix( + i_z, j_z, weight_z, n_s + ); + + // Row-standardize W_ss + // Does *not* make sense when using anisotropy + //for( int row = 0; row < n_s; row ++ ){ + // Type rowsum = W_ss.row(row).sum(); + // W_ss.row(row) /= rowsum; + //} + + // Assemble + Eigen::SparseMatrix I_ss( n_s, n_s ); + I_ss.setIdentity(); + Eigen::SparseMatrix IminusP_ss = I_ss - W_ss; + Eigen::SparseMatrix Q = IminusP_ss.transpose() * IminusP_ss; + return Q; +} + +// New matrix-notation precision constructor for tail-down exponential stream network +template +Eigen::SparseMatrix Q_network2( + Type log_theta, + int n_s, + vector parent_s, + vector child_s, + vector dist_s ){ + + // Compute vectors + Type theta = exp(log_theta); + vector v1_s = exp(-theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); + vector v2_s = exp(-2.0 * theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); + + // Make components + Eigen::SparseMatrix P_ss = vectorsToSparseMatrix( child_s, + parent_s, + v1_s, + n_s ); + Eigen::SparseMatrix D_ss = vectorsToSparseMatrix( child_s, + child_s, + v2_s, + n_s ); + Eigen::SparseMatrix invD_ss( n_s, n_s ); + for( int s=0; s DminusP_ss = D_ss - P_ss; + Eigen::SparseMatrix Q = DminusP_ss.transpose() * invD_ss * DminusP_ss; + return Q; +} + +// Functions to evaluate density for nearest-neighbors Gaussian process +template +vector covariance_function(vector d, Type sigma2, Type inv_range) { + return ((-d.array() * inv_range).exp() * sigma2).matrix(); +} +template +matrix covariance_function(matrix d, Type sigma2, Type inv_range) { + return ((-d.array() * inv_range).exp() * sigma2).matrix(); +} +/** \brief Object containing all data elements of an NNGP */ +template +struct nngp_data_t{ + vector nn_index_flat; + vector nn_len; + vector dist_to_nn_flat; + vector dist_within_nn_flat; + vector gp_order; + + // Define output + nngp_data_t(SEXP x){ /* x = List passed from R */ + nn_index_flat = asVector(getListElement(x,"nn_index_flat")); + nn_len = asVector(getListElement(x,"nn_len")); + dist_to_nn_flat = asVector(getListElement(x,"dist_to_nn_flat")); + dist_within_nn_flat = asVector(getListElement(x,"dist_within_nn_flat")); + gp_order = asVector(getListElement(x,"gp_order")); + } +}; +// Density function .. sigma2 fixed at 1.0 +template +Type NNGP( + Type sigma2, + Type range, + vector field_s, + // Data + nngp_data_t nngp_data ){ + + // Using original order and ordered_structure, by calling gp_order(i) and gp_order(nn_ids), because: + // 1. using original version in new order is very slow! presumably the order is terrible for the inner Hessian + // 2. using re-ordered version of field is confusing for users + Type nll = 0.0; + Type inv_range = 1.0 / range; // Multiplication is faster than division + vector nn_index_flat = nngp_data.nn_index_flat; + //vector nn_start = nngp_data.nn_start; + vector nn_len = nngp_data.nn_len; + vector dist_to_nn_flat = nngp_data.dist_to_nn_flat; + vector dist_within_nn_flat = nngp_data.dist_within_nn_flat; + vector gp_order = nngp_data.gp_order; + int n = field_s.size(); + + int pos_mat = 0; + int pos_vec = 0; + for( int i = 0; i < n; i++ ){ + int k = nn_len(i); + + // No neighbors + if(k == 0){ + nll -= dnorm( field_s(gp_order(i)), Type(0.0), sqrt(sigma2), true ); + }else{ + // Extract neighbor indices and distance to neighbors + vector nn_ids(k); + vector dist_iN(k); + for (int j = 0; j < k; j++) { + nn_ids(j) = nn_index_flat(pos_vec); + dist_iN(j) = dist_to_nn_flat(pos_vec); + pos_vec++; + } + + // Extract within-neighbor distance matrix (k x k) ... + matrix dist_NN(k, k); + for (int r = 0; r < k; r++) { + for (int c = 0; c < k; c++) { + dist_NN(r, c) = dist_within_nn_flat(pos_mat); + pos_mat++; + } + } + + // Covariances + matrix Sigma_NN = covariance_function(dist_NN, sigma2, inv_range); + vector Sigma_iN = covariance_function(dist_iN, sigma2, inv_range); + + // Solve + //vector a_i = solve(Sigma_NN, Sigma_iN); + //vector a_i = Sigma_NN.ldlt().solve( Sigma_iN.matrix() ); + //Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > invSigma_NN; + //invSigma_NN.compute(Sigma_NN); + //vector a_i = invSigma_NN.solve(Sigma_iN); + matrix Sigma_NN_inv = atomic::matinv(Sigma_NN); + vector a_i = Sigma_NN_inv * Sigma_iN; + + // Residual variance + Type resid_var = sigma2 - (a_i * Sigma_iN).sum(); // + 1e-12; + + // Conditional mean + Type cond_mean = 0.0; + for (int j = 0; j < k; j++) { + cond_mean += a_i(j) * field_s(gp_order(nn_ids(j))); + } + + // Likelihood + nll -= dnorm( field_s(gp_order(i)), cond_mean, sqrt(resid_var), true ); + } + } + return nll; +} + +// Function to calculate RAM matrices +template +Eigen::SparseMatrix make_ram( + matrix ram, + vector ram_start, + vector beta_z, + int n_c, + int what ){ + + Eigen::SparseMatrix out_cc(n_c, n_c); + out_cc.setZero(); + Type tmp; + + for(int r=0; r=1){ + tmp = beta_z(ram(r,3)-1); + }else{ + tmp = ram_start(r); + } + // Rho_cc + if( (ram(r,0)==1) && (what==0) ){ + out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; + } + // Gammainv_cc + if( (ram(r,0)==2) && (what==1) ){ + out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = 1 / tmp; + } + // Gamma_cc + if( (ram(r,0)==2) && (what==2) ){ + out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; + } + } + + return out_cc; +} + +// distribution/projection for gamma +// Based on: +// https://github.com/meganferg/FergusonEtal_20250125_EBS_Beluga_DSM/blob/main/src/te_tw_DSM.cpp#L85C9-L85C40 (Megan Ferguson) +template +Type gamma_distribution( + vector gamma_k, + vector Sdims, + vector Sblock, + Eigen::SparseMatrix S_kk, + vector log_lambda ){ + + using namespace density; + Type nll = 0.0; + int start_gamma = 0; // Counter for gamma + int start_k = 0; // counter for columns of S_kk + int index_lambda = 0; + for(int z=0; z gamma_segment = gamma_k.segment(start_gamma, ngamma_z); + start_gamma += ngamma_z; + + // s() splines + if( Sblock(z) == 1 ){ + // Recover S_block + Eigen::SparseMatrix S_block = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i + + /// Quadratic-form GRMF + // GMRF(Q).Quadform(x) caused a problem calculating the log-determinant unnecessarily, resulting in valgrind error + //nll -= Type(0.5)*Type(m_z)*log_lambda(z) - Type(0.5)*exp(log_lambda(z))*GMRF(S_block).Quadform(gamma_segment); + nll -= Type(0.5)*Type(ngamma_z)*log_lambda(index_lambda) - Type(0.5) * exp(log_lambda(index_lambda)) * + (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); + + start_k += ngamma_z; + index_lambda += 1; + } + + // te() / ti() / t2() splines + if( Sblock(z) >= 2 ){ + // Recover S_block ... Eigen::SparseMatrix appears to initialize as empty so no .setZero() equivalent needed + Eigen::SparseMatrix S_block( ngamma_z, ngamma_z ); + for( int block=0; block < Sblock(z); block ++ ){ + Eigen::SparseMatrix S_tmp = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i + S_block += exp(log_lambda(index_lambda)) * S_tmp; + start_k += ngamma_z; + index_lambda++; + } + + /// Quadratic-form GRMF + nll -= 0.5*(atomic::logdet(matrix(S_block))) - 0.5 * + (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); + } + } + return( nll ); +} + +// distribution/projection for omega +template +tmbutils::array omega_distribution( + tmbutils::array omega_sc, + vector model_options, + Eigen::SparseMatrix Rho_cc, + Eigen::SparseMatrix Gamma_cc, + Eigen::SparseMatrix Gammainv_cc, + Eigen::SparseMatrix Q_ss, + Type range, + nngp_data_t nngp_data, + Type &nll ){ + + if( omega_sc.size() > 0 ){ + int n_c = omega_sc.dim(1); + using namespace density; + Eigen::SparseMatrix I_cc( n_c, n_c ); + I_cc.setIdentity(); + if( omega_sc.size()>0 ){ // PARALLEL_REGION + Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; + if( model_options(1) == 0 ){ + // Separable precision ... Option-1 + //Eigen::SparseMatrix Linv_cc = Gammainv_cc * ( I_cc - Rho_cc ); + //Eigen::SparseMatrix Q_cc = Linv_cc.transpose() * Linv_cc; + + // Separable precision ... Option-2 + // Only compute Vinv_kk if Gamma_kk is full rank + Eigen::SparseMatrix V_cc = Gamma_cc.transpose() * Gamma_cc; + matrix Vinv_cc = invertSparseMatrix( V_cc ); + Eigen::SparseMatrix Vinv2_cc = asSparseMatrix( Vinv_cc ); + Eigen::SparseMatrix Q_cc = IminusRho_cc.transpose() * Vinv2_cc * IminusRho_cc; + + // GMRF for SEM: separable variable-space + nll += SEPARABLE( GMRF(Q_cc), GMRF(Q_ss) )( omega_sc ); + // Including this line with Makevars below seems to cause a crash: + // PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) + // PKG_CXXFLAGS=$(SHLIB_OPENMP_CXXFLAGS) + }else{ + // Rank-deficient (projection) method + if( model_options(0) == 7 ){ + vector omega_s( omega_sc.rows() ); + for( int ci = 0; ci < omega_sc.cols(); ci++ ){ + omega_s = omega_sc.col(ci); + nll += NNGP( Type(1.0), range, omega_s, nngp_data ); + } + }else{ + nll += SEPARABLE( GMRF(I_cc), GMRF(Q_ss) )( omega_sc ); + } + + // Sparse inverse-product + //Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; + Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_cc; + inverseIminusRho_cc.compute(IminusRho_cc); + + // (I-Rho)^{-1} * Gamma * Epsilon + matrix omega2_cs = Gamma_cc * omega_sc.matrix().transpose(); + matrix omega3_cs = inverseIminusRho_cc.solve(omega2_cs); + omega_sc = omega3_cs.transpose(); + } + } + } + + return omega_sc; +} + +// distribution/projection for xi +template +Type xi_distribution( + vector model_options, + tmbutils::array xi_sl, + vector log_sigmaxi_l, + Eigen::SparseMatrix Q_ss, + Type range, + nngp_data_t nngp_data ){ + + Type nll = 0; + if( xi_sl.size() > 0 ){ + int n_l = xi_sl.cols(); + using namespace density; + if( model_options(0) == 7 ){ + vector xi_s( xi_sl.rows() ); + for( int l=0; l +tmbutils::array epsilon_distribution( + tmbutils::array epsilon_stc, + vector model_options, + Eigen::SparseMatrix Rho_hh, + Eigen::SparseMatrix Gamma_hh, + Eigen::SparseMatrix Gammainv_hh, + Eigen::SparseMatrix Q_ss, + Type range, + nngp_data_t nngp_data, + Type &nll ){ + + if( epsilon_stc.size() > 0 ){ + int n_s = epsilon_stc.dim(0); + int n_t = epsilon_stc.dim(1); + int n_c = epsilon_stc.dim(2); + int n_h = n_t * n_c; + using namespace density; + Eigen::SparseMatrix I_hh( n_h, n_h ); + I_hh.setIdentity(); + int h; + + //if( epsilon_stc.size()>0 ){ // PARALLEL_REGION + // Reshape for either model_options + tmbutils::array epsilon_hs( n_h, n_s ); + for( int s=0; s IminusRho_hh = I_hh - Rho_hh; + + if( model_options(1) == 0 ){ + // Separable precision ... Option-1 + //Eigen::SparseMatrix Linv_hh = Gammainv_hh * ( I_hh - Rho_hh ); + //Eigen::SparseMatrix Q_hh = Linv_hh.transpose() * Linv_hh; + + // Separable precision ... Option-2 + // Only compute Vinv_kk if Gamma_kk is full rank + Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; + matrix Vinv_hh = invertSparseMatrix( V_hh ); + Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); + Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; + + // GMRF for DSEM: non-separable time-variable, with separable space + nll += SEPARABLE( GMRF(Q_ss), GMRF(Q_hh) )( epsilon_hs ); + }else{ + // Rank-deficient (projection) method + if( model_options(0) == 7 ){ + vector epsilon_s( epsilon_hs.cols() ); + for( int hi = 0; hi < epsilon_hs.rows(); hi++ ){ + epsilon_s = epsilon_hs.matrix().row(hi); + nll += NNGP( Type(1.0), range, epsilon_s, nngp_data ); + } + }else{ + nll += SEPARABLE( GMRF(Q_ss), GMRF(I_hh) )( epsilon_hs ); + } + + // Sparse inverse-product + //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; + Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; + inverseIminusRho_hh.compute(IminusRho_hh); + + // (I-Rho)^{-1} * Gamma * Epsilon + matrix e2_hs = Gamma_hh * epsilon_hs.matrix(); + matrix e3_hs = inverseIminusRho_hh.solve(e2_hs); + + // Transformations + for( int s=0; s +tmbutils::array delta_distribution( + tmbutils::array delta_tc, + vector model_options, + Eigen::SparseMatrix Rho_hh, + Eigen::SparseMatrix Gamma_hh, + Eigen::SparseMatrix Gammainv_hh, + Type &nll ){ + + if( delta_tc.size() > 0 ){ + int n_t = delta_tc.dim(0); + int n_c = delta_tc.dim(1); + int n_h = n_t * n_c; + using namespace density; + Eigen::SparseMatrix I_hh( n_h, n_h ); + I_hh.setIdentity(); + int h; + + // Reshape for either model_options + tmbutils::array delta_h1( n_h, 1 ); + for( int t=0; t IminusRho_hh = I_hh - Rho_hh; + + if( model_options(1) == 0 ){ + Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; + matrix Vinv_hh = invertSparseMatrix( V_hh ); + Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); + Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; + + // GMRF for DSEM: non-separable time-variable, with separable space + nll += GMRF(Q_hh)( delta_h1 ); + }else{ + // Rank-deficient (projection) method + nll += GMRF(I_hh)( delta_h1 ); + + // Sparse inverse-product + //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; + Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; + inverseIminusRho_hh.compute(IminusRho_hh); + + // (I-Rho)^{-1} * Gamma * Epsilon + matrix e2_h1 = Gamma_hh * delta_h1.matrix(); + matrix e3_h1 = inverseIminusRho_hh.solve(e2_h1); + + // Transformations + for( int t=0; t +bool isNA(Type x){ + return R_IsNA(asDouble(x)); +} + +// Sparse array * matrix +// NAs in IVECTOR or IMATRIX get converted to -2147483648, so isNA doesn't work ... instead drop NAs from A prior to passing to TMB +template +vector multiply_epsilon( + matrix A, + vector weight, + tmbutils::array x, + int n_i ){ + + vector out( n_i ); + out.setZero(); + if( x.size() > 0 ){ + for( int z=0; z +vector multiply_omega( + matrix A, + vector weight, + tmbutils::array x, + int n_i ){ + + vector out( n_i ); + out.setZero(); + if( x.size() > 0 ){ + for( int z=0; z +vector multiply_xi( + Eigen::SparseMatrix A_is, + tmbutils::array xi_sl, + matrix W_il ){ + + vector out( W_il.rows() ); + out.setZero(); + if( xi_sl.size() > 0 ){ + matrix xi_il = A_is * xi_sl.matrix(); + for( int i=0; i +vector multiply_delta( + tmbutils::array delta_tc, + vector t_i, + vector c_i, + int n_i ){ + + vector delta_i( n_i ); + delta_i.setZero(); + if( delta_tc.size() > 0 ){ + for( int i=0; i +Type sign(Type x){ + return x / pow(pow(x,2),0.5); +} + +// dlnorm +template +Type dlnorm( + Type x, + Type meanlog, + Type sdlog, + int give_log=0){ + + //return 1/(sqrt(2*M_PI)*sd) * exp(-.5*pow((x-mean)/sd,2)); + Type logres = dnorm( log(x), meanlog, sdlog, true) - log(x); + if(give_log) return logres; else return exp(logres); +} + +// dlnorm +template +Type dbinom_custom( + Type x, + Type log_prob, + Type log_one_minus_prob, + Type size, + int give_log = 0 ){ + + // size choose x + Type logres = lgamma(size + 1.0) - lgamma(x + 1.0) - lgamma(size - x + 1.0); + // p^x * (1-p)^(size-x) + logres += x * log_prob + (size-x) * log_one_minus_prob; + if(give_log) return logres; else return exp(logres); +} + +// dlnorm +template +Type devresid_binom( + Type y, + Type weight, // weight = size + Type mu ){ + + Type y_weight = y * weight; + Type mu_weight = mu * weight; + Type p1, p2; + if(y_weight == 0){ + p1 = 0.0; + }else{ + p1 = y_weight * log(y_weight / mu_weight); + } + if( (weight - y_weight) == 0 ){ + p2 = 0.0; + }else{ + p2 = (weight - y_weight) * log( (weight - y_weight) / (weight - mu_weight) ); + } + Type devresid = sign(y - mu) * pow(2 * (p1 + p2), 0.5); + return devresid; +} + +// Deviance for the Tweedie +// https://en.wikipedia.org/wiki/Tweedie_distribution#Properties +template +Type devresid_tweedie( + Type y, + Type mu, + Type p ){ + + Type c1 = pow( y, 2.0-p ) / (1.0-p) / (2.0-p); + Type c2 = y * pow( mu, 1.0-p ) / (1.0-p); + Type c3 = pow( mu, 2.0-p ) / (2.0-p); + Type deviance = 2 * (c1 - c2 + c3 ); + Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); + return devresid; +} + +// Deviance for the student-T +// from chatGPT (experimental) ... converges on Gaussian as df -> Inf +template +Type devresid_student( + Type y, + Type mu, + Type sigma, + Type df ){ + + Type deviance = (df + 1.0) * log( 1.0 + pow(y-mu,2.0) / (df * sigma*sigma) ); + Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); + return devresid; +} + +// COPIED from sdmTMB.cpp in sdmTMB package on Nov. 14, 2025 +template +Type dstudent( + Type x, + Type mean, + Type sigma, + Type df, + int give_log = 0) { + + // from metRology::dt.scaled() + // dt((x - mean)/sd, df, ncp = ncp, log = TRUE) - log(sd) + Type logres = dt((x - mean) / sigma, df, true) - log(sigma); + if (give_log) + return logres; + else + return exp(logres); +} + +// Deviance for the Negative binomial +//template +//Type devresid_nbinom1( Type y, +// Type logmu, +// Type logtheta ){ +// +// // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu +// Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), log(y + Type(1e-10)) + logtheta, true ); +// Type logp2 = dnbinom_robust( y, logmu, logmu + logtheta, true ); +// Type deviance = 2 * (logp1 - logp2); +// Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); +// return devresid; +//} +template +Type devresid_nbinom2( + Type y, + Type logmu, + Type logtheta ){ + + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), Type(2.0) * log(y + Type(1e-10)) - logtheta, true ); + Type logp2 = dnbinom_robust( y, logmu, Type(2.0) * logmu - logtheta, true ); + Type deviance = 2 * (logp1 - logp2); + Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); + return devresid; +} + + +// distribution/projection for epsilon +// deviance = deviance1 + deviance2 +template +Type one_predictor_likelihood( + Type &y, + Type p, + Type size, + int link, + int family, + vector log_sigma_segment, + Type &nll, + Type &devresid, + objective_function* of ){ + + Type mu, logmu, log_one_minus_mu; + //Type devresid = 0; + + switch( link ){ + case identity_link: + mu = p; + logmu = log( p ); + log_one_minus_mu = log( Type(1.0) - mu ); + break; + case log_link: + mu = exp(p); + logmu = p; + log_one_minus_mu = log( Type(1.0) - mu ); + break; + case logit_link: + mu = invlogit(p); + //logmu = log(mu); + logmu = p - logspace_add( Type(0.0), p ); + //log_one_minus_mu = log( invlogit(-1 * p) ); + log_one_minus_mu = 0.0 - logspace_add( Type(0.0), p ); + break; + case cloglog_link: + mu = Type(1.0) - exp( -1 * exp(p) ); + logmu = logspace_sub( Type(0.0), -1.0 * exp(p) ); + log_one_minus_mu = -1.0 * exp(p); + break; + default: + error("Link not implemented."); + } + if( !R_IsNA(asDouble(y)) ){ + // Distribution + switch( family ){ + case gaussian_family: + nll = -1 * dnorm( y, mu, exp(log_sigma_segment(0)), true ); + devresid = y - mu; + if(isDouble::value && of->do_simulate){ + y = rnorm( mu, exp(log_sigma_segment(0)) ); + } + break; + case tweedie_family: + nll = -1 * dtweedie( y, mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); + devresid = devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); + if(isDouble::value && of->do_simulate){ + y = rtweedie( mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); + } + break; + case lognormal_family: + nll = -1 * dlnorm( y, logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); + devresid = log(y) - ( logmu - 0.5*exp(2.0*log_sigma_segment(0)) ); + if(isDouble::value && of->do_simulate){ + y = exp(rnorm( logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); + } + break; + case poisson_family: + nll = -1 * dpois( y, mu, true ); + devresid = sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); + if(isDouble::value && of->do_simulate){ + y = rpois( mu ); + } + break; + case binomial_family: + //if(y==0){ + // nll = -1 * log_one_minus_mu; + //}else{ + // nll = -1 * logmu; + //} + nll = -1 * dbinom_custom( y * size, logmu, log_one_minus_mu, size, true ); + if(isDouble::value && of->do_simulate){ + y = rbinom( size, mu ); + } + // TODO: Update deviance residual for Trials = size + //devresid = sign(y - mu) * pow(-2*((1-y)*log(1.0-mu) + y*log(mu)), 0.5); + devresid = devresid_binom( y, size, mu ); + break; + case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 + nll = -1 * dgamma( y, exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)), true ); + devresid = sign(y - mu) * pow(2 * ( (y-mu)/mu - log(y/mu) ), 0.5); + if(isDouble::value && of->do_simulate){ + y = rgamma( exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)) ); + } + break; + case nbinom1_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu + nll = -1 * dnbinom_robust( y, logmu, logmu + log_sigma_segment(0), true); + devresid = devresid_nbinom2( y, logmu, logmu - log_sigma_segment(0) ); // theta = mu / phi + if(isDouble::value && of->do_simulate){ + // rnbinom2( mu, var ) + y = rnbinom2( mu, mu * (Type(1.0) + exp(log_sigma_segment(0))) ); + } + break; + case nbinom2_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + nll = -1 * dnbinom_robust( y, logmu, Type(2.0) * logmu - log_sigma_segment(0), true); + devresid = devresid_nbinom2( y, logmu, log_sigma_segment(0) ); + if(isDouble::value && of->do_simulate){ + // rnbinom2( mu, var ) + y = rnbinom2( mu, mu * (Type(1.0) + mu / exp(log_sigma_segment(0))) ); + } + break; + case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + nll = -1 * dstudent( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); + devresid = devresid_student( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)) ); + if(isDouble::value && of->do_simulate){ + y = mu + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); + } + break; + default: + error("Distribution not implemented."); + } + } + + return mu; +} + +// distribution/projection for epsilon +template +Type two_predictor_likelihood( + Type &y, + Type p1, + Type p2, + Type size, + vector link, + vector family, + vector log_sigma_segment, + int poislink, + Type &nll, + Type &dev, + objective_function* of ){ + + Type mu1, logmu1, mu2, logmu2, log_one_minus_mu1; + + // First link + if( poislink==0 ){ + mu1 = invlogit( p1 ); + logmu1 = log( mu1 ); + log_one_minus_mu1 = log( Type(1.0) - mu1 ); + // second link + switch( link(1) ){ + case identity_link: + mu2 = p2; + logmu2 = log( p2 ); + break; + case log_link: + mu2 = exp(p2); + logmu2 = p2; + break; + default: + error("Link not implemented."); + } + }else{ + mu1 = Type(1.0) - exp( -1.0*exp(p1) ); + logmu1 = logspace_sub( Type(0.0), -1*exp(p1) ); + log_one_minus_mu1 = -1.0*exp(p1); + mu2 = exp( p1 + p2 ) / mu1; + logmu2 = p1 + p2 - logmu1; + } + if( !R_IsNA(asDouble(y)) ){ + // Distribution + if(isDouble::value && of->do_simulate){ + y = rbinom( Type(1), mu1 ); + } + if( y == 0 ){ + nll = -1 * log_one_minus_mu1; + dev = -2 * log_one_minus_mu1; + } + if( y>0 ){ // Not if-else so y>0 triggered when simulating y>0 + nll = -1 * logmu1; + dev = -2 * logmu1; + //deviance1_i(i) = -2 * log_mu1(i); + switch( family(1) ){ + case gaussian_family: + nll -= dnorm( y, mu2, exp(log_sigma_segment(0)), true ); + dev += pow(y - mu2, 2.0); + if(isDouble::value && of->do_simulate){ + y = rnorm( mu2, exp(log_sigma_segment(0)) ); + } + break; + //case tweedie_family: + // nll -= dtweedie( y, mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); + // devresid += devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); + // if(isDouble::value && of->do_simulate){ + // y = rtweedie( mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); + // } + // break; + case lognormal_family: + nll -= dlnorm( y, logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); + dev += pow( log(y) - (logmu2 - 0.5*exp(2.0*log_sigma_segment(0))), 2.0 ); + if(isDouble::value && of->do_simulate){ + y = exp(rnorm( logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); + } + break; + //case poisson_family: + // nll -= dpois( y, mu2, true ); + // devresid += sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); + // if(isDouble::value && of->do_simulate){ + // y = rpois( mu2 ); + // } + // break; + // case 4: // Bernoulli + case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 + nll -= dgamma( y, exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)), true ); + dev += 2 * ( (y-mu2)/mu2 - log(y/mu2) ); + if(isDouble::value && of->do_simulate){ + y = rgamma( exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)) ); + } + break; + case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + nll -= dstudent( y, mu2, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); + //dev = NAN; + if(isDouble::value && of->do_simulate){ + y = mu2 + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); + } + break; + default: + error("Distribution not implemented."); + } + } + } + + return mu1 * mu2; +} + template Type objective_function::operator() (){ //using namespace R_inla; // Not loaded globally, but used below using namespace density; using namespace Eigen; - using namespace tinyVAST; + //using namespace tinyVAST; // Settings DATA_IMATRIX( family_ez ); // family From 0f7fd850ed1c2aa879699769e729f1b3d4a2853d Mon Sep 17 00:00:00 2001 From: James Thorson Date: Mon, 13 Jul 2026 20:42:07 -0700 Subject: [PATCH 15/37] re-add tinyVAST namespace --- NEWS.md | 1 + scratch/helper_functions.cpp | 1122 +++++++++++++++++++++++++++++++++ src/tinyVAST.cpp | 1126 +--------------------------------- src/utils.h | 1122 +++++++++++++++++++++++++++++++++ 4 files changed, 2247 insertions(+), 1124 deletions(-) create mode 100644 scratch/helper_functions.cpp create mode 100644 src/utils.h diff --git a/NEWS.md b/NEWS.md index 9d6b3d5d..59433e67 100644 --- a/NEWS.md +++ b/NEWS.md @@ -3,6 +3,7 @@ * Replace array with tmbutils::array in CPP, to disambiguate new array typedef in RcppEigen, following andrjohns in dsem#63 * Remove "test-basic-fits.R" test "tinyVAST works as dsem" from CRAN, due to weird and un-reproducible ERROR on CRAN openBLAS check * Update `epsilon_distribution` to pass arguments using const and pointers (pass-by-const-reference) to avoid compiler errors +* Move helper functions to `tinyVAST` namespace # tinyVAST 1.6.1 diff --git a/scratch/helper_functions.cpp b/scratch/helper_functions.cpp new file mode 100644 index 00000000..62afc6be --- /dev/null +++ b/scratch/helper_functions.cpp @@ -0,0 +1,1122 @@ +// Note that moving functions to utils.hpp resulted in Internal Compiler Error (ICE) + +enum valid_family { + gaussian_family = 0, + tweedie_family = 1, + lognormal_family = 2, + poisson_family = 3, + bernoulli_family = 4, + binomial_family = 4, + gamma_family = 5, + nbinom1_family = 6, + nbinom2_family = 7, + student_family = 8 +}; + +enum valid_link { + identity_link = 0, + log_link = 1, + logit_link = 2, + cloglog_link = 3 +}; + +// Old algorithmic constructor for tail-down exponential stream network, copied from VAST +//template +//Eigen::SparseMatrix Q_network( Type log_theta, +// int n_s, +// vector parent_s, +// vector child_s, +// vector dist_s ){ +// +// Eigen::SparseMatrix Q( n_s, n_s ); +// Type theta = exp( log_theta ); +// for(int s=0; s +Eigen::SparseMatrix vectorsToSparseMatrix( + vector i, + vector j, + vector x, + int N ){ + + // https://eigen.tuxfamily.org/dox/classEigen_1_1SparseMatrix.html#title35 + using namespace Eigen; + std::vector> tripletList; + for( int index = 0; index < i.size(); index ++ ){ + tripletList.push_back(Triplet( i[index], j[index], x[index]) ); + } + SparseMatrix M( N, N ); + M.setFromTriplets( tripletList.begin(), tripletList.end() ); + + //Eigen::SparseMatrix M( N, N ); + //for(int index=0; index +struct spde_covariates_t{ + int n_s; + //int n_tri; + vector Tri_Area; + matrix E0; + matrix E1; + matrix E2; + matrix V_zk; + matrix TV; + Eigen::SparseMatrix G0; + Eigen::SparseMatrix G0_inv; + + // Define output + spde_covariates_t(SEXP x){ /* x = List passed from R */ + n_s = CppAD::Integer(asVector(getListElement(x,"n_s"))[0]); + //n_tri = CppAD::Integer(asVector(getListElement(x,"n_tri"))[0]); + Tri_Area = asVector(getListElement(x,"Tri_Area")); + E0 = asMatrix(getListElement(x,"E0")); + E1 = asMatrix(getListElement(x,"E1")); + E2 = asMatrix(getListElement(x,"E2")); + V_zk = asMatrix(getListElement(x,"V_zk")); + TV = asMatrix(getListElement(x,"TV")); + G0 = tmbutils::asSparseMatrix(getListElement(x,"G0")); + G0_inv = tmbutils::asSparseMatrix(getListElement(x,"G0_inv")); + } +}; +// make stiffness G1 from covariates in columns of E0, E1, E2 +template +Eigen::SparseMatrix G_spde_covariates( + spde_covariates_t spde, + matrix H_jj, + //matrix V_zk, + vector triangle_k ){ + + // TO ADD EDGE COVARIATES: + // 0. add n_e = edge0_tj.rows() + // 1. Add TE, where dim(TE) = n_t \times 3, listing the edge-number for each triangle-edge of n_e edges + // 2. Add A_ek design matrix, where dim(A_ek) = n_e \times n_k (edge-covariates) + + // Extract objects + vector area_t = spde.Tri_Area; + matrix edge0_tj = spde.E0; + matrix edge1_tj = spde.E1; + matrix edge2_tj = spde.E2; + matrix s_tv = spde.TV; // dim = n_t \times n_v + matrix triangle_t1 = spde.V_zk * triangle_k.matrix(); + int n_s = spde.n_s; + int n_t = s_tv.rows(); + int n_v = s_tv.cols(); // number of vertices per triangle + int n_j = edge0_tj.cols(); // number of covariates (default = 2) + + // Output + Eigen::SparseMatrix G_ss(n_s, n_s); + + // Objects to assemble triangle contributions + matrix edges_vj( n_v, n_j ); + matrix Gt_vv( n_v, n_v ); + + // Calculate adjugate of H + //matrix adjH_jj = H_jj.inverse() * H_jj.determinant(); // CAUSES CRASH + matrix adjH_jj = H_jj.adjoint(); + + // Assemble stiffness G + for( int t=0; t Gt_ss( n_s, n_s ); + for(int v1 = 0; v1 < 3; v1++ ){ + for(int v2 = 0; v2 < 3; v2++ ){ + Gt_ss.coeffRef( s_tv(t,v1), s_tv(t,v2) ) = Gt_vv(v1,v2); + }} + G_ss += Gt_ss / ( 4.0 * area_t(t) ); + } + return G_ss; +} + +// Q_SAR( log_kappa, H, n_s, i_z, j_z, delta_z2 ) +// Using a SAR (not standardized) to approximate spatial function +template +Eigen::SparseMatrix Q_SAR( + //Type rho, + Type kappa, + matrix H, + int n_s, + vector i_z, + vector j_z, + matrix delta_z2 ){ + + //Type max_dist = delta_z2.cwiseAbs().maxCoeff(); + + //d_z = sqrt((delta_z2 %*% H)^2 %*% matrix(1,nrow=2,ncol=1))[,1] + matrix deltaprime_z2 = (delta_z2 * H); // / max_dist; + vector dist_z( i_z.size() ); + for( int z = 0; z < i_z.size(); z++ ){ + dist_z(z) = pow( pow(deltaprime_z2(z,0),2.0) + pow(deltaprime_z2(z,1),2.0), 0.5 ); + } + vector weight_z = exp( -kappa * dist_z ); + + // Make weight matrix + Eigen::SparseMatrix W_ss = vectorsToSparseMatrix( + i_z, j_z, weight_z, n_s + ); + + // Row-standardize W_ss + // Does *not* make sense when using anisotropy + //for( int row = 0; row < n_s; row ++ ){ + // Type rowsum = W_ss.row(row).sum(); + // W_ss.row(row) /= rowsum; + //} + + // Assemble + Eigen::SparseMatrix I_ss( n_s, n_s ); + I_ss.setIdentity(); + Eigen::SparseMatrix IminusP_ss = I_ss - W_ss; + Eigen::SparseMatrix Q = IminusP_ss.transpose() * IminusP_ss; + return Q; +} + +// New matrix-notation precision constructor for tail-down exponential stream network +template +Eigen::SparseMatrix Q_network2( + Type log_theta, + int n_s, + vector parent_s, + vector child_s, + vector dist_s ){ + + // Compute vectors + Type theta = exp(log_theta); + vector v1_s = exp(-theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); + vector v2_s = exp(-2.0 * theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); + + // Make components + Eigen::SparseMatrix P_ss = vectorsToSparseMatrix( child_s, + parent_s, + v1_s, + n_s ); + Eigen::SparseMatrix D_ss = vectorsToSparseMatrix( child_s, + child_s, + v2_s, + n_s ); + Eigen::SparseMatrix invD_ss( n_s, n_s ); + for( int s=0; s DminusP_ss = D_ss - P_ss; + Eigen::SparseMatrix Q = DminusP_ss.transpose() * invD_ss * DminusP_ss; + return Q; +} + +// Functions to evaluate density for nearest-neighbors Gaussian process +template +vector covariance_function(vector d, Type sigma2, Type inv_range) { + return ((-d.array() * inv_range).exp() * sigma2).matrix(); +} +template +matrix covariance_function(matrix d, Type sigma2, Type inv_range) { + return ((-d.array() * inv_range).exp() * sigma2).matrix(); +} +/** \brief Object containing all data elements of an NNGP */ +template +struct nngp_data_t{ + vector nn_index_flat; + vector nn_len; + vector dist_to_nn_flat; + vector dist_within_nn_flat; + vector gp_order; + + // Define output + nngp_data_t(SEXP x){ /* x = List passed from R */ + nn_index_flat = asVector(getListElement(x,"nn_index_flat")); + nn_len = asVector(getListElement(x,"nn_len")); + dist_to_nn_flat = asVector(getListElement(x,"dist_to_nn_flat")); + dist_within_nn_flat = asVector(getListElement(x,"dist_within_nn_flat")); + gp_order = asVector(getListElement(x,"gp_order")); + } +}; +// Density function .. sigma2 fixed at 1.0 +template +Type NNGP( + Type sigma2, + Type range, + vector field_s, + // Data + nngp_data_t nngp_data ){ + + // Using original order and ordered_structure, by calling gp_order(i) and gp_order(nn_ids), because: + // 1. using original version in new order is very slow! presumably the order is terrible for the inner Hessian + // 2. using re-ordered version of field is confusing for users + Type nll = 0.0; + Type inv_range = 1.0 / range; // Multiplication is faster than division + vector nn_index_flat = nngp_data.nn_index_flat; + //vector nn_start = nngp_data.nn_start; + vector nn_len = nngp_data.nn_len; + vector dist_to_nn_flat = nngp_data.dist_to_nn_flat; + vector dist_within_nn_flat = nngp_data.dist_within_nn_flat; + vector gp_order = nngp_data.gp_order; + int n = field_s.size(); + + int pos_mat = 0; + int pos_vec = 0; + for( int i = 0; i < n; i++ ){ + int k = nn_len(i); + + // No neighbors + if(k == 0){ + nll -= dnorm( field_s(gp_order(i)), Type(0.0), sqrt(sigma2), true ); + }else{ + // Extract neighbor indices and distance to neighbors + vector nn_ids(k); + vector dist_iN(k); + for (int j = 0; j < k; j++) { + nn_ids(j) = nn_index_flat(pos_vec); + dist_iN(j) = dist_to_nn_flat(pos_vec); + pos_vec++; + } + + // Extract within-neighbor distance matrix (k x k) ... + matrix dist_NN(k, k); + for (int r = 0; r < k; r++) { + for (int c = 0; c < k; c++) { + dist_NN(r, c) = dist_within_nn_flat(pos_mat); + pos_mat++; + } + } + + // Covariances + matrix Sigma_NN = covariance_function(dist_NN, sigma2, inv_range); + vector Sigma_iN = covariance_function(dist_iN, sigma2, inv_range); + + // Solve + //vector a_i = solve(Sigma_NN, Sigma_iN); + //vector a_i = Sigma_NN.ldlt().solve( Sigma_iN.matrix() ); + //Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > invSigma_NN; + //invSigma_NN.compute(Sigma_NN); + //vector a_i = invSigma_NN.solve(Sigma_iN); + matrix Sigma_NN_inv = atomic::matinv(Sigma_NN); + vector a_i = Sigma_NN_inv * Sigma_iN; + + // Residual variance + Type resid_var = sigma2 - (a_i * Sigma_iN).sum(); // + 1e-12; + + // Conditional mean + Type cond_mean = 0.0; + for (int j = 0; j < k; j++) { + cond_mean += a_i(j) * field_s(gp_order(nn_ids(j))); + } + + // Likelihood + nll -= dnorm( field_s(gp_order(i)), cond_mean, sqrt(resid_var), true ); + } + } + return nll; +} + +// Function to calculate RAM matrices +template +Eigen::SparseMatrix make_ram( + matrix ram, + vector ram_start, + vector beta_z, + int n_c, + int what ){ + + Eigen::SparseMatrix out_cc(n_c, n_c); + out_cc.setZero(); + Type tmp; + + for(int r=0; r=1){ + tmp = beta_z(ram(r,3)-1); + }else{ + tmp = ram_start(r); + } + // Rho_cc + if( (ram(r,0)==1) && (what==0) ){ + out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; + } + // Gammainv_cc + if( (ram(r,0)==2) && (what==1) ){ + out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = 1 / tmp; + } + // Gamma_cc + if( (ram(r,0)==2) && (what==2) ){ + out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; + } + } + + return out_cc; +} + +// distribution/projection for gamma +// Based on: +// https://github.com/meganferg/FergusonEtal_20250125_EBS_Beluga_DSM/blob/main/src/te_tw_DSM.cpp#L85C9-L85C40 (Megan Ferguson) +template +Type gamma_distribution( + vector gamma_k, + vector Sdims, + vector Sblock, + Eigen::SparseMatrix S_kk, + vector log_lambda ){ + + using namespace density; + Type nll = 0.0; + int start_gamma = 0; // Counter for gamma + int start_k = 0; // counter for columns of S_kk + int index_lambda = 0; + for(int z=0; z gamma_segment = gamma_k.segment(start_gamma, ngamma_z); + start_gamma += ngamma_z; + + // s() splines + if( Sblock(z) == 1 ){ + // Recover S_block + Eigen::SparseMatrix S_block = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i + + /// Quadratic-form GRMF + // GMRF(Q).Quadform(x) caused a problem calculating the log-determinant unnecessarily, resulting in valgrind error + //nll -= Type(0.5)*Type(m_z)*log_lambda(z) - Type(0.5)*exp(log_lambda(z))*GMRF(S_block).Quadform(gamma_segment); + nll -= Type(0.5)*Type(ngamma_z)*log_lambda(index_lambda) - Type(0.5) * exp(log_lambda(index_lambda)) * + (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); + + start_k += ngamma_z; + index_lambda += 1; + } + + // te() / ti() / t2() splines + if( Sblock(z) >= 2 ){ + // Recover S_block ... Eigen::SparseMatrix appears to initialize as empty so no .setZero() equivalent needed + Eigen::SparseMatrix S_block( ngamma_z, ngamma_z ); + for( int block=0; block < Sblock(z); block ++ ){ + Eigen::SparseMatrix S_tmp = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i + S_block += exp(log_lambda(index_lambda)) * S_tmp; + start_k += ngamma_z; + index_lambda++; + } + + /// Quadratic-form GRMF + nll -= 0.5*(atomic::logdet(matrix(S_block))) - 0.5 * + (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); + } + } + return( nll ); +} + +// distribution/projection for omega +template +tmbutils::array omega_distribution( + tmbutils::array omega_sc, + vector model_options, + Eigen::SparseMatrix Rho_cc, + Eigen::SparseMatrix Gamma_cc, + Eigen::SparseMatrix Gammainv_cc, + Eigen::SparseMatrix Q_ss, + Type range, + nngp_data_t nngp_data, + Type &nll ){ + + if( omega_sc.size() > 0 ){ + int n_c = omega_sc.dim(1); + using namespace density; + Eigen::SparseMatrix I_cc( n_c, n_c ); + I_cc.setIdentity(); + if( omega_sc.size()>0 ){ // PARALLEL_REGION + Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; + if( model_options(1) == 0 ){ + // Separable precision ... Option-1 + //Eigen::SparseMatrix Linv_cc = Gammainv_cc * ( I_cc - Rho_cc ); + //Eigen::SparseMatrix Q_cc = Linv_cc.transpose() * Linv_cc; + + // Separable precision ... Option-2 + // Only compute Vinv_kk if Gamma_kk is full rank + Eigen::SparseMatrix V_cc = Gamma_cc.transpose() * Gamma_cc; + matrix Vinv_cc = invertSparseMatrix( V_cc ); + Eigen::SparseMatrix Vinv2_cc = asSparseMatrix( Vinv_cc ); + Eigen::SparseMatrix Q_cc = IminusRho_cc.transpose() * Vinv2_cc * IminusRho_cc; + + // GMRF for SEM: separable variable-space + nll += SEPARABLE( GMRF(Q_cc), GMRF(Q_ss) )( omega_sc ); + // Including this line with Makevars below seems to cause a crash: + // PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) + // PKG_CXXFLAGS=$(SHLIB_OPENMP_CXXFLAGS) + }else{ + // Rank-deficient (projection) method + if( model_options(0) == 7 ){ + vector omega_s( omega_sc.rows() ); + for( int ci = 0; ci < omega_sc.cols(); ci++ ){ + omega_s = omega_sc.col(ci); + nll += NNGP( Type(1.0), range, omega_s, nngp_data ); + } + }else{ + nll += SEPARABLE( GMRF(I_cc), GMRF(Q_ss) )( omega_sc ); + } + + // Sparse inverse-product + //Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; + Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_cc; + inverseIminusRho_cc.compute(IminusRho_cc); + + // (I-Rho)^{-1} * Gamma * Epsilon + matrix omega2_cs = Gamma_cc * omega_sc.matrix().transpose(); + matrix omega3_cs = inverseIminusRho_cc.solve(omega2_cs); + omega_sc = omega3_cs.transpose(); + } + } + } + + return omega_sc; +} + +// distribution/projection for xi +template +Type xi_distribution( + vector model_options, + tmbutils::array xi_sl, + vector log_sigmaxi_l, + Eigen::SparseMatrix Q_ss, + Type range, + nngp_data_t nngp_data ){ + + Type nll = 0; + if( xi_sl.size() > 0 ){ + int n_l = xi_sl.cols(); + using namespace density; + if( model_options(0) == 7 ){ + vector xi_s( xi_sl.rows() ); + for( int l=0; l +tmbutils::array epsilon_distribution( + tmbutils::array epsilon_stc, + vector model_options, + Eigen::SparseMatrix Rho_hh, + Eigen::SparseMatrix Gamma_hh, + Eigen::SparseMatrix Gammainv_hh, + Eigen::SparseMatrix Q_ss, + Type range, + nngp_data_t nngp_data, + Type &nll ){ + + if( epsilon_stc.size() > 0 ){ + int n_s = epsilon_stc.dim(0); + int n_t = epsilon_stc.dim(1); + int n_c = epsilon_stc.dim(2); + int n_h = n_t * n_c; + using namespace density; + Eigen::SparseMatrix I_hh( n_h, n_h ); + I_hh.setIdentity(); + int h; + + //if( epsilon_stc.size()>0 ){ // PARALLEL_REGION + // Reshape for either model_options + tmbutils::array epsilon_hs( n_h, n_s ); + for( int s=0; s IminusRho_hh = I_hh - Rho_hh; + + if( model_options(1) == 0 ){ + // Separable precision ... Option-1 + //Eigen::SparseMatrix Linv_hh = Gammainv_hh * ( I_hh - Rho_hh ); + //Eigen::SparseMatrix Q_hh = Linv_hh.transpose() * Linv_hh; + + // Separable precision ... Option-2 + // Only compute Vinv_kk if Gamma_kk is full rank + Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; + matrix Vinv_hh = invertSparseMatrix( V_hh ); + Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); + Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; + + // GMRF for DSEM: non-separable time-variable, with separable space + nll += SEPARABLE( GMRF(Q_ss), GMRF(Q_hh) )( epsilon_hs ); + }else{ + // Rank-deficient (projection) method + if( model_options(0) == 7 ){ + vector epsilon_s( epsilon_hs.cols() ); + for( int hi = 0; hi < epsilon_hs.rows(); hi++ ){ + epsilon_s = epsilon_hs.matrix().row(hi); + nll += NNGP( Type(1.0), range, epsilon_s, nngp_data ); + } + }else{ + nll += SEPARABLE( GMRF(Q_ss), GMRF(I_hh) )( epsilon_hs ); + } + + // Sparse inverse-product + //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; + Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; + inverseIminusRho_hh.compute(IminusRho_hh); + + // (I-Rho)^{-1} * Gamma * Epsilon + matrix e2_hs = Gamma_hh * epsilon_hs.matrix(); + matrix e3_hs = inverseIminusRho_hh.solve(e2_hs); + + // Transformations + for( int s=0; s +tmbutils::array delta_distribution( + tmbutils::array delta_tc, + vector model_options, + Eigen::SparseMatrix Rho_hh, + Eigen::SparseMatrix Gamma_hh, + Eigen::SparseMatrix Gammainv_hh, + Type &nll ){ + + if( delta_tc.size() > 0 ){ + int n_t = delta_tc.dim(0); + int n_c = delta_tc.dim(1); + int n_h = n_t * n_c; + using namespace density; + Eigen::SparseMatrix I_hh( n_h, n_h ); + I_hh.setIdentity(); + int h; + + // Reshape for either model_options + tmbutils::array delta_h1( n_h, 1 ); + for( int t=0; t IminusRho_hh = I_hh - Rho_hh; + + if( model_options(1) == 0 ){ + Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; + matrix Vinv_hh = invertSparseMatrix( V_hh ); + Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); + Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; + + // GMRF for DSEM: non-separable time-variable, with separable space + nll += GMRF(Q_hh)( delta_h1 ); + }else{ + // Rank-deficient (projection) method + nll += GMRF(I_hh)( delta_h1 ); + + // Sparse inverse-product + //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; + Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; + inverseIminusRho_hh.compute(IminusRho_hh); + + // (I-Rho)^{-1} * Gamma * Epsilon + matrix e2_h1 = Gamma_hh * delta_h1.matrix(); + matrix e3_h1 = inverseIminusRho_hh.solve(e2_h1); + + // Transformations + for( int t=0; t +bool isNA(Type x){ + return R_IsNA(asDouble(x)); +} + +// Sparse array * matrix +// NAs in IVECTOR or IMATRIX get converted to -2147483648, so isNA doesn't work ... instead drop NAs from A prior to passing to TMB +template +vector multiply_epsilon( + matrix A, + vector weight, + tmbutils::array x, + int n_i ){ + + vector out( n_i ); + out.setZero(); + if( x.size() > 0 ){ + for( int z=0; z +vector multiply_omega( + matrix A, + vector weight, + tmbutils::array x, + int n_i ){ + + vector out( n_i ); + out.setZero(); + if( x.size() > 0 ){ + for( int z=0; z +vector multiply_xi( + Eigen::SparseMatrix A_is, + tmbutils::array xi_sl, + matrix W_il ){ + + vector out( W_il.rows() ); + out.setZero(); + if( xi_sl.size() > 0 ){ + matrix xi_il = A_is * xi_sl.matrix(); + for( int i=0; i +vector multiply_delta( + tmbutils::array delta_tc, + vector t_i, + vector c_i, + int n_i ){ + + vector delta_i( n_i ); + delta_i.setZero(); + if( delta_tc.size() > 0 ){ + for( int i=0; i +Type sign(Type x){ + return x / pow(pow(x,2),0.5); +} + +// dlnorm +template +Type dlnorm( + Type x, + Type meanlog, + Type sdlog, + int give_log=0){ + + //return 1/(sqrt(2*M_PI)*sd) * exp(-.5*pow((x-mean)/sd,2)); + Type logres = dnorm( log(x), meanlog, sdlog, true) - log(x); + if(give_log) return logres; else return exp(logres); +} + +// dlnorm +template +Type dbinom_custom( + Type x, + Type log_prob, + Type log_one_minus_prob, + Type size, + int give_log = 0 ){ + + // size choose x + Type logres = lgamma(size + 1.0) - lgamma(x + 1.0) - lgamma(size - x + 1.0); + // p^x * (1-p)^(size-x) + logres += x * log_prob + (size-x) * log_one_minus_prob; + if(give_log) return logres; else return exp(logres); +} + +// dlnorm +template +Type devresid_binom( + Type y, + Type weight, // weight = size + Type mu ){ + + Type y_weight = y * weight; + Type mu_weight = mu * weight; + Type p1, p2; + if(y_weight == 0){ + p1 = 0.0; + }else{ + p1 = y_weight * log(y_weight / mu_weight); + } + if( (weight - y_weight) == 0 ){ + p2 = 0.0; + }else{ + p2 = (weight - y_weight) * log( (weight - y_weight) / (weight - mu_weight) ); + } + Type devresid = sign(y - mu) * pow(2 * (p1 + p2), 0.5); + return devresid; +} + +// Deviance for the Tweedie +// https://en.wikipedia.org/wiki/Tweedie_distribution#Properties +template +Type devresid_tweedie( + Type y, + Type mu, + Type p ){ + + Type c1 = pow( y, 2.0-p ) / (1.0-p) / (2.0-p); + Type c2 = y * pow( mu, 1.0-p ) / (1.0-p); + Type c3 = pow( mu, 2.0-p ) / (2.0-p); + Type deviance = 2 * (c1 - c2 + c3 ); + Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); + return devresid; +} + +// Deviance for the student-T +// from chatGPT (experimental) ... converges on Gaussian as df -> Inf +template +Type devresid_student( + Type y, + Type mu, + Type sigma, + Type df ){ + + Type deviance = (df + 1.0) * log( 1.0 + pow(y-mu,2.0) / (df * sigma*sigma) ); + Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); + return devresid; +} + +// COPIED from sdmTMB.cpp in sdmTMB package on Nov. 14, 2025 +template +Type dstudent( + Type x, + Type mean, + Type sigma, + Type df, + int give_log = 0) { + + // from metRology::dt.scaled() + // dt((x - mean)/sd, df, ncp = ncp, log = TRUE) - log(sd) + Type logres = dt((x - mean) / sigma, df, true) - log(sigma); + if (give_log) + return logres; + else + return exp(logres); +} + +// Deviance for the Negative binomial +//template +//Type devresid_nbinom1( Type y, +// Type logmu, +// Type logtheta ){ +// +// // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu +// Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), log(y + Type(1e-10)) + logtheta, true ); +// Type logp2 = dnbinom_robust( y, logmu, logmu + logtheta, true ); +// Type deviance = 2 * (logp1 - logp2); +// Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); +// return devresid; +//} +template +Type devresid_nbinom2( + Type y, + Type logmu, + Type logtheta ){ + + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), Type(2.0) * log(y + Type(1e-10)) - logtheta, true ); + Type logp2 = dnbinom_robust( y, logmu, Type(2.0) * logmu - logtheta, true ); + Type deviance = 2 * (logp1 - logp2); + Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); + return devresid; +} + + +// distribution/projection for epsilon +// deviance = deviance1 + deviance2 +template +Type one_predictor_likelihood( + Type &y, + Type p, + Type size, + int link, + int family, + vector log_sigma_segment, + Type &nll, + Type &devresid, + objective_function* of ){ + + Type mu, logmu, log_one_minus_mu; + //Type devresid = 0; + + switch( link ){ + case identity_link: + mu = p; + logmu = log( p ); + log_one_minus_mu = log( Type(1.0) - mu ); + break; + case log_link: + mu = exp(p); + logmu = p; + log_one_minus_mu = log( Type(1.0) - mu ); + break; + case logit_link: + mu = invlogit(p); + //logmu = log(mu); + logmu = p - logspace_add( Type(0.0), p ); + //log_one_minus_mu = log( invlogit(-1 * p) ); + log_one_minus_mu = 0.0 - logspace_add( Type(0.0), p ); + break; + case cloglog_link: + mu = Type(1.0) - exp( -1 * exp(p) ); + logmu = logspace_sub( Type(0.0), -1.0 * exp(p) ); + log_one_minus_mu = -1.0 * exp(p); + break; + default: + error("Link not implemented."); + } + if( !R_IsNA(asDouble(y)) ){ + // Distribution + switch( family ){ + case gaussian_family: + nll = -1 * dnorm( y, mu, exp(log_sigma_segment(0)), true ); + devresid = y - mu; + if(isDouble::value && of->do_simulate){ + y = rnorm( mu, exp(log_sigma_segment(0)) ); + } + break; + case tweedie_family: + nll = -1 * dtweedie( y, mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); + devresid = devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); + if(isDouble::value && of->do_simulate){ + y = rtweedie( mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); + } + break; + case lognormal_family: + nll = -1 * dlnorm( y, logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); + devresid = log(y) - ( logmu - 0.5*exp(2.0*log_sigma_segment(0)) ); + if(isDouble::value && of->do_simulate){ + y = exp(rnorm( logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); + } + break; + case poisson_family: + nll = -1 * dpois( y, mu, true ); + devresid = sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); + if(isDouble::value && of->do_simulate){ + y = rpois( mu ); + } + break; + case binomial_family: + //if(y==0){ + // nll = -1 * log_one_minus_mu; + //}else{ + // nll = -1 * logmu; + //} + nll = -1 * dbinom_custom( y * size, logmu, log_one_minus_mu, size, true ); + if(isDouble::value && of->do_simulate){ + y = rbinom( size, mu ); + } + // TODO: Update deviance residual for Trials = size + //devresid = sign(y - mu) * pow(-2*((1-y)*log(1.0-mu) + y*log(mu)), 0.5); + devresid = devresid_binom( y, size, mu ); + break; + case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 + nll = -1 * dgamma( y, exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)), true ); + devresid = sign(y - mu) * pow(2 * ( (y-mu)/mu - log(y/mu) ), 0.5); + if(isDouble::value && of->do_simulate){ + y = rgamma( exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)) ); + } + break; + case nbinom1_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu + nll = -1 * dnbinom_robust( y, logmu, logmu + log_sigma_segment(0), true); + devresid = devresid_nbinom2( y, logmu, logmu - log_sigma_segment(0) ); // theta = mu / phi + if(isDouble::value && of->do_simulate){ + // rnbinom2( mu, var ) + y = rnbinom2( mu, mu * (Type(1.0) + exp(log_sigma_segment(0))) ); + } + break; + case nbinom2_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + nll = -1 * dnbinom_robust( y, logmu, Type(2.0) * logmu - log_sigma_segment(0), true); + devresid = devresid_nbinom2( y, logmu, log_sigma_segment(0) ); + if(isDouble::value && of->do_simulate){ + // rnbinom2( mu, var ) + y = rnbinom2( mu, mu * (Type(1.0) + mu / exp(log_sigma_segment(0))) ); + } + break; + case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + nll = -1 * dstudent( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); + devresid = devresid_student( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)) ); + if(isDouble::value && of->do_simulate){ + y = mu + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); + } + break; + default: + error("Distribution not implemented."); + } + } + + return mu; +} + +// distribution/projection for epsilon +template +Type two_predictor_likelihood( + Type &y, + Type p1, + Type p2, + Type size, + vector link, + vector family, + vector log_sigma_segment, + int poislink, + Type &nll, + Type &dev, + objective_function* of ){ + + Type mu1, logmu1, mu2, logmu2, log_one_minus_mu1; + + // First link + if( poislink==0 ){ + mu1 = invlogit( p1 ); + logmu1 = log( mu1 ); + log_one_minus_mu1 = log( Type(1.0) - mu1 ); + // second link + switch( link(1) ){ + case identity_link: + mu2 = p2; + logmu2 = log( p2 ); + break; + case log_link: + mu2 = exp(p2); + logmu2 = p2; + break; + default: + error("Link not implemented."); + } + }else{ + mu1 = Type(1.0) - exp( -1.0*exp(p1) ); + logmu1 = logspace_sub( Type(0.0), -1*exp(p1) ); + log_one_minus_mu1 = -1.0*exp(p1); + mu2 = exp( p1 + p2 ) / mu1; + logmu2 = p1 + p2 - logmu1; + } + if( !R_IsNA(asDouble(y)) ){ + // Distribution + if(isDouble::value && of->do_simulate){ + y = rbinom( Type(1), mu1 ); + } + if( y == 0 ){ + nll = -1 * log_one_minus_mu1; + dev = -2 * log_one_minus_mu1; + } + if( y>0 ){ // Not if-else so y>0 triggered when simulating y>0 + nll = -1 * logmu1; + dev = -2 * logmu1; + //deviance1_i(i) = -2 * log_mu1(i); + switch( family(1) ){ + case gaussian_family: + nll -= dnorm( y, mu2, exp(log_sigma_segment(0)), true ); + dev += pow(y - mu2, 2.0); + if(isDouble::value && of->do_simulate){ + y = rnorm( mu2, exp(log_sigma_segment(0)) ); + } + break; + //case tweedie_family: + // nll -= dtweedie( y, mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); + // devresid += devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); + // if(isDouble::value && of->do_simulate){ + // y = rtweedie( mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); + // } + // break; + case lognormal_family: + nll -= dlnorm( y, logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); + dev += pow( log(y) - (logmu2 - 0.5*exp(2.0*log_sigma_segment(0))), 2.0 ); + if(isDouble::value && of->do_simulate){ + y = exp(rnorm( logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); + } + break; + //case poisson_family: + // nll -= dpois( y, mu2, true ); + // devresid += sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); + // if(isDouble::value && of->do_simulate){ + // y = rpois( mu2 ); + // } + // break; + // case 4: // Bernoulli + case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 + nll -= dgamma( y, exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)), true ); + dev += 2 * ( (y-mu2)/mu2 - log(y/mu2) ); + if(isDouble::value && of->do_simulate){ + y = rgamma( exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)) ); + } + break; + case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + nll -= dstudent( y, mu2, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); + //dev = NAN; + if(isDouble::value && of->do_simulate){ + y = mu2 + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); + } + break; + default: + error("Distribution not implemented."); + } + } + } + + return mu1 * mu2; +} diff --git a/src/tinyVAST.cpp b/src/tinyVAST.cpp index 40035546..8b58db30 100644 --- a/src/tinyVAST.cpp +++ b/src/tinyVAST.cpp @@ -1,6 +1,6 @@ #define TMB_LIB_INIT R_init_tinyVAST #include //Links in the TMB libraries -//#include "utils.h" +#include "utils.h" // Coding principles // 1. Don't telescope model features using `map` (which is bug-prone), but @@ -12,1135 +12,13 @@ // 4. spatial_graph always has dimension 1+, but DSEM functionality is removed if // sem=NULL such that nrow(ram_spacetime_term)=0 -// Note that moving functions to utils.hpp resulted in Internal Compiler Error (ICE) - -enum valid_family { - gaussian_family = 0, - tweedie_family = 1, - lognormal_family = 2, - poisson_family = 3, - bernoulli_family = 4, - binomial_family = 4, - gamma_family = 5, - nbinom1_family = 6, - nbinom2_family = 7, - student_family = 8 -}; - -enum valid_link { - identity_link = 0, - log_link = 1, - logit_link = 2, - cloglog_link = 3 -}; - -// Old algorithmic constructor for tail-down exponential stream network, copied from VAST -//template -//Eigen::SparseMatrix Q_network( Type log_theta, -// int n_s, -// vector parent_s, -// vector child_s, -// vector dist_s ){ -// -// Eigen::SparseMatrix Q( n_s, n_s ); -// Type theta = exp( log_theta ); -// for(int s=0; s -Eigen::SparseMatrix vectorsToSparseMatrix( - vector i, - vector j, - vector x, - int N ){ - - // https://eigen.tuxfamily.org/dox/classEigen_1_1SparseMatrix.html#title35 - using namespace Eigen; - std::vector> tripletList; - for( int index = 0; index < i.size(); index ++ ){ - tripletList.push_back(Triplet( i[index], j[index], x[index]) ); - } - SparseMatrix M( N, N ); - M.setFromTriplets( tripletList.begin(), tripletList.end() ); - - //Eigen::SparseMatrix M( N, N ); - //for(int index=0; index -struct spde_covariates_t{ - int n_s; - //int n_tri; - vector Tri_Area; - matrix E0; - matrix E1; - matrix E2; - matrix V_zk; - matrix TV; - Eigen::SparseMatrix G0; - Eigen::SparseMatrix G0_inv; - - // Define output - spde_covariates_t(SEXP x){ /* x = List passed from R */ - n_s = CppAD::Integer(asVector(getListElement(x,"n_s"))[0]); - //n_tri = CppAD::Integer(asVector(getListElement(x,"n_tri"))[0]); - Tri_Area = asVector(getListElement(x,"Tri_Area")); - E0 = asMatrix(getListElement(x,"E0")); - E1 = asMatrix(getListElement(x,"E1")); - E2 = asMatrix(getListElement(x,"E2")); - V_zk = asMatrix(getListElement(x,"V_zk")); - TV = asMatrix(getListElement(x,"TV")); - G0 = tmbutils::asSparseMatrix(getListElement(x,"G0")); - G0_inv = tmbutils::asSparseMatrix(getListElement(x,"G0_inv")); - } -}; -// make stiffness G1 from covariates in columns of E0, E1, E2 -template -Eigen::SparseMatrix G_spde_covariates( - spde_covariates_t spde, - matrix H_jj, - //matrix V_zk, - vector triangle_k ){ - - // TO ADD EDGE COVARIATES: - // 0. add n_e = edge0_tj.rows() - // 1. Add TE, where dim(TE) = n_t \times 3, listing the edge-number for each triangle-edge of n_e edges - // 2. Add A_ek design matrix, where dim(A_ek) = n_e \times n_k (edge-covariates) - - // Extract objects - vector area_t = spde.Tri_Area; - matrix edge0_tj = spde.E0; - matrix edge1_tj = spde.E1; - matrix edge2_tj = spde.E2; - matrix s_tv = spde.TV; // dim = n_t \times n_v - matrix triangle_t1 = spde.V_zk * triangle_k.matrix(); - int n_s = spde.n_s; - int n_t = s_tv.rows(); - int n_v = s_tv.cols(); // number of vertices per triangle - int n_j = edge0_tj.cols(); // number of covariates (default = 2) - - // Output - Eigen::SparseMatrix G_ss(n_s, n_s); - - // Objects to assemble triangle contributions - matrix edges_vj( n_v, n_j ); - matrix Gt_vv( n_v, n_v ); - - // Calculate adjugate of H - //matrix adjH_jj = H_jj.inverse() * H_jj.determinant(); // CAUSES CRASH - matrix adjH_jj = H_jj.adjoint(); - - // Assemble stiffness G - for( int t=0; t Gt_ss( n_s, n_s ); - for(int v1 = 0; v1 < 3; v1++ ){ - for(int v2 = 0; v2 < 3; v2++ ){ - Gt_ss.coeffRef( s_tv(t,v1), s_tv(t,v2) ) = Gt_vv(v1,v2); - }} - G_ss += Gt_ss / ( 4.0 * area_t(t) ); - } - return G_ss; -} - -// Q_SAR( log_kappa, H, n_s, i_z, j_z, delta_z2 ) -// Using a SAR (not standardized) to approximate spatial function -template -Eigen::SparseMatrix Q_SAR( - //Type rho, - Type kappa, - matrix H, - int n_s, - vector i_z, - vector j_z, - matrix delta_z2 ){ - - //Type max_dist = delta_z2.cwiseAbs().maxCoeff(); - - //d_z = sqrt((delta_z2 %*% H)^2 %*% matrix(1,nrow=2,ncol=1))[,1] - matrix deltaprime_z2 = (delta_z2 * H); // / max_dist; - vector dist_z( i_z.size() ); - for( int z = 0; z < i_z.size(); z++ ){ - dist_z(z) = pow( pow(deltaprime_z2(z,0),2.0) + pow(deltaprime_z2(z,1),2.0), 0.5 ); - } - vector weight_z = exp( -kappa * dist_z ); - - // Make weight matrix - Eigen::SparseMatrix W_ss = vectorsToSparseMatrix( - i_z, j_z, weight_z, n_s - ); - - // Row-standardize W_ss - // Does *not* make sense when using anisotropy - //for( int row = 0; row < n_s; row ++ ){ - // Type rowsum = W_ss.row(row).sum(); - // W_ss.row(row) /= rowsum; - //} - - // Assemble - Eigen::SparseMatrix I_ss( n_s, n_s ); - I_ss.setIdentity(); - Eigen::SparseMatrix IminusP_ss = I_ss - W_ss; - Eigen::SparseMatrix Q = IminusP_ss.transpose() * IminusP_ss; - return Q; -} - -// New matrix-notation precision constructor for tail-down exponential stream network -template -Eigen::SparseMatrix Q_network2( - Type log_theta, - int n_s, - vector parent_s, - vector child_s, - vector dist_s ){ - - // Compute vectors - Type theta = exp(log_theta); - vector v1_s = exp(-theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); - vector v2_s = exp(-2.0 * theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); - - // Make components - Eigen::SparseMatrix P_ss = vectorsToSparseMatrix( child_s, - parent_s, - v1_s, - n_s ); - Eigen::SparseMatrix D_ss = vectorsToSparseMatrix( child_s, - child_s, - v2_s, - n_s ); - Eigen::SparseMatrix invD_ss( n_s, n_s ); - for( int s=0; s DminusP_ss = D_ss - P_ss; - Eigen::SparseMatrix Q = DminusP_ss.transpose() * invD_ss * DminusP_ss; - return Q; -} - -// Functions to evaluate density for nearest-neighbors Gaussian process -template -vector covariance_function(vector d, Type sigma2, Type inv_range) { - return ((-d.array() * inv_range).exp() * sigma2).matrix(); -} -template -matrix covariance_function(matrix d, Type sigma2, Type inv_range) { - return ((-d.array() * inv_range).exp() * sigma2).matrix(); -} -/** \brief Object containing all data elements of an NNGP */ -template -struct nngp_data_t{ - vector nn_index_flat; - vector nn_len; - vector dist_to_nn_flat; - vector dist_within_nn_flat; - vector gp_order; - - // Define output - nngp_data_t(SEXP x){ /* x = List passed from R */ - nn_index_flat = asVector(getListElement(x,"nn_index_flat")); - nn_len = asVector(getListElement(x,"nn_len")); - dist_to_nn_flat = asVector(getListElement(x,"dist_to_nn_flat")); - dist_within_nn_flat = asVector(getListElement(x,"dist_within_nn_flat")); - gp_order = asVector(getListElement(x,"gp_order")); - } -}; -// Density function .. sigma2 fixed at 1.0 -template -Type NNGP( - Type sigma2, - Type range, - vector field_s, - // Data - nngp_data_t nngp_data ){ - - // Using original order and ordered_structure, by calling gp_order(i) and gp_order(nn_ids), because: - // 1. using original version in new order is very slow! presumably the order is terrible for the inner Hessian - // 2. using re-ordered version of field is confusing for users - Type nll = 0.0; - Type inv_range = 1.0 / range; // Multiplication is faster than division - vector nn_index_flat = nngp_data.nn_index_flat; - //vector nn_start = nngp_data.nn_start; - vector nn_len = nngp_data.nn_len; - vector dist_to_nn_flat = nngp_data.dist_to_nn_flat; - vector dist_within_nn_flat = nngp_data.dist_within_nn_flat; - vector gp_order = nngp_data.gp_order; - int n = field_s.size(); - - int pos_mat = 0; - int pos_vec = 0; - for( int i = 0; i < n; i++ ){ - int k = nn_len(i); - - // No neighbors - if(k == 0){ - nll -= dnorm( field_s(gp_order(i)), Type(0.0), sqrt(sigma2), true ); - }else{ - // Extract neighbor indices and distance to neighbors - vector nn_ids(k); - vector dist_iN(k); - for (int j = 0; j < k; j++) { - nn_ids(j) = nn_index_flat(pos_vec); - dist_iN(j) = dist_to_nn_flat(pos_vec); - pos_vec++; - } - - // Extract within-neighbor distance matrix (k x k) ... - matrix dist_NN(k, k); - for (int r = 0; r < k; r++) { - for (int c = 0; c < k; c++) { - dist_NN(r, c) = dist_within_nn_flat(pos_mat); - pos_mat++; - } - } - - // Covariances - matrix Sigma_NN = covariance_function(dist_NN, sigma2, inv_range); - vector Sigma_iN = covariance_function(dist_iN, sigma2, inv_range); - - // Solve - //vector a_i = solve(Sigma_NN, Sigma_iN); - //vector a_i = Sigma_NN.ldlt().solve( Sigma_iN.matrix() ); - //Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > invSigma_NN; - //invSigma_NN.compute(Sigma_NN); - //vector a_i = invSigma_NN.solve(Sigma_iN); - matrix Sigma_NN_inv = atomic::matinv(Sigma_NN); - vector a_i = Sigma_NN_inv * Sigma_iN; - - // Residual variance - Type resid_var = sigma2 - (a_i * Sigma_iN).sum(); // + 1e-12; - - // Conditional mean - Type cond_mean = 0.0; - for (int j = 0; j < k; j++) { - cond_mean += a_i(j) * field_s(gp_order(nn_ids(j))); - } - - // Likelihood - nll -= dnorm( field_s(gp_order(i)), cond_mean, sqrt(resid_var), true ); - } - } - return nll; -} - -// Function to calculate RAM matrices -template -Eigen::SparseMatrix make_ram( - matrix ram, - vector ram_start, - vector beta_z, - int n_c, - int what ){ - - Eigen::SparseMatrix out_cc(n_c, n_c); - out_cc.setZero(); - Type tmp; - - for(int r=0; r=1){ - tmp = beta_z(ram(r,3)-1); - }else{ - tmp = ram_start(r); - } - // Rho_cc - if( (ram(r,0)==1) && (what==0) ){ - out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; - } - // Gammainv_cc - if( (ram(r,0)==2) && (what==1) ){ - out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = 1 / tmp; - } - // Gamma_cc - if( (ram(r,0)==2) && (what==2) ){ - out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; - } - } - - return out_cc; -} - -// distribution/projection for gamma -// Based on: -// https://github.com/meganferg/FergusonEtal_20250125_EBS_Beluga_DSM/blob/main/src/te_tw_DSM.cpp#L85C9-L85C40 (Megan Ferguson) -template -Type gamma_distribution( - vector gamma_k, - vector Sdims, - vector Sblock, - Eigen::SparseMatrix S_kk, - vector log_lambda ){ - - using namespace density; - Type nll = 0.0; - int start_gamma = 0; // Counter for gamma - int start_k = 0; // counter for columns of S_kk - int index_lambda = 0; - for(int z=0; z gamma_segment = gamma_k.segment(start_gamma, ngamma_z); - start_gamma += ngamma_z; - - // s() splines - if( Sblock(z) == 1 ){ - // Recover S_block - Eigen::SparseMatrix S_block = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i - - /// Quadratic-form GRMF - // GMRF(Q).Quadform(x) caused a problem calculating the log-determinant unnecessarily, resulting in valgrind error - //nll -= Type(0.5)*Type(m_z)*log_lambda(z) - Type(0.5)*exp(log_lambda(z))*GMRF(S_block).Quadform(gamma_segment); - nll -= Type(0.5)*Type(ngamma_z)*log_lambda(index_lambda) - Type(0.5) * exp(log_lambda(index_lambda)) * - (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); - - start_k += ngamma_z; - index_lambda += 1; - } - - // te() / ti() / t2() splines - if( Sblock(z) >= 2 ){ - // Recover S_block ... Eigen::SparseMatrix appears to initialize as empty so no .setZero() equivalent needed - Eigen::SparseMatrix S_block( ngamma_z, ngamma_z ); - for( int block=0; block < Sblock(z); block ++ ){ - Eigen::SparseMatrix S_tmp = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i - S_block += exp(log_lambda(index_lambda)) * S_tmp; - start_k += ngamma_z; - index_lambda++; - } - - /// Quadratic-form GRMF - nll -= 0.5*(atomic::logdet(matrix(S_block))) - 0.5 * - (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); - } - } - return( nll ); -} - -// distribution/projection for omega -template -tmbutils::array omega_distribution( - tmbutils::array omega_sc, - vector model_options, - Eigen::SparseMatrix Rho_cc, - Eigen::SparseMatrix Gamma_cc, - Eigen::SparseMatrix Gammainv_cc, - Eigen::SparseMatrix Q_ss, - Type range, - nngp_data_t nngp_data, - Type &nll ){ - - if( omega_sc.size() > 0 ){ - int n_c = omega_sc.dim(1); - using namespace density; - Eigen::SparseMatrix I_cc( n_c, n_c ); - I_cc.setIdentity(); - if( omega_sc.size()>0 ){ // PARALLEL_REGION - Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; - if( model_options(1) == 0 ){ - // Separable precision ... Option-1 - //Eigen::SparseMatrix Linv_cc = Gammainv_cc * ( I_cc - Rho_cc ); - //Eigen::SparseMatrix Q_cc = Linv_cc.transpose() * Linv_cc; - - // Separable precision ... Option-2 - // Only compute Vinv_kk if Gamma_kk is full rank - Eigen::SparseMatrix V_cc = Gamma_cc.transpose() * Gamma_cc; - matrix Vinv_cc = invertSparseMatrix( V_cc ); - Eigen::SparseMatrix Vinv2_cc = asSparseMatrix( Vinv_cc ); - Eigen::SparseMatrix Q_cc = IminusRho_cc.transpose() * Vinv2_cc * IminusRho_cc; - - // GMRF for SEM: separable variable-space - nll += SEPARABLE( GMRF(Q_cc), GMRF(Q_ss) )( omega_sc ); - // Including this line with Makevars below seems to cause a crash: - // PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) - // PKG_CXXFLAGS=$(SHLIB_OPENMP_CXXFLAGS) - }else{ - // Rank-deficient (projection) method - if( model_options(0) == 7 ){ - vector omega_s( omega_sc.rows() ); - for( int ci = 0; ci < omega_sc.cols(); ci++ ){ - omega_s = omega_sc.col(ci); - nll += NNGP( Type(1.0), range, omega_s, nngp_data ); - } - }else{ - nll += SEPARABLE( GMRF(I_cc), GMRF(Q_ss) )( omega_sc ); - } - - // Sparse inverse-product - //Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; - Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_cc; - inverseIminusRho_cc.compute(IminusRho_cc); - - // (I-Rho)^{-1} * Gamma * Epsilon - matrix omega2_cs = Gamma_cc * omega_sc.matrix().transpose(); - matrix omega3_cs = inverseIminusRho_cc.solve(omega2_cs); - omega_sc = omega3_cs.transpose(); - } - } - } - - return omega_sc; -} - -// distribution/projection for xi -template -Type xi_distribution( - vector model_options, - tmbutils::array xi_sl, - vector log_sigmaxi_l, - Eigen::SparseMatrix Q_ss, - Type range, - nngp_data_t nngp_data ){ - - Type nll = 0; - if( xi_sl.size() > 0 ){ - int n_l = xi_sl.cols(); - using namespace density; - if( model_options(0) == 7 ){ - vector xi_s( xi_sl.rows() ); - for( int l=0; l -tmbutils::array epsilon_distribution( - tmbutils::array epsilon_stc, - vector model_options, - Eigen::SparseMatrix Rho_hh, - Eigen::SparseMatrix Gamma_hh, - Eigen::SparseMatrix Gammainv_hh, - Eigen::SparseMatrix Q_ss, - Type range, - nngp_data_t nngp_data, - Type &nll ){ - - if( epsilon_stc.size() > 0 ){ - int n_s = epsilon_stc.dim(0); - int n_t = epsilon_stc.dim(1); - int n_c = epsilon_stc.dim(2); - int n_h = n_t * n_c; - using namespace density; - Eigen::SparseMatrix I_hh( n_h, n_h ); - I_hh.setIdentity(); - int h; - - //if( epsilon_stc.size()>0 ){ // PARALLEL_REGION - // Reshape for either model_options - tmbutils::array epsilon_hs( n_h, n_s ); - for( int s=0; s IminusRho_hh = I_hh - Rho_hh; - - if( model_options(1) == 0 ){ - // Separable precision ... Option-1 - //Eigen::SparseMatrix Linv_hh = Gammainv_hh * ( I_hh - Rho_hh ); - //Eigen::SparseMatrix Q_hh = Linv_hh.transpose() * Linv_hh; - - // Separable precision ... Option-2 - // Only compute Vinv_kk if Gamma_kk is full rank - Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; - matrix Vinv_hh = invertSparseMatrix( V_hh ); - Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); - Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; - - // GMRF for DSEM: non-separable time-variable, with separable space - nll += SEPARABLE( GMRF(Q_ss), GMRF(Q_hh) )( epsilon_hs ); - }else{ - // Rank-deficient (projection) method - if( model_options(0) == 7 ){ - vector epsilon_s( epsilon_hs.cols() ); - for( int hi = 0; hi < epsilon_hs.rows(); hi++ ){ - epsilon_s = epsilon_hs.matrix().row(hi); - nll += NNGP( Type(1.0), range, epsilon_s, nngp_data ); - } - }else{ - nll += SEPARABLE( GMRF(Q_ss), GMRF(I_hh) )( epsilon_hs ); - } - - // Sparse inverse-product - //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; - Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; - inverseIminusRho_hh.compute(IminusRho_hh); - - // (I-Rho)^{-1} * Gamma * Epsilon - matrix e2_hs = Gamma_hh * epsilon_hs.matrix(); - matrix e3_hs = inverseIminusRho_hh.solve(e2_hs); - - // Transformations - for( int s=0; s -tmbutils::array delta_distribution( - tmbutils::array delta_tc, - vector model_options, - Eigen::SparseMatrix Rho_hh, - Eigen::SparseMatrix Gamma_hh, - Eigen::SparseMatrix Gammainv_hh, - Type &nll ){ - - if( delta_tc.size() > 0 ){ - int n_t = delta_tc.dim(0); - int n_c = delta_tc.dim(1); - int n_h = n_t * n_c; - using namespace density; - Eigen::SparseMatrix I_hh( n_h, n_h ); - I_hh.setIdentity(); - int h; - - // Reshape for either model_options - tmbutils::array delta_h1( n_h, 1 ); - for( int t=0; t IminusRho_hh = I_hh - Rho_hh; - - if( model_options(1) == 0 ){ - Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; - matrix Vinv_hh = invertSparseMatrix( V_hh ); - Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); - Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; - - // GMRF for DSEM: non-separable time-variable, with separable space - nll += GMRF(Q_hh)( delta_h1 ); - }else{ - // Rank-deficient (projection) method - nll += GMRF(I_hh)( delta_h1 ); - - // Sparse inverse-product - //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; - Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; - inverseIminusRho_hh.compute(IminusRho_hh); - - // (I-Rho)^{-1} * Gamma * Epsilon - matrix e2_h1 = Gamma_hh * delta_h1.matrix(); - matrix e3_h1 = inverseIminusRho_hh.solve(e2_h1); - - // Transformations - for( int t=0; t -bool isNA(Type x){ - return R_IsNA(asDouble(x)); -} - -// Sparse array * matrix -// NAs in IVECTOR or IMATRIX get converted to -2147483648, so isNA doesn't work ... instead drop NAs from A prior to passing to TMB -template -vector multiply_epsilon( - matrix A, - vector weight, - tmbutils::array x, - int n_i ){ - - vector out( n_i ); - out.setZero(); - if( x.size() > 0 ){ - for( int z=0; z -vector multiply_omega( - matrix A, - vector weight, - tmbutils::array x, - int n_i ){ - - vector out( n_i ); - out.setZero(); - if( x.size() > 0 ){ - for( int z=0; z -vector multiply_xi( - Eigen::SparseMatrix A_is, - tmbutils::array xi_sl, - matrix W_il ){ - - vector out( W_il.rows() ); - out.setZero(); - if( xi_sl.size() > 0 ){ - matrix xi_il = A_is * xi_sl.matrix(); - for( int i=0; i -vector multiply_delta( - tmbutils::array delta_tc, - vector t_i, - vector c_i, - int n_i ){ - - vector delta_i( n_i ); - delta_i.setZero(); - if( delta_tc.size() > 0 ){ - for( int i=0; i -Type sign(Type x){ - return x / pow(pow(x,2),0.5); -} - -// dlnorm -template -Type dlnorm( - Type x, - Type meanlog, - Type sdlog, - int give_log=0){ - - //return 1/(sqrt(2*M_PI)*sd) * exp(-.5*pow((x-mean)/sd,2)); - Type logres = dnorm( log(x), meanlog, sdlog, true) - log(x); - if(give_log) return logres; else return exp(logres); -} - -// dlnorm -template -Type dbinom_custom( - Type x, - Type log_prob, - Type log_one_minus_prob, - Type size, - int give_log = 0 ){ - - // size choose x - Type logres = lgamma(size + 1.0) - lgamma(x + 1.0) - lgamma(size - x + 1.0); - // p^x * (1-p)^(size-x) - logres += x * log_prob + (size-x) * log_one_minus_prob; - if(give_log) return logres; else return exp(logres); -} - -// dlnorm -template -Type devresid_binom( - Type y, - Type weight, // weight = size - Type mu ){ - - Type y_weight = y * weight; - Type mu_weight = mu * weight; - Type p1, p2; - if(y_weight == 0){ - p1 = 0.0; - }else{ - p1 = y_weight * log(y_weight / mu_weight); - } - if( (weight - y_weight) == 0 ){ - p2 = 0.0; - }else{ - p2 = (weight - y_weight) * log( (weight - y_weight) / (weight - mu_weight) ); - } - Type devresid = sign(y - mu) * pow(2 * (p1 + p2), 0.5); - return devresid; -} - -// Deviance for the Tweedie -// https://en.wikipedia.org/wiki/Tweedie_distribution#Properties -template -Type devresid_tweedie( - Type y, - Type mu, - Type p ){ - - Type c1 = pow( y, 2.0-p ) / (1.0-p) / (2.0-p); - Type c2 = y * pow( mu, 1.0-p ) / (1.0-p); - Type c3 = pow( mu, 2.0-p ) / (2.0-p); - Type deviance = 2 * (c1 - c2 + c3 ); - Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); - return devresid; -} - -// Deviance for the student-T -// from chatGPT (experimental) ... converges on Gaussian as df -> Inf -template -Type devresid_student( - Type y, - Type mu, - Type sigma, - Type df ){ - - Type deviance = (df + 1.0) * log( 1.0 + pow(y-mu,2.0) / (df * sigma*sigma) ); - Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); - return devresid; -} - -// COPIED from sdmTMB.cpp in sdmTMB package on Nov. 14, 2025 -template -Type dstudent( - Type x, - Type mean, - Type sigma, - Type df, - int give_log = 0) { - - // from metRology::dt.scaled() - // dt((x - mean)/sd, df, ncp = ncp, log = TRUE) - log(sd) - Type logres = dt((x - mean) / sigma, df, true) - log(sigma); - if (give_log) - return logres; - else - return exp(logres); -} - -// Deviance for the Negative binomial -//template -//Type devresid_nbinom1( Type y, -// Type logmu, -// Type logtheta ){ -// -// // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu -// Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), log(y + Type(1e-10)) + logtheta, true ); -// Type logp2 = dnbinom_robust( y, logmu, logmu + logtheta, true ); -// Type deviance = 2 * (logp1 - logp2); -// Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); -// return devresid; -//} -template -Type devresid_nbinom2( - Type y, - Type logmu, - Type logtheta ){ - - // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), Type(2.0) * log(y + Type(1e-10)) - logtheta, true ); - Type logp2 = dnbinom_robust( y, logmu, Type(2.0) * logmu - logtheta, true ); - Type deviance = 2 * (logp1 - logp2); - Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); - return devresid; -} - - -// distribution/projection for epsilon -// deviance = deviance1 + deviance2 -template -Type one_predictor_likelihood( - Type &y, - Type p, - Type size, - int link, - int family, - vector log_sigma_segment, - Type &nll, - Type &devresid, - objective_function* of ){ - - Type mu, logmu, log_one_minus_mu; - //Type devresid = 0; - - switch( link ){ - case identity_link: - mu = p; - logmu = log( p ); - log_one_minus_mu = log( Type(1.0) - mu ); - break; - case log_link: - mu = exp(p); - logmu = p; - log_one_minus_mu = log( Type(1.0) - mu ); - break; - case logit_link: - mu = invlogit(p); - //logmu = log(mu); - logmu = p - logspace_add( Type(0.0), p ); - //log_one_minus_mu = log( invlogit(-1 * p) ); - log_one_minus_mu = 0.0 - logspace_add( Type(0.0), p ); - break; - case cloglog_link: - mu = Type(1.0) - exp( -1 * exp(p) ); - logmu = logspace_sub( Type(0.0), -1.0 * exp(p) ); - log_one_minus_mu = -1.0 * exp(p); - break; - default: - error("Link not implemented."); - } - if( !R_IsNA(asDouble(y)) ){ - // Distribution - switch( family ){ - case gaussian_family: - nll = -1 * dnorm( y, mu, exp(log_sigma_segment(0)), true ); - devresid = y - mu; - if(isDouble::value && of->do_simulate){ - y = rnorm( mu, exp(log_sigma_segment(0)) ); - } - break; - case tweedie_family: - nll = -1 * dtweedie( y, mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); - devresid = devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); - if(isDouble::value && of->do_simulate){ - y = rtweedie( mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); - } - break; - case lognormal_family: - nll = -1 * dlnorm( y, logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); - devresid = log(y) - ( logmu - 0.5*exp(2.0*log_sigma_segment(0)) ); - if(isDouble::value && of->do_simulate){ - y = exp(rnorm( logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); - } - break; - case poisson_family: - nll = -1 * dpois( y, mu, true ); - devresid = sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); - if(isDouble::value && of->do_simulate){ - y = rpois( mu ); - } - break; - case binomial_family: - //if(y==0){ - // nll = -1 * log_one_minus_mu; - //}else{ - // nll = -1 * logmu; - //} - nll = -1 * dbinom_custom( y * size, logmu, log_one_minus_mu, size, true ); - if(isDouble::value && of->do_simulate){ - y = rbinom( size, mu ); - } - // TODO: Update deviance residual for Trials = size - //devresid = sign(y - mu) * pow(-2*((1-y)*log(1.0-mu) + y*log(mu)), 0.5); - devresid = devresid_binom( y, size, mu ); - break; - case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 - nll = -1 * dgamma( y, exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)), true ); - devresid = sign(y - mu) * pow(2 * ( (y-mu)/mu - log(y/mu) ), 0.5); - if(isDouble::value && of->do_simulate){ - y = rgamma( exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)) ); - } - break; - case nbinom1_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) - // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu - nll = -1 * dnbinom_robust( y, logmu, logmu + log_sigma_segment(0), true); - devresid = devresid_nbinom2( y, logmu, logmu - log_sigma_segment(0) ); // theta = mu / phi - if(isDouble::value && of->do_simulate){ - // rnbinom2( mu, var ) - y = rnbinom2( mu, mu * (Type(1.0) + exp(log_sigma_segment(0))) ); - } - break; - case nbinom2_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) - // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - nll = -1 * dnbinom_robust( y, logmu, Type(2.0) * logmu - log_sigma_segment(0), true); - devresid = devresid_nbinom2( y, logmu, log_sigma_segment(0) ); - if(isDouble::value && of->do_simulate){ - // rnbinom2( mu, var ) - y = rnbinom2( mu, mu * (Type(1.0) + mu / exp(log_sigma_segment(0))) ); - } - break; - case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) - // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - nll = -1 * dstudent( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); - devresid = devresid_student( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)) ); - if(isDouble::value && of->do_simulate){ - y = mu + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); - } - break; - default: - error("Distribution not implemented."); - } - } - - return mu; -} - -// distribution/projection for epsilon -template -Type two_predictor_likelihood( - Type &y, - Type p1, - Type p2, - Type size, - vector link, - vector family, - vector log_sigma_segment, - int poislink, - Type &nll, - Type &dev, - objective_function* of ){ - - Type mu1, logmu1, mu2, logmu2, log_one_minus_mu1; - - // First link - if( poislink==0 ){ - mu1 = invlogit( p1 ); - logmu1 = log( mu1 ); - log_one_minus_mu1 = log( Type(1.0) - mu1 ); - // second link - switch( link(1) ){ - case identity_link: - mu2 = p2; - logmu2 = log( p2 ); - break; - case log_link: - mu2 = exp(p2); - logmu2 = p2; - break; - default: - error("Link not implemented."); - } - }else{ - mu1 = Type(1.0) - exp( -1.0*exp(p1) ); - logmu1 = logspace_sub( Type(0.0), -1*exp(p1) ); - log_one_minus_mu1 = -1.0*exp(p1); - mu2 = exp( p1 + p2 ) / mu1; - logmu2 = p1 + p2 - logmu1; - } - if( !R_IsNA(asDouble(y)) ){ - // Distribution - if(isDouble::value && of->do_simulate){ - y = rbinom( Type(1), mu1 ); - } - if( y == 0 ){ - nll = -1 * log_one_minus_mu1; - dev = -2 * log_one_minus_mu1; - } - if( y>0 ){ // Not if-else so y>0 triggered when simulating y>0 - nll = -1 * logmu1; - dev = -2 * logmu1; - //deviance1_i(i) = -2 * log_mu1(i); - switch( family(1) ){ - case gaussian_family: - nll -= dnorm( y, mu2, exp(log_sigma_segment(0)), true ); - dev += pow(y - mu2, 2.0); - if(isDouble::value && of->do_simulate){ - y = rnorm( mu2, exp(log_sigma_segment(0)) ); - } - break; - //case tweedie_family: - // nll -= dtweedie( y, mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); - // devresid += devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); - // if(isDouble::value && of->do_simulate){ - // y = rtweedie( mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); - // } - // break; - case lognormal_family: - nll -= dlnorm( y, logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); - dev += pow( log(y) - (logmu2 - 0.5*exp(2.0*log_sigma_segment(0))), 2.0 ); - if(isDouble::value && of->do_simulate){ - y = exp(rnorm( logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); - } - break; - //case poisson_family: - // nll -= dpois( y, mu2, true ); - // devresid += sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); - // if(isDouble::value && of->do_simulate){ - // y = rpois( mu2 ); - // } - // break; - // case 4: // Bernoulli - case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 - nll -= dgamma( y, exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)), true ); - dev += 2 * ( (y-mu2)/mu2 - log(y/mu2) ); - if(isDouble::value && of->do_simulate){ - y = rgamma( exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)) ); - } - break; - case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) - // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - nll -= dstudent( y, mu2, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); - //dev = NAN; - if(isDouble::value && of->do_simulate){ - y = mu2 + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); - } - break; - default: - error("Distribution not implemented."); - } - } - } - - return mu1 * mu2; -} template Type objective_function::operator() (){ //using namespace R_inla; // Not loaded globally, but used below using namespace density; using namespace Eigen; - //using namespace tinyVAST; + using namespace tinyVAST; // Settings DATA_IMATRIX( family_ez ); // family diff --git a/src/utils.h b/src/utils.h new file mode 100644 index 00000000..2bf5805d --- /dev/null +++ b/src/utils.h @@ -0,0 +1,1122 @@ +// Notes +// don't use pass-by-const-reference for tmbutils::array + +namespace tinyVAST { + +enum valid_family { + gaussian_family = 0, + tweedie_family = 1, + lognormal_family = 2, + poisson_family = 3, + bernoulli_family = 4, + binomial_family = 4, + gamma_family = 5, + nbinom1_family = 6, + nbinom2_family = 7, + student_family = 8 +}; + +enum valid_link { + identity_link = 0, + log_link = 1, + logit_link = 2, + cloglog_link = 3 +}; + +// Old algorithmic constructor for tail-down exponential stream network, copied from VAST +//template +//Eigen::SparseMatrix Q_network( Type log_theta, +// int n_s, +// vector parent_s, +// vector child_s, +// vector dist_s ){ +// +// Eigen::SparseMatrix Q( n_s, n_s ); +// Type theta = exp( log_theta ); +// for(int s=0; s +Eigen::SparseMatrix vectorsToSparseMatrix( + const vector &i, + const vector &j, + const vector &x, + int N ){ + + // https://eigen.tuxfamily.org/dox/classEigen_1_1SparseMatrix.html#title35 + using namespace Eigen; + std::vector> tripletList; + for( int index = 0; index < i.size(); index ++ ){ + tripletList.push_back(Triplet( i[index], j[index], x[index]) ); + } + SparseMatrix M( N, N ); + M.setFromTriplets( tripletList.begin(), tripletList.end() ); + + //Eigen::SparseMatrix M( N, N ); + //for(int index=0; index +struct spde_covariates_t{ + int n_s; + //int n_tri; + vector Tri_Area; + matrix E0; + matrix E1; + matrix E2; + matrix V_zk; + matrix TV; + Eigen::SparseMatrix G0; + Eigen::SparseMatrix G0_inv; + + // Define output + spde_covariates_t(SEXP x){ /* x = List passed from R */ + n_s = CppAD::Integer(asVector(getListElement(x,"n_s"))[0]); + //n_tri = CppAD::Integer(asVector(getListElement(x,"n_tri"))[0]); + Tri_Area = asVector(getListElement(x,"Tri_Area")); + E0 = asMatrix(getListElement(x,"E0")); + E1 = asMatrix(getListElement(x,"E1")); + E2 = asMatrix(getListElement(x,"E2")); + V_zk = asMatrix(getListElement(x,"V_zk")); + TV = asMatrix(getListElement(x,"TV")); + G0 = tmbutils::asSparseMatrix(getListElement(x,"G0")); + G0_inv = tmbutils::asSparseMatrix(getListElement(x,"G0_inv")); + } +}; +// make stiffness G1 from covariates in columns of E0, E1, E2 +template +Eigen::SparseMatrix G_spde_covariates( + const spde_covariates_t &spde, + const matrix &H_jj, + //matrix V_zk, + const vector &triangle_k ){ + + // TO ADD EDGE COVARIATES: + // 0. add n_e = edge0_tj.rows() + // 1. Add TE, where dim(TE) = n_t \times 3, listing the edge-number for each triangle-edge of n_e edges + // 2. Add A_ek design matrix, where dim(A_ek) = n_e \times n_k (edge-covariates) + + // Extract objects + vector area_t = spde.Tri_Area; + matrix edge0_tj = spde.E0; + matrix edge1_tj = spde.E1; + matrix edge2_tj = spde.E2; + matrix s_tv = spde.TV; // dim = n_t \times n_v + matrix triangle_t1 = spde.V_zk * triangle_k.matrix(); + int n_s = spde.n_s; + int n_t = s_tv.rows(); + int n_v = s_tv.cols(); // number of vertices per triangle + int n_j = edge0_tj.cols(); // number of covariates (default = 2) + + // Output + Eigen::SparseMatrix G_ss(n_s, n_s); + + // Objects to assemble triangle contributions + matrix edges_vj( n_v, n_j ); + matrix Gt_vv( n_v, n_v ); + + // Calculate adjugate of H + //matrix adjH_jj = H_jj.inverse() * H_jj.determinant(); // CAUSES CRASH + matrix adjH_jj = H_jj.adjoint(); + + // Assemble stiffness G + for( int t=0; t Gt_ss( n_s, n_s ); + for(int v1 = 0; v1 < 3; v1++ ){ + for(int v2 = 0; v2 < 3; v2++ ){ + Gt_ss.coeffRef( s_tv(t,v1), s_tv(t,v2) ) = Gt_vv(v1,v2); + }} + G_ss += Gt_ss / ( 4.0 * area_t(t) ); + } + return G_ss; +} + +// Q_SAR( log_kappa, H, n_s, i_z, j_z, delta_z2 ) +// Using a SAR (not standardized) to approximate spatial function +template +Eigen::SparseMatrix Q_SAR( + //Type rho, + Type kappa, + const matrix &H, + int n_s, + const vector &i_z, + const vector &j_z, + const matrix &delta_z2 ){ + + //Type max_dist = delta_z2.cwiseAbs().maxCoeff(); + + //d_z = sqrt((delta_z2 %*% H)^2 %*% matrix(1,nrow=2,ncol=1))[,1] + matrix deltaprime_z2 = (delta_z2 * H); // / max_dist; + vector dist_z( i_z.size() ); + for( int z = 0; z < i_z.size(); z++ ){ + dist_z(z) = pow( pow(deltaprime_z2(z,0),2.0) + pow(deltaprime_z2(z,1),2.0), 0.5 ); + } + vector weight_z = exp( -kappa * dist_z ); + + // Make weight matrix + Eigen::SparseMatrix W_ss = vectorsToSparseMatrix( + i_z, j_z, weight_z, n_s + ); + + // Row-standardize W_ss + // Does *not* make sense when using anisotropy + //for( int row = 0; row < n_s; row ++ ){ + // Type rowsum = W_ss.row(row).sum(); + // W_ss.row(row) /= rowsum; + //} + + // Assemble + Eigen::SparseMatrix I_ss( n_s, n_s ); + I_ss.setIdentity(); + Eigen::SparseMatrix IminusP_ss = I_ss - W_ss; + Eigen::SparseMatrix Q = IminusP_ss.transpose() * IminusP_ss; + return Q; +} + +// New matrix-notation precision constructor for tail-down exponential stream network +template +Eigen::SparseMatrix Q_network2( + Type log_theta, + int n_s, + const vector &parent_s, + const vector &child_s, + const vector &dist_s ){ + + // Compute vectors + Type theta = exp(log_theta); + vector v1_s = exp(-theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); + vector v2_s = exp(-2.0 * theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); + + // Make components + Eigen::SparseMatrix P_ss = vectorsToSparseMatrix( child_s, + parent_s, + v1_s, + n_s ); + Eigen::SparseMatrix D_ss = vectorsToSparseMatrix( child_s, + child_s, + v2_s, + n_s ); + Eigen::SparseMatrix invD_ss( n_s, n_s ); + for( int s=0; s DminusP_ss = D_ss - P_ss; + Eigen::SparseMatrix Q = DminusP_ss.transpose() * invD_ss * DminusP_ss; + return Q; +} + +// Functions to evaluate density for nearest-neighbors Gaussian process +template +vector covariance_function(vector d, Type sigma2, Type inv_range) { + return ((-d.array() * inv_range).exp() * sigma2).matrix(); +} +template +matrix covariance_function(matrix d, Type sigma2, Type inv_range) { + return ((-d.array() * inv_range).exp() * sigma2).matrix(); +} +/** \brief Object containing all data elements of an NNGP */ +template +struct nngp_data_t{ + vector nn_index_flat; + vector nn_len; + vector dist_to_nn_flat; + vector dist_within_nn_flat; + vector gp_order; + + // Define output + nngp_data_t(SEXP x){ /* x = List passed from R */ + nn_index_flat = asVector(getListElement(x,"nn_index_flat")); + nn_len = asVector(getListElement(x,"nn_len")); + dist_to_nn_flat = asVector(getListElement(x,"dist_to_nn_flat")); + dist_within_nn_flat = asVector(getListElement(x,"dist_within_nn_flat")); + gp_order = asVector(getListElement(x,"gp_order")); + } +}; +// Density function .. sigma2 fixed at 1.0 +template +Type NNGP( Type sigma2, + Type range, + vector field_s, + // Data + nngp_data_t nngp_data ){ + + // Using original order and ordered_structure, by calling gp_order(i) and gp_order(nn_ids), because: + // 1. using original version in new order is very slow! presumably the order is terrible for the inner Hessian + // 2. using re-ordered version of field is confusing for users + Type nll = 0.0; + Type inv_range = 1.0 / range; // Multiplication is faster than division + vector nn_index_flat = nngp_data.nn_index_flat; + //vector nn_start = nngp_data.nn_start; + vector nn_len = nngp_data.nn_len; + vector dist_to_nn_flat = nngp_data.dist_to_nn_flat; + vector dist_within_nn_flat = nngp_data.dist_within_nn_flat; + vector gp_order = nngp_data.gp_order; + int n = field_s.size(); + + int pos_mat = 0; + int pos_vec = 0; + for( int i = 0; i < n; i++ ){ + int k = nn_len(i); + + // No neighbors + if(k == 0){ + nll -= dnorm( field_s(gp_order(i)), Type(0.0), sqrt(sigma2), true ); + }else{ + // Extract neighbor indices and distance to neighbors + vector nn_ids(k); + vector dist_iN(k); + for (int j = 0; j < k; j++) { + nn_ids(j) = nn_index_flat(pos_vec); + dist_iN(j) = dist_to_nn_flat(pos_vec); + pos_vec++; + } + + // Extract within-neighbor distance matrix (k x k) ... + matrix dist_NN(k, k); + for (int r = 0; r < k; r++) { + for (int c = 0; c < k; c++) { + dist_NN(r, c) = dist_within_nn_flat(pos_mat); + pos_mat++; + } + } + + // Covariances + matrix Sigma_NN = covariance_function(dist_NN, sigma2, inv_range); + vector Sigma_iN = covariance_function(dist_iN, sigma2, inv_range); + + // Solve + //vector a_i = solve(Sigma_NN, Sigma_iN); + //vector a_i = Sigma_NN.ldlt().solve( Sigma_iN.matrix() ); + //Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > invSigma_NN; + //invSigma_NN.compute(Sigma_NN); + //vector a_i = invSigma_NN.solve(Sigma_iN); + matrix Sigma_NN_inv = atomic::matinv(Sigma_NN); + vector a_i = Sigma_NN_inv * Sigma_iN; + + // Residual variance + Type resid_var = sigma2 - (a_i * Sigma_iN).sum(); // + 1e-12; + + // Conditional mean + Type cond_mean = 0.0; + for (int j = 0; j < k; j++) { + cond_mean += a_i(j) * field_s(gp_order(nn_ids(j))); + } + + // Likelihood + nll -= dnorm( field_s(gp_order(i)), cond_mean, sqrt(resid_var), true ); + } + } + return nll; +} + +// Function to calculate RAM matrices +template +Eigen::SparseMatrix make_ram( matrix ram, + vector ram_start, + vector beta_z, + int n_c, + int what ){ + + Eigen::SparseMatrix out_cc(n_c, n_c); + out_cc.setZero(); + Type tmp; + + for(int r=0; r=1){ + tmp = beta_z(ram(r,3)-1); + }else{ + tmp = ram_start(r); + } + // Rho_cc + if( (ram(r,0)==1) && (what==0) ){ + out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; + } + // Gammainv_cc + if( (ram(r,0)==2) && (what==1) ){ + out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = 1 / tmp; + } + // Gamma_cc + if( (ram(r,0)==2) && (what==2) ){ + out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; + } + } + + return out_cc; +} + +// distribution/projection for gamma +// Based on: +// https://github.com/meganferg/FergusonEtal_20250125_EBS_Beluga_DSM/blob/main/src/te_tw_DSM.cpp#L85C9-L85C40 (Megan Ferguson) +template +Type gamma_distribution( vector gamma_k, + vector Sdims, + vector Sblock, + Eigen::SparseMatrix S_kk, + vector log_lambda ){ + + using namespace density; + Type nll = 0.0; + int start_gamma = 0; // Counter for gamma + int start_k = 0; // counter for columns of S_kk + int index_lambda = 0; + for(int z=0; z gamma_segment = gamma_k.segment(start_gamma, ngamma_z); + start_gamma += ngamma_z; + + // s() splines + if( Sblock(z) == 1 ){ + // Recover S_block + Eigen::SparseMatrix S_block = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i + + /// Quadratic-form GRMF + // GMRF(Q).Quadform(x) caused a problem calculating the log-determinant unnecessarily, resulting in valgrind error + //nll -= Type(0.5)*Type(m_z)*log_lambda(z) - Type(0.5)*exp(log_lambda(z))*GMRF(S_block).Quadform(gamma_segment); + nll -= Type(0.5)*Type(ngamma_z)*log_lambda(index_lambda) - Type(0.5) * exp(log_lambda(index_lambda)) * + (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); + + start_k += ngamma_z; + index_lambda += 1; + } + + // te() / ti() / t2() splines + if( Sblock(z) >= 2 ){ + // Recover S_block ... Eigen::SparseMatrix appears to initialize as empty so no .setZero() equivalent needed + Eigen::SparseMatrix S_block( ngamma_z, ngamma_z ); + for( int block=0; block < Sblock(z); block ++ ){ + Eigen::SparseMatrix S_tmp = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i + S_block += exp(log_lambda(index_lambda)) * S_tmp; + start_k += ngamma_z; + index_lambda++; + } + + /// Quadratic-form GRMF + nll -= 0.5*(atomic::logdet(matrix(S_block))) - 0.5 * + (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); + } + } + return( nll ); +} + +// distribution/projection for omega +template +tmbutils::array omega_distribution( tmbutils::array omega_sc, + vector model_options, + Eigen::SparseMatrix Rho_cc, + Eigen::SparseMatrix Gamma_cc, + Eigen::SparseMatrix Gammainv_cc, + Eigen::SparseMatrix Q_ss, + Type range, + nngp_data_t nngp_data, + Type &nll ){ + + if( omega_sc.size() > 0 ){ + int n_c = omega_sc.dim(1); + using namespace density; + Eigen::SparseMatrix I_cc( n_c, n_c ); + I_cc.setIdentity(); + if( omega_sc.size()>0 ){ // PARALLEL_REGION + Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; + if( model_options(1) == 0 ){ + // Separable precision ... Option-1 + //Eigen::SparseMatrix Linv_cc = Gammainv_cc * ( I_cc - Rho_cc ); + //Eigen::SparseMatrix Q_cc = Linv_cc.transpose() * Linv_cc; + + // Separable precision ... Option-2 + // Only compute Vinv_kk if Gamma_kk is full rank + Eigen::SparseMatrix V_cc = Gamma_cc.transpose() * Gamma_cc; + matrix Vinv_cc = invertSparseMatrix( V_cc ); + Eigen::SparseMatrix Vinv2_cc = asSparseMatrix( Vinv_cc ); + Eigen::SparseMatrix Q_cc = IminusRho_cc.transpose() * Vinv2_cc * IminusRho_cc; + + // GMRF for SEM: separable variable-space + nll += SEPARABLE( GMRF(Q_cc), GMRF(Q_ss) )( omega_sc ); + // Including this line with Makevars below seems to cause a crash: + // PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) + // PKG_CXXFLAGS=$(SHLIB_OPENMP_CXXFLAGS) + }else{ + // Rank-deficient (projection) method + if( model_options(0) == 7 ){ + vector omega_s( omega_sc.rows() ); + for( int ci = 0; ci < omega_sc.cols(); ci++ ){ + omega_s = omega_sc.col(ci); + nll += NNGP( Type(1.0), range, omega_s, nngp_data ); + } + }else{ + nll += SEPARABLE( GMRF(I_cc), GMRF(Q_ss) )( omega_sc ); + } + + // Sparse inverse-product + //Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; + Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_cc; + inverseIminusRho_cc.compute(IminusRho_cc); + + // (I-Rho)^{-1} * Gamma * Epsilon + matrix omega2_cs = Gamma_cc * omega_sc.matrix().transpose(); + matrix omega3_cs = inverseIminusRho_cc.solve(omega2_cs); + omega_sc = omega3_cs.transpose(); + } + } + } + + return omega_sc; +} + +// distribution/projection for xi +template +Type xi_distribution( vector model_options, + tmbutils::array xi_sl, + vector log_sigmaxi_l, + Eigen::SparseMatrix Q_ss, + Type range, + nngp_data_t nngp_data ){ + + Type nll = 0; + if( xi_sl.size() > 0 ){ + int n_l = xi_sl.cols(); + using namespace density; + if( model_options(0) == 7 ){ + vector xi_s( xi_sl.rows() ); + for( int l=0; l +tmbutils::array epsilon_distribution( + tmbutils::array epsilon_stc, + const vector &model_options, + const Eigen::SparseMatrix &Rho_hh, + const Eigen::SparseMatrix &Gamma_hh, + const Eigen::SparseMatrix &Gammainv_hh, + const Eigen::SparseMatrix &Q_ss, + Type range, + const nngp_data_t &nngp_data, + Type &nll ){ + + if( epsilon_stc.size() > 0 ){ + int n_s = epsilon_stc.dim(0); + int n_t = epsilon_stc.dim(1); + int n_c = epsilon_stc.dim(2); + int n_h = n_t * n_c; + using namespace density; + Eigen::SparseMatrix I_hh( n_h, n_h ); + I_hh.setIdentity(); + int h; + + //if( epsilon_stc.size()>0 ){ // PARALLEL_REGION + // Reshape for either model_options + tmbutils::array epsilon_hs( n_h, n_s ); + for( int s=0; s IminusRho_hh = I_hh - Rho_hh; + + if( model_options(1) == 0 ){ + // Separable precision ... Option-1 + //Eigen::SparseMatrix Linv_hh = Gammainv_hh * ( I_hh - Rho_hh ); + //Eigen::SparseMatrix Q_hh = Linv_hh.transpose() * Linv_hh; + + // Separable precision ... Option-2 + // Only compute Vinv_kk if Gamma_kk is full rank + Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; + matrix Vinv_hh = invertSparseMatrix( V_hh ); + Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); + Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; + + // GMRF for DSEM: non-separable time-variable, with separable space + nll += SEPARABLE( GMRF(Q_ss), GMRF(Q_hh) )( epsilon_hs ); + }else{ + // Rank-deficient (projection) method + if( model_options(0) == 7 ){ + vector epsilon_s( epsilon_hs.cols() ); + for( int hi = 0; hi < epsilon_hs.rows(); hi++ ){ + epsilon_s = epsilon_hs.matrix().row(hi); + nll += NNGP( Type(1.0), range, epsilon_s, nngp_data ); + } + }else{ + nll += SEPARABLE( GMRF(Q_ss), GMRF(I_hh) )( epsilon_hs ); + } + + // Sparse inverse-product + //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; + Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; + inverseIminusRho_hh.compute(IminusRho_hh); + + // (I-Rho)^{-1} * Gamma * Epsilon + matrix e2_hs = Gamma_hh * epsilon_hs.matrix(); + matrix e3_hs = inverseIminusRho_hh.solve(e2_hs); + + // Transformations + for( int s=0; s +tmbutils::array delta_distribution( + tmbutils::array delta_tc, + const vector &model_options, + const Eigen::SparseMatrix &Rho_hh, + const Eigen::SparseMatrix &Gamma_hh, + const Eigen::SparseMatrix &Gammainv_hh, + Type &nll ){ + + if( delta_tc.size() > 0 ){ + int n_t = delta_tc.dim(0); + int n_c = delta_tc.dim(1); + int n_h = n_t * n_c; + using namespace density; + Eigen::SparseMatrix I_hh( n_h, n_h ); + I_hh.setIdentity(); + int h; + + // Reshape for either model_options + tmbutils::array delta_h1( n_h, 1 ); + for( int t=0; t IminusRho_hh = I_hh - Rho_hh; + + if( model_options(1) == 0 ){ + Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; + matrix Vinv_hh = invertSparseMatrix( V_hh ); + Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); + Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; + + // GMRF for DSEM: non-separable time-variable, with separable space + nll += GMRF(Q_hh)( delta_h1 ); + }else{ + // Rank-deficient (projection) method + nll += GMRF(I_hh)( delta_h1 ); + + // Sparse inverse-product + //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; + Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; + inverseIminusRho_hh.compute(IminusRho_hh); + + // (I-Rho)^{-1} * Gamma * Epsilon + matrix e2_h1 = Gamma_hh * delta_h1.matrix(); + matrix e3_h1 = inverseIminusRho_hh.solve(e2_h1); + + // Transformations + for( int t=0; t +bool isNA(Type x){ + return R_IsNA(asDouble(x)); +} + +// Sparse array * matrix +// NAs in IVECTOR or IMATRIX get converted to -2147483648, so isNA doesn't work ... instead drop NAs from A prior to passing to TMB +template +vector multiply_epsilon( + const matrix &A, + const vector &weight, + tmbutils::array x, + int n_i ){ + + vector out( n_i ); + out.setZero(); + if( x.size() > 0 ){ + for( int z=0; z +vector multiply_omega( + const matrix &A, + const vector &weight, + tmbutils::array x, + int n_i ){ + + vector out( n_i ); + out.setZero(); + if( x.size() > 0 ){ + for( int z=0; z +vector multiply_xi( + const Eigen::SparseMatrix &A_is, + tmbutils::array xi_sl, + const matrix &W_il ){ + + vector out( W_il.rows() ); + out.setZero(); + if( xi_sl.size() > 0 ){ + matrix xi_il = A_is * xi_sl.matrix(); + for( int i=0; i +vector multiply_delta( + tmbutils::array delta_tc, + const vector &t_i, + const vector &c_i, + int n_i ){ + + vector delta_i( n_i ); + delta_i.setZero(); + if( delta_tc.size() > 0 ){ + for( int i=0; i +Type sign(Type x){ + return x / pow(pow(x,2),0.5); +} + +// dlnorm +template +Type dlnorm( + Type x, + Type meanlog, + Type sdlog, + int give_log=0){ + + //return 1/(sqrt(2*M_PI)*sd) * exp(-.5*pow((x-mean)/sd,2)); + Type logres = dnorm( log(x), meanlog, sdlog, true) - log(x); + if(give_log) return logres; else return exp(logres); +} + +// dlnorm +template +Type dbinom_custom( + Type x, + Type log_prob, + Type log_one_minus_prob, + Type size, + int give_log = 0 ){ + + // size choose x + Type logres = lgamma(size + 1.0) - lgamma(x + 1.0) - lgamma(size - x + 1.0); + // p^x * (1-p)^(size-x) + logres += x * log_prob + (size-x) * log_one_minus_prob; + if(give_log) return logres; else return exp(logres); +} + +// dlnorm +template +Type devresid_binom( + Type y, + Type weight, // weight = size + Type mu ){ + + Type y_weight = y * weight; + Type mu_weight = mu * weight; + Type p1, p2; + if(y_weight == 0){ + p1 = 0.0; + }else{ + p1 = y_weight * log(y_weight / mu_weight); + } + if( (weight - y_weight) == 0 ){ + p2 = 0.0; + }else{ + p2 = (weight - y_weight) * log( (weight - y_weight) / (weight - mu_weight) ); + } + Type devresid = sign(y - mu) * pow(2 * (p1 + p2), 0.5); + return devresid; +} + +// Deviance for the Tweedie +// https://en.wikipedia.org/wiki/Tweedie_distribution#Properties +template +Type devresid_tweedie( + Type y, + Type mu, + Type p ){ + + Type c1 = pow( y, 2.0-p ) / (1.0-p) / (2.0-p); + Type c2 = y * pow( mu, 1.0-p ) / (1.0-p); + Type c3 = pow( mu, 2.0-p ) / (2.0-p); + Type deviance = 2 * (c1 - c2 + c3 ); + Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); + return devresid; +} + +// Deviance for the student-T +// from chatGPT (experimental) ... converges on Gaussian as df -> Inf +template +Type devresid_student( + Type y, + Type mu, + Type sigma, + Type df ){ + + Type deviance = (df + 1.0) * log( 1.0 + pow(y-mu,2.0) / (df * sigma*sigma) ); + Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); + return devresid; +} + +// COPIED from sdmTMB.cpp in sdmTMB package on Nov. 14, 2025 +template +Type dstudent( + Type x, + Type mean, + Type sigma, + Type df, + int give_log = 0) { + + // from metRology::dt.scaled() + // dt((x - mean)/sd, df, ncp = ncp, log = TRUE) - log(sd) + Type logres = dt((x - mean) / sigma, df, true) - log(sigma); + if (give_log) + return logres; + else + return exp(logres); +} + +// Deviance for the Negative binomial +//template +//Type devresid_nbinom1( Type y, +// Type logmu, +// Type logtheta ){ +// +// // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu +// Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), log(y + Type(1e-10)) + logtheta, true ); +// Type logp2 = dnbinom_robust( y, logmu, logmu + logtheta, true ); +// Type deviance = 2 * (logp1 - logp2); +// Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); +// return devresid; +//} +template +Type devresid_nbinom2( + Type y, + Type logmu, + Type logtheta ){ + + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), Type(2.0) * log(y + Type(1e-10)) - logtheta, true ); + Type logp2 = dnbinom_robust( y, logmu, Type(2.0) * logmu - logtheta, true ); + Type deviance = 2 * (logp1 - logp2); + Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); + return devresid; +} + + +// distribution/projection for epsilon +// deviance = deviance1 + deviance2 +template +Type one_predictor_likelihood( + Type &y, + Type p, + Type size, + int link, + int family, + vector log_sigma_segment, + Type &nll, + Type &devresid, + objective_function* of ){ + + Type mu, logmu, log_one_minus_mu; + //Type devresid = 0; + + switch( link ){ + case identity_link: + mu = p; + logmu = log( p ); + log_one_minus_mu = log( Type(1.0) - mu ); + break; + case log_link: + mu = exp(p); + logmu = p; + log_one_minus_mu = log( Type(1.0) - mu ); + break; + case logit_link: + mu = invlogit(p); + //logmu = log(mu); + logmu = p - logspace_add( Type(0.0), p ); + //log_one_minus_mu = log( invlogit(-1 * p) ); + log_one_minus_mu = 0.0 - logspace_add( Type(0.0), p ); + break; + case cloglog_link: + mu = Type(1.0) - exp( -1 * exp(p) ); + logmu = logspace_sub( Type(0.0), -1.0 * exp(p) ); + log_one_minus_mu = -1.0 * exp(p); + break; + default: + error("Link not implemented."); + } + if( !R_IsNA(asDouble(y)) ){ + // Distribution + switch( family ){ + case gaussian_family: + nll = -1 * dnorm( y, mu, exp(log_sigma_segment(0)), true ); + devresid = y - mu; + if(isDouble::value && of->do_simulate){ + y = rnorm( mu, exp(log_sigma_segment(0)) ); + } + break; + case tweedie_family: + nll = -1 * dtweedie( y, mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); + devresid = devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); + if(isDouble::value && of->do_simulate){ + y = rtweedie( mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); + } + break; + case lognormal_family: + nll = -1 * dlnorm( y, logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); + devresid = log(y) - ( logmu - 0.5*exp(2.0*log_sigma_segment(0)) ); + if(isDouble::value && of->do_simulate){ + y = exp(rnorm( logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); + } + break; + case poisson_family: + nll = -1 * dpois( y, mu, true ); + devresid = sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); + if(isDouble::value && of->do_simulate){ + y = rpois( mu ); + } + break; + case binomial_family: + //if(y==0){ + // nll = -1 * log_one_minus_mu; + //}else{ + // nll = -1 * logmu; + //} + nll = -1 * dbinom_custom( y * size, logmu, log_one_minus_mu, size, true ); + if(isDouble::value && of->do_simulate){ + y = rbinom( size, mu ); + } + // TODO: Update deviance residual for Trials = size + //devresid = sign(y - mu) * pow(-2*((1-y)*log(1.0-mu) + y*log(mu)), 0.5); + devresid = devresid_binom( y, size, mu ); + break; + case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 + nll = -1 * dgamma( y, exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)), true ); + devresid = sign(y - mu) * pow(2 * ( (y-mu)/mu - log(y/mu) ), 0.5); + if(isDouble::value && of->do_simulate){ + y = rgamma( exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)) ); + } + break; + case nbinom1_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu + nll = -1 * dnbinom_robust( y, logmu, logmu + log_sigma_segment(0), true); + devresid = devresid_nbinom2( y, logmu, logmu - log_sigma_segment(0) ); // theta = mu / phi + if(isDouble::value && of->do_simulate){ + // rnbinom2( mu, var ) + y = rnbinom2( mu, mu * (Type(1.0) + exp(log_sigma_segment(0))) ); + } + break; + case nbinom2_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + nll = -1 * dnbinom_robust( y, logmu, Type(2.0) * logmu - log_sigma_segment(0), true); + devresid = devresid_nbinom2( y, logmu, log_sigma_segment(0) ); + if(isDouble::value && of->do_simulate){ + // rnbinom2( mu, var ) + y = rnbinom2( mu, mu * (Type(1.0) + mu / exp(log_sigma_segment(0))) ); + } + break; + case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + nll = -1 * dstudent( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); + devresid = devresid_student( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)) ); + if(isDouble::value && of->do_simulate){ + y = mu + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); + } + break; + default: + error("Distribution not implemented."); + } + } + + return mu; +} + +// distribution/projection for epsilon +template +Type two_predictor_likelihood( + Type &y, + Type p1, + Type p2, + Type size, + vector link, + vector family, + vector log_sigma_segment, + int poislink, + Type &nll, + Type &dev, + objective_function* of ){ + + Type mu1, logmu1, mu2, logmu2, log_one_minus_mu1; + + // First link + if( poislink==0 ){ + mu1 = invlogit( p1 ); + logmu1 = log( mu1 ); + log_one_minus_mu1 = log( Type(1.0) - mu1 ); + // second link + switch( link(1) ){ + case identity_link: + mu2 = p2; + logmu2 = log( p2 ); + break; + case log_link: + mu2 = exp(p2); + logmu2 = p2; + break; + default: + error("Link not implemented."); + } + }else{ + mu1 = Type(1.0) - exp( -1.0*exp(p1) ); + logmu1 = logspace_sub( Type(0.0), -1*exp(p1) ); + log_one_minus_mu1 = -1.0*exp(p1); + mu2 = exp( p1 + p2 ) / mu1; + logmu2 = p1 + p2 - logmu1; + } + if( !R_IsNA(asDouble(y)) ){ + // Distribution + if(isDouble::value && of->do_simulate){ + y = rbinom( Type(1), mu1 ); + } + if( y == 0 ){ + nll = -1 * log_one_minus_mu1; + dev = -2 * log_one_minus_mu1; + } + if( y>0 ){ // Not if-else so y>0 triggered when simulating y>0 + nll = -1 * logmu1; + dev = -2 * logmu1; + //deviance1_i(i) = -2 * log_mu1(i); + switch( family(1) ){ + case gaussian_family: + nll -= dnorm( y, mu2, exp(log_sigma_segment(0)), true ); + dev += pow(y - mu2, 2.0); + if(isDouble::value && of->do_simulate){ + y = rnorm( mu2, exp(log_sigma_segment(0)) ); + } + break; + //case tweedie_family: + // nll -= dtweedie( y, mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); + // devresid += devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); + // if(isDouble::value && of->do_simulate){ + // y = rtweedie( mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); + // } + // break; + case lognormal_family: + nll -= dlnorm( y, logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); + dev += pow( log(y) - (logmu2 - 0.5*exp(2.0*log_sigma_segment(0))), 2.0 ); + if(isDouble::value && of->do_simulate){ + y = exp(rnorm( logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); + } + break; + //case poisson_family: + // nll -= dpois( y, mu2, true ); + // devresid += sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); + // if(isDouble::value && of->do_simulate){ + // y = rpois( mu2 ); + // } + // break; + // case 4: // Bernoulli + case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 + nll -= dgamma( y, exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)), true ); + dev += 2 * ( (y-mu2)/mu2 - log(y/mu2) ); + if(isDouble::value && of->do_simulate){ + y = rgamma( exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)) ); + } + break; + case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) + // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta + nll -= dstudent( y, mu2, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); + //dev = NAN; + if(isDouble::value && of->do_simulate){ + y = mu2 + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); + } + break; + default: + error("Distribution not implemented."); + } + } + } + + return mu1 * mu2; +} + +} // namespace tinyVAST From 0e16a6573658a2a0c7a20d1d91440bd7b0332eb5 Mon Sep 17 00:00:00 2001 From: James Thorson Date: Mon, 13 Jul 2026 20:46:48 -0700 Subject: [PATCH 16/37] add more pass-by-const-reference --- scratch/utils.h | 1122 ----------------------------------------------- src/utils.h | 67 +-- 2 files changed, 36 insertions(+), 1153 deletions(-) delete mode 100644 scratch/utils.h diff --git a/scratch/utils.h b/scratch/utils.h deleted file mode 100644 index 2bf5805d..00000000 --- a/scratch/utils.h +++ /dev/null @@ -1,1122 +0,0 @@ -// Notes -// don't use pass-by-const-reference for tmbutils::array - -namespace tinyVAST { - -enum valid_family { - gaussian_family = 0, - tweedie_family = 1, - lognormal_family = 2, - poisson_family = 3, - bernoulli_family = 4, - binomial_family = 4, - gamma_family = 5, - nbinom1_family = 6, - nbinom2_family = 7, - student_family = 8 -}; - -enum valid_link { - identity_link = 0, - log_link = 1, - logit_link = 2, - cloglog_link = 3 -}; - -// Old algorithmic constructor for tail-down exponential stream network, copied from VAST -//template -//Eigen::SparseMatrix Q_network( Type log_theta, -// int n_s, -// vector parent_s, -// vector child_s, -// vector dist_s ){ -// -// Eigen::SparseMatrix Q( n_s, n_s ); -// Type theta = exp( log_theta ); -// for(int s=0; s -Eigen::SparseMatrix vectorsToSparseMatrix( - const vector &i, - const vector &j, - const vector &x, - int N ){ - - // https://eigen.tuxfamily.org/dox/classEigen_1_1SparseMatrix.html#title35 - using namespace Eigen; - std::vector> tripletList; - for( int index = 0; index < i.size(); index ++ ){ - tripletList.push_back(Triplet( i[index], j[index], x[index]) ); - } - SparseMatrix M( N, N ); - M.setFromTriplets( tripletList.begin(), tripletList.end() ); - - //Eigen::SparseMatrix M( N, N ); - //for(int index=0; index -struct spde_covariates_t{ - int n_s; - //int n_tri; - vector Tri_Area; - matrix E0; - matrix E1; - matrix E2; - matrix V_zk; - matrix TV; - Eigen::SparseMatrix G0; - Eigen::SparseMatrix G0_inv; - - // Define output - spde_covariates_t(SEXP x){ /* x = List passed from R */ - n_s = CppAD::Integer(asVector(getListElement(x,"n_s"))[0]); - //n_tri = CppAD::Integer(asVector(getListElement(x,"n_tri"))[0]); - Tri_Area = asVector(getListElement(x,"Tri_Area")); - E0 = asMatrix(getListElement(x,"E0")); - E1 = asMatrix(getListElement(x,"E1")); - E2 = asMatrix(getListElement(x,"E2")); - V_zk = asMatrix(getListElement(x,"V_zk")); - TV = asMatrix(getListElement(x,"TV")); - G0 = tmbutils::asSparseMatrix(getListElement(x,"G0")); - G0_inv = tmbutils::asSparseMatrix(getListElement(x,"G0_inv")); - } -}; -// make stiffness G1 from covariates in columns of E0, E1, E2 -template -Eigen::SparseMatrix G_spde_covariates( - const spde_covariates_t &spde, - const matrix &H_jj, - //matrix V_zk, - const vector &triangle_k ){ - - // TO ADD EDGE COVARIATES: - // 0. add n_e = edge0_tj.rows() - // 1. Add TE, where dim(TE) = n_t \times 3, listing the edge-number for each triangle-edge of n_e edges - // 2. Add A_ek design matrix, where dim(A_ek) = n_e \times n_k (edge-covariates) - - // Extract objects - vector area_t = spde.Tri_Area; - matrix edge0_tj = spde.E0; - matrix edge1_tj = spde.E1; - matrix edge2_tj = spde.E2; - matrix s_tv = spde.TV; // dim = n_t \times n_v - matrix triangle_t1 = spde.V_zk * triangle_k.matrix(); - int n_s = spde.n_s; - int n_t = s_tv.rows(); - int n_v = s_tv.cols(); // number of vertices per triangle - int n_j = edge0_tj.cols(); // number of covariates (default = 2) - - // Output - Eigen::SparseMatrix G_ss(n_s, n_s); - - // Objects to assemble triangle contributions - matrix edges_vj( n_v, n_j ); - matrix Gt_vv( n_v, n_v ); - - // Calculate adjugate of H - //matrix adjH_jj = H_jj.inverse() * H_jj.determinant(); // CAUSES CRASH - matrix adjH_jj = H_jj.adjoint(); - - // Assemble stiffness G - for( int t=0; t Gt_ss( n_s, n_s ); - for(int v1 = 0; v1 < 3; v1++ ){ - for(int v2 = 0; v2 < 3; v2++ ){ - Gt_ss.coeffRef( s_tv(t,v1), s_tv(t,v2) ) = Gt_vv(v1,v2); - }} - G_ss += Gt_ss / ( 4.0 * area_t(t) ); - } - return G_ss; -} - -// Q_SAR( log_kappa, H, n_s, i_z, j_z, delta_z2 ) -// Using a SAR (not standardized) to approximate spatial function -template -Eigen::SparseMatrix Q_SAR( - //Type rho, - Type kappa, - const matrix &H, - int n_s, - const vector &i_z, - const vector &j_z, - const matrix &delta_z2 ){ - - //Type max_dist = delta_z2.cwiseAbs().maxCoeff(); - - //d_z = sqrt((delta_z2 %*% H)^2 %*% matrix(1,nrow=2,ncol=1))[,1] - matrix deltaprime_z2 = (delta_z2 * H); // / max_dist; - vector dist_z( i_z.size() ); - for( int z = 0; z < i_z.size(); z++ ){ - dist_z(z) = pow( pow(deltaprime_z2(z,0),2.0) + pow(deltaprime_z2(z,1),2.0), 0.5 ); - } - vector weight_z = exp( -kappa * dist_z ); - - // Make weight matrix - Eigen::SparseMatrix W_ss = vectorsToSparseMatrix( - i_z, j_z, weight_z, n_s - ); - - // Row-standardize W_ss - // Does *not* make sense when using anisotropy - //for( int row = 0; row < n_s; row ++ ){ - // Type rowsum = W_ss.row(row).sum(); - // W_ss.row(row) /= rowsum; - //} - - // Assemble - Eigen::SparseMatrix I_ss( n_s, n_s ); - I_ss.setIdentity(); - Eigen::SparseMatrix IminusP_ss = I_ss - W_ss; - Eigen::SparseMatrix Q = IminusP_ss.transpose() * IminusP_ss; - return Q; -} - -// New matrix-notation precision constructor for tail-down exponential stream network -template -Eigen::SparseMatrix Q_network2( - Type log_theta, - int n_s, - const vector &parent_s, - const vector &child_s, - const vector &dist_s ){ - - // Compute vectors - Type theta = exp(log_theta); - vector v1_s = exp(-theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); - vector v2_s = exp(-2.0 * theta * dist_s) / (1.0 - exp(-2.0 * theta * dist_s)); - - // Make components - Eigen::SparseMatrix P_ss = vectorsToSparseMatrix( child_s, - parent_s, - v1_s, - n_s ); - Eigen::SparseMatrix D_ss = vectorsToSparseMatrix( child_s, - child_s, - v2_s, - n_s ); - Eigen::SparseMatrix invD_ss( n_s, n_s ); - for( int s=0; s DminusP_ss = D_ss - P_ss; - Eigen::SparseMatrix Q = DminusP_ss.transpose() * invD_ss * DminusP_ss; - return Q; -} - -// Functions to evaluate density for nearest-neighbors Gaussian process -template -vector covariance_function(vector d, Type sigma2, Type inv_range) { - return ((-d.array() * inv_range).exp() * sigma2).matrix(); -} -template -matrix covariance_function(matrix d, Type sigma2, Type inv_range) { - return ((-d.array() * inv_range).exp() * sigma2).matrix(); -} -/** \brief Object containing all data elements of an NNGP */ -template -struct nngp_data_t{ - vector nn_index_flat; - vector nn_len; - vector dist_to_nn_flat; - vector dist_within_nn_flat; - vector gp_order; - - // Define output - nngp_data_t(SEXP x){ /* x = List passed from R */ - nn_index_flat = asVector(getListElement(x,"nn_index_flat")); - nn_len = asVector(getListElement(x,"nn_len")); - dist_to_nn_flat = asVector(getListElement(x,"dist_to_nn_flat")); - dist_within_nn_flat = asVector(getListElement(x,"dist_within_nn_flat")); - gp_order = asVector(getListElement(x,"gp_order")); - } -}; -// Density function .. sigma2 fixed at 1.0 -template -Type NNGP( Type sigma2, - Type range, - vector field_s, - // Data - nngp_data_t nngp_data ){ - - // Using original order and ordered_structure, by calling gp_order(i) and gp_order(nn_ids), because: - // 1. using original version in new order is very slow! presumably the order is terrible for the inner Hessian - // 2. using re-ordered version of field is confusing for users - Type nll = 0.0; - Type inv_range = 1.0 / range; // Multiplication is faster than division - vector nn_index_flat = nngp_data.nn_index_flat; - //vector nn_start = nngp_data.nn_start; - vector nn_len = nngp_data.nn_len; - vector dist_to_nn_flat = nngp_data.dist_to_nn_flat; - vector dist_within_nn_flat = nngp_data.dist_within_nn_flat; - vector gp_order = nngp_data.gp_order; - int n = field_s.size(); - - int pos_mat = 0; - int pos_vec = 0; - for( int i = 0; i < n; i++ ){ - int k = nn_len(i); - - // No neighbors - if(k == 0){ - nll -= dnorm( field_s(gp_order(i)), Type(0.0), sqrt(sigma2), true ); - }else{ - // Extract neighbor indices and distance to neighbors - vector nn_ids(k); - vector dist_iN(k); - for (int j = 0; j < k; j++) { - nn_ids(j) = nn_index_flat(pos_vec); - dist_iN(j) = dist_to_nn_flat(pos_vec); - pos_vec++; - } - - // Extract within-neighbor distance matrix (k x k) ... - matrix dist_NN(k, k); - for (int r = 0; r < k; r++) { - for (int c = 0; c < k; c++) { - dist_NN(r, c) = dist_within_nn_flat(pos_mat); - pos_mat++; - } - } - - // Covariances - matrix Sigma_NN = covariance_function(dist_NN, sigma2, inv_range); - vector Sigma_iN = covariance_function(dist_iN, sigma2, inv_range); - - // Solve - //vector a_i = solve(Sigma_NN, Sigma_iN); - //vector a_i = Sigma_NN.ldlt().solve( Sigma_iN.matrix() ); - //Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > invSigma_NN; - //invSigma_NN.compute(Sigma_NN); - //vector a_i = invSigma_NN.solve(Sigma_iN); - matrix Sigma_NN_inv = atomic::matinv(Sigma_NN); - vector a_i = Sigma_NN_inv * Sigma_iN; - - // Residual variance - Type resid_var = sigma2 - (a_i * Sigma_iN).sum(); // + 1e-12; - - // Conditional mean - Type cond_mean = 0.0; - for (int j = 0; j < k; j++) { - cond_mean += a_i(j) * field_s(gp_order(nn_ids(j))); - } - - // Likelihood - nll -= dnorm( field_s(gp_order(i)), cond_mean, sqrt(resid_var), true ); - } - } - return nll; -} - -// Function to calculate RAM matrices -template -Eigen::SparseMatrix make_ram( matrix ram, - vector ram_start, - vector beta_z, - int n_c, - int what ){ - - Eigen::SparseMatrix out_cc(n_c, n_c); - out_cc.setZero(); - Type tmp; - - for(int r=0; r=1){ - tmp = beta_z(ram(r,3)-1); - }else{ - tmp = ram_start(r); - } - // Rho_cc - if( (ram(r,0)==1) && (what==0) ){ - out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; - } - // Gammainv_cc - if( (ram(r,0)==2) && (what==1) ){ - out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = 1 / tmp; - } - // Gamma_cc - if( (ram(r,0)==2) && (what==2) ){ - out_cc.coeffRef( ram(r,1)-1, ram(r,2)-1 ) = tmp; - } - } - - return out_cc; -} - -// distribution/projection for gamma -// Based on: -// https://github.com/meganferg/FergusonEtal_20250125_EBS_Beluga_DSM/blob/main/src/te_tw_DSM.cpp#L85C9-L85C40 (Megan Ferguson) -template -Type gamma_distribution( vector gamma_k, - vector Sdims, - vector Sblock, - Eigen::SparseMatrix S_kk, - vector log_lambda ){ - - using namespace density; - Type nll = 0.0; - int start_gamma = 0; // Counter for gamma - int start_k = 0; // counter for columns of S_kk - int index_lambda = 0; - for(int z=0; z gamma_segment = gamma_k.segment(start_gamma, ngamma_z); - start_gamma += ngamma_z; - - // s() splines - if( Sblock(z) == 1 ){ - // Recover S_block - Eigen::SparseMatrix S_block = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i - - /// Quadratic-form GRMF - // GMRF(Q).Quadform(x) caused a problem calculating the log-determinant unnecessarily, resulting in valgrind error - //nll -= Type(0.5)*Type(m_z)*log_lambda(z) - Type(0.5)*exp(log_lambda(z))*GMRF(S_block).Quadform(gamma_segment); - nll -= Type(0.5)*Type(ngamma_z)*log_lambda(index_lambda) - Type(0.5) * exp(log_lambda(index_lambda)) * - (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); - - start_k += ngamma_z; - index_lambda += 1; - } - - // te() / ti() / t2() splines - if( Sblock(z) >= 2 ){ - // Recover S_block ... Eigen::SparseMatrix appears to initialize as empty so no .setZero() equivalent needed - Eigen::SparseMatrix S_block( ngamma_z, ngamma_z ); - for( int block=0; block < Sblock(z); block ++ ){ - Eigen::SparseMatrix S_tmp = S_kk.block(start_k, start_k, ngamma_z, ngamma_z); // Recover S_i - S_block += exp(log_lambda(index_lambda)) * S_tmp; - start_k += ngamma_z; - index_lambda++; - } - - /// Quadratic-form GRMF - nll -= 0.5*(atomic::logdet(matrix(S_block))) - 0.5 * - (gamma_segment.matrix().transpose()*(S_block * gamma_segment.matrix())).sum(); - } - } - return( nll ); -} - -// distribution/projection for omega -template -tmbutils::array omega_distribution( tmbutils::array omega_sc, - vector model_options, - Eigen::SparseMatrix Rho_cc, - Eigen::SparseMatrix Gamma_cc, - Eigen::SparseMatrix Gammainv_cc, - Eigen::SparseMatrix Q_ss, - Type range, - nngp_data_t nngp_data, - Type &nll ){ - - if( omega_sc.size() > 0 ){ - int n_c = omega_sc.dim(1); - using namespace density; - Eigen::SparseMatrix I_cc( n_c, n_c ); - I_cc.setIdentity(); - if( omega_sc.size()>0 ){ // PARALLEL_REGION - Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; - if( model_options(1) == 0 ){ - // Separable precision ... Option-1 - //Eigen::SparseMatrix Linv_cc = Gammainv_cc * ( I_cc - Rho_cc ); - //Eigen::SparseMatrix Q_cc = Linv_cc.transpose() * Linv_cc; - - // Separable precision ... Option-2 - // Only compute Vinv_kk if Gamma_kk is full rank - Eigen::SparseMatrix V_cc = Gamma_cc.transpose() * Gamma_cc; - matrix Vinv_cc = invertSparseMatrix( V_cc ); - Eigen::SparseMatrix Vinv2_cc = asSparseMatrix( Vinv_cc ); - Eigen::SparseMatrix Q_cc = IminusRho_cc.transpose() * Vinv2_cc * IminusRho_cc; - - // GMRF for SEM: separable variable-space - nll += SEPARABLE( GMRF(Q_cc), GMRF(Q_ss) )( omega_sc ); - // Including this line with Makevars below seems to cause a crash: - // PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) - // PKG_CXXFLAGS=$(SHLIB_OPENMP_CXXFLAGS) - }else{ - // Rank-deficient (projection) method - if( model_options(0) == 7 ){ - vector omega_s( omega_sc.rows() ); - for( int ci = 0; ci < omega_sc.cols(); ci++ ){ - omega_s = omega_sc.col(ci); - nll += NNGP( Type(1.0), range, omega_s, nngp_data ); - } - }else{ - nll += SEPARABLE( GMRF(I_cc), GMRF(Q_ss) )( omega_sc ); - } - - // Sparse inverse-product - //Eigen::SparseMatrix IminusRho_cc = I_cc - Rho_cc; - Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_cc; - inverseIminusRho_cc.compute(IminusRho_cc); - - // (I-Rho)^{-1} * Gamma * Epsilon - matrix omega2_cs = Gamma_cc * omega_sc.matrix().transpose(); - matrix omega3_cs = inverseIminusRho_cc.solve(omega2_cs); - omega_sc = omega3_cs.transpose(); - } - } - } - - return omega_sc; -} - -// distribution/projection for xi -template -Type xi_distribution( vector model_options, - tmbutils::array xi_sl, - vector log_sigmaxi_l, - Eigen::SparseMatrix Q_ss, - Type range, - nngp_data_t nngp_data ){ - - Type nll = 0; - if( xi_sl.size() > 0 ){ - int n_l = xi_sl.cols(); - using namespace density; - if( model_options(0) == 7 ){ - vector xi_s( xi_sl.rows() ); - for( int l=0; l -tmbutils::array epsilon_distribution( - tmbutils::array epsilon_stc, - const vector &model_options, - const Eigen::SparseMatrix &Rho_hh, - const Eigen::SparseMatrix &Gamma_hh, - const Eigen::SparseMatrix &Gammainv_hh, - const Eigen::SparseMatrix &Q_ss, - Type range, - const nngp_data_t &nngp_data, - Type &nll ){ - - if( epsilon_stc.size() > 0 ){ - int n_s = epsilon_stc.dim(0); - int n_t = epsilon_stc.dim(1); - int n_c = epsilon_stc.dim(2); - int n_h = n_t * n_c; - using namespace density; - Eigen::SparseMatrix I_hh( n_h, n_h ); - I_hh.setIdentity(); - int h; - - //if( epsilon_stc.size()>0 ){ // PARALLEL_REGION - // Reshape for either model_options - tmbutils::array epsilon_hs( n_h, n_s ); - for( int s=0; s IminusRho_hh = I_hh - Rho_hh; - - if( model_options(1) == 0 ){ - // Separable precision ... Option-1 - //Eigen::SparseMatrix Linv_hh = Gammainv_hh * ( I_hh - Rho_hh ); - //Eigen::SparseMatrix Q_hh = Linv_hh.transpose() * Linv_hh; - - // Separable precision ... Option-2 - // Only compute Vinv_kk if Gamma_kk is full rank - Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; - matrix Vinv_hh = invertSparseMatrix( V_hh ); - Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); - Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; - - // GMRF for DSEM: non-separable time-variable, with separable space - nll += SEPARABLE( GMRF(Q_ss), GMRF(Q_hh) )( epsilon_hs ); - }else{ - // Rank-deficient (projection) method - if( model_options(0) == 7 ){ - vector epsilon_s( epsilon_hs.cols() ); - for( int hi = 0; hi < epsilon_hs.rows(); hi++ ){ - epsilon_s = epsilon_hs.matrix().row(hi); - nll += NNGP( Type(1.0), range, epsilon_s, nngp_data ); - } - }else{ - nll += SEPARABLE( GMRF(Q_ss), GMRF(I_hh) )( epsilon_hs ); - } - - // Sparse inverse-product - //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; - Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; - inverseIminusRho_hh.compute(IminusRho_hh); - - // (I-Rho)^{-1} * Gamma * Epsilon - matrix e2_hs = Gamma_hh * epsilon_hs.matrix(); - matrix e3_hs = inverseIminusRho_hh.solve(e2_hs); - - // Transformations - for( int s=0; s -tmbutils::array delta_distribution( - tmbutils::array delta_tc, - const vector &model_options, - const Eigen::SparseMatrix &Rho_hh, - const Eigen::SparseMatrix &Gamma_hh, - const Eigen::SparseMatrix &Gammainv_hh, - Type &nll ){ - - if( delta_tc.size() > 0 ){ - int n_t = delta_tc.dim(0); - int n_c = delta_tc.dim(1); - int n_h = n_t * n_c; - using namespace density; - Eigen::SparseMatrix I_hh( n_h, n_h ); - I_hh.setIdentity(); - int h; - - // Reshape for either model_options - tmbutils::array delta_h1( n_h, 1 ); - for( int t=0; t IminusRho_hh = I_hh - Rho_hh; - - if( model_options(1) == 0 ){ - Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; - matrix Vinv_hh = invertSparseMatrix( V_hh ); - Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); - Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; - - // GMRF for DSEM: non-separable time-variable, with separable space - nll += GMRF(Q_hh)( delta_h1 ); - }else{ - // Rank-deficient (projection) method - nll += GMRF(I_hh)( delta_h1 ); - - // Sparse inverse-product - //Eigen::SparseMatrix IminusRho_hh = I_hh - Rho_hh; - Eigen::SparseLU< Eigen::SparseMatrix, Eigen::COLAMDOrdering > inverseIminusRho_hh; - inverseIminusRho_hh.compute(IminusRho_hh); - - // (I-Rho)^{-1} * Gamma * Epsilon - matrix e2_h1 = Gamma_hh * delta_h1.matrix(); - matrix e3_h1 = inverseIminusRho_hh.solve(e2_h1); - - // Transformations - for( int t=0; t -bool isNA(Type x){ - return R_IsNA(asDouble(x)); -} - -// Sparse array * matrix -// NAs in IVECTOR or IMATRIX get converted to -2147483648, so isNA doesn't work ... instead drop NAs from A prior to passing to TMB -template -vector multiply_epsilon( - const matrix &A, - const vector &weight, - tmbutils::array x, - int n_i ){ - - vector out( n_i ); - out.setZero(); - if( x.size() > 0 ){ - for( int z=0; z -vector multiply_omega( - const matrix &A, - const vector &weight, - tmbutils::array x, - int n_i ){ - - vector out( n_i ); - out.setZero(); - if( x.size() > 0 ){ - for( int z=0; z -vector multiply_xi( - const Eigen::SparseMatrix &A_is, - tmbutils::array xi_sl, - const matrix &W_il ){ - - vector out( W_il.rows() ); - out.setZero(); - if( xi_sl.size() > 0 ){ - matrix xi_il = A_is * xi_sl.matrix(); - for( int i=0; i -vector multiply_delta( - tmbutils::array delta_tc, - const vector &t_i, - const vector &c_i, - int n_i ){ - - vector delta_i( n_i ); - delta_i.setZero(); - if( delta_tc.size() > 0 ){ - for( int i=0; i -Type sign(Type x){ - return x / pow(pow(x,2),0.5); -} - -// dlnorm -template -Type dlnorm( - Type x, - Type meanlog, - Type sdlog, - int give_log=0){ - - //return 1/(sqrt(2*M_PI)*sd) * exp(-.5*pow((x-mean)/sd,2)); - Type logres = dnorm( log(x), meanlog, sdlog, true) - log(x); - if(give_log) return logres; else return exp(logres); -} - -// dlnorm -template -Type dbinom_custom( - Type x, - Type log_prob, - Type log_one_minus_prob, - Type size, - int give_log = 0 ){ - - // size choose x - Type logres = lgamma(size + 1.0) - lgamma(x + 1.0) - lgamma(size - x + 1.0); - // p^x * (1-p)^(size-x) - logres += x * log_prob + (size-x) * log_one_minus_prob; - if(give_log) return logres; else return exp(logres); -} - -// dlnorm -template -Type devresid_binom( - Type y, - Type weight, // weight = size - Type mu ){ - - Type y_weight = y * weight; - Type mu_weight = mu * weight; - Type p1, p2; - if(y_weight == 0){ - p1 = 0.0; - }else{ - p1 = y_weight * log(y_weight / mu_weight); - } - if( (weight - y_weight) == 0 ){ - p2 = 0.0; - }else{ - p2 = (weight - y_weight) * log( (weight - y_weight) / (weight - mu_weight) ); - } - Type devresid = sign(y - mu) * pow(2 * (p1 + p2), 0.5); - return devresid; -} - -// Deviance for the Tweedie -// https://en.wikipedia.org/wiki/Tweedie_distribution#Properties -template -Type devresid_tweedie( - Type y, - Type mu, - Type p ){ - - Type c1 = pow( y, 2.0-p ) / (1.0-p) / (2.0-p); - Type c2 = y * pow( mu, 1.0-p ) / (1.0-p); - Type c3 = pow( mu, 2.0-p ) / (2.0-p); - Type deviance = 2 * (c1 - c2 + c3 ); - Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); - return devresid; -} - -// Deviance for the student-T -// from chatGPT (experimental) ... converges on Gaussian as df -> Inf -template -Type devresid_student( - Type y, - Type mu, - Type sigma, - Type df ){ - - Type deviance = (df + 1.0) * log( 1.0 + pow(y-mu,2.0) / (df * sigma*sigma) ); - Type devresid = sign( y - mu ) * pow( deviance, 0.5 ); - return devresid; -} - -// COPIED from sdmTMB.cpp in sdmTMB package on Nov. 14, 2025 -template -Type dstudent( - Type x, - Type mean, - Type sigma, - Type df, - int give_log = 0) { - - // from metRology::dt.scaled() - // dt((x - mean)/sd, df, ncp = ncp, log = TRUE) - log(sd) - Type logres = dt((x - mean) / sigma, df, true) - log(sigma); - if (give_log) - return logres; - else - return exp(logres); -} - -// Deviance for the Negative binomial -//template -//Type devresid_nbinom1( Type y, -// Type logmu, -// Type logtheta ){ -// -// // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu -// Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), log(y + Type(1e-10)) + logtheta, true ); -// Type logp2 = dnbinom_robust( y, logmu, logmu + logtheta, true ); -// Type deviance = 2 * (logp1 - logp2); -// Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); -// return devresid; -//} -template -Type devresid_nbinom2( - Type y, - Type logmu, - Type logtheta ){ - - // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - Type logp1 = dnbinom_robust( y, log(y + Type(1e-10)), Type(2.0) * log(y + Type(1e-10)) - logtheta, true ); - Type logp2 = dnbinom_robust( y, logmu, Type(2.0) * logmu - logtheta, true ); - Type deviance = 2 * (logp1 - logp2); - Type devresid = sign( y - exp(logmu) ) * pow( deviance, 0.5 ); - return devresid; -} - - -// distribution/projection for epsilon -// deviance = deviance1 + deviance2 -template -Type one_predictor_likelihood( - Type &y, - Type p, - Type size, - int link, - int family, - vector log_sigma_segment, - Type &nll, - Type &devresid, - objective_function* of ){ - - Type mu, logmu, log_one_minus_mu; - //Type devresid = 0; - - switch( link ){ - case identity_link: - mu = p; - logmu = log( p ); - log_one_minus_mu = log( Type(1.0) - mu ); - break; - case log_link: - mu = exp(p); - logmu = p; - log_one_minus_mu = log( Type(1.0) - mu ); - break; - case logit_link: - mu = invlogit(p); - //logmu = log(mu); - logmu = p - logspace_add( Type(0.0), p ); - //log_one_minus_mu = log( invlogit(-1 * p) ); - log_one_minus_mu = 0.0 - logspace_add( Type(0.0), p ); - break; - case cloglog_link: - mu = Type(1.0) - exp( -1 * exp(p) ); - logmu = logspace_sub( Type(0.0), -1.0 * exp(p) ); - log_one_minus_mu = -1.0 * exp(p); - break; - default: - error("Link not implemented."); - } - if( !R_IsNA(asDouble(y)) ){ - // Distribution - switch( family ){ - case gaussian_family: - nll = -1 * dnorm( y, mu, exp(log_sigma_segment(0)), true ); - devresid = y - mu; - if(isDouble::value && of->do_simulate){ - y = rnorm( mu, exp(log_sigma_segment(0)) ); - } - break; - case tweedie_family: - nll = -1 * dtweedie( y, mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); - devresid = devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); - if(isDouble::value && of->do_simulate){ - y = rtweedie( mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); - } - break; - case lognormal_family: - nll = -1 * dlnorm( y, logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); - devresid = log(y) - ( logmu - 0.5*exp(2.0*log_sigma_segment(0)) ); - if(isDouble::value && of->do_simulate){ - y = exp(rnorm( logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); - } - break; - case poisson_family: - nll = -1 * dpois( y, mu, true ); - devresid = sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); - if(isDouble::value && of->do_simulate){ - y = rpois( mu ); - } - break; - case binomial_family: - //if(y==0){ - // nll = -1 * log_one_minus_mu; - //}else{ - // nll = -1 * logmu; - //} - nll = -1 * dbinom_custom( y * size, logmu, log_one_minus_mu, size, true ); - if(isDouble::value && of->do_simulate){ - y = rbinom( size, mu ); - } - // TODO: Update deviance residual for Trials = size - //devresid = sign(y - mu) * pow(-2*((1-y)*log(1.0-mu) + y*log(mu)), 0.5); - devresid = devresid_binom( y, size, mu ); - break; - case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 - nll = -1 * dgamma( y, exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)), true ); - devresid = sign(y - mu) * pow(2 * ( (y-mu)/mu - log(y/mu) ), 0.5); - if(isDouble::value && of->do_simulate){ - y = rgamma( exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)) ); - } - break; - case nbinom1_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) - // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu - nll = -1 * dnbinom_robust( y, logmu, logmu + log_sigma_segment(0), true); - devresid = devresid_nbinom2( y, logmu, logmu - log_sigma_segment(0) ); // theta = mu / phi - if(isDouble::value && of->do_simulate){ - // rnbinom2( mu, var ) - y = rnbinom2( mu, mu * (Type(1.0) + exp(log_sigma_segment(0))) ); - } - break; - case nbinom2_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) - // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - nll = -1 * dnbinom_robust( y, logmu, Type(2.0) * logmu - log_sigma_segment(0), true); - devresid = devresid_nbinom2( y, logmu, log_sigma_segment(0) ); - if(isDouble::value && of->do_simulate){ - // rnbinom2( mu, var ) - y = rnbinom2( mu, mu * (Type(1.0) + mu / exp(log_sigma_segment(0))) ); - } - break; - case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) - // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - nll = -1 * dstudent( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); - devresid = devresid_student( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)) ); - if(isDouble::value && of->do_simulate){ - y = mu + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); - } - break; - default: - error("Distribution not implemented."); - } - } - - return mu; -} - -// distribution/projection for epsilon -template -Type two_predictor_likelihood( - Type &y, - Type p1, - Type p2, - Type size, - vector link, - vector family, - vector log_sigma_segment, - int poislink, - Type &nll, - Type &dev, - objective_function* of ){ - - Type mu1, logmu1, mu2, logmu2, log_one_minus_mu1; - - // First link - if( poislink==0 ){ - mu1 = invlogit( p1 ); - logmu1 = log( mu1 ); - log_one_minus_mu1 = log( Type(1.0) - mu1 ); - // second link - switch( link(1) ){ - case identity_link: - mu2 = p2; - logmu2 = log( p2 ); - break; - case log_link: - mu2 = exp(p2); - logmu2 = p2; - break; - default: - error("Link not implemented."); - } - }else{ - mu1 = Type(1.0) - exp( -1.0*exp(p1) ); - logmu1 = logspace_sub( Type(0.0), -1*exp(p1) ); - log_one_minus_mu1 = -1.0*exp(p1); - mu2 = exp( p1 + p2 ) / mu1; - logmu2 = p1 + p2 - logmu1; - } - if( !R_IsNA(asDouble(y)) ){ - // Distribution - if(isDouble::value && of->do_simulate){ - y = rbinom( Type(1), mu1 ); - } - if( y == 0 ){ - nll = -1 * log_one_minus_mu1; - dev = -2 * log_one_minus_mu1; - } - if( y>0 ){ // Not if-else so y>0 triggered when simulating y>0 - nll = -1 * logmu1; - dev = -2 * logmu1; - //deviance1_i(i) = -2 * log_mu1(i); - switch( family(1) ){ - case gaussian_family: - nll -= dnorm( y, mu2, exp(log_sigma_segment(0)), true ); - dev += pow(y - mu2, 2.0); - if(isDouble::value && of->do_simulate){ - y = rnorm( mu2, exp(log_sigma_segment(0)) ); - } - break; - //case tweedie_family: - // nll -= dtweedie( y, mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); - // devresid += devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); - // if(isDouble::value && of->do_simulate){ - // y = rtweedie( mu2, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); - // } - // break; - case lognormal_family: - nll -= dlnorm( y, logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); - dev += pow( log(y) - (logmu2 - 0.5*exp(2.0*log_sigma_segment(0))), 2.0 ); - if(isDouble::value && of->do_simulate){ - y = exp(rnorm( logmu2 - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); - } - break; - //case poisson_family: - // nll -= dpois( y, mu2, true ); - // devresid += sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); - // if(isDouble::value && of->do_simulate){ - // y = rpois( mu2 ); - // } - // break; - // case 4: // Bernoulli - case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 - nll -= dgamma( y, exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)), true ); - dev += 2 * ( (y-mu2)/mu2 - log(y/mu2) ); - if(isDouble::value && of->do_simulate){ - y = rgamma( exp(-2.0*log_sigma_segment(0)), mu2*exp(2.0*log_sigma_segment(0)) ); - } - break; - case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) - // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - nll -= dstudent( y, mu2, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); - //dev = NAN; - if(isDouble::value && of->do_simulate){ - y = mu2 + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); - } - break; - default: - error("Distribution not implemented."); - } - } - } - - return mu1 * mu2; -} - -} // namespace tinyVAST diff --git a/src/utils.h b/src/utils.h index 2bf5805d..5aeab8ba 100644 --- a/src/utils.h +++ b/src/utils.h @@ -107,7 +107,7 @@ struct spde_covariates_t{ template Eigen::SparseMatrix G_spde_covariates( const spde_covariates_t &spde, - const matrix &H_jj, + matrix H_jj, //matrix V_zk, const vector &triangle_k ){ @@ -268,11 +268,12 @@ struct nngp_data_t{ }; // Density function .. sigma2 fixed at 1.0 template -Type NNGP( Type sigma2, - Type range, - vector field_s, - // Data - nngp_data_t nngp_data ){ +Type NNGP( + Type sigma2, + Type range, + vector field_s, + // Data + const nngp_data_t &nngp_data ){ // Using original order and ordered_structure, by calling gp_order(i) and gp_order(nn_ids), because: // 1. using original version in new order is very slow! presumably the order is terrible for the inner Hessian @@ -345,11 +346,12 @@ Type NNGP( Type sigma2, // Function to calculate RAM matrices template -Eigen::SparseMatrix make_ram( matrix ram, - vector ram_start, - vector beta_z, - int n_c, - int what ){ +Eigen::SparseMatrix make_ram( + const matrix &ram, + vector ram_start, + vector beta_z, + int n_c, + int what ){ Eigen::SparseMatrix out_cc(n_c, n_c); out_cc.setZero(); @@ -383,11 +385,12 @@ Eigen::SparseMatrix make_ram( matrix ram, // Based on: // https://github.com/meganferg/FergusonEtal_20250125_EBS_Beluga_DSM/blob/main/src/te_tw_DSM.cpp#L85C9-L85C40 (Megan Ferguson) template -Type gamma_distribution( vector gamma_k, - vector Sdims, - vector Sblock, - Eigen::SparseMatrix S_kk, - vector log_lambda ){ +Type gamma_distribution( + vector gamma_k, + vector Sdims, + vector Sblock, + const Eigen::SparseMatrix &S_kk, + vector log_lambda ){ using namespace density; Type nll = 0.0; @@ -436,15 +439,16 @@ Type gamma_distribution( vector gamma_k, // distribution/projection for omega template -tmbutils::array omega_distribution( tmbutils::array omega_sc, - vector model_options, - Eigen::SparseMatrix Rho_cc, - Eigen::SparseMatrix Gamma_cc, - Eigen::SparseMatrix Gammainv_cc, - Eigen::SparseMatrix Q_ss, - Type range, - nngp_data_t nngp_data, - Type &nll ){ +tmbutils::array omega_distribution( + tmbutils::array omega_sc, + vector model_options, + const Eigen::SparseMatrix &Rho_cc, + const Eigen::SparseMatrix &Gamma_cc, + const Eigen::SparseMatrix &Gammainv_cc, + const Eigen::SparseMatrix &Q_ss, + Type range, + const nngp_data_t &nngp_data, + Type &nll ){ if( omega_sc.size() > 0 ){ int n_c = omega_sc.dim(1); @@ -500,12 +504,13 @@ tmbutils::array omega_distribution( tmbutils::array omega_sc, // distribution/projection for xi template -Type xi_distribution( vector model_options, - tmbutils::array xi_sl, - vector log_sigmaxi_l, - Eigen::SparseMatrix Q_ss, - Type range, - nngp_data_t nngp_data ){ +Type xi_distribution( + vector model_options, + tmbutils::array xi_sl, + vector log_sigmaxi_l, + const Eigen::SparseMatrix &Q_ss, + Type range, + const nngp_data_t &nngp_data ){ Type nll = 0; if( xi_sl.size() > 0 ){ From ba12db2b1899cbd5f1dd591ac4bc2b04afe66757 Mon Sep 17 00:00:00 2001 From: James Thorson Date: Mon, 13 Jul 2026 21:25:55 -0700 Subject: [PATCH 17/37] Update R-CMD-check.yaml --- .github/workflows/R-CMD-check.yaml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index b836a671..b1babc23 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -84,3 +84,17 @@ jobs: upload-snapshots: true args: 'c("--no-manual", "--as-cran", "--ignore-vignettes", "--no-build-vignettes")' build_args: 'c("--no-manual", "--no-build-vignettes")' + + - name: Build tar.gz for CRAN submission + if: matrix.config.os == 'ubuntu-latest' && matrix.config.r == 'release' + run: | + install.packages('pkgbuild') + pkgbuild::build(".", dest_path = ".", vignettes = TRUE) + shell: Rscript {0} + + - name: Upload tar.gz + if: matrix.config.os == 'ubuntu-latest' && matrix.config.r == 'release' + uses: actions/upload-artifact@v4 + with: + name: tinyVAST-tarball + path: '*.tar.gz' From bffa0ab1a96b3b254194e1e303f49d358b48ea6e Mon Sep 17 00:00:00 2001 From: Sean Anderson Date: Wed, 7 Oct 2026 07:52:16 -0700 Subject: [PATCH 18/37] Model fitting speed ups (#140) * Speed up model fitting; see details - With help from Claude's Opus 5.5, did some extensive benchmarking trying to figure out why tinyVAST was slower than sdmTMB for relatively large SPDE models. Here's what we came up with. - Overall, ~25-30% faster - Somewhat reduced memory too Changes: - Vectorize apply() over A-matrix on R side (easy win) - Put tau in GMRF densities - Make DATA_UPDATE(weights_i) optional; it's slower - Change nll lines from -1 * d() to -d(); trivial but strangely seems to interact with DATA_UPDATE speed-up - Models also seem to often take more nlminb iterations to converge; Could be due to parameterization of marginal SD as leading parameter rather than 'tau', but that's a more major structural change that may not be worth it. * Fix 2 unit tests * Delete extra comment * Fix #141 * Use sampled params for future with project(parm_var = TRUE) Future Rho/Gamma and Q_ss were built from the fitted parameters rather than the sampled draw, so parameter uncertainty didn't propagate into projected process errors * Add nsim to project() and build TMB objects once across samples *Much* faster * Condition future epsilon on separate time and space precisions in project() * Use report-only TMB objects in project() Faster again * Pass full unmapped parameter lists to report objects in project() --- R/fit.R | 16 +- R/predict.R | 4 +- R/project.R | 244 +++++++++----------- R/utility.R | 2 +- man/project.Rd | 29 +-- man/tinyVASTcontrol.Rd | 7 +- src/tinyVAST.cpp | 50 ++-- src/utils.h | 35 +-- tests/testthat/test-basic-fits.R | 14 +- tests/testthat/test-index-standardization.R | 4 +- tests/testthat/test-smooths.R | 15 +- 11 files changed, 212 insertions(+), 208 deletions(-) diff --git a/R/fit.R b/R/fit.R index a5e21e8c..3337f4af 100644 --- a/R/fit.R +++ b/R/fit.R @@ -604,7 +604,7 @@ function( formula, # Aepsilon_zz = cbind(Atriplet$i, Atriplet$j, t_i[Atriplet$i], c_i[Atriplet$i]) - which_Arows = which(apply( Aepsilon_zz, MARGIN=1, FUN=function(x) all(!is.na(x)) & any(x>0) )) + which_Arows = which( rowSums(is.na(Aepsilon_zz))==0 & rowSums(Aepsilon_zz>0, na.rm=TRUE)>0 ) which_Arows = which_Arows[ which(Atriplet$x[which_Arows] > 0) ] if( (nrow(spacetime_term_ram$output$ram)==0) & (nrow(delta_spacetime_term_ram$output$ram)==0) ){ which_Arows = numeric(0) @@ -614,7 +614,7 @@ function( formula, # Aomega_zz = cbind(Atriplet$i, Atriplet$j, c_i[Atriplet$i]) - which_Arows = which(apply( Aomega_zz, MARGIN=1, FUN=function(x) all(!is.na(x)) )) + which_Arows = which( rowSums(is.na(Aomega_zz))==0 ) which_Arows = which_Arows[ which(Atriplet$x[which_Arows] > 0) ] if( (nrow(space_term_ram$output$ram)==0) & (nrow(delta_space_term_ram$output$ram)==0) ){ which_Arows = numeric(0) @@ -799,7 +799,8 @@ function( formula, ifelse( control$gmrf_parameterization=="separable", 0, 1), ifelse( isFALSE(control$get_rsr), 0, 1), ifelse( isFALSE(control$extra_reporting), 0, 1), - 0 + 0, + ifelse( isTRUE(control$update_weights), 1, 0) ) # make dat @@ -1307,6 +1308,9 @@ function( formula, #' in the SPDE method when using \code{add_mesh_covariates}. The #' default \code{barrier_stiffness = 0.01} is the value from Bakka et al. #' 2019. +#' @param update_weights Whether to allow \code{weights_i} to be changed via +#' \code{obj$env$data} without re-taping (e.g., for stochastic gradient +#' descent). This slows down fitting for large datasets. #' #' @references #' Bakka, H., Vanhatalo, J., Illian, J., Simpson, D., Rue, H. (2019). Non-stationary Gaussian models with physical barriers. Spatial Statistics, 29, 268-288. \doi{10.1016/j.spasta.2019.01.002} @@ -1343,7 +1347,8 @@ function( opt_loops = 1, extra_reporting = FALSE, use_anisotropy = FALSE, sar_adjacency = "queen", - barrier_stiffness = 0.01 ){ + barrier_stiffness = 0.01, + update_weights = FALSE ){ gmrf_parameterization = match.arg(gmrf_parameterization) #optimizer = match.arg(optimizer) @@ -1383,7 +1388,8 @@ function( opt_loops = 1, extra_reporting = extra_reporting, use_anisotropy = use_anisotropy, sar_adjacency = sar_adjacency, - barrier_stiffness = barrier_stiffness + barrier_stiffness = barrier_stiffness, + update_weights = update_weights ), class = "tinyVASTcontrol" ) } diff --git a/R/predict.R b/R/predict.R index defa5c5b..eddda794 100644 --- a/R/predict.R +++ b/R/predict.R @@ -629,7 +629,7 @@ function( object, # AepsilonG_zz = cbind(predAtriplet$i, predAtriplet$j, t_g[predAtriplet$i], c_g[predAtriplet$i]) - which_Arows = which(apply( AepsilonG_zz, MARGIN=1, FUN=\(x) all(!is.na(x)) & any(x>0) )) + which_Arows = which( rowSums(is.na(AepsilonG_zz))==0 & rowSums(AepsilonG_zz>0, na.rm=TRUE)>0 ) which_Arows = which_Arows[ which(predAtriplet$x[which_Arows] > 0) ] if( (nrow(object$internal$spacetime_term_ram$output$ram)==0) & (nrow(object$internal$delta_spacetime_term_ram$output$ram)==0) ){ which_Arows = numeric(0) @@ -639,7 +639,7 @@ function( object, # AomegaG_zz = cbind(predAtriplet$i, predAtriplet$j, c_g[predAtriplet$i]) - which_Arows = which(apply( AomegaG_zz, MARGIN=1, FUN=\(x) all(!is.na(x)) )) + which_Arows = which( rowSums(is.na(AomegaG_zz))==0 ) which_Arows = which_Arows[ which(predAtriplet$x[which_Arows] > 0) ] if( (nrow(object$internal$space_term_ram$output$ram)==0) & (nrow(object$internal$delta_space_term_ram$output$ram)==0) ){ which_Arows = numeric(0) diff --git a/R/project.R b/R/project.R index 8edbc1e7..0b801949 100644 --- a/R/project.R +++ b/R/project.R @@ -87,9 +87,11 @@ function( Q, #' condition of the forecast #' @param parm_var logical indicating whether to re-sample fixed effects from their #' predictive distribution, thus changing the GMRF for future process errors +#' @param nsim number of samples #' #' @return -#' A vector of values corresponding to rows in \code{newdata} +#' A vector of values corresponding to rows in \code{newdata}, or a matrix +#' with a column for each sample when \code{nsim > 1} #' #' @examples #' # Convert to long-form @@ -139,18 +141,15 @@ function( Q, #' extra_times = length(x) + 1:100 #' n_sims = 10 #' newdata = data.frame( "time" = c(seq_along(x),extra_times), "var" = "y" ) -#' Y = NULL -#' for(i in seq_len(n_sims) ){ -#' tmp = project( -#' mytiny, -#' newdata = newdata, -#' extra_times = extra_times, -#' future_var = TRUE, -#' past_var = TRUE, -#' parm_var = TRUE -#' ) -#' Y = cbind(Y, tmp) -#' } +#' Y = project( +#' mytiny, +#' newdata = newdata, +#' extra_times = extra_times, +#' future_var = TRUE, +#' past_var = TRUE, +#' parm_var = TRUE, +#' nsim = n_sims +#' ) #' matplot( x = row(Y), #' y = Y, #' type = "l", lty = "solid", col = "black" ) @@ -164,31 +163,31 @@ function( object, what = "mu_g", future_var = TRUE, past_var = FALSE, - parm_var = FALSE ){ + parm_var = FALSE, + nsim = 1 ){ ############## # Step 1: Generate uncertainty from parm_var and past_var, - # and load into parlist + # and load into columns of parmat ############## if( isFALSE(parm_var) & isFALSE(past_var) ){ - parlist = object$internal$parlist + parmat = object$obj$env$last.par.best %o% rep(1, nsim) } if( isTRUE(parm_var) & isFALSE(past_var) ){ stop("option not available") } if( isFALSE(parm_var) & isTRUE(past_var) ){ - parvec = object$obj$env$last.par.best - MC = object$obj$env$MC( keep=TRUE, n=1, antithetic=FALSE ) - parvec[object$obj$env$lrandom()] = attr(MC, "samples") - parlist = object$obj$env$parList( par = parvec ) + parmat = object$obj$env$last.par.best %o% rep(1, nsim) + MC = object$obj$env$MC( keep=TRUE, n=nsim, antithetic=FALSE ) + parmat[object$obj$env$lrandom(),] = attr(MC, "samples") } if( isTRUE(parm_var) & isTRUE(past_var) ){ if(is.null(object$sdrep$jointPrecision)) stop("Rerun with `getJointPrecision=TRUE`") - parvec = rmvnorm_prec( mu = object$obj$env$last.par.best, - prec = object$sdrep$jointPrecision ) - parlist = object$obj$env$parList( par = parvec ) + parmat = rmvnorm_prec( mu = object$obj$env$last.par.best, + prec = object$sdrep$jointPrecision, + n = nsim ) } ############## @@ -202,15 +201,15 @@ function( object, ############## new_control = object$internal$control - new_control$run_model = TRUE - new_control$nlminb_loops = 0 + new_control$run_model = FALSE + new_control$opt_loops = 0 new_control$newton_loops = 0 new_control$getsd = FALSE new_control$calculate_deviance_explained = FALSE new_control$suppress_user_warnings = TRUE new_control$extra_reporting = TRUE - newobj = tinyVAST( + new_inputs = tinyVAST( formula = object$formula, data = object$data, time_term = object$internal$time_term, @@ -235,12 +234,15 @@ function( object, development = object$internal$development ) - # - newpar = newobj$obj$env$last.par - oldpar = object$obj$env$last.par.best - tmb_fixed = setdiff(unique(names(newpar)), newobj$tmb_inputs$tmb_random) - newpar[ (names(newpar) %in% tmb_fixed) ] = oldpar[ (names(oldpar) %in% tmb_fixed) ] - newrep = newobj$obj$report( newpar ) + # REPORT uses expanded parameter lists, so omit both maps and random effects. + # parList() on the fitted object restores fixed and shared mapped values. + newobj = object + newobj$tmb_inputs = new_inputs + newobj$internal$times = all_times + newobj$obj = MakeADFun( data = new_inputs$tmb_data, + parameters = new_inputs$tmb_par, + silent = TRUE, + DLL = "tinyVAST" ) ############## # Step 4: Merge ParList and ParList1 @@ -270,27 +272,24 @@ function( object, IminusRho_hh = Matrix::Diagonal(n=nrow(newrep$Rho_hh)) - newrep$Rho2_hh Q_kk = Matrix::t(IminusRho_hh) %*% Matrix::solve(Matrix::t(newrep$Gamma2_hh) %*% newrep$Gamma2_hh) %*% IminusRho_hh } - Q_hh = Matrix::kronecker( Q_kk, Q_ss ) # - grid = expand.grid( s = seq_len(dim(neweps_stc)[1]), - t = all_times, + grid = expand.grid( t = all_times, c = object$internal$variables ) - grid$num = seq_len(prod(dim(neweps_stc))) + grid$num = seq_len(nrow(grid)) observed_idx = subset( grid, t %in% object$internal$times )$num - - # - tmp = conditional_gmrf( - Q = Q_hh, - observed_idx = observed_idx, - x_obs = as.vector( eps_stc ), - n_sims = 1, - what = ifelse(future_var, "simulate", "predict") - ) + unobserved_idx = setdiff( grid$num, observed_idx ) + + # Precision is kronecker( Q_kk, Q_ss ) and past times include all sites, so the + # conditional mean only needs Q_kk and the conditional precision is kronecker( Q_uu, Q_ss ) + Q_uu = Q_kk[unobserved_idx, unobserved_idx, drop = FALSE] + Q_uo = Q_kk[unobserved_idx, observed_idx, drop = FALSE] + eps_so = matrix( eps_stc, nrow = dim(eps_stc)[1] ) + simeps_h = -1 * as.matrix( eps_so %*% Matrix::t(Matrix::solve(Q_uu, Q_uo)) ) if( isTRUE(future_var) ){ - simeps_h = tmp[,1] - }else{ - simeps_h = tmp$mean + # Columns have precision Q_ss, and are then correlated to have precision Q_uu among columns + z_su = rmvnorm_prec( prec = Q_ss, n = length(unobserved_idx) ) + simeps_h = simeps_h + t( backsolve(chol(as.matrix(Q_uu)), t(z_su)) ) } # Compile @@ -363,105 +362,74 @@ function( object, return(newdelta_tc) } - # - new_parlist = newobj$tmb_inputs$tmb_par - #new_parlist = newobj$tmb_par - Q_ss = object$rep$Q_ss - - # Replace epsilon - new_parlist$epsilon_stc = augment_epsilon( - #beta_z = parlist$beta_z, - eps_stc = parlist$epsilon_stc, - neweps_stc = new_parlist$epsilon_stc, - #model = object$internal$spacetime_term_ram$output$model, - linpred = 1 - ) - new_parlist$epsilon2_stc = augment_epsilon( - #beta_z = parlist$beta2_z, - eps_stc = parlist$epsilon2_stc, - neweps_stc = new_parlist$epsilon2_stc, - #model = object$internal$delta_spacetime_term_ram$output$model, - linpred = 2 - ) - - # Replace delta - new_parlist$delta_tc = augment_delta( - #nu_z = parlist$nu_z, - delta_tc = parlist$delta_tc, - newdelta_tc = new_parlist$delta_tc, - #model = object$internal$time_term_ram$output$model, - linpred = 1 - ) - new_parlist$delta2_tc = augment_delta( - #nu_z = parlist$nu2_z, - delta_tc = parlist$delta2_tc, - newdelta_tc = new_parlist$delta2_tc, - #model = object$internal$delta_time_term_ram$output$model, - linpred = 2 - ) + ############## + # Step 5: Re-build model + ############## - # Replace other variables that are not changed - same_vars = setdiff( names(new_parlist), c("epsilon_stc","epsilon2_stc","delta_tc","delta2_tc") ) - new_parlist[same_vars] = parlist[same_vars] + # Build prediction object once, and then REPORT for each sample + predobj = MakeADFun( data = add_predictions( object = newobj, newdata = newdata ), + parameters = newobj$tmb_inputs$tmb_par, + type = "Fun", + silent = TRUE, + DLL = "tinyVAST" ) ############## - # Step 5: Re-build model + # Step 6: simulate samples ############## - #new_control$run_model = TRUE - new_control$tmb_par = new_parlist - new_control$extra_reporting = FALSE - #new_control$nlminb_loops = 0 - #new_control$newton_loops = 0 - #new_control$getsd = FALSE - #new_control$calculate_deviance_explained = FALSE + # Use TMB's parameter order when flattening lists for REPORT. + par_template = newobj$obj$env$parList() + same_vars = setdiff( names(par_template), c("epsilon_stc","epsilon2_stc","delta_tc","delta2_tc") ) + pred = matrix( NA, nrow = nrow(newdata), ncol = nsim ) + for( i in seq_len(nsim) ){ + parvec = parmat[,i] + parlist = object$obj$env$parList( par = parvec ) - newobj = tinyVAST( - formula = object$formula, - data = object$data, - time_term = object$internal$time_term, - space_term = object$internal$space_term, - spacetime_term = object$internal$spacetime_term, - family = object$internal$family, - space_columns = object$internal$space_columns, - spatial_domain = object$spatial_domain, - time_column = object$internal$time_column, - times = all_times, - variable_column = object$internal$variable_column, - variables = object$internal$variables, - distribution_column = object$internal$distribution_column, - delta_options = list( formula = object$internal$delta_formula, - space_term = object$internal$delta_space_term, - time_term = object$internal$delta_time_term, - spacetime_term = object$internal$delta_spacetime_term, - spatial_varying = object$internal$delta_spatial_varying ), - spatial_varying = object$internal$spatial_varying, - weights = object$internal$weights, - control = new_control, - development = object$internal$development - ) + # Copy parameters with unchanged dimensions before building future precisions. + # Process arrays retain their padded dimensions until augmented below. + new_parlist = par_template + new_parlist[same_vars] = parlist[same_vars] + newrep = newobj$obj$report( unlist(new_parlist, use.names = FALSE) ) - # CHECK SIZES ... if throwing error - if( FALSE ){ - # Check length - range( - # NEW - sapply( newobj$tmb_inputs$tmb_par, length ) - - # OLD - sapply( new_parlist, length ) - ) # - isTRUE(all.equal(new_parlist, newobj$tmb_inputs$tmb_par, tolerance=Inf)) - } + # random effects are scaled by tau, so their precision is Q_ss * tau^2 + Q_ss = newrep$Q_ss * exp(2 * newrep$log_tau) + + # Replace epsilon + new_parlist$epsilon_stc = augment_epsilon( + #beta_z = parlist$beta_z, + eps_stc = parlist$epsilon_stc, + neweps_stc = new_parlist$epsilon_stc, + #model = object$internal$spacetime_term_ram$output$model, + linpred = 1 + ) + new_parlist$epsilon2_stc = augment_epsilon( + #beta_z = parlist$beta2_z, + eps_stc = parlist$epsilon2_stc, + neweps_stc = new_parlist$epsilon2_stc, + #model = object$internal$delta_spacetime_term_ram$output$model, + linpred = 2 + ) - ############## - # Step 6: simulate samples - ############## + # Replace delta + new_parlist$delta_tc = augment_delta( + #nu_z = parlist$nu_z, + delta_tc = parlist$delta_tc, + newdelta_tc = new_parlist$delta_tc, + #model = object$internal$time_term_ram$output$model, + linpred = 1 + ) + new_parlist$delta2_tc = augment_delta( + #nu_z = parlist$nu2_z, + delta_tc = parlist$delta2_tc, + newdelta_tc = new_parlist$delta2_tc, + #model = object$internal$delta_time_term_ram$output$model, + linpred = 2 + ) - pred = predict( - object = newobj, - newdata = newdata, - what = what - ) + # Include every augmented effect, including effects fitted as fixed parameters. + pred[,i] = predobj$report( unlist(new_parlist, use.names = FALSE) )[[what]] + } + if( nsim == 1 ) pred = pred[,1] return(pred) } diff --git a/R/utility.R b/R/utility.R index 8076299e..9eaabf1a 100644 --- a/R/utility.R +++ b/R/utility.R @@ -403,7 +403,7 @@ function( x, # control_initial = control - control_initial$nlminb_loops = 0 + control_initial$opt_loops = 0 control_initial$newton_loops = 0 control_initial$run_model = FALSE diff --git a/man/project.Rd b/man/project.Rd index f6f6ac22..7ec7f25e 100644 --- a/man/project.Rd +++ b/man/project.Rd @@ -11,7 +11,8 @@ project( what = "mu_g", future_var = TRUE, past_var = FALSE, - parm_var = FALSE + parm_var = FALSE, + nsim = 1 ) } \arguments{ @@ -46,9 +47,12 @@ condition of the forecast} \item{parm_var}{logical indicating whether to re-sample fixed effects from their predictive distribution, thus changing the GMRF for future process errors} + +\item{nsim}{number of samples} } \value{ -A vector of values corresponding to rows in \code{newdata} +A vector of values corresponding to rows in \code{newdata}, or a matrix +with a column for each sample when \code{nsim > 1} } \description{ Projects a fitted model forward in time. @@ -101,18 +105,15 @@ plot( x = seq_along(Y), extra_times = length(x) + 1:100 n_sims = 10 newdata = data.frame( "time" = c(seq_along(x),extra_times), "var" = "y" ) -Y = NULL -for(i in seq_len(n_sims) ){ - tmp = project( - mytiny, - newdata = newdata, - extra_times = extra_times, - future_var = TRUE, - past_var = TRUE, - parm_var = TRUE - ) - Y = cbind(Y, tmp) -} +Y = project( + mytiny, + newdata = newdata, + extra_times = extra_times, + future_var = TRUE, + past_var = TRUE, + parm_var = TRUE, + nsim = n_sims +) matplot( x = row(Y), y = Y, type = "l", lty = "solid", col = "black" ) diff --git a/man/tinyVASTcontrol.Rd b/man/tinyVASTcontrol.Rd index d45a31b5..2e284e91 100644 --- a/man/tinyVASTcontrol.Rd +++ b/man/tinyVASTcontrol.Rd @@ -27,7 +27,8 @@ tinyVASTcontrol( extra_reporting = FALSE, use_anisotropy = FALSE, sar_adjacency = "queen", - barrier_stiffness = 0.01 + barrier_stiffness = 0.01, + update_weights = FALSE ) } \arguments{ @@ -116,6 +117,10 @@ rate and resulting decorrelation distance) for barriers relative to normal areas in the SPDE method when using \code{add_mesh_covariates}. The default \code{barrier_stiffness = 0.01} is the value from Bakka et al. 2019.} + +\item{update_weights}{Whether to allow \code{weights_i} to be changed via +\code{obj$env$data} without re-taping (e.g., for stochastic gradient +descent). This slows down fitting for large datasets.} } \value{ An object (list) of class \code{tinyVASTcontrol}, containing either default or diff --git a/src/tinyVAST.cpp b/src/tinyVAST.cpp index 8b58db30..e8e987b9 100644 --- a/src/tinyVAST.cpp +++ b/src/tinyVAST.cpp @@ -40,7 +40,6 @@ Type objective_function::operator() (){ DATA_IVECTOR( c_i ); DATA_VECTOR( offset_i ); DATA_VECTOR( weights_i ); - DATA_UPDATE( weights_i ); // Warning: cannot use branching (weights_i > 0) when using DATA_UPDATE DATA_VECTOR( size_i ); // Ignored unless family = binomial DATA_SPARSE_MATRIX( S_kk ); // Sparse penalization matrix DATA_IVECTOR( Sdims ); // Dimensions of blockwise components of S_kk @@ -56,6 +55,11 @@ Type objective_function::operator() (){ // model_options(2)==0: no RSS; model_options(2)==1: yes RSR // model_options(3)==0: no extra reporting; model_options(3)==1: yes extra reporting // model_options(4)==0: no SE for _g; model_options(4)==1: SE for p_g; model_options(4)==2: SE for mu_g + // model_options(5)==0: fixed weights_i; model_options(5)==1: weights_i can be updated without re-taping + bool update_weights = (model_options.size() > 5) && (model_options(5) == 1); + if( update_weights ){ + DATA_UPDATE( weights_i ); // Warning: cannot use branching (weights_i > 0) when using DATA_UPDATE + } DATA_IMATRIX( Aepsilon_zz ); // NAs get converted to -2147483648 DATA_VECTOR( Aepsilon_z ); DATA_IMATRIX( Aomega_zz ); // NAs get converted to -2147483648 @@ -272,18 +276,18 @@ Type objective_function::operator() (){ // space_term omega_sc = omega_distribution( omega_sc, model_options, Rho_cc, - Gamma_cc, Gammainv_cc, Q_ss, + Gamma_cc, Gammainv_cc, Q_ss, exp(log_tau), exp(log_kappa), nngp_data, nll ); // nngp_data, omega2_sc = omega_distribution( omega2_sc, model_options, Rho2_cc, - Gamma2_cc, Gammainv2_cc, Q_ss, + Gamma2_cc, Gammainv2_cc, Q_ss, exp(log_tau), exp(log_kappa), nngp_data, nll ); // nngp_data, // spacetime_term epsilon_stc = epsilon_distribution( epsilon_stc, model_options, Rho_hh, - Gamma_hh, Gammainv_hh, Q_ss, + Gamma_hh, Gammainv_hh, Q_ss, exp(log_tau), exp(log_kappa), nngp_data, nll ); epsilon2_stc = epsilon_distribution( epsilon2_stc, model_options, Rho2_hh, - Gamma2_hh, Gammainv2_hh, Q_ss, + Gamma2_hh, Gammainv2_hh, Q_ss, exp(log_tau), exp(log_kappa), nngp_data, nll ); // time_term @@ -299,9 +303,9 @@ Type objective_function::operator() (){ // Distribution for SVC components nll += xi_distribution( model_options, xi_sl, log_sigmaxi_l, - Q_ss, exp(log_kappa), nngp_data ); + Q_ss, exp(log_tau), exp(log_kappa), nngp_data ); nll += xi_distribution( model_options, xi2_sl, log_sigmaxi2_l, - Q_ss, exp(log_kappa), nngp_data ); + Q_ss, exp(log_tau), exp(log_kappa), nngp_data ); // Linear predictor .. keep partial effects for RSR adjustment below vector p_i( n_i ); @@ -312,9 +316,9 @@ Type objective_function::operator() (){ p_i = offset_i; if(alpha_j.size() > 0){ palpha1_i = X_ij*alpha_j; } if(gamma_k.size() > 0){ pgamma1_i = Z_ik*gamma_k; } - vector pepsilon1_i = multiply_epsilon( Aepsilon_zz, Aepsilon_z, epsilon_stc, p_i.size() ) / exp(log_tau); - vector pomega1_i = multiply_omega( Aomega_zz, Aomega_z, omega_sc, p_i.size() ) / exp(log_tau); - vector pxi1_i = multiply_xi( A_is, xi_sl, W_il ) / exp(log_tau); + vector pepsilon1_i = multiply_epsilon( Aepsilon_zz, Aepsilon_z, epsilon_stc, p_i.size() ); + vector pomega1_i = multiply_omega( Aomega_zz, Aomega_z, omega_sc, p_i.size() ); + vector pxi1_i = multiply_xi( A_is, xi_sl, W_il ); vector pdelta1_i = multiply_delta( delta_tc, t_i, c_i, n_i ); p_i += palpha1_i; p_i += pgamma1_i; @@ -332,9 +336,9 @@ Type objective_function::operator() (){ p2_i.setZero(); if(alpha2_j.size() > 0){ palpha2_i = X2_ij*alpha2_j; } if(gamma2_k.size() > 0){ pgamma2_i = Z2_ik*gamma2_k; } - vector pepsilon2_i = multiply_epsilon( Aepsilon_zz, Aepsilon_z, epsilon2_stc, p_i.size() ) / exp(log_tau); - vector pomega2_i = multiply_omega( Aomega_zz, Aomega_z, omega2_sc, p_i.size() ) / exp(log_tau); - vector pxi2_i = multiply_xi( A_is, xi2_sl, W2_il ) / exp(log_tau); + vector pepsilon2_i = multiply_epsilon( Aepsilon_zz, Aepsilon_z, epsilon2_stc, p_i.size() ); + vector pomega2_i = multiply_omega( Aomega_zz, Aomega_z, omega2_sc, p_i.size() ); + vector pxi2_i = multiply_xi( A_is, xi2_sl, W2_il ); vector pdelta2_i = multiply_delta( delta2_tc, t_i, c_i, n_i ); p2_i += palpha2_i; p2_i += pgamma2_i; @@ -358,14 +362,18 @@ Type objective_function::operator() (){ if( components_e(e_i(i))==1 ){ mu_i(i) = one_predictor_likelihood( y_i(i), p_i(i), size_i(i), link_ez(e_i(i),0), family_ez(e_i(i),0), log_sigma_segment, nll_tmp, devresid, this ); negloglik_i(i) = nll_tmp; - nll += weights_i(i) * nll_tmp; + // Multiplying by weights_i=1 is not free, because it adds per-observation terms to the random-effect Hessian + if( update_weights || (weights_i(i) != Type(1.0)) ) nll_tmp *= weights_i(i); + nll += nll_tmp; deviance += pow( devresid, 2.0 ); devresid_i(i) = devresid; } if( components_e(e_i(i))==2 ){ mu_i(i) = two_predictor_likelihood( y_i(i), p_i(i), p2_i(i), size_i(i), link_ez.row(e_i(i)), family_ez.row(e_i(i)), log_sigma_segment, poislink_e(e_i(i)), nll_tmp, dev, this ); negloglik_i(i) = nll_tmp; - nll += weights_i(i) * nll_tmp; + // Multiplying by weights_i=1 is not free, because it adds per-observation terms to the random-effect Hessian + if( update_weights || (weights_i(i) != Type(1.0)) ) nll_tmp *= weights_i(i); + nll += nll_tmp; deviance += dev; devresid_i(i) = NAN; } @@ -392,17 +400,17 @@ Type objective_function::operator() (){ if( n_g > 0 ){ vector palpha1_g = X_gj*alpha_j; vector pgamma1_g = Z_gk*gamma_k; - vector pepsilon1_g = multiply_epsilon( AepsilonG_zz, AepsilonG_z, epsilon_stc, palpha1_g.size() ) / exp(log_tau); - vector pomega1_g = multiply_omega( AomegaG_zz, AomegaG_z, omega_sc, palpha1_g.size() ) / exp(log_tau); - vector pxi1_g = multiply_xi( A_gs, xi_sl, W_gl ) / exp(log_tau); + vector pepsilon1_g = multiply_epsilon( AepsilonG_zz, AepsilonG_z, epsilon_stc, palpha1_g.size() ); + vector pomega1_g = multiply_omega( AomegaG_zz, AomegaG_z, omega_sc, palpha1_g.size() ); + vector pxi1_g = multiply_xi( A_gs, xi_sl, W_gl ); vector pdelta1_g = multiply_delta( delta_tc, t_g, c_g, n_g ); vector p1_g = palpha1_g + pgamma1_g+ pepsilon1_g + pomega1_g + pdelta1_g + pxi1_g + offset_g ; // Second linear predictor vector palpha2_g = X2_gj*alpha2_j; vector pgamma2_g = Z2_gk*gamma2_k; - vector pepsilon2_g = multiply_epsilon( AepsilonG_zz, AepsilonG_z, epsilon2_stc, palpha2_g.size() ) / exp(log_tau); - vector pomega2_g = multiply_omega( AomegaG_zz, AomegaG_z, omega2_sc, palpha2_g.size() ) / exp(log_tau); - vector pxi2_g = multiply_xi( A_gs, xi2_sl, W2_gl ) / exp(log_tau); + vector pepsilon2_g = multiply_epsilon( AepsilonG_zz, AepsilonG_z, epsilon2_stc, palpha2_g.size() ); + vector pomega2_g = multiply_omega( AomegaG_zz, AomegaG_z, omega2_sc, palpha2_g.size() ); + vector pxi2_g = multiply_xi( A_gs, xi2_sl, W2_gl ); vector pdelta2_g = multiply_delta( delta2_tc, t_g, c_g, n_g ); vector p2_g = palpha2_g + pgamma2_g + pepsilon2_g + pomega2_g + pdelta2_g + pxi2_g; // Combined diff --git a/src/utils.h b/src/utils.h index 48fb16f0..16cdf709 100644 --- a/src/utils.h +++ b/src/utils.h @@ -446,6 +446,7 @@ tmbutils::array omega_distribution( const Eigen::SparseMatrix &Gamma_cc, const Eigen::SparseMatrix &Gammainv_cc, const Eigen::SparseMatrix &Q_ss, + Type tau, Type range, const nngp_data_t &nngp_data, Type &nll ){ @@ -470,7 +471,7 @@ tmbutils::array omega_distribution( Eigen::SparseMatrix Q_cc = IminusRho_cc.transpose() * Vinv2_cc * IminusRho_cc; // GMRF for SEM: separable variable-space - nll += SEPARABLE( GMRF(Q_cc), GMRF(Q_ss) )( omega_sc ); + nll += SCALE( SEPARABLE( GMRF(Q_cc), GMRF(Q_ss) ), Type(1.0)/tau )( omega_sc ); // Including this line with Makevars below seems to cause a crash: // PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) // PKG_CXXFLAGS=$(SHLIB_OPENMP_CXXFLAGS) @@ -483,7 +484,7 @@ tmbutils::array omega_distribution( nll += NNGP( Type(1.0), range, omega_s, nngp_data ); } }else{ - nll += SEPARABLE( GMRF(I_cc), GMRF(Q_ss) )( omega_sc ); + nll += SCALE( SEPARABLE( GMRF(I_cc), GMRF(Q_ss) ), Type(1.0)/tau )( omega_sc ); } // Sparse inverse-product @@ -509,6 +510,7 @@ Type xi_distribution( tmbutils::array xi_sl, vector log_sigmaxi_l, const Eigen::SparseMatrix &Q_ss, + Type tau, Type range, const nngp_data_t &nngp_data ){ @@ -524,7 +526,7 @@ Type xi_distribution( } }else{ for( int l=0; l epsilon_distribution( const Eigen::SparseMatrix &Gamma_hh, const Eigen::SparseMatrix &Gammainv_hh, const Eigen::SparseMatrix &Q_ss, + Type tau, Type range, const nngp_data_t &nngp_data, Type &nll ){ @@ -580,7 +583,7 @@ tmbutils::array epsilon_distribution( Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; // GMRF for DSEM: non-separable time-variable, with separable space - nll += SEPARABLE( GMRF(Q_ss), GMRF(Q_hh) )( epsilon_hs ); + nll += SCALE( SEPARABLE( GMRF(Q_ss), GMRF(Q_hh) ), Type(1.0)/tau )( epsilon_hs ); }else{ // Rank-deficient (projection) method if( model_options(0) == 7 ){ @@ -590,7 +593,7 @@ tmbutils::array epsilon_distribution( nll += NNGP( Type(1.0), range, epsilon_s, nngp_data ); } }else{ - nll += SEPARABLE( GMRF(Q_ss), GMRF(I_hh) )( epsilon_hs ); + nll += SCALE( SEPARABLE( GMRF(Q_ss), GMRF(I_hh) ), Type(1.0)/tau )( epsilon_hs ); } // Sparse inverse-product @@ -933,28 +936,28 @@ Type one_predictor_likelihood( // Distribution switch( family ){ case gaussian_family: - nll = -1 * dnorm( y, mu, exp(log_sigma_segment(0)), true ); + nll = -dnorm( y, mu, exp(log_sigma_segment(0)), true ); devresid = y - mu; if(isDouble::value && of->do_simulate){ y = rnorm( mu, exp(log_sigma_segment(0)) ); } break; case tweedie_family: - nll = -1 * dtweedie( y, mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); + nll = -dtweedie( y, mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)), true ); devresid = devresid_tweedie( y, mu, 1.0 + invlogit(log_sigma_segment(1)) ); if(isDouble::value && of->do_simulate){ y = rtweedie( mu, exp(log_sigma_segment(0)), 1.0 + invlogit(log_sigma_segment(1)) ); } break; case lognormal_family: - nll = -1 * dlnorm( y, logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); + nll = -dlnorm( y, logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)), true ); devresid = log(y) - ( logmu - 0.5*exp(2.0*log_sigma_segment(0)) ); if(isDouble::value && of->do_simulate){ y = exp(rnorm( logmu - 0.5*exp(2.0*log_sigma_segment(0)), exp(log_sigma_segment(0)) )); } break; case poisson_family: - nll = -1 * dpois( y, mu, true ); + nll = -dpois( y, mu, true ); devresid = sign(y - mu) * pow(2*(y*log((Type(1e-10) + y)/mu) - (y-mu)), 0.5); if(isDouble::value && of->do_simulate){ y = rpois( mu ); @@ -966,7 +969,7 @@ Type one_predictor_likelihood( //}else{ // nll = -1 * logmu; //} - nll = -1 * dbinom_custom( y * size, logmu, log_one_minus_mu, size, true ); + nll = -dbinom_custom( y * size, logmu, log_one_minus_mu, size, true ); if(isDouble::value && of->do_simulate){ y = rbinom( size, mu ); } @@ -975,7 +978,7 @@ Type one_predictor_likelihood( devresid = devresid_binom( y, size, mu ); break; case gamma_family: // shape = 1/CV^2; scale = mean*CV^2 - nll = -1 * dgamma( y, exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)), true ); + nll = -dgamma( y, exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)), true ); devresid = sign(y - mu) * pow(2 * ( (y-mu)/mu - log(y/mu) ), 0.5); if(isDouble::value && of->do_simulate){ y = rgamma( exp(-2.0*log_sigma_segment(0)), mu*exp(2.0*log_sigma_segment(0)) ); @@ -983,7 +986,7 @@ Type one_predictor_likelihood( break; case nbinom1_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) // var - mu = exp( log(mu) + log(theta) ) = theta * mu --> var = (theta+1) * mu - nll = -1 * dnbinom_robust( y, logmu, logmu + log_sigma_segment(0), true); + nll = -dnbinom_robust( y, logmu, logmu + log_sigma_segment(0), true); devresid = devresid_nbinom2( y, logmu, logmu - log_sigma_segment(0) ); // theta = mu / phi if(isDouble::value && of->do_simulate){ // rnbinom2( mu, var ) @@ -992,7 +995,7 @@ Type one_predictor_likelihood( break; case nbinom2_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - nll = -1 * dnbinom_robust( y, logmu, Type(2.0) * logmu - log_sigma_segment(0), true); + nll = -dnbinom_robust( y, logmu, Type(2.0) * logmu - log_sigma_segment(0), true); devresid = devresid_nbinom2( y, logmu, log_sigma_segment(0) ); if(isDouble::value && of->do_simulate){ // rnbinom2( mu, var ) @@ -1001,7 +1004,7 @@ Type one_predictor_likelihood( break; case student_family: // dnbinom_robust( x, log(mu_i), log(var - mu) ) // var - mu = exp( 2 * log(mu) - log(theta) ) = mu^2 / theta --> var = mu + mu^2 / theta - nll = -1 * dstudent( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); + nll = -dstudent( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)), true); devresid = devresid_student( y, mu, exp(log_sigma_segment(0)), 1.0 + exp(log_sigma_segment(1)) ); if(isDouble::value && of->do_simulate){ y = mu + exp(log_sigma_segment(0)) * rt(1.0 + exp(log_sigma_segment(1))); @@ -1063,11 +1066,11 @@ Type two_predictor_likelihood( y = rbinom( Type(1), mu1 ); } if( y == 0 ){ - nll = -1 * log_one_minus_mu1; + nll = -log_one_minus_mu1; dev = -2 * log_one_minus_mu1; } if( y>0 ){ // Not if-else so y>0 triggered when simulating y>0 - nll = -1 * logmu1; + nll = -logmu1; dev = -2 * logmu1; //deviance1_i(i) = -2 * log_mu1(i); switch( family(1) ){ diff --git a/tests/testthat/test-basic-fits.R b/tests/testthat/test-basic-fits.R index 7220c267..318c4a42 100644 --- a/tests/testthat/test-basic-fits.R +++ b/tests/testthat/test-basic-fits.R @@ -42,8 +42,18 @@ test_that("cv::cv works", { skip_on_covr() # Run cv::cv - CV = cv::cv(out, seed = 123) - expect_equal( as.numeric(CV[['CV crit']]), 1.607874, tolerance = 0.0001 ) + # cv::cv() re-evaluates the call from inside cv + # where the test-local `mesh` isn't visible + # bquote() solves this without assigning to global env. + out_cv <- eval(bquote(tinyVAST( + data = dat, + formula = n ~ s(w), + spatial_domain = .(mesh), # .() looks up mesh in the test environment + space_term = "", + control = tinyVASTcontrol(newton_loops = 1) + ))) + CV = cv::cv(out_cv, seed = 123) + expect_equal( as.numeric(CV[['CV crit']]), 1.60805, tolerance = 0.0001 ) }) # test_that("data_colnames are robust", { diff --git a/tests/testthat/test-index-standardization.R b/tests/testthat/test-index-standardization.R index 73a931f7..474e7610 100644 --- a/tests/testthat/test-index-standardization.R +++ b/tests/testthat/test-index-standardization.R @@ -48,7 +48,7 @@ test_that("Basic index standardization works", { spatial_domain = mesh, family = delta_gamma(type="poisson-link"), control = tinyVASTcontrol(gmrf="sep") ) - expect_equal( my1$opt, my2$opt, tolerance=0.001 ) + expect_equal( my1$opt[c("par","objective")], my2$opt[c("par","objective")], tolerance=0.001 ) # Predicted sample-weighted total index = integrate_output( my1, @@ -70,7 +70,7 @@ test_that("Basic index standardization works", { spatial_domain = mesh, family = delta_gamma(type="poisson-link"), control = tinyVASTcontrol(gmrf="sep") ) - expect_equal( my3$opt, my4$opt, tolerance=0.001 ) + expect_equal( my3$opt[c("par","objective")], my4$opt[c("par","objective")], tolerance=0.001 ) }) test_that("Index standardization results are identical in VAST, tinyVAST, and sdmTMB", { diff --git a/tests/testthat/test-smooths.R b/tests/testthat/test-smooths.R index 6a57785f..469f0d5e 100644 --- a/tests/testthat/test-smooths.R +++ b/tests/testthat/test-smooths.R @@ -262,18 +262,21 @@ test_that("A model with s(x, bs = 'cc') works", { }) test_that("A model with s() by variables works", { - set.seed(1) - # For some reason, it doesn't work on CI but does locally skip_on_ci() skip_on_cran() - dat <- mgcv::gamSim(4) - m_mgcv <- mgcv::gam(y ~ fac + s(x2, by = fac) + s(x0), data = dat) + set.seed(1) + n <- 400 + x2 <- runif(n) + fac <- factor(sample(1:3, n, replace = TRUE)) + mu <- ifelse(fac == 1, sin(2 * pi * x2), ifelse(fac == 2, cos(3 * pi * x2), 8 * (x2 - 0.5)^2)) + dat <- data.frame(y = mu + rnorm(n, sd = 0.5), x2 = x2, fac = fac) + m_mgcv <- mgcv::gam(y ~ fac + s(x2, by = fac), data = dat) p_mgcv <- predict(m_mgcv) - m_s <- sdmTMB::sdmTMB(formula = y ~ fac + s(x2, by = fac) + s(x0), data = dat, spatial = "off") + m_s <- sdmTMB::sdmTMB(formula = y ~ fac + s(x2, by = fac), data = dat, spatial = "off") - m_v <- tinyVAST(formula = y ~ fac + s(x2, by = fac) + s(x0), data = dat) + m_v <- tinyVAST(formula = y ~ fac + s(x2, by = fac), data = dat) expect_s3_class(m_v, "tinyVAST") p_m <- predict(m_mgcv) From 61f072abd676f8205d63d0978f23db28fcea23bf Mon Sep 17 00:00:00 2001 From: "James T. Thorson" Date: Tue, 20 Oct 2026 11:33:31 +0200 Subject: [PATCH 19/37] add faster cAIC --- DESCRIPTION | 5 +++-- NEWS.md | 4 ++++ R/cAIC.R | 21 +++++++++++++++++++-- man/cAIC.Rd | 8 +++++++- src/utils.h | 6 +++--- 5 files changed, 36 insertions(+), 8 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 9282feb1..c0d800ea 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: tinyVAST Title: Multivariate Spatio-Temporal Models using Structural Equations -Version: 1.6.3 +Version: 1.6.3.9999 Date: 2026-09-19 Authors@R: c( person(c("James", "T."), "Thorson", , "James.Thorson@noaa.gov", @@ -63,7 +63,8 @@ Suggests: DHARMa, glmmTMB, tibble, - RANN + RANN, + sparseinv LinkingTo: RcppEigen, TMB diff --git a/NEWS.md b/NEWS.md index e5c7cf7d..d721e631 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,7 @@ +# tinyVAST 1.6.3.9999 + +* Add an experimental option for cAIC to avoid constructing a dense matrix prior to extracting its diagonal using sparseinv::Takahashi_Davis + # tinyVAST 1.6.3 * Move most vignettes to web_only vignettes directory, and update interface for visreg in mgcv.Rmd vignette diff --git a/R/cAIC.R b/R/cAIC.R index 80c8e62b..be348f9a 100644 --- a/R/cAIC.R +++ b/R/cAIC.R @@ -3,6 +3,11 @@ #' Calculates the conditional Akaike Information criterion (cAIC). #' #' @param object Output from [tinyVAST()]. +#' @param method whether to compute effective degrees of freedom using +#' the stable method \code{diag(solve(Hess, Hess_new))} +#' or a faster and experimental method +#' \code{-rowSums(sparseinv::Takahashi_Davis(-Hess) * t(Hess_new))}, +#' where the latter avoids constructing a dense matrix prior to extracting its diagonal #' #' @details cAIC is designed to optimize the expected out-of-sample predictive #' performance for new data that share the same random effects as the in-sample @@ -60,8 +65,10 @@ #' #' @export cAIC <- -function( object ){ +function( object, + method = c("stable", "fast") ){ + method = match.arg(version) check_tinyVAST_version( object$internal$packageVersion ) #what = match.arg(what) #requireNamespace(Matrix) @@ -103,7 +110,17 @@ function( object ){ ## Joint hessian etc Hess = -Matrix::Matrix(obj$env$f(parDataMode,order=1,type="ADGrad"),sparse = TRUE) Hess = Hess[indx,indx] - negEDF = Matrix::diag(Matrix::solve(Hess, Hess_new)) + + if( method == "stable" ){ + negEDF = Matrix::diag(Matrix::solve(Hess, Hess_new)) + }else{ + #S = TMB:::solveSubset(-Hess) + if( !requireNamespace("sparseinv", quietly = TRUE) ){ + stop("method = 'fast' requires the 'sparseinv' package; use method = 'stable' or install it") + } + S = sparseinv::Takahashi_Davis(-Hess) + negEDF = -1 * Matrix::rowSums(S * Matrix::t(Hess_new)) + } #if(what == "cAIC"){ jnll = obj$env$f(parDataMode) diff --git a/man/cAIC.Rd b/man/cAIC.Rd index 69271de3..7928937f 100644 --- a/man/cAIC.Rd +++ b/man/cAIC.Rd @@ -4,10 +4,16 @@ \alias{cAIC} \title{Calculate conditional AIC} \usage{ -cAIC(object) +cAIC(object, method = c("stable", "fast")) } \arguments{ \item{object}{Output from \code{\link[=tinyVAST]{tinyVAST()}}.} + +\item{method}{whether to compute effective degrees of freedom using +the stable method \code{diag(solve(Hess, Hess_new))} +or a faster and experimental method +\code{-rowSums(sparseinv::Takahashi_Davis(-Hess) * t(Hess_new))}, +where the latter avoids constructing a dense matrix prior to extracting its diagonal} } \value{ cAIC value diff --git a/src/utils.h b/src/utils.h index 16cdf709..dbc2638a 100644 --- a/src/utils.h +++ b/src/utils.h @@ -466,7 +466,7 @@ tmbutils::array omega_distribution( // Separable precision ... Option-2 // Only compute Vinv_kk if Gamma_kk is full rank Eigen::SparseMatrix V_cc = Gamma_cc.transpose() * Gamma_cc; - matrix Vinv_cc = invertSparseMatrix( V_cc ); + matrix Vinv_cc = tmbutils::invertSparseMatrix( V_cc ); Eigen::SparseMatrix Vinv2_cc = asSparseMatrix( Vinv_cc ); Eigen::SparseMatrix Q_cc = IminusRho_cc.transpose() * Vinv2_cc * IminusRho_cc; @@ -578,7 +578,7 @@ tmbutils::array epsilon_distribution( // Separable precision ... Option-2 // Only compute Vinv_kk if Gamma_kk is full rank Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; - matrix Vinv_hh = invertSparseMatrix( V_hh ); + matrix Vinv_hh = tmbutils::invertSparseMatrix( V_hh ); Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; @@ -649,7 +649,7 @@ tmbutils::array delta_distribution( if( model_options(1) == 0 ){ Eigen::SparseMatrix V_hh = Gamma_hh.transpose() * Gamma_hh; - matrix Vinv_hh = invertSparseMatrix( V_hh ); + matrix Vinv_hh = tmbutils::invertSparseMatrix( V_hh ); Eigen::SparseMatrix Vinv2_hh = asSparseMatrix( Vinv_hh ); Eigen::SparseMatrix Q_hh = IminusRho_hh.transpose() * Vinv2_hh * IminusRho_hh; From f11c65b157dffff46a1946520108d6eeec70e173 Mon Sep 17 00:00:00 2001 From: "James T. Thorson" Date: Tue, 20 Oct 2026 11:38:35 +0200 Subject: [PATCH 20/37] update ref for cAIC --- R/cAIC.R | 8 ++++---- man/cAIC.Rd | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/R/cAIC.R b/R/cAIC.R index be348f9a..264a756b 100644 --- a/R/cAIC.R +++ b/R/cAIC.R @@ -30,10 +30,10 @@ #' cAIC value #' #' @references -#' Zheng, N., Cadigan, N., & Thorson, J. T. (2024). -#' A note on numerical evaluation of conditional Akaike information for -#' nonlinear mixed-effects models (arXiv:2411.14185). arXiv. -#' \doi{10.48550/arXiv.2411.14185} +#' Zheng, N., Cadigan, N., & Thorson, J. T. (2026). +#' A unifying theory for the evaluation of conditional Akaike information for +#' mixed-effects models. Journal of Statistical Computation and Simulation. +#' \doi{10.1080/00949655.2026.2736799} #' #' @examples #' data( red_snapper ) diff --git a/man/cAIC.Rd b/man/cAIC.Rd index 7928937f..a5170b13 100644 --- a/man/cAIC.Rd +++ b/man/cAIC.Rd @@ -68,8 +68,8 @@ AIC(fit) # marginal AIC } \references{ -Zheng, N., Cadigan, N., & Thorson, J. T. (2024). -A note on numerical evaluation of conditional Akaike information for -nonlinear mixed-effects models (arXiv:2411.14185). arXiv. -\doi{10.48550/arXiv.2411.14185} +Zheng, N., Cadigan, N., & Thorson, J. T. (2026). +A unifying theory for the evaluation of conditional Akaike information for +mixed-effects models. Journal of Statistical Computation and Simulation. +\doi{10.1080/00949655.2026.2736799} } From 6960bceadef6273bba3324edf44ff68c04258764 Mon Sep 17 00:00:00 2001 From: "James T. Thorson" Date: Tue, 20 Oct 2026 11:49:36 +0200 Subject: [PATCH 21/37] fix typo in last commit --- R/cAIC.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/cAIC.R b/R/cAIC.R index 264a756b..2153e6d6 100644 --- a/R/cAIC.R +++ b/R/cAIC.R @@ -68,7 +68,7 @@ cAIC <- function( object, method = c("stable", "fast") ){ - method = match.arg(version) + method = match.arg(method) check_tinyVAST_version( object$internal$packageVersion ) #what = match.arg(what) #requireNamespace(Matrix) From ebeb51b85b6324d78313ffdb3cac310593af725d Mon Sep 17 00:00:00 2001 From: "James T. Thorson" Date: Sun, 15 Nov 2026 09:00:26 +0100 Subject: [PATCH 22/37] add what = "EDF" option to cAIC(.) --- NEWS.md | 1 + R/cAIC.R | 53 +++++++++++++++++++++++++++++++---------------------- man/cAIC.Rd | 6 ++++-- 3 files changed, 36 insertions(+), 24 deletions(-) diff --git a/NEWS.md b/NEWS.md index d721e631..b870c4cc 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,7 @@ # tinyVAST 1.6.3.9999 * Add an experimental option for cAIC to avoid constructing a dense matrix prior to extracting its diagonal using sparseinv::Takahashi_Davis +* Add what = "EDF" option to cAIC(.) # tinyVAST 1.6.3 diff --git a/R/cAIC.R b/R/cAIC.R index 2153e6d6..9d493dfa 100644 --- a/R/cAIC.R +++ b/R/cAIC.R @@ -3,6 +3,7 @@ #' Calculates the conditional Akaike Information criterion (cAIC). #' #' @param object Output from [tinyVAST()]. +#' @param what whether to get cAIC or the EDF (the latter grouped by type of random effect). #' @param method whether to compute effective degrees of freedom using #' the stable method \code{diag(solve(Hess, Hess_new))} #' or a faster and experimental method @@ -21,7 +22,7 @@ #' generative parameters. #' #' Both cAIC and EDF are calculated using Eq. 6 of Zheng, Cadigan, and Thorson -#' (2024). +#' (2026). #' #' For models that include profiled fixed effects, these profiles are turned #' off. @@ -66,8 +67,10 @@ #' @export cAIC <- function( object, + what = c("cAIC", "EDF"), method = c("stable", "fast") ){ + what = match.arg(what) method = match.arg(method) check_tinyVAST_version( object$internal$packageVersion ) #what = match.arg(what) @@ -78,27 +81,32 @@ function( object, if( is.null(object$internal$control$profile) ){ obj = object$obj }else{ - obj = TMB::MakeADFun( data = data, - parameters = object$internal$parlist, - map = object$tmb_inputs$tmb_map, - random = object$tmb_inputs$tmb_random, - DLL = "tinyVAST", - profile = NULL ) + obj = TMB::MakeADFun( + data = data, + parameters = object$internal$parlist, + map = object$tmb_inputs$tmb_map, + random = object$tmb_inputs$tmb_random, + DLL = "tinyVAST", + profile = NULL + ) } # Make obj_new data$weights_i[] = 0 - obj_new = TMB::MakeADFun( data = data, - parameters = object$internal$parlist, - map = object$tmb_inputs$tmb_map, - random = object$tmb_inputs$tmb_random, - DLL = "tinyVAST", - profile = NULL ) + obj_new = TMB::MakeADFun( + data = data, + parameters = object$internal$parlist, + map = object$tmb_inputs$tmb_map, + random = object$tmb_inputs$tmb_random, + DLL = "tinyVAST", + profile = NULL + ) # par = obj$env$parList() parDataMode <- obj$env$last.par indx = obj$env$lrandom() + random_names = names(parDataMode)[indx] q = sum(indx) p = length(object$opt$par) @@ -122,17 +130,18 @@ function( object, negEDF = -1 * Matrix::rowSums(S * Matrix::t(Hess_new)) } - #if(what == "cAIC"){ + if(what == "cAIC"){ jnll = obj$env$f(parDataMode) cnll = jnll - obj_new$env$f(parDataMode) cAIC = 2*cnll + 2*(p+q) - 2*sum(negEDF) return(cAIC) - #} - #if(what == "EDF"){ - # group = colnames(object$tmb_inputs$tmb_data$Z_ik) - # group = sapply(group, FUN=\(char)strsplit(char,split=".",fixed=TRUE)[[1]][1]) - # group = factor(group) - # EDF = tapply(negEDF,INDEX=group,FUN=length) - tapply(negEDF,INDEX=group,FUN=sum) - # return(EDF) - #} + } + if(what == "EDF"){ + #group = colnames(object$tmb_inputs$tmb_data$Z_ik) + #group = sapply(group, FUN=\(char)strsplit(char,split=".",fixed=TRUE)[[1]][1]) + #group = factor(group) + group = factor(random_names) + EDF = tapply(negEDF, INDEX=group, FUN=length) - tapply(negEDF, INDEX=group, FUN=sum) + return(EDF) + } } diff --git a/man/cAIC.Rd b/man/cAIC.Rd index a5170b13..a25f8f2c 100644 --- a/man/cAIC.Rd +++ b/man/cAIC.Rd @@ -4,11 +4,13 @@ \alias{cAIC} \title{Calculate conditional AIC} \usage{ -cAIC(object, method = c("stable", "fast")) +cAIC(object, what = c("cAIC", "EDF"), method = c("stable", "fast")) } \arguments{ \item{object}{Output from \code{\link[=tinyVAST]{tinyVAST()}}.} +\item{what}{whether to get cAIC or the EDF (the latter grouped by type of random effect).} + \item{method}{whether to compute effective degrees of freedom using the stable method \code{diag(solve(Hess, Hess_new))} or a faster and experimental method @@ -34,7 +36,7 @@ that have new random effects, e.g., extrapolation, or inference about generative parameters. Both cAIC and EDF are calculated using Eq. 6 of Zheng, Cadigan, and Thorson -(2024). +(2026). For models that include profiled fixed effects, these profiles are turned off. From 3389d8049eafea1a0706f664bf4ca4d922ecc18d Mon Sep 17 00:00:00 2001 From: James Thorson Date: Sat, 21 Nov 2026 10:05:29 +0100 Subject: [PATCH 23/37] make CRAN checks happy --- NEWS.md | 2 ++ scratch/build_pkgdown_website.R | 2 +- tests/testthat/test-smooths.R | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index 5865c584..0c696426 100644 --- a/NEWS.md +++ b/NEWS.md @@ -3,6 +3,8 @@ * Add an experimental option for cAIC to avoid constructing a dense matrix prior to extracting its diagonal using sparseinv::Takahashi_Davis * Add what = "EDF" option to cAIC(.) * Remove ti and te mgcv tests from CRAN +* Speed up `project` by adding argument `nsim` and using more efficient linear algebra +* Speed up TMB code on C++ side, e.g., by making DATA_UPDATE optional, making weights_i optional, using SCALE for scaling a precision matrix, and other smaller improvements # tinyVAST 1.6.3 diff --git a/scratch/build_pkgdown_website.R b/scratch/build_pkgdown_website.R index d9b90cab..d4295e6a 100644 --- a/scratch/build_pkgdown_website.R +++ b/scratch/build_pkgdown_website.R @@ -34,7 +34,7 @@ if( FALSE ){ # output = "web_only/VAST.Rmd" ) } -setwd(R'(C:\Users\James.Thorson\Desktop\Git\tinyVAST)') +setwd(R'(C:\Users\james\OneDrive\Desktop\Git\tinyVAST)') # Only needed once if( FALSE ){ diff --git a/tests/testthat/test-smooths.R b/tests/testthat/test-smooths.R index 469f0d5e..29dcb947 100644 --- a/tests/testthat/test-smooths.R +++ b/tests/testthat/test-smooths.R @@ -114,6 +114,7 @@ test_that("t2 splines throw an error for now", { }) test_that("ti and te splines work", { + skip_on_cran() set.seed(1) dat <- mgcv::gamSim(1, n = 400, scale = 2) dat$fac <- fac <- as.factor(sample(1:20, 400, replace = TRUE)) From 40533a510746f201d31ce28421f5a3232d2ba79f Mon Sep 17 00:00:00 2001 From: James Thorson Date: Sat, 21 Nov 2026 10:17:08 +0100 Subject: [PATCH 24/37] try fixing test-coverage.yaml --- .github/workflows/test-coverage.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test-coverage.yaml b/.github/workflows/test-coverage.yaml index 6e560b38..888548b5 100644 --- a/.github/workflows/test-coverage.yaml +++ b/.github/workflows/test-coverage.yaml @@ -46,6 +46,8 @@ jobs: install_path = file.path(normalizePath(Sys.getenv("RUNNER_TEMP"), winslash = "/"), "package") ) shell: Rscript {0} + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - name: Show testthat output if: always() @@ -59,4 +61,4 @@ jobs: uses: actions/upload-artifact@v4 with: name: coverage-test-failures - path: ${{ runner.temp }}/package + path: ${{ runner.temp }}/package \ No newline at end of file From 76eb50e881be454236de1cdce9a87548dbde7ffa Mon Sep 17 00:00:00 2001 From: James Thorson Date: Sat, 21 Nov 2026 10:31:07 +0100 Subject: [PATCH 25/37] improve cAIC by using spHess(random=TRUE) --- NEWS.md | 2 +- R/cAIC.R | 26 +++++++++++++++----------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/NEWS.md b/NEWS.md index 0c696426..0a27de6b 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,6 @@ # tinyVAST 1.6.3.9999 -* Add an experimental option for cAIC to avoid constructing a dense matrix prior to extracting its diagonal using sparseinv::Takahashi_Davis +* Add an experimental option for cAIC to avoid constructing a dense matrix prior to extracting its diagonal using sparseinv::Takahashi_Davis, and use spHess(random=TRUE) to efficiently access sparse Hessians * Add what = "EDF" option to cAIC(.) * Remove ti and te mgcv tests from CRAN * Speed up `project` by adding argument `nsim` and using more efficient linear algebra diff --git a/R/cAIC.R b/R/cAIC.R index 9d493dfa..7178ffd2 100644 --- a/R/cAIC.R +++ b/R/cAIC.R @@ -110,24 +110,28 @@ function( object, q = sum(indx) p = length(object$opt$par) - ## use - for Hess because model returns negative loglikelihood; - #cov_Psi_inv = -Hess_new[indx,indx]; ## this is the marginal prec mat of REs; - Hess_new = -Matrix::Matrix(obj_new$env$f(parDataMode,order=1,type="ADGrad"),sparse = TRUE) - Hess_new = Hess_new[indx,indx] + if( method == "stable" ){ + ## use - for Hess because model returns negative loglikelihood; + #cov_Psi_inv = -Hess_new[indx,indx]; ## this is the marginal prec mat of REs; + Hess_new = -Matrix::Matrix(obj_new$env$f(parDataMode,order=1,type="ADGrad"),sparse = TRUE) + Hess_new = Hess_new[indx,indx] - ## Joint hessian etc - Hess = -Matrix::Matrix(obj$env$f(parDataMode,order=1,type="ADGrad"),sparse = TRUE) - Hess = Hess[indx,indx] + # Joint hessian etc + Hess = -Matrix::Matrix(obj$env$f(parDataMode,order=1,type="ADGrad"),sparse = TRUE) + Hess = Hess[indx,indx] - if( method == "stable" ){ negEDF = Matrix::diag(Matrix::solve(Hess, Hess_new)) }else{ - #S = TMB:::solveSubset(-Hess) if( !requireNamespace("sparseinv", quietly = TRUE) ){ stop("method = 'fast' requires the 'sparseinv' package; use method = 'stable' or install it") } - S = sparseinv::Takahashi_Davis(-Hess) - negEDF = -1 * Matrix::rowSums(S * Matrix::t(Hess_new)) + # h/t Jie Cao for suggesting spHess to avoid sparsifying a dense Hessian as done previously + # Also dropping negative signs (which all cancel) + Hess_new = obj_new$env$spHess(par, random = TRUE) + Hess = obj$env$spHess(par, random = TRUE) + #S = TMB:::solveSubset(Hess) + S = sparseinv::Takahashi_Davis(Hess) + negEDF = Matrix::rowSums(S * Hess_new) } if(what == "cAIC"){ From 358a5124889306b8477e0b1b66c8f7879ba489c0 Mon Sep 17 00:00:00 2001 From: James Thorson Date: Sat, 21 Nov 2026 10:39:08 +0100 Subject: [PATCH 26/37] try fixing pkgdown actions --- .github/workflows/pkgdown.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pkgdown.yaml b/.github/workflows/pkgdown.yaml index 028b4635..646f7f68 100644 --- a/.github/workflows/pkgdown.yaml +++ b/.github/workflows/pkgdown.yaml @@ -44,7 +44,7 @@ jobs: - uses: r-lib/actions/setup-r-dependencies@v2 with: - extra-packages: any::pkgdown, local::. + extra-packages: any::pkgdown, any::systemfonts, local::. needs: website - name: Build site From f7574e1d3e106d9ae0bd6dffc0d6061bb259a111 Mon Sep 17 00:00:00 2001 From: James Thorson Date: Sat, 21 Nov 2026 10:49:55 +0100 Subject: [PATCH 27/37] try again: fixing pggkdown.yaml --- .github/workflows/pkgdown.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/pkgdown.yaml b/.github/workflows/pkgdown.yaml index 646f7f68..cef3cfd1 100644 --- a/.github/workflows/pkgdown.yaml +++ b/.github/workflows/pkgdown.yaml @@ -35,6 +35,7 @@ jobs: run: | install.packages('remotes') remotes::install_deps(dependencies = TRUE) + remotes::install_cran("systemfonts") remotes::install_cran("knitr") remotes::install_cran("rmarkdown") remotes::install_cran("rcmdcheck") From 31622f2d966172e952deac2bcb2cc89efb6803ea Mon Sep 17 00:00:00 2001 From: James Thorson Date: Sat, 21 Nov 2026 11:14:54 +0100 Subject: [PATCH 28/37] fix NOTE in CRAN check --- DESCRIPTION | 1 - 1 file changed, 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index c0d800ea..2bc60ec6 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -41,7 +41,6 @@ Imports: dsem (>= 3.0.0), insight, cv, - sparseinv, gstat, cli, GpGp, From 74c2c398f931fc64d073606749ae6cd912483c0e Mon Sep 17 00:00:00 2001 From: James Thorson Date: Sat, 21 Nov 2026 11:23:50 +0100 Subject: [PATCH 29/37] fix CI R_CMD_check --- DESCRIPTION | 8 ++++---- R/cAIC.R | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 2bc60ec6..120905bb 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -2,7 +2,7 @@ Type: Package Package: tinyVAST Title: Multivariate Spatio-Temporal Models using Structural Equations Version: 1.6.3.9999 -Date: 2026-09-19 +Date: 2026-11-21 Authors@R: c( person(c("James", "T."), "Thorson", , "James.Thorson@noaa.gov", role = c("aut", "cre"), @@ -44,7 +44,8 @@ Imports: gstat, cli, GpGp, - GPvecchia + GPvecchia, + sparseinv Suggests: ggplot2, knitr, @@ -62,8 +63,7 @@ Suggests: DHARMa, glmmTMB, tibble, - RANN, - sparseinv + RANN LinkingTo: RcppEigen, TMB diff --git a/R/cAIC.R b/R/cAIC.R index 7178ffd2..81588e17 100644 --- a/R/cAIC.R +++ b/R/cAIC.R @@ -122,9 +122,9 @@ function( object, negEDF = Matrix::diag(Matrix::solve(Hess, Hess_new)) }else{ - if( !requireNamespace("sparseinv", quietly = TRUE) ){ - stop("method = 'fast' requires the 'sparseinv' package; use method = 'stable' or install it") - } + #if( !requireNamespace("sparseinv", quietly = TRUE) ){ + # stop("method = 'fast' requires the 'sparseinv' package; use method = 'stable' or install it") + #} # h/t Jie Cao for suggesting spHess to avoid sparsifying a dense Hessian as done previously # Also dropping negative signs (which all cancel) Hess_new = obj_new$env$spHess(par, random = TRUE) From 775638b2e8b35f1f2f4c3e9147f0a4929d49446b Mon Sep 17 00:00:00 2001 From: James Thorson Date: Sat, 21 Nov 2026 11:31:30 +0100 Subject: [PATCH 30/37] try again to fix pkgdown action --- .github/workflows/pkgdown.yaml | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/.github/workflows/pkgdown.yaml b/.github/workflows/pkgdown.yaml index cef3cfd1..55e14a7b 100644 --- a/.github/workflows/pkgdown.yaml +++ b/.github/workflows/pkgdown.yaml @@ -22,7 +22,7 @@ jobs: permissions: contents: write steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: r-lib/actions/setup-pandoc@v2 @@ -30,26 +30,26 @@ jobs: with: use-public-rspm: true - - name: Install dependencies Ubuntu - if: runner.os == 'Linux' - run: | - install.packages('remotes') - remotes::install_deps(dependencies = TRUE) - remotes::install_cran("systemfonts") - remotes::install_cran("knitr") - remotes::install_cran("rmarkdown") - remotes::install_cran("rcmdcheck") - install.packages("Matrix", type = "source") - install.packages("TMB", type = "source") - shell: Rscript {0} - - uses: r-lib/actions/setup-r-dependencies@v2 with: - extra-packages: any::pkgdown, any::systemfonts, local::. + extra-packages: any::pkgdown, local::. needs: website + cache-version: 2 + + - name: Reinstall TMB/Matrix from source + run: | + install.packages(c("Matrix", "TMB"), type = "source") + shell: Rscript {0} + + - name: Check systemfonts + run: | + print(.libPaths()) + print(find.package("systemfonts")) + print(packageVersion("systemfonts")) + shell: Rscript {0} - name: Build site - run: pkgdown::build_site_github_pages(new_process = FALSE, install = FALSE) + run: pkgdown::build_site_github_pages(new_process = TRUE, install = FALSE) shell: Rscript {0} - name: Deploy to GitHub pages 🚀 @@ -58,4 +58,4 @@ jobs: with: clean: false branch: gh-pages - folder: docs + folder: docs \ No newline at end of file From f4bcc21ef72daee95b1e037f6069e1aa04f4b0d6 Mon Sep 17 00:00:00 2001 From: James Thorson Date: Sat, 21 Nov 2026 11:36:13 +0100 Subject: [PATCH 31/37] try fixing san-check.yaml --- .github/workflows/san-check.yaml | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/.github/workflows/san-check.yaml b/.github/workflows/san-check.yaml index 37f07c49..ae17ac5f 100644 --- a/.github/workflows/san-check.yaml +++ b/.github/workflows/san-check.yaml @@ -21,14 +21,24 @@ jobs: steps: - uses: actions/checkout@v4 + - name: Use binary packages (avoid libc++/libstdc++ mismatch) + run: | + . /etc/os-release + echo "Distro codename: ${VERSION_CODENAME}" + echo "options(repos = c(CRAN = 'https://packagemanager.posit.co/cran/__linux__/${VERSION_CODENAME}/latest'))" >> ~/.Rprofile + cat ~/.Rprofile + - name: Install dependencies run: | R -q -e 'install.packages("pak")' + R -q -e 'pak::pkg_install(c("sf", "terra"), upgrade = FALSE)' R -q -e 'pak::pkg_install(c("local::.", "rcmdcheck", "knitr", "rmarkdown", "AER", "MARSS", "testthat", "RANN"))' - # R -q -e 'pak::pkg_install(c("phylopath", "reshape", "dynlm", "ggpubr", "vars", "DHARMa"))' # Oher SUGGESTS packages + # R -q -e 'pak::pkg_install(c("phylopath", "reshape", "dynlm", "ggpubr", "vars", "DHARMa"))' # Other SUGGESTS packages - - name: Run check + - name: Check that sf loads run: | - # R -q -e 'rcmdcheck::rcmdcheck(args = c("--no-manual", "--no-vignettes", "--no-build-vignettes", "--no-examples", "--no-tests"), build_args = c("--no-build-vignettes", "--no-build-vignettes"), error_on = "error")' - R -q -e 'rcmdcheck::rcmdcheck(args = c("--no-manual", "--no-vignettes", "--no-build-vignettes"), build_args = c("--no-build-vignettes", "--no-build-vignettes"), error_on = "error")' + R -q -e 'library(sf); print(sf::sf_extSoftVersion())' + - name: Run check + run: | + R -q -e 'rcmdcheck::rcmdcheck(args = c("--no-manual", "--no-vignettes", "--no-build-vignettes"), build_args = c("--no-build-vignettes", "--no-build-vignettes"), error_on = "error")' \ No newline at end of file From fdf50faf5fddbf62910964c2d1c2707dda407265 Mon Sep 17 00:00:00 2001 From: James Thorson Date: Sat, 21 Nov 2026 11:43:10 +0100 Subject: [PATCH 32/37] make CI R_CMD_check happy --- R/fit.R | 1 + 1 file changed, 1 insertion(+) diff --git a/R/fit.R b/R/fit.R index 3337f4af..0f7293e9 100644 --- a/R/fit.R +++ b/R/fit.R @@ -154,6 +154,7 @@ #' @importFrom cli cli_abort cli_warn cli_inform cli_alert_success cli_alert_danger cli_alert_info #' @importFrom GpGp find_ordered_nn #' @importFrom GPvecchia order_maxmin_exact +#' @importFrom sparseinv Takahashi_Davis #' #' @seealso Details section of [make_dsem_ram()] for a summary of the math involved with constructing the DSEM, and \doi{10.1111/2041-210X.14289} for more background on math and inference #' @seealso \doi{10.48550/arXiv.2401.10193} for more details on how GAM, SEM, and DSEM components are combined from a statistical and software-user perspective From dcb1bde3f99c24330750af782d98e5d860f82d76 Mon Sep 17 00:00:00 2001 From: James Thorson Date: Sat, 21 Nov 2026 11:48:03 +0100 Subject: [PATCH 33/37] try again to fix sanitizer Action --- .github/workflows/san-check.yaml | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/.github/workflows/san-check.yaml b/.github/workflows/san-check.yaml index ae17ac5f..d10788e2 100644 --- a/.github/workflows/san-check.yaml +++ b/.github/workflows/san-check.yaml @@ -21,24 +21,42 @@ jobs: steps: - uses: actions/checkout@v4 - - name: Use binary packages (avoid libc++/libstdc++ mismatch) + - name: Show compiler configuration run: | - . /etc/os-release - echo "Distro codename: ${VERSION_CODENAME}" - echo "options(repos = c(CRAN = 'https://packagemanager.posit.co/cran/__linux__/${VERSION_CODENAME}/latest'))" >> ~/.Rprofile - cat ~/.Rprofile + R CMD config CXX17 + R CMD config CXX17FLAGS + R CMD config CXX17STD + R CMD config CXXFLAGS + cat /etc/os-release | head -3 + + - name: Compile dependencies against libstdc++ (matches system GDAL) + run: | + mkdir -p ~/.R + cat > ~/.R/Makevars <<'EOF' + CXX=clang++ + CXX11=clang++ + CXX14=clang++ + CXX17=clang++ + CXX20=clang++ + CXXFLAGS=-O2 -fPIC + CXX11FLAGS=-O2 -fPIC + CXX14FLAGS=-O2 -fPIC + CXX17FLAGS=-O2 -fPIC + CXX20FLAGS=-O2 -fPIC + EOF - name: Install dependencies run: | R -q -e 'install.packages("pak")' - R -q -e 'pak::pkg_install(c("sf", "terra"), upgrade = FALSE)' R -q -e 'pak::pkg_install(c("local::.", "rcmdcheck", "knitr", "rmarkdown", "AER", "MARSS", "testthat", "RANN"))' - # R -q -e 'pak::pkg_install(c("phylopath", "reshape", "dynlm", "ggpubr", "vars", "DHARMa"))' # Other SUGGESTS packages - name: Check that sf loads run: | R -q -e 'library(sf); print(sf::sf_extSoftVersion())' + - name: Restore sanitizer compiler settings + run: rm -f ~/.R/Makevars + - name: Run check run: | R -q -e 'rcmdcheck::rcmdcheck(args = c("--no-manual", "--no-vignettes", "--no-build-vignettes"), build_args = c("--no-build-vignettes", "--no-build-vignettes"), error_on = "error")' \ No newline at end of file From 92c41f3ded86e4236095280e860450c47fee23a8 Mon Sep 17 00:00:00 2001 From: James Thorson Date: Sat, 21 Nov 2026 11:57:03 +0100 Subject: [PATCH 34/37] try once again to fix san-check.yaml --- .github/workflows/san-check.yaml | 33 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/.github/workflows/san-check.yaml b/.github/workflows/san-check.yaml index d10788e2..38e258ff 100644 --- a/.github/workflows/san-check.yaml +++ b/.github/workflows/san-check.yaml @@ -23,27 +23,26 @@ jobs: - name: Show compiler configuration run: | - R CMD config CXX17 - R CMD config CXX17FLAGS - R CMD config CXX17STD - R CMD config CXXFLAGS - cat /etc/os-release | head -3 + for v in CXX CXX17 CXX17FLAGS CXX17STD CXXFLAGS LDFLAGS; do + echo "$v = $(R CMD config $v)" + done - name: Compile dependencies against libstdc++ (matches system GDAL) run: | mkdir -p ~/.R - cat > ~/.R/Makevars <<'EOF' - CXX=clang++ - CXX11=clang++ - CXX14=clang++ - CXX17=clang++ - CXX20=clang++ - CXXFLAGS=-O2 -fPIC - CXX11FLAGS=-O2 -fPIC - CXX14FLAGS=-O2 -fPIC - CXX17FLAGS=-O2 -fPIC - CXX20FLAGS=-O2 -fPIC - EOF + : > ~/.R/Makevars + strip_stdlib() { sed -e 's/-stdlib=[A-Za-z+]*//g'; } + for s in "" 11 14 17 20; do + cxx=$(R CMD config CXX$s 2>/dev/null | strip_stdlib || true) + flags=$(R CMD config CXX${s}FLAGS 2>/dev/null | strip_stdlib || true) + if [ -n "$cxx" ]; then + echo "CXX$s = $cxx -stdlib=libstdc++" >> ~/.R/Makevars + echo "CXX${s}FLAGS = $flags" >> ~/.R/Makevars + fi + done + echo "LDFLAGS = $(R CMD config LDFLAGS | strip_stdlib)" >> ~/.R/Makevars + echo "---- ~/.R/Makevars ----" + cat ~/.R/Makevars - name: Install dependencies run: | From 0697e5b1c401e137be9d6f61b104d0409458c495 Mon Sep 17 00:00:00 2001 From: "James T. Thorson" Date: Sat, 21 Nov 2026 16:53:18 +0100 Subject: [PATCH 35/37] add CI test for cAIC --- DESCRIPTION | 2 +- NAMESPACE | 192 +++++++++++--------- R/cAIC.R | 6 +- man/cAIC.Rd | 2 +- tests/testthat/test-index-standardization.R | 5 + 5 files changed, 120 insertions(+), 87 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 120905bb..4674f382 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -77,4 +77,4 @@ LazyDataCompression: xz Roxygen: list(markdown = TRUE) URL: https://vast-lib.github.io/tinyVAST/ BugReports: https://github.com/vast-lib/tinyVAST/issues/ -Config/roxygen2/version: 8.0.0 +Config/roxygen2/version: 8.1.1 diff --git a/NAMESPACE b/NAMESPACE index 4424a552..5bc4f7f3 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -45,91 +45,119 @@ export(tweedie) import(methods) importFrom(GPvecchia,order_maxmin_exact) importFrom(GpGp,find_ordered_nn) -importFrom(Matrix,Cholesky) -importFrom(Matrix,Diagonal) -importFrom(Matrix,Matrix) -importFrom(Matrix,diag) -importFrom(Matrix,mat2triplet) -importFrom(Matrix,rowSums) -importFrom(Matrix,solve) -importFrom(Matrix,sparseMatrix) -importFrom(Matrix,t) -importFrom(TMB,MakeADFun) -importFrom(TMB,config) -importFrom(TMB,runSymbolicAnalysis) -importFrom(TMB,sdreport) +importFrom(Matrix, + Cholesky, + Diagonal, + Matrix, + diag, + mat2triplet, + rowSums, + solve, + sparseMatrix, + t +) +importFrom(TMB, + MakeADFun, + config, + runSymbolicAnalysis, + sdreport +) importFrom(abind,abind) -importFrom(checkmate,assertClass) -importFrom(checkmate,assertDataFrame) -importFrom(checkmate,assertInteger) -importFrom(checkmate,assertNumeric) -importFrom(cli,cli_abort) -importFrom(cli,cli_alert_danger) -importFrom(cli,cli_alert_info) -importFrom(cli,cli_alert_success) -importFrom(cli,cli_inform) -importFrom(cli,cli_warn) +importFrom(checkmate, + assertClass, + assertDataFrame, + assertInteger, + assertNumeric +) +importFrom(cli, + cli_abort, + cli_alert_danger, + cli_alert_info, + cli_alert_success, + cli_inform, + cli_warn +) importFrom(corpcor,pseudoinverse) -importFrom(cv,GetResponse) -importFrom(cv,cv) +importFrom(cv, + GetResponse, + cv +) importFrom(dsem,make_matrices) -importFrom(fmesher,fm_evaluator) -importFrom(fmesher,fm_fem) -importFrom(fmesher,fm_mesh_2d) -importFrom(igraph,as_adjacency_matrix) -importFrom(igraph,ecount) -importFrom(insight,get_data) -importFrom(insight,get_response) -importFrom(methods,as) -importFrom(methods,is) -importFrom(sdmTMB,lognormal) -importFrom(sdmTMB,nbinom1) -importFrom(sdmTMB,nbinom2) -importFrom(sdmTMB,student) -importFrom(sdmTMB,tweedie) -importFrom(sf,st_as_sf) -importFrom(sf,st_centroid) -importFrom(sf,st_coordinates) -importFrom(sf,st_crs) -importFrom(sf,st_distance) -importFrom(sf,st_geometry) -importFrom(sf,st_geometry_type) -importFrom(sf,st_length) -importFrom(sf,st_nearest_feature) -importFrom(sf,st_relate) -importFrom(sf,st_within) +importFrom(fmesher, + fm_evaluator, + fm_fem, + fm_mesh_2d +) +importFrom(igraph, + as_adjacency_matrix, + ecount +) +importFrom(insight, + get_data, + get_response +) +importFrom(methods, + as, + is +) +importFrom(sdmTMB, + lognormal, + nbinom1, + nbinom2, + student, + tweedie +) +importFrom(sf, + st_as_sf, + st_centroid, + st_coordinates, + st_crs, + st_distance, + st_geometry, + st_geometry_type, + st_length, + st_nearest_feature, + st_relate, + st_within +) importFrom(sfnetworks,activate) -importFrom(sparseinv,Takahashi_Davis) -importFrom(sparseinv,cholPermute) -importFrom(stats,.getXlevels) -importFrom(stats,Gamma) -importFrom(stats,as.formula) -importFrom(stats,binomial) -importFrom(stats,dist) -importFrom(stats,fitted) -importFrom(stats,gaussian) -importFrom(stats,lm) -importFrom(stats,logLik) -importFrom(stats,model.frame) -importFrom(stats,model.matrix) -importFrom(stats,model.offset) -importFrom(stats,model.response) -importFrom(stats,na.omit) -importFrom(stats,na.pass) -importFrom(stats,nlminb) -importFrom(stats,optim) -importFrom(stats,optimHess) -importFrom(stats,pnorm) -importFrom(stats,poisson) -importFrom(stats,predict) -importFrom(stats,rnorm) -importFrom(stats,sd) -importFrom(stats,simulate) -importFrom(stats,terms) -importFrom(stats,update) -importFrom(stats,update.formula) -importFrom(stats,vcov) +importFrom(sparseinv, + Takahashi_Davis, + cholPermute +) +importFrom(stats, + .getXlevels, + Gamma, + as.formula, + binomial, + dist, + fitted, + gaussian, + lm, + logLik, + model.frame, + model.matrix, + model.offset, + model.response, + na.omit, + na.pass, + nlminb, + optim, + optimHess, + pnorm, + poisson, + predict, + rnorm, + sd, + simulate, + terms, + update, + update.formula, + vcov +) importFrom(units,drop_units) -importFrom(utils,capture.output) -importFrom(utils,packageVersion) +importFrom(utils, + capture.output, + packageVersion +) useDynLib(tinyVAST, .registration = TRUE) diff --git a/R/cAIC.R b/R/cAIC.R index 81588e17..6c3a8722 100644 --- a/R/cAIC.R +++ b/R/cAIC.R @@ -68,7 +68,7 @@ cAIC <- function( object, what = c("cAIC", "EDF"), - method = c("stable", "fast") ){ + method = c("fast", "stable") ){ what = match.arg(what) method = match.arg(method) @@ -127,8 +127,8 @@ function( object, #} # h/t Jie Cao for suggesting spHess to avoid sparsifying a dense Hessian as done previously # Also dropping negative signs (which all cancel) - Hess_new = obj_new$env$spHess(par, random = TRUE) - Hess = obj$env$spHess(par, random = TRUE) + Hess_new = obj_new$env$spHess(parDataMode, random = TRUE) + Hess = obj$env$spHess(parDataMode, random = TRUE) #S = TMB:::solveSubset(Hess) S = sparseinv::Takahashi_Davis(Hess) negEDF = Matrix::rowSums(S * Hess_new) diff --git a/man/cAIC.Rd b/man/cAIC.Rd index a25f8f2c..13372385 100644 --- a/man/cAIC.Rd +++ b/man/cAIC.Rd @@ -4,7 +4,7 @@ \alias{cAIC} \title{Calculate conditional AIC} \usage{ -cAIC(object, what = c("cAIC", "EDF"), method = c("stable", "fast")) +cAIC(object, what = c("cAIC", "EDF"), method = c("fast", "stable")) } \arguments{ \item{object}{Output from \code{\link[=tinyVAST]{tinyVAST()}}.} diff --git a/tests/testthat/test-index-standardization.R b/tests/testthat/test-index-standardization.R index 474e7610..2b2c1fae 100644 --- a/tests/testthat/test-index-standardization.R +++ b/tests/testthat/test-index-standardization.R @@ -71,6 +71,11 @@ test_that("Basic index standardization works", { family = delta_gamma(type="poisson-link"), control = tinyVASTcontrol(gmrf="sep") ) expect_equal( my3$opt[c("par","objective")], my4$opt[c("par","objective")], tolerance=0.001 ) + + # check cAIC + expect_equal( cAIC(my1, method = "stable"), cAIC(my1, method = "fast"), tolerance=0.001 ) + expect_equal( cAIC(my2, method = "stable"), cAIC(my2, method = "fast"), tolerance=0.001 ) + expect_equal( cAIC(my3, method = "stable", what = "EDF"), cAIC(my3, method = "fast", what = "EDF"), tolerance=0.001 ) }) test_that("Index standardization results are identical in VAST, tinyVAST, and sdmTMB", { From bf04d8c045f7bbb9ec5b8ef02d4a3497e2caac0d Mon Sep 17 00:00:00 2001 From: "James T. Thorson" Date: Sat, 21 Nov 2026 16:53:53 +0100 Subject: [PATCH 36/37] prep for CRAN upload --- DESCRIPTION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 4674f382..644a2e10 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: tinyVAST Title: Multivariate Spatio-Temporal Models using Structural Equations -Version: 1.6.3.9999 +Version: 1.6.4 Date: 2026-11-21 Authors@R: c( person(c("James", "T."), "Thorson", , "James.Thorson@noaa.gov", From f7efd0f260bcf83a89a1332e58c08ade65928a4a Mon Sep 17 00:00:00 2001 From: "James T. Thorson" Date: Sat, 21 Nov 2026 20:18:37 +0100 Subject: [PATCH 37/37] make CRAN check happy --- .gitignore | 1 + R/cAIC.R | 2 ++ man/cAIC.Rd | 2 ++ 3 files changed, 5 insertions(+) diff --git a/.gitignore b/.gitignore index eefd9515..db28ed84 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,5 @@ inst/doc docs *.pdf *.Rhistory +scratch/*.tar.gz vignettes\.Rhistory diff --git a/R/cAIC.R b/R/cAIC.R index 6c3a8722..e530b49e 100644 --- a/R/cAIC.R +++ b/R/cAIC.R @@ -37,6 +37,7 @@ #' \doi{10.1080/00949655.2026.2736799} #' #' @examples +#' \donttest{ #' data( red_snapper ) #' red_snapper = droplevels(subset(red_snapper, Data_type=="Biomass_KG")) #' @@ -63,6 +64,7 @@ #' #' cAIC(fit) # conditional AIC #' AIC(fit) # marginal AIC +#' } #' #' @export cAIC <- diff --git a/man/cAIC.Rd b/man/cAIC.Rd index 13372385..1d0a9f1e 100644 --- a/man/cAIC.Rd +++ b/man/cAIC.Rd @@ -42,6 +42,7 @@ For models that include profiled fixed effects, these profiles are turned off. } \examples{ +\donttest{ data( red_snapper ) red_snapper = droplevels(subset(red_snapper, Data_type=="Biomass_KG")) @@ -67,6 +68,7 @@ fit = tinyVAST( data = red_snapper, cAIC(fit) # conditional AIC AIC(fit) # marginal AIC +} } \references{