-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathsdmTMB.cpp
1589 lines (1476 loc) · 59.1 KB
/
sdmTMB.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define TMB_LIB_INIT R_init_sdmTMB
#define EIGEN_DONT_PARALLELIZE
#include <TMB.hpp>
#include "utils.h"
// #include <omp.h>
enum valid_family {
gaussian_family = 0,
binomial_family = 1,
tweedie_family = 2,
poisson_family = 3,
Gamma_family = 4,
nbinom2_family = 5,
lognormal_family= 6,
student_family = 7,
Beta_family = 8,
truncated_nbinom2_family = 9,
nbinom1_family = 10,
truncated_nbinom1_family = 11,
censored_poisson_family = 12,
gamma_mix_family = 13,
lognormal_mix_family = 14,
nbinom2_mix_family = 15,
gengamma_family = 16
};
enum valid_link {
identity_link = 0,
log_link = 1,
logit_link = 2,
inverse_link = 3,
cloglog_link = 4
};
template <class Type>
Type InverseLink(Type eta, int link)
{
Type out;
switch (link) {
case identity_link:
out = eta;
break;
case log_link:
out = exp(eta);
break;
case logit_link:
out = invlogit(eta);
break;
case inverse_link:
out = Type(1.0) / eta;
break;
case cloglog_link:
out = Type(1) - exp(-exp(eta));
break;
default:
error("Link not implemented.");
}
return out;
}
// logit transformed inverse_linkfun without losing too much accuracy
template<class Type>
Type LogitInverseLink(Type eta, int link) {
Type ans;
switch (link) {
case logit_link:
ans = eta;
break;
case cloglog_link:
ans = sdmTMB::logit_invcloglog(eta);
break;
default:
ans = logit(InverseLink(eta, link));
}
return ans;
}
template <class Type>
Type Link(Type eta, int link)
{
Type out;
switch (link) {
case identity_link:
out = eta;
break;
case log_link:
out = log(eta);
break;
case logit_link:
out = logit(eta);
break;
case inverse_link:
out = Type(1.0) / eta;
break;
default:
error("Link not implemented.");
}
return out;
}
/* List of sparse matrices */
// taken from kaskr, https://github.com/kaskr/adcomp/issues/96
using namespace Eigen;
using namespace tmbutils;
template<class Type>
struct LOSM_t : vector<SparseMatrix<Type> > {
LOSM_t(SEXP x){ /* x = List passed from R */
(*this).resize(LENGTH(x));
for(int i=0; i<LENGTH(x); i++){
SEXP sm = VECTOR_ELT(x, i);
(*this)(i) = asSparseMatrix<Type>(sm);
}
}
};
// Modified from glmmTMB:
/* log-prob of non-zero value in conditional distribution */
template<class Type>
Type calc_log_nzprob(Type mu, Type phi, int family) {
Type ans, s1, s2;
switch (family) {
case truncated_nbinom1_family:
s2 = logspace_add(Type(0), log(phi)); // log(1. + phi(i)
ans = logspace_sub(Type(0), -mu / phi * s2); // 1-prob(0)
break;
case truncated_nbinom2_family:
s1 = log(mu);
// s2 := log( 1. + mu(i) / phi(i) )
s2 = logspace_add(Type(0), s1 - log(phi));
ans = logspace_sub(Type(0), -phi * s2);
break;
// case truncated_poisson_family:
// ans = logspace_sub(Type(0), -mu); // log(1-exp(-mu(i))) = P(x>0)
// break;
default: ans = Type(0);
}
return ans;
}
// ------------------ Main TMB template ----------------------------------------
template <class Type>
Type objective_function<Type>::operator()()
{
using namespace R_inla;
using namespace density;
using namespace Eigen;
// Vectors of real data
DATA_ARRAY(y_i); // response
DATA_STRUCT(X_ij, sdmTMB::LOM_t); // list of model matrices
DATA_MATRIX(z_i); // model matrix for spatial covariate effect
DATA_MATRIX(X_rw_ik); // model matrix for random walk covariate(s)
DATA_STRUCT(Zs, sdmTMB::LOM_t); // [L]ist [O]f (basis function matrices) [Matrices]
DATA_STRUCT(proj_Zs, sdmTMB::LOM_t); // [L]ist [O]f (basis function matrices) [Matrices]
DATA_MATRIX(Xs); // smoother linear effect matrix
DATA_MATRIX(proj_Xs); // smoother linear effect matrix
// DATA_VECTOR_INDICATOR(keep, y_i); // https://rdrr.io/cran/TMB/man/oneStepPredict.html
DATA_VECTOR(weights_i); // optional weights
DATA_VECTOR(offset_i); // optional offset
DATA_VECTOR(proj_offset_i); // optional offset
DATA_INTEGER(n_t); // number of years
// Random effects
DATA_IMATRIX(re_cov_df); // dataframe describing the random effects covariance parameters
DATA_IMATRIX(re_cov_df_map); // dataframe describing the groups of random effects covariance parameters
DATA_IMATRIX(re_b_df);// dataframe describing the random effects parameters
DATA_IMATRIX(re_b_map);// dataframe describing the groups of random effects parameters
DATA_IVECTOR(n_re_groups);
DATA_STRUCT(Zt_list, LOSM_t); // list of model matrices for random effects
DATA_STRUCT(Zt_list_proj, LOSM_t); // list of model matrices for random effects (prediction)
DATA_IMATRIX(var_indx_matrix); // matrix of indices of each level/group with the appropriate sd
DATA_SPARSE_MATRIX(A_st); // INLA 'A' projection matrix for unique stations
DATA_IVECTOR(A_spatial_index); // Vector of stations to match up A_st output
// Indices for factors
DATA_FACTOR(year_i);
DATA_INTEGER(normalize_in_r);
DATA_INTEGER(flag);
DATA_IVECTOR(share_range);
// Prediction?
DATA_INTEGER(do_predict);
// With standard errors on the full projections?
DATA_INTEGER(calc_se);
// Should predictions be population (vs. individual-level) predictions?
DATA_INTEGER(pop_pred);
// Calculate total summed by year (e.g. biomass)?
DATA_INTEGER(calc_index_totals);
DATA_INTEGER(calc_cog);
DATA_INTEGER(calc_eao);
// DATA_INTEGER(calc_quadratic_range); // DELTA TODO
DATA_VECTOR(area_i); // area per prediction grid cell for index standardization
DATA_VECTOR(priors_b_mean);
DATA_MATRIX(priors_b_Sigma); // beta priors matrix
DATA_INTEGER(priors_b_n);
DATA_IVECTOR(priors_b_index);
DATA_MATRIX(priors_sigma_V); // time-varying params SD
DATA_VECTOR(priors); // all other priors as a vector
DATA_IVECTOR(ar1_fields);
DATA_IVECTOR(rw_fields);
DATA_IVECTOR(include_spatial); // include spatial intercept field(s)?
DATA_INTEGER(omit_spatial_intercept);
DATA_INTEGER(random_walk);
DATA_INTEGER(ar1_time);
DATA_INTEGER(exclude_RE); // DELTA TODO currently shared...
DATA_INTEGER(no_spatial); // omit all spatial calculations
DATA_VECTOR(proj_lon);
DATA_VECTOR(proj_lat);
// Distribution
DATA_IVECTOR(family);
DATA_IVECTOR(link);
DATA_SCALAR(df); // Student-t DF
DATA_VECTOR(size); // binomial, via glmmTMB
// SPDE objects from R-INLA
DATA_STRUCT(spde_aniso, spde_aniso_t);
DATA_STRUCT(spde, spde_t);
PARAMETER_ARRAY(ln_H_input);
DATA_INTEGER(anisotropy);
// Barrier
DATA_INTEGER(barrier);
DATA_STRUCT(spde_barrier, sdmTMB::spde_barrier_t);
DATA_VECTOR(barrier_scaling); // scaling of range
// Projections
DATA_SPARSE_MATRIX(proj_mesh);
DATA_STRUCT(proj_X_ij, sdmTMB::LOM_t);
DATA_MATRIX(proj_X_rw_ik);
DATA_FACTOR(proj_year);
DATA_MATRIX(proj_z_i);
DATA_IVECTOR(proj_spatial_index);
DATA_IVECTOR(spatial_only); // !spatial_only means include spatiotemporal(!)
DATA_INTEGER(spatial_covariate); // include SVC?
DATA_VECTOR(X_threshold);
DATA_VECTOR(proj_X_threshold);
DATA_INTEGER(threshold_func);
// optional model for nonstationary st variance
DATA_INTEGER(est_epsilon_model);
DATA_INTEGER(est_epsilon_slope);
DATA_INTEGER(est_epsilon_re);
DATA_VECTOR(epsilon_predictor);
// optional stuff for penalized regression splines
DATA_INTEGER(has_smooths); // whether or not smooths are included
DATA_IVECTOR(b_smooth_start);
DATA_IVECTOR(sim_re); // sim random effects? 0,1; order: omega, epsilon, zeta, IID, RW, smoothers
DATA_IVECTOR(simulate_t); // sim this specific time step? (used for forecasting)
DATA_INTEGER(sim_obs);
DATA_VECTOR(lwr); // lower bound for censpois on counts
DATA_VECTOR(upr); // upper bound for censpois on counts
DATA_INTEGER(poisson_link_delta); // logical
DATA_INTEGER(stan_flag); // logical whether to pass the model to Stan
// ------------------ Parameters ---------------------------------------------
// Parameters
// Fixed effects
PARAMETER_VECTOR(b_j); // fixed effect parameters
PARAMETER_VECTOR(b_j2); // fixed effect parameters delta2 part
PARAMETER_ARRAY(bs); // smoother linear effects
PARAMETER_VECTOR(ln_tau_O); // spatial process
PARAMETER_ARRAY(ln_tau_Z); // optional spatially varying covariate process
PARAMETER_VECTOR(ln_tau_E); // spatio-temporal process
PARAMETER_ARRAY(ln_kappa); // Matern parameter
PARAMETER(thetaf); // tweedie only
PARAMETER(gengamma_Q); // gengamma only
PARAMETER(logit_p_mix); // ECE / positive mixture only
PARAMETER(log_ratio_mix); // ECE / positive mixture only
PARAMETER_VECTOR(ln_phi); // sigma / dispersion / etc.
PARAMETER_ARRAY(ln_tau_V); // random walk sigma
PARAMETER_ARRAY(rho_time_unscaled); // (k, m) dimension ar1 time correlation rho -Inf to Inf
PARAMETER_VECTOR(ar1_phi); // AR1 fields correlation
// Random effects
PARAMETER_ARRAY(re_cov_pars); // covariance parameters for random slopes/intercepts
PARAMETER_ARRAY(re_b_pars); // beta parameters for random slopes/intercepts
PARAMETER_ARRAY(b_rw_t); // random walk effects
PARAMETER_ARRAY(omega_s); // spatial effects; n_s length
PARAMETER_ARRAY(zeta_s); // spatial effects on covariate; n_s length, n_z cols, n_m
PARAMETER_ARRAY(epsilon_st); // spatio-temporal effects; n_s by n_t by n_m array
PARAMETER_ARRAY(b_threshold); // coefficients for threshold relationship (3) // DELTA TODO
PARAMETER_VECTOR(b_epsilon); // slope coefficient for log-linear model on epsilon
PARAMETER_VECTOR(ln_epsilon_re_sigma);
PARAMETER_ARRAY(epsilon_re);
PARAMETER_ARRAY(b_smooth); // P-spline smooth parameters
PARAMETER_ARRAY(ln_smooth_sigma); // variances of spline REs if included
// Joint negative log-likelihood
Type jnll = 0.;
// ------------------ End of parameters --------------------------------------
// DELTA DONE
int n_i = y_i.rows(); // number of observations
int n_m = y_i.cols(); // number of models (delta)
// DELTA TODO
// ------------------ Derived variables -------------------------------------------------
vector<Type> s_slope(n_m), s_cut(n_m), s50(n_m), s95(n_m), s_max(n_m);
// these are for linear model
for (int m = 0; m < n_m; m++) {
s_slope(m) = b_threshold(0,m);
s_cut(m) = b_threshold(1,m);
if (threshold_func == 2) {
s50(m) = b_threshold(0,m); // threshold at which function is 50% of max
s95(m) = b_threshold(0,m) + exp(b_threshold(1,m)); // threshold at which function is 95% of max
s_max(m) = b_threshold(2,m);
}
}
// DELTA DONE
vector<Type> rho(n_m);
for (int m = 0; m < n_m; m++) rho(m) = sdmTMB::minus_one_to_one(ar1_phi(m));
vector<Type> phi = exp(ln_phi);
// ------------------ Geospatial ---------------------------------------------
// DELTA DONE
// Matern:
array<Type> range(2,n_m);
for (int m = 0; m < n_m; m++) {
for (int r = 0; r < 2; r++) {
range(r,m) = sqrt(Type(8.)) / exp(ln_kappa(r,m));
}
}
// DELTA DONE
array<Type> sigma_O(1,n_m); // array b/c ADREPORT crashes if vector elements mapped
array<Type> log_sigma_O(1,n_m); // array b/c ADREPORT crashes if vector elements mapped
int n_z = ln_tau_Z.rows();
array<Type> sigma_Z(n_z, n_m);
array<Type> log_sigma_Z(n_z,n_m); // for SE
for (int m = 0; m < n_m; m++) {
if (include_spatial(m)) {
sigma_O(0,m) = sdmTMB::calc_rf_sigma(ln_tau_O(m), ln_kappa(0,m));
log_sigma_O(0,m) = log(sigma_O(0,m));
}
if (spatial_covariate) {
for (int z = 0; z < n_z; z++) {
sigma_Z(z,m) = sdmTMB::calc_rf_sigma(ln_tau_Z(z,m), ln_kappa(0,m));
}
for (int z = 0; z < n_z; z++)
for (int m = 0; m < n_m; m++)
log_sigma_Z(z,m) = log(sigma_Z(z,m));
}
}
REPORT(sigma_Z);
ADREPORT(sigma_Z);
ADREPORT(log_sigma_Z);
REPORT(sigma_O);
ADREPORT(sigma_O);
ADREPORT(log_sigma_O);
ADREPORT(log_sigma_Z);
// TODO can we not always run this for speed?
//vector<Type> sigma_E(n_m);
//for (int m = 0; m < n_m; m++) {
// sigma_E(m) = sdmTMB::calc_rf_sigma(ln_tau_E(m), ln_kappa(1,m));
//}
// optional non-stationary model on epsilon
array<Type> sigma_E(n_t, n_m);
array<Type> ln_tau_E_vec(n_t, n_m);
if (!est_epsilon_model) { // constant model
for (int m = 0; m < n_m; m++) {
// do calculation once,
sigma_E(0,m) = sdmTMB::calc_rf_sigma(ln_tau_E(m), ln_kappa(1,m));
ln_tau_E_vec(0,m) = ln_tau_E(m);
for (int i = 1; i < n_t; i++) {
sigma_E(i,m) = sigma_E(0,m);
ln_tau_E_vec(i,m) = ln_tau_E_vec(0,m);
}
}
}
if (est_epsilon_model) { // loglinear model
// epsilon_intcpt is the intercept parameter, derived from ln_tau_E.
// For models with time as covariate, this is interpreted as sigma when covariate = 0.
for (int m = 0; m < n_m; m++) {
Type epsilon_intcpt = sdmTMB::calc_rf_sigma(ln_tau_E(m), ln_kappa(1,m));
Type log_epsilon_intcpt = log(epsilon_intcpt);
Type log_epsilon_temp = 0.0;
Type epsilon_cnst = - log(Type(4.0) * M_PI) / Type(2.0) - ln_kappa(1,m);
if (est_epsilon_re) {
Type epsilon_re_sigma = exp(ln_epsilon_re_sigma(m));
for (int i = 0; i < n_t; i++) {
jnll -= dnorm(epsilon_re(i,m), Type(0), Type(epsilon_re_sigma), true);
}
}
for(int i = 0; i < n_t; i++) {
log_epsilon_temp = log_epsilon_intcpt;
if (est_epsilon_slope) log_epsilon_temp += b_epsilon(m) * epsilon_predictor(i);
if (est_epsilon_re) log_epsilon_temp += epsilon_re(i,m);
sigma_E(i,m) = exp(log_epsilon_temp); // log-linear model
ln_tau_E_vec(i,m) = -log_epsilon_temp + epsilon_cnst;
}
}
}
array<Type> log_sigma_E(sigma_E.rows(),sigma_E.cols()); // for SE
log_sigma_E.setZero();
for (int i = 0; i < sigma_E.rows(); i++) {
for (int m = 0; m < sigma_E.cols(); m++) {
log_sigma_E(i,m) = log(sigma_E(i,m));
}
}
REPORT(sigma_E); // spatio-temporal SD
ADREPORT(sigma_E);
ADREPORT(log_sigma_E); // log spatio-temporal SD
Eigen::SparseMatrix<Type> Q_s; // Precision matrix
Eigen::SparseMatrix<Type> Q_st; // Precision matrix
Eigen::SparseMatrix<Type> Q_s2; // Precision matrix
Eigen::SparseMatrix<Type> Q_st2; // Precision matrix
if (barrier) {
Q_s = Q_spde(spde_barrier, exp(ln_kappa(0,0)), barrier_scaling);
if (n_m > 1) Q_s2 = Q_spde(spde_barrier, exp(ln_kappa(0,1)), barrier_scaling);
if (!share_range(0)) Q_st = Q_spde(spde_barrier, exp(ln_kappa(1,0)), barrier_scaling);
if (!share_range(1) && n_m > 1) Q_st2 = Q_spde(spde_barrier, exp(ln_kappa(1,1)), barrier_scaling);
} else {
if (anisotropy) {
matrix<Type> H = sdmTMB::MakeH(vector<Type>(ln_H_input.col(0)));
Q_s = R_inla::Q_spde(spde_aniso, exp(ln_kappa(0,0)), H);
if (!share_range(0)) Q_st = R_inla::Q_spde(spde_aniso, exp(ln_kappa(1,0)), H);
REPORT(H);
if (n_m > 1) {
matrix<Type> H2 = sdmTMB::MakeH(vector<Type>(ln_H_input.col(1)));
Q_s2 = R_inla::Q_spde(spde_aniso, exp(ln_kappa(0,1)), H2);
if (!share_range(1)) Q_st2 = R_inla::Q_spde(spde_aniso, exp(ln_kappa(1,1)), H2);
REPORT(H2);
}
}
if (!anisotropy) {
Q_s = R_inla::Q_spde(spde, exp(ln_kappa(0,0)));
if (!share_range(0)) Q_st = R_inla::Q_spde(spde, exp(ln_kappa(1,0)));
if (n_m > 1) Q_s2 = R_inla::Q_spde(spde, exp(ln_kappa(0,1)));
if (!share_range(1) && n_m > 1) Q_st2 = R_inla::Q_spde(spde, exp(ln_kappa(1,1)));
}
}
if (share_range(0)) Q_st = Q_s;
if (share_range(1)) Q_st2 = Q_s2;
bool s = true;
if (normalize_in_r) s = false;
// Spatial (intercept) random effects:
for (int m = 0; m < n_m; m++) {
if (include_spatial(m)) {
Eigen::SparseMatrix<Type> Q_temp; // Precision matrix
if (include_spatial(m)) {
if (m == 0) {
Q_temp = Q_s;
} else {
Q_temp = Q_s2;
}
if (!omit_spatial_intercept) {
PARALLEL_REGION jnll += SCALE(GMRF(Q_temp, s), 1. / exp(ln_tau_O(m)))(omega_s.col(m));
if (sim_re(0)) {
vector<Type> omega_s_tmp(omega_s.rows());
SIMULATE {
GMRF(Q_temp, s).simulate(omega_s_tmp);
omega_s.col(m) = omega_s_tmp / exp(ln_tau_O(m));
}
}
}
if (spatial_covariate) {
for (int z = 0; z < n_z; z++) {
PARALLEL_REGION jnll += SCALE(GMRF(Q_temp, s), 1. / exp(ln_tau_Z(z,m)))(zeta_s.col(m).col(z));
if (sim_re(3)) {
vector<Type> zeta_s_tmp(zeta_s.col(m).rows());
SIMULATE {
GMRF(Q_s, s).simulate(zeta_s_tmp);
zeta_s.col(m).col(z) = zeta_s_tmp / exp(ln_tau_Z(z,m));
}
}
}
}
}
}
}
// Spatiotemporal random effects:
for (int m = 0; m < n_m; m++) {
Eigen::SparseMatrix<Type> Q_temp; // Precision matrix
if (m == 0) {
Q_temp = Q_st;
} else {
Q_temp = Q_st2;
}
if (!spatial_only(m)) {
if (!ar1_fields(m) && !rw_fields(m)) {
for (int t = 0; t < n_t; t++)
PARALLEL_REGION jnll += SCALE(GMRF(Q_temp, s), 1. / exp(ln_tau_E_vec(t,m)))(epsilon_st.col(m).col(t));
if (sim_re(1)) {
for (int t = 0; t < n_t; t++) {
if (simulate_t(t)) {
vector<Type> epsilon_st_tmp(epsilon_st.col(m).rows());
SIMULATE {GMRF(Q_temp, s).simulate(epsilon_st_tmp);
epsilon_st.col(m).col(t) = epsilon_st_tmp / exp(ln_tau_E_vec(t,m));}
}
}
}
} else {
if (ar1_fields(m)) { // not using separable(ar1()) so we can simulate by time step
// PARALLEL_REGION jnll += SCALE(SEPARABLE(AR1(rho(m)), GMRF(Q_temp, s)), 1./exp(ln_tau_E(m)))(epsilon_st.col(m));
// Split out by year so we can turn on/off simulation by year and model covariates of ln_tau_E:
PARALLEL_REGION jnll += SCALE(GMRF(Q_temp, s), 1. / exp(ln_tau_E_vec(0,m)))(epsilon_st.col(m).col(0));
for (int t = 1; t < n_t; t++) {
PARALLEL_REGION jnll += SCALE(GMRF(Q_temp, s), 1. /exp(ln_tau_E_vec(t,m)))((epsilon_st.col(m).col(t) -
rho(m) * epsilon_st.col(m).col(t - 1))/sqrt(1. - rho(m) * rho(m)));
}
Type n_cols = epsilon_st.col(m).cols();
Type n_rows = epsilon_st.col(m).rows();
// Penalty to match TMB AR1_t() implementation:
PARALLEL_REGION jnll += Type((n_cols - 1.) * n_rows) * log(sqrt(1. - rho(m) * rho(m)));
if (sim_re(1)) {
// array<Type> epsilon_st_tmp(epsilon_st.col(m).rows(),n_t);
// SIMULATE {SEPARABLE(AR1(rho(m)), GMRF(Q_temp, s)).simulate(epsilon_st_tmp);
// epsilon_st.col(m) = epsilon_st_tmp / exp(ln_tau_E(m));}
for (int t = 0; t < n_t; t++) {
if (simulate_t(t)) {
vector<Type> epsilon_st_tmp(epsilon_st.col(m).rows());
SIMULATE {
GMRF(Q_temp, s).simulate(epsilon_st_tmp);
epsilon_st_tmp *= 1./exp(ln_tau_E_vec(t,m));
// https://kaskr.github.io/adcomp/classdensity_1_1AR1__t.html
Type ar1_scaler = sqrt(1. - rho(m) * rho(m));
if (t == 0) {
epsilon_st.col(m).col(0) = epsilon_st_tmp; // no scaling of first step
} else {
epsilon_st.col(m).col(t) = rho(m) * epsilon_st.col(m).col(t-1) + epsilon_st_tmp * ar1_scaler;
}
}
}
}
}
ADREPORT(rho);
} else if (rw_fields(m)) {
PARALLEL_REGION jnll += SCALE(GMRF(Q_temp, s), 1./exp(ln_tau_E_vec(0,m)))(epsilon_st.col(m).col(0));
for (int t = 1; t < n_t; t++) {
PARALLEL_REGION jnll += SCALE(GMRF(Q_temp, s),
1./exp(ln_tau_E_vec(t,m)))(epsilon_st.col(m).col(t) - epsilon_st.col(m).col(t - 1));
}
if (sim_re(1)) {
for (int t = 0; t < n_t; t++) {
if (simulate_t(t)) {
vector<Type> epsilon_st_tmp(epsilon_st.col(m).rows());
SIMULATE {
GMRF(Q_temp, s).simulate(epsilon_st_tmp);
epsilon_st_tmp *= 1./exp(ln_tau_E_vec(t,m));
if (t == 0) {
epsilon_st.col(m).col(0) = epsilon_st_tmp;
} else {
epsilon_st.col(m).col(t) = epsilon_st.col(m).col(t-1) + epsilon_st_tmp;
}
}
}
}
}
} else {
error("Field type not implemented.");
}
}
}
}
if (flag == 0) return jnll;
// ------------------ Probability of random effects --------------------------
// re_cov_pars , re_b_pars will be a 2D PARAMETER_ARRAY
int g_index = -1;
for (int m = 0; m < n_m; m++) {
for (int g = 0; g < n_re_groups(m); g++) { // loop over each group in the model
// construct the variance covariance matrix based on the dimension
// for example, (1|x) would have 1 dimension; (day+school|x) would have 3
// fill the covariance matrix and evaluate the likelihood. The elements of Z that
// get passed in are ordered by group -- so that they are
// level1_group1 / level2_group1 / level3_group1 / ... / level1_group2 / level2_group2
// cycle through rows of re_cov_df_map
g_index = g_index + 1;
int n = re_cov_df_map(g_index, 1); // dimension of random effects for this group
// unconstrained params here are the lower triangular of the cholesky corr matrix, and sds are the diagonal
vector<Type> unconstrained_params(n*(n-1)/2); // Dummy parameterization of correlation matrix
vector<Type> sds(n); // Standard deviations
int par_indx = 0;
int jj = 0;
for (jj = re_cov_df_map(g_index, 2); jj <= re_cov_df_map(g_index, 3); jj++) {
if(re_cov_df(jj,3) == 1) { // standard deviation, is_sd indexed as col 3
sds(re_cov_df(jj,2)) = exp(re_cov_pars(jj,m)); // sd estimated in log_space
} else {
unconstrained_params(par_indx) = re_cov_pars(jj,m);
par_indx = par_indx + 1;
}
}
// covariance matrix has now been constructed. we have to cycle through all of the levels
// for this group to evaluate the probability of joint random effects
vector<Type> b_re_vec(n); // this is the vectorized version of the corr matrix for this group
for (int levels = re_b_map(g_index,1); levels <= re_b_map(g_index,2); levels++) {
// this is indexing of indexing
jj = 0;
// this_level is indexing the elements of b_re_vec re_b_pars(,m) associated with this group and level
for (int this_level = re_b_df(levels,0); this_level <= re_b_df(levels,1); this_level++) {
b_re_vec(jj) = re_b_pars(this_level,m);
if (n == 1) {
// evaluate univariate / uncorrelated REs. can be slopes or intercepts
PARALLEL_REGION jnll -= dnorm(re_b_pars(this_level,m), Type(0), Type(sds(var_indx_matrix(jj,m))), true);
if (sim_re(3)) SIMULATE{re_b_pars(this_level,m) = rnorm(Type(0), Type(sds(var_indx_matrix(jj,m))));}
}
jj = jj + 1;
}
// evaluate likelihood for the betas corresponding to this group + level
if (n > 1) {
// multivariate densities from from namespace 'density' return the negative log likelihood. So code should be:
jnll += VECSCALE(UNSTRUCTURED_CORR(unconstrained_params),sds)(b_re_vec);
if (sim_re(3)) error("Simulation not implemented for random slopes/intercepts yet");
}
} // end for levels
} // end for g
} // end for m
REPORT(re_cov_pars);
ADREPORT(re_cov_pars);
REPORT(re_b_pars);
ADREPORT(re_b_pars);
array<Type> sigma_V(X_rw_ik.cols(),n_m);
// Time-varying effects (dynamic regression):
if (random_walk == 1 || ar1_time || random_walk == 2) {
array<Type> rho_time(X_rw_ik.cols(), n_m);
rho_time.setZero();
for (int m = 0; m < n_m; m++) {
for (int k = 0; k < X_rw_ik.cols(); k++) {
sigma_V(k,m) = exp(ln_tau_V(k,m));
if (random_walk == 1) { // type = 'rw'
// flat prior on the initial value... then:
for (int t = 1; t < n_t; t++) {
PARALLEL_REGION jnll -=
dnorm(b_rw_t(t, k, m), b_rw_t(t - 1, k, m), sigma_V(k,m), true);
if (sim_re(4) && simulate_t(t))
SIMULATE{b_rw_t(t, k, m) = rnorm(b_rw_t(t - 1, k, m), sigma_V(k,m));}
}
} else if (random_walk == 2) { // type = 'rw0'
// N(0, SD) prior on the initial value... then:
for (int t = 0; t < n_t; t++) {
if (t == 0) {
PARALLEL_REGION jnll -=
dnorm(b_rw_t(t, k, m), Type(0.), sigma_V(k,m), true);
if (sim_re(4) && simulate_t(t))
SIMULATE{b_rw_t(t, k, m) = rnorm(Type(0.), sigma_V(k,m));}
} else {
PARALLEL_REGION jnll -=
dnorm(b_rw_t(t, k, m), b_rw_t(t - 1, k, m), sigma_V(k,m), true);
if (sim_re(4) && simulate_t(t))
SIMULATE{b_rw_t(t, k, m) = rnorm(b_rw_t(t - 1, k, m), sigma_V(k,m));}
}
}
} else if (ar1_time) { // type = 'ar1'
rho_time(k, m) = sdmTMB::minus_one_to_one(rho_time_unscaled(k, m));
jnll += SCALE(AR1(rho_time(k, m)), sigma_V(k,m))(vector<Type>(b_rw_t.col(m).col(k)));
if (sim_re(4)) {
// https://kaskr.github.io/adcomp/classdensity_1_1AR1__t.html
vector<Type> tmp(n_t);
Type ar1_sigma = sqrt(Type(1) - rho_time(k, m) * rho_time(k, m));
Type x0 = rnorm(Type(0), sigma_V(k,m));
tmp(0) = rho_time(k, m) * x0 + ar1_sigma * rnorm(Type(0), sigma_V(k,m));
for (int t = 1; t < n_t; t++)
tmp(t) = rho_time(k, m) * tmp(t-1) + ar1_sigma * rnorm(Type(0), sigma_V(k,m));
for(int t = 0; t < n_t; t++)
if (simulate_t(t)) SIMULATE{b_rw_t(t, k, m) = tmp(t);}
}
} else {
error("Time-varying type not found.");
}
}
}
REPORT(sigma_V);
ADREPORT(sigma_V); // time-varying SD
}
// ------------------ INLA projections ---------------------------------------
// Here we are projecting the spatiotemporal and spatial random effects to the
// locations of the data using the INLA 'A' matrices.
array<Type> omega_s_A(n_i, n_m);
array<Type> zeta_s_A(n_i, n_z, n_m);
array<Type> epsilon_st_A(n_i, n_t, n_m);
array<Type> epsilon_st_A_vec(n_i, n_m);
omega_s_A.setZero();
zeta_s_A.setZero();
epsilon_st_A.setZero();
epsilon_st_A_vec.setZero();
if (!no_spatial) {
for (int m = 0; m < n_m; m++) {
for (int t = 0; t < n_t; t++)
if (!spatial_only(m)) epsilon_st_A.col(m).col(t) =
A_st * vector<Type>(epsilon_st.col(m).col(t));
if (!omit_spatial_intercept) omega_s_A.col(m) = A_st * vector<Type>(omega_s.col(m));
for (int z = 0; z < n_z; z++)
zeta_s_A.col(m).col(z) = A_st * vector<Type>(zeta_s.col(m).col(z));
}
}
// ------------------ Linear predictor ---------------------------------------
array<Type> eta_fixed_i(n_i, n_m);
for (int m = 0; m < n_m; m++) {
if (m == 0) eta_fixed_i.col(m) = X_ij(m) * b_j;
if (m == 1) eta_fixed_i.col(m) = X_ij(m) * b_j2;
}
// FIXME delta must be same in 2 components:
// p-splines/smoothers
array<Type> eta_smooth_i(n_i, n_m);
eta_smooth_i.setZero();
if (has_smooths) {
for (int m = 0; m < n_m; m++) {
for (int s = 0; s < b_smooth_start.size(); s++) { // iterate over # of smooth elements
array<Type> beta_s(Zs(s).cols(),n_m);
beta_s.setZero();
for (int j = 0; j < beta_s.rows(); j++) {
beta_s(j,m) = b_smooth(b_smooth_start(s) + j,m);
PARALLEL_REGION jnll -= dnorm(beta_s(j,m), Type(0), exp(ln_smooth_sigma(s,m)), true);
if (sim_re(5)) SIMULATE{beta_s(j,m) = rnorm(Type(0), exp(ln_smooth_sigma(s,m)));}
}
eta_smooth_i.col(m) += Zs(s) * vector<Type>(beta_s.col(m));
}
eta_smooth_i.col(m) += Xs * vector<Type>(bs.col(m));
}
REPORT(b_smooth); // smooth coefficients for penalized splines
REPORT(ln_smooth_sigma); // standard deviations of smooth random effects, in log-space
}
// add threshold effect if specified
if (threshold_func > 0) {
if (threshold_func == 1) {
// linear
for (int m = 0; m < n_m; m++) {
for (int i = 0; i < n_i; i++) {
eta_fixed_i(i,m) += sdmTMB::linear_threshold(X_threshold(i), s_slope(m), s_cut(m));
}
}
} else {
// logistic
for (int m = 0; m < n_m; m++) {
for (int i = 0; i < n_i; i++) {
eta_fixed_i(i,m) += sdmTMB::logistic_threshold(X_threshold(i), s50(m), s95(m), s_max(m));
}
}
}
}
matrix<Type> mu_i(n_i,n_m), eta_i(n_i,n_m), eta_rw_i(n_i,n_m), eta_iid_re_i(n_i,n_m);
eta_rw_i.setZero();
eta_iid_re_i.setZero();
mu_i.setZero();
eta_i.setZero();
vector<Type> poisson_link_m0_ll(n_i);
// combine parts:
for (int m = 0; m < n_m; m++) {
// this is the matrix multiplication for all random effects for this model.
if (n_re_groups(m) > 0) {
// Extract the m-th column an Eigen vector
Eigen::Matrix<Type, Eigen::Dynamic, 1> col_vec = re_b_pars.col(m);
Eigen::SparseMatrix<Type> temp_Z = Zt_list(m);
for (int j = 0; j < temp_Z.rows(); j++) {
eta_iid_re_i.col(m) += Zt_list(m).row(j) * col_vec(j);
}
}
for (int i = 0; i < n_i; i++) {
eta_i(i,m) = eta_fixed_i(i,m) + eta_smooth_i(i,m);
if ((n_m == 2 && m == 1) || n_m == 1) {
if (!poisson_link_delta) eta_i(i,m) += offset_i(i);
}
if (random_walk == 1 || ar1_time || random_walk == 2) {
for (int k = 0; k < X_rw_ik.cols(); k++) {
eta_rw_i(i,m) += X_rw_ik(i, k) * b_rw_t(year_i(i), k, m); // record it
eta_i(i,m) += eta_rw_i(i,m);
}
}
// Spatially varying effects:
if (include_spatial(m)) {
if (!omit_spatial_intercept) // FIXME needs to be an n_m vector??
eta_i(i,m) += omega_s_A(i,m); // spatial omega
}
if (spatial_covariate)
for (int z = 0; z < n_z; z++)
eta_i(i,m) += zeta_s_A(i,z,m) * z_i(i,z); // spatially varying covariate DELTA
if (!no_spatial) epsilon_st_A_vec(i,m) = epsilon_st_A(A_spatial_index(i), year_i(i),m); // record it
eta_i(i,m) += epsilon_st_A_vec(i,m); // spatiotemporal
eta_i(i,m) += eta_iid_re_i(i,m);
if (family(m) == binomial_family && !poisson_link_delta) { // regular binomial
mu_i(i,m) = LogitInverseLink(eta_i(i,m), link(m));
} else if (poisson_link_delta) { // a tweak on cloglog:
// eta_i(i,0) = log numbers density
// eta_i(i,1) = log average weight
// mu_i(i,0) = probability of occurrence
// mu_i(i,1) = positive density prediction
Type log_one_minus_p = -exp(offset_i(i) + eta_i(i,0));
Type log_p = logspace_sub(Type(0.0), log_one_minus_p);
if (m == 0) {
if (y_i(i,0) > Type(0.0)) {
poisson_link_m0_ll(i) = log_p; // calc ll here; more robust than dbinom_robust(logit(p))
} else {
poisson_link_m0_ll(i) = log_one_minus_p; // log(1 - p)
}
mu_i(i,0) = exp(log_p); // just for recording; not used in ll b/c robustness
}
if (m == 1) mu_i(i,1) = exp(offset_i(i) + eta_i(i,0) + eta_i(i,1) - log_p);
} else { // all the regular stuff:
mu_i(i,m) = InverseLink(eta_i(i,m), link(m));
}
}
}
// ------------------ Probability of data given random effects ---------------
// from glmmTMB:
// close to zero: use for count data (cf binomial()$initialize)
#define zt_lik_nearzero(x,loglik_exp) ((x < Type(0.001)) ? -INFINITY : loglik_exp)
Type s1, s2, s3, lognzprob, tmp_ll, ll_1, ll_2, p_mix, mix_ratio, tweedie_p, s2_large;
// calcs for mix distr. first:
int pos_model;
if (n_m > 1) {
pos_model = 1;
} else {
pos_model = 0;
}
vector<Type> mu_i_large(n_i);
switch (family(pos_model)) {
case gamma_mix_family:
case lognormal_mix_family:
case nbinom2_mix_family: {
p_mix = invlogit(logit_p_mix); // probability of larger event
mix_ratio = exp(log_ratio_mix) + Type(1.); // ratio of large:small values, constrained > 1.0
for (int i = 0; i < n_i; i++) {
mu_i_large(i) = exp(log(mu_i(i, pos_model)) + log(mix_ratio)); // mean of large component = mean of smaller * ratio
}
ADREPORT(logit_p_mix);
ADREPORT(log_ratio_mix);
REPORT(p_mix);
REPORT(mix_ratio);
break;
}
default:
break;
}
if (!sim_obs) {
for (int m = 0; m < n_m; m++) {
for (int i = 0; i < n_i; i++) {
y_i(i,m) = mu_i(i,m);
}
}
}
vector<Type> jnll_obs(n_i); // for cross validation
jnll_obs.setZero();
for (int m = 0; m < n_m; m++) PARALLEL_REGION {
for (int i = 0; i < n_i; i++) {
bool notNA = !sdmTMB::isNA(y_i(i,m));
switch (family(m)) {
case gaussian_family: {
if (notNA) tmp_ll = dnorm(y_i(i,m), mu_i(i,m), phi(m), true);
if (sim_obs) SIMULATE{y_i(i,m) = rnorm(mu_i(i,m), phi(m));}
break;
}
case tweedie_family: {
tweedie_p = invlogit(thetaf) + Type(1.0);
// FIXME! move this out of loop!!!!!!!!
if (!sdmTMB::isNA(priors(12))) {
error("Priors not enabled for Tweedie p currently");
jnll -= dnorm(s1, priors(12), priors(13), true);
// derivative: https://www.wolframalpha.com/input?i=e%5Ex%2F%281%2Be%5Ex%29+%2B+1
if (stan_flag) jnll -= thetaf - 2 * log(1 + exp(thetaf)); // Jacobian adjustment
}
if (notNA) tmp_ll = dtweedie(y_i(i,m), mu_i(i,m), phi(m), tweedie_p, true);
if (sim_obs) SIMULATE{y_i(i,m) = rtweedie(mu_i(i,m), phi(m), tweedie_p);}
break;
}
case binomial_family: {
if (poisson_link_delta) {
if (notNA) tmp_ll = poisson_link_m0_ll(i); // needed for robustness; must be first model component
if (sim_obs) SIMULATE{y_i(i,m) = rbinom(size(i), mu_i(i,m));}
} else {
if (notNA) tmp_ll = dbinom_robust(y_i(i,m), size(i), mu_i(i,m), true);
if (sim_obs) SIMULATE{y_i(i,m) = rbinom(size(i), invlogit(mu_i(i,m)));} // hardcoded invlogit b/c mu_i in logit space
}
break;
}
case poisson_family: {
if (notNA) tmp_ll = dpois(y_i(i,m), mu_i(i,m), true);
if (sim_obs) SIMULATE{y_i(i,m) = rpois(mu_i(i,m));}
break;
}
case censored_poisson_family: {
if (notNA) tmp_ll = sdmTMB::dcenspois2(y_i(i,m), mu_i(i,m), upr(i), true);
if (sim_obs) SIMULATE{y_i(i,m) = rpois(mu_i(i,m));}
break;
}
case Gamma_family: {
s1 = exp(ln_phi(m)); // shape
s2 = mu_i(i,m) / s1; // scale
if (notNA) tmp_ll = dgamma(y_i(i,m), s1, s2, true);
if (sim_obs) SIMULATE{y_i(i,m) = rgamma(s1, s2);}
// s1 = Type(1) / (pow(phi, Type(2))); // s1=shape, ln_phi=CV,shape=1/CV^2
// tmp_ll = dgamma(y_i(i,m), s1, mu_i(i,m) / s1, true);
break;
}
case nbinom2_family: {
s1 = log(mu_i(i,m)); // log(mu_i)
s2 = 2. * s1 - ln_phi(m); // log(var - mu)
if (notNA) tmp_ll = dnbinom_robust(y_i(i,m), s1, s2, true);
if (sim_obs) SIMULATE { // from glmmTMB
s1 = mu_i(i,m);
s2 = mu_i(i,m) * (Type(1) + mu_i(i,m) / phi(m));
y_i(i,m) = rnbinom2(s1, s2);
}
break;
}
case truncated_nbinom2_family: {
s1 = log(mu_i(i,m)); // log(mu_i)
s2 = 2. * s1 - ln_phi(m); // log(var - mu)
if (notNA) tmp_ll = dnbinom_robust(y_i(i,m), s1, s2, true);
s3 = logspace_add(Type(0), s1 - ln_phi(m));
lognzprob = logspace_sub(Type(0), -phi(m) * s3);
if (notNA) tmp_ll -= lognzprob;
if (notNA) tmp_ll = zt_lik_nearzero(y_i(i,m), tmp_ll); // from glmmTMB
if (sim_obs) SIMULATE{y_i(i,m) = sdmTMB::rtruncated_nbinom(asDouble(phi(m)), 0, asDouble(mu_i(i,m)));}
break;
}
case nbinom1_family: {
s1 = log(mu_i(i,m));
s2 = s1 + ln_phi(m);
if (notNA) tmp_ll = dnbinom_robust(y_i(i,m), s1, s2, true);
if (sim_obs) SIMULATE { // from glmmTMB
s1 = mu_i(i,m);
s2 = mu_i(i,m) * (Type(1)+phi(m));
y_i(i,m) = rnbinom2(s1, s2);
}
break;
}
case truncated_nbinom1_family: {
s1 = log(mu_i(i,m));
s2 = s1 + ln_phi(m);
if (notNA) tmp_ll = dnbinom_robust(y_i(i,m), s1, s2, true);
s3 = logspace_add(Type(0), ln_phi(m));
lognzprob = logspace_sub(Type(0), -mu_i(i,m) / phi(m) * s3); // 1-prob(0)
if (notNA) tmp_ll -= lognzprob;
if (notNA) tmp_ll = zt_lik_nearzero(y_i(i,m), tmp_ll);
if (sim_obs) SIMULATE{y_i(i,m) = sdmTMB::rtruncated_nbinom(asDouble(mu_i(i,m)/phi(m)), 0, asDouble(mu_i(i,m)));}
break;
}
case lognormal_family: {
if (notNA) tmp_ll = sdmTMB::dlnorm(y_i(i,m), log(mu_i(i,m)) - pow(phi(m), Type(2)) / Type(2), phi(m), true);
if (sim_obs) SIMULATE{y_i(i,m) = exp(rnorm(log(mu_i(i,m)) - pow(phi(m), Type(2)) / Type(2), phi(m)));}
break;
}
case student_family: {
if (notNA) tmp_ll = sdmTMB::dstudent(y_i(i,m), mu_i(i,m), exp(ln_phi(m)), df, true);
if (sim_obs) SIMULATE{y_i(i,m) = mu_i(i,m) + phi(m) * rt(df);}
break;
}
case Beta_family: { // Ferrari and Cribari-Neto 2004; betareg package
s1 = mu_i(i,m) * phi(m);
s2 = (Type(1) - mu_i(i,m)) * phi(m);
if (notNA) tmp_ll = dbeta(y_i(i,m), s1, s2, true);
if (sim_obs) SIMULATE{y_i(i,m) = rbeta(s1, s2);}
break;
}
case gamma_mix_family: {
s1 = exp(ln_phi(m)); // shape
s2 = mu_i(i,m) / s1; // scale
ll_1 = log(Type(1. - p_mix)) + dgamma(y_i(i,m), s1, s2, true);
s2_large = mu_i_large(i) / s1; // scale
ll_2 = log(p_mix) + dgamma(y_i(i,m), s1, s2_large, true);
if (notNA) tmp_ll = sdmTMB::log_sum_exp(ll_1, ll_2);