Rceattle C++ template
The CEATTLE likelihood: src/TMB/ceattle.cpp and its headers
Loading...
Searching...
No Matches
ceattle.cpp
Go to the documentation of this file.
1#if defined(__clang__)
2# pragma clang diagnostic push
3# pragma clang diagnostic ignored "-Wunknown-warning-option"
4#endif
5#include <TMB.hpp>
6#if defined(__clang__)
7# pragma clang diagnostic pop
8#endif
9
10// GCC/Eigen emits false -Warray-bounds positives where its vectorized reductions
11// inline TMB's multi-dimensional indexing (e.g. the 5-D suitability() access in
12// predation.hpp). A source pragma rather than a -Wno-array-bounds compiler flag,
13// so CRAN's compilation-flags check stays clean and other diagnostics still show.
14#if defined(__GNUC__)
15# pragma GCC diagnostic ignored "-Warray-bounds"
16#endif
17
18#include "helper_functions.hpp"
19#include "comp_osa.hpp"
20#include "comp_sim.hpp"
21#include "growth.hpp"
22#include "selectivity.hpp"
23#include "recruitment.hpp"
24#include "spr.hpp"
25#include "bioenergetics.hpp"
26#include "predation.hpp"
27#include "diet_data.hpp"
28#include "linkage.hpp"
29#include "likelihood.hpp"
30
31/**
32 * @file ceattle.cpp
33 * @brief The CEATTLE objective function: configuration, population dynamics,
34 * predation, likelihood and report. The numbered section index is in the
35 * banner below; the process equations live in the headers this file includes.
36 */
37
38// Reads an R list() of matrices into a vector<matrix<Type>>: the per-fleet
39// survey-index covariance matrices Sigma supplied when Index_loglike is
40// "MVN"/"MVNORM" (the AMAK/ebswp DoCovBTS covariance survey likelihood; sections
41// 8.2 and 13.1). Other fleets pass a 1x1 inert dummy, so the list is always
42// length n_flt and indexes by fleet code.
43template<class Type>
44struct LOM_t : vector<matrix<Type> > {
45 LOM_t(SEXP x) { // x = R list of matrices
46 (*this).resize(LENGTH(x));
47 for(int i = 0; i < LENGTH(x); i++){
48 SEXP m = VECTOR_ELT(x, i);
49 (*this)(i) = asMatrix<Type>(m);
50 }
51 }
52};
53
54/* ------------------------------------------------------------------------- //
55 * CEATTLE: Bioenergetic-based Assessment for Understanding Biomass Linkages To
56 * The Environment -- a multispecies statistical model in Template Model
57 * Builder. Version: see DESCRIPTION.
58 *
59 * Follows the Google C++ style guide
60 * (https://google.github.io/styleguide/cppguide.html#General_Naming_Rules),
61 * except that free functions stay snake_case.
62 *
63 * CITATIONS:
64 * 1. Holsman, K. K., Ianelli, J., Aydin, K., Punt, A. E., & Moffitt, E. A. (2016). A comparison of fisheries biological reference points estimated from temperature-specific multi-species and single-species climate-enhanced stock assessment models. Deep-Sea Research Part II: Topical Studies in Oceanography, 134, 360–378. https://doi.org/10.1016/j.dsr2.2015.08.001
65 * 2. Adams, G. D., Holsman, K. K., Barbeaux, S. J., Dorn, M. W., Ianelli, J. N., Spies, I., ... & Punt, A. E. (2022). An ensemble approach to understand predation mortality for groundfish in the Gulf of Alaska. Fisheries Research, 251, 106303.
66 * 3. Wassermann, S. N., Adams, G. D., Haltuch, M. A., Kaplan, I. C., Marshall, K. N., & Punt, A. E. (2025). Even low levels of cannibalism can bias population estimates for Pacific hake. ICES Journal of Marine Science, 82(1), fsae064.
67 * ------------------------------------------------------------------------- //
68 * INDEX:
69 * 0. Load dependencies
70 * 1. Model configuration
71 * 2. Model inputs
72 * 3. Model parameters
73 * 4. Derived quantities
74 * 5. Initial calculations
75 * 6. Population dynamics
76 * 7. Predation mortality equations
77 * 8. Index components equations
78 * 9. Fishery components equations
79 * 10. Composition equations
80 * 11. Predicted stomach content
81 * 12. Derived quantities
82 * 13. Likelihood components
83 * 14. Report section
84 * 15. Model return/end
85 *
86 */
87
88
89template<class Type>
90Type objective_function<Type>::operator() () {
91 using namespace density; // necessary to use AR1, SCALE, SEPARABLE
92
93 /** ------------------------------------------------------------------------ //
94 * 1. MODEL CONFIGURATION //
95 * ------------------------------------------------------------------------- */
96 // 1.1. CONFIGURE MODEL (this section sets up the switches)
97 DATA_INTEGER(estimateMode); // 0 = hindcast + HCR projection, 1 = hindcast, 2 = projection from inits, 3 = build only, 4 = smoke test
98 DATA_INTEGER(msmMode);
99 // 0 = single species (no predation mortality)
100 // 1 = Type II MSVPA based (sensu Holsman et al. 2016)
101 // 2 = Type III MSVPA based
102 // 3-9 = not yet implemented (Holling forms, predator interference and
103 // preemption, Hassell-Varley, Ecosim)
104 DATA_IVECTOR(suitMode); // Estimate suitability
105 // DATA_INTEGER(est_diet); // Include diet data in the likelihood
106 // DATA_INTEGER(avgnMode); // Not read; predation uses avgN_at_age
107 DATA_INTEGER(initMode); // How the age-structure is initialized
108 DATA_IVECTOR(forecast); // Run the model in forecast mode
109
110
111 // 1.2. Temporal dimensions
112 DATA_INTEGER( styr ); // Start year
113 DATA_INTEGER( endyr ); // End of estimation years
114 DATA_INTEGER( projyr ); // End year of projection
115
116 DATA_INTEGER( srr_mse_switchyr ); // Last year of the average-recruitment window; for MSE runs.
117 DATA_IVECTOR( suit_styr ); // First year of the suitability average, per predator species.
118 DATA_IVECTOR( suit_endyr ); // Last year of the suitability average, per predator species.
119 DATA_INTEGER( srr_hat_styr ); // First year of the stock-recruitment-penalty / env-rec window.
120 DATA_INTEGER( srr_hat_endyr ); // Last year of the stock-recruitment-penalty / env-rec window.
121
122 int nyrs = projyr - styr + 1;
123 int nyrs_hind = endyr - styr + 1;
124
125 // suit_styr / suit_endyr are per-predator (offset to model-year indices below,
126 // once `nspp` is available).
127 int nyrs_srrmean = srr_mse_switchyr - styr + 1;
128
129 srr_hat_styr = srr_hat_styr - styr;
130 srr_hat_endyr = srr_hat_endyr - styr;
131 if(nyrs_srrmean > nyrs_hind){nyrs_srrmean = nyrs_hind;}
132 if(srr_hat_styr == 0){srr_hat_styr = 1;} // R_hat starts at year 1.
133
134 // 1.3. Number of species
135 DATA_INTEGER( nspp ); // Number of species (prey)
136
137 // Offset per-predator suitability reference years to model-year indices and
138 // count the averaging window length for each predator species.
139 vector<int> nyrs_suit(nspp);
140 for(int sp = 0; sp < nspp; sp++){
141 suit_endyr(sp) = suit_endyr(sp) - styr;
142 suit_styr(sp) = suit_styr(sp) - styr;
143 nyrs_suit(sp) = suit_endyr(sp) - suit_styr(sp) + 1;
144 }
145
146 DATA_IVECTOR( pop_wt_index ); // Dim 1 of weight_obs to use for population dynamics
147 DATA_IVECTOR( ssb_wt_index ); // Dim 1 of weight_obs to use for spawning stock biomass
148 DATA_IVECTOR( pop_age_transition_index );// Dim 1 of age_trans_matrix to use for population dynamics
149 DATA_IVECTOR( estDynamics ); // 0 = population parameters estimated, 1 = numbers-at-age provided, 2 = provided numbers-at-age times an estimated scalar
150 pop_wt_index -= 1; // Indexing starts at 0
151 ssb_wt_index -= 1; // Indexing starts at 0
152 pop_age_transition_index -= 1; // Indexing starts at 0
153
154
155 // 1.4. RECRUITMENT SETTINGS
156 DATA_INTEGER(srr_fun); // Stock recruit relationship for hindcast estimation
157 DATA_INTEGER(srr_pred_fun); // Stock recruit relationship for projection/brps/penalty
158 DATA_INTEGER(proj_mean_rec);
159 // 0 = project recruitment using log_R0 and rec devs
160 // 1 = project recruitment using mean rec (can also have adjusted rec devs)
161 DATA_INTEGER(srr_est_mode); // Logical of wether to add normal prior to stock recruit-relationship
162 DATA_VECTOR(srr_prior); // Prior mean for stock recruit relationship parameter
163 DATA_VECTOR(srr_prior_sd); // Prior sd for stock recruit relationship parameter
164 DATA_INTEGER( niter ); // Number of loops for MSM mode
165 DATA_VECTOR( Bmsy_lim ); // Upper limit for Bmsy in ricker function. Will add penalty if 1/beta > lim
166
167
168 // 1.5. HARVEST CONTROL RULE (HCR) SETTINGS
169 DATA_INTEGER(HCR); // Function to be used for harvest control rule
170 DATA_INTEGER(DynamicHCR); // TRUE/FALSE. Whether to use static or dynamic reference points (default = FALSE)
171 DATA_VECTOR(Ptarget); // Target SSB as a PROPORTION of static or dynamic SSB at F = 0 (B40% is 0.40)
172 DATA_VECTOR(Plimit); // Limit SSB as a PROPORTION of static or dynamic SSB at F = 0 (B10% is 0.10)
173 DATA_VECTOR(Ftarget_percent); // Proportion of SSB-per-recruit or SB0 at F = 0 that sets the target F (F40% is 0.40)
174 DATA_VECTOR(Flimit_percent); // Proportion of SSB-per-recruit or SB0 at F = 0 that sets the limit F (F35% is 0.35)
175 DATA_VECTOR(Alpha); // Parameter used in NPFMC Tier 3 HCR
176 DATA_VECTOR(Fmult); // Multiplier for target fishing mortality (Fmult * Ftarget). For example 0.75 * F40%.
177 DATA_VECTOR(QnormHCR); // Add to Flimit to set Ftarget based on the Pstar approach: Flimit + qnorm(Pstar, 0, Sigma)
178
179
180 // 1.6. MODEL OBJECTS
181 // 1.6.1. LOOPING INDICES -- k = observation, sp = species, sex = sex (0 = combined; 1 = females; 2 = males)
182 // age = age, ln = length, yr = year
183 int sp, sex, age, ln, yr;
184 int index, flt; // Survey and fishery indices
185 int flt_yr, flt_sex, comp_type;
186 int fsh_ind, index_ind, comp_ind, yr_ind; // Indices for survey sets
187 int wt_idx_pop, wt_idx_ssb, wt_idx_flt; // Indices for weight indices
188 Type mo = 0; // Month float
189 if(msmMode == 0) { niter = 1; } // Number of iterations for SS mode
190
191
192 /** ------------------------------------------------------------------------ //
193 * 2. MODEL INPUTS //
194 * ------------------------------------------------------------------------- */
195
196 // -- 2.1. Species attributes
197 DATA_IVECTOR( nsex ); // Sexes modelled per species: 1 = combined, 2 = both.
198 int max_sex = imax(nsex); // Max sexes, for array dimensions
199 DATA_VECTOR( spawn_month ); // Month of spawning to adjust mortality
200 DATA_IVECTOR( nages ); // Age bins per species.
201 DATA_IVECTOR( minage ); // Minimum age of each species
202 DATA_IVECTOR( nlengths ); // Observation length bins per species.
203 DATA_MATRIX(lengths); // Length bins for each species [sp, nlengths]
204 DATA_IVECTOR( nlengths_pop ); // Population length bins per species. Equals nlengths when no population grid is given
205 DATA_MATRIX( lengths_pop ); // Population length bins, lower edges (cm) [sp, nlengths_pop]: the grid the age-length key, weight and maturity are integrated on
206 DATA_IMATRIX( pop_to_data_bin ); // Data length bin (0-based) that each population bin sums into [sp, nlengths_pop]
207 DATA_ARRAY( NByageFixed ); // Input numbers- or index-at-age, multiplied (or not) by pop_scalar to get N_at_age
208 DATA_VECTOR( MSSB0 ); // SB0 from projecting forward in multi-species mode under no fishing
209 DATA_VECTOR( MSB0 ); // B0 from projecting forward in multi-species mode under no fishing
210
211 int max_nlengths = imax(nlengths); // Max nlengths, for array dimensions
212 // The age-length key and selectivity-at-length live on the POPULATION length bins,
213 // which are the data bins whenever no pop_lengths is supplied.
214 int max_nlengths_pop = imax(nlengths_pop);
215
216 // -- 2.3c. First and last population bin in each data bin, per species. SS3 forms
217 // sel(L) * P(L|age) at population resolution and bins the result, so pred_CAAL and the
218 // length compositions sum each data bin's run rather than applying one bin-average
219 // selectivity across it. The map is monotone, so the runs are contiguous; with one grid
220 // every run is one bin.
221 matrix<int> pop_bin_lo(nspp, max_nlengths); pop_bin_lo.setZero();
222 matrix<int> pop_bin_hi(nspp, max_nlengths); pop_bin_hi.setZero();
223 for(int sp_i = 0; sp_i < nspp; sp_i++){
224 for(int d = 0; d < nlengths(sp_i); d++){ pop_bin_lo(sp_i, d) = -1; pop_bin_hi(sp_i, d) = -2; }
225 for(int lp = 0; lp < nlengths_pop(sp_i); lp++){
226 int d = pop_to_data_bin(sp_i, lp);
227 if(pop_bin_lo(sp_i, d) < 0) pop_bin_lo(sp_i, d) = lp;
228 pop_bin_hi(sp_i, d) = lp;
229 }
230 }
231 int max_age = imax(nages); // Max nages, for array dimensions
232 // Sized on the POPULATION bins: the non-parametric curves are built over nlengths_pop,
233 // so a finer grid would otherwise write past non_par_sel.
234 int max_bin = (max_age > max_nlengths_pop) ? max_age : max_nlengths_pop;
235
236 // -- 2.2. M1_at_age specifications
237 DATA_IVECTOR(M1_model);
238 DATA_IVECTOR(M1_re);
239 DATA_IVECTOR(M1_use_prior);
240 DATA_IVECTOR(M2_use_prior);
241 DATA_VECTOR(M_prior);
242 DATA_VECTOR(M_prior_sd);
243
244 // -- 2.3. Growth model specifications
245 DATA_IVECTOR(growth_model); // 0: "input", 1: "vB-classic", 2: "Richards", 3: "nonparametric LAA" [sp]
246 DATA_IVECTOR(growth_sd_style); // Plus-group SD-at-age treatment [sp]: 1 = WHAM (pin to exp(sd_Linf)), 2 = interpolate by length
247 DATA_IVECTOR(growth_sd_form); // Growth variability endpoints [sp]: 1 = SDs in cm (SS3 CV_Growth_Pattern 2), 2 = CVs, SD = CV * L (SS3 pattern 0)
248 DATA_IVECTOR(growth_plus_length); // Plus-group mean length [sp]: 1 = M1-weighted, 2 = none (SS3 Linf_decay -998), 3 = SS3.24 (-999), 4 = SS3 decay rate
249 DATA_VECTOR(plus_group_decay); // Decay rate (per year) for growth_plus_length == 4 [sp]
250 DATA_IMATRIX(sel_dn6_ends); // DoubleNormalSS3, per fleet [flt, 2]: 1 = scale the initial / final end by P5 / P6, 0 = SS3's -999 (unscaled)
251 DATA_IVECTOR(mat_len_use); // 1 = maturity-at-length replaces the age-based maturity in spawning output [sp]
252 DATA_MATRIX(mat_len_pars); // Maturity-at-length [sp, 2]: L50 (cm), logistic slope (per cm)
253 DATA_VECTOR(growth_age_L1); // VB anchor age (= SS3 Growth_Age_for_L1) per sp; defaults to max(0.5, minage[sp]) in R-side fit_mod()
254
255 // -- 2.3b. Linkage table (R/0-linkage_encode.R): covariate and year effects on a
256 // process parameter p in one stratum (species, sex, age bin, fleet; 0 = all).
257 // Row i adds beta_i * x_i(y), with x_i(y) = linkage_X(y, linkage_X_col(i)) its
258 // design column in model year y (row 0 = styr; offset 0 past the last row).
259 // With S_log, S_id and S_exp the sums of beta_i * x_i(y) over p's log-,
260 // identity- and exponential-link rows, and p's own deviates (log_M1_dev,
261 // index_q_dev, sel_inf_dev, log_sel_slp_dev) still applied:
262 // most parameters: p_y = exp(log p + S_log) + S_id
263 // sel_inf, DoubleNormalSS3 P1-P6: p_y = (p + S_id) * exp(S_log), stored scale
264 // catchability (5.3): q_y = exp((log q + S_log) * exp(S_exp) + index_q_dev) + S_id
265 // (Intercept) rows are held at 0, so p carries the level, except R_init's,
266 // which is estimated: a log multiplier on the initial age structure, not on
267 // year-1 recruitment (6.4). Composition and growth-sd rows add no offset;
268 // an (Intercept)'s init, bounds and prior go to the base parameter.
269 // Terms used below:
270 // row one beta_i; fixed-effect rows read beta_linkage.
271 // slot one random-effect deviation, e.g. one year of (1 | Year) in one
272 // stratum; its row's beta is beta_linkage_re_all(slot) (5.2b), times
273 // beta_linkage_obs if observed.
274 // position where a slot sits in beta_linkage_re (integrated) or
275 // beta_linkage_re_pen (penalized): linkage_re_slot.
276 // group the slots of one random term (re_group, e.g. Year, and structure)
277 // on one parameter and stratum: one sd, log_sigma_linkage, and one
278 // structure, IID, random walk or AR1. An observed AR1 is QAR1 (Rogers
279 // et al. 2024), its latent also fitted to an env_data series.
280 // Empty when no build_*() supplied `linkages`.
281 DATA_IVECTOR(linkage_process); // process code, RCEATTLE_PROC_* (linkage.hpp): recruitment, M, growth, q, sel, comp
282 DATA_IVECTOR(linkage_param); // per-process parameter code
283 DATA_IVECTOR(linkage_species); // 1-based sp id; 0 = all
284 DATA_IVECTOR(linkage_sex); // 1-based sex id; 0 = all
285 DATA_IVECTOR(linkage_age_bin); // 1-based age bin, age - minage + 1; 0 = all
286 DATA_IVECTOR(linkage_fleet); // 1-based Fleet_code; 0 = all
287 DATA_IVECTOR(linkage_X_col); // 0-based column of linkage_X
288 DATA_IVECTOR(linkage_link); // link code, RCEATTLE_LINK_* (linkage.hpp)
289 // Only an identity-link recruitment offset can make the curve non-positive, so
290 // the recruitment floors (sections 6.3, 6.5, 6.6 and 6.9) run only then; every
291 // other model's AD tape is left exactly as it was.
292 int rec_floor_on = 0;
293 for (int i = 0; i < linkage_link.size(); ++i) {
294 if (linkage_process(i) == RCEATTLE_PROC_RECRUIT && linkage_link(i) == RCEATTLE_LINK_IDENTITY) rec_floor_on = 1;
295 }
296 DATA_IVECTOR(linkage_re_index); // per row: -1 = fixed; else its 0-based slot in beta_linkage_re_all
297 // linkage_re_sigma, _rho and _obs give positions in log_sigma_linkage, trans_rho_linkage
298 // and beta_linkage_obs; one sd per group, so linkage_re_sigma is the slot's group.
299 DATA_IVECTOR(linkage_re_sigma); // per RE slot: its 0-based group (an index, not an sd)
300 DATA_IVECTOR(linkage_re_integrate); // per RE slot: 1 = integrated out (Laplace), 0 = penalized
301 DATA_IVECTOR(linkage_re_slot); // per RE slot: its position (2.3b)
302 DATA_IVECTOR(linkage_re_struct); // per RE group: RCEATTLE_RE_IID (a plain (1 | Year)), _RW or _AR1 (linkage.hpp)
303 DATA_IVECTOR(linkage_re_rho); // per RE group: 0-based position in trans_rho_linkage (ar1 only; -1 otherwise)
304 DATA_IVECTOR(linkage_re_sigma_prior_family); // per RE group: prior on the SD (0=none,1=normal,2=lognormal,3=gamma,4=beta)
305 DATA_IVECTOR(linkage_re_rho_prior_family); // per RE group: prior on rho (natural (-1,1) scale)
306 DATA_VECTOR(linkage_re_rho_prior_p1); // per RE group: rho prior param 1
307 DATA_VECTOR(linkage_re_rho_prior_p2); // per RE group: rho prior param 2
308 DATA_IVECTOR(linkage_re_obs); // per RE group: 0-based position in beta_linkage_obs (Rogers QAR1 observed ar1; -1 otherwise)
309 // linkage_re_obs_sd is unread here; log_obs_sd_linkage starts at its log.
310 DATA_VECTOR(linkage_re_obs_sd); // per RE group: the obs_sd supplied (0 if unobserved)
311 DATA_VECTOR(linkage_re_obs_value); // per RE slot: observed covariate value (0 if unobserved)
312 DATA_IVECTOR(linkage_re_obs_mask); // per RE slot: 1 if the covariate is observed that year, 0 otherwise
313 DATA_IVECTOR(linkage_re_obsvec_idx); // per RE slot: 0-based obsvec position for OSA (-1 if unobserved / not built)
314 DATA_VECTOR(linkage_re_sigma_prior_p1); // per RE group: prior param 1
315 DATA_VECTOR(linkage_re_sigma_prior_p2); // per RE group: prior param 2
316 DATA_IVECTOR(linkage_is_intercept); // 1 if design_col == "(Intercept)", 0 otherwise
317 DATA_IVECTOR(linkage_prior_family); // none=0, normal=1, lognormal=2, gamma=3, beta=4
318 DATA_VECTOR(linkage_prior_p1); // family-specific prior param 1
319 DATA_VECTOR(linkage_prior_p2); // family-specific prior param 2
320 DATA_MATRIX(linkage_X); // design matrix [model year from styr, design column]
321
322 // -- 2.4. Fleet controls (i.e. how to assign data to objects)
323 DATA_IVECTOR(flt_type); // Fleet_type: 0 = Off, 1 = Fishery, 2 = Survey (NOT a boolean)
324 DATA_VECTOR(flt_month);
325 DATA_IVECTOR(flt_sel_type); // Fleet selectivity parameterization
326 DATA_IVECTOR(flt_sel_dim); // Fleet selectivity dimension (0 = age, 1 = length)
327 DATA_IVECTOR(flt_n_sel_bins); // Age/length bins for non-parametric selectivity
328 DATA_IVECTOR(flt_sel_cap_bin); // NonParametricPM (type 9): first bin (0-based, age or length per flt_sel_dim) at/after which realized selectivity is held flat (RTMB cap_old_age). < 0 = no cap.
329 DATA_IVECTOR(flt_varying_sel); // Whether time-varying selectivity is estimated
330 DATA_IVECTOR(flt_spp); // Fleet species
331 DATA_IVECTOR(bin_first_selected); // First selected age/length BIN, 0-based (selectivity below it = 0)
332 DATA_IVECTOR(age_first_selected); // Length-based fleet: first selected AGE index, 0-based; younger ages leave the fleet's age-length key. 0 elsewhere.
333 DATA_IVECTOR(sel_norm_bin1); // Normalization BIN, 0-based, or a control flag when negative (-999 = do not normalize, -99 = normalize by the maximum); rearrange_data() converts, so NA never arrives. LogisticPM (type 11): lower bin of the selectivity-penalty range.
334 DATA_IVECTOR(sel_norm_bin2); // Upper normalization BIN, same encoding as sel_norm_bin1. LogisticPM (type 11): upper bin of the selectivity-penalty range.
335 DATA_IVECTOR(sel_norm_scope); // Whether normalization pools its reference across sexes: 0 = WithinSex (each sex divided by its own reference; both reach 1), 1 = AcrossSexes (one pooled reference; the lower sex stays below 1). Orthogonal to sel_norm_bin1/2, which say WHERE the reference is taken.
336 DATA_IVECTOR(flt_sel_start_yr); // Per-fleet selectivity start year (0-based from styr); selectivity penalties start the year after this. Default 0 (= styr).
337 DATA_IVECTOR(flt_sel_pen_first_bin); // Per-fleet first bin (0-based, age or length per flt_sel_dim) for the non-parametric shape/monotonicity penalty. < 0 -> defaults to bin_first_selected. Lets the shape constraint span a narrower range than the (possibly non-zero) first selected bin (e.g. ATS mina_ats > first selected age).
338 DATA_IVECTOR(flt_sel_lead); // 1 if this fleet's selectivity penalty should be accumulated; 0 if it mirrors an earlier fleet's selectivity (same Selectivity_index + type) so the shared penalty is counted once.
339 DATA_IVECTOR(flt_q_lead); // As flt_sel_lead, for catchability: 1 if this fleet carries the q prior / deviate penalties, 0 if it shares an earlier fleet's Q_index so the shared block is counted once.
340 DATA_IVECTOR(flt_sel_pen_last_bin); // Per-fleet last bin (0-based, = left bin of the last adjacent pair) for the non-parametric shape penalty. < 0 -> defaults to nbins-2 (whole range).
341 DATA_IVECTOR(flt_sel_shape_mode); // Non-parametric shape-penalty mode: 0 = directional (sign of Sel_curve_pen1 -> penalize decreasing/increasing, one-sided, ADMB/AMAK); 1 = smooth (two-sided d^2 over adjacent ages, RTMB "rpm").
342 DATA_VECTOR(flt_sel_avgsel_pen); // Per-fleet weight on the AMAK "avgsel" base-level penalty (type 9 only); the form is penalty (5) in section 13. 0 = off (default).
343 DATA_IVECTOR(comp_ll_type); // Composition log-likelihood type
344 DATA_IVECTOR(comp_accum_young); // Per-fleet age/length-composition young-tail accumulation bin (1-based ordinal on the comp dimension); bins below it fold into it. 1 (or <1) = no young accumulation (AFSC ac_yng).
345 DATA_IVECTOR(comp_accum_old); // Per-fleet age/length-composition old-tail accumulation bin (1-based); bins above it fold into it. 0/NA or >= nbins = no old accumulation (AFSC ac_old).
346 DATA_IVECTOR(caal_ll_type); // CAAL composition log-likelihood type
347 DATA_IVECTOR(flt_units); // Fleet units (1 = weight, 2 = numbers)
348 DATA_IVECTOR(flt_wt_index); // Vector to save 1st dim of weight to use for weight-at-age
349 DATA_IVECTOR(flt_age_transition_index); // Dim 1 of age_trans_matrix each fleet reads for its ALK
350 DATA_IVECTOR(flt_ageing_error_index); // Ageing error matrix each fleet reads (0-based); the fleet's own species unless fleet_control gives one
351 DATA_IVECTOR(est_index_q); // Catchability form per fleet; see q_map and sections 8.2/8.2b
352 DATA_IVECTOR(index_varying_q); // Whether time-varying q is estimated
353 DATA_IVECTOR(est_sigma_index); // Whether survey sigma is estimated
354 DATA_IVECTOR(est_sigma_fsh); // Whether fishery sigma is estimated
355
356 // -- 2.4.1 Fishery Components
357 DATA_IMATRIX( catch_ctl ); // Fishery catch metadata; columns = Fleet_code, Species, Year
358 DATA_IMATRIX( catch_n ); // Info for fishery biomass; columns = Month
359 DATA_MATRIX( catch_obs ); // Observed fishery catch (mt or thousands of fish per the fleet's Observation_units) and log_sd; columns = Observation, Error
360
361 // -- 2.4.2 Survey components
362 DATA_IMATRIX( index_ctl ); // Index metadata; columns = Fleet_code, Species, Year
363 DATA_MATRIX( index_n ); // Info for index; columns = Month
364 DATA_MATRIX( index_obs ); // Observed index and log_sd; columns = Observation, Error
365 DATA_VECTOR( index_log_q_prior ); // Prior mean for catchability
366 DATA_IVECTOR( index_ll_type ); // Survey index likelihood family per fleet (0 = lognormal IID, 1 = MVN bare quadratic form, 2 = MVNORM full density, 3 = natural-scale normal with absolute sd)
367 DATA_STRUCT( index_cov_mat, LOM_t ); // Per-fleet covariance matrices Sigma for the MVN/MVNORM survey likelihood (1x1 dummy if unused)
368 DATA_VECTOR( index_cov_const ); // Per-fleet 0.5*(logdet(Sigma) + n*log(2pi)); subtracted for "MVN" so it reports the bare quadratic form
369
370 // -- 2.4.2b One-step-ahead (OSA) residual support
371 // `obsvec` is every observation entering the likelihood, flat: log catch, log index,
372 // each comp/caal row's bin counts, each stomach's diet composition. `keep` is the
373 // indicator TMB::oneStepPredict() toggles element by element; it defaults to all ones,
374 // so ordinary fitting is unchanged. Each `*_obsvec_idx` gives its `*_obs` row's 0-based
375 // position in `obsvec` (for a composition, where the row's bins start), or -1 when the
376 // row is not fitted. osa_mode 1 switches the comp/caal/diet branches to a proper,
377 // unweighted, keep-gated density; mode 2 adds the conditional CDF terms
378 // oneStepPredict(method = "cdf") reads -- log F(x) gated by keep.cdf_lower,
379 // log(1 - F(x)) by keep.cdf_upper -- computed only in mode 2, so no other path pays
380 // for the pbeta/pnorm. The Dirichlet-multinomial families have no CDF term
381 // (comp_osa.hpp) and osa_residuals() keeps those fleets off this method.
382 DATA_VECTOR( obsvec ); // Flat observations for OSA residuals
383 DATA_VECTOR_INDICATOR( keep, obsvec ); // oneStepPredict keep indicator (defaults to 1 when fitting)
384 DATA_IVECTOR( catch_obsvec_idx ); // obsvec position for each catch_obs row (-1 = excluded)
385 DATA_IVECTOR( index_obsvec_idx ); // obsvec position for each index_obs row (-1 = excluded)
386 DATA_IVECTOR( comp_obsvec_idx ); // obsvec start position for each comp_obs row's bins (-1 = excluded)
387 DATA_IVECTOR( caal_obsvec_idx ); // obsvec start position for each caal_obs row's bins (-1 = excluded)
388 DATA_IVECTOR( diet_obsvec_idx ); // obsvec start position for each stomach's prey bins (incl. "other prey"); length n_stomach_obs (-1 = excluded)
389 DATA_INTEGER( osa_mode ); // 0 = normal fitting (default); 1 = OSA build (unweighted keep-gated comp/caal/diet densities); 2 = OSA build + conditional CDF terms for method = "cdf"
390 DATA_INTEGER( adreport_sel ); // 0 = no selectivity standard errors (default); 1 = ADREPORT log_sel_at_age; set via fit_control(selectivity_se =)
391 DATA_INTEGER( adreport_catch ); // 0 = default; 1 = ADREPORT catch_hat; set only by the catch-conditioned band of a retrospective peel
392 DATA_SCALAR( comp_offset ); // proportion offset added to comp/caal/diet obs & pred before the multinomial; set via rearrange_data()/fit_control()
393
394 // -- 2.4.2c. Simulation switches (sim_mod(simulate = TRUE))
395 // Observations are always drawn; process error is a choice, so it is switched.
396 //
397 // simulate_state: which process. Slots 0 recruitment, 1 M, 2 growth, 3 catchability,
398 // 4 selectivity -- the codes linkage_process uses, so a random linkage gates on
399 // simulate_state(linkage_process(i)) untranslated. Default off: redrawing a process
400 // changes what self_test() measures, from recovering parameters to recovering a
401 // process. Recruitment covers init_dev too, the initial age structure being recruitment
402 // pre-styr.
403 //
404 // simulate_period: slot 0 the fitted window (0 < Year <= endyr), slot 1 outside it.
405 // Only slot 0 is read, and only by the PROCESS draws, whose densities cover the
406 // hindcast alone. Observations are drawn in every period deliberately, because
407 // run_mse() splices the negative-Year rows back in as the next assessment's data. Slot
408 // 1 is reserved and inert; sim_mod() exposes neither slot.
409 DATA_IVECTOR( simulate_state );
410 DATA_IVECTOR( simulate_period );
411
412 // -- 2.4.3. Composition data
413 DATA_IMATRIX( comp_ctl ); // Age/length comp metadata; columns = Fleet_code, Species, Sex, Age0_Length1, Year
414 DATA_MATRIX( comp_n ); // Month and sample size on observed age/length comp; columns = Month, Sample size
415 DATA_MATRIX( comp_obs ); // Observed age/length comp; cols = Comp_1, Comp_2, etc. can be proportion
416 DATA_IMATRIX( caal_ctl ); // CAAL metadata; columns = Fleet_code, Species, Sex, Year, Length_bin
417 DATA_MATRIX( caal_n ); // Sample size on CAAL; ONE column = Sample size. Unlike comp_n there is no month: a CAAL observation is placed at its fleet's Month, and the age-length key is annual.
418
419 // -- 2.4.4. Initial equilibrium catch: the catch yielded under the initial F,
420 // in the year before the hindcast. 0 rows unless the data supply one.
421 DATA_IMATRIX( equil_catch_ctl ); // columns = Fleet_code, Species
422 DATA_MATRIX( equil_catch_obs ); // columns = Catch, Log_sd
423 DATA_MATRIX( caal_obs ); // Observed CAAL; cols = Comp_1, Comp_2, etc. can be proportion
424
425 // -- 2.4.5 Age and selectivity
426 DATA_IMATRIX( emp_sel_ctl ); // Empirical selectivity metadata; columns = Fleet_code, Species, Sex, Year
427 DATA_MATRIX( emp_sel_obs ); // Observed emprical fishery selectivity; columns = Compe_1, Comp_2, etc.
428 DATA_ARRAY( age_trans_matrix); // observed sp_age/size compositions; n = [nspp, nages, index_age_bins]
429 DATA_ARRAY( age_error ); // Aging error matrices; n = [n_matrices, nages, nages]. One per species unless fleet_control$Ageing_error_index selects otherwise.
430
431 // -- 2.3.5. Growth
432 DATA_ARRAY( weight_obs ); // Weight-at-age by year; n = [nweight, sex, nages, nyrs]
433
434 // 2.3.6. Diet data
435 DATA_IVECTOR(diet_ll_type); // Diet composition log-likelihood type
436 DATA_VECTOR( fday ); // number of foraging days for each predator
437 DATA_ARRAY( ration_data ); // Relative-foraging rate
438 DATA_MATRIX( diet_obs ); // Pred, prey, pred-age, prey-age for diet matrix (weight of prey in pred stomach)
439 DATA_IMATRIX( diet_ctl ); // Per diet_obs row: predator, prey, both sexes, both ages, year
440 DATA_INTEGER(n_stomach_obs); // The total number of unique stomach samples (groups)
441 DATA_IVECTOR(stomach_id); // A vector mapping each diet data row to a stomach ID
442
443 // 2.3.7. Environmental data
444 DATA_MATRIX( env_index ); // Matrix of environmental predictors such as bottom temperature
445
446 // 2.4. INPUT PARAMETERS
447 // -- 2.4.1. Bioenergetics parameters (BP)
448 DATA_VECTOR( other_food ); // Biomass of other prey (mt)
449 DATA_VECTOR( Pvalue ); // Proportion of Cmax; the P in Cmax*fT*Pvalue*PAge
450 DATA_IVECTOR( Ceq ); // Which consumption equation to use; currently all sp = 1
451 DATA_IVECTOR( Cindex ); // Which env_index column drives bioenergetics.
452 DATA_VECTOR( CA ); // Wt specific intercept of Cmax=CA*W^CB
453 DATA_VECTOR( CB ); // Wt specific slope of Cmax=CA*W^CB
454 DATA_VECTOR( Qc ); // used in fT, QC value
455 DATA_VECTOR( Tco ); // used in fT, thermal optimum
456 DATA_VECTOR( Tcm ); // used in fT, thermal max
457 DATA_VECTOR( Tcl ); // used in fT eq 3, limit
458 DATA_VECTOR( CK1 ); // used in fT eq 3, limit where C is .98 max (ascending)
459 DATA_VECTOR( CK4 ); // used in fT eq 3, temp where C is .98 max (descending)
460
461 // -- 2.4.3. Others
462 DATA_MATRIX( sex_ratio ); // Proportion-at-age of females of population
463 DATA_MATRIX( maturity ); // Proportion of mature females at age; [nspp, nages]
464 DATA_SCALAR(bias_adjust_obs); // Whether to apply bias adjustment (-sigma^2/2) in index likelihoods
465 DATA_SCALAR(bias_adjust_proc); // Whether to apply bias adjustment (-sigma^2/2) in process likelihoods
466
467
468 /** ------------------------------------------------------------------------ //
469 * 3. PARAMETER SECTION //
470 * ------------------------------------------------------------------------- */
471
472 PARAMETER( dummy ); // Tests derived quantities given input parameters; n = [1]
473 PARAMETER_VECTOR( log_pop_scalar ); // Log multiplier on input numbers-at-age, per species (estDynamics = 2)
474
475 // -- 3.1. Recruitment parameters
476 PARAMETER_MATRIX( rec_pars ); // Stock-recruit parameters: col1 = mean rec, col2 = SRR alpha, col3 = SRR beta
477 PARAMETER_VECTOR( R_log_sd ); // Standard deviation of recruitment deviations
478 PARAMETER_MATRIX( rec_dev ); // Annual recruitment deviation; n = [nspp, nyrs]
479 PARAMETER_MATRIX( init_dev ); // Log initial numbers-at-age under initMode 0, log deviations off equilibrium under 2/3/4/6; n = [nspp, max_age]
480
481 // -- 3.2. Natural mortality (M1)
482 PARAMETER_ARRAY( log_M1 ); // Natural mortality: residual under multispecies mode, total under single species; n = [nspp, nsex, nages]
483 PARAMETER_ARRAY( log_M1_dev ); // Natural mortality annual deviate; n = [nspp, nsex, nyrs]
484 PARAMETER_ARRAY( M1_beta ); // Regression coefficients for environmnetally linked M1; n = [nspp, nsex, n indices]
485 PARAMETER_ARRAY( M1_rho ); // Correlation for AR1 random effects on age and year; n = [nspp, nsex, 2]
486 PARAMETER_ARRAY( M1_dev_log_sd ); // Innovation sd of the M1 random effects, one per species/sex; n = [nspp, nsex]
487
488 // -- 3.3. Growth
489 PARAMETER_ARRAY(log_growth_pars); // Mean growth curve parameters [sp, sex, par]
490 // Time-varying growth comes from growth_linkage_offset below.
491 PARAMETER_ARRAY(growth_log_sd); // Log standard deviation of length-at- min and max age [sp, sex, 2]
492 PARAMETER_MATRIX(weight_length_pars); // Length-weight parameters [sp, (alpha, beta)]
493
494 // -- 3.3b. Linkage-table coefficients (see section 2.3b). Aligned row-for-row with the
495 // linkage_* DATA vectors above. May be length 0 (no linkages supplied).
496 PARAMETER_VECTOR(beta_linkage);
497
498 // Random-effect linkage coefficients and their hyperparameters. All length 0 unless a
499 // `~ (1|group)` / rw() / ar1() linkage was supplied; when present, beta_linkage_re
500 // enters the Laplace approximation (added to random=) and its density goes to
501 // JNLL_LINKAGE_RE (13.14).
502 PARAMETER_VECTOR(beta_linkage_re); // RE deviation coefficients (Laplace-integrated)
503 // Penalized RE deviations: same density, outside `random` (TMB picks random effects by
504 // name). Fixed SD (and AR1 rho) only; see the vignette, "Integrated or penalized".
505 PARAMETER_VECTOR(beta_linkage_re_pen);
506 PARAMETER_VECTOR(log_sigma_linkage); // one log-SD per RE group
507 PARAMETER_VECTOR(trans_rho_linkage); // one per AR1 group; rho = tanh(trans_rho_linkage), via rho_trans()
508 PARAMETER_VECTOR(beta_linkage_obs); // Rogers QAR1 effect size: one per observed ar1 group
509 PARAMETER_VECTOR(log_obs_sd_linkage); // Rogers QAR1 observation log-SD: one per observed ar1 group (estimated if obs_sd_est = TRUE)
510
511 // -- 3.4. Fishing mortality parameters
512 PARAMETER_VECTOR( log_Flimit ); // Target fishing mortality for projections on log scale; n = [nspp, nyrs]
513 PARAMETER_VECTOR( log_Ftarget ); // Target fishing mortality for projections on log scale; n = [nspp, nyrs]
514 PARAMETER_VECTOR( log_Finit ); // Fishing mortality for initial population to induce non-equilibrium; n = [nspp]
515 PARAMETER_VECTOR( proj_F_prop ); // Proportion of fishing mortality from each fleet for projections; n = [n_fsh]
516 PARAMETER_MATRIX( log_F ); // Annual fishing mortality; n = [n_fsh, nyrs]
517
518 // -- 3.4. Survey catchability parameters
519 PARAMETER_VECTOR( index_log_q ); // Survey catchability; n = [n_index]
520 PARAMETER_MATRIX( index_q_beta ); // Survey catchability regression coefficients on env_data columns
521 PARAMETER_MATRIX( index_q_dev ); // Annual survey catchability deviates; n = [n_index, nyrs_hind]
522 PARAMETER_VECTOR( index_q_log_sd ); // Log standard deviation of prior on survey catchability; n = [1, n_index]
523 PARAMETER_VECTOR( index_q_dev_log_sd );// Log standard deviation of time varying survey catchability; n = [1, n_index]
524
525 // -- 3.5. Selectivity parameters
526 PARAMETER_ARRAY( sel_coff ); // selectivity parameters for non-parametric; n = [n_selectivities, nsex, n_sel_bins]
527 PARAMETER_ARRAY( sel_coff_dev ); // Annual deviates for non-parametric selectivity parameters; n = [n_selectivities, nsex, n_sel_bins]
528 PARAMETER_ARRAY( log_sel_slp ); // selectivity paramaters for logistic; n = [2, n_selectivities, nsex]
529 PARAMETER_ARRAY( sel_inf ); // selectivity paramaters for logistic; n = [2, n_selectivities, nsex]
530 PARAMETER_ARRAY( log_sel_slp_dev ); // selectivity parameter deviate for logistic; n = [2, n_selectivities, nsex, n_sel_blocks]
531 PARAMETER_ARRAY( sel_inf_dev ); // selectivity parameter deviate for logistic; n = [2, n_selectivities, nsex, n_sel_blocks]
532 PARAMETER_ARRAY( log_sel_apical ); // per-sex log multiplier on the whole curve, after the form and before normalization; n = [n_selectivities, nsex]
533 PARAMETER_ARRAY( sel_dn6 ); // DoubleNormalSS3 (SS3 pattern 24) parameters on SS3's scales: peak, logit top, log asc, log desc, logit init, logit final; n = [6, n_selectivities, nsex]
534 PARAMETER_VECTOR( sel_dev_log_sd ); // Log standard deviation of selectivity; n = [1, n_selectivities]
535 PARAMETER_MATRIX( sel_curve_pen ); // Non-parametric selectivity penalty columns (Sel_curve_pen1-3), read differently per form -- see the penalty blocks in section 13.7
536
537 // -- 3.6. Data variance
538 //FIXME: remove log_sd terms below
539 PARAMETER_VECTOR( index_log_sd ); // Log standard deviation of survey index time-series; n = [1, n_index]
540 PARAMETER_VECTOR( catch_log_sd ); // Log standard deviation of fishery catch time-series; n = [1, n_fsh]
541 PARAMETER_VECTOR( comp_weights ); // Weights for composition data
542 PARAMETER_VECTOR( caal_weights ); // Weights for CAAL data
543 vector<Type> DM_pars_comp = exp(comp_weights); // Dirichlet-multinomial scalars
544 vector<Type> DM_pars_caal = exp(caal_weights); // Dirichlet-multinomial scalars
545
546 PARAMETER_VECTOR( diet_comp_weights ); // Weights for diet composition data
547 vector<Type> DM_diet_pars = exp(diet_comp_weights);// Dirichlet-multinomial scalars
548
549 // 3.8. Gamma selectivity parameters
550 PARAMETER_VECTOR( log_gam_a ); // Log predator selectivity; n = [1,nspp]; FIXME: bounds = 1.0e-10 and 19.9
551 PARAMETER_VECTOR( log_gam_b ); // Log predator selectivity; n = [1,nspp]; FIXME: bounds = -5.2 and 10
552
553 // 3.9. Preference
554 PARAMETER_MATRIX( log_phi ); // Species preference coefficient; n = [nspp, nspp]
555
556
557 /** ------------------------------------------------------------------------ //
558 * 4. DERIVED QUANTITIES SECTION ---- //
559 * ------------------------------------------------------------------------- */
560
561 // 4.1. Derived indices
562 int n_flt = flt_type.size();
563 vector<int> joint_adjust(comp_obs.rows()); joint_adjust.setZero();
564 Type penalty = 0.0;
565 Type ricker_intercept = 0.0;
566
567 // -- 4.2. Growth
568 array<Type> growth_matrix(nspp * 2 + n_flt, max_sex, max_age, max_nlengths_pop, nyrs); growth_matrix.setZero(); // Growth transition matrix on the POPULATION length bins, per fleet and per species derived quantity (biomass, ssb)
569 array<Type> weight_hat(nspp * 2 + n_flt, max_sex, max_age, nyrs); weight_hat.setZero(); // Estimated weight-at-age, per fleet and per species derived quantity (biomass, ssb)
570 array<Type> mat_weight_hat(nspp * 2 + n_flt, max_sex, max_age, nyrs); mat_weight_hat.setZero(); // Mature weight-at-age (kg), maturity-at-length species only
571 array<Type> length_hat(nspp * 2 + n_flt, max_sex, max_age, nyrs); length_hat.setZero(); // Estimated length-at-age, per fleet and per species derived quantity (biomass, ssb)
572
573 // -- 4.3. Estimated population quantities
574 vector<Type> pop_scalar = exp(log_pop_scalar); // Multiplier on input numbers-at-age, per species
575 vector<Type> avg_R(nspp); avg_R.setZero(); // Mean recruitment of hindcast
576 matrix<Type> R_hat(nspp, nyrs); R_hat.setZero(); // Expected recruitment given SR curve
577 matrix<Type> mort_sum(nspp, max_age); mort_sum.setZero();
578 // Fishery selectivity at age used by initMode 6 to spread Finit over ages;
579 // filled in section 5.12.1, and 1 everywhere for every other mode.
580 array<Type> sel_init(nspp, max_sex, max_age); sel_init.setZero();
581 // Initial age structure WITHOUT the initial deviates: the equilibrium they are applied
582 // to. Only the equilibrium catch reads it, and that is the quantity it is defined on --
583 // SS3 computes the equilibrium catch from the deviation-free equilibrium, not from the
584 // year-1 numbers. Filled alongside N_at_age in section 6.5 so the two cannot drift
585 // apart.
586 array<Type> N_eq(nspp, max_sex, max_age); N_eq.setZero();
587 matrix<Type> R0(nspp, nyrs); R0.setZero(); // Equilibrium recruitment at F = 0.
588 matrix<Type> alpha(nspp, nyrs); alpha.setZero(); // Stock recruit alpha
589 matrix<Type> Beta(nspp, nyrs); Beta.setZero(); // Stock recruit beta
590 matrix<Type> steepness(nspp, nyrs); steepness.setZero(); // Expected % of R0 at 20% SSB0.
591 vector<Type> R_init(nspp); R_init.setZero(); // Equilibrium recruitment at F = Finit (non-equilibrium).
592 matrix<Type> R(nspp, nyrs); R.setZero(); // Estimated recruitment (thousands of fish; n-at-age is in thousands)
593 array<Type> biomass_at_age(nspp, max_sex, max_age, nyrs); biomass_at_age.setZero();// Estimated biomass-at-age (mt; thousands of fish x kg)
594 matrix<Type> biomass(nspp, nyrs); biomass.setZero(); // Estimated biomass (mt)
595 matrix<Type> exploitable_biomass(nspp, nyrs); exploitable_biomass.setZero(); // Estimated exploitable biomass (mt)
596 matrix<Type> ssb(nspp, nyrs); ssb.setZero(); // Estimated spawning stock biomass (mt)
597 matrix<Type> biomass_depletion(nspp, nyrs); biomass_depletion.setZero(); // Estimated biomass biomass_depletion
598 matrix<Type> ssb_depletion(nspp, nyrs); ssb_depletion.setZero(); // Estimated biomass_depletion of spawning stock biomass
599 array<Type> M_at_age(nspp, max_sex, max_age, nyrs); M_at_age.setZero(); // Total natural mortality at age
600 array<Type> M_at_age_dB0(nspp, max_sex, max_age, nyrs); M_at_age_dB0.setZero(); // Total natural mortality at age (dynamic B0)
601 array<Type> M_at_age_dBF(nspp, max_sex, max_age, nyrs); M_at_age_dBF.setZero(); // Total natural mortality at age (dynamic BF)
602 array<Type> M1_at_age(nspp, max_sex, max_age, nyrs); M1_at_age.setZero(); // Residual or total natural mortality at age
603 array<Type> N_at_age(nspp, max_sex, max_age, nyrs); N_at_age.setZero(); // Numbers at age
604 array<Type> avgN_at_age(nspp, max_sex, max_age, nyrs); avgN_at_age.setZero(); // Average numbers-at-age
605 array<Type> avgN_at_age_dB0(nspp, max_sex, max_age, nyrs); avgN_at_age_dB0.setZero(); // Average numbers-at-age (dynamic B0)
606 array<Type> avgN_at_age_dBF(nspp, max_sex, max_age, nyrs); avgN_at_age_dBF.setZero(); // Average numbers-at-age (dynamic BF)
607 array<Type> Z_at_age(nspp, max_sex, max_age, nyrs); Z_at_age.setZero(); // Total mortality at age
608 vector<Type> R_sd(nspp); R_sd.setZero(); // Standard deviation of recruitment variation
609 vector<Type> zero_N_pen(nspp); zero_N_pen.setZero(); // Additional penalty to add to likelihood if n-at-age goes < 0
610
611 // -- 4.4. Selectivity parameters
612 array<Type> sel_at_age(n_flt, max_sex, max_age, nyrs); sel_at_age.setZero(); // Estimated selectivity at age
613 array<Type> sel_at_length(n_flt, max_sex, max_nlengths_pop, nyrs); sel_at_length.setZero();// Estimated selectivity at length, on the POPULATION length bins
614 array<Type> avg_sel(n_flt, max_sex, nyrs_hind); avg_sel.setZero(); // Average selectivity for non-parametric up to n_sel_bins
615 array<Type> non_par_sel(n_flt, max_sex, max_bin, nyrs); non_par_sel.setZero(); // Estimated selectivity for AMAK non-parametric (pre-normalization)
616 array<Type> log_non_par_sel(n_flt, max_sex, max_bin, nyrs); log_non_par_sel.setZero(); // Same curve on the log scale, where the penalties are written (exp() underflows below about -745, so it is carried, not recovered)
617 vector<Type> sel_dev_sd(n_flt); sel_dev_sd.setZero(); // Standard deviation of selectivity deviates
618
619 // -- 4.5. Fishery components
620 matrix<Type> F_spp(nspp, nyrs); F_spp.setZero(); // Fully selected fishing mortality by species
621 matrix<Type> F_flt(n_flt, nyrs); F_flt.setZero(); // Fully selected fishing mortality by fleet
622 array<Type> F_flt_age(n_flt, max_sex, max_age, nyrs); F_flt_age.setZero(); // Estimated fishing mortality-at-age/sex for each fishery
623 array<Type> Flimit_at_age(nspp, max_sex, max_age, nyrs); Flimit_at_age.setZero(); // Estimated limit fishing mortality-at-age/sex for each species (FOFL proxy)
624 array<Type> Ftarget_at_age(nspp, max_sex, max_age, nyrs); Ftarget_at_age.setZero(); // Estimated target fishing mortality-at-age/sex for each species (max FABC proxy)
625 array<Type> F_at_age(nspp, max_sex, max_age, nyrs); F_at_age.setZero(); // Sum of annual estimated fishing mortalities for each species-at-age
626 vector<Type> catch_hat(catch_obs.rows()); catch_hat.setZero(); // Estimated fishery yield/numbers (mt, or thousands of fish)
627 vector<Type> max_catch_hat(catch_obs.rows()); max_catch_hat.setZero(); // Estimated exploitable biomass/numbers by fleet (mt, or thousands of fish)
628 // As index_sd below, for the fishery. Catch is lognormal throughout, so this is
629 // always a log-scale sd (unitless), not a log of anything. rename_output()
630 // also writes it as log_catch_sd, the name fits saved before 5.9.0 carry.
631 vector<Type> catch_sd(catch_obs.rows()); catch_sd.setZero();
632 // Concentrated (analytical) catch sd used when Estimate_catch_sd = 2; a
633 // log-scale sd (unitless), not a log. Mirrors index_analytical_sd below.
634 vector<Type> catch_analytical_sd(n_flt); catch_analytical_sd.setZero();
635 vector<Type> catch_n_obs(n_flt); catch_n_obs.setZero(); // fitted catch rows per fleet
636
637 // -- 4.6. Biological reference points
638 array<Type> NByage0(nspp, max_sex, max_age, nyrs); NByage0.setZero(); // Numbers at age at mean recruitment and F = 0
639 array<Type> NByageF(nspp, max_sex, max_age, nyrs); NByageF.setZero(); // Numbers at age at mean recruitment and F = Ftarget; the age structure behind SBF
640 array<Type> N_at_age_dB0(nspp, max_sex, max_age, nyrs); N_at_age_dB0.setZero(); // Numbers at age at F = 0 (accounts for annual recruitment)
641 array<Type> N_at_age_dBF(nspp, max_sex, max_age, nyrs); N_at_age_dBF.setZero(); // Female numbers at age at F = Ftarget (accounts for annual recruitment)
642 matrix<Type> DynamicSB0(nspp, nyrs); DynamicSB0.setZero(); // Estimated dynamic spawning biomass at F = 0 (accounts for S-R curve)
643 matrix<Type> DynamicB0(nspp, nyrs); DynamicB0.setZero(); // Estimated dynamic biomass at F = 0 (accounts for S-R curve)
644 matrix<Type> DynamicSBF(nspp, nyrs); DynamicSBF.setZero(); // Estimated dynamic spawning biomass at F = Ftarget (accounts for S-R curve)
645 // Zeroed explicitly, like every other array here: the recursion writes only
646 // ages below a species' own nages, and nothing at all under predation, so the
647 // rest is read from the REPORT as whatever it was initialised to.
648 array<Type> NbyageSPR(4, nspp, max_age); NbyageSPR.setZero(); // Numbers at age per recruit for the SPR reference points; slots 0-3 are F = 0, Flimit, Ftarget, Finit
649 vector<Type> SPRlimit(nspp); SPRlimit.setZero(); // Estimated Plimit SPR
650 vector<Type> SPRtarget(nspp); SPRtarget.setZero(); // Estimated Ptarget SPR
651 vector<Type> SPR0(nspp); SPR0.setZero(); // Estimated spawning biomass per recruit at F = 0
652 vector<Type> SPRFinit(nspp); SPRFinit.setZero(); // Estimated spawning biomass per recruit at Finit
653 matrix<Type> SB0(nspp, nyrs); SB0.setZero(); // Estimated spawning stock biomass at F = 0 (Accounts for S-R)
654 matrix<Type> SBF(nspp, nyrs); SBF.setZero(); // Estimated spawning stock biomass at F = target (Accounts for S-R)
655 matrix<Type> B0(nspp, nyrs); B0.setZero(); // Estimated biomass at F = 0 (Accounts for S-R)
656 vector<Type> Flimit = exp(log_Flimit); // Limit F (FOFL proxy, e.g. F35%) on natural scale
657 vector<Type> Ftarget = exp(log_Ftarget); // Target F (max FABC proxy, e.g. F40%) on natural scale
658 vector<Type> Finit = exp(log_Finit); // Initial F for non-equilibrium age-structure
659 vector<Type> index_q_mult(index_q_beta.cols()); index_q_mult.setZero(); // Environmental design matrix for q
660 vector<Type> M1_mult(M1_beta.dim(2)); M1_mult.setZero(); // Environmental design matrix for M1
661 vector<Type> beta_q_tmp(index_q_beta.cols()); beta_q_tmp.setZero(); // Q beta parameters by species, for the matrix multiply
662 vector<Type> env_q_tmp(index_q_beta.cols()); env_q_tmp.setZero(); // Q env data by year, for the matrix multiply
663 vector<Type> beta_M1_tmp(M1_beta.dim(2)); beta_M1_tmp.setZero(); // Beta parameters by species, for the matrix multiply
664 vector<Type> env_M1_tmp(M1_beta.dim(2)); env_M1_tmp.setZero(); // Env data by year, for the matrix multiply
665 matrix<Type> proj_F(nspp, nyrs); proj_F.setZero(); // Projected F (Fabc/Ftac/etc) using harvest control rule
666
667 // -- 4.7. Survey components
668 vector<Type> index_q_sd(n_flt); index_q_sd.setZero(); // Vector of standard deviation of survey catchability prior
669 vector<Type> index_q_dev_sd(n_flt); index_q_dev_sd.setZero(); // Vector of standard deviation of time-varying survey catchability deviation
670 vector<Type> index_hat(index_obs.rows()); index_hat.setZero(); // Estimated survey index; mt or thousands of fish per the fleet's Observation_units
671 // Rejection bookkeeping for the natural-scale survey draws (sim_mod only), per
672 // index_obs row: a non-zero tries count marks the rows a rejection-capable branch drew
673 // -- the untruncated "Normal" family and MVN/MVNORM, which must redraw a non-positive
674 // index. "TruncatedNormal" draws by inverse CDF and never enters here. sim_mod() sizes
675 // the draw/density gap from index_hat and index_sd, not from these counts.
676 vector<Type> index_trunc_tries_sim(index_obs.rows()); index_trunc_tries_sim.setZero();
677 vector<Type> index_trunc_rejects_sim(index_obs.rows()); index_trunc_rejects_sim.setZero();
678 // The marginal sd the draw itself used, so sim_mod() can size the truncated mass as
679 // Phi(-index_hat/sd). Separate from index_sd because a covariance fleet draws from
680 // index_cov_mat, leaving its index_sd whatever the (unused) Index_sd column carried.
681 vector<Type> index_trunc_sd_sim(index_obs.rows()); index_trunc_sd_sim.setZero();
682 // The redraw budget ACTUALLY applied to each row, which is what sim_mod() quotes: the
683 // constant below on the univariate branch, and that scaled by the fleet's row count on
684 // the correlated one, which rejects the whole vector at once, so its joint rejection
685 // probability climbs with the row count.
686 vector<Type> index_trunc_budget_sim(index_obs.rows()); index_trunc_budget_sim.setZero();
687 const int index_trunc_max_tries = 100;
688 // The observation sd the index likelihood actually used for each row, whichever of the
689 // three est_sigma_index routes supplied it. NOT a log: the sd itself, on the scale that
690 // fleet's Index_distribution works on -- a log-scale sd (unitless) for Lognormal, an
691 // ABSOLUTE sd in the units of the index for the natural-scale families. rename_output()
692 // also writes it as log_index_sd, the name fits saved before 5.9.0 carry.
693 vector<Type> index_sd(index_obs.rows()); index_sd.setZero();
694 vector<Type> index_analytical_sd(n_flt); index_analytical_sd.setZero(); // Concentrated (analytical) index sd used when Estimate_index_sd = 2; a log-scale sd, not a log
695 vector<Type> index_q_analytical(n_flt); index_q_analytical.setZero(); // Analytical catchability (not an sd) used when Catchability = 3; "AnalyticalArith" (7) has its own block at 8.2b
696 matrix<Type> index_q(n_flt, nyrs_hind); index_q.setZero(); // Estimated survey catchability //FIXME: extend out to full time-series
697 vector<Type> index_n_obs(n_flt); index_n_obs.setZero(); // Per-fleet denominator: sum of weights in 8.2, observation count in 8.4
698
699 // -- 4.8. Composition data
700 // age_hat / age_obs_hat are indexed by AGE whatever dimension the fleet's composition
701 // data are on -- a length composition is built at age, then converted through the
702 // age-length transition -- so the width is the widest age index any row writes:
703 // nages(sp), or nages(sp) * 2 for a joint-sex row (comp_ctl column 2 == 3), never
704 // narrower than comp_obs. Sizing from comp_obs alone gives only the workbook's Comp_
705 // columns, i.e. nlengths on a length-only model, and Eigen does not bounds-check in a
706 // release build, so nlengths < nages would write silently into adjacent memory. Species
707 // is range-checked because nothing between rearrange_data() and MakeADFun validates
708 // comp_data$Species, and a non-numeric one arrives as NA_integer_.
709 int max_age_cols = static_cast<int>(comp_obs.cols());
710 for(int comp_row = 0; comp_row < comp_ctl.rows(); comp_row++){
711 int comp_row_sp = comp_ctl(comp_row, 1) - 1;
712 if((comp_row_sp < 0) | (comp_row_sp >= nspp)){
713 error("comp_data Species on row %d is not in 1..nspp", comp_row + 1);
714 }
715 int comp_row_cols = (comp_ctl(comp_row, 2) == 3) ? nages(comp_row_sp) * 2 : nages(comp_row_sp);
716 if(comp_row_cols > max_age_cols){ max_age_cols = comp_row_cols; }
717 }
718 vector<Type> n_hat(comp_obs.rows()) ; n_hat.setZero() ; // Estimated catch (numbers)
719 matrix<Type> age_hat(comp_obs.rows(), max_age_cols); age_hat.setZero(); // Estimated catch at true age
720 matrix<Type> age_obs_hat(comp_obs.rows(), max_age_cols); age_obs_hat.setZero(); // Estimated catch at observed age (accounts for ageing error)
721 matrix<Type> comp_hat = comp_obs; comp_hat.setZero(); // Estimated comp
722 matrix<Type> caal_hat = caal_obs; caal_hat.setZero(); // Estimated CAAL
723 array<Type> pred_CAAL(n_flt, max_sex, max_age, max_nlengths, nyrs); pred_CAAL.setZero(); // Predicted CAAL for each fleet
724 array<Type> comp_pred(max_sex, max_age, max_nlengths); comp_pred.setZero(); // Predicted fleet numbers by age and length for one comp row
725
726 // -- 4.9. Ration components
727 array<Type> consumption_at_age( nspp, max_sex, max_age, nyrs ); consumption_at_age.setZero(); // Annual ration at age (kg/yr)
728 matrix<Type> fT( nspp, nyrs ); fT.setZero(); // Pre-allocation of temperature function of consumption
729
730 // -- 4.10. Diet components
731 array<Type> diet_prop(nspp * max_sex, nspp * max_sex, max_age, max_age, nyrs); diet_prop.setZero(); // Stomach proportion by weight U
732 array<Type> diet_prop_hat(nspp * max_sex, nspp * max_sex, max_age, max_age, nyrs); diet_prop_hat.setZero(); // Predicted stomach proportion by weight U
733 array<Type> other_food_diet_prop(nspp, max_sex, max_age, nyrs); other_food_diet_prop.setZero(); // Other food diet proportion by weight
734 matrix<Type> diet_hat = diet_obs; diet_hat.setZero(); // Estimated stomach proportion by weight U (formated following data input)
735
736 // -- 4.11. Suitability components
737 array<Type> avail_food(nspp, max_sex, max_age, nyrs); avail_food.setZero(); // Available food to predator
738 array<Type> avail_food_dB0(nspp, max_sex, max_age, nyrs); avail_food_dB0.setZero(); // Available food to predator (dynamic B0)
739 array<Type> avail_food_dBF(nspp, max_sex, max_age, nyrs); avail_food_dBF.setZero(); // Available food to predator (dynamic BF)
740 array<Type> stom_div_bio(nspp * max_sex, nspp * max_sex, max_age, max_age, nyrs); stom_div_bio.setZero(); // Stomach proportion over biomass; U/ (W * N)
741 array<Type> suitability(nspp * max_sex, nspp * max_sex, max_age, max_age, nyrs); suitability.setZero(); // Suitability/gamma selectivity of predator age u on prey age a
742 array<Type> suit_other(nspp, max_sex, max_age, nyrs); suit_other.setZero(); // Suitability not accounted for by the included prey
743 array<Type> other_diet_prop_hat(nspp, max_sex, max_age, nyrs); other_diet_prop_hat.setZero(); // Diet of prey not included in the model
744
745 // -- 4.12. Suitability parameters
746 vector<Type> gam_a = exp(log_gam_a); // Predator size-selectivity: shape parameter for gamma suitability, mean for normal of logs
747 vector<Type> gam_b = exp(log_gam_b); // Predator size-selectivity: scale parameter for gamma suitability, sd for normal of logs
748 matrix<Type> vulnerability(nspp, nspp); vulnerability.setZero(); // Predator-prey preference coefficients
749 vector<Type> vulnerability_other(nspp); vulnerability_other.setZero(); // Preference for other food
750
751 // -- 4.13. Predation components
752 array<Type> M2_at_age(nspp, max_sex, max_age, nyrs); M2_at_age.setZero(); // Predation mortality at age
753 array<Type> M2_at_age_dB0(nspp, max_sex, max_age, nyrs); M2_at_age_dB0.setZero(); // Predation mortality at age (dynamic B0)
754 array<Type> M2_at_age_dBF(nspp, max_sex, max_age, nyrs); M2_at_age_dBF.setZero(); // Predation mortality at age (dynamic BF)
755 array<Type> M2_prop(nspp * max_sex, nspp * max_sex, max_age, max_age, nyrs); M2_prop.setZero(); // Each predator-at-age's contribution to prey M2 (yr^-1), not a share of it
756 array<Type> B_eaten(nspp * max_sex, nspp * max_sex, max_age, max_age, nyrs); B_eaten.setZero(); // Biomass of prey eaten via predation by a predator at age
757 array<Type> B_eaten_as_prey(nspp, max_sex, max_age, nyrs); B_eaten_as_prey.setZero(); // Biomass eaten as prey via predation
758
759 /** ------------------------------------------------------------------------ //
760 * 5. INITIAL CALCULATIONS //
761 * ------------------------------------------------------------------------- */
762
763 // 5.1. DATA VARIANCE TERMS
764 R_sd = exp(R_log_sd); // Convert log sd to natural scale
765 sel_dev_sd = exp(sel_dev_log_sd) ;
766 index_q_sd = exp(index_q_log_sd) ;
767 index_q_dev_sd = exp(index_q_dev_log_sd) ;
768 Cindex -=1; // Subtract 1 from Cindex to deal with indexing start at 0
769
770
771 // -- 5.2. SIMULATE LINKAGE RANDOM EFFECTS (sim_mod(simulate = TRUE))
772 // A random linkage on any of the five processes draws here, before they read it, from
773 // its density in rceattle_re_group_nll() (linkage.hpp, called in 13.14). Slots are in
774 // time order within a group, so a random walk starts from the fitted first slot, and an
775 // AR1 draw is standardized then scaled by the MARGINAL sd sigma.
776 //
777 // beta_linkage_re_drawn_sim marks which slots this call wrote. The reported deviation
778 // vector spans EVERY random linkage, drawn or not, so without the mask a caller would
779 // score recovery on slots left at their fitted values.
780 SIMULATE {
781 vector<Type> beta_linkage_re_drawn_sim(linkage_re_sigma.size());
782 beta_linkage_re_drawn_sim.setZero();
783 if (log_sigma_linkage.size() > 0 && simulate_period(0) == 1) {
784 int n_grp = log_sigma_linkage.size();
785
786 // Drawn only if EVERY row using the group names a process the caller asked for.
787 // A group belongs to one process (.assign_re_registry() keys it on process,
788 // parameter, stratum and random term), so this reads that process's simulate_state.
789 vector<int> grp_used(n_grp), grp_draw(n_grp);
790 grp_used.setZero();
791 grp_draw.fill(1);
792 for (int i = 0; i < linkage_re_index.size(); ++i) {
793 if (linkage_re_index(i) < 0) continue;
794 int grp = linkage_re_sigma(linkage_re_index(i));
795 grp_used(grp) = 1;
796 // linkage_process also codes composition (5), which simulate_state does not cover
797 // because composition linkages carry priors, not random effects. Treat anything
798 // outside the five as "not asked for" rather than reading past simulate_state.
799 int proc = linkage_process(i);
800 if (proc < 0 || proc >= simulate_state.size() || simulate_state(proc) != 1) {
801 grp_draw(grp) = 0;
802 }
803 }
804
805 for (int grp = 0; grp < n_grp; ++grp) {
806 if (grp_used(grp) == 0 || grp_draw(grp) == 0) continue;
807
808 // Rogers QAR1: the latent is measured by an observed covariate series, so
809 // redrawing it alone would leave the two describing different histories.
810 // Left as fitted; sim_mod() warns that it was.
811 if (linkage_re_obs(grp) >= 0) continue;
812
813 vector<int> slots = rceattle_group_slots(linkage_re_sigma, grp);
814 int len = slots.size();
815 if (len == 0) continue;
816
817 Type sigma = exp(log_sigma_linkage(grp));
818 vector<Type> re(len);
819 int st = linkage_re_struct(grp);
820
821 // Each slot sits in beta_linkage_re if integrated, else beta_linkage_re_pen, at
822 // position linkage_re_slot(slot).
823 if (st == RCEATTLE_RE_RW) {
824 re(0) = linkage_re_integrate(slots(0))
825 ? beta_linkage_re(linkage_re_slot(slots(0)))
826 : beta_linkage_re_pen(linkage_re_slot(slots(0)));
827 for (int t = 1; t < len; ++t) re(t) = re(t - 1) + rnorm(Type(0), sigma);
828 } else if (st == RCEATTLE_RE_AR1) {
829 Type rho = rho_trans(trans_rho_linkage(linkage_re_rho(grp)));
830 AR1(rho).simulate(re);
831 re *= sigma;
832 } else { // RCEATTLE_RE_IID
833 for (int t = 0; t < len; ++t) re(t) = rnorm(Type(0), sigma);
834 }
835
836 for (int t = 0; t < len; ++t) {
837 if (linkage_re_integrate(slots(t))) {
838 beta_linkage_re(linkage_re_slot(slots(t))) = re(t);
839 } else {
840 beta_linkage_re_pen(linkage_re_slot(slots(t))) = re(t);
841 }
842 // A random walk keeps its first slot at the fitted level (it has no density
843 // term of its own), so that slot is written but not drawn.
844 if (!(st == RCEATTLE_RE_RW && t == 0)) beta_linkage_re_drawn_sim(slots(t)) = 1;
845 }
846 }
847 }
848 REPORT(beta_linkage_re_drawn_sim);
849 }
850
851 // -- 5.2b. EFFECTIVE LINKAGE COEFFICIENTS (beta_linkage_re_all, beta_linkage_eff)
852 // Every deviation in one vector, indexed by RE slot: integrated deviations in
853 // beta_linkage_re, penalized ones in beta_linkage_re_pen, with linkage_re_slot giving
854 // the position within whichever holds it. With no penalized group it copies
855 // beta_linkage_re.
856 vector<Type> beta_linkage_re_all(linkage_re_sigma.size());
857 for (int s = 0; s < beta_linkage_re_all.size(); ++s) {
858 beta_linkage_re_all(s) = linkage_re_integrate(s)
859 ? beta_linkage_re(linkage_re_slot(s))
860 : beta_linkage_re_pen(linkage_re_slot(s));
861 }
862
863 // THE _sim NAMING RULE, stated once here and referred to below. TMB never clears the
864 // report environment, so anything REPORTed inside a SIMULATE block stays visible in
865 // obj$report() for this object's life -- under the observed object's own name, a random
866 // replicate would read as the data. Every draw is reported under a name ending _sim,
867 // and the composition, CAAL and diet draws go into separate copies (comp_sim, caal_sim,
868 // diet_sim) for the same reason.
869 SIMULATE {
870 vector<Type> beta_linkage_re_sim = beta_linkage_re_all;
871 REPORT(beta_linkage_re_sim);
872 }
873
874 // Effective linkage coefficient per table row. A fixed row uses its beta_linkage(i); a
875 // random-effect row (linkage_re_index >= 0) takes its deviation from the slot-space
876 // vector, whose density is JNLL_LINKAGE_RE (13.14). The accumulators below see one beta vector
877 // either way; with no RE rows this copies beta_linkage.
878 vector<Type> beta_linkage_eff = beta_linkage;
879 for (int i = 0; i < beta_linkage_eff.size(); ++i) {
880 if (linkage_re_index(i) >= 0) {
881 Type z = beta_linkage_re_all(linkage_re_index(i));
882 // Rogers QAR1: an observed AR1 latent enters the target scaled by an estimated
883 // effect size, beta_linkage_obs. Unobserved groups keep the deviate as is.
884 int grp = linkage_re_sigma(linkage_re_index(i));
885 if (linkage_re_obs(grp) >= 0) z *= beta_linkage_obs(linkage_re_obs(grp));
886 beta_linkage_eff(i) = z;
887 }
888 }
889
890 // The table every rceattle_apply_*_linkages() call below reads (linkage.hpp): each row
891 // adds offset = beta * X(yr, X_col) to one parameter in one stratum (2.3b).
892 LinkageTable<Type> linkage_table = {
893 linkage_process, linkage_param, // which parameter
894 linkage_species, linkage_sex, linkage_age_bin, linkage_fleet, // which stratum (0 = all)
895 linkage_X_col, linkage_link, linkage_X, beta_linkage_eff}; // the offset
896
897
898 // 5.3. CATCHABILITY
899 // Environmental linkage offsets, one pass per link scale. Zero unless a
900 // q linkage was supplied, so models without one are unaffected.
901 matrix<Type> q_linkage_offset(n_flt, nyrs_hind); q_linkage_offset.setZero();
902 matrix<Type> q_linkage_offset_nat(n_flt, nyrs_hind); q_linkage_offset_nat.setZero();
903 matrix<Type> q_linkage_log_mult(n_flt, nyrs_hind); q_linkage_log_mult.setZero();
904
905 // Log-link rows into the log-scale offset, identity-link rows into the natural-scale
906 // one, exponential rows into the log of the multiplier on log q (applied as exp()).
907 rceattle_apply_q_linkages(q_linkage_offset, RCEATTLE_LINK_LOG, linkage_table, n_flt, nyrs_hind);
908 rceattle_apply_q_linkages(q_linkage_offset_nat, RCEATTLE_LINK_IDENTITY, linkage_table, n_flt, nyrs_hind);
909 rceattle_apply_q_linkages(q_linkage_log_mult, RCEATTLE_LINK_EXPONENTIAL, linkage_table, n_flt, nyrs_hind);
910
911 REPORT(q_linkage_offset);
912 REPORT(q_linkage_offset_nat);
913 REPORT(q_linkage_log_mult);
914
915 for(flt = 0; flt < n_flt; flt++){
916 for(yr = 0; yr < nyrs_hind; yr++){
917 // q_y = exp((log q + S_log) * exp(S_exp) + index_q_dev) + S_id. The deviate is added
918 // after the product, as SS3 applies its devs after the env link; inside, its sd
919 // would vary by year.
920 index_q(flt, yr) = exp((index_log_q(flt) + q_linkage_offset(flt, yr))
921 * exp(q_linkage_log_mult(flt, yr))
922 + index_q_dev(flt, yr))
923 + q_linkage_offset_nat(flt, yr);
924
925 // Catchability 5 ("Environmental", legacy): log q_y = log q + beta * env_index,
926 // replacing the line above; R refuses a q linkage on such a fleet.
927 if(est_index_q(flt) == 5){
928 beta_q_tmp = index_q_beta.row(flt);
929 env_q_tmp = env_index.row(yr) ;
930 index_q_mult = env_q_tmp * beta_q_tmp;
931 index_q(flt, yr) = exp(index_log_q(flt) + (index_q_mult).sum());
932 }
933 }
934 }
935
936 matrix<int> r_sexes(diet_obs.rows(), 2); r_sexes.setZero();
937 matrix<int> k_sexes(diet_obs.rows(), 2); k_sexes.setZero();
938
939
940 // 5.4. MATURITY, Finit, AND SEX RATIO
941 // -- for SSB derivation, not SPR
942 matrix<Type> mature_females = maturity;
943 for( sp = 0; sp < nspp ; sp++) {
944
945 if(initMode < 3 || initMode == 5){
946 Finit(sp) = 0; // An equilibrium start takes Finit = 0, so R_init and R0 agree. initMode 5 (OffsetEquilibrium) is an F = 0 equilibrium seeded by first-year recruitment.
947 }
948
949 // Sex ratio for SSB derivation
950 for( age = 0 ; age < nages(sp); age++ ) {
951 if(nsex(sp) == 1){
952 mature_females( sp, age ) = maturity( sp, age ) * sex_ratio(sp, age); // Multiply sex_ratio and maturity for 1 sex models
953 }
954 }
955 }
956
957 // 5.5. OFFSETS
958 // One array per link scale per process: `*_linkage_offset` from log-link rows (S_log),
959 // `*_linkage_offset_nat` from identity-link rows (S_id), combined as in section 2.3b.
960 // Catchability has a third, `q_linkage_log_mult` (S_exp, 5.3). All zero with no linkages.
961 //
962 // - RECRUITMENT OFFSETS
963 array<Type> recruitment_linkage_offset(nspp,
965 nyrs);
966 array<Type> recruitment_linkage_offset_nat(nspp,
968 nyrs);
969 recruitment_linkage_offset.setZero();
970 recruitment_linkage_offset_nat.setZero();
971 rceattle_apply_recruitment_linkages(recruitment_linkage_offset, RCEATTLE_LINK_LOG, linkage_table, nspp, nyrs);
972 rceattle_apply_recruitment_linkages(recruitment_linkage_offset_nat, RCEATTLE_LINK_IDENTITY, linkage_table, nspp, nyrs);
973 REPORT(recruitment_linkage_offset);
974 REPORT(recruitment_linkage_offset_nat);
975
976 // - M OFFSETS
977 array<Type> M_linkage_offset(nspp, max_sex, max_age, nyrs);
978 array<Type> M_linkage_offset_nat(nspp, max_sex, max_age, nyrs);
979 M_linkage_offset.setZero();
980 M_linkage_offset_nat.setZero();
981 rceattle_apply_M_linkages(M_linkage_offset, RCEATTLE_LINK_LOG, linkage_table, nspp, nsex, nages, nyrs);
982 rceattle_apply_M_linkages(M_linkage_offset_nat, RCEATTLE_LINK_IDENTITY, linkage_table, nspp, nsex, nages, nyrs);
983 REPORT(M_linkage_offset);
984 REPORT(M_linkage_offset_nat);
985
986
987 // - GROWTH OFFSETS
988 array<Type> growth_linkage_offset(nspp, max_sex, nyrs, RCEATTLE_N_GROWTH_PARAMS);
989 array<Type> growth_linkage_offset_nat(nspp, max_sex, nyrs, RCEATTLE_N_GROWTH_PARAMS);
990 growth_linkage_offset.setZero();
991 growth_linkage_offset_nat.setZero();
992 rceattle_apply_growth_linkages(growth_linkage_offset, RCEATTLE_LINK_LOG, linkage_table, nspp, nsex, nyrs);
993 rceattle_apply_growth_linkages(growth_linkage_offset_nat, RCEATTLE_LINK_IDENTITY, linkage_table, nspp, nsex, nyrs);
994 REPORT(growth_linkage_offset);
995 REPORT(growth_linkage_offset_nat);
996
997
998 // 5.6. RECRUITMENT PARAMETERS
999 // R0, alpha, Beta: p_y = exp(log p + S_log) + S_id (2.3b).
1000 // TODO: a negative nat_offset can make R0, alpha or Beta non-positive; only hindcast R, R_hat and the penalty curve are floored (issue #234).
1001 for(sp = 0; sp < nspp; sp++){
1002 for(yr = 0; yr < nyrs; yr++){
1003 R0(sp, yr) = exp(rec_pars(sp, RCEATTLE_REC_R0) + recruitment_linkage_offset(sp, RCEATTLE_REC_R0, yr))
1004 + recruitment_linkage_offset_nat(sp, RCEATTLE_REC_R0, yr);
1005 alpha(sp, yr) = exp(rec_pars(sp, RCEATTLE_REC_ALPHA) + recruitment_linkage_offset(sp, RCEATTLE_REC_ALPHA, yr))
1006 + recruitment_linkage_offset_nat(sp, RCEATTLE_REC_ALPHA, yr);
1007 Beta(sp, yr) = exp(rec_pars(sp, RCEATTLE_REC_BETA) + recruitment_linkage_offset(sp, RCEATTLE_REC_BETA, yr))
1008 + recruitment_linkage_offset_nat(sp, RCEATTLE_REC_BETA, yr);
1009 }
1010 }
1011
1012
1013 // 5.7. GROWTH
1014 // -- Rearrange growth parameters. Log-link offset enters additively
1015 // on the log scale (multiplicative on natural K/L1/Linf/m);
1016 // identity-link offset enters additively on the natural scale.
1017 array<Type> growth_parameters(nspp, max_sex, nyrs, RCEATTLE_N_GROWTH_PARAMS); growth_parameters.setZero(); // K, L1, Linf, m
1018 for(sp = 0; sp < nspp; sp++){
1019 for(sex = 0; sex < nsex(sp); sex ++){
1020 for(yr = 0; yr < nyrs; yr++){
1021 for(int par = 0; par < RCEATTLE_N_GROWTH_PARAMS; par++){
1022 growth_parameters(sp, sex, yr, par) = exp(
1023 log_growth_pars(sp, sex, par)
1024 + growth_linkage_offset(sp, sex, yr, par)
1025 ) + growth_linkage_offset_nat(sp, sex, yr, par);
1026 }
1027 }
1028 }
1029 }
1030 REPORT(growth_parameters);
1031
1032 // -- Calculate weight
1034 weight_hat,
1035 length_hat,
1036 growth_matrix,
1037 mat_weight_hat,
1038 weight_obs,
1039 growth_model,
1040 growth_sd_style,
1041 growth_sd_form,
1042 growth_plus_length,
1043 plus_group_decay,
1044 nspp,
1045 nyrs,
1046 nyrs_hind,
1047 n_flt,
1048 flt_spp,
1049 flt_month,
1050 nsex,
1051 minage,
1052 growth_age_L1,
1053 nages,
1054 nlengths,
1055 pop_wt_index,
1056 ssb_wt_index,
1057 flt_wt_index,
1058 spawn_month,
1059 lengths,
1060 nlengths_pop,
1061 lengths_pop,
1062 growth_parameters,
1063 growth_log_sd,
1064 weight_length_pars,
1065 mat_len_use,
1066 mat_len_pars,
1067 log_M1
1068 );
1069
1070 // -- Spawning output per fish (kg) at spawning time, female-only for a
1071 // two-sex species. Weight x maturity-at-age x sex ratio by default; with
1072 // maturity-at-length it is the mature weight integrated over the length
1073 // distribution at spawning, so maturity and weight vary together with length.
1074 array<Type> spawn_output(nspp, max_age, nyrs); spawn_output.setZero();
1075 for(sp = 0; sp < nspp; sp++){
1076 wt_idx_ssb = 2 * sp + 1;
1077 for(age = 0; age < nages(sp); age++){
1078 for(yr = 0; yr < nyrs; yr++){
1079 if(mat_len_use(sp) == 1){
1080 spawn_output(sp, age, yr) = mat_weight_hat(wt_idx_ssb, 0, age, yr) * ((nsex(sp) == 1) ? sex_ratio(sp, age) : Type(1.0));
1081 } else {
1082 spawn_output(sp, age, yr) = weight_hat(wt_idx_ssb, 0, age, yr) * mature_females(sp, age);
1083 }
1084 }
1085 }
1086 }
1087 REPORT(spawn_output);
1088
1089
1090 // 5.8. SELECTIVITY
1091 // Environmental-linkage offsets. Two arrays per parameter family (log and
1092 // natural scale), all zero unless a selectivity linkage was supplied.
1093 array<Type> sel_slp_off (2, n_flt, max_sex, nyrs); sel_slp_off.setZero();
1094 array<Type> sel_slp_off_nat (2, n_flt, max_sex, nyrs); sel_slp_off_nat.setZero();
1095 array<Type> sel_inf_off (2, n_flt, max_sex, nyrs); sel_inf_off.setZero();
1096 array<Type> sel_inf_off_nat (2, n_flt, max_sex, nyrs); sel_inf_off_nat.setZero();
1097 array<Type> sel_coff_off (n_flt, max_sex, max_bin, nyrs); sel_coff_off.setZero();
1098 array<Type> sel_coff_off_nat (n_flt, max_sex, max_bin, nyrs); sel_coff_off_nat.setZero();
1099 array<Type> sel_apical_off (n_flt, max_sex, nyrs); sel_apical_off.setZero();
1100 array<Type> sel_apical_off_nat (n_flt, max_sex, nyrs); sel_apical_off_nat.setZero();
1101 array<Type> sel_dn6_off (6, n_flt, max_sex, nyrs); sel_dn6_off.setZero();
1102 array<Type> sel_dn6_off_nat (6, n_flt, max_sex, nyrs); sel_dn6_off_nat.setZero();
1103
1104 // The per-sex apical multiplier is compiled in only when a selectivity
1105 // linkage names it (RCEATTLE_SEL_APICAL); otherwise the curve is untouched and the AD
1106 // tape of every existing model is unchanged.
1107 int sel_apical_on = 0;
1108 for (int i = 0; i < linkage_process.size(); i++) {
1109 if (linkage_process(i) == RCEATTLE_PROC_SEL && linkage_param(i) == RCEATTLE_SEL_APICAL) sel_apical_on = 1;
1110 }
1111
1112 rceattle_apply_sel_linkages( // log link, into the log-scale arrays
1113 sel_slp_off, sel_inf_off, sel_coff_off, sel_apical_off, sel_dn6_off,
1114 RCEATTLE_LINK_LOG, linkage_table, n_flt, max_sex, max_bin, nyrs);
1115 rceattle_apply_sel_linkages( // identity link, into the natural-scale arrays
1116 sel_slp_off_nat, sel_inf_off_nat, sel_coff_off_nat, sel_apical_off_nat, sel_dn6_off_nat,
1117 RCEATTLE_LINK_IDENTITY, linkage_table, n_flt, max_sex, max_bin, nyrs);
1118
1119 // Zero ages below Age_first_selected in each non-Fixed length-based fleet's age-length key
1120 // (SS3 age pattern 11), the key its selectivity-at-age, weight-at-age, comps and CAAL read.
1121 for(flt = 0; flt < n_flt; flt++){
1122 if(flt_sel_dim(flt) != 1 || flt_sel_type(flt) == 0) continue;
1123 sp = flt_spp(flt);
1124 int wt_idx_mask = nspp * 2 + flt;
1125 for(sex = 0; sex < nsex(sp); sex++){
1126 for(age = 0; age < age_first_selected(flt) && age < nages(sp); age++){
1127 for(int lp = 0; lp < nlengths_pop(sp); lp++){
1128 for(yr = 0; yr < nyrs; yr++) growth_matrix(wt_idx_mask, sex, age, lp, yr) = 0;
1129 }
1130 }
1131 }
1132 }
1133
1134 // "sel_at_age" and "sel_at_length" modified via pass-by-reference
1135 // when "sel_at_length" is used, it is converted to "sel_at_age" using the growth matrix
1137 nspp, // Number of species.
1138 n_flt, // Number of fleets.
1139 nyrs, // Years, hindcast plus projection.
1140 nyrs_hind, // Years in the hindcast.
1141 styr, // Start year
1142 nsex, // Sexes modelled per species: 1 = combined, 2 = both.
1143 nages, // Age bins per species.
1144 nlengths, // Observation length bins per species.
1145 lengths, // Length bin boundaries matrix
1146 nlengths_pop, // Population length bins per species (= nlengths when no pop grid)
1147 lengths_pop, // Population length bin lower edges
1148 flt_spp, // Fleet to species mapping
1149 flt_sel_type, // Selectivity model type per fleet
1150 flt_varying_sel, // Time_varying_sel per fleet (picks NonParametricIntegrable's construction)
1151 flt_sel_dim, // Age or length based
1152 bin_first_selected, // Min bin selected per fleet
1153 flt_n_sel_bins, // Max estimated bins per fleet
1154 flt_sel_cap_bin, // Bin (0-based) at/after which realized non-par sel is capped flat (NonParametricPM)
1155 sel_norm_bin1, // Normalization control/bin 1
1156 sel_norm_bin2, // Normalization control/bin 2
1157 sel_norm_scope, // Normalization reference pooled across sexes?
1158 flt_sel_start_yr, // Per-fleet selectivity start year (0-based)
1159 emp_sel_obs, // Empirical observations matrix
1160 emp_sel_ctl, // Empirical control matrix
1161 log_sel_slp, // Logistic slope parameters
1162 log_sel_slp_dev, // Slope deviations
1163 sel_inf, // Inflection parameters
1164 sel_inf_dev, // Inflection deviations
1165 sel_coff, // Non-parametric coefficients
1166 sel_coff_dev, // Coefficient deviations
1167 avg_sel, // [Modified] Average selectivity
1168 non_par_sel, // [Modified] Unnormalized non-parametric selectivity
1169 log_non_par_sel, // [Modified] The same curve on the log scale, for the penalties
1170 sel_at_length, // [Modified] Final length-based selectivity
1171 sel_at_age, // [Modified] Final age-based selectivity
1172 growth_matrix, // Length to age transition matrix
1173 sel_slp_off, sel_slp_off_nat, // selectivity linkage offsets (log / natural)
1174 sel_inf_off, sel_inf_off_nat,
1175 sel_coff_off, sel_coff_off_nat,
1176 sel_apical_on, log_sel_apical, // per-sex apical height, only when a linkage names it
1177 sel_apical_off, sel_apical_off_nat,
1178 sel_dn6, sel_dn6_off, sel_dn6_off_nat, sel_dn6_ends // DoubleNormalSS3
1179 );
1180
1181 // -- Selected body weight (kg): sum_l P(l|a) s(l) w(l) / sum_l P(l|a) s(l),
1182 // SS3's "bodywt". A length-selective fleet takes the larger or smaller fish
1183 // of an age class, so its catch and survey biomass weigh that class by the
1184 // fish it selects, not by the class mean. Estimated growth only.
1185 for(flt = 0; flt < n_flt; flt++){
1186 sp = flt_spp(flt);
1187 if(growth_model(sp) == 0 || flt_sel_dim(flt) != 1 || flt_sel_type(flt) == 0) continue;
1188 int wt_idx_sel = nspp * 2 + flt;
1189 for(sex = 0; sex < nsex(sp); sex++){
1190 for(age = 0; age < nages(sp); age++){
1191 for(yr = 0; yr < nyrs; yr++){
1192 Type num = 0, den = 0;
1193 // Integrated over POPULATION bins: both the key and the curve live
1194 // there, so the selectivity weighting is applied at the resolution
1195 // the curve is defined on rather than to a bin average.
1196 for(int ln = 0; ln < nlengths_pop(sp); ln++){
1197 // The last bin takes the previous bin's width; a single-bin grid has
1198 // no neighbour to take one from, so it keeps the edge itself.
1199 Type lenmid = (ln < nlengths_pop(sp) - 1)
1200 ? (lengths_pop(sp, ln) + lengths_pop(sp, ln + 1)) / Type(2.0)
1201 : (nlengths_pop(sp) < 2
1202 ? lengths_pop(sp, ln)
1203 : lengths_pop(sp, ln) + (lengths_pop(sp, ln) - lengths_pop(sp, ln - 1)) / Type(2.0));
1204 Type p_sel = growth_matrix(wt_idx_sel, sex, age, ln, yr) * sel_at_length(flt, sex, ln, yr);
1205 num += p_sel * weight_length_pars(sp, 0) * pow(lenmid, weight_length_pars(sp, 1));
1206 den += p_sel;
1207 }
1208 // An age class the fleet does not select contributes nothing either way.
1209 weight_hat(wt_idx_sel, sex, age, yr) = num / (den + Type(1e-30));
1210 }
1211 }
1212 }
1213 }
1214
1215
1216 // 5.9. BIOENERGETICS AND CONSUMPTION
1217 // - Calculate temperature function of consumption
1218 calculate_temperature_function(fT, nspp, nyrs, Ceq, Cindex, Qc, Tcm, Tco, Tcl, CK1, CK4, env_index);
1219
1220 // - Calculate historic ration
1221 calculate_ration(consumption_at_age, nspp, nyrs, nyrs_hind, nsex, nages, Ceq, CA, CB, fday, Pvalue, fT, ration_data, weight_hat);
1222
1223
1224 // 5.10. PARAMETRIC SUITABILITY
1225 // - Estimate vulnerability (Parametric Suitability)
1226 calculate_vulnerability(vulnerability, vulnerability_other, nspp, suitMode, log_phi);
1227
1228 // - Parametric Suitability (Gamma, Lognormal, Normal)
1229 calculate_parametric_suitability(suitability, suit_other, nspp, nyrs, nsex, nages, suitMode,
1230 length_hat, weight_hat, vulnerability, vulnerability_other, gam_a, gam_b);
1231
1232
1233 // 5.11. REORGANIZE MSVPA DIET DATA
1234 // - Reorganize diet_obs content
1235 organize_diet_obs(nspp, nyrs, nyrs_hind, styr, minage, nsex,
1236 diet_obs, diet_ctl, diet_prop);
1237
1238 // - Calculate other food stomach content
1239 calculate_other_food_diet_prop(nspp, nyrs, nsex, nages, other_food,
1240 diet_prop, other_food_diet_prop);
1241
1242 // 5.12. FISHING MORTALITY and FSPRs
1243 // Outside the multi-species iteration loop: hindcast F needs no M. The
1244 // forecast arm below is provisional -- section 6.7 recomputes it once the
1245 // HCR has its reference points.
1246 F_spp.setZero();
1247 F_flt_age.setZero();
1248 F_at_age.setZero();
1249 Ftarget_at_age.setZero();
1250 Flimit_at_age.setZero();
1251 for(flt = 0; flt < n_flt; flt++) {
1252
1253 sp = flt_spp(flt); // Species this fleet fishes or surveys
1254
1255 if(flt_type(flt) == 1){
1256 for(age = 0; age < nages(sp); age++) {
1257 for(sex = 0; sex < nsex(sp); sex ++){
1258 for(yr = 0; yr < nyrs; yr++) {
1259
1260 // Hindcast
1261 if( yr < nyrs_hind){
1262 F_flt_age(flt, sex, age, yr) = sel_at_age(flt, sex, age, yr) * exp(log_F(flt, yr));
1263 }
1264
1265
1266 // Forecast
1267 if( yr >= nyrs_hind){
1268 // -- Apply HCRs
1269 switch(HCR){
1270 case 0: // No fishing
1271 proj_F(sp, yr) = 0;
1272 break;
1273
1274 case 1: // CMSY
1275 proj_F(sp, yr) = Ftarget(sp);
1276 break;
1277
1278 case 2: // Constant F
1279 proj_F(sp, yr) = Ftarget(sp);
1280 break;
1281
1282 case 3: // Constant F that acheives X% of SSB0
1283 proj_F(sp, yr) = Ftarget(sp);
1284 break;
1285
1286 case 4: // Constant Fspr
1287 proj_F(sp, yr) = Ftarget(sp) * Fmult(sp);
1288 break;
1289
1290 case 5: // NPFMC Tier 3 HCR
1291 proj_F(sp, yr) = Ftarget(sp); // Used Fabc of Ftarget_age%
1292 break;
1293
1294 case 6: // PFMC Category 1 HCR
1295 proj_F(sp, yr) = Ftarget(sp) = Flimit(sp) + QnormHCR(sp);
1296 break;
1297
1298 case 7: // SESSF Tier 1 HCR
1299 proj_F(sp, yr) = Ftarget(sp); // Used Fabc of Ftarget_age%
1300 break;
1301 }
1302
1303 // No projected F when the forecast is off or numbers-at-age are input (estDynamics > 0).
1304 if((forecast(sp) == 0) | (estDynamics(sp) > 0)){
1305 proj_F(sp, yr) = 0;
1306 }
1307 F_flt_age(flt, sex, age, yr) = sel_at_age(flt, sex, age, yr) * proj_F_prop(flt) * proj_F(sp, yr);
1308 }
1309
1310 // -- Sum F across fleets
1311 F_at_age(sp, sex, age, yr) += F_flt_age(flt, sex, age, yr);
1312
1313 // -- Calculate F target by age and sex for reference points
1314 Flimit_at_age(sp, sex, age, yr) += sel_at_age(flt, sex, age, yr) * proj_F_prop(flt) * Flimit(sp); // account for time-varying sel
1315 Ftarget_at_age(sp, sex, age, yr) += sel_at_age(flt, sex, age, yr) * proj_F_prop(flt) * Ftarget(sp); // account for time-varying sel
1316 }
1317 }
1318 }
1319
1320 // F across fleets or species
1321 for(yr = 0; yr < nyrs; yr++) {
1322 // Hindcast
1323 if( yr < nyrs_hind){
1324 F_flt(flt, yr) = exp(log_F(flt, yr));
1325 F_spp(sp, yr) += exp(log_F(flt, yr)); // Fully selected fishing mortality
1326 }
1327
1328 // Forecast
1329 if( yr >= nyrs_hind){
1330 F_flt(flt, yr) = proj_F_prop(flt) * proj_F(sp, yr);
1331 F_spp(sp, yr) += proj_F_prop(flt) * proj_F(sp, yr);
1332 }
1333 }
1334 }
1335 }
1336
1337
1338 // 5.12.1. FISHERY SELECTIVITY AT AGE FOR THE INITIAL STATE (initMode 6 only)
1339 // SS3's InitF convention: the initial equilibrium decays at Finit weighted by fishery
1340 // selectivity, so a size-selective fishery barely touches the young ages. Mean over the
1341 // species' fishery fleets in year 1, and 1 everywhere for every other mode. Filled
1342 // before the SPR reference points build Z_init, and so SPRFinit, from it.
1343 for(sp = 0; sp < nspp; sp++){
1344 for(sex = 0; sex < nsex(sp); sex++){
1345 for(age = 0; age < nages(sp); age++){
1346 sel_init(sp, sex, age) = 1.0;
1347 }
1348 }
1349 }
1350 if(initMode == 6){
1351 for(sp = 0; sp < nspp; sp++){
1352 int n_fsh = 0;
1353 for(flt = 0; flt < n_flt; flt++){
1354 if((flt_type(flt) == 1) && (flt_spp(flt) == sp)) n_fsh++;
1355 }
1356 if(n_fsh > 0){
1357 for(sex = 0; sex < nsex(sp); sex++){
1358 for(age = 0; age < nages(sp); age++){
1359 Type acc = 0.0;
1360 for(flt = 0; flt < n_flt; flt++){
1361 if((flt_type(flt) == 1) && (flt_spp(flt) == sp)){
1362 acc += sel_at_age(flt, sex, age, 0);
1363 }
1364 }
1365 sel_init(sp, sex, age) = acc / Type(n_fsh);
1366 }
1367 }
1368 }
1369 }
1370 }
1371
1372
1373 // 5.13. SIMULATE PROCESS ERROR (sim_mod(simulate = TRUE), simulate_state)
1374 // Drawn before the dynamics consume the deviations -- the initial-numbers block below
1375 // is the first reader of rec_dev and init_dev -- so the dynamics and every observation
1376 // draw downstream are consistent with the simulated process. No second copy of the
1377 // population dynamics is needed (WHAM's sim_pop), these deviations and their SDs all
1378 // being parameters. Each draw uses the density that scores it in section 13, bias
1379 // correction included, which is what makes simulated recruitment mean-unbiased.
1380 //
1381 // True if exactly one density scores rec_dev. False for the AMAK/Ianelli configuration
1382 // (srr_fun == 0 with srr_pred_fun > 0), where the stock-recruit curve is fitted as a
1383 // second penalty on the same deviation. REPORTed so sim_mod() can warn without
1384 // re-deriving it.
1385 int rec_srr_single_density = !((srr_fun == 0) && (srr_pred_fun > 0));
1386 REPORT(rec_srr_single_density);
1387
1388 SIMULATE {
1389 // Masks marking which cells this call actually drew. Every deviation array
1390 // is REPORTed whole -- hindcast and projection alike -- so without these a
1391 // caller cannot tell a simulated cell from one left at its fitted value, and
1392 // a recovery statistic taken over the whole array scores both.
1393 matrix<Type> rec_dev_drawn_sim(rec_dev.rows(), rec_dev.cols());
1394 matrix<Type> init_dev_drawn_sim(init_dev.rows(), init_dev.cols());
1395 array<Type> log_M1_dev_drawn_sim(log_M1_dev.dim);
1396 rec_dev_drawn_sim.setZero();
1397 init_dev_drawn_sim.setZero();
1398 log_M1_dev_drawn_sim.setZero();
1399
1400 for(sp = 0; sp < nspp; sp++){
1401
1402 // The density covers the hindcast only -- projection recruitment comes from the
1403 // harvest control rule or sample_rec() -- so the fitted window is the only period
1404 // this can honestly redraw. srr_fun == 0 with srr_pred_fun > 0
1405 // (rec_srr_single_density, above) is excluded: in that AMAK/Ianelli configuration
1406 // section 13 scores rec_dev through JNLL_REC_DEV and again through
1407 // JNLL_SRR_PENALTY, so there is no single distribution to draw from. Nothing is
1408 // drawn, sim_mod() says why, and the full argument is in
1409 // vignette("model-diagnostics").
1410 if(simulate_state(0) == 1 && simulate_period(0) == 1 && rec_srr_single_density){
1411 for(yr = 0; yr < nyrs_hind; yr++){
1412 rec_dev(sp, yr) = rnorm(-bias_adjust_proc*square(R_sd(sp))/2.0, R_sd(sp));
1413 rec_dev_drawn_sim(sp, yr) = 1;
1414 }
1415 }
1416
1417 // Initial abundance-at-age: the same process, for years before styr. The
1418 // gate is the density's own -- the equilibrium modes and OffsetEquilibrium
1419 // (5) fix init_dev and carry no penalty, so there is nothing to draw -- and
1420 // the rec_srr_single_density gate as well, a fresh initial age structure on
1421 // top of FITTED hindcast deviations being no history the model generated.
1422 if(simulate_state(0) == 1 && simulate_period(0) == 1 && rec_srr_single_density &&
1423 (initMode > 1) && (initMode != 5)){
1424 for(age = 1; age < nages(sp); age++){
1425 init_dev(sp, age - 1) = rnorm(-bias_adjust_proc*square(R_sd(sp))/2.0, R_sd(sp));
1426 init_dev_drawn_sim(sp, age - 1) = 1;
1427 }
1428 }
1429 }
1430
1431 // Natural mortality random effects. The IID modes are the AR1 code at rho = 0, so one
1432 // construction covers all six: draw a standardized AR1 and scale by the marginal SD
1433 // afterwards. M1_dev_log_sd is the INNOVATION sd; Sigma_M is the marginal.
1434 //
1435 // The draw is BROADCAST along whichever dimension the mode holds constant (modes 1/4
1436 // over years, modes 2/5 over ages) and across the sexes sharing one parameter --
1437 // build_map() separates the sexes only at M1_model = 2, so num_re_sexes is the number
1438 // of INDEPENDENT draws. This block writes the expanded array, so writing only the
1439 // cell the density reads would leave the rest at fitted values and the deviation
1440 // would not be constant.
1441 if(simulate_state(1) == 1 && simulate_period(0) == 1){
1442 for(sp = 0; sp < nspp; sp++){
1443 int num_re_sexes = (M1_model(sp) == 2 && nsex(sp) > 1) ? 2 : 1;
1444
1445 if((M1_re(sp) == 1) || (M1_re(sp) == 4)){ // by age, constant over years
1446 Type sigma_M = exp(M1_dev_log_sd(sp, 0));
1447 Type rho_M_a = rho_trans(M1_rho(sp, 0, 0));
1448 Type Sigma_M = pow(pow(sigma_M, 2) / (1.0 - pow(rho_M_a, 2)), 0.5);
1449 for(int s = 0; s < num_re_sexes; s++){
1450 vector<Type> M_re_age(nages(sp));
1451 AR1(rho_M_a).simulate(M_re_age);
1452 M_re_age *= Sigma_M;
1453 int sex_end = (num_re_sexes == 1) ? nsex(sp) : s + 1;
1454 for(int sex = s; sex < sex_end; sex++){
1455 for(age = 0; age < nages(sp); age++){
1456 for(yr = 0; yr < nyrs; yr++){
1457 log_M1_dev(sp, sex, age, yr) = M_re_age(age);
1458 log_M1_dev_drawn_sim(sp, sex, age, yr) = 1;
1459 }
1460 }
1461 }
1462 }
1463 }
1464
1465 if((M1_re(sp) == 2) || (M1_re(sp) == 5)){ // by year, constant over ages
1466 Type sigma_M = exp(M1_dev_log_sd(sp, 0));
1467 Type rho_M_y = rho_trans(M1_rho(sp, 0, 1));
1468 Type Sigma_M = pow(pow(sigma_M, 2) / (1.0 - pow(rho_M_y, 2)), 0.5);
1469 for(int s = 0; s < num_re_sexes; s++){
1470 vector<Type> M_re_yr(nyrs_hind);
1471 AR1(rho_M_y).simulate(M_re_yr);
1472 M_re_yr *= Sigma_M;
1473 int sex_end = (num_re_sexes == 1) ? nsex(sp) : s + 1;
1474 for(int sex = s; sex < sex_end; sex++){
1475 for(yr = 0; yr < nyrs_hind; yr++){
1476 for(age = 0; age < nages(sp); age++){
1477 log_M1_dev(sp, sex, age, yr) = M_re_yr(yr);
1478 log_M1_dev_drawn_sim(sp, sex, age, yr) = 1;
1479 }
1480 }
1481 }
1482 }
1483 }
1484
1485 if((M1_re(sp) == 3) || (M1_re(sp) == 6)){ // by age and year
1486 Type sigma_M = exp(M1_dev_log_sd(sp, 0));
1487 Type rho_M_a = rho_trans(M1_rho(sp, 0, 0));
1488 Type rho_M_y = rho_trans(M1_rho(sp, 0, 1));
1489 Type Sigma_M = pow(pow(sigma_M, 2) / ((1.0 - pow(rho_M_y, 2)) * (1.0 - pow(rho_M_a, 2))), 0.5);
1490 for(int s = 0; s < num_re_sexes; s++){
1491 array<Type> M_re_a_yr(nages(sp), nyrs_hind);
1492 // Same argument order as the density in section 14 -- year on the
1493 // outermost dimension, age on the fastest-running one.
1494 SEPARABLE(AR1(rho_M_y), AR1(rho_M_a)).simulate(M_re_a_yr);
1495 int sex_end = (num_re_sexes == 1) ? nsex(sp) : s + 1;
1496 for(int sex = s; sex < sex_end; sex++){
1497 for(age = 0; age < nages(sp); age++){
1498 for(yr = 0; yr < nyrs_hind; yr++){
1499 log_M1_dev(sp, sex, age, yr) = Sigma_M * M_re_a_yr(age, yr);
1500 log_M1_dev_drawn_sim(sp, sex, age, yr) = 1;
1501 }
1502 }
1503 }
1504 }
1505 }
1506 }
1507 }
1508
1509 // Reported so the draw can be checked directly. Inferring it from the data
1510 // it produces cannot tell "drew correctly" from "drew nothing, and the
1511 // observation error moved". Each goes out with its drawn-cell mask.
1512 matrix<Type> rec_dev_sim = rec_dev;
1513 matrix<Type> init_dev_sim = init_dev;
1514 array<Type> log_M1_dev_sim = log_M1_dev;
1515 REPORT(rec_dev_sim);
1516 REPORT(init_dev_sim);
1517 REPORT(log_M1_dev_sim);
1518 REPORT(rec_dev_drawn_sim);
1519 REPORT(init_dev_drawn_sim);
1520 REPORT(log_M1_dev_drawn_sim);
1521 }
1522
1523 /** ------------------------------------------------------------------------ //
1524 * 6. POPULATION DYNAMICS EQUATIONS //
1525 * ------------------------------------------------------------------------- */
1526 // TMB records this template on AD types for the objective and ADREPORT(), and runs it on
1527 // doubles for REPORT() and simulation. Predation output only REPORT() reads is skipped on AD.
1528 const bool reporting = isDouble<Type>::value;
1529 // Stomach contents are predicted (section 11) and fitted (13.6) under diet_fitted;
1530 // diet_prop_hat (7.2) is filled for them and on the REPORT() pass (diet_used).
1531 const bool diet_fitted = (msmMode > 2) || (imax(suitMode) > 0);
1532 const bool diet_used = reporting || diet_fitted;
1533 // Dynamic B0 and BF (predation at F = 0 and F = Ftarget) are read by REPORT() and a dynamic HCR.
1534 const bool dynamic_B0_used = (DynamicHCR == 1) || reporting;
1535
1536 // Start iterations for multi-species convergence (anything dependent on M)
1537 for(int iter = 0; iter < niter; iter++) {
1538
1539 // 6.1. TOTAL MORTALITY-AT-AGE
1540 for(sp = 0; sp < nspp; sp++) {
1541 for(sex = 0; sex < nsex(sp); sex ++){
1542 // Element-wise: assigning a scalar to a vector would broadcast.
1543 for(int i = 0; i < M1_beta.dim(2); i++){
1544 beta_M1_tmp(i) = M1_beta(sp, sex, i);
1545 }
1546 for(age = 0; age < nages(sp); age++) {
1547 for(yr = 0; yr < nyrs; yr++) {
1548 // Matrix multiplication from sliced arrays doesn't work
1549 env_M1_tmp = env_index.row(yr);
1550 M1_mult = env_M1_tmp * beta_M1_tmp;
1551
1552 // M1_mult.sum() is LEGACY (scheduled removal: v4.5.0). It carries
1553 // the environmental effect of the soft-deprecated M1_indices path,
1554 // so fits built that way still reproduce; `linkages` is the current
1555 // route. See "Scheduled removal" in NEWS.md (4.1.0 section).
1556 M1_at_age(sp, sex, age, yr) = exp(
1557 log_M1(sp, sex, age)
1558 + log_M1_dev(sp, sex, age, yr)
1559 + M1_mult.sum()
1560 + M_linkage_offset(sp, sex, age, yr)
1561 ) + M_linkage_offset_nat(sp, sex, age, yr);
1562 M_at_age(sp, sex, age, yr) = M1_at_age(sp, sex, age, yr) + M2_at_age(sp, sex, age, yr);
1563 M_at_age_dB0(sp, sex, age, yr) = M1_at_age(sp, sex, age, yr) + M2_at_age_dB0(sp, sex, age, yr);
1564 M_at_age_dBF(sp, sex, age, yr) = M1_at_age(sp, sex, age, yr) + M2_at_age_dBF(sp, sex, age, yr);
1565 Z_at_age(sp, sex, age, yr) = M1_at_age(sp, sex, age, yr) + F_at_age(sp, sex, age, yr) + M2_at_age(sp, sex, age, yr);
1566 }
1567 }
1568 }
1569 }
1570
1571
1572 // 6.2. SPR BASED REFERENCE POINTS
1573 //FIXME - make time-varying?
1574 SPR0.setZero();
1575 SPRFinit.setZero();
1576 SPRlimit.setZero();
1577 SPRtarget.setZero();
1578 // Not defined under predation: M carries M2, which scales with predator abundance, so
1579 // spawning output per recruit would not be a property of the prey stock alone.
1580 // data_check() refuses the switch combinations that read these downstream.
1581 if(msmMode == 0){
1582 for(sp = 0; sp < nspp; sp++) {
1583
1584 int na = nages(sp);
1585 int term_yr = nyrs_hind - 1; // rates for a reference point are the terminal hindcast year's
1586 wt_idx_ssb = 2 * sp + 1;
1587
1588 // The four schedules. Flimit and Ftarget are selectivity-scaled and read the
1589 // terminal hindcast year; Finit is the flat F that generated the initial age
1590 // structure, so it is constant across ages and reads year 0, weight included.
1591 // FIXME: time-vary sel in the forecast
1592 vector<Type> Z_unfished(na), Z_limit(na), Z_target(na), Z_init(na);
1593 vector<Type> wt_term(na), wt_first(na), mature_at_age(na);
1594 Type female_split = (nsex(sp) == 1) ? Type(1.0) : sex_ratio(sp, 0);
1595
1596 for(age = 0; age < na; age++){
1597 Z_unfished(age) = M_at_age(sp, 0, age, term_yr);
1598 Z_limit(age) = M_at_age(sp, 0, age, term_yr) + Flimit_at_age(sp, 0, age, term_yr);
1599 Z_target(age) = M_at_age(sp, 0, age, term_yr) + Ftarget_at_age(sp, 0, age, term_yr);
1600 Z_init(age) = M_at_age(sp, 0, age, 0) + Finit(sp) * sel_init(sp, 0, age);
1601
1602 // Spawning output per TOTAL recruit, so the female fraction enters once:
1603 // spawn_output (5.7) carries maturity and the age-varying ratio for a
1604 // one-sex species, female_split the recruitment split (6.6) for a two-sex one.
1605 wt_term(age) = spawn_output(sp, age, term_yr);
1606 wt_first(age) = spawn_output(sp, age, 0);
1607 mature_at_age(age) = female_split;
1608 }
1609
1610 vector<Type> n_unfished = per_recruit_survivors(Z_unfished);
1611 vector<Type> n_limit = per_recruit_survivors(Z_limit);
1612 vector<Type> n_target = per_recruit_survivors(Z_target);
1613 vector<Type> n_init = per_recruit_survivors(Z_init);
1614
1615 SPR0(sp) = spawning_biomass_per_recruit(n_unfished, Z_unfished, wt_term, mature_at_age, spawn_month(sp));
1616 SPRlimit(sp) = spawning_biomass_per_recruit(n_limit, Z_limit, wt_term, mature_at_age, spawn_month(sp));
1617 SPRtarget(sp) = spawning_biomass_per_recruit(n_target, Z_target, wt_term, mature_at_age, spawn_month(sp));
1618 SPRFinit(sp) = spawning_biomass_per_recruit(n_init, Z_init, wt_first, mature_at_age, spawn_month(sp));
1619
1620 // Reported for inspection; slot order matches the four calls above.
1621 for(age = 0; age < na; age++){
1622 NbyageSPR(0, sp, age) = n_unfished(age);
1623 NbyageSPR(1, sp, age) = n_limit(age);
1624 NbyageSPR(2, sp, age) = n_target(age);
1625 NbyageSPR(3, sp, age) = n_init(age);
1626 }
1627 }
1628 }
1629
1630
1631 // 6.3. INITIAL RECRUITMENT
1632 // -- For beverton-holt, steepness and R0 are derived from SPR0
1633 penalty = 0.0;
1634 zero_N_pen.setZero();
1635 for( sp = 0; sp < nspp ; sp++) {
1636 // Under predation SPR is undefined: a hindcast curve takes R_init from the
1637 // free level R0(sp, 0) and reports steepness 0, skipping the cases below.
1638 if((msmMode > 0) & (srr_fun > 1)){
1639 for(yr = 0; yr < nyrs; yr++){ steepness(sp, yr) = 0; }
1640 R_init(sp) = R0(sp, 0);
1641 } else switch(srr_fun){
1642 case 0: // Random about mean (e.g. Alaska)
1643 // No compensation, so steepness is constant across years.
1644 for(yr = 0; yr < nyrs; yr++){ steepness(sp, yr) = 0.99; }
1645 {
1646 R_init(sp) = R0(sp, 0);
1647 }
1648 break;
1649
1650 case 1: // Random about mean with environmental linkage
1651 for(yr = 0; yr < nyrs; yr++){ steepness(sp, yr) = 0.99; }
1652 {
1653 R_init(sp) = R0(sp, 0);
1654 }
1655 break;
1656
1657 case 2: // Beverton-Holt
1658 {
1659 // Steepness for every year: alpha may be time-varying through a linkage.
1660 for(yr = 0; yr < nyrs; yr++){
1661 steepness(sp, yr) = alpha(sp, yr) * SPR0(sp)/(4.0 + alpha(sp, yr) * SPR0(sp));
1662 }
1663 // Unfished recruitment implied by the curve, first year only. Filling every
1664 // year would make R0 an AD function of alpha and Beta across the whole series
1665 // -- ~6x the fit time for a value that is reported rather than used,
1666 // Beverton-Holt recruitment being a function of alpha, Beta and SSB, not of R0.
1667 R0(sp, 0) = (alpha(sp, 0) - 1.0/SPR0(sp)) / Beta(sp, 0); // (Alpha-1/SPR0)/beta
1668 R_init(sp) = (alpha(sp, 0) - 1.0/SPRFinit(sp)) / Beta(sp, 0); // (Alpha-1/SPRFinit)/beta
1669 // Same floor as R in 6.6.1: an identity-link alpha offset can make both negative.
1670 if (rec_floor_on) { Type pen_R = 0; R0(sp, 0) = posfun(R0(sp, 0), Type(1e-3), pen_R); R_init(sp) = posfun(R_init(sp), Type(1e-3), pen_R); zero_N_pen(sp) += pen_R; }
1671 }
1672 break;
1673
1674 case 3: // Retired alias of 2; build_srr() refuses it (alpha moves via a linkage)
1675 {
1676 // Steepness for every year: alpha may be time-varying through a linkage.
1677 for(yr = 0; yr < nyrs; yr++){
1678 steepness(sp, yr) = alpha(sp, yr) * SPR0(sp)/(4.0 + alpha(sp, yr) * SPR0(sp));
1679 }
1680 // Unfished recruitment implied by the curve, first year only -- see
1681 // case 2 for why it is not filled for every year.
1682 R0(sp, 0) = (alpha(sp, 0) - 1.0/SPR0(sp)) / Beta(sp, 0); // (Alpha-1/SPR0)/beta
1683 R_init(sp) = (alpha(sp, 0) - 1.0/SPRFinit(sp)) / Beta(sp, 0); // (Alpha-1/SPRFinit)/beta
1684 // Same floor as R in 6.6.1: an identity-link alpha offset can make both negative.
1685 if (rec_floor_on) { Type pen_R = 0; R0(sp, 0) = posfun(R0(sp, 0), Type(1e-3), pen_R); R_init(sp) = posfun(R_init(sp), Type(1e-3), pen_R); zero_N_pen(sp) += pen_R; }
1686 }
1687 break;
1688
1689 case 4: // Ricker
1690 {
1691 // Steepness for every year: alpha may be time-varying through a linkage.
1692 for(yr = 0; yr < nyrs; yr++){
1693 { Type aS = alpha(sp, yr) * SPR0(sp); // kept positive under an identity-link alpha offset
1694 if (rec_floor_on) { Type pen_d = 0; aS = posfun(aS, Type(1e-3), pen_d); }
1695 steepness(sp, yr) = 0.2 * exp(0.8*log(aS)); }
1696 }
1697
1698 // - R at F0
1699 Type pen_rk = 0; // this species' floor penalties alone
1700 ricker_intercept = alpha(sp, 0) * SPR0(sp) - 1.0;
1701 ricker_intercept = posfun(ricker_intercept, Type(0.001), pen_rk) + 1.0;
1702 // Year 0 only: posfun() keeps the Ricker intercept positive, charging the
1703 // excursion to the objective. The Ianelli configuration (srr_fun < 2)
1704 // never reaches this case, so its R0 keeps its estimated value.
1705 R0(sp, 0) = log(ricker_intercept)/(Beta(sp, 0) * SPR0(sp)/1000000.0);
1706
1707 // R at equilibrium F
1708 ricker_intercept = alpha(sp, 0) * SPRFinit(sp) - 1.0;
1709 ricker_intercept = posfun(ricker_intercept, Type(0.001), pen_rk) + 1.0;
1710 R_init(sp) = log(ricker_intercept)/(Beta(sp, 0) * SPRFinit(sp)/1000000.0);
1711 zero_N_pen(sp) += pen_rk;
1712 }
1713 break;
1714
1715 case 5: // Ricker with environmental impacts on alpha
1716 {
1717 // Steepness for every year: alpha may be time-varying through a linkage.
1718 for(yr = 0; yr < nyrs; yr++){
1719 { Type aS = alpha(sp, yr) * SPR0(sp); // kept positive under an identity-link alpha offset
1720 if (rec_floor_on) { Type pen_d = 0; aS = posfun(aS, Type(1e-3), pen_d); }
1721 steepness(sp, yr) = 0.2 * exp(0.8*log(aS)); }
1722 }
1723
1724 // - R at F0
1725 Type pen_rk = 0; // this species' floor penalties alone
1726 ricker_intercept = alpha(sp, 0) * SPR0(sp) - 1.0;
1727 ricker_intercept = posfun(ricker_intercept, Type(0.001), pen_rk) + 1.0;
1728 // Year 0 only, as case 4.
1729 R0(sp, 0) = log(ricker_intercept)/(Beta(sp, 0) * SPR0(sp)/1000000.0);
1730
1731 // R at equilibrium F
1732 ricker_intercept = alpha(sp, 0) * SPRFinit(sp) - 1.0;
1733 ricker_intercept = posfun(ricker_intercept, Type(0.001), pen_rk) + 1.0;
1734 R_init(sp) = log(ricker_intercept)/(Beta(sp, 0) * SPRFinit(sp)/1000000.0);
1735 zero_N_pen(sp) += pen_rk;
1736 }
1737 break;
1738
1739 default:
1740 error("Invalid 'srr_fun'");
1741 }
1742
1743 // Under the Ianelli configuration (srr_fun 0 or 1, srr_pred_fun > 1) the curve is
1744 // estimated as a recruitment penalty rather than driving the hindcast, and the
1745 // switch above -- keyed on srr_fun -- would leave steepness at the mean-recruitment
1746 // constant. Derive it from the penalty curve's alpha instead, since the
1747 // stock-recruit prior (JNLL_SRR_PRIOR) is evaluated on it. R0 is deliberately NOT
1748 // re-derived: recruitment here is R0 * exp(rec_dev), so R0 keeps its estimated
1749 // value.
1750 if((srr_fun < 2) & (srr_pred_fun > 1) & (msmMode == 0)){
1751 for(yr = 0; yr < nyrs; yr++){
1752 if((srr_pred_fun == 2) | (srr_pred_fun == 3)){
1753 steepness(sp, yr) = alpha(sp, yr) * SPR0(sp)/(4.0 + alpha(sp, yr) * SPR0(sp));
1754 }
1755 if((srr_pred_fun == 4) | (srr_pred_fun == 5)){
1756 { Type aS = alpha(sp, yr) * SPR0(sp); // kept positive under an identity-link alpha offset
1757 if (rec_floor_on) { Type pen_d = 0; aS = posfun(aS, Type(1e-3), pen_d); }
1758 steepness(sp, yr) = 0.2 * exp(0.8*log(aS)); }
1759 }
1760 }
1761 }
1762 // SPR0 is undefined under predation, so steepness is reported as 0;
1763 // data_check() refuses a steepness prior there.
1764 if((srr_fun < 2) & (srr_pred_fun > 1) & (msmMode > 0)){
1765 for(yr = 0; yr < nyrs; yr++){ steepness(sp, yr) = 0; }
1766 }
1767 }
1768
1769
1770 // 6.4. INITIAL ABUNDANCE AT AGE, BIOMASS, AND SSB (YEAR 1)
1771 biomass.setZero();
1772 ssb.setZero();
1773 for(sp = 0; sp < nspp; sp++) {
1774
1775 // Sex ratio at recruitment (1-sex model gets all R)
1776 if(nsex(sp) == 1){
1777 sex_ratio(sp, 0) = 1.0;
1778 }
1779
1780 // A free initial recruitment level, log scale; 0 without an R_init linkage.
1781 // Read at year 0 because the initial state is one year, and per species
1782 // because that is the stratum it is estimated on. Only the estimated branch
1783 // reads it: input numbers-at-age have no initial state to scale.
1784 Type init_level = recruitment_linkage_offset(sp, RCEATTLE_REC_R_INIT, 0);
1785
1786 for(age = 0; age < nages(sp); age++){
1787 for(sex = 0; sex < nsex(sp); sex ++){
1788
1789 switch(estDynamics(sp)){
1790 case 0: // Estimated
1791
1792 // - Amin (i.e. recruitment).
1793 if(age == 0){
1794 // Year-1 recruitment is a recruitment year with its own deviate,
1795 // not part of the pre-hindcast level, so it stays at R_init.
1796 R(sp, 0) = R_init(sp) * exp(rec_dev(sp, 0));
1797 N_at_age(sp, 0, 0, 0) = R(sp, 0) * sex_ratio(sp, 0);
1798 // Guarded because the male slot exists only where some species is
1799 // two-sex: the value would be 0 anyway (sex_ratio 1, set above),
1800 // but the index is out of range when max_sex is 1.
1801 if(nsex(sp) > 1){
1802 N_at_age(sp, 1, 0, 0) = R(sp, 0) * (1-sex_ratio(sp, 0));
1803 }
1804 // The equilibrium carries no recruitment deviation: it is the mean
1805 // level the deviates depart from. It DOES carry the initial level,
1806 // on every age including this one, so the equilibrium that
1807 // equil_catch_hat integrates sits at one recruitment level.
1808 N_eq(sp, 0, 0) = R_init(sp) * exp(init_level) * sex_ratio(sp, 0);
1809 if(nsex(sp) > 1){
1810 N_eq(sp, 1, 0) = R_init(sp) * exp(init_level) * (1-sex_ratio(sp, 0));
1811 }
1812 }
1813
1814 // - Estimate as free parameters
1815 if(initMode == 0){
1816 if(age > 0){
1817 N_at_age(sp, 0, age, 0) = exp(init_dev(sp, age-1)) * sex_ratio(sp, 0);
1818 if(nsex(sp) > 1){
1819 N_at_age(sp, 1, age, 0) = exp(init_dev(sp, age-1)) * (1-sex_ratio(sp, 0));
1820 }
1821 // No equilibrium underlies free initial numbers; Finit is 0 here
1822 // and an equilibrium catch is refused, so this is never fitted.
1823 N_eq(sp, 0, age) = N_at_age(sp, 0, age, 0);
1824 if(nsex(sp) > 1){
1825 N_eq(sp, 1, age) = N_at_age(sp, 1, age, 0);
1826 }
1827 }
1828 }
1829
1830 // - Equilibrium or non-equilibrium from Rinit, Finit, mortality and init devs
1831 // Finit is 0 for initMode 0, 1, 2 and 5; it is estimated for the
1832 // fished non-equilibrium modes 3, 4 and 6 (see section 6.1).
1833 if(initMode > 0){
1834
1835 // How far the initial age-structure sits off the mean-recruitment
1836 // equilibrium R0, on the log scale; 0 under neither source below. Two
1837 // sources, never both (an R_init linkage is refused under mode 5): the free
1838 // R_init level -- SS3's SR_regime block on the year before the hindcast,
1839 // which SS3 shrinks at sigmaR/ave_age and Rceattle leaves free, so put a
1840 // prior on the coefficient to match SS3 -- or, under OffsetEquilibrium (5),
1841 // the first-year recruitment deviation, seeding the structure off
1842 // exp(rec_pars + rec_dev(sp, 0)) with init devs off (Cole Monnahan / AFSC
1843 // GOA pollock convention).
1844 Type init_log_scalar = init_level;
1845 if(initMode == 5){
1846 init_log_scalar += rec_dev(sp, 0);
1847 }
1848
1849 // Sum M1 until age - 1. OffsetEquilibrium (5) uses the same
1850 // standard departing-age cumulative-M decay as the equilibrium
1851 // modes (Finit is 0 for mode 5).
1852 if((initMode == 1) | (initMode == 2) | (initMode == 3) | (initMode == 5)){
1853 mort_sum(sp, age) = 0;
1854 for(int age_tmp = 0; age_tmp < age; age_tmp++){
1855 mort_sum(sp, age) += M1_at_age(sp, sex, age_tmp, 0) + Finit(sp);
1856 }
1857 }
1858
1859 // SS3's InitF convention: the initial F is spread over ages by
1860 // the fishery's selectivity before it accumulates, so an
1861 // unselected young age carries almost none of it.
1862 if(initMode == 6){
1863 mort_sum(sp, age) = 0;
1864 for(int age_tmp = 0; age_tmp < age; age_tmp++){
1865 mort_sum(sp, age) += M1_at_age(sp, sex, age_tmp, 0)
1866 + Finit(sp) * sel_init(sp, sex, age_tmp);
1867 }
1868 }
1869
1870 if(initMode == 4){
1871 mort_sum(sp, age) = 0;
1872 for(int age_tmp = 0; age_tmp < age; age_tmp++){
1873 mort_sum(sp, age) += M1_at_age(sp, sex, age_tmp, 0);
1874 }
1875 mort_sum(sp, age) += Finit(sp);
1876 }
1877
1878 // -- 6.5.2. Age Amin+1:Amax-1 (initial abundance)
1879 if((age > 0) & (age < nages(sp) - 1)) {
1880
1881 if(sex == 0){
1882 N_at_age(sp, 0, age, 0) = R_init(sp) * exp( - mort_sum(sp, age) + init_dev(sp, age - 1) + init_log_scalar) * sex_ratio(sp, 0);
1883 N_eq(sp, 0, age) = R_init(sp) * exp( - mort_sum(sp, age) + init_log_scalar) * sex_ratio(sp, 0);
1884 }
1885 if(sex == 1){
1886 N_at_age(sp, 1, age, 0) = R_init(sp) * exp( - mort_sum(sp, age) + init_dev(sp, age - 1) + init_log_scalar) * (1-sex_ratio(sp, 0));
1887 N_eq(sp, 1, age) = R_init(sp) * exp( - mort_sum(sp, age) + init_log_scalar) * (1-sex_ratio(sp, 0));
1888 }
1889 }
1890
1891 // -- 6.5.3. Amax
1892 if(age == (nages(sp) - 1)) {
1893
1894 // The plus group accumulates at its own total mortality. Under initMode
1895 // 6 the initial F reaches an age through that age's selectivity, so the
1896 // oldest age decays at M1 + Finit * sel (SS3's equilibrium convention);
1897 // every other mode charges the full Finit, as in mort_sum above.
1898 Type Z_plus = M1_at_age(sp, sex, nages(sp) - 1, 0) + Finit(sp) *
1899 ((initMode == 6) ? sel_init(sp, sex, nages(sp) - 1) : Type(1.0));
1900 Type plus_grp = 1 - exp(-Z_plus);
1901
1902 if(sex == 0){// NOTE: This solves for the geometric series
1903 N_at_age(sp, 0, age, 0) = R_init(sp) * exp( - mort_sum(sp, age) + init_dev(sp, age - 1) + init_log_scalar) / plus_grp * sex_ratio(sp, 0);
1904 N_eq(sp, 0, age) = R_init(sp) * exp( - mort_sum(sp, age) + init_log_scalar) / plus_grp * sex_ratio(sp, 0);
1905 }
1906
1907 if(sex == 1){
1908 N_at_age(sp, 1, age, 0) = R_init(sp) * exp( - mort_sum(sp, age) + init_dev(sp, age - 1) + init_log_scalar) / plus_grp * (1-sex_ratio(sp, 0));
1909 N_eq(sp, 1, age) = R_init(sp) * exp( - mort_sum(sp, age) + init_log_scalar) / plus_grp * (1-sex_ratio(sp, 0));
1910 }
1911 }
1912 }
1913 break;
1914
1915 case 1: // Numbers-at-age fixed exactly to NByageFixed (pop_scalar mapped to
1916 // NA in build_map so log_pop_scalar = 0 -> pop_scalar = 1.0)
1917 N_at_age(sp, sex, age, 0) = pop_scalar(sp) * NByageFixed(sp, sex, age, 0);
1918 break;
1919
1920 case 2: // Numbers-at-age scaled by a single estimated age-independent scalar
1921 N_at_age(sp, sex, age, 0) = pop_scalar(sp) * NByageFixed(sp, sex, age, 0);
1922 break;
1923
1924 default:
1925 error("Invalid 'estDynamics'");
1926 }
1927
1928 // -- 6.5.3. Estimate total biomass in year 1
1929 wt_idx_pop = 2 * sp;
1930 biomass_at_age(sp, sex, age, 0) = N_at_age(sp, sex, age, 0) * weight_hat( wt_idx_pop, sex, age, 0);
1931 biomass(sp, 0) += N_at_age(sp, sex, age, 0) * weight_hat( wt_idx_pop, sex, age, 0);
1932 }
1933
1934 // -- 6.5.4. Estimated initial female SSB
1935 wt_idx_ssb = 2 * sp + 1;
1936 ssb(sp, 0) += N_at_age(sp, 0, age, 0) * exp(-Z_at_age(sp, 0, age, 0) * spawn_month(sp)/12) * spawn_output(sp, age, 0); // 6.6.
1937 }
1938 }
1939
1940
1941 // 6.5. HINDCAST NUMBERS AT AGE, BIOMASS-AT-AGE (mt), and ssb-AT-AGE (mt)
1942 penalty = 0.0;
1943 for(sp = 0; sp < nspp; sp++) {
1944 for(yr = 1; yr < nyrs_hind; yr++) {
1945
1946 // Switch for srr (for MSEs if using Ianelli SRR method)
1947 int srr_switch = srr_fun;
1948 if(yr >= nyrs_srrmean){
1949 srr_switch = srr_pred_fun;
1950 }
1951
1952 // -- 6.6.1. Recruitment
1953
1954 // Recruits arriving at age minage in year yr were spawned in yr - minage,
1955 // before styr while yr < minage. With no modelled SSB those years take
1956 // R_init * exp(rec_dev) -- equilibrium recruitment at F = Finit, what
1957 // year 0 gets, so ages seeded from the same equilibrium agree. Stock
1958 // Synthesis treats the pre-start period the same way; WHAM avoids it by
1959 // fixing the lag at one year. Cannot fire at minage = 1.
1960 int spawn_yr = yr - minage(sp);
1961 int srr_use = (spawn_yr < 0) ? 0 : srr_switch;
1962 Type ssb_tmp = (spawn_yr < 0) ? Type(0.0) : ssb(sp, spawn_yr);
1963 // Pre-styr years take R_init, not R0(sp, yr): under a hindcast curve R0 is
1964 // set only at year 0 (derived, or the free level under predation).
1965 Type rec_mean = (spawn_yr < 0) ? R_init(sp) : R0(sp, yr);
1966
1967 R(sp, yr) = calculate_recruitment(srr_use, rec_mean, ssb_tmp, alpha(sp, yr), Beta(sp, yr), rec_dev(sp, yr), SPR0(sp));
1968 // Under an identity-link recruitment offset the curve can go non-positive: keep R
1969 // positive (posfun, 0.001 barrier), charging the excursion to the zero-N row.
1970 if (rec_floor_on) { Type pen_R = 0; R(sp, yr) = posfun(R(sp, yr), Type(1e-3), pen_R); zero_N_pen(sp) += pen_R; }
1971
1972 N_at_age(sp, 0, 0, yr) = R(sp, yr) * sex_ratio(sp, 0);
1973 if(nsex(sp) > 1){
1974 N_at_age(sp, 1, 0, yr) = R(sp, yr) * (1.0-sex_ratio(sp, 0));
1975 }
1976
1977
1978 // -- 6.6.2. Ages beyond recruitment
1979 for(age = 0; age < nages(sp); age++){
1980 for(sex = 0; sex < nsex(sp); sex ++){
1981
1982 switch(estDynamics(sp)){
1983 case 0: // Estimated numbers-at-age
1984
1985 // -- Where Amin < age < Amax
1986 if(age < (nages(sp) - 1)) {
1987 N_at_age(sp, sex, age + 1, yr) = N_at_age(sp, sex, age, yr - 1) * exp(-Z_at_age(sp, sex, age, yr-1));// S_at_age(sp, sex, age, yr - 1);
1988 }
1989
1990 // -- Plus group where age = Amax.
1991 if(age == (nages(sp) - 1)) {
1992 N_at_age(sp, sex, age, yr) = N_at_age(sp, sex, age - 1, yr - 1) * exp(-Z_at_age(sp, sex, age-1, yr-1)) + N_at_age(sp, sex, age, yr - 1) * exp(-Z_at_age(sp, sex, age, yr-1)); // S_at_age(sp, sex, age, yr - 1);
1993 }
1994 break;
1995
1996 case 1: // Numbers-at-age fixed exactly to NByageFixed (pop_scalar = 1.0 via map)
1997 N_at_age(sp, sex, age, yr) = pop_scalar(sp) * NByageFixed(sp, sex, age, yr);
1998 break;
1999
2000 case 2: // Numbers-at-age scaled by a single estimated age-independent scalar
2001 N_at_age(sp, sex, age, yr) = pop_scalar(sp) * NByageFixed(sp, sex, age, yr);
2002 break;
2003
2004 default:
2005 error("Invalid 'estDynamics'");
2006 }
2007
2008 // A fresh accumulator per cell: the penalty is this cell's excursion alone.
2009 { Type pen_N = 0; N_at_age(sp, sex, age, yr) = posfun(N_at_age(sp, sex, age, yr), Type(0.001), pen_N); zero_N_pen(sp) += pen_N; }
2010
2011 // -- 6.6.3. Estimate total biomass
2012 wt_idx_pop = 2 * sp ;
2013 biomass_at_age(sp, sex, age, yr) = N_at_age(sp, sex, age, yr) * weight_hat( wt_idx_pop, sex, age, yr );
2014 biomass(sp, yr) += biomass_at_age(sp, sex, age, yr);
2015 }
2016
2017 // -- 6.6.4. Estimated female ssb
2018 wt_idx_ssb = 2 * sp + 1;
2019 ssb(sp, yr) += N_at_age(sp, 0, age, yr) * exp(-Z_at_age(sp, 0, age, yr) * spawn_month(sp)/12.0) * spawn_output(sp, age, yr); // 6.6.
2020 }
2021 }
2022 }
2023
2024
2025 // 6.6. DEPLETION BASED BIOMASS REFERENCE POINTS (i.e. SB0 and dynamic SB0)
2026 // -- calculate mean recruitment
2027 // FIXME: may want specified year ranges
2028 avg_R.setZero();
2029 for(sp = 0; sp < nspp; sp++) {
2030 for(yr = 0; yr < nyrs_srrmean; yr++) {
2031 avg_R(sp) += R(sp, yr)/Type(nyrs_srrmean);
2032 }
2033 }
2034
2035 // -- Calc biomass_depletion based BRPs
2036 NByage0.setZero();
2037 NByageF.setZero();
2038 N_at_age_dBF.setZero();
2039 N_at_age_dB0.setZero();
2040 B0.setZero();
2041 SB0.setZero();
2042 SBF.setZero();
2043 DynamicB0.setZero();
2044 DynamicSB0.setZero();
2045 DynamicSBF.setZero();
2046 for(sp = 0; sp < nspp; sp++) {
2047 for(yr = 0; yr < nyrs; yr++) {
2048
2049 // - Year 1
2050 // -- Initial abundance-at-age is the same as the hindcast
2051 if(yr == 0){
2052 for(sex = 0; sex < nsex(sp); sex ++){
2053 for(age = 0; age < nages(sp); age++){
2054 NByage0(sp, sex, age , 0) = NByageF(sp, sex, age , 0) = N_at_age_dBF(sp, sex, age, 0) = N_at_age_dB0(sp, sex, age, 0) = N_at_age(sp,sex,age,0);
2055 }
2056 }
2057 }
2058
2059 // - Recruitment Year > 1
2060 if(yr > 0){
2061 // - Option 1a: Use mean rec
2062 if((proj_mean_rec == 1) & (srr_pred_fun < 2)){
2063 // Equilibrium RPs used mean rec across all years
2064 NByage0(sp, 0, 0, yr) = avg_R(sp);
2065 NByageF(sp, 0, 0, yr) = avg_R(sp);
2066
2067 // Dynamic RPs use mean rec for the forecast and observed rec for the
2068 // hindcast. LEGACY (scheduled removal: v4.5.0): prefer the
2069 // stock-recruit arm below. This split feeds SB0(sp, nyrs-1), so it
2070 // wants a deliberate decision rather than a sweep.
2071 if(yr < nyrs_hind){
2072 N_at_age_dBF(sp, 0, 0, yr) = N_at_age_dB0(sp, 0, 0, yr) = R(sp, yr); // Hindcast use observed R
2073 }
2074 if(yr >= nyrs_hind){
2075 N_at_age_dBF(sp, 0, 0, yr) = N_at_age_dB0(sp, 0, 0, yr) = exp(log(avg_R(sp)) + rec_dev(sp, yr)); // Projections use mean R given bias in R0
2076 }
2077 }
2078
2079
2080 // - Option 2: Use SRR
2081 // Reached whenever a curve exists, not only when the projection runs on it. The
2082 // breadth is deliberate: Option 1a excludes srr_pred_fun >= 2, so proj_mean_rec
2083 // = 1 (the build_srr() default) with an estimated curve would match NEITHER
2084 // arm, leaving reference-point recruitment 0 after the first year. SB0 would
2085 // decay towards zero, and SB0(sp, nyrs-1) is the depletion reference HCRs 5 and
2086 // 6 read. Projection recruitment is unaffected: 6.8 reads that switch
2087 // separately, so mean-recruitment projections stay mean.
2088 if((proj_mean_rec == 0) | (srr_pred_fun >= 2)){
2089
2090 // - Equilibrium reference points (No recruitment deviation: pass Type(0.0))
2091 // Equilibrium spawning biomass exists every year; yr < minage reads the
2092 // first year's value so the lag stays in bounds.
2093 int rp_yr = yr - minage(sp);
2094 if(rp_yr < 0){ rp_yr = 0; }
2095
2096 // TODO: not floored under an identity-link recruitment offset, so SB0, SBF and B0 can go negative (issue #234).
2097 NByage0(sp, 0, 0, yr) = calculate_recruitment(srr_pred_fun, R0(sp, yr), SB0(sp, rp_yr), alpha(sp, yr), Beta(sp, yr), Type(0.0), SPR0(sp));
2098 NByageF(sp, 0, 0, yr) = calculate_recruitment(srr_pred_fun, R0(sp, yr), SBF(sp, rp_yr), alpha(sp, yr), Beta(sp, yr), Type(0.0), SPR0(sp));
2099
2100 // - Dynamic reference points (Includes annual recruitment deviation: pass rdev)
2101 // Cohorts spawned before the first year take the hindcast's realized R
2102 // (R_init with its deviation), so both runs start from the same cohorts.
2103 Type rdev = rec_dev(sp, yr);
2104 if(yr < minage(sp)){
2105 Type R_early = (yr < nyrs_hind) ? R(sp, yr) : R_init(sp) * exp(rdev);
2106 N_at_age_dB0(sp, 0, 0, yr) = R_early;
2107 N_at_age_dBF(sp, 0, 0, yr) = R_early;
2108 } else {
2109 // Under the Ianelli form the hindcast is on mean recruitment until
2110 // srr_mse_switchyr, so rec_dev there is measured from R0; the curve takes
2111 // the realized deviation from it, log R - log R_hat.
2112 if((srr_fun != srr_pred_fun) & (yr < nyrs_srrmean)){
2113 Type R_curve = calculate_recruitment(srr_pred_fun, R0(sp, yr), ssb(sp, rp_yr), alpha(sp, yr), Beta(sp, yr), Type(0.0), SPR0(sp));
2114 // Same floor as R in 6.6.1, for an identity-link offset that makes the curve non-positive.
2115 if (rec_floor_on) { Type pen_R = 0; R_curve = posfun(R_curve, Type(1e-3), pen_R); zero_N_pen(sp) += pen_R; }
2116 rdev = log(R(sp, yr)) - log(R_curve);
2117 }
2118 // TODO: dynamic-B0 recruitment is not floored under an identity-link offset (issue #234).
2119 N_at_age_dB0(sp, 0, 0, yr) = calculate_recruitment(srr_pred_fun, R0(sp, yr), DynamicSB0(sp, rp_yr), alpha(sp, yr), Beta(sp, yr), rdev, SPR0(sp));
2120 N_at_age_dBF(sp, 0, 0, yr) = calculate_recruitment(srr_pred_fun, R0(sp, yr), DynamicSBF(sp, rp_yr), alpha(sp, yr), Beta(sp, yr), rdev, SPR0(sp));
2121 }
2122
2123 } // End recruitment switch
2124
2125 // Account for sex ratio. The male block is guarded because that slot
2126 // exists only where some species is two-sex; the value would be 0
2127 // anyway (sex_ratio 1, set in 6.4).
2128 NByage0(sp, 0, 0, yr) = NByage0(sp, 0, 0, yr) * sex_ratio(sp, 0); // Females
2129 NByageF(sp, 0, 0, yr) = NByageF(sp, 0, 0, yr) * sex_ratio(sp, 0); // Females
2130 N_at_age_dB0(sp, 0, 0, yr) = N_at_age_dB0(sp, 0, 0, yr) * sex_ratio(sp, 0); // Females
2131 N_at_age_dBF(sp, 0, 0, yr) = N_at_age_dBF(sp, 0, 0, yr) * sex_ratio(sp, 0); // Females
2132
2133 if(nsex(sp) > 1){
2134 // Males (divide by sex_ratio because we multiplied in the lines above)
2135 NByage0(sp, 1, 0, yr) = NByage0(sp, 0, 0, yr) / sex_ratio(sp, 0) * (1.0-sex_ratio(sp, 0));
2136 NByageF(sp, 1, 0, yr) = NByageF(sp, 0, 0, yr) / sex_ratio(sp, 0) * (1.0-sex_ratio(sp, 0));
2137 N_at_age_dB0(sp, 1, 0, yr) = N_at_age_dB0(sp, 0, 0, yr) / sex_ratio(sp, 0) * (1.0-sex_ratio(sp, 0));
2138 N_at_age_dBF(sp, 1, 0, yr) = N_at_age_dBF(sp, 0, 0, yr) / sex_ratio(sp, 0) * (1.0-sex_ratio(sp, 0));
2139 }
2140
2141
2142 // N-at-age year > 1
2143 for(sex = 0; sex < nsex(sp); sex ++){
2144 for(age = 1; age < nages(sp)-1; age++) {
2145 NByage0(sp, sex, age, yr) = NByage0(sp, sex, age-1, yr-1) * exp(-M_at_age(sp, sex, age-1, yr-1)); // F = 0
2146
2147 NByageF(sp, sex, age, yr) = NByageF(sp, sex, age-1, yr-1) * exp(-M_at_age(sp, sex, age-1, yr-1) - Ftarget_at_age(sp, sex, age-1, yr-1)); // F = target
2148
2149 // No 0.001 floor here: the hindcast's is a numerical guard, and dynamic B0
2150 // must not assume a stock that fell to it would not have crashed without
2151 // fishing.
2152 N_at_age_dB0(sp, sex, age, yr) = N_at_age_dB0(sp, sex, age-1, yr-1) * exp(-M_at_age_dB0(sp, sex, age-1, yr - 1)); // F = 0
2153
2154 N_at_age_dBF(sp, sex, age, yr) = N_at_age_dBF(sp, sex, age-1, yr-1) * exp(-M_at_age_dBF(sp, sex, age-1, yr - 1) - Ftarget_at_age(sp, sex, age-1, yr-1)); // F = Ftarget
2155 }
2156
2157 // Plus group -- No fishing
2158 NByage0(sp, sex, nages(sp)-1, yr) = NByage0(sp, sex, nages(sp)-2, yr - 1) * exp(-M_at_age(sp, sex, nages(sp)-2, yr - 1)) + NByage0(sp, sex, nages(sp)-1, yr - 1) * exp(-M_at_age(sp, sex, nages(sp)-1, yr - 1));
2159
2160 NByageF(sp, sex, nages(sp)-1, yr) = NByageF(sp, sex, nages(sp)-2, yr - 1) * exp(-M_at_age(sp, sex, nages(sp)-2, yr - 1) - Ftarget_at_age(sp, sex, nages(sp)-2, yr-1)) + NByageF(sp, sex, nages(sp)-1, yr - 1) * exp(-M_at_age(sp, sex, nages(sp)-1, yr - 1) - Ftarget_at_age(sp, sex, nages(sp)-1, yr-1));
2161
2162 N_at_age_dB0(sp, sex, nages(sp)-1, yr) = N_at_age_dB0(sp, sex, nages(sp)-2, yr - 1) * exp(-M_at_age_dB0(sp, sex, nages(sp)-2, yr - 1)) + N_at_age_dB0(sp, sex, nages(sp)-1, yr - 1) * exp(-M_at_age_dB0(sp, sex, nages(sp)-1, yr - 1));
2163
2164 N_at_age_dBF(sp, sex, nages(sp)-1, yr) = N_at_age_dBF(sp, sex, nages(sp)-2, yr - 1) * exp(-M_at_age_dBF(sp, sex, nages(sp)-2, yr - 1) - Ftarget_at_age(sp, sex, nages(sp)-2, yr-1)) + N_at_age_dBF(sp, sex, nages(sp)-1, yr - 1) * exp(-M_at_age_dBF(sp, sex, nages(sp)-1, yr - 1) - Ftarget_at_age(sp, sex, nages(sp)-1, yr-1));
2165
2166 }
2167 }
2168
2169 // A species with input numbers-at-age (estDynamics > 0) keeps them in the
2170 // dynamic runs; projection years are read directly, as 6.8 fills N later.
2171 if(estDynamics(sp) > 0){
2172 for(sex = 0; sex < nsex(sp); sex ++){
2173 for(age = 0; age < nages(sp); age++){
2174 Type n_fixed = (yr < nyrs_hind) ? N_at_age(sp, sex, age, yr) :
2175 pop_scalar(sp) * NByageFixed(sp, sex, age, yr);
2176 N_at_age_dB0(sp, sex, age, yr) = n_fixed;
2177 N_at_age_dBF(sp, sex, age, yr) = n_fixed;
2178 }
2179 }
2180 }
2181
2182
2183 // Calculate Dynamic SB0 and SB at F target
2184 for(age = 0; age < nages(sp); age++) {
2185
2186 wt_idx_ssb = 2 * sp + 1;
2187 // Multispecies: M_at_age carries the projection's realized M2. The one rule
2188 // that reads SBF, NPFMC (HCR 5), is refused there; SB0 is replaced by MSSB0
2189 // below.
2190 SB0(sp, yr) += NByage0(sp, 0, age, yr) * spawn_output(sp, age, nyrs_hind - 1) * exp(-M_at_age(sp, 0, age, yr) * spawn_month(sp)/12.0);
2191 SBF(sp, yr) += NByageF(sp, 0, age, yr) * spawn_output(sp, age, nyrs_hind - 1) * exp(-(M_at_age(sp, 0, age, yr) + Ftarget_at_age(sp, 0, age, yr)) * spawn_month(sp)/12.0);
2192 DynamicSB0(sp, yr) += N_at_age_dB0(sp, 0, age, yr) * spawn_output(sp, age, yr) * exp(-M_at_age_dB0(sp, 0, age, yr) * spawn_month(sp)/12.0);
2193 DynamicSBF(sp, yr) += N_at_age_dBF(sp, 0, age, yr) * spawn_output(sp, age, yr) * exp(-(M_at_age_dBF(sp, 0, age, yr) + Ftarget_at_age(sp, 0, age, yr)) * spawn_month(sp)/12.0);
2194
2195 for(sex = 0; sex < nsex(sp); sex ++){
2196
2197 wt_idx_pop = 2 * sp;
2198 B0(sp, yr) += NByage0(sp, sex, age, yr) * weight_hat( wt_idx_pop, sex, age, nyrs_hind - 1 );
2199 DynamicB0(sp, yr) += N_at_age_dB0(sp, sex,age, yr) * weight_hat( wt_idx_pop, sex, age, yr );
2200 }
2201 }
2202
2203
2204 // Input SB0 (if running in multi-species mode)
2205 if(msmMode > 0){
2206 SB0(sp, yr) = MSSB0(sp);
2207 B0(sp, yr) = MSB0(sp);
2208 }
2209 }
2210 }
2211
2212 // 6.7-6.9. FORECAST NUMBERS AT AGE, BIOMASS-AT-AGE (mt), and ssb-AT-AGE (mt)
2213 // Includes Harvest Control Rules
2214 for(sp = 0; sp < nspp; sp++) {
2215 for(yr = nyrs_hind; yr < nyrs; yr++){
2216
2217 // 6.7. HARVEST CONTROL RULES FOR PROJECTION
2218 // Equilibrium or dynamic reference points (i.e. SB0 or dynamic SB0)
2219 Type ref_SB0 = (DynamicHCR == 1) ? DynamicSB0(sp, yr-1) : SB0(sp, nyrs-1);
2220 Type ref_SBF = (DynamicHCR == 1) ? DynamicSBF(sp, yr-1) : SBF(sp, nyrs-1);
2221
2222 switch(HCR){
2223 case 0: // No fishing
2224 proj_F(sp, yr) = 0.0;
2225 break;
2226
2227 case 1: // CMSY
2228 // proj_F(sp, yr) retains its incoming value
2229 break;
2230
2231 case 2: // Constant F
2232 // proj_F(sp, yr) retains its incoming value
2233 break;
2234
2235 case 3: // Constant F to acheive X% of SB0
2236 // proj_F(sp, yr) retains its incoming value
2237 break;
2238
2239 case 4: // Constant Fspr with multiplier
2240 // proj_F(sp, yr) retains its incoming value
2241 break;
2242
2243 case 5: // NPFMC Tier 3 HCR
2244 if(ssb(sp, yr-1) < ref_SBF){
2245 proj_F(sp, yr) = Ftarget(sp) * (((ssb(sp, yr-1)/ref_SBF)-Alpha(sp))/(1-Alpha(sp))); // Used Fabc of FtargetSPR%
2246 }
2247 if((ssb(sp, nyrs_hind-1) < ref_SB0 * Plimit(sp)) || (ssb(sp, yr-1) / ref_SBF < Alpha(sp))){ // If overfished
2248 proj_F(sp, yr) = 0.0;
2249 }
2250 break;
2251
2252 case 6: // PFMC Category 1 HCR
2253 if(ssb(sp, yr-1) < ref_SB0 * Ptarget(sp)){
2254 proj_F(sp, yr) = (Flimit(sp) + QnormHCR(sp)) * (ref_SB0 * Ptarget(sp) * (ssb(sp, yr-1) - ref_SB0 * Plimit(sp))) / (ssb(sp, yr-1) * (ref_SB0 * (Ptarget(sp) - Plimit(sp))));
2255 }
2256 if(ssb(sp, yr-1) < ref_SB0 * Plimit(sp)){ // If overfished
2257 proj_F(sp, yr) = 0.0;
2258 }
2259 break;
2260
2261 case 7: // SESSF Tier 1 HCR
2262 if(ssb(sp, yr-1) < ref_SB0 * Ptarget(sp)){
2263 proj_F(sp, yr) = Ftarget(sp) * ((ssb(sp, yr-1)/(ref_SB0 * Plimit(sp)))-1); // Used Fabc of FtargetSPR%
2264 }
2265 if(ssb(sp, yr-1) < ref_SB0 * Plimit(sp)){ // If overfished
2266 proj_F(sp, yr) = 0.0;
2267 }
2268 break;
2269 }
2270
2271
2272 // No projected F when the forecast is off or numbers-at-age are input (estDynamics > 0).
2273 if((forecast(sp) == 0) | (estDynamics(sp) > 0)){
2274 proj_F(sp, yr) = 0.0;
2275 }
2276
2277 // -- Update F for the projection (account for selectivity and fleets)
2278 for(age = 0; age < nages(sp); age++) {
2279 for(sex = 0; sex < nsex(sp); sex ++){
2280 F_at_age(sp, sex, age, yr) = 0.0;
2281 }
2282 }
2283
2284 // -- Multiply F from HCR by selectivity and fleet proportion
2285 F_spp(sp, yr) = proj_F(sp, yr);
2286 for(flt = 0; flt < n_flt; flt++) {
2287 if((sp == flt_spp(flt)) & (flt_type(flt) == 1)){ // Fisheries only, as in 5.12
2288 F_flt(flt, yr) = proj_F_prop(flt) * proj_F(sp, yr);
2289 for(age = 0; age < nages(sp); age++) {
2290 for(sex = 0; sex < nsex(sp); sex ++){
2291 F_flt_age(flt, sex, age, yr) = sel_at_age(flt, sex, age, nyrs_hind - 1) * proj_F_prop(flt) * proj_F(sp, yr); // Projection F uses the terminal hindcast year's selectivity
2292 if(flt_type(flt) == 1){
2293 F_at_age(sp, sex, age, yr) += F_flt_age(flt, sex, age, yr);
2294 }
2295 }
2296 }
2297 }
2298 }
2299
2300
2301 // -- Update mortality for forecast with new F
2302 for(age = 0; age < nages(sp); age++) {
2303 for(sex = 0; sex < nsex(sp); sex ++){
2304 M_at_age(sp, sex, age, yr) = M1_at_age(sp, sex, age, yr) + M2_at_age(sp, sex, age, yr);
2305 Z_at_age(sp, sex, age, yr) = M1_at_age(sp, sex, age, yr) + F_at_age(sp, sex, age, yr) + M2_at_age(sp, sex, age, yr);
2306 }
2307 }
2308
2309
2310 // 6.8. FORECAST NUMBERS AT AGE, BIOMASS-AT-AGE (mt), and ssb-AT-AGE (mt)
2311 // -- 6.8.1. Forecasted recruitment
2312 // - Option 1: Use mean rec
2313 if(proj_mean_rec == 1){
2314 R(sp, yr) = avg_R(sp); // // Projections use mean R given bias in R0
2315 }
2316
2317 // - Option 2: Use SRR and rec devs
2318 if(proj_mean_rec == 0){
2319
2320 // - Calculate recruitment (with linkage offsets pre-added).
2321 // Pre-styr spawning year takes R_init, as in the hindcast block;
2322 // reachable only if the hindcast is shorter than minage.
2323 int proj_spawn_yr = yr - minage(sp);
2324 int proj_srr_use = (proj_spawn_yr < 0) ? 0 : srr_pred_fun;
2325 Type ssb_tmp = (proj_spawn_yr < 0) ? Type(0.0) : ssb(sp, proj_spawn_yr);
2326 Type proj_rec_mean = (proj_spawn_yr < 0) ? R_init(sp) : R0(sp, yr);
2327 // TODO: projected recruitment is not floored under an identity-link offset (issue #234).
2328 R(sp, yr) = calculate_recruitment(proj_srr_use, proj_rec_mean, ssb_tmp, alpha(sp, yr), Beta(sp, yr), rec_dev(sp, yr), SPR0(sp));
2329 }
2330
2331 N_at_age(sp, 0, 0 , yr) = R(sp, yr) * sex_ratio(sp, 0);
2332 if(nsex(sp) > 1){
2333 N_at_age(sp, 1, 0 , yr) = R(sp, yr) * (1 - sex_ratio(sp, 0));
2334 }
2335
2336
2337 // -- 6.8.2. Ages > recruitment
2338 for(age = 0; age < nages(sp); age++) {
2339 for(sex = 0; sex < nsex(sp); sex ++){
2340 switch(estDynamics(sp)){
2341 case 0: // Estimated numbers-at-age
2342
2343 // -- 6.8.2. Where minage + 1 <= age < Ai
2344 if(age < (nages(sp) - 1)) {
2345 N_at_age(sp, sex, age + 1, yr) = N_at_age(sp, sex, age, yr - 1) * exp(-Z_at_age(sp, sex, age, yr-1));
2346 }
2347
2348 // -- 6.8.3. Plus group where age > Ai.
2349 if(age == (nages(sp) - 1)) {
2350 N_at_age(sp, sex, age, yr) = N_at_age(sp, sex, age - 1, yr - 1) * exp(-Z_at_age(sp, sex, age-1, yr-1)) + N_at_age(sp, sex, age, yr - 1) * exp(-Z_at_age(sp, sex, age, yr-1));
2351 }
2352 break;
2353
2354 case 1: // Fixed numbers-at-age - fixed scalar
2355 N_at_age(sp, sex, age, yr) = pop_scalar(sp) * NByageFixed(sp, sex, age, yr);
2356 break;
2357
2358 case 2: // Fixed numbers-at-age age-independent scalar
2359 N_at_age(sp, sex, age, yr) = pop_scalar(sp) * NByageFixed(sp, sex, age, yr);
2360 break;
2361
2362 default: // Wrong estDynamics
2363 error("Invalid 'estDynamics'");
2364 }
2365
2366 // -- 6.8.4. FORECAST BIOMASS
2367 wt_idx_pop = 2 * sp;
2368 biomass_at_age(sp, sex, age, yr) = N_at_age(sp, sex, age, yr) * weight_hat( wt_idx_pop, sex, age, nyrs_hind-1 ); // 6.5.
2369 biomass(sp, yr) += biomass_at_age(sp, sex, age, yr);
2370 } // End sex loop
2371
2372 // -- 6.8.5. FORECAST SSB (SUM ACROSS AGES)
2373 wt_idx_ssb = 2 * sp + 1;
2374 ssb(sp, yr) += N_at_age(sp, 0, age, yr) * exp(-Z_at_age(sp, 0, age, yr) * spawn_month(sp)/12.0) * spawn_output(sp, age, nyrs_hind-1); // 6.6.
2375 }
2376 }
2377 }
2378
2379
2380 // 6.9. EXPECTED RECRUITMENT
2381 // The function-scope `yr` is left at `nyrs` by the forecast loop above, so
2382 // the year-0 block uses the explicit `first_yr` constant: reading
2383 // R0/alpha/Beta at `yr` would run one column past the end and segfault
2384 // inside MakeADFun. The assertion pins those matrices to the year horizon.
2385 const int first_yr = 0;
2386 if (R0.cols() != nyrs || alpha.cols() != nyrs || Beta.cols() != nyrs) {
2387 error("Section 6.9: R0/alpha/Beta column count does not equal nyrs; "
2388 "recruitment-parameter matrices were sized inconsistently.");
2389 }
2390 for(sp = 0; sp < nspp; sp++) {
2391
2392 // Year 1 (arent fit in likelihood)
2393 // Under predation there is no SPRFinit (6.2) to place the first year on
2394 // the curve, so it takes R_init, the anchor its realised recruitment uses.
2395 if((msmMode > 0) & (srr_pred_fun > 1)){
2396 R_hat(sp, first_yr) = R_init(sp);
2397 } else {
2398 switch(srr_pred_fun){
2399 case 0: // Random about mean (e.g. Alaska)
2400 R_hat(sp, first_yr) = R0(sp, first_yr);
2401 break;
2402
2403 case 1: // Random about mean with environmental effects
2404 R_hat(sp, first_yr) = R0(sp, first_yr);
2405 break;
2406
2407 case 2: // Beverton-Holt
2408 R_hat(sp, first_yr) = (alpha(sp, first_yr) - 1/SPRFinit(sp)) / Beta(sp, first_yr); // (Alpha-1/SPR0)/beta
2409 break;
2410
2411 case 3: // Retired alias of 2; build_srr() refuses it (alpha moves via a linkage)
2412 R_hat(sp, first_yr) = (alpha(sp, first_yr) - 1/SPRFinit(sp)) / Beta(sp, first_yr); // (Alpha-1/SPR0)/beta
2413 break;
2414
2415 case 4: // Ricker
2416 { Type aS = alpha(sp, first_yr) * SPRFinit(sp); // kept positive so the log is finite; R_hat itself is floored below
2417 if (rec_floor_on) { Type pen_d = 0; aS = posfun(aS, Type(1e-3), pen_d); }
2418 R_hat(sp, first_yr) = log(aS) / (Beta(sp, first_yr) * SPRFinit(sp)/1000000.0); }
2419 break;
2420
2421 case 5: // Ricker with environmental impacts on alpha
2422 { Type aS = alpha(sp, first_yr) * SPRFinit(sp); // kept positive so the log is finite; R_hat itself is floored below
2423 if (rec_floor_on) { Type pen_d = 0; aS = posfun(aS, Type(1e-3), pen_d); }
2424 R_hat(sp, first_yr) = log(aS) / (Beta(sp, first_yr) * SPRFinit(sp)/1000000.0); }
2425 break;
2426 default:
2427 error("Invalid 'srr_pred_fun'");
2428 }
2429 }
2430 // Same floor as R in 6.6.1: the first year's R_hat is reported and read by retrospective().
2431 if (rec_floor_on) { Type pen_R = 0; R_hat(sp, first_yr) = posfun(R_hat(sp, first_yr), Type(1e-3), pen_R); zero_N_pen(sp) += pen_R; }
2432
2433 // Year 1+
2434 for(yr = 1; yr < nyrs; yr++){
2435 // Pre-styr spawning year takes R_init, the SAME anchor the realised recruitment
2436 // above uses, so expected and realised differ only by rec_dev and the
2437 // stock-recruit penalty (13.9) scores the deviation alone -- these years have no
2438 // spawning biomass to carry information about the curve's level. Anchoring on the
2439 // curve instead (R_hat's own first year) leaves a mean-versus-curve level gap the
2440 // penalty reads as signal: under the Ianelli configuration (srr_fun mean,
2441 // srr_pred_fun BevertonHolt) a fixed 0.83 nats per guarded year, pulling rec_pars
2442 // against alpha and Beta from years with no data. Identical for
2443 // BevertonHolt/BevertonHolt and Ricker/Ricker, where R_init is already R_hat's
2444 // first-year value.
2445 int hat_spawn_yr = yr - minage(sp);
2446 int hat_srr_use = (hat_spawn_yr < 0) ? 0 : srr_pred_fun;
2447 Type ssb_tmp = (hat_spawn_yr < 0) ? Type(0.0) : ssb(sp, hat_spawn_yr);
2448 Type hat_rec_mean = (hat_spawn_yr < 0) ? R_init(sp) : R0(sp, yr);
2449
2450 // Expected recruitment carries no deviation, hence Type(0.0).
2451 R_hat(sp, yr) = calculate_recruitment(hat_srr_use, hat_rec_mean, ssb_tmp, alpha(sp, yr), Beta(sp, yr), Type(0.0), SPR0(sp));
2452 // Same floor as R in 6.6.1: log(R_hat) enters the stock-recruit penalty.
2453 if (rec_floor_on) { Type pen_R = 0; R_hat(sp, yr) = posfun(R_hat(sp, yr), Type(1e-3), pen_R); zero_N_pen(sp) += pen_R; }
2454 }
2455 }
2456
2457
2458
2459 // 6.11. ESTIMATE AVERAGE NUMBERS AT AGE
2460 for(sp = 0; sp < nspp; sp++) {
2461 for(sex = 0; sex < nsex(sp); sex ++){
2462 for(age = 0; age < nages(sp); age++) {
2463 for(yr = 0; yr < nyrs; yr++) {
2464 // MSVPA average N over the year.
2465 avgN_at_age(sp, sex, age, yr) = N_at_age(sp, sex, age, yr) * (1 - exp(-Z_at_age(sp, sex, age, yr))) / Z_at_age(sp, sex, age, yr);
2466 avgN_at_age_dB0(sp, sex, age, yr) = N_at_age_dB0(sp, sex, age, yr) * (1 - exp(-M_at_age_dB0(sp, sex, age, yr))) / M_at_age_dB0(sp, sex, age, yr);
2467 avgN_at_age_dBF(sp, sex, age, yr) = N_at_age_dBF(sp, sex, age, yr) * (1 - exp(-M_at_age_dBF(sp, sex, age, yr) - Ftarget_at_age(sp, sex, age, yr))) / (M_at_age_dBF(sp, sex, age, yr) + Ftarget_at_age(sp, sex, age, yr));
2468 }
2469 }
2470 }
2471 }
2472
2473
2474 /** ------------------------------------------------------------------------ //
2475 // 7. MSVPA PREDATION MORTALITY EQUATIONS //
2476 * ------------------------------------------------------------------------- */
2477
2478 // START PREDATION
2479 // Section 7's M2 feeds the next iteration's section 6; after the last iteration only REPORT()
2480 // and a fitted diet (diet_prop_hat) read this pass. A new reader after the loop goes in this test.
2481 const bool predation_needed = (iter < niter - 1) || diet_used;
2482 if((msmMode > 0) && predation_needed) {
2483
2484 // NOTE -- LOOPING INDICES -- sp = species, age = age, ln = length, ksp = prey, k_age = prey age (yr), k_ln = prey length, yr = year, rsp = predator, r_age = predator age (yr), r_ln = predator length
2485
2486 // 7.1. Empirical MSVPA Suitability
2487 calculate_msvpa_suitability(stom_div_bio, suitability, suit_other,
2488 nspp, nyrs, suit_styr, suit_endyr, nyrs_suit, msmMode,
2489 nsex, nages, suitMode, diet_prop, avgN_at_age, weight_hat, other_food_diet_prop);
2490
2491
2492 // 7.2. MSVPA PREDATION MORTALITY
2493 if((msmMode == 1) | (msmMode == 2)) {
2494 calculate_msvpa_predation(avail_food, avail_food_dB0, avail_food_dBF,
2495 M2_at_age, M2_at_age_dB0, M2_at_age_dBF, M2_prop,
2496 B_eaten, B_eaten_as_prey, diet_prop_hat, other_diet_prop_hat,
2497 nspp, nyrs, nsex, nages, msmMode,
2498 avgN_at_age, avgN_at_age_dB0, avgN_at_age_dBF,
2499 suitability, suit_other, weight_hat, consumption_at_age, other_food,
2500 reporting /* fill_report_only */, diet_used /* fill_diet */,
2501 dynamic_B0_used /* fill_dynamic_B0 */);
2502 }
2503 } // End 7. Predation mortality
2504 } // End population dynamics iterations
2505
2506
2507
2508 /** ------------------------------------------------------------------------ //
2509 // 8. INDEX COMPONENTS EQUATIONS //
2510 * ------------------------------------------------------------------------- */
2511
2512 // -- 8.1. Index of abundance/biomass
2513 for(index_ind = 0; index_ind < index_ctl.rows(); index_ind++){
2514
2515 index = index_ctl(index_ind, 0) - 1; // Survey index
2516 sp = index_ctl(index_ind, 1) - 1; // Species
2517 flt_yr = index_ctl(index_ind, 2); // Data year
2518 wt_idx_flt = nspp * 2 + index; // Fleet weight index
2519 mo = index_n(index_ind, 0); // Month
2520
2521 index_hat(index_ind) = 0.0;
2522
2523 if(flt_yr > 0){
2524 flt_yr = flt_yr - styr;
2525 }
2526 else if(flt_yr < 0){
2527 flt_yr = -flt_yr - styr;
2528 }
2529
2530 for(age = 0; age < nages(sp); age++) {
2531 for(sex = 0; sex < nsex(sp); sex++){
2532
2533 // Index by fleet type. Month is not used for a fishery: a year-average
2534 // has no instant to be taken at. SS3 splits the same way on its
2535 // per-fleet survey timing (SS_expval.tpl: timing >= 0 -> exp(-Z*timing);
2536 // timing < 0, required of every fishing fleet -> (1 - exp(-Z))/Z).
2537 //
2538 // A seasonal fishery takes the same form. Its exact predictor over [t1, t1+D] is
2539 // N_a * exp(-Zpre_a * t1) * (1 - exp(-Zwin_a * D)) / (Zwin_a * D)
2540 // Zpre_a = M_a + other fleets' F_a (this fishery has yet to fish)
2541 // Zwin_a = M_a + F_a/D + other fleets' F_a
2542 // Since Zwin*D = M*D + F, the window factor tracks F almost as the annual
2543 // one does, and q absorbs the F-free exp(-M*t1) offset. Trend error
2544 // against the exact form is ~1.5% over F 0.05-0.8, against -29% to +33%
2545 // for the snapshot. TODO: fit the window form directly if a fleet needs it.
2546 Type n_index;
2547 if(flt_type(index) == 1){
2548 n_index = N_at_age(sp, sex, age, flt_yr) * (1.0 - exp( - Z_at_age(sp, sex, age, flt_yr))) / Z_at_age(sp, sex, age, flt_yr);
2549 } else {
2550 n_index = N_at_age(sp, sex, age, flt_yr) * exp( - (mo/12.0) * Z_at_age(sp, sex, age, flt_yr));
2551 }
2552
2553 // Weight
2554 if(flt_units(index) == 1){
2555 index_hat(index_ind) += n_index * sel_at_age(index, sex, age, flt_yr) * weight_hat(wt_idx_flt, sex, age, flt_yr );
2556 }
2557 // Numbers
2558 if(flt_units(index) == 2){
2559 index_hat(index_ind) += n_index * sel_at_age(index, sex, age, flt_yr);
2560 }
2561 }
2562 }
2563 }
2564
2565
2566 // -- 8.2. Analytical survey q (lognormal form: Walters and Ludwig 1994)
2567 // The q that maximizes the fleet's index likelihood (13.1) given the other parameters and any
2568 // random effects; vignette("model-parameterizations") gives it for each Index_distribution.
2569 // index_q_analytical sums the numerator and index_n_obs the denominator (Lognormal, Normal);
2570 // MVN/MVNORM solve with Sigma below. data_check() refuses TruncatedNormal (no closed form).
2571 index_n_obs.setZero();
2572 index_q_analytical.setZero();
2573 for(index_ind = 0; index_ind < index_ctl.rows(); index_ind++){
2574 index = index_ctl(index_ind, 0) - 1; // Survey index
2575 flt_yr = index_ctl(index_ind, 2); // Data year
2576 // Only hindcast years with an observation, as 13.1 fits; a missing (NA) year fails the > 0 test
2577 if((flt_yr <= 0) || (flt_yr - styr >= nyrs_hind) || !(index_obs(index_ind, 0) > 0)) continue;
2578
2579 if(index_ll_type(index) == 3){ // Normal: sd is absolute, input by year or estimated
2580 Type sd2 = (est_sigma_index(index) == 0) ? square(index_obs(index_ind, 1)) : exp(2.0 * index_log_sd(index));
2581 index_n_obs(index) += square(index_hat(index_ind)) / sd2;
2582 index_q_analytical(index) += index_obs(index_ind, 0) * index_hat(index_ind) / sd2;
2583 continue;
2584 }
2585
2586 Type log_ratio = log(index_obs(index_ind, 0) / index_hat(index_ind));
2587 Type b = (index_ll_type(index) == 0) ? bias_adjust_obs : Type(0.0);
2588 switch(est_sigma_index(index)){
2589 case 0: // sd input by year: weight each year by 1 / sd^2
2590 index_n_obs(index) += 1 / square(index_obs(index_ind, 1));
2591 index_q_analytical(index) += log_ratio / square(index_obs(index_ind, 1)) + b / 2.0;
2592 break;
2593 case 1: // estimated sd
2594 index_n_obs(index) += 1;
2595 index_q_analytical(index) += log_ratio + b * exp(2.0 * index_log_sd(index)) / 2.0;
2596 break;
2597 case 2: // analytical sd: its bias term needs the mean, so is added below
2598 index_n_obs(index) += 1;
2599 index_q_analytical(index) += log_ratio;
2600 break;
2601 }
2602 }
2603 index_q_analytical = index_q_analytical / index_n_obs;
2604
2605 // Analytical sd: variance of the log residuals about their mean, so 8.4 returns the joint MLE
2606 vector<Type> index_q_resid_ss(n_flt); index_q_resid_ss.setZero();
2607 for(index_ind = 0; index_ind < index_ctl.rows(); index_ind++){
2608 index = index_ctl(index_ind, 0) - 1;
2609 flt_yr = index_ctl(index_ind, 2);
2610 if((flt_yr <= 0) || (flt_yr - styr >= nyrs_hind) || !(index_obs(index_ind, 0) > 0) ||
2611 (est_sigma_index(index) != 2)) continue;
2612 index_q_resid_ss(index) += square(log(index_obs(index_ind, 0) / index_hat(index_ind)) - index_q_analytical(index));
2613 }
2614
2615 for(index = 0 ; index < n_flt; index ++){
2616 if((est_sigma_index(index) == 2) && (index_ll_type(index) == 0)){
2617 index_q_analytical(index) += bias_adjust_obs * index_q_resid_ss(index) / index_n_obs(index) / 2.0;
2618 }
2619 if(index_ll_type(index) != 3) index_q_analytical(index) = exp(index_q_analytical(index));
2620
2621 // MVN / MVNORM: the fitted rows in index_obs order, which is the row order of Sigma (13.1)
2622 if((est_index_q(index) == 3) && (flt_type(index) > 0) &&
2623 ((index_ll_type(index) == 1) || (index_ll_type(index) == 2))){
2624 int n_mvn = 0;
2625 for(index_ind = 0; index_ind < index_ctl.rows(); index_ind++){
2626 flt_yr = index_ctl(index_ind, 2);
2627 if(((index_ctl(index_ind, 0) - 1) == index) && (flt_yr > 0) && (flt_yr <= endyr) &&
2628 (index_obs(index_ind, 0) > 0)) n_mvn++;
2629 }
2630 if(n_mvn > 0){
2631 matrix<Type> mvn_obs(n_mvn, 1), mvn_pred(n_mvn, 1);
2632 int k = 0;
2633 for(index_ind = 0; index_ind < index_ctl.rows(); index_ind++){
2634 flt_yr = index_ctl(index_ind, 2);
2635 if(((index_ctl(index_ind, 0) - 1) == index) && (flt_yr > 0) && (flt_yr <= endyr) &&
2636 (index_obs(index_ind, 0) > 0)){
2637 mvn_obs(k, 0) = index_obs(index_ind, 0);
2638 mvn_pred(k, 0) = index_hat(index_ind);
2639 k++;
2640 }
2641 }
2642 Eigen::LLT<Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> > llt(index_cov_mat(index));
2643 matrix<Type> w = llt.solve(mvn_pred); // Sigma^-1 pred
2644 index_q_analytical(index) = (w.transpose() * mvn_obs)(0, 0) / (w.transpose() * mvn_pred)(0, 0);
2645 }
2646 }
2647
2648 // Set index_q to analytical if used
2649 if(est_index_q(index) == 3){
2650 for(yr = 0; yr < nyrs_hind; yr++){
2651 index_q(index, yr) = index_q_analytical(index);
2652 }
2653 }
2654 }
2655
2656
2657 // -- 8.2b. Arithmetic-mean analytical q (AMAK/ebswp): q = sum(obs)/sum(pred)
2658 // over the fitted survey years (est_index_q == 7, "AnalyticalArith"). This
2659 // reproduces the AMAK BTS q_bts = mean(ob_bts)/mean(eb_bts) and is the q
2660 // form paired with the MVN covariance survey likelihood (Index_loglike =
2661 // "MVN"). Uses index_hat before it is scaled by q just below.
2662 vector<Type> index_obs_sum(n_flt); index_obs_sum.setZero();
2663 vector<Type> index_hat_sum(n_flt); index_hat_sum.setZero();
2664 for(index_ind = 0; index_ind < index_ctl.rows(); index_ind++){
2665 index = index_ctl(index_ind, 0) - 1;
2666 flt_yr = index_ctl(index_ind, 2);
2667 if(flt_yr > 0){
2668 flt_yr = flt_yr - styr;
2669 if((flt_yr < nyrs_hind) && (index_obs(index_ind, 0) > 0)){ // a missing (NA) year compares false
2670 index_obs_sum(index) += index_obs(index_ind, 0);
2671 index_hat_sum(index) += index_hat(index_ind);
2672 }
2673 }
2674 }
2675 for(index = 0; index < n_flt; index++){
2676 if(est_index_q(index) == 7){
2677 Type q_arith = index_obs_sum(index) / index_hat_sum(index);
2678 for(yr = 0; yr < nyrs_hind; yr++){
2679 index_q(index, yr) = q_arith;
2680 }
2681 }
2682 }
2683
2684
2685 // -- 8.3. Survey Biomass - multiply by q
2686 for(index_ind = 0; index_ind < index_ctl.rows(); index_ind++){
2687
2688 index = index_ctl(index_ind, 0) - 1; // Survey index
2689 flt_yr = index_ctl(index_ind, 2); // Data year
2690
2691 if(flt_yr > 0){
2692 flt_yr = flt_yr - styr;
2693 }
2694 else if(flt_yr < 0){
2695 flt_yr = -flt_yr - styr;
2696 }
2697
2698 // Hindcast or projection indexing for q
2699 int yr_ind = (flt_yr < nyrs_hind) ? flt_yr : (nyrs_hind - 1);
2700
2701 index_hat(index_ind) = index_q(index, yr_ind) * index_hat(index_ind); // pow(index_hat(index_ind), (1 + index_q_pow(index)));
2702 }
2703
2704
2705
2706 // --8.4. Calculate analytical sigma following Walters and Ludwig 1994
2707 // Only hindcast years with an observation; a missing (NA) year fails the > 0 test,
2708 // as in 8.2 and the catch estimator.
2709 index_n_obs.setZero();
2710 index_analytical_sd.setZero();
2711 for(index_ind = 0; index_ind < index_ctl.rows(); index_ind++){
2712
2713 index = index_ctl(index_ind, 0) - 1; // Survey index
2714 flt_yr = index_ctl(index_ind, 2); // Data year
2715
2716 if(flt_yr > 0){
2717 flt_yr = flt_yr - styr;
2718
2719 if((flt_yr < nyrs_hind) && (index_obs(index_ind, 0) > 0)){
2720 index_n_obs(index) += 1;
2721 index_analytical_sd(index) += square( log(index_obs(index_ind, 0)) - log(index_hat(index_ind)));
2722 }
2723 }
2724 }
2725
2726 for(index = 0 ; index < n_flt; index ++){
2727 if(index_n_obs(index) > 0){
2728 index_analytical_sd(index) = concentrated_lognormal_sd(index_analytical_sd(index) / index_n_obs(index), bias_adjust_obs);
2729 }
2730 }
2731
2732
2733 /** ------------------------------------------------------------------------ //
2734 // 9. FISHERY COMPONENTS EQUATIONS //
2735 * ------------------------------------------------------------------------- */
2736 // 9.1. ESTIMATE CATCH-AT-AGE and TOTAL YIELD (mt or thousands of fish)
2737 for(fsh_ind = 0; fsh_ind < catch_ctl.rows(); fsh_ind++){
2738
2739 flt = catch_ctl(fsh_ind, 0) - 1; // Fleet index (0-based)
2740 sp = catch_ctl(fsh_ind, 1) - 1; // Species
2741 flt_yr = catch_ctl(fsh_ind, 2); // Data year
2742 mo = catch_n(fsh_ind, 0); // Month
2743 wt_idx_flt = nspp * 2 + flt; // Weight index for fleet
2744
2745 catch_hat(fsh_ind) = 0.0;
2746 max_catch_hat(fsh_ind) = 0.0;
2747
2748 if(flt_yr > 0){
2749 flt_yr = flt_yr - styr;
2750 }
2751 else if(flt_yr < 0){
2752 flt_yr = -flt_yr - styr;
2753 }
2754
2755 for(sex = 0; sex < nsex(sp); sex ++){
2756 for(age = 0; age < nages(sp); age++) {
2757
2758 // By weight
2759 if(flt_units(flt) == 1){
2760 catch_hat(fsh_ind) += F_flt_age(flt, sex, age, flt_yr) / Z_at_age(sp, sex, age, flt_yr) * (1.0 - exp(-Z_at_age(sp, sex, age, flt_yr))) * N_at_age(sp, sex, age, flt_yr) * weight_hat( wt_idx_flt, sex, age, flt_yr ); // 5.5.
2761 max_catch_hat(fsh_ind) += N_at_age(sp, sex, age, flt_yr) * weight_hat( wt_idx_flt, sex, age, flt_yr ) * sel_at_age(flt, sex, age, flt_yr) * proj_F_prop(flt);
2762 }
2763
2764 // By numbers
2765 if(flt_units(flt) == 2){
2766 catch_hat(fsh_ind) += F_flt_age(flt, sex, age, flt_yr) / Z_at_age(sp, sex, age, flt_yr) * (1.0 - exp(-Z_at_age(sp, sex, age, flt_yr))) * N_at_age(sp, sex, age, flt_yr);
2767 max_catch_hat(fsh_ind) += N_at_age(sp, sex, age, flt_yr) * sel_at_age(flt, sex, age, flt_yr) * proj_F_prop(flt);
2768 }
2769 }
2770 }
2771 }
2772
2773 // -- 9.1a. Initial equilibrium catch, in weight or numbers per the fleet's
2774 // Observation_units, as catch_hat is:
2775 // C_eq = sum_a Finit * s_a * w_a * N_eq_a * (1 - exp(-Z_a)) / Z_a
2776 // Z_a = M1_a + Finit * s_a
2777 // Baranov on the deviation-free equilibrium age structure, at the fleet's own
2778 // selectivity and weight in the first hindcast year; SS3's Equil_catch
2779 // (SS_popdyn.tpl, Do_Equil_Calc). R supplies these rows only under initMode 6,
2780 // the one mode that builds N_eq at this same Finit * selectivity.
2781 vector<Type> equil_catch_hat(equil_catch_ctl.rows()); equil_catch_hat.setZero();
2782 for(int eq_ind = 0; eq_ind < equil_catch_ctl.rows(); eq_ind++){
2783 flt = equil_catch_ctl(eq_ind, 0) - 1;
2784 sp = equil_catch_ctl(eq_ind, 1) - 1;
2785 wt_idx_flt = nspp * 2 + flt;
2786 for(sex = 0; sex < nsex(sp); sex++){
2787 for(age = 0; age < nages(sp); age++){
2788 Type s_a = sel_at_age(flt, sex, age, 0);
2789 Type Z_a = M1_at_age(sp, sex, age, 0) + Finit(sp) * s_a;
2790 Type baranov = Finit(sp) * s_a / Z_a * (1.0 - exp(-Z_a)) * N_eq(sp, sex, age);
2791 if(flt_units(flt) == 1){ // by weight
2792 equil_catch_hat(eq_ind) += baranov * weight_hat( wt_idx_flt, sex, age, 0 );
2793 }
2794 if(flt_units(flt) == 2){ // by numbers
2795 equil_catch_hat(eq_ind) += baranov;
2796 }
2797 }
2798 }
2799 }
2800
2801 // -- 9.1b. Analytical catch sigma, following Walters and Ludwig (1994)
2802 // The sd that minimises the catch density: squared log residuals accumulated
2803 // here, concentrated in concentrated_lognormal_sd(). The row predicate matches
2804 // the likelihood's own -- a fitted year, a fishery, a positive observation --
2805 // so the sd is estimated over exactly the rows it is applied to. A zero-catch
2806 // year is legal input and log(0) is -inf, which would poison the fleet's sd,
2807 // hence the positive-observation guard.
2808 //
2809 // It reads catch_obs, not obsvec, so oneStepPredict()'s candidate value never
2810 // reaches it: the sd enters an OSA sweep as a fixed full-data number, as an
2811 // estimated sd held at its MLE would.
2812 catch_n_obs.setZero();
2813 catch_analytical_sd.setZero();
2814 for(fsh_ind = 0; fsh_ind < catch_ctl.rows(); fsh_ind++){
2815
2816 flt = catch_ctl(fsh_ind, 0) - 1;
2817 flt_yr = catch_ctl(fsh_ind, 2);
2818
2819 if((flt_yr > 0) && (flt_yr <= endyr) && (flt_type(flt) == 1) && (catch_obs(fsh_ind, 0) > 0)){
2820 catch_n_obs(flt) += 1;
2821 catch_analytical_sd(flt) += square( log(catch_obs(fsh_ind, 0)) - log(catch_hat(fsh_ind)) );
2822 }
2823 }
2824
2825 for(flt = 0; flt < n_flt; flt++){
2826 if(catch_n_obs(flt) > 0){
2827 catch_analytical_sd(flt) = concentrated_lognormal_sd(catch_analytical_sd(flt) / catch_n_obs(flt), bias_adjust_obs);
2828 }
2829 }
2830
2831
2832 // 9.2 Exploitable biomass ----
2833 exploitable_biomass.setZero();
2834
2835 for(flt = 0; flt < n_flt; flt++) {
2836
2837 sp = flt_spp(flt);
2838 wt_idx_flt = nspp * 2 + flt;
2839
2840 if(flt_type(flt) == 1){ //Fishery only
2841 for(yr = 0; yr < nyrs; yr++) {
2842 for(age = 0; age < nages(sp); age++) {
2843 for(sex = 0; sex < nsex(sp); sex ++){
2844 exploitable_biomass(sp, yr) += N_at_age(sp, sex, age, yr) * weight_hat( wt_idx_flt, sex, age, yr ) * sel_at_age(flt, sex, age, yr) * proj_F_prop(flt);
2845 }
2846 }
2847 }
2848 }
2849 }
2850
2851
2852 /** ------------------------------------------------------------------------ //
2853 * 10. COMPOSITION EQUATIONS //
2854 * ------------------------------------------------------------------------- */
2855
2856 // -- 10.1. Marginal age/length composition
2857 age_hat.setZero(); // Age-composition
2858 age_obs_hat.setZero(); // Age-composition with ageing error
2859 comp_hat.setZero(); // Age- or length-comp following data
2860 for(comp_ind = 0; comp_ind < comp_hat.rows(); comp_ind++){
2861
2862 flt = comp_ctl(comp_ind, 0) - 1; // Fleet index (0-based)
2863 sp = comp_ctl(comp_ind, 1) - 1; // Species
2864 flt_sex = comp_ctl(comp_ind, 2); // Comp sex: 0 = combined, 1 = female, 2 = male
2865 comp_type = comp_ctl(comp_ind, 3); // Comp type: 0 = age, 1 = length, 2 = CAAL
2866 yr = comp_ctl(comp_ind, 4); // Data year
2867 mo = (growth_model(sp) > 0) ? flt_month(flt) : comp_n(comp_ind, 0); // Month (use fleet month if estimating growth, otherwise use from data)
2868 int wtind = nspp * 2 + flt;
2869 n_hat(comp_ind) = 0.0;
2870
2871 // Likelihood (yr > 0) vs prediction (yr < 0)
2872 if(yr > 0){
2873 yr = yr - styr;
2874 }
2875 else if(yr < 0){
2876 yr = -yr - styr;
2877 }
2878
2879 // Hindcast
2880 Type Frate = 0.0;
2881 if(yr < nyrs_hind){
2882 yr_ind = yr;
2883 Frate = exp(log_F(flt, yr));
2884 }
2885
2886 // Projection
2887 if(yr >= nyrs_hind){
2888 yr_ind = nyrs_hind - 1;
2889 Frate = proj_F_prop(flt) * proj_F(sp, yr);
2890 }
2891
2892 // 10.1.1. Estimated growth
2893 if(growth_model(sp) > 0){
2894 for(age = 0; age < nages(sp); age++) {
2895 for(ln = 0; ln < nlengths(sp); ln++) {
2896 for(sex = 0; sex < nsex(sp); sex ++){
2897
2898 switch(flt_type(flt)){
2899 case 1: // - Fishery
2900 if(flt_sel_dim(flt) == 1){ // Length based
2901 {
2902 // sel(L) * P(L|age) over this data bin's population bins (2.3c).
2903 Type ps_ln = 0.0;
2904 for(int lp = pop_bin_lo(sp, ln); lp <= pop_bin_hi(sp, ln); lp++){
2905 ps_ln += sel_at_length(flt, sex, lp, yr) * growth_matrix(wtind, sex, age, lp, yr);
2906 }
2907 pred_CAAL(flt, sex, age, ln, yr) = ps_ln * (Frate / Z_at_age(sp, sex, age, yr) * (1 - exp(-Z_at_age(sp, sex, age, yr))) * N_at_age(sp, sex, age, yr));
2908 }
2909 }
2910 break;
2911
2912
2913 case 2: // - Survey
2914 if(flt_sel_dim(flt) == 1){ // Length based
2915 {
2916 // sel(L) * P(L|age) over this data bin's population bins (2.3c).
2917 Type ps_ln = 0.0;
2918 for(int lp = pop_bin_lo(sp, ln); lp <= pop_bin_hi(sp, ln); lp++){
2919 ps_ln += sel_at_length(flt, sex, lp, yr) * growth_matrix(wtind, sex, age, lp, yr);
2920 }
2921 pred_CAAL(flt, sex, age, ln, yr) = ps_ln * (N_at_age(sp, sex, age, yr) * index_q(flt, yr_ind) * exp( - Type(mo/12.0) * Z_at_age(sp, sex, age, yr)));
2922 }
2923 }
2924 break;
2925 }
2926 // Comps read this, not pred_CAAL, which CAAL reads and stays length-based. A fleet with
2927 // selectivity at age (Fixed is always at age) has no sel(L), so sel(a) weights P(L|age).
2928 comp_pred(sex, age, ln) = pred_CAAL(flt, sex, age, ln, yr);
2929 if(flt_sel_dim(flt) != 1 || flt_sel_type(flt) == 0){
2930 Type p_ln = 0.0;
2931 for(int lp = pop_bin_lo(sp, ln); lp <= pop_bin_hi(sp, ln); lp++){
2932 p_ln += growth_matrix(wtind, sex, age, lp, yr);
2933 }
2934 switch(flt_type(flt)){
2935 case 1: // - Fishery
2936 comp_pred(sex, age, ln) = p_ln * (F_flt_age(flt, sex, age, yr) / Z_at_age(sp, sex, age, yr) * (1 - exp(-Z_at_age(sp, sex, age, yr))) * N_at_age(sp, sex, age, yr));
2937 break;
2938
2939 case 2: // - Survey
2940 comp_pred(sex, age, ln) = p_ln * (N_at_age(sp, sex, age, yr) * sel_at_age(flt, sex, age, yr) * index_q(flt, yr_ind) * exp( - Type(mo/12.0) * Z_at_age(sp, sex, age, yr)));
2941 break;
2942 }
2943 }
2944 }
2945 }
2946 }
2947
2948 // Sum predicted numbers at age and length into the marginal age or length composition
2949 for(age = 0; age < nages(sp); age++) {
2950 for(ln = 0; ln < nlengths(sp); ln++) {
2951
2952 // Age composition
2953 // - Catch-at-age
2954 if(comp_type == 0){
2955 switch(flt_sex){
2956 case 0: // Sexes combined or 1 sex assessment
2957 for(sex = 0; sex < nsex(sp); sex ++){
2958 age_hat(comp_ind, age ) += comp_pred(sex, age, ln);
2959 }
2960 break;
2961
2962 case 1: case 2: // Sex-specific composition data
2963 sex = flt_sex - 1;
2964 age_hat(comp_ind, age ) += comp_pred(sex, age, ln);
2965 break;
2966
2967 case 3: // Joint composition data
2968 for(sex = 0; sex < nsex(sp); sex ++){
2969 age_hat(comp_ind, age + nages(sp) * sex ) += comp_pred(sex, age, ln);
2970 }
2971 break;
2972 }
2973 }
2974
2975
2976 // Length composition
2977 // - Catch-at-length
2978 if(comp_type == 1){
2979 switch(flt_sex){
2980 case 0: // Sexes combined or 1 sex assessment
2981 for(sex = 0; sex < nsex(sp); sex ++){
2982 comp_hat(comp_ind, ln ) += comp_pred(sex, age, ln);
2983 }
2984 break;
2985
2986 case 1: case 2: // Sex-specific composition data
2987 sex = flt_sex - 1;
2988 comp_hat(comp_ind, ln ) += comp_pred(sex, age, ln);
2989 break;
2990
2991 case 3: // Joint composition data
2992 for(sex = 0; sex < nsex(sp); sex ++){
2993 comp_hat(comp_ind, ln + nlengths(sp) * sex ) += comp_pred(sex, age, ln) ;
2994 }
2995 break;
2996 }
2997 }
2998 }
2999 }
3000
3001 // Adjust for aging error
3002 for(int obs_age = 0; obs_age < nages(sp); obs_age++) {
3003 for(int true_age = 0; true_age < nages(sp); true_age++) {
3004 age_obs_hat(comp_ind, obs_age) += age_hat(comp_ind, true_age ) * age_error(flt_ageing_error_index(flt), true_age, obs_age);
3005 }
3006 }
3007
3008 // Adjust for aging error for joint data
3009 if(flt_sex == 3){
3010 for(int obs_age = nages(sp); obs_age < nages(sp) * 2; obs_age++) {
3011 for(int true_age = nages(sp); true_age < nages(sp) * 2; true_age++) {
3012
3013 // Adjust indexing for joint age/length comp
3014 int true_age_tmp = true_age - nages(sp);
3015 int obs_age_tmp = obs_age - nages(sp);
3016
3017 age_obs_hat(comp_ind, obs_age) += age_hat(comp_ind, true_age ) * age_error(flt_ageing_error_index(flt), true_age_tmp, obs_age_tmp);
3018 }
3019 }
3020 }
3021
3022 // Assign age-comp to estimated comp
3023 if( comp_type == 0) {
3024 joint_adjust(comp_ind) = 1;
3025 if(flt_sex == 3){
3026 joint_adjust(comp_ind) = 2;
3027 }
3028 for(age = 0; age < nages(sp) * joint_adjust(comp_ind); age++) {
3029 comp_hat(comp_ind, age ) = age_obs_hat(comp_ind, age );
3030 }
3031 }
3032 } // End estimated growth loop
3033
3034
3035 // 10.1.2. Empirical weight-at-age
3036 if(growth_model(sp) == 0){
3037 for(age = 0; age < nages(sp); age++) {
3038
3039 switch(flt_type(flt)){
3040 case 1: // - Fishery
3041 switch(flt_sex){
3042 case 0: // Sexes combined or 1 sex assessment
3043 for(sex = 0; sex < nsex(sp); sex ++){
3044 // Catch-at-age
3045 age_hat(comp_ind, age ) += F_flt_age(flt, sex, age, yr) / Z_at_age(sp, sex, age, yr) * (1 - exp(-Z_at_age(sp, sex, age, yr))) * N_at_age(sp, sex, age, yr);
3046 }
3047 break;
3048
3049 case 1: case 2: // Sex-specific composition data
3050 sex = flt_sex - 1;
3051 // Catch-at-age
3052 age_hat(comp_ind, age ) = F_flt_age(flt, sex, age, yr) / Z_at_age(sp, sex, age, yr) * (1 - exp(-Z_at_age(sp, sex, age, yr))) * N_at_age(sp, sex, age, yr);
3053 break;
3054
3055 case 3: // Joint composition data
3056 for(sex = 0; sex < nsex(sp); sex ++){
3057 // Catch-at-age
3058 age_hat(comp_ind, age + nages(sp) * sex ) = F_flt_age(flt, sex, age, yr) / Z_at_age(sp, sex, age, yr) * (1 - exp(-Z_at_age(sp, sex, age, yr))) * N_at_age(sp, sex, age, yr);
3059 }
3060 break;
3061 }
3062 break;
3063
3064
3065 case 2: // - Survey
3066 switch(flt_sex){
3067 case 0: // Sexes combined or 1 sex assessment
3068 for(sex = 0; sex < nsex(sp); sex ++){
3069 // Survey catch-at-age
3070 age_hat(comp_ind, age ) += N_at_age(sp, sex, age, yr) * sel_at_age(flt, sex, age, yr) * index_q(flt, yr_ind) * exp( - Type(mo/12.0) * Z_at_age(sp, sex, age, yr));
3071 }
3072 break;
3073
3074 case 1: case 2: // Sex-specific composition data
3075 sex = flt_sex - 1;
3076 // Survey catch-at-age
3077 age_hat(comp_ind, age ) = N_at_age(sp, sex, age, yr) * sel_at_age(flt, sex, age, yr) * index_q(flt, yr_ind) * exp( - Type(mo/12.0) * Z_at_age(sp, sex, age, yr));
3078 break;
3079
3080 case 3: // Joint composition data
3081 for(sex = 0; sex < nsex(sp); sex ++){
3082 // Survey catch-at-age
3083 age_hat(comp_ind, age + nages(sp) * sex ) = N_at_age(sp, sex, age, yr) * sel_at_age(flt, sex, age, yr) * index_q(flt, yr_ind) * exp( - Type(mo/12.0) * Z_at_age(sp, sex, age, yr));
3084 }
3085 break;
3086 }
3087 }
3088 }
3089
3090
3091 // Adjust for aging error
3092 for(int obs_age = 0; obs_age < nages(sp); obs_age++) {
3093 for(int true_age = 0; true_age < nages(sp); true_age++) {
3094 age_obs_hat(comp_ind, obs_age) += age_hat(comp_ind, true_age ) * age_error(flt_ageing_error_index(flt), true_age, obs_age);
3095 }
3096 }
3097
3098 // Adjust for aging error for joint data
3099 if(flt_sex == 3){
3100 for(int obs_age = nages(sp); obs_age < nages(sp) * 2; obs_age++) {
3101 for(int true_age = nages(sp); true_age < nages(sp) * 2; true_age++) {
3102
3103 // Adjust indexing for joint age/length comp
3104 int true_age_tmp = true_age - nages(sp);
3105 int obs_age_tmp = obs_age - nages(sp);
3106
3107 age_obs_hat(comp_ind, obs_age) += age_hat(comp_ind, true_age ) * age_error(flt_ageing_error_index(flt), true_age_tmp, obs_age_tmp);
3108 }
3109 }
3110 }
3111
3112 // Assign age-comp to estimated comp
3113 if( comp_type == 0) {
3114 joint_adjust(comp_ind) = 1;
3115 if(flt_sex == 3){
3116 joint_adjust(comp_ind) = 2;
3117 }
3118 for(age = 0; age < nages(sp) * joint_adjust(comp_ind); age++) {
3119 comp_hat(comp_ind, age ) = age_obs_hat(comp_ind, age );
3120 }
3121 }
3122
3123 // Convert from catch-at-age to catch-at-length, reading age_hat, the TRUE ages, not
3124 // age_obs_hat: the age-length key is P(length | true age), and a measured length
3125 // carries no otolith reading, so ageing error has no part in a length composition.
3126 // SS3 likewise applies its age_age matrix only to age and CAAL data.
3127 if( comp_type == 1) {
3128 for(ln = 0; ln < nlengths(sp); ln++) {
3129 for(age = 0; age < nages(sp); age++) {
3130
3131 sex = 0;
3132
3133 // Adjust sex for males/females
3134 if((flt_sex > 0) & (flt_sex < 3)){
3135 sex = flt_sex - 1;
3136 }
3137 comp_hat(comp_ind, ln ) += age_hat(comp_ind, age) * age_trans_matrix(flt_age_transition_index(flt), sex, age, ln );
3138 }
3139 }
3140
3141
3142 // Convert from catch-at-age to catch-at-length for joint comp data
3143 if( flt_sex == 3) {
3144 for(ln = nlengths(sp); ln < nlengths(sp) * 2; ln++) {
3145 for(age = nages(sp); age < nages(sp) * 2; age++) {
3146
3147 // Adjust indexing for joint age/length comp
3148 int obs_log_tmp = ln;
3149 int obs_age_tmp = age;
3150
3151 obs_age_tmp = age - nages(sp);
3152 obs_log_tmp = ln - nlengths(sp);
3153 sex = 1;
3154
3155 comp_hat(comp_ind, ln ) += age_hat(comp_ind, age) * age_trans_matrix(flt_age_transition_index(flt), sex, obs_age_tmp, obs_log_tmp );
3156 }
3157 }
3158 }
3159 }
3160 } // End empirical weight-at-age loop
3161
3162 // Standardize to sum to 1
3163 Type penalty = 0.0;
3164 comp_hat.row(comp_ind) /= posfun(comp_hat.row(comp_ind).sum(), Type(0.001), penalty);
3165 (void) penalty;
3166 }
3167
3168
3169 // -- 10.2. CAAL
3170 // -- length-based selectivity was converted above
3171 caal_hat.setZero();
3172 for(int caal_ind = 0; caal_ind < caal_hat.rows(); caal_ind++){
3173
3174 flt = caal_ctl(caal_ind, 0) - 1; // Fleet index (0-based)
3175 sp = caal_ctl(caal_ind, 1) - 1; // Species
3176 flt_sex = caal_ctl(caal_ind, 2); // CAAL sex: 0 = combined, 1 = female, 2 = male
3177 yr = caal_ctl(caal_ind, 3); // Data year
3178 ln = caal_ctl(caal_ind, 4) - 1; // Length bin
3179 mo = flt_month(flt); // Month (use fleet month b/c estimating growth)
3180
3181 if(growth_model(sp) == 0) continue; // Skip empirical weight-at-age species
3182
3183 if(flt_sex > 0){
3184 sex = flt_sex - 1;
3185 } else {
3186 sex = flt_sex;
3187 }
3188
3189 int wtind = nspp * 2 + flt;
3190
3191 // Likelihood (yr > 0) vs prediction (yr < 0)
3192 if(yr > 0){
3193 yr = yr - styr;
3194 }
3195 else if(yr < 0){
3196 yr = -yr - styr;
3197 }
3198 // Hindcast
3199 Type Frate = 0.0;
3200 if(yr < nyrs_hind){
3201 yr_ind = yr;
3202 Frate = exp(log_F(flt, yr));
3203 }
3204
3205 // Projection
3206 if(yr >= nyrs_hind){
3207 yr_ind = nyrs_hind - 1;
3208 Frate = proj_F_prop(flt) * proj_F(sp, yr);
3209 }
3210
3211 // 10.2. Calculate CAAL (predicted conditional age-at-length)
3212 for(age = 0; age < nages(sp); age++) {
3213
3214 switch(flt_type(flt)){
3215 case 1: // - Fishery
3216 if(flt_sel_dim(flt) == 1){
3217 {
3218 // sel(L) * P(L|age) over this data bin's population bins (2.3c).
3219 Type ps_ln = 0.0;
3220 for(int lp = pop_bin_lo(sp, ln); lp <= pop_bin_hi(sp, ln); lp++){
3221 ps_ln += sel_at_length(flt, sex, lp, yr) * growth_matrix(wtind, sex, age, lp, yr);
3222 }
3223 pred_CAAL(flt, sex, age, ln, yr) = ps_ln * (Frate / Z_at_age(sp, sex, age, yr) * (1 - exp(-Z_at_age(sp, sex, age, yr))) * N_at_age(sp, sex, age, yr));
3224 }
3225 }
3226 break;
3227
3228
3229 case 2: // - Survey
3230 if(flt_sel_dim(flt) == 1){
3231 {
3232 // sel(L) * P(L|age) over this data bin's population bins (2.3c).
3233 Type ps_ln = 0.0;
3234 for(int lp = pop_bin_lo(sp, ln); lp <= pop_bin_hi(sp, ln); lp++){
3235 ps_ln += sel_at_length(flt, sex, lp, yr) * growth_matrix(wtind, sex, age, lp, yr);
3236 }
3237 pred_CAAL(flt, sex, age, ln, yr) = ps_ln * (N_at_age(sp, sex, age, yr) * index_q(flt, yr_ind) * exp( - Type(mo/12.0) * Z_at_age(sp, sex, age, yr)) );
3238 }
3239 }
3240 break;
3241 }
3242 }
3243
3244 // Adjust for aging error
3245 for(int obs_age = 0; obs_age < nages(sp); obs_age++) {
3246 for(int true_age = 0; true_age < nages(sp); true_age++) {
3247 caal_hat(caal_ind, obs_age) += pred_CAAL(flt, sex, true_age, ln, yr) * age_error(flt_ageing_error_index(flt), true_age, obs_age);
3248 }
3249 }
3250
3251 // Observed CAAL standardize to sum to 1
3252 Type penalty = 0.0;
3253 caal_hat.row(caal_ind) /= posfun(caal_hat.row(caal_ind).sum(), Type(0.0001), penalty);
3254 (void) penalty;
3255 }
3256
3257
3258
3259 /** ------------------------------------------------------------------------ //
3260 * 11. PREDICTED STOMACH CONTENT //
3261 * ------------------------------------------------------------------------- */
3262
3263 // Predict stomach content
3264 if(diet_fitted) {
3265 predict_stomach_content(nspp, nyrs_hind, styr, suit_styr, suit_endyr,
3266 minage, nsex, nages, diet_obs, diet_ctl,
3267 avgN_at_age, diet_prop_hat, diet_hat);
3268 }
3269
3270
3271 /** ------------------------------------------------------------------------ //
3272 // 12. DERIVED QUANTITIES
3273 * ------------------------------------------------------------------------- */
3274
3275
3276 // 12.1. Depletion
3277 biomass_depletion.setZero();
3278 ssb_depletion.setZero();
3279 for(sp = 0; sp < nspp; sp++){
3280 for(yr = 0; yr < nyrs; yr++){
3281
3282 if(DynamicHCR == 0){
3283 biomass_depletion(sp, yr) = biomass(sp, yr)/B0(sp, nyrs-1);
3284 ssb_depletion(sp, yr) = ssb(sp, yr)/SB0(sp, nyrs-1);
3285 }
3286
3287 if(DynamicHCR == 1){
3288 biomass_depletion(sp, yr) = biomass(sp, yr)/DynamicB0(sp, yr);
3289 ssb_depletion(sp, yr) = ssb(sp, yr)/DynamicSB0(sp, yr);
3290 }
3291
3292 // Multi-species, no HCR: the projection runs unfished, so SSB in the last
3293 // projection year is multispecies SB0 once `projyr` is far enough out to
3294 // equilibrate. Excluded under DynamicHCR, where DynamicSB0 is the
3295 // reference and this would overwrite it.
3296 if((HCR == 0) & (msmMode > 0) & (DynamicHCR == 0)){
3297 biomass_depletion(sp, yr) = biomass(sp, yr)/biomass(sp, nyrs-1);
3298 ssb_depletion(sp, yr) = ssb(sp, yr)/ssb(sp, nyrs-1);
3299 }
3300 }
3301 }
3302
3303
3304
3305
3306 /** ------------------------------------------------------------------------ //
3307 // 13. LIKELIHOOD EQUATIONS
3308 * ------------------------------------------------------------------------- */
3309
3310 // 13.0. OBJECTIVE FUNCTION
3311 // Data likelihoods come first (13.1-13.6), then priors and penalties (13.7-13.14).
3312 // Each SIMULATE block sits beside the density it draws from, in the same order,
3313 // so sim_mod() draws what the likelihood scores.
3314 // dnorm(..., true) and similar return a log density, which is subtracted; TMB's
3315 // MVNORM, AR1, SEPARABLE and GMRF return a negative log density, which is added.
3316 // Data terms read observations from obsvec, gated by keep so oneStepPredict() can
3317 // hold each one out for OSA residuals; in ordinary fitting keep = 1.
3318 int n_col = std::max(n_flt, nspp);
3319 // Rows of jnll_comp. Keep in sync with the row names in R/6-rename_output.R and
3320 // .JNLL_ROW_AXIS in R/9-profile.R; test-schema-jnll-rows.R checks all three.
3321 enum JnllRow {
3322 JNLL_INDEX = 0, // Index data
3323 JNLL_CATCH = 1, // Catch data
3324 JNLL_COMP = 2, // Composition data
3325 JNLL_CAAL = 3, // CAAL data
3326 JNLL_SEL_NONPARAM = 4, // Non-parametric selectivity
3327 JNLL_SEL_DEV = 5, // Selectivity deviates
3328 JNLL_Q_PRIOR = 6, // Catchability prior
3329 JNLL_Q_DEV = 7, // Catchability deviates
3330 JNLL_SRR_PRIOR = 8, // Stock-recruit prior
3331 JNLL_INIT_DEV = 9, // Initial abundance deviates
3332 JNLL_REC_DEV = 10, // Recruitment deviates
3333 JNLL_SRR_PENALTY = 11, // Stock-recruit penalty
3334 JNLL_REFPT_PENALTY = 12, // Reference point penalties
3335 JNLL_ZERO_N_PENALTY = 13, // Zero n-at-age penalty
3336 JNLL_M_PRIOR = 14, // M prior
3337 JNLL_M_RE = 15, // M random effects
3338 JNLL_RATION = 16, // Ration
3339 JNLL_RATION_PENALTY = 17, // Ration penalties
3340 JNLL_STOMACH = 18, // Stomach content data
3341 JNLL_LINKAGE_PRIOR = 19, // Linkage-table priors (per-row)
3342 JNLL_LINKAGE_RE = 20, // Linkage random effects
3343 JNLL_EQUIL_CATCH = 21, // Initial equilibrium catch
3344 JNLL_N_ROWS = 22 // total row count (for dimensioning)
3345 };
3346 matrix<Type> jnll_comp(JNLL_N_ROWS, n_col); jnll_comp.setZero(); // negative log-likelihood components
3347 matrix<Type> unweighted_jnll_comp(JNLL_N_ROWS, n_col); unweighted_jnll_comp.setZero(); // see 13.15
3348
3349 // A column is a fleet on rows JNLL_INDEX-JNLL_Q_DEV and JNLL_EQUIL_CATCH, a species
3350 // on JNLL_SRR_PRIOR-JNLL_LINKAGE_PRIOR, and neither on JNLL_LINKAGE_RE (one
3351 // model-wide density), so never sum down a column. Nothing writes the two ration rows.
3352
3353
3354 // 13.1. INDEX OF ABUNDANCE (JNLL_INDEX)
3355 // Index_distribution: 0 Lognormal; 1 MVN and 2 MVNORM, correlated across years
3356 // (fitted per fleet below); 3 Normal and 4 TruncatedNormal, both with an absolute
3357 // sd on the natural scale.
3358 Type index_std_dev = 0;
3359 for(index_ind = 0; index_ind < index_obs.rows(); index_ind++) {
3360
3361 index = index_ctl(index_ind, 0) - 1; // Fleet
3362 sp = index_ctl(index_ind, 1) - 1; // Species
3363 flt_yr = index_ctl(index_ind, 2); // Year
3364 int family = index_ll_type(index);
3365
3366 switch (est_sigma_index(index)) {
3367 case 0: index_std_dev = index_obs(index_ind, 1); break; // input, per row
3368 case 1: index_std_dev = exp(index_log_sd(index)); break; // estimated
3369 case 2: index_std_dev = index_analytical_sd(index); break; // Walters and Ludwig (1994), section 8.4
3370 default: error("Invalid 'Estimate_sigma_index'");
3371 }
3372 index_sd(index_ind) = index_std_dev;
3373
3374 // Fit hindcast years with an observation.
3375 bool fit_row = (flt_yr > 0) && (flt_yr <= endyr) && (flt_type(index) > 0) && (index_obs(index_ind, 0) > 0);
3376
3377 // Lognormal, read from obsvec (= log index) so OSA can gate each row with keep.
3378 if(fit_row && (family == 0)){
3379 int pos = index_obsvec_idx(index_ind);
3380 if(pos >= 0){
3381 Type index_mu = log(index_hat(index_ind)) - bias_adjust_obs*square(index_std_dev)/2.0;
3382 jnll_comp(JNLL_INDEX, index) -= keep(pos) * dnorm(obsvec(pos), index_mu, index_std_dev, true);
3383 if(osa_mode == 2){
3384 jnll_comp(JNLL_INDEX, index) -= osa_norm_cdf_terms(
3385 obsvec(pos), index_mu, index_std_dev, keep.cdf_lower(pos), keep.cdf_upper(pos));
3386 }
3387 }
3388 }
3389
3390 // Normal (3) matches AMAK's avo_like/cpue_like, 0.5 * (obs - q * pred)^2 / sd^2.
3391 // TruncatedNormal (4) renormalizes over obs > 0: log Phi(mu / sd), in [log 0.5, 0].
3392 if(fit_row && ((family == 3) || (family == 4))){
3393 Type log_Z = (family == 4) ? log(pnorm(index_hat(index_ind) / index_std_dev)) : Type(0.0);
3394 if(osa_mode == 0){
3395 jnll_comp(JNLL_INDEX, index) -= dnorm(index_obs(index_ind, 0), index_hat(index_ind), index_std_dev, true);
3396 jnll_comp(JNLL_INDEX, index) += log_Z;
3397 } else {
3398 // OSA: obsvec holds the untransformed index for these families.
3399 int pos = index_obsvec_idx(index_ind);
3400 if(pos >= 0){
3401 jnll_comp(JNLL_INDEX, index) -= keep(pos) * dnorm(obsvec(pos), index_hat(index_ind), index_std_dev, true);
3402 jnll_comp(JNLL_INDEX, index) += keep(pos) * log_Z;
3403 if(osa_mode == 2){
3404 if(family == 4){
3405 jnll_comp(JNLL_INDEX, index) -= osa_trunc_norm_cdf_terms(
3406 obsvec(pos), index_hat(index_ind), index_std_dev,
3407 keep.cdf_lower(pos), keep.cdf_upper(pos));
3408 } else {
3409 jnll_comp(JNLL_INDEX, index) -= osa_norm_cdf_terms(
3410 obsvec(pos), index_hat(index_ind), index_std_dev,
3411 keep.cdf_lower(pos), keep.cdf_upper(pos));
3412 }
3413 }
3414 }
3415 }
3416 }
3417
3418 // -- Simulate (families 0, 3, 4; MVN is drawn per fleet below). Projection rows
3419 // are always drawn, as run_mse() reveals them; a missing hindcast year stays NA.
3420 SIMULATE {
3421 bool sim_row = (flt_yr <= 0) || (flt_yr > endyr) || (index_obs(index_ind, 0) > 0);
3422 if(sim_row && (flt_type(index) > 0) && (family == 0)){
3423 index_obs(index_ind, 0) = exp(rnorm(log(index_hat(index_ind)) - bias_adjust_obs*square(index_std_dev)/2.0, index_std_dev));
3424 int sim_pos = index_obsvec_idx(index_ind);
3425 if(sim_pos >= 0){
3426 obsvec(sim_pos) = log(index_obs(index_ind, 0));
3427 }
3428 }
3429 if(sim_row && (flt_type(index) > 0) && (family == 3)){
3430 // The untruncated normal can draw <= 0, which data_check() refuses, so redraw and
3431 // count rejections; sim_mod() warns when they matter. Family 4 has no such gap.
3432 Type sim_draw = rnorm(index_hat(index_ind), index_std_dev);
3433 int tn_tries = 0;
3434 while((sim_draw <= Type(0)) && (tn_tries < index_trunc_max_tries)){
3435 index_trunc_rejects_sim(index_ind) += 1;
3436 sim_draw = rnorm(index_hat(index_ind), index_std_dev);
3437 tn_tries++;
3438 }
3439 index_trunc_tries_sim(index_ind) += tn_tries + 1;
3440 index_trunc_sd_sim(index_ind) = index_std_dev;
3441 index_trunc_budget_sim(index_ind) = index_trunc_max_tries;
3442 index_obs(index_ind, 0) = sim_draw;
3443 }
3444 if(sim_row && (flt_type(index) > 0) && (family == 4)){
3445 // Exact inverse-CDF draw from the normal restricted to (0, inf).
3446 Type a = pnorm(-index_hat(index_ind) / index_std_dev);
3447 Type u = a + (Type(1.0) - a) * runif(Type(0.0), Type(1.0));
3448 index_obs(index_ind, 0) = index_hat(index_ind) + index_std_dev * qnorm(u);
3449 }
3450 // Keep obsvec in step: log(obs) when fitting, the untransformed obs under OSA.
3451 if((flt_type(index) > 0) && ((family == 3) || (family == 4))){
3452 int sim_pos = index_obsvec_idx(index_ind);
3453 if(sim_pos >= 0){
3454 if(osa_mode == 0){
3455 if(index_obs(index_ind, 0) > Type(0)) obsvec(sim_pos) = log(index_obs(index_ind, 0));
3456 } else {
3457 obsvec(sim_pos) = index_obs(index_ind, 0);
3458 }
3459 }
3460 }
3461 }
3462 }
3463
3464 // MVN (1) and MVNORM (2): the AMAK/ebswp DoCovBTS survey likelihood on the arithmetic
3465 // residual r = obs - q * pred, with the fleet's fixed covariance index_cov_mat. MVN
3466 // reports the bare quadratic form 0.5 r' Sigma^-1 r, MVNORM the full density; the fit
3467 // is the same. Pair with Catchability 7 for the AMAK arithmetic-mean q.
3468 for(index = 0; index < n_flt; index++){
3469 if((flt_type(index) > 0) && (index_ll_type(index) == 1 || index_ll_type(index) == 2)){
3470 int n_mvn = 0;
3471 for(index_ind = 0; index_ind < index_obs.rows(); index_ind++){
3472 if((index_ctl(index_ind, 0) - 1) == index){
3473 flt_yr = index_ctl(index_ind, 2);
3474 if((flt_yr > 0) && (flt_yr <= endyr) && (index_obs(index_ind, 0) > 0)) n_mvn++;
3475 }
3476 }
3477 if(n_mvn > 0){
3478 // Fitted rows in index_obs order, which is the row order of Sigma.
3479 vector<Type> resid(n_mvn);
3480 vector<Type> mu(n_mvn);
3481 vector<int> posv(n_mvn);
3482 vector<int> rowv(n_mvn);
3483 int k = 0;
3484 for(index_ind = 0; index_ind < index_obs.rows(); index_ind++){
3485 if((index_ctl(index_ind, 0) - 1) == index){
3486 flt_yr = index_ctl(index_ind, 2);
3487 if((flt_yr > 0) && (flt_yr <= endyr) && (index_obs(index_ind, 0) > 0)){
3488 resid(k) = index_obs(index_ind, 0) - index_hat(index_ind);
3489 mu(k) = index_hat(index_ind);
3490 posv(k) = index_obsvec_idx(index_ind);
3491 rowv(k) = index_ind;
3492 k++;
3493 }
3494 }
3495 }
3496 if(osa_mode == 0){
3497 // MVNORM() returns 0.5 * (r' Sigma^-1 r + logdet(Sigma) + n log(2 pi));
3498 // index_cov_const holds the constant MVN drops.
3499 Type dens = MVNORM(index_cov_mat(index))(resid);
3500 jnll_comp(JNLL_INDEX, index) += (index_ll_type(index) == 2) ? dens : (dens - index_cov_const(index));
3501 } else {
3502 // OSA: build_osa_data() stores z = L^-1 obs, with Sigma = L L'. Each z_k is an
3503 // independent N((L^-1 mu)_k, 1) (Thygesen et al. 2017).
3504 Eigen::LLT<Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> > llt(index_cov_mat(index));
3505 matrix<Type> Lmat = llt.matrixL();
3506 matrix<Type> muc(n_mvn, 1);
3507 for(k = 0; k < n_mvn; k++) muc(k, 0) = mu(k);
3508 matrix<Type> mwhite = Lmat.template triangularView<Eigen::Lower>().solve(muc); // L^-1 mu
3509 for(k = 0; k < n_mvn; k++){
3510 int pos = posv(k);
3511 if(pos >= 0){
3512 jnll_comp(JNLL_INDEX, index) -= keep(pos) * dnorm(obsvec(pos), mwhite(k, 0), Type(1.0), true);
3513 if(osa_mode == 2){
3514 jnll_comp(JNLL_INDEX, index) -= osa_norm_cdf_terms(
3515 obsvec(pos), mwhite(k, 0), Type(1.0),
3516 keep.cdf_lower(pos), keep.cdf_upper(pos));
3517 }
3518 }
3519 }
3520 }
3521
3522 // -- Simulate the fitted rows only (Sigma covers no others), redrawing the vector
3523 // while any row is <= 0: exact for the positive-orthant truncation, which per-margin
3524 // truncation would decorrelate. A draw left when the budget runs out is reported.
3525 SIMULATE {
3526 vector<Type> sim_dev = MVNORM(index_cov_mat(index)).simulate();
3527 int mvn_tries = 0;
3528 while(true){
3529 bool any_nonpos = false;
3530 for(k = 0; k < n_mvn; k++){
3531 if(mu(k) + sim_dev(k) <= Type(0)) any_nonpos = true;
3532 }
3533 if(!any_nonpos) break;
3534 if(mvn_tries >= index_trunc_max_tries * n_mvn) break;
3535 for(k = 0; k < n_mvn; k++){
3536 if(mu(k) + sim_dev(k) <= Type(0)) index_trunc_rejects_sim(rowv(k)) += 1;
3537 }
3538 sim_dev = MVNORM(index_cov_mat(index)).simulate();
3539 mvn_tries++;
3540 }
3541 for(k = 0; k < n_mvn; k++){
3542 index_trunc_tries_sim(rowv(k)) += mvn_tries + 1;
3543 index_trunc_sd_sim(rowv(k)) = sqrt(index_cov_mat(index)(k, k));
3544 index_trunc_budget_sim(rowv(k)) = index_trunc_max_tries * n_mvn;
3545 index_obs(rowv(k), 0) = mu(k) + sim_dev(k);
3546 // obsvec is log(obs) when fitting and whitened under OSA; update only the former.
3547 int sim_pos = posv(k);
3548 if((sim_pos >= 0) && (osa_mode == 0) && (index_obs(rowv(k), 0) > Type(0))){
3549 obsvec(sim_pos) = log(index_obs(rowv(k), 0));
3550 }
3551 }
3552 }
3553 }
3554 }
3555 }
3556
3557 // Reported under a _sim name -- see the naming rule in section 5.2b.
3558 SIMULATE {
3559 matrix<Type> index_obs_sim = index_obs;
3560 REPORT(index_obs_sim);
3561 REPORT(index_trunc_tries_sim);
3562 REPORT(index_trunc_rejects_sim);
3563 REPORT(index_trunc_sd_sim);
3564 REPORT(index_trunc_budget_sim);
3565 }
3566
3567
3568 // 13.2. CATCH (JNLL_CATCH)
3569 // Lognormal on total catch, fishery fleets and hindcast years only.
3570 Type fsh_std_dev = 0;
3571 for(fsh_ind = 0; fsh_ind < catch_obs.rows(); fsh_ind++) {
3572
3573 flt = catch_ctl(fsh_ind, 0) - 1; // Fleet
3574 sp = catch_ctl(fsh_ind, 1) - 1; // Species
3575 flt_yr = catch_ctl(fsh_ind, 2); // Year
3576 yr = flt_yr - styr; // Year index, 0-based
3577
3578 switch (est_sigma_fsh(flt)) {
3579 case 0: fsh_std_dev = catch_obs(fsh_ind, 1); break; // input, per row
3580 case 1: fsh_std_dev = exp(catch_log_sd(flt)); break; // estimated
3581 case 2: fsh_std_dev = catch_analytical_sd(flt); break; // Walters and Ludwig (1994), section 9.1b
3582 default: error("Invalid 'Estimate_sigma_catch'");
3583 }
3584 catch_sd(fsh_ind) = fsh_std_dev;
3585
3586 // Read from obsvec (= log catch) so OSA can gate each row with keep.
3587 if((flt_yr > 0) && (flt_yr <= endyr) && (flt_type(flt) == 1) && (catch_obs(fsh_ind, 0) > 0)){
3588 int pos = catch_obsvec_idx(fsh_ind);
3589 if(pos >= 0){
3590 Type catch_mu = log(catch_hat(fsh_ind)) - bias_adjust_obs*square(fsh_std_dev)/2.0;
3591 jnll_comp(JNLL_CATCH, flt) -= keep(pos) * dnorm(obsvec(pos), catch_mu, fsh_std_dev, true) ;
3592 if(osa_mode == 2){
3593 jnll_comp(JNLL_CATCH, flt) -= osa_norm_cdf_terms(
3594 obsvec(pos), catch_mu, fsh_std_dev, keep.cdf_lower(pos), keep.cdf_upper(pos));
3595 }
3596 }
3597 }
3598
3599 // -- Simulate every row, with the dnorm's bias-corrected mean. Projection rows
3600 // (NA catch from clean_data()) are filled too; where catch_hat = 0 the draw is
3601 // exp(-inf) = 0, safe only on doubles. Do not share this mean with the dnorm (log 0
3602 // puts a NaN on the tape) or add a catch_hat > 0 guard (it changes the draw count).
3603 SIMULATE {
3604 catch_obs(fsh_ind, 0) = exp(rnorm(log(catch_hat(fsh_ind)) - bias_adjust_obs*square(fsh_std_dev)/2.0, fsh_std_dev));
3605 int sim_pos = catch_obsvec_idx(fsh_ind);
3606 if(sim_pos >= 0){
3607 obsvec(sim_pos) = log(catch_obs(fsh_ind, 0));
3608 }
3609 }
3610 }
3611
3612
3613 // 13.3. INITIAL EQUILIBRIUM CATCH (JNLL_EQUIL_CATCH)
3614 // Lognormal on its own Log_sd and its own row, as SS3's equ_catch_like. No OSA: one
3615 // observation has no sequence to condition on.
3616 for(int eq_ind = 0; eq_ind < equil_catch_ctl.rows(); eq_ind++){
3617 int eq_flt = equil_catch_ctl(eq_ind, 0) - 1;
3618 if((equil_catch_obs(eq_ind, 0) > 0) && (flt_type(eq_flt) == 1)){
3619 Type eq_sd = equil_catch_obs(eq_ind, 1);
3620 Type eq_mu = log(equil_catch_hat(eq_ind)) - bias_adjust_obs*square(eq_sd)/2.0;
3621 jnll_comp(JNLL_EQUIL_CATCH, eq_flt) -=
3622 dnorm(log(equil_catch_obs(eq_ind, 0)), eq_mu, eq_sd, true);
3623
3624 // -- Simulate. Under initMode 6 this is the only observation on Finit, so a
3625 // self_test() replicate must redraw it.
3626 SIMULATE {
3627 equil_catch_obs(eq_ind, 0) = exp(rnorm(eq_mu, eq_sd));
3628 }
3629 }
3630 }
3631
3632 // Reported under _sim names -- see the naming rule in section 5.2b. obsvec_sim is for
3633 // inspection: only its catch and index entries are redrawn.
3634 SIMULATE {
3635 matrix<Type> catch_obs_sim = catch_obs;
3636 matrix<Type> equil_catch_obs_sim = equil_catch_obs;
3637 vector<Type> obsvec_sim = obsvec;
3638 REPORT(catch_obs_sim);
3639 REPORT(equil_catch_obs_sim);
3640 REPORT(obsvec_sim);
3641 }
3642
3643
3644 // 13.4. AGE AND LENGTH COMPOSITION (JNLL_COMP)
3645 // Likelihood types are in comp_row_nll() (likelihood.hpp). comp_offset (default
3646 // 1e-5, from fit_control()) keeps log(0) out, and build_osa_data() uses the same.
3647 // FIXME: the multinomial (type 0) is renormalized after the offset, so its reported
3648 // NLL carries a per-row constant N_eff * log(1 + n_bins * offset); fit and MLE unchanged.
3649 Type comp_prop_offset = comp_offset;
3650 matrix<Type> comp_sim = comp_obs; // simulated comps; see the _sim rule in section 5.2b
3651
3652 for(comp_ind = 0; comp_ind < comp_obs.rows(); comp_ind++) {
3653
3654 flt = comp_ctl(comp_ind, 0) - 1; // Fleet
3655 sp = comp_ctl(comp_ind, 1) - 1; // Species
3656 flt_sex = comp_ctl(comp_ind, 2); // 0 = combined, 1 = female, 2 = male, 3 = joint
3657 comp_type = comp_ctl(comp_ind, 3); // 0 = age, 1 = length
3658 yr = comp_ctl(comp_ind, 4); // Year
3659
3660 // A joint-sex row holds both sexes, so twice the bins.
3661 joint_adjust(comp_ind) = 1;
3662 if(flt_sex == 3){
3663 joint_adjust(comp_ind) = 2;
3664 }
3665 int nbins_blk = (comp_type == 0) ? nages(sp) : nlengths(sp);
3666 int n_comp = 0; // a comp type other than age or length scores no bins
3667 if((comp_type == 0) || (comp_type == 1)) n_comp = nbins_blk * joint_adjust(comp_ind);
3668
3669 vector<Type> comp_obs_tmp = comp_obs.row(comp_ind).segment(0, n_comp); // Observed proportion
3670 vector<Type> comp_hat_tmp = comp_hat.row(comp_ind).segment(0, n_comp); // Expected proportion
3671
3672 // Tail accumulation (Comp_accum_young / Comp_accum_old). OSA reads an obsvec that
3673 // build_osa_data() folds the same way.
3674 fold_comp_tails(comp_obs_tmp, comp_hat_tmp, n_comp, nbins_blk, joint_adjust(comp_ind),
3675 comp_accum_young(flt), comp_accum_old(flt));
3676
3677 if((yr <= endyr) && (yr > 0) && (flt_type(flt) > 0) && (comp_n(comp_ind, 1) > 0)){
3678 comp_row_nll(comp_ll_type(flt), osa_mode, comp_obs_tmp, comp_hat_tmp,
3679 comp_prop_offset, comp_n(comp_ind, 1), comp_weights(flt), DM_pars_comp(flt),
3680 obsvec, keep, comp_obsvec_idx(comp_ind), "comp_ll_type",
3681 jnll_comp(JNLL_COMP, flt), unweighted_jnll_comp(JNLL_COMP, flt));
3682 }
3683
3684 // -- Simulate in raw bins, before the fold and offset (both families are closed
3685 // under merging bins), projection rows included, as run_mse() reveals them.
3686 SIMULATE {
3687 int nbin_raw = ((comp_type == 0) ? nages(sp) : nlengths(sp)) * joint_adjust(comp_ind);
3688 vector<Type> sim_p = comp_hat.row(comp_ind).segment(0, nbin_raw);
3689 Type sim_tot = sim_p.sum();
3690 Type n_nom = comp_n(comp_ind, 1);
3691 // A row with nothing predicted or nothing sampled comes back EMPTY, never as the
3692 // noise-free prediction: run_mse() reads an all-zero row as "no catch, no comp".
3693 vector<Type> sim_out(nbin_raw); sim_out.setZero();
3694
3695 if((sim_tot > Type(0)) && (n_nom > Type(0))){
3696 vector<Type> p = sim_p / sim_tot;
3697 if(comp_ll_type(flt) == 1){
3698 // DM: theta already carries the weight, so draw at the nominal N.
3699 vector<Type> sim_alphas = p * n_nom * DM_pars_comp(flt);
3700 sim_out = rdirmultinom_rce(n_nom, sim_alphas);
3701 } else {
3702 // Multinomial: the weight scales the log-likelihood, so it is an effective
3703 // sample size and the draw uses it too.
3704 sim_out = rmultinom_rce(n_nom * comp_weights(flt), p);
3705 }
3706 }
3707 for(int b = 0; b < nbin_raw; b++){
3708 comp_sim(comp_ind, b) = sim_out(b);
3709 }
3710 // Zero the padding past this row's bins, which rearrange_data() would otherwise
3711 // normalize into the real ones.
3712 for(int b = nbin_raw; b < comp_sim.cols(); b++){
3713 comp_sim(comp_ind, b) = Type(0);
3714 }
3715 }
3716 }
3717
3718 SIMULATE {
3719 matrix<Type> comp_obs_sim = comp_sim;
3720 REPORT(comp_obs_sim);
3721 }
3722
3723
3724 // 13.5. CONDITIONAL AGE-AT-LENGTH (JNLL_CAAL)
3725 // One row per fleet, year, sex and length bin, scored like a composition row.
3726 matrix<Type> caal_sim = caal_obs; // simulated CAAL; see the _sim rule in section 5.2b
3727
3728 for(int caal_ind = 0; caal_ind < caal_hat.rows(); caal_ind++){
3729
3730 flt = caal_ctl(caal_ind, 0) - 1; // Fleet
3731 sp = caal_ctl(caal_ind, 1) - 1; // Species
3732 flt_sex = caal_ctl(caal_ind, 2); // 0 = combined, 1 = female, 2 = male, 3 = joint
3733 yr = caal_ctl(caal_ind, 3); // Year
3734 ln = caal_ctl(caal_ind, 4) - 1; // Length bin
3735
3736 int n_caal = nages(sp);
3737
3738 vector<Type> caal_obs_tmp = caal_obs.row(caal_ind).segment(0, n_caal); // Observed proportion
3739 vector<Type> caal_hat_tmp = caal_hat.row(caal_ind).segment(0, n_caal); // Expected proportion
3740
3741 if((yr <= endyr) && (yr > 0) && (flt_type(flt) > 0) && (caal_n(caal_ind, 0) > 0)){
3742 comp_row_nll(caal_ll_type(flt), osa_mode, caal_obs_tmp, caal_hat_tmp,
3743 comp_prop_offset, caal_n(caal_ind, 0), caal_weights(flt), DM_pars_caal(flt),
3744 obsvec, keep, caal_obsvec_idx(caal_ind), "caal_ll_type",
3745 jnll_comp(JNLL_CAAL, flt), unweighted_jnll_comp(JNLL_CAAL, flt));
3746 }
3747
3748 // -- Simulate, as for the compositions above (CAAL has no tail fold).
3749 SIMULATE {
3750 vector<Type> sim_p = caal_hat.row(caal_ind).segment(0, n_caal);
3751 Type sim_tot = sim_p.sum();
3752 Type n_nom = caal_n(caal_ind, 0);
3753 vector<Type> sim_out(n_caal); sim_out.setZero();
3754
3755 if((sim_tot > Type(0)) && (n_nom > Type(0))){
3756 vector<Type> p = sim_p / sim_tot;
3757 if(caal_ll_type(flt) == 1){
3758 vector<Type> sim_alphas = p * n_nom * DM_pars_caal(flt);
3759 sim_out = rdirmultinom_rce(n_nom, sim_alphas);
3760 } else {
3761 sim_out = rmultinom_rce(n_nom * caal_weights(flt), p);
3762 }
3763 }
3764 for(int b = 0; b < n_caal; b++){
3765 caal_sim(caal_ind, b) = sim_out(b);
3766 }
3767 for(int b = n_caal; b < caal_sim.cols(); b++){
3768 caal_sim(caal_ind, b) = Type(0);
3769 }
3770 }
3771 }
3772
3773 SIMULATE {
3774 matrix<Type> caal_obs_sim = caal_sim;
3775 REPORT(caal_obs_sim);
3776 }
3777
3778
3779 // 13.6. STOMACH CONTENTS (JNLL_STOMACH)
3780 // Each stomach's prey proportions plus an "other prey" balance, scored per predator
3781 // when suitability is estimated.
3782 matrix<Type> diet_sim = diet_obs; // simulated diet; see the _sim rule in section 5.2b
3783
3784 if(diet_fitted) {
3785
3786 int current_j = 0; // Track position in diet_ctl
3787
3788 for (int i = 0; i < n_stomach_obs; ++i) {
3789
3790 // This stomach's prey are the run of diet_ctl rows with stomach_id == i. The scan
3791 // only moves forward, so ids must be sorted 0, 1, 2, ... with no gaps; clean_data()
3792 // builds them that way and data_check() refuses a table that is not.
3793 int start_j = current_j;
3794 while((current_j < diet_ctl.rows()) && (stomach_id(current_j) == i)) {
3795 current_j++;
3796 }
3797 int n_prey = current_j - start_j;
3798 if (n_prey == 0) continue; // before reading row start_j, which may be past the end
3799
3800 int rsp = diet_ctl(start_j, 0) - 1; // predator species
3801 Type N_s = diet_obs(start_j, 0); // stomach sample size
3802
3803 if (suitMode(rsp) <= 0) continue;
3804
3805 // Prey proportions, with "other prey" as the last bin.
3806 vector<Type> obs_diet_prop(n_prey + 1); obs_diet_prop.setZero();
3807 vector<Type> pred_diet_prop(n_prey + 1); pred_diet_prop.setZero();
3808
3809 for (int k = 0; k < n_prey; ++k) {
3810 obs_diet_prop(k) = diet_obs(start_j + k, 1);
3811 pred_diet_prop(k) = diet_hat(start_j + k, 1);
3812 }
3813
3814 Type sum_obs_p = obs_diet_prop.head(n_prey).sum();
3815 if (sum_obs_p > 1.0) sum_obs_p = 1.0;
3816 obs_diet_prop(n_prey) = 1.0 - sum_obs_p;
3817
3818 Type sum_est_p = pred_diet_prop.head(n_prey).sum();
3819 pred_diet_prop(n_prey) = posfun(1.0 - sum_est_p, Type(0.00001), penalty); // smooth floor at 0
3820
3821 // Same offset as the compositions, then renormalize.
3822 obs_diet_prop += comp_offset;
3823 pred_diet_prop += comp_offset;
3824
3825 obs_diet_prop /= obs_diet_prop.sum();
3826 pred_diet_prop /= pred_diet_prop.sum();
3827
3828 vector<Type> obs_diet_content = obs_diet_prop * N_s; // observed counts
3829
3830 // Not comp_row_nll(): the stomach multinomial is TMB's dmultinom() on proportions
3831 // renormalized after the offset, a different number from the composition form.
3832
3833 Type stomach_log_likelihood = 0;
3834 Type unweighted_stomach_log_likelihood = 0;
3835 Type DM_diet_par = DM_diet_pars(rsp);
3836
3837 vector<Type> diet_alphas = pred_diet_prop * N_s * DM_diet_par;
3838 vector<Type> unweighted_diet_alphas = pred_diet_prop * N_s;
3839
3840 if(osa_mode == 0){
3841 switch(diet_ll_type(rsp)){
3842
3843 case 0: // Multinomial; the weight multiplies the log-likelihood
3844 stomach_log_likelihood = dmultinom(obs_diet_content, pred_diet_prop, true);
3845
3846 unweighted_jnll_comp(JNLL_STOMACH, rsp) -= stomach_log_likelihood;
3847 jnll_comp(JNLL_STOMACH, rsp) -= diet_comp_weights(rsp) * stomach_log_likelihood;
3848 break;
3849 case 1: // Dirichlet-multinomial; theta = exp(weight)
3850 stomach_log_likelihood = ddirmultinom(obs_diet_content, diet_alphas, true);
3851 unweighted_stomach_log_likelihood = ddirmultinom(obs_diet_content, unweighted_diet_alphas, true);
3852
3853 unweighted_jnll_comp(JNLL_STOMACH, rsp) -= unweighted_stomach_log_likelihood;
3854 jnll_comp(JNLL_STOMACH, rsp) -= stomach_log_likelihood;
3855 break;
3856
3857 default:
3858 error("Invalid 'diet_ll_type'");
3859 }
3860 } else {
3861 // OSA: unweighted and keep-gated, read from obsvec over the n_prey + 1 bins.
3862 int start = diet_obsvec_idx(i);
3863 if(start >= 0){
3864 vector<Type> osa_x = obsvec.segment(start, n_prey + 1);
3865 if(diet_ll_type(rsp) == 1){ // Dirichlet-multinomial: no CDF term (comp_osa.hpp)
3866 jnll_comp(JNLL_STOMACH, rsp) -= ddirmultinom_osa(osa_x, diet_alphas, keep.segment(start, n_prey + 1), 1, 1);
3867 } else {
3868 jnll_comp(JNLL_STOMACH, rsp) -= dmultinom_osa(osa_x, pred_diet_prop, keep.segment(start, n_prey + 1), 1, 1, osa_mode == 2);
3869 }
3870 }
3871 }
3872
3873 // -- Simulate from the same family, from the prediction before the offset. Only
3874 // the prey bins are written back; "other prey" is recomputed on the next fit.
3875 SIMULATE {
3876 vector<Type> sim_p(n_prey + 1);
3877 Type prey_sum = 0.0;
3878 for(int k = 0; k < n_prey; k++){
3879 sim_p(k) = diet_hat(start_j + k, 1);
3880 prey_sum += sim_p(k);
3881 }
3882 sim_p(n_prey) = (prey_sum < Type(1.0)) ? Type(1.0) - prey_sum : Type(0.0);
3883 Type sim_tot = sim_p.sum();
3884 if(sim_tot > Type(0)) sim_p /= sim_tot;
3885
3886 if((N_s > Type(0)) && (sim_tot > Type(0))){
3887 vector<Type> sim_counts(n_prey + 1);
3888 switch(diet_ll_type(rsp)){
3889 case 0: {
3890 // The weight on a multinomial log-likelihood is an effective sample size.
3891 Type n_eff = N_s * diet_comp_weights(rsp);
3892 sim_counts = rmultinom_rce(n_eff, sim_p);
3893 break;
3894 }
3895 case 1: {
3896 vector<Type> sim_alphas = sim_p * N_s * DM_diet_par;
3897 sim_counts = rdirmultinom_rce(N_s, sim_alphas);
3898 break;
3899 }
3900 default:
3901 error("Invalid 'diet_ll_type'");
3902 }
3903 // Divide by the count actually drawn (rmultinom_rce rounds N), so the prey
3904 // proportions cannot sum past 1. A stomach that draws nothing comes back empty.
3905 Type n_drawn = sim_counts.sum();
3906 for(int k = 0; k < n_prey; k++){
3907 diet_sim(start_j + k, 1) = (n_drawn > Type(0))
3908 ? sim_counts(k) / n_drawn
3909 : Type(0);
3910 }
3911 }
3912 }
3913 }
3914 }
3915
3916 // Reported under a _sim name -- see the naming rule in section 5.2b.
3917 SIMULATE {
3918 matrix<Type> diet_obs_sim = diet_sim;
3919 REPORT(diet_obs_sim);
3920 }
3921
3922
3923 // 13.7. SELECTIVITY PENALTIES (JNLL_SEL_NONPARAM, JNLL_SEL_DEV)
3924 // Charged once per Selectivity_index, on the lead fleet. Bins are on the fleet's
3925 // selectivity dimension (ages, or population length bins).
3926 // FIXME: penalize every deviation, not a sub-range, and the bin and year range controls
3927 // (Sel_pen_first_bin, Sel_pen_last_bin, Sel_cap_bin, Sel_start_year) could go.
3928 for(flt = 0; flt < n_flt; flt++){
3929 sp = flt_spp(flt);
3930 bool sel_is_length = (flt_sel_dim(flt) == 1);
3931 int nbins = sel_is_length ? nlengths_pop(sp) : nages(sp);
3932
3933 if(flt_type(flt) > 0 && flt_sel_lead(flt) == 1){
3934
3935 // NonParametric (2): Ianelli/AMAK penalties on log selectivity centred to mean 1
3936 // (arrowtooth ADMB model), each year's curve when it varies (Atka mackerel).
3937 // Refused under random_sel = TRUE; form 13 is the integrable version.
3938 if(flt_sel_type(flt) == 2) {
3939 int nyrs_tmp = 1;
3940 if((flt_varying_sel(flt) == 1) || (flt_varying_sel(flt) == 4)){
3941 nyrs_tmp = nyrs_hind;
3942 }
3943
3944 for(yr = 0; yr < nyrs_tmp; yr++){
3945
3946 // 1. Decreasing selectivity: (|d| + d) / 2 = max(d, 0), d > 0 if decreasing.
3947 // FIXME: AMAK starts this penalty at bin nbins/2; here it starts at bin 0.
3948 for(sex = 0; sex < nsex(sp); sex++){
3949 for(age = 0; age < (nbins - 1); age++) {
3950 Type sel_ratio_tmp = log_non_par_sel(flt, sex, age, yr) - log_non_par_sel(flt, sex, age + 1, yr);
3951 jnll_comp(JNLL_SEL_NONPARAM, flt) += sel_curve_pen(flt, 0) * square( (CppAD::abs(sel_ratio_tmp) + sel_ratio_tmp)/2.0);
3952 }
3953 }
3954
3955 // 2. Curvature: squared second differences.
3956 for(sex = 0; sex < nsex(sp); sex++){
3957 vector<Type> sel_tmp(nbins); sel_tmp.setZero();
3958 for(age = 0; age < nbins; age++) {
3959 sel_tmp(age) = log_non_par_sel(flt, sex, age, yr);
3960 }
3961 vector<Type> sel_d2 = first_difference( first_difference( sel_tmp ) );
3962 for(int a2 = 0; a2 < sel_d2.size(); a2++) {
3963 jnll_comp(JNLL_SEL_NONPARAM, flt) += sel_curve_pen(flt, 1) * sel_d2(a2) * sel_d2(a2);
3964 }
3965 }
3966
3967 // 3. Time variation. RandomWalk (4): the year-to-year change in realized log
3968 // selectivity (Atka mackerel). IID (1): each deviate, over only the bins
3969 // build_map() estimates, as a fixed bin would pull the sd toward zero.
3970 if(flt_varying_sel(flt) == 4){
3971 if(yr > 0){
3972 for(sex = 0; sex < nsex(sp); sex++){
3973 for(age = 0; age < (nbins - 1); age++) {
3974 jnll_comp(JNLL_SEL_DEV, flt) -= dnorm(log_non_par_sel(flt, sex, age, yr), log_non_par_sel(flt, sex, age, yr - 1), sel_dev_sd(flt), true);
3975 }
3976 }
3977 }
3978 } else if(flt_varying_sel(flt) == 1){
3979 for(sex = 0; sex < nsex(sp); sex++){
3980 for(int bin = bin_first_selected(flt); bin < flt_n_sel_bins(flt); bin++) {
3981 jnll_comp(JNLL_SEL_DEV, flt) -= dnorm(sel_coff_dev(flt, sex, bin, yr), Type(0.0), sel_dev_sd(flt), true);
3982 }
3983 }
3984 }
3985
3986 // 4. Average selectivity: holds each year's mean, deviates included.
3987 for(sex = 0; sex < nsex(sp); sex++){
3988 jnll_comp(JNLL_SEL_NONPARAM, flt) += 2.0 * square(avg_sel(flt, sex, yr));
3989 }
3990 }
3991 }
3992
3993 // NonParametricPM (9): ADMB's Selectivity_Likelihood. JNLL_SEL_NONPARAM is
3994 // sel_like(1): shape, Sel_curve_pen1 = ctrl_flag(13); plus the optional avgsel (5).
3995 // JNLL_SEL_DEV is sel_like_dev(1): curvature, Sel_curve_pen2 = ctrl_flag(11)/nch; a
3996 // random walk with no normalizing constant; increments, Sel_curve_pen3 =
3997 // ctrl_flag(10)/group_num.
3998 if(flt_sel_type(flt) == 9) {
3999
4000 int nyrs_tmp = 1;
4001 if(flt_varying_sel(flt) == 4){
4002 nyrs_tmp = nyrs_hind;
4003 }
4004
4005 // Years before the fleet's selectivity start year (0-based) are skipped, as in
4006 // ADMB, whose base-year terms are anchored at styr.
4007 int start_yr = flt_sel_start_yr(flt);
4008 int shape_a0 = flt_sel_pen_first_bin(flt); // first left bin of the shape pairs
4009 if(shape_a0 < 0) shape_a0 = bin_first_selected(flt);
4010 int shape_a1 = flt_sel_pen_last_bin(flt); // last left bin of the shape pairs
4011 if(shape_a1 < 0) shape_a1 = nbins - 2;
4012 // Pairs are (age, age + 1), so the last left bin is nbins - 2.
4013 if(shape_a1 > nbins - 2) shape_a1 = nbins - 2;
4014 int shape_mode = flt_sel_shape_mode(flt); // 0 = directional, 1 = smooth
4015 for(sex = 0; sex < nsex(sp); sex++){
4016 for(yr = start_yr; yr < nyrs_tmp; yr++){
4017
4018 // (1) Shape. Directional (ADMB/AMAK): Sel_curve_pen1 >= 0 penalizes
4019 // decreasing pairs, < 0 increasing ones. Smooth (RTMB "rpm"): two-sided d^2.
4020 for(age = shape_a0; age <= shape_a1; age++) {
4021 Type d = log_non_par_sel(flt, sex, age, yr) - log_non_par_sel(flt, sex, age + 1, yr); // > 0 if decreasing
4022 if(shape_mode == 1)
4023 jnll_comp(JNLL_SEL_NONPARAM, flt) += sel_curve_pen(flt, 0) * d * d;
4024 else if(sel_curve_pen(flt, 0) >= 0)
4025 jnll_comp(JNLL_SEL_NONPARAM, flt) += sel_curve_pen(flt, 0) * square( (CppAD::abs(d) + d)/2.0 );
4026 else
4027 jnll_comp(JNLL_SEL_NONPARAM, flt) += -sel_curve_pen(flt, 0) * square( (CppAD::abs(d) - d)/2.0 );
4028 }
4029
4030 // (2) Curvature; the start year counts only for a fleet starting at styr.
4031 if((yr > start_yr) || (start_yr == 0)){
4032 vector<Type> ls(nbins); ls.setZero();
4033 for(age = 0; age < nbins; age++) ls(age) = log_non_par_sel(flt, sex, age, yr);
4034 vector<Type> d2 = first_difference( first_difference( ls ) );
4035 for(int a2 = 0; a2 < d2.size(); a2++) jnll_comp(JNLL_SEL_DEV, flt) += sel_curve_pen(flt, 1) * d2(a2) * d2(a2);
4036 }
4037
4038 // (3) Random walk, a bare sum of squares.
4039 if(yr > start_yr){
4040 for(age = 0; age < nbins; age++) {
4041 Type dd = log_non_par_sel(flt, sex, age, yr) - log_non_par_sel(flt, sex, age, yr - 1);
4042 jnll_comp(JNLL_SEL_DEV, flt) += dd * dd / (2.0 * sel_dev_sd(flt) * sel_dev_sd(flt));
4043 }
4044 }
4045 }
4046
4047 // (4) Increment size: sum of squared sel_coff_dev, the random-walk increments.
4048 for(int bin = 0; bin < flt_n_sel_bins(flt); bin++){
4049 for(yr = start_yr; yr < nyrs_tmp; yr++){
4050 jnll_comp(JNLL_SEL_DEV, flt) += sel_curve_pen(flt, 2) * sel_coff_dev(flt, sex, bin, yr) * sel_coff_dev(flt, sex, bin, yr);
4051 }
4052 }
4053
4054 // (5) AMAK avgsel: Sel_avgsel_pen * log(mean(exp(base coefficients)))^2 over
4055 // the estimated bins; AMAK uses 10. Off (0) by default.
4056 if(flt_sel_avgsel_pen(flt) > 0){
4057 int n_base = flt_n_sel_bins(flt) - bin_first_selected(flt);
4058 vector<Type> base(n_base);
4059 for(int bin = 0; bin < n_base; bin++){
4060 base(bin) = sel_coff(flt, sex, bin + bin_first_selected(flt));
4061 }
4062 Type avgsel = log_mean_exp(base);
4063 jnll_comp(JNLL_SEL_NONPARAM, flt) += flt_sel_avgsel_pen(flt) * avgsel * avgsel;
4064 }
4065 }
4066 }
4067
4068 // NonParametricIntegrable (13): the NonParametric shape penalties, charged once on
4069 // the base curve sel_coff, and a proper normal density on the deviates, so
4070 // random_sel = TRUE integrates a complete density. With no deviates it equals form 2.
4071 if(flt_sel_type(flt) == 13) {
4072 int n_sel_bins = flt_n_sel_bins(flt);
4073 int start_yr = flt_sel_start_yr(flt);
4074 for(sex = 0; sex < nsex(sp); sex++){
4075
4076 // The base curve as selectivity.hpp builds a year with no deviates: the
4077 // estimated bins, the last held through the tail, centred to a mean exp() of 1.
4078 vector<Type> base(nbins);
4079 for(int bin = 0; bin < nbins; bin++){
4080 base(bin) = sel_coff(flt, sex, (bin < n_sel_bins ? bin : n_sel_bins - 1));
4081 }
4082 vector<Type> est(n_sel_bins);
4083 for(int bin = 0; bin < n_sel_bins; bin++) est(bin) = base(bin);
4084 Type avg_base = log_mean_exp(est);
4085 Type ctr = log_mean_exp(base);
4086 for(int bin = 0; bin < nbins; bin++) base(bin) -= ctr;
4087
4088 // 1. Decreasing selectivity.
4089 for(int bin = 0; bin < (nbins - 1); bin++) {
4090 Type d = base(bin) - base(bin + 1);
4091 jnll_comp(JNLL_SEL_NONPARAM, flt) += sel_curve_pen(flt, 0) * square( (CppAD::abs(d) + d)/2.0 );
4092 }
4093 // 2. Curvature.
4094 vector<Type> d2 = first_difference( first_difference( base ) );
4095 for(int a2 = 0; a2 < d2.size(); a2++) {
4096 jnll_comp(JNLL_SEL_NONPARAM, flt) += sel_curve_pen(flt, 1) * d2(a2) * d2(a2);
4097 }
4098 // 4. Average selectivity of the estimated coefficients.
4099 jnll_comp(JNLL_SEL_NONPARAM, flt) += 2.0 * square(avg_base);
4100
4101 // 3. Deviates, over the estimated bins only: IID in every hindcast year, or
4102 // random-walk increments after the start year (whose increment is fixed at 0).
4103 bool scored = (flt_varying_sel(flt) == 1) || (flt_varying_sel(flt) == 4);
4104 int yr_lo = (flt_varying_sel(flt) == 4) ? start_yr + 1 : 0;
4105 if(scored){
4106 for(yr = yr_lo; yr < nyrs_hind; yr++){
4107 for(int bin = bin_first_selected(flt); bin < n_sel_bins; bin++) {
4108 jnll_comp(JNLL_SEL_DEV, flt) -= dnorm(sel_coff_dev(flt, sex, bin, yr), Type(0.0), sel_dev_sd(flt), true);
4109 }
4110 }
4111 }
4112 }
4113 }
4114
4115 // Logistic-family selectivity deviates: logistic (1), double logistic (3),
4116 // descending logistic (4), double normal (8). Each limb's inflection has sd and log
4117 // slope 4 * sd; the ascending random walk swaps them, to match the GOA pollock
4118 // assessment. Double normal: slot 0 is the peak and ascending width, slot 1 the
4119 // right-floor logit and descending width.
4120 bool asc_limb = (flt_sel_type(flt) == 1) || (flt_sel_type(flt) == 3) || (flt_sel_type(flt) == 8);
4121 bool desc_limb = (flt_sel_type(flt) == 3) || (flt_sel_type(flt) == 4) || (flt_sel_type(flt) == 8);
4122
4123 // Time_varying_sel IID (1) or 2, scored the same way.
4124 if((flt_varying_sel(flt) == 1) || (flt_varying_sel(flt) == 2)){
4125 for(sex = 0; sex < nsex(sp); sex ++){
4126 for(yr = 0; yr < nyrs_hind; yr++){
4127 if(asc_limb){
4128 jnll_comp(JNLL_SEL_DEV, flt) -= dnorm(sel_inf_dev(0, flt, sex, yr), Type(0.0), sel_dev_sd(flt), true);
4129 jnll_comp(JNLL_SEL_DEV, flt) -= dnorm(log_sel_slp_dev(0, flt, sex, yr), Type(0.0), 4 * sel_dev_sd(flt), true);
4130 }
4131 if(desc_limb){
4132 jnll_comp(JNLL_SEL_DEV, flt) -= dnorm(sel_inf_dev(1, flt, sex, yr), Type(0.0), sel_dev_sd(flt), true);
4133 jnll_comp(JNLL_SEL_DEV, flt) -= dnorm(log_sel_slp_dev(1, flt, sex, yr), Type(0.0), 4 * sel_dev_sd(flt), true);
4134 }
4135 }
4136 }
4137 }
4138
4139 // Random walk on both limbs (4) or the ascending limb only (5). Under 5 the
4140 // descending deviates are not estimated, so scoring them would bias the sd down.
4141 if((flt_varying_sel(flt) == 4) || (flt_varying_sel(flt) == 5)){
4142 for(sex = 0; sex < nsex(sp); sex ++){
4143 for(yr = 1; yr < nyrs_hind; yr++){
4144 if(asc_limb){
4145 jnll_comp(JNLL_SEL_DEV, flt) -= dnorm(log_sel_slp_dev(0, flt, sex, yr) - log_sel_slp_dev(0, flt, sex, yr-1), Type(0.0), sel_dev_sd(flt), true);
4146 jnll_comp(JNLL_SEL_DEV, flt) -= dnorm(sel_inf_dev(0, flt, sex, yr) - sel_inf_dev(0, flt, sex, yr-1), Type(0.0), 4 * sel_dev_sd(flt), true);
4147 }
4148 if((flt_varying_sel(flt) == 4) && desc_limb){
4149 jnll_comp(JNLL_SEL_DEV, flt) -= dnorm(sel_inf_dev(1, flt, sex, yr) - sel_inf_dev(1, flt, sex, yr-1), Type(0.0), sel_dev_sd(flt), true);
4150 jnll_comp(JNLL_SEL_DEV, flt) -= dnorm(log_sel_slp_dev(1, flt, sex, yr) - log_sel_slp_dev(1, flt, sex, yr-1), Type(0.0), sel_dev_sd(flt) * 4, true);
4151 }
4152 }
4153 }
4154 }
4155
4156 // LogisticPM (11): the AMAK "pm" survey penalties (ctrl_flag(19) > 0), from the year
4157 // after the selectivity start year. Sel_curve_pen1 (ctrl_flag(26)) on the change in
4158 // log selectivity over [Sel_norm_bin, Sel_norm_bin_upper], and Sel_curve_pen3 (ADMB's
4159 // 8) on the change in the free age-1 deviate. Sel_curve_pen2 is unused.
4160 if(flt_sel_type(flt) == 11){
4161 int start_yr = flt_sel_start_yr(flt);
4162 int alo = sel_norm_bin1(flt); int ahi = sel_norm_bin2(flt);
4163 if(alo < 0) alo = bin_first_selected(flt); // default: whole selected range
4164 if(ahi < 0) ahi = nbins - 1;
4165 for(sex = 0; sex < nsex(sp); sex ++){
4166 for(yr = start_yr + 1; yr < nyrs_hind; yr++){
4167 for(age = alo; age <= ahi; age++){
4168 Type s_now = sel_is_length ? sel_at_length(flt, sex, age, yr) : sel_at_age(flt, sex, age, yr);
4169 Type s_prev = sel_is_length ? sel_at_length(flt, sex, age, yr - 1) : sel_at_age(flt, sex, age, yr - 1);
4170 Type d = log(s_now) - log(s_prev);
4171 jnll_comp(JNLL_SEL_DEV, flt) += sel_curve_pen(flt, 0) * d * d;
4172 }
4173 Type da1 = sel_inf_dev(1, flt, sex, yr) - sel_inf_dev(1, flt, sex, yr - 1);
4174 jnll_comp(JNLL_SEL_DEV, flt) += sel_curve_pen(flt, 2) * da1 * da1;
4175 }
4176 }
4177 }
4178
4179 // Hake non-parametric (5): IID deviates (Taylor et al. 2015), over all N_sel_bins,
4180 // including any bin build_map() holds at 0.
4181 if(((flt_varying_sel(flt) == 1) || (flt_varying_sel(flt) == 2)) && (flt_sel_type(flt) == 5)){
4182 for(int bin = 0; bin < flt_n_sel_bins(flt); bin++){
4183 for(sex = 0; sex < nsex(sp); sex++){
4184 for(yr = 0; yr < nyrs_hind; yr++){
4185 jnll_comp(JNLL_SEL_DEV, flt) -= dnorm(sel_coff_dev(flt, sex, bin, yr), Type(0.0), sel_dev_sd(flt), true);
4186 }
4187 }
4188 }
4189 }
4190
4191 // 2D AR1 (6): separable AR1 over year and bin. rho_trans() maps Sel_curve_pen1 and 2
4192 // to the bin and year correlations; sel_dev_sd is the conditional sd.
4193 if(flt_sel_type(flt) == 6){
4194 int n_sel_bins = flt_n_sel_bins(flt);
4195 array<Type> tmp_AR2(n_sel_bins, nyrs_hind);
4196
4197 for(sex = 0; sex < nsex(sp); sex ++){
4198 for (int bin = 0; bin < n_sel_bins; bin++) {
4199 for (int yr = 0; yr < nyrs_hind; yr++) {
4200 tmp_AR2(bin, yr) = sel_coff_dev(flt, sex, bin, yr);
4201 }
4202 }
4203
4204 Type rho_a = rho_trans(sel_curve_pen(flt, 0));
4205 Type rho_y = rho_trans(sel_curve_pen(flt, 1));
4206
4207 Type Sigma_sig_sel = pow(pow(sel_dev_sd(flt),2) / ((1-pow(rho_y,2))*(1-pow(rho_a,2))),0.5);
4208 // SEPARABLE(f, g): f correlates the last array index, g the first; tmp_AR2 is
4209 // (bin, year), so the year correlation goes first.
4210 jnll_comp(JNLL_SEL_DEV, flt) += SCALE(SEPARABLE(AR1(rho_y),AR1(rho_a)), Sigma_sig_sel)(tmp_AR2);
4211 }
4212 }
4213
4214 // 3D AR1 (7): GMRF over bin, year and cohort (the weight-at-age GMRF of Cheng et al. 2023). Sel_curve_pen1-3
4215 // carry the bin, year and cohort correlations.
4216 if(flt_sel_type(flt) == 7){
4217 int n_sel_bins = flt_n_sel_bins(flt);
4218 int num_rows = n_sel_bins * nyrs_hind;
4219 matrix<Type> ay_index(num_rows, 2);
4220
4221 for(sex = 0; sex < nsex(sp); sex ++){
4222
4223 int row = 0;
4224 for (int year = 1; year <= nyrs_hind; ++year) {
4225 for (int bin = 1; bin <= n_sel_bins; ++bin) {
4226 ay_index(row, 0) = bin;
4227 ay_index(row, 1) = year;
4228 row++;
4229 }
4230 }
4231
4232 // Pass (bin, year, cohort): construct_Q() (GMRF_WAA) applies rho_y across bins and rho_a
4233 // across years, whatever the names say. Do not "correct" the order to match the names.
4234 Eigen::SparseMatrix<Type> Q_sparse(num_rows, num_rows);
4235 Q_sparse = construct_Q(nyrs_hind, n_sel_bins, ay_index,
4236 sel_curve_pen(flt, 0), sel_curve_pen(flt, 1), sel_curve_pen(flt, 2), // natural scale
4237 log(square(sel_dev_sd(flt))), 0); // conditional variance
4238
4239 array<Type> tmp_AR2(n_sel_bins, nyrs_hind);
4240 for (int bin = 0; bin < n_sel_bins; bin++) {
4241 for (int yr = 0; yr < nyrs_hind; yr++) {
4242 tmp_AR2(bin, yr) = sel_coff_dev(flt, sex, bin, yr);
4243 }
4244 }
4245 jnll_comp(JNLL_SEL_DEV, flt) += GMRF(Q_sparse)(tmp_AR2);
4246 }
4247 }
4248 }
4249 }
4250
4251
4252 // 13.8. CATCHABILITY (JNLL_Q_PRIOR, JNLL_Q_DEV)
4253 // Charged once per Catchability_index, on the lead fleet.
4254 for(flt = 0; flt < n_flt; flt++){
4255 if(flt_q_lead(flt) == 1){
4256
4257 // Lognormal prior (Catchability 2, Estimated-with-prior). Catchability_init is the
4258 // mean of q when bias_adjust_proc = 1, the median when 0.
4259 if( est_index_q(flt) == 2){
4260 jnll_comp(JNLL_Q_PRIOR, flt) -= dnorm(index_log_q(flt), index_log_q_prior(flt) - bias_adjust_proc*square(index_q_sd(flt))/2.0, index_q_sd(flt), true);
4261 }
4262
4263 // Deviates, on an estimated q (Catchability 1 or 2) of a survey or CPUE fleet.
4264 bool q_devs = (flt_type(flt) > 0) && ((est_index_q(flt) == 1) || (est_index_q(flt) == 2));
4265
4266 // IID (1); the retired AR1 (2) is scored as IID.
4267 if(q_devs && ((index_varying_q(flt) == 1) || (index_varying_q(flt) == 2))){
4268 for(yr = 0; yr < nyrs_hind; yr++){
4269 jnll_comp(JNLL_Q_DEV, flt) -= dnorm(index_q_dev(flt, yr), Type(0.0), index_q_dev_sd(flt), true );
4270 }
4271 }
4272
4273 // RandomWalk (4)
4274 if(q_devs && (index_varying_q(flt) == 4)){
4275 for(yr = 1; yr < nyrs_hind; yr++){
4276 jnll_comp(JNLL_Q_DEV, flt) -= dnorm(index_q_dev(flt, yr) - index_q_dev(flt, yr-1), Type(0.0), index_q_dev_sd(flt), true );
4277 }
4278 }
4279 }
4280 }
4281
4282
4283 // 13.9. RECRUITMENT (JNLL_SRR_PRIOR, JNLL_INIT_DEV, JNLL_REC_DEV, JNLL_SRR_PENALTY)
4284 // Lognormal deviates are centred at -sigma^2/2 when bias_adjust_proc = 1, so the
4285 // expected recruitment is the curve's (mean-unbiased); at 0 the curve is the median.
4286 for(sp = 0; sp < nspp; sp++) {
4287 penalty = 0.0;
4288 // Input numbers-at-age (estDynamics > 0) have no stock-recruit curve to penalize.
4289 int srr_terms_on = (estDynamics(sp) == 0);
4290
4291 // Beverton-Holt steepness prior: lognormal (srr_prior is its mean or median, as above)...
4292 if(srr_terms_on && (srr_est_mode == 2) & ((srr_pred_fun == 2) | (srr_pred_fun == 3))){
4293 jnll_comp(JNLL_SRR_PRIOR, sp) -= dnorm(log(steepness(sp, 0)), log(srr_prior(sp)) - bias_adjust_proc*square(srr_prior_sd(sp))/2.0, srr_prior_sd(sp), true);
4294 }
4295
4296 // ...or beta, from the prior mean and sd.
4297 if(srr_terms_on && (srr_est_mode == 3) & ((srr_pred_fun == 2) | (srr_pred_fun == 3))){
4298 Type beta_alpha = ((1 - srr_prior(sp))/ square(srr_prior_sd(sp)) - 1/srr_prior(sp)) * square(srr_prior(sp));
4299 Type beta_beta = beta_alpha * (1/srr_prior(sp) - 1);
4300 jnll_comp(JNLL_SRR_PRIOR, sp) -= dbeta(steepness(sp, 0), beta_alpha, beta_beta, true);
4301 }
4302
4303 // Ricker alpha prior, lognormal.
4304 if(srr_terms_on && (srr_est_mode == 2) & ((srr_pred_fun == 4) | (srr_pred_fun == 5))){
4305 jnll_comp(JNLL_SRR_PRIOR, sp) -= dnorm(rec_pars(sp, 1), log(srr_prior(sp)) - bias_adjust_proc*square(srr_prior_sd(sp))/2.0, srr_prior_sd(sp), true);
4306 }
4307
4308 // Ricker: penalty when 1 / beta (spawning biomass at peak recruitment) exceeds
4309 // Bmsy_lim / 1e6.
4310 if(srr_terms_on && (!isNA(Bmsy_lim(sp))) && ((srr_pred_fun == 4) || (srr_pred_fun == 5))){
4311 Type bmsy = 1.0/exp(rec_pars(sp, 2));
4312 bmsy = posfun(Bmsy_lim(sp)/Type(1000000.0) - bmsy, Type(0.001), penalty);
4313 jnll_comp(JNLL_SRR_PRIOR, sp) += 100 * penalty;
4314 }
4315
4316 // Initial-abundance deviates; none under FreeParams (0), Equilibrium (1) or
4317 // OffsetEquilibrium (5).
4318 if(initMode > 1 && initMode != 5){
4319 for(age = 1; age < nages(sp); age++) {
4320 jnll_comp(JNLL_INIT_DEV, sp) -= dnorm( init_dev(sp, age - 1), -bias_adjust_proc*square(R_sd(sp))/2.0, R_sd(sp), true);
4321 }
4322 }
4323
4324 // Recruitment deviates.
4325 for(yr = 0; yr < nyrs_hind; yr++) {
4326 jnll_comp(JNLL_REC_DEV, sp) -= dnorm( rec_dev(sp, yr), -bias_adjust_proc*square(R_sd(sp))/2.0, R_sd(sp), true);
4327 }
4328
4329 // Stock-recruit curve penalty (AMAK/Ianelli): recruitment is estimated about a mean
4330 // (srr_fun 0) and a curve is fitted to it (srr_pred_fun > 0). R_hat is the mean of R
4331 // when bias_adjust_proc = 1 (Ianelli pm.tpl, Dorn 2002), the median (AMAK) when 0.
4332 if(srr_terms_on && (srr_fun == 0) & (srr_pred_fun > 0)){
4333 for(yr = srr_hat_styr; yr <= srr_hat_endyr; yr++) {
4334 jnll_comp(JNLL_SRR_PENALTY, sp) -= dnorm( log(R(sp, yr)), log(R_hat(sp,yr)) - bias_adjust_proc*square(R_sd(sp))/2.0, R_sd(sp), true);
4335 }
4336 }
4337 }
4338
4339
4340 // 13.10. REFERENCE POINT PENALTIES (JNLL_REFPT_PENALTY)
4341 // Each finds the F that meets a harvest-control-rule target by penalizing the miss.
4342
4343 // HCR 1 (CMSY): maximize total terminal-year catch across species, subject to
4344 // SSB depletion staying above Plimit.
4345 Type CMSY = 0;
4346 if(HCR == 1){
4347 for(fsh_ind = 0; fsh_ind < catch_ctl.rows(); fsh_ind++){
4348 flt = catch_ctl(fsh_ind, 0) - 1;
4349 sp = catch_ctl(fsh_ind, 1) - 1;
4350 flt_yr = catch_ctl(fsh_ind, 2);
4351 if((flt_type(flt) == 1) && (forecast(sp) == 1) && (estDynamics(sp) == 0)){
4352 if(flt_yr == projyr){
4353 CMSY += catch_hat(fsh_ind);
4354 }
4355 }
4356 }
4357
4358 jnll_comp(JNLL_REFPT_PENALTY, 0) = - square(CMSY/1000000.0);
4359
4360 for(sp = 0; sp < nspp; sp++) {
4361 if((forecast(sp) == 1) && (estDynamics(sp) == 0)){
4362 penalty = 0.0;
4363 Type nothing_useful = posfun( (ssb_depletion(sp, nyrs-1) - Plimit(sp)), Type(0.0001), penalty); (void) nothing_useful;
4364 jnll_comp(JNLL_REFPT_PENALTY, sp) += 500.0 * square(CMSY/1000.0) * penalty;
4365 }
4366 }
4367 }
4368
4369 for(sp = 0; sp < nspp; sp++) {
4370 // Single species: Flimit and Ftarget are SPR fractions, except under HCR 3, where
4371 // Ftarget is a fraction of SB0.
4372 if((forecast(sp) == 1) && (msmMode == 0) && (estDynamics(sp) == 0) && ((DynamicHCR == 0) || (DynamicHCR == 1))){
4373
4374 // ConstantF (2): Flimit is still estimated, for reference.
4375 if(HCR == 2){
4376 jnll_comp(JNLL_REFPT_PENALTY, sp) += 200*square((SPRlimit(sp)/SPR0(sp))-Flimit_percent(sp));
4377 }
4378
4379 // ConstantFSSB (3): SSB at Ftarget of SB0 in the last projection year (static),
4380 // or every year against dynamic SB0.
4381 if(HCR == 3){
4382 if(DynamicHCR == 0){
4383 jnll_comp(JNLL_REFPT_PENALTY, sp) += 200*square((ssb(sp, nyrs-1)/SB0(sp, nyrs-1))-Ftarget_percent(sp));
4384 } else {
4385 for(yr = 1; yr < nyrs; yr++){ // No initial abundance
4386 jnll_comp(JNLL_REFPT_PENALTY, sp) += 200*square((DynamicSBF(sp, yr)/DynamicSB0(sp, yr))-Ftarget_percent(sp));
4387 }
4388 }
4389 }
4390
4391 // ConstantFSPR, NPFMC, PFMC, SESSF (4-7): SPR-based limit and target.
4392 if(HCR > 3){
4393 jnll_comp(JNLL_REFPT_PENALTY, sp) += 200*square((SPRlimit(sp)/SPR0(sp))-Flimit_percent(sp));
4394 jnll_comp(JNLL_REFPT_PENALTY, sp) += 200*square((SPRtarget(sp)/SPR0(sp))-Ftarget_percent(sp));
4395 }
4396 }
4397
4398 // Multispecies: per-recruit quantities are undefined under predation, so each
4399 // target is a fraction of SB0 in the last projection year (2 and 6 Flimit, 3 Ftarget).
4400 if((forecast(sp) == 1) && (msmMode > 0) && (estDynamics(sp) == 0)){
4401 if(HCR == 2){
4402 jnll_comp(JNLL_REFPT_PENALTY, sp) += 200*square((ssb(sp, nyrs-1)/SB0(sp, nyrs-1))-Flimit_percent(sp));
4403 }
4404 if(HCR == 3){
4405 jnll_comp(JNLL_REFPT_PENALTY, sp) += 200*square((ssb(sp, nyrs-1)/SB0(sp, nyrs-1))-Ftarget_percent(sp));
4406 }
4407 if(HCR == 6){
4408 jnll_comp(JNLL_REFPT_PENALTY, sp) += 200*square((ssb(sp, nyrs-1)/SB0(sp, nyrs-1))-Flimit_percent(sp));
4409 }
4410 }
4411 }
4412
4413
4414 // 13.11. FLOOR PENALTIES (JNLL_ZERO_N_PENALTY): what posfun() adds in the dynamics
4415 // when it holds numbers-at-age, or recruitment terms, above zero.
4416 for(sp = 0; sp < nspp; sp++){
4417 if(estDynamics(sp) == 0){
4418 jnll_comp(JNLL_ZERO_N_PENALTY, sp) += zero_N_pen(sp);
4419 }
4420 }
4421
4422
4423 // 13.12. NATURAL MORTALITY (JNLL_M_PRIOR, JNLL_M_RE)
4424 for(sp = 0; sp < nspp; sp++) {
4425
4426 // Lognormal prior: M_prior is its mean when bias_adjust_proc = 1, its median when 0.
4427 Type M_prior_mean = log(M_prior(sp)) - bias_adjust_proc*square(M_prior_sd(sp)) / 2.0;
4428
4429 // On the estimated M1 only: one value (M1_model 1), one per sex (2), or one per sex
4430 // and age (3).
4431 if( (M1_use_prior(sp) == 1) && (M2_use_prior(sp) == 0) ) {
4432 int nsex_tmp = (M1_model(sp) > 1) ? nsex(sp) : 1;
4433 int nage_tmp = (M1_model(sp) == 3) ? nages(sp) : 1;
4434
4435 for(int sex = 0; sex < nsex_tmp; sex++) {
4436 for(int age = 0; age < nage_tmp; age++) {
4437 jnll_comp(JNLL_M_PRIOR, sp) -= dnorm(log_M1(sp, sex, age), M_prior_mean, M_prior_sd(sp), true);
4438 }
4439 }
4440 }
4441
4442 // On total M = M1 + M2, every sex, age and hindcast year.
4443 // FIXME: sex-specific prior?
4444 if( M2_use_prior(sp) == 1 ) {
4445 for(int sex = 0; sex < nsex(sp); sex++) {
4446 for(int age = 0; age < nages(sp); age++) {
4447 for(int yr = 0; yr < nyrs_hind; yr++) {
4448 jnll_comp(JNLL_M_PRIOR, sp) -= dnorm(log(M_at_age(sp, sex, age, yr)), M_prior_mean, M_prior_sd(sp), true);
4449 }
4450 }
4451 }
4452 }
4453
4454 // M1 random effects (M1_re): 1 IID by age, 2 IID by year, 3 IID by age and year,
4455 // 4 AR1 by age, 5 AR1 by year, 6 2D AR1; the IID codes are AR1 with rho mapped at
4456 // its start. sigma (the conditional sd) and rho are per species, shared by sex;
4457 // the deviates are per sex under M1_model 2. SCALE() takes the marginal sd.
4458 int num_re_sexes = (M1_model(sp) == 2 && nsex(sp) > 1) ? 2 : 1;
4459
4460 // By age, constant over years.
4461 if( (M1_re(sp) == 1) || (M1_re(sp) == 4) ) {
4462 Type sigma_M = exp(M1_dev_log_sd(sp, 0));
4463 Type rho_M_a = rho_trans(M1_rho(sp, 0, 0));
4464 Type Sigma_M = pow(pow(sigma_M, 2) / (1.0 - pow(rho_M_a, 2)), 0.5);
4465 vector<Type> M_re_age(nages(sp));
4466
4467 for(int sex = 0; sex < num_re_sexes; sex++) {
4468 for(int age = 0; age < nages(sp); age++) {
4469 M_re_age(age) = log_M1_dev(sp, sex, age, 0);
4470 }
4471 jnll_comp(JNLL_M_RE, sp) += SCALE(AR1(rho_M_a), Sigma_M)(M_re_age);
4472 }
4473 }
4474
4475 // By year, constant over ages.
4476 if( (M1_re(sp) == 2) || (M1_re(sp) == 5) ) {
4477 Type sigma_M = exp(M1_dev_log_sd(sp, 0));
4478 Type rho_M_y = rho_trans(M1_rho(sp, 0, 1));
4479 Type Sigma_M = pow(pow(sigma_M, 2) / (1.0 - pow(rho_M_y, 2)), 0.5);
4480 vector<Type> M_re_yr(nyrs_hind);
4481
4482 for(int sex = 0; sex < num_re_sexes; sex++) {
4483 for(int yr = 0; yr < nyrs_hind; yr++) {
4484 M_re_yr(yr) = log_M1_dev(sp, sex, 0, yr);
4485 }
4486 jnll_comp(JNLL_M_RE, sp) += SCALE(AR1(rho_M_y), Sigma_M)(M_re_yr);
4487 }
4488 }
4489
4490 // By age and year.
4491 if( (M1_re(sp) == 3) || (M1_re(sp) == 6) ) {
4492 Type sigma_M = exp(M1_dev_log_sd(sp, 0));
4493 Type rho_M_a = rho_trans(M1_rho(sp, 0, 0));
4494 Type rho_M_y = rho_trans(M1_rho(sp, 0, 1));
4495 Type Sigma_M = pow(pow(sigma_M, 2) / ((1.0 - pow(rho_M_y, 2)) * (1.0 - pow(rho_M_a, 2))), 0.5);
4496 array<Type> M_re_a_yr(nages(sp), nyrs_hind);
4497
4498 for(int sex = 0; sex < num_re_sexes; sex++) {
4499 for(int age = 0; age < nages(sp); age++) {
4500 for(int yr = 0; yr < nyrs_hind; yr++) {
4501 M_re_a_yr(age, yr) = log_M1_dev(sp, sex, age, yr);
4502 }
4503 }
4504 // SEPARABLE(f, g): f correlates the last array index, g the first; the array is
4505 // (age, year), so the year correlation goes first.
4506 jnll_comp(JNLL_M_RE, sp) += SCALE(SEPARABLE(AR1(rho_M_y), AR1(rho_M_a)), Sigma_M)(M_re_a_yr);
4507 }
4508 }
4509 }
4510
4511
4512 // 13.13. LINKAGE PRIORS (JNLL_LINKAGE_PRIOR)
4513 // Families are in linkage_log_prior() (likelihood.hpp). A prior on a log-stored base (R0,
4514 // alpha, M1, K, q, slope, apical) is on its natural scale; one on a sel inflection or
4515 // DoubleNormalSS3 parameter is on its stored scale. Most (Intercept) rows are held at 0 (2.3b), so
4516 // the prior reads the base parameter they stand in for; a slope row reads its coefficient.
4517 for (int i = 0; i < beta_linkage.size(); ++i) {
4518 int fam = linkage_prior_family(i);
4519 if (fam == 0) continue; // 0 = no prior
4520 Type p1 = linkage_prior_p1(i);
4521 Type p2 = linkage_prior_p2(i);
4522 int slot_col = linkage_species(i) - 1; // jnll column: the row's species, or 0 if it names none
4523 if (slot_col < 0) slot_col = 0; // all species => column 0
4524 if (slot_col >= n_col) slot_col = 0;
4525
4526 Type b = beta_linkage(i);
4527 bool base_is_log = true; // most base parameters are stored as logs
4528 if (linkage_is_intercept(i) == 1) {
4529 // Species/sex/age 0 means "all"; the prior reads the first level's base parameter.
4530 int sp_in = linkage_species(i);
4531 int sx_in = linkage_sex(i);
4532 int ab_in = linkage_age_bin(i);
4533 int sp_idx = (sp_in == 0) ? 0 : (sp_in - 1);
4534 int sx_idx = (sx_in == 0) ? 0 : (sx_in - 1);
4535 int ab_idx = (ab_in == 0) ? 0 : (ab_in - 1);
4536
4537 int proc = linkage_process(i);
4538 int param = linkage_param(i);
4539 if (proc == RCEATTLE_PROC_RECRUIT) {
4540 // rec_pars columns: log R0, log alpha, log Beta (stock-recruit). R_init has no base parameter;
4541 // its intercept is the level, so its prior stays on beta_linkage(i).
4542 if (param != RCEATTLE_REC_R_INIT) {
4543 b = rec_pars(sp_idx, param);
4544 }
4545 } else if (proc == RCEATTLE_PROC_M) {
4546 b = log_M1(sp_idx, sx_idx, ab_idx);
4547 } else if (proc == RCEATTLE_PROC_GROWTH) {
4548 // K, L1, Linf, m in log_growth_pars; then sd_L1, sd_Linf in growth_log_sd.
4549 if (param < RCEATTLE_N_GROWTH_PARAMS) {
4550 b = log_growth_pars(sp_idx, sx_idx, param);
4551 } else {
4552 b = growth_log_sd(sp_idx, sx_idx, param - RCEATTLE_N_GROWTH_PARAMS);
4553 }
4554 } else if (proc == RCEATTLE_PROC_Q) {
4555 // Fleet-indexed: log q.
4556 int fl_in = linkage_fleet(i);
4557 int fl_idx = (fl_in == 0) ? 0 : (fl_in - 1);
4558 b = index_log_q(fl_idx);
4559 } else if (proc == RCEATTLE_PROC_COMP) {
4560 // Dirichlet-multinomial log theta: comp and CAAL by fleet, diet by predator.
4561 int fl_in = linkage_fleet(i);
4562 int fl_idx = (fl_in == 0) ? 0 : (fl_in - 1);
4563 if (param == RCEATTLE_COMP_THETA_COMP) b = comp_weights(fl_idx);
4564 else if (param == RCEATTLE_COMP_THETA_CAAL) b = caal_weights(fl_idx);
4565 else if (param == RCEATTLE_COMP_THETA_DIET) b = diet_comp_weights(sp_idx);
4566 } else if (proc == RCEATTLE_PROC_SEL) {
4567 // Parametric selectivity, element 0 ascending, 1 descending. The (Intercept)
4568 // adds no offset, so the prior regularizes the base parameter (as in Cole
4569 // Monnahan's GOA pollock priors). RCEATTLE_SEL_COFF has no scalar base and is
4570 // refused by .check_sel_linkage_support().
4571 int fl_in = linkage_fleet(i);
4572 int fl_idx = (fl_in == 0) ? 0 : (fl_in - 1);
4573 if (param == RCEATTLE_SEL_SLP_ASC || param == RCEATTLE_SEL_SLP_DESC) {
4574 b = log_sel_slp(param - RCEATTLE_SEL_SLP_ASC, fl_idx, sx_idx); // log slope
4575 } else if (param == RCEATTLE_SEL_INF_ASC || param == RCEATTLE_SEL_INF_DESC) {
4576 // As stored: an inflection, DoubleNormal's peak or logit floor, or LogisticPM's
4577 // log first-bin selectivity.
4578 b = sel_inf(param - RCEATTLE_SEL_INF_ASC, fl_idx, sx_idx);
4579 base_is_log = false;
4580 } else if (param == RCEATTLE_SEL_APICAL) {
4581 b = log_sel_apical(fl_idx, sx_idx); // log apical multiplier; 0 = a multiplier of 1
4582 } else if (param >= RCEATTLE_SEL_DN_PEAK && param <= RCEATTLE_SEL_END_LOGIT) {
4583 // DoubleNormalSS3, on SS3's own scale (peak in bins or cm, log widths, logits),
4584 // where an SS3 control file puts its priors.
4585 b = sel_dn6(param - RCEATTLE_SEL_DN_PEAK, fl_idx, sx_idx);
4586 base_is_log = false;
4587 }
4588 }
4589 }
4590
4591 Type log_prior = linkage_log_prior(fam, b, (linkage_is_intercept(i) == 1) && base_is_log,
4592 p1, p2, bias_adjust_proc);
4593 jnll_comp(JNLL_LINKAGE_PRIOR, slot_col) -= log_prior;
4594 unweighted_jnll_comp(JNLL_LINKAGE_PRIOR, slot_col) -= log_prior;
4595 }
4596
4597 // Priors on each random-effect group's sd, from linkage_spec(priors = list(sigma = )).
4598 // FIXME(jacobian): normal, gamma and beta read the sd while log_sigma is estimated,
4599 // with no Jacobian -- a penalty, not a proper prior. Add log_sigma for a density.
4600 if (log_sigma_linkage.size() > 0) {
4601 for (int g = 0; g < log_sigma_linkage.size(); ++g) {
4602 int fam = linkage_re_sigma_prior_family(g);
4603 if (fam == 0) continue; // 0 = no prior
4604 Type sd = exp(log_sigma_linkage(g));
4605 Type log_prior = linkage_log_prior(fam, sd, false, linkage_re_sigma_prior_p1(g),
4606 linkage_re_sigma_prior_p2(g), bias_adjust_proc);
4607 jnll_comp(JNLL_LINKAGE_PRIOR, 0) -= log_prior;
4608 unweighted_jnll_comp(JNLL_LINKAGE_PRIOR, 0) -= log_prior;
4609 }
4610 }
4611
4612 // Priors on each AR1 group's correlation rho in (-1, 1), from priors = list(rho = ):
4613 // normal on rho, or beta on (rho + 1) / 2.
4614 // FIXME(jacobian): as for sigma, no rho_trans Jacobian.
4615 if (trans_rho_linkage.size() > 0) {
4616 for (int g = 0; g < linkage_re_rho.size(); ++g) {
4617 int fam = linkage_re_rho_prior_family(g);
4618 if ((fam != 1) && (fam != 4)) continue; // only normal (1) and beta (4) are read for rho
4619 Type rho = rho_trans(trans_rho_linkage(linkage_re_rho(g)));
4620 Type x = (fam == 4) ? (rho + Type(1)) / Type(2) : rho;
4621 Type log_prior = linkage_log_prior(fam, x, false, linkage_re_rho_prior_p1(g),
4622 linkage_re_rho_prior_p2(g), bias_adjust_proc);
4623 jnll_comp(JNLL_LINKAGE_PRIOR, 0) -= log_prior;
4624 unweighted_jnll_comp(JNLL_LINKAGE_PRIOR, 0) -= log_prior;
4625 }
4626 }
4627
4628
4629 // 13.14. LINKAGE RANDOM EFFECTS (JNLL_LINKAGE_RE)
4630 // Group g's deviations u, in time order: IID u_t ~ N(0, sigma_g); random walk
4631 // u_t - u_{t-1} ~ N(0, sigma_g); or stationary AR1, marginal sd sigma_g
4632 // (rceattle_re_group_nll()). Integrated and penalized deviations share this density.
4633 for (int grp = 0; grp < log_sigma_linkage.size(); ++grp) {
4634 vector<int> slots = rceattle_group_slots(linkage_re_sigma, grp);
4635 int len = slots.size();
4636 if (len == 0) continue;
4637 vector<Type> re(len);
4638 for (int t = 0; t < len; ++t) re(t) = beta_linkage_re_all(slots(t));
4639
4640 int st = linkage_re_struct(grp);
4641 Type sigma = exp(log_sigma_linkage(grp));
4642 Type rho = (st == RCEATTLE_RE_AR1) ? rho_trans(trans_rho_linkage(linkage_re_rho(grp))) : Type(0);
4643 rceattle_re_group_nll(st, re, sigma, rho,
4644 jnll_comp(JNLL_LINKAGE_RE, 0), unweighted_jnll_comp(JNLL_LINKAGE_RE, 0));
4645
4646 // Rogers QAR1: covariate x(t) ~ N(re(t), obs_sd), obs_sd fixed unless obs_sd_est =
4647 // TRUE. Tying re to x identifies beta_linkage_obs, which multiplies re (5.2b).
4648 if (linkage_re_obs(grp) >= 0) {
4649 Type osd = exp(log_obs_sd_linkage(linkage_re_obs(grp)));
4650 for (int t = 0; t < len; ++t) {
4651 int s = slots(t);
4652 if (linkage_re_obs_mask(s) == 0) continue; // no observation that year
4653 if (osa_mode == 0) {
4654 Type log_dens = dnorm(linkage_re_obs_value(s), re(t), osd, true);
4655 jnll_comp(JNLL_LINKAGE_RE, 0) -= log_dens;
4656 unweighted_jnll_comp(JNLL_LINKAGE_RE, 0) -= log_dens;
4657 } else {
4658 // OSA (osa_mode 1-2): the same x(t), from obsvec so oneStepPredict() can hold
4659 // it out through keep(pos); residualized against re(t), as WHAM's Ecov.
4660 int pos = linkage_re_obsvec_idx(s);
4661 if (pos >= 0) {
4662 jnll_comp(JNLL_LINKAGE_RE, 0) -= keep(pos) * dnorm(obsvec(pos), re(t), osd, true);
4663 unweighted_jnll_comp(JNLL_LINKAGE_RE, 0) -= keep(pos) * dnorm(obsvec(pos), re(t), osd, true);
4664 // The CDF term is not a likelihood, so only jnll_comp gets it here.
4665 if (osa_mode == 2) {
4666 jnll_comp(JNLL_LINKAGE_RE, 0) -= osa_norm_cdf_terms(
4667 obsvec(pos), re(t), osd, keep.cdf_lower(pos), keep.cdf_upper(pos));
4668 }
4669 }
4670 }
4671 }
4672 }
4673 }
4674
4675
4676 // 13.15. UNWEIGHTED COMPONENTS
4677 // jnll_comp without data weights. In ordinary fitting the composition, CAAL and
4678 // stomach rows were written unweighted above (0 under OSA), and the linkage rows to
4679 // both; every other row carries no data weight, so it is copied.
4680 for(flt = 0; flt < n_col; flt++){
4681 for(int ind = 0; ind < JNLL_N_ROWS; ind++){
4682 bool written_above = (ind == JNLL_COMP) || (ind == JNLL_CAAL) || (ind == JNLL_STOMACH) ||
4683 (ind == JNLL_LINKAGE_PRIOR) || (ind == JNLL_LINKAGE_RE);
4684 if(!written_above){
4685 unweighted_jnll_comp(ind, flt) = jnll_comp(ind, flt);
4686 }
4687 }
4688 }
4689
4690
4691 /** ------------------------------------------------------------------------ //
4692 // 14. REPORT SECTION //
4693 * ------------------------------------------------------------------------- */
4694
4695 // 14.1. Population components
4696 REPORT( pop_scalar );
4697 ADREPORT( pop_scalar );
4698 REPORT( avg_R );
4699 REPORT( Z_at_age );
4700 REPORT( N_at_age );
4701 REPORT( avgN_at_age );
4702 REPORT( biomass_at_age );
4703 REPORT( biomass_depletion );
4704 REPORT( ssb_depletion );
4705 REPORT( biomass );
4706 REPORT( ssb );
4707 REPORT( exploitable_biomass );
4708 REPORT(R_sd);
4709 REPORT( R0 );
4710 REPORT( R_init );
4711 REPORT( R );
4712 REPORT( R_hat );
4713 REPORT( M_at_age );
4714 //REPORT( mature_females );
4715 //REPORT( sex_ratio_hat );
4716 //REPORT( N_at_age_dB0);
4717 //REPORT( N_at_age_dBF);
4718 // ADREPORT( M_at_age ); // no SEs: see ?plot_mortality
4719 REPORT( weight_hat );
4720 REPORT( growth_matrix );
4721 REPORT( length_hat );
4722
4723 ADREPORT( biomass );
4724 ADREPORT( ssb );
4725
4726 // -- Secondary display series, so add_ci = TRUE can draw an interval at all.
4727 // Natural scale ONLY: exploitable_biomass sums over fisheries alone, so it is
4728 // exactly 0 for a survey-only species or proj_F_prop = 0, and the depletions
4729 // divide by B0 / SB0. log() of either puts -Inf on the tape and NaNs the whole
4730 // sdreport; the plotters recover sd(log x) = sd(x)/x instead.
4731 ADREPORT( exploitable_biomass );
4732 ADREPORT( biomass_depletion );
4733 ADREPORT( ssb_depletion );
4734
4735 // -- Log-scale derived series.
4736 // sdreport linearizes once about the MLE, so its SD is exact only for a linear function
4737 // of the parameters. These are built multiplicatively (R = R0 * exp(rec_dev); n-at-age
4738 // is a product of survivals), so log(x) is near-linear and exp(log(x) +/- z * sd) is
4739 // right-skewed and cannot cross zero. The log SD is also the CV, the form the ABC / OFL
4740 // buffer wants. The natural-scale ADREPORTs stay so existing sdrep$value callers work.
4741 matrix<Type> log_biomass = biomass; log_biomass = log(biomass.array());
4742 matrix<Type> log_ssb = ssb; log_ssb = log(ssb.array());
4743 matrix<Type> log_R = R; log_R = log(R.array());
4744 REPORT( log_biomass );
4745 REPORT( log_ssb );
4746 REPORT( log_R );
4747 ADREPORT( log_biomass );
4748 ADREPORT( log_ssb );
4749 ADREPORT( log_R );
4750 ADREPORT( R_sd );
4751 ADREPORT( R );
4752
4753 // -- Log selectivity-at-age, for a delta-method interval on the curve. Log and not
4754 // logit, because the non-parametric forms normalize to a MEAN of one, so sel_at_age
4755 // routinely exceeds one. Gated because the delta method costs every reported value
4756 // against every parameter; see ?fit_control.
4757 //
4758 // Only estimated, age-based lead fleets, from their first selected bin: those cells
4759 // cannot be a structural zero, and one log(0) = -Inf on the tape turns EVERY sdreport
4760 // quantity to NaN, biomass and SSB included. The four routes to a structural zero are
4761 // enumerated in ?fit_control and all read from the data, so the reported SET never
4762 // depends on a parameter value. A reported VALUE can still underflow -- a narrow dome
4763 // puts exp(-x^2/2) below 1e-308 many bins from its peak -- so the log is floored with
4764 // max2(), exact above the floor. log_sel_at_age_index carries each row's fleet, sex,
4765 // absolute age and calendar year, since which cells are reported depends on the model.
4766 if(adreport_sel == 1){
4767 // Clamp bin_first_selected to [0, nages]: a 0 in fleet_control arrives as -1,
4768 // and the template builds with safebounds = FALSE.
4769 vector<int> sel_first_bin(n_flt); sel_first_bin.setZero();
4770 vector<int> sel_rep_bins(n_flt); sel_rep_bins.setZero();
4771 for(int flt = 0; flt < n_flt; flt++){
4772 if((flt_type(flt) <= 0) || (flt_sel_lead(flt) != 1) ||
4773 (flt_sel_type(flt) == 0) || (flt_sel_dim(flt) == 1)) continue;
4774 int n_age = nages(flt_spp(flt));
4775 int first = bin_first_selected(flt);
4776 if(first < 0) first = 0;
4777 if(first > n_age) first = n_age;
4778 sel_first_bin(flt) = first;
4779 sel_rep_bins(flt) = n_age - first;
4780 }
4781
4782 int n_sel = 0;
4783 for(int flt = 0; flt < n_flt; flt++){
4784 n_sel += nsex(flt_spp(flt)) * sel_rep_bins(flt) * nyrs_hind;
4785 }
4786
4787 vector<Type> log_sel_at_age(n_sel); log_sel_at_age.setZero();
4788 matrix<Type> log_sel_at_age_index(n_sel, 4); log_sel_at_age_index.setZero();
4789
4790 int i_sel = 0;
4791 for(int flt = 0; flt < n_flt; flt++){
4792 if(sel_rep_bins(flt) == 0) continue;
4793 int sel_sp = flt_spp(flt);
4794 for(int sel_sex = 0; sel_sex < nsex(sel_sp); sel_sex++){
4795 for(int sel_age = sel_first_bin(flt); sel_age < nages(sel_sp); sel_age++){
4796 for(int sel_yr = 0; sel_yr < nyrs_hind; sel_yr++){
4797 log_sel_at_age(i_sel) = log(max2(sel_at_age(flt, sel_sex, sel_age, sel_yr),
4798 Type(1e-300)));
4799 log_sel_at_age_index(i_sel, 0) = Type(flt + 1);
4800 log_sel_at_age_index(i_sel, 1) = Type(sel_sex + 1);
4801 log_sel_at_age_index(i_sel, 2) = Type(minage(sel_sp) + sel_age);
4802 log_sel_at_age_index(i_sel, 3) = Type(styr + sel_yr);
4803 i_sel++;
4804 }
4805 }
4806 }
4807 }
4808
4809 REPORT( log_sel_at_age );
4810 REPORT( log_sel_at_age_index );
4811 ADREPORT( log_sel_at_age );
4812 }
4813
4814
4815 // -- 14.2. Biological reference points
4816 REPORT( NByageF );
4817 REPORT( NByage0);
4818 REPORT( NbyageSPR);
4819 REPORT( B0 );
4820 REPORT( SB0 );
4821 REPORT( SBF );
4822 REPORT( DynamicB0 );
4823 REPORT( DynamicSB0 );
4824 REPORT( DynamicSBF );
4825 REPORT( SPR0 );
4826 REPORT( SPRFinit );
4827 REPORT( SPRlimit );
4828 REPORT( SPRtarget );
4829 REPORT( steepness );
4830 REPORT( proj_F );
4831 REPORT( Ftarget );
4832 REPORT( Flimit );
4833
4834 // -- 14.3. Selectivity
4835 REPORT( sel_at_age );
4836 REPORT( sel_at_length );
4837
4838
4839 // -- 14.4. Survey components
4840 REPORT( index_hat );
4841 REPORT( index_sd );
4842 REPORT( index_q );
4843 vector<Type> log_index_hat = index_hat; log_index_hat = log(index_hat.array());// Log predicted index
4844 REPORT( log_index_hat );
4845 ADREPORT( log_index_hat );
4846 if(adreport_catch == 1){
4847 ADREPORT( catch_hat ); // mt, or thousands of fish
4848 }
4849
4850 // -- 14.4b. Formula-linkage effect sizes: the estimated coefficients, the random-effect
4851 // deviations and the Rogers (2024) QAR1 effect size, so a user can read the *effect*
4852 // and, through ADREPORT, its uncertainty -- not just the realized parameter (index_q
4853 // above). All may be length 0 (no linkages), in which case they report nothing.
4854 REPORT( beta_linkage );
4855 ADREPORT( beta_linkage );
4856 REPORT( beta_linkage_re );
4857 REPORT( beta_linkage_re_pen );
4858 // Slot-ordered deviations across both vectors, so a caller can read a group's
4859 // walk without knowing how it is stored.
4860 REPORT( beta_linkage_re_all );
4861 REPORT( beta_linkage_obs );
4862 ADREPORT( beta_linkage_obs );
4863
4864
4865 // -- 14.5. Fishery components
4866 REPORT( F_spp );
4867 REPORT( F_flt );
4868 REPORT( F_flt_age );
4869 REPORT( F_at_age );
4870 REPORT( catch_hat );
4871 REPORT( max_catch_hat );
4872 REPORT( catch_sd );
4873 REPORT( catch_analytical_sd );
4874
4875
4876 // 14.6. Age/length composition
4877 REPORT( age_obs_hat );
4878 REPORT( age_hat );
4879 REPORT( comp_obs );
4880 REPORT( comp_hat );
4881 REPORT( caal_hat );
4882 REPORT( equil_catch_hat );
4883 REPORT( caal_obs );
4884 REPORT( pred_CAAL );
4885
4886
4887 // -- 14.7. Likelihood components
4888 REPORT( jnll_comp );
4889 REPORT( unweighted_jnll_comp );
4890
4891
4892 // -- 14.8. Ration components
4893 REPORT( consumption_at_age );
4894 REPORT( fT );
4895
4896 // -- 14.9. Predation components
4897 REPORT( M2_prop );
4898 REPORT( diet_obs );
4899 REPORT( suitability );
4900 REPORT( M1_at_age );
4901 REPORT( M2_at_age );
4902 REPORT( B_eaten );
4903 REPORT( B_eaten_as_prey );
4904 // ADREPORT( B_eaten_as_prey ); // no SEs: see ?plot_b_eaten_prop; also 0 on AD types (7.2)
4905 REPORT( vulnerability );
4906 REPORT( vulnerability_other );
4907 REPORT( gam_a );
4908 REPORT( gam_b );
4909 REPORT( diet_hat );
4910 REPORT( suit_other );
4911 REPORT( stom_div_bio );
4912 REPORT( avail_food );
4913
4914
4915 // -- 14.10. Initial-state cumulative mortality (feeds the initial age structure)
4916 REPORT(mort_sum);
4917
4918 /** ------------------------------------------------------------------------ //
4919 // 15. END MODEL //
4920 * ------------------------------------------------------------------------- */
4921
4922 Type jnll = 0;
4923
4924 // Modes 0-3 return the real objective. Mode 3 builds the TMB object without
4925 // running the optimizer, so obj$fn()/obj$gr() are usable for diagnostics.
4926 if(estimateMode < 4) {
4927 jnll = jnll_comp.sum();
4928 }
4929
4930 // Mode 4: build_map() maps out every hindcast parameter, leaving `dummy` as
4931 // the only free parameter. Placeholder objective so nlminb has something
4932 // valid to minimize -- a plumbing smoke test, not a likelihood.
4933 if(estimateMode > 3) {
4934 jnll = dummy * dummy;
4935 }
4936
4937
4938 REPORT( jnll );
4939 return jnll;
4940}
4941
void calculate_temperature_function(matrix< Type > &fT, int nspp, int nyrs, const vector< int > &Ceq, const vector< int > &Cindex, const vector< Type > &Qc, const vector< Type > &Tcm, const vector< Type > &Tco, const vector< Type > &Tcl, const vector< Type > &CK1, const vector< Type > &CK4, const matrix< Type > &env_index)
Temperature-dependent function of consumption (fT) for bioenergetics.
void calculate_ration(array< Type > &consumption_at_age, int nspp, int nyrs, int nyrs_hind, const vector< int > &nsex, const vector< int > &nages, const vector< int > &Ceq, const vector< Type > &CA, const vector< Type > &CB, const vector< Type > &fday, const vector< Type > &Pvalue, matrix< Type > &fT, array< Type > &ration_data, array< Type > &weight_hat)
Annual ration of a predator at age, in kg per predator per year.
One-step-ahead (OSA) residual helpers for composition data.
Type ddirmultinom_osa(vector< Type > obs, vector< Type > alpha, data_indicator< vector< Type >, Type > keep, int do_osa, int give_log)
Keep-aware Dirichlet-multinomial log-density via conditional beta-binomials.
Definition comp_osa.hpp:266
Type dmultinom_osa(vector< Type > x, vector< Type > p, data_indicator< vector< Type >, Type > keep, int do_osa, int give_log, int do_cdf=0)
Keep-aware multinomial log-density via conditional binomials.
Definition comp_osa.hpp:173
Type osa_norm_cdf_terms(Type x, Type mu, Type sd, Type cdf_lower, Type cdf_upper)
One-step-ahead CDF terms for a normal observation.
Definition comp_osa.hpp:131
Type osa_trunc_norm_cdf_terms(Type x, Type mu, Type sd, Type cdf_lower, Type cdf_upper)
One-step-ahead CDF terms for a normal left-truncated at zero.
Definition comp_osa.hpp:153
Random draws for composition-style observations, used by SIMULATE.
vector< Type > rdirmultinom_rce(Type N, vector< Type > alpha)
Draw Dirichlet-multinomial counts.
Definition comp_sim.hpp:128
vector< Type > rmultinom_rce(Type N, vector< Type > p)
Draw multinomial counts by sequential conditional binomials.
Definition comp_sim.hpp:41
void organize_diet_obs(const int &nspp, const int &nyrs, const int &nyrs_hind, const int &styr, const vector< int > &minage, const vector< int > &nsex, matrix< Type > &diet_obs, matrix< int > &diet_ctl, array< Type > &diet_prop)
Parses empirical diet observations and maps them into a 5D proportion array.
Definition diet_data.hpp:24
void predict_stomach_content(const int &nspp, const int &nyrs_hind, const int &styr, const vector< int > &suit_styr, const vector< int > &suit_endyr, const vector< int > &minage, const vector< int > &nsex, const vector< int > &nages, matrix< Type > &diet_obs, matrix< int > &diet_ctl, array< Type > &avgN_at_age, array< Type > &diet_prop_hat, matrix< Type > &diet_hat)
Expected stomach content proportions given the modeled population state.
void calculate_other_food_diet_prop(const int &nspp, const int &nyrs, const vector< int > &nsex, const vector< int > &nages, const vector< Type > &other_food, array< Type > &diet_prop, array< Type > &other_food_diet_prop)
Residual stomach content: the "other food" not explicitly modeled.
Definition diet_data.hpp:97
void calculate_weight(array< Type > &weight_hat, array< Type > &length_hat, array< Type > &growth_matrix, array< Type > &mat_weight_hat, array< Type > &weight_obs, const vector< int > &growth_model, const vector< int > &growth_sd_style, const vector< int > &growth_sd_form, const vector< int > &growth_plus_length, const vector< Type > &plus_group_decay, const int &nspp, const int &nyrs, const int &nyrs_hind, const int &n_flt, const vector< int > &flt_spp, vector< Type > flt_month, const vector< int > &nsex, const vector< int > &minage, const vector< Type > &growth_age_L1, const vector< int > &nages, const vector< int > &nlengths, const vector< int > &pop_wt_index, const vector< int > &ssb_wt_index, const vector< int > &flt_wt_index, vector< Type > spawn_month, matrix< Type > &lengths, const vector< int > &nlengths_pop, matrix< Type > &lengths_pop, array< Type > &growth_parameters, array< Type > &growth_log_sd, matrix< Type > weight_length_pars, const vector< int > &mat_len_use, matrix< Type > &mat_len_pars, array< Type > &log_M1)
Population, SSB and fleet weight-at-age (kg) for every species and fleet.
Definition growth.hpp:504
Small differentiable (AD-safe) utilities used across the CEATTLE template: numeric guards and transfo...
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.
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)
Likelihood math for section 13 of ceattle.cpp: the composition row density and linkage prior families...
Type linkage_log_prior(int family, Type value, bool value_is_log, Type p1, Type p2, Type bias_adjust_proc)
Log density of a linkage prior on the natural scale.
void fold_comp_tails(vector< Type > &obs, vector< Type > &hat, int &n_comp, int nbins_blk, int nblk, int yng, int old)
Composition tail accumulation (AFSC ac_yng / ac_old).
void comp_row_nll(int ll_type, int osa_mode, vector< Type > obs_prop, vector< Type > hat_prop, Type offset, Type n_samp, Type weight, Type dm_theta, vector< Type > &obsvec, data_indicator< vector< Type >, Type > &keep, int osa_start, const char *type_name, Type &nll, Type &unweighted_nll)
Negative log-likelihood of one composition row: an age or length composition, or one length bin of co...
#define RCEATTLE_SEL_DN_PEAK
Definition linkage.hpp:61
#define RCEATTLE_N_REC_PARAMS
Definition linkage.hpp:35
#define RCEATTLE_SEL_APICAL
Definition linkage.hpp:60
#define RCEATTLE_COMP_THETA_DIET
Definition linkage.hpp:71
#define RCEATTLE_REC_BETA
Definition linkage.hpp:38
#define RCEATTLE_SEL_END_LOGIT
Definition linkage.hpp:66
#define RCEATTLE_PROC_RECRUIT
Definition linkage.hpp:22
void rceattle_apply_q_linkages(matrix< Type > &q_offset, int link_code, const LinkageTable< Type > &lt, int n_flt, int nyrs)
Add catchability offsets to q_offset[fleet, yr].
Definition linkage.hpp:280
#define RCEATTLE_REC_R_INIT
Definition linkage.hpp:39
#define RCEATTLE_PROC_GROWTH
Definition linkage.hpp:24
#define RCEATTLE_N_GROWTH_PARAMS
Definition linkage.hpp:31
#define RCEATTLE_REC_ALPHA
Definition linkage.hpp:37
#define RCEATTLE_RE_AR1
Definition linkage.hpp:51
void rceattle_apply_sel_linkages(array< Type > &slp_offset, array< Type > &inf_offset, array< Type > &coff_offset, array< Type > &apical_offset, array< Type > &dn6_offset, int link_code, const LinkageTable< Type > &lt, int n_flt, int max_sex, int n_sel_bins, int nyrs)
Add selectivity offsets, by fleet, sex and year, to one of five arrays.
Definition linkage.hpp:328
void rceattle_apply_recruitment_linkages(array< Type > &rec_offset, int link_code, const LinkageTable< Type > &lt, int nspp, int nyrs)
Add recruitment offsets to rec_offset[sp, param, yr].
Definition linkage.hpp:236
#define RCEATTLE_COMP_THETA_COMP
Definition linkage.hpp:69
#define RCEATTLE_LINK_IDENTITY
Definition linkage.hpp:42
#define RCEATTLE_RE_RW
Definition linkage.hpp:50
#define RCEATTLE_PROC_Q
Definition linkage.hpp:25
void rceattle_apply_growth_linkages(array< Type > &growth_offset, int link_code, const LinkageTable< Type > &lt, int nspp, const vector< int > &nsex, int nyrs)
Add growth offsets to growth_offset[sp, sex, yr, param].
Definition linkage.hpp:136
#define RCEATTLE_SEL_SLP_ASC
Definition linkage.hpp:55
void rceattle_re_group_nll(int structure, vector< Type > re, Type sigma, Type rho, Type &nll, Type &nll_unweighted)
Add the negative log density of one group's deviations to two accumulators.
Definition linkage.hpp:414
#define RCEATTLE_PROC_COMP
Definition linkage.hpp:27
void rceattle_apply_M_linkages(array< Type > &M_offset, int link_code, const LinkageTable< Type > &lt, int nspp, const vector< int > &nsex, const vector< int > &nages, int nyrs)
Add natural-mortality offsets to M_offset[sp, sex, age, yr].
Definition linkage.hpp:185
#define RCEATTLE_REC_R0
Definition linkage.hpp:36
#define RCEATTLE_LINK_LOG
Definition linkage.hpp:43
#define RCEATTLE_SEL_INF_DESC
Definition linkage.hpp:58
vector< int > rceattle_group_slots(const vector< int > &group_of_slot, int grp)
The random-effect slots of one group, in slot order, which is time order within a group (....
Definition linkage.hpp:389
#define RCEATTLE_PROC_M
Definition linkage.hpp:23
#define RCEATTLE_SEL_SLP_DESC
Definition linkage.hpp:56
#define RCEATTLE_LINK_EXPONENTIAL
Definition linkage.hpp:45
#define RCEATTLE_SEL_INF_ASC
Definition linkage.hpp:57
#define RCEATTLE_COMP_THETA_CAAL
Definition linkage.hpp:70
#define RCEATTLE_PROC_SEL
Definition linkage.hpp:26
void calculate_msvpa_predation(array< Type > &avail_food, array< Type > &avail_food_dB0, array< Type > &avail_food_dBF, array< Type > &M2_at_age, array< Type > &M2_at_age_dB0, array< Type > &M2_at_age_dBF, array< Type > &M2_prop, array< Type > &B_eaten, array< Type > &B_eaten_as_prey, array< Type > &diet_prop_hat, array< Type > &other_diet_prop_hat, int nspp, int nyrs, const vector< int > &nsex, const vector< int > &nages, int msmMode, array< Type > &avgN_at_age, array< Type > &avgN_at_age_dB0, array< Type > &avgN_at_age_dBF, array< Type > &suitability, array< Type > &suit_other, array< Type > &weight_hat, array< Type > &ration, const vector< Type > &other_food, bool fill_report_only, bool fill_diet, bool fill_dynamic_B0)
Available food, predation mortality (M2), and consumed biomass (MSVPA).
void calculate_parametric_suitability(array< Type > &suitability, array< Type > &suit_other, int nspp, int nyrs, const vector< int > &nsex, const vector< int > &nages, const vector< int > &suitMode, array< Type > &length_hat, array< Type > &weight_hat, matrix< Type > &vulnerability, const vector< Type > &vulnerability_other, const vector< Type > &gam_a, const vector< Type > &gam_b)
Parametric suitability (Gamma, Lognormal, Normal) from size ratios.
Definition predation.hpp:77
void calculate_vulnerability(matrix< Type > &vulnerability, vector< Type > &vulnerability_other, int nspp, const vector< int > &suitMode, matrix< Type > &log_phi)
Transforms predator-prey preference parameters into vulnerability.
Definition predation.hpp:20
void calculate_msvpa_suitability(array< Type > &stom_div_bio, array< Type > &suitability, array< Type > &suit_other, int nspp, int nyrs, const vector< int > &suit_styr, const vector< int > &suit_endyr, const vector< int > &nyrs_suit, int msmMode, const vector< int > &nsex, const vector< int > &nages, const vector< int > &suitMode, array< Type > &diet_prop, array< Type > &avgN_at_age, array< Type > &weight_hat, array< Type > &other_food_diet_prop)
MSVPA/empirical suitability, from stomach content and prey biomass.
Type calculate_recruitment(int srr_fun, Type R0, Type ssb, Type srr_alpha, Type srr_beta, Type rec_dev, Type spr0)
Calculates the recruitment for a given species and year.
void calculate_selectivity(const int &nspp, const int &n_flt, const int &nyrs, const int &nyrs_hind, const int &styr, const vector< int > &nsex, const vector< int > &nages, const vector< int > &nlengths, matrix< Type > &lengths, const vector< int > &nlengths_pop, matrix< Type > &lengths_pop, const vector< int > &flt_spp, const vector< int > &flt_sel_type, const vector< int > &flt_varying_sel, const vector< int > &flt_sel_dim, const vector< int > &bin_first_selected, const vector< int > &flt_n_sel_bins, const vector< int > &flt_sel_cap_bin, const vector< int > &sel_norm_bin1, const vector< int > &sel_norm_bin2, const vector< int > &sel_norm_scope, const vector< int > &flt_sel_start_yr, matrix< Type > &emp_sel_obs, matrix< int > &emp_sel_ctl, array< Type > &log_sel_slp, array< Type > &log_sel_slp_dev, array< Type > &sel_inf, array< Type > &sel_inf_dev, array< Type > &sel_coff, array< Type > &sel_coff_dev, array< Type > &avg_sel, array< Type > &non_par_sel, array< Type > &log_non_par_sel, array< Type > &sel_at_length, array< Type > &sel_at_age, array< Type > &growth_matrix, array< Type > &sel_slp_off, array< Type > &sel_slp_off_nat, array< Type > &sel_inf_off, array< Type > &sel_inf_off_nat, array< Type > &sel_coff_off, array< Type > &sel_coff_off_nat, const int &sel_apical_on, array< Type > &log_sel_apical, array< Type > &sel_apical_off, array< Type > &sel_apical_off_nat, array< Type > &sel_dn6, array< Type > &sel_dn6_off, array< Type > &sel_dn6_off_nat, matrix< int > &sel_dn6_ends)
Calculates selectivity for every fleet, sex, bin (age or length) and year.
Spawning biomass per recruit, for the Amendment-56 SPR proxies.
Type spawning_biomass_per_recruit(const vector< Type > &n, const vector< Type > &Z, const vector< Type > &weight, const vector< Type > &mature_female, Type spawn_month)
Female spawning biomass per recruit, given a survivor schedule.
Definition spr.hpp:69
vector< Type > per_recruit_survivors(const vector< Type > &Z)
Survivors at age from one recruit under a fixed mortality schedule.
Definition spr.hpp:38
LOM_t(SEXP x)
Definition ceattle.cpp:45
The linkage table: one entry per row, and the shared design matrix.
Definition linkage.hpp:96