Rceattle C++ template
The CEATTLE likelihood: src/TMB/ceattle.cpp and its headers
Loading...
Searching...
No Matches
helper_functions.hpp
Go to the documentation of this file.
1
2/**
3 * @file helper_functions.hpp
4 * @brief Small differentiable (AD-safe) utilities used across the CEATTLE
5 * template: numeric guards and transforms, the Dirichlet-multinomial density,
6 * and the separable year x age x cohort GMRF precision matrix (construct_Q).
7 */
8
9// Max of an IVECTOR, returned as an int.
10template <class Type>
11Type imax(const vector<Type> &x)
12{
13 int res = x[0];
14 for(int i=0; i < x.size(); i++){
15 int res2 = x[i];
16 if(res < res2){
17 res = res2;
18 }
19 }
20 return res;
21}
22
23// Smooth positive constraint: returns x where x >= eps, otherwise a value in
24// (0, eps), and adds a quadratic penalty for the shortfall.
25template<class Type>
26Type posfun(Type x, Type eps, Type &penalty) {
27 Type denom = 2;
28 denom -= x/eps;
29 Type ans = CppAD::CondExpGe(x, eps, x, eps/denom);
30 penalty += CppAD::CondExpGe(x, eps, Type(0), 0.01 * (x - eps) * (x - eps));
31 return ans;
32}
33
34
35// Dirichlet-multinomial density (log when do_log = 1), from WHAM
36// src/age_comp_osa.hpp (GPL-3); identical in Trijoulet et al.'s distr.hpp.
37template<class Type>
38Type ddirmultinom(vector<Type> obs, vector<Type> alpha, int do_log)
39{
40 int dim = obs.size();
41 Type N = obs.sum();
42 Type phi=sum(alpha);
43 Type ll = lgamma(N + 1.0) + lgamma(phi) - lgamma(N + phi);
44 for(int a = 0; a < dim; a++) ll += -lgamma(obs(a) + 1.0) + lgamma(obs(a) + alpha(a)) - lgamma(alpha(a));
45 if(do_log == 1) return ll;
46 else return exp(ll);
47}
48
49// From TMB examples, modified name, constrains between -1 and 1
50template <class Type>
51Type rho_trans(Type x){
52 return Type(2)/(Type(1) + exp(-Type(2) * x)) - Type(1);
53}
54
55
56template<class Type>
57bool isNA(Type x){
58 return R_IsNA(asDouble(x));
59}
60
61
62template<class Type>
63bool isFinite(Type x){
64 return R_finite(asDouble(x));
65}
66
67
68template <class Type> Type square(Type x){return x*x;}
69
70
71/**
72 * @brief Concentrated (analytical) sd of a lognormal observation likelihood.
73 *
74 * Catch and index observations are fit as `log(obs) ~ N(log(pred) - b * sigma^2 / 2,
75 * sigma)`, with `b` the bias-adjustment flag `bias_adjust_obs` (1 = mean-unbiased
76 * predictions, Rceattle's default; 0 = median-unbiased). Minimising that density over
77 * sigma with `S` = mean squared log residual gives
78 *
79 * sigma^2 = 2 * S / (sqrt(1 + b^2 * S) + 1)
80 *
81 * the Walters and Ludwig (1994) estimator `sigma = sqrt(S)` at `b = 0`, shrunk as the
82 * bias term takes up part of the residual. It is the rationalised form of `2 (sqrt(1 +
83 * b^2 S) - 1) / b^2`, which needs no branch at `b = 0` and stays accurate for small `b`,
84 * where that expression cancels to zero.
85 *
86 * @param mean_sq_resid S, the mean of squared `log(obs) - log(pred)`.
87 * @param bias_adjust b, the bias-adjustment flag applied by the density.
88 * @return The sd that minimises the lognormal negative log-likelihood.
89 */
90template <class Type>
91Type concentrated_lognormal_sd(Type mean_sq_resid, Type bias_adjust)
92{
93 return sqrt( Type(2.0) * mean_sq_resid /
94 (sqrt(Type(1.0) + square(bias_adjust) * mean_sq_resid) + Type(1.0)) );
95}
96
97
98template <class Type>
99vector<Type> first_difference(const vector<Type> &x)
100{
101 int length = x.size() - 1;
102
103 if(length <= 0){
104 std::cerr << "Error -- vector size too small in first_difference()" << std::endl;
105 return vector<Type>(0); // no first difference exists below two elements
106 }
107
108 vector<Type> tmp(length);
109
110 for(int i = 0; i < length; i++){
111 tmp(i) = x(i+1) - x(i);
112 }
113
114 return tmp;
115}
116
117
118// Differentiable max of two values.
119// https://groups.google.com/g/tmb-users/c/QAVmgj66OC0
120template <class Type>
121Type max2(Type x, Type y){
122 Type ans = 0.5*(CppAD::abs(x-y)+x+y);
123 return ans;
124}
125
126
127/**
128 * @brief log(mean(exp(x))) over a non-empty vector, computed so it cannot overflow.
129 *
130 * The non-parametric selectivity forms rescale their log-scale coefficients against
131 * log(mean(exp(coefficients))) once a year, holding a curve whose level is otherwise
132 * unidentified at mean selectivity 1. Summed directly, exp() overflows to infinity once a
133 * coefficient passes about 709, the largest argument it takes in double precision, and
134 * the objective is NaN thereafter. Subtracting the largest coefficient first holds every
135 * exponent at or below 0; the shift cancels out of both the result and its derivative.
136 *
137 * @param x non-empty vector of log-scale values.
138 * @return log of the mean of exp(x).
139 */
140template <class Type>
141Type log_mean_exp(const vector<Type> &x)
142{
143 Type mx = x(0);
144 for(int i = 1; i < x.size(); i++) mx = max2(mx, x(i));
145
146 Type total = 0;
147 for(int i = 0; i < x.size(); i++) total += exp(x(i) - mx);
148
149 return mx + log(total / Type(x.size()));
150}
151
152
153/**
154 * @brief Construct a sparse GMRF precision matrix separable along year, age, and cohort.
155 *
156 * From Matthew Cheng's GMRF_WAA (https://github.com/chengmatt/GMRF_WAA; Cheng et
157 * al. 2023, Fisheries Research 266: 106755). Builds Q = (I - B^T) * Omega * (I - B),
158 * where B carries the partial correlation to each neighbouring node and Omega is the
159 * diagonal precision (1 / variance). `Var_Param` selects the conditional (0) or
160 * marginal (1) variance parameterization of the GMRF.
161 *
162 * The names do not match what they act on: `rho_y` links nodes one apart in column 0 of
163 * `ay_Index` (age, or bin) within a year, and `rho_a` nodes one year apart. The sole
164 * caller, ceattle.cpp's 3D-AR1 selectivity, relies on this; read its note first.
165 *
166 * @param n_years Number of years.
167 * @param n_ages Number of ages.
168 * @param ay_Index [total_n x 2] age/year index locating each node.
169 * @param rho_y Partial correlation across `ay_Index` column 0 (adjacent bins within a year
170 * in 3D-AR1 selectivity).
171 * @param rho_a Partial correlation across column 1 (adjacent years at the same bin).
172 * @param rho_c Partial correlation along the diagonal of both columns, which is the cohort
173 * when column 0 is age.
174 * @param log_sigma2 Log variance parameter governing the GMRF.
175 * @param Var_Param 0 = conditional variance, 1 = marginal variance.
176 * @return Sparse precision matrix [total_n x total_n], total_n = n_years * n_ages.
177 */
178template<class Type>
179Eigen::SparseMatrix<Type> construct_Q(int n_years,
180 int n_ages,
181 matrix<Type> ay_Index,
182 Type rho_y,
183 Type rho_a,
184 Type rho_c,
185 Type log_sigma2,
186 int Var_Param
187) {
188
189 int total_n = n_years * n_ages;
190
191 Eigen::SparseMatrix<Type> B(total_n,total_n);
192 Eigen::SparseMatrix<Type> I(total_n,total_n);
193 I.setIdentity();
194 Eigen::SparseMatrix<Type> Omega(total_n,total_n);
195 Eigen::SparseMatrix<Type> Q_sparse(total_n, total_n);
196
197 for(int n = 0; n < total_n; n++) {
198
199 Type age = ay_Index(n,0);
200 Type year = ay_Index(n,1);
201
202 // B holds the partial correlation from node n to each of its neighbours.
203 if(age > 1) {
204
205 // One step back in ay_Index column 0, same column 1.
206 for(int n1 = 0; n1 < total_n; n1++) {
207 if(ay_Index(n1, 0) == age - 1 && ay_Index(n1, 1) == year)
208 B.coeffRef(n, n1) = rho_y;
209 } // n1 loop
210
211 } // end age > 1
212
213 if(year > 1) {
214
215 // One step back in column 1, same column 0.
216 for(int n1 = 0; n1 < total_n; n1++) {
217 if(ay_Index(n1, 0) == age && ay_Index(n1, 1) == year - 1)
218 B.coeffRef(n, n1) = rho_a;
219 } // n1 loop
220
221 } // if year > 1
222
223 if(year > 1 && age > 1) {
224
225 // One step back in both columns: the diagonal (cohort) neighbour.
226 for(int n1 = 0; n1 < total_n; n1++) {
227 if(ay_Index(n1, 0) == age - 1 && ay_Index(n1, 1) == year - 1)
228 B.coeffRef(n,n1) = rho_c;
229 } // n1 loop
230
231 } // if both year and age > 1
232
233 } // end n loop
234
235 // Omega is diagonal and holds precisions, 1 / variance.
236 if(Var_Param == 0) { // Conditional variance
237
238 for(int i = 0; i < total_n; i++) {
239 for(int j = 0; j < total_n; j++) {
240 if(i == j) Omega.coeffRef(i,j) = 1/exp(log_sigma2);
241 else Omega.coeffRef(i,j) = Type(0.0);
242 } // j loop
243 } // i loop
244
245 } // end if conditional variance
246
247 if(Var_Param == 1) { // Marginal Variance
248
249 matrix<Type> L(total_n, total_n);
250 matrix<Type> tmp_I_B = I-B;
251 L = tmp_I_B.inverse();
252 vector<Type> d(total_n); // conditional variance per node
253
254 for(int n = 0; n < total_n; n++) {
255 if(n == 0) {
256 d(n) = exp(log_sigma2); // marginal variance parameter
257 } else{
258
259 Type cumvar = 0;
260
261 for(int n1 = 0; n1 < n; n1++) {
262 cumvar += L(n, n1) * d(n1) * L(n, n1);
263 } // n1 loop
264
265 // Set d(n) so node n's MARGINAL variance comes out at exp(log_sigma2).
266 d(n) = (exp(log_sigma2) - cumvar) / pow(L(n, n), 2);
267
268 } // else loop
269 } // n loop
270
271 for(int i = 0; i < total_n; i++) {
272 for(int j = 0; j < total_n; j++) {
273 if(i == j) Omega.coeffRef(i,j) = 1/d(i);
274 else Omega.coeffRef(i,j) = Type(0.0);
275 } // j loop
276 } // i loop
277
278 } // end if marginal variance
279
280 Eigen::SparseMatrix<Type> B_transpose = B.transpose();
281
282 Q_sparse = (I - B_transpose) * Omega * (I-B);
283
284 return(Q_sparse);
285
286} // end construct_Q function
287
Type concentrated_lognormal_sd(Type mean_sq_resid, Type bias_adjust)
Concentrated (analytical) sd of a lognormal observation likelihood.
bool isNA(Type x)
Type rho_trans(Type x)
Eigen::SparseMatrix< Type > construct_Q(int n_years, int n_ages, matrix< Type > ay_Index, Type rho_y, Type rho_a, Type rho_c, Type log_sigma2, int Var_Param)
Construct a sparse GMRF precision matrix separable along year, age, and cohort.
bool isFinite(Type x)
Type log_mean_exp(const vector< Type > &x)
log(mean(exp(x))) over a non-empty vector, computed so it cannot overflow.
Type imax(const vector< Type > &x)
Type max2(Type x, Type y)
Type ddirmultinom(vector< Type > obs, vector< Type > alpha, int do_log)
Type square(Type x)
Type posfun(Type x, Type eps, Type &penalty)
vector< Type > first_difference(const vector< Type > &x)