run_alscl()
View source ↗On this page
Fit the age- and length-structured statistical catch-at-length model (ALSCL) to survey length data with TMB by maximum marginal likelihood. The inputs are the survey index table, the weight table and the maturity table, aligned by length bin and time step.
Usage
run_alscl(
data.CatL,
data.wgt,
data.mat,
rec.age,
nage,
M,
sel_L50 = NULL,
sel_L95 = NULL,
growth_step = NULL,
parameters = NULL,
parameters.L = NULL,
parameters.U = NULL,
map = NULL,
len_mid = NULL,
len_border = NULL,
len_lower = NULL,
len_upper = NULL,
output = FALSE,
train_times = 1,
ncores = 1,
silent = FALSE,
zero_action = c("missing", "error"),
control = list(),
nstarts = ncores,
F_structure = c("group_year", "year"),
polish = TRUE,
structure = list(),
start_spread = 0.15,
t0_lower = 0,
survey_q = NULL,
survey_q_age = NULL
)
Arguments
| Argument | Default | Description |
|---|---|---|
data.CatL | required | Survey index table, a data frame or matrix with length labels in its first column followed by at least two numerically labelled time columns, or an input bundle such as YTF_example. Text cells "NA" and "", also with spaces around them, are read as missing values. |
data.wgt | required | Weight table (mean individual weight by length bin), with the labels, columns and dimensions of the survey index table. |
data.mat | required | Maturity table (proportion mature by length bin, 0-1), with the layout of the survey index table. |
rec.age | required | Recruitment age in years, greater than t0. |
nage | required | Number of age classes including the plus group (at least two). |
M | required | Nonnegative natural mortality rate (M) per model time step (for quarterly time steps, the annual rate divided by 4), in one of three forms. A single number is one rate for all lengths, ages and time steps. A matrix with one row per age class (nage rows) and one column per time step, or one column that is used for every time step, is M by age and time step. A numeric vector with one value per length bin is M by length, the same for all ages and time steps; |
sel_L50 | NULL | Lengths at 50 and 95 percent survey catchability, which define a logistic survey catchability curve with a maximum of 1. Leave both as NULL when survey_q is supplied. |
sel_L95 | NULL | Lengths at 50 and 95 percent survey catchability, which define a logistic survey catchability curve with a maximum of 1. Leave both as NULL when survey_q is supplied. |
growth_step | NULL | Time between consecutive ages, in years; 0.25 for quarters. NULL uses rec.age when it is below one, otherwise one. Numeric time-column labels must have this spacing; keep missing time steps as NA survey columns with weights and maturity for every time step. |
parameters | NULL | Named list of starting values of the scalar parameters, on the optimizer scale. |
parameters.L | NULL | Named list of lower bounds on the optimizer scale. The bounds apply to the free parameters after the map; free starting values outside them are moved to the bound. |
parameters.U | NULL | Named list of upper bounds on the optimizer scale. The bounds apply to the free parameters after the map; free starting values outside them are moved to the bound. |
map | NULL | Named list of TMB factors. factor(NA) fixes a parameter at its supplied value; a named NULL entry releases that parameter. A whole map = NULL or list() applies the model defaults. Defaults not named remain in force. |
len_mid | NULL | Finite length-bin midpoints, one per row of the data; they replace the values read from the length labels. |
len_border | NULL | Interior boundaries between length bins, one fewer than the number of length bins. Interval labels with gaps, such as "10-14" and "15-19", need both len_mid and len_border. |
len_lower | NULL | Deprecated. Optional lower bin boundaries; the first entry must be |
len_upper | NULL | Deprecated. Optional upper bin boundaries; the last entry must be |
output | FALSE | Save diagnostic tables and plots below output/ when TRUE. |
train_times | 1 | Positive integer. Number of successive optimization passes from each start; it does not add independent starts. |
ncores | 1 | Maximum number of socket workers that fit independent starts, at most nstarts; it does not set threads within one start. |
silent | FALSE | Suppress fitting progress messages when TRUE. |
zero_action | c("missing", "error") | "missing" excludes zero observations as missing; "error" rejects them. NA is always missing; negative or infinite values are errors. Letter case does not matter. |
control | list() | Named list of nlminb control settings, such as iter.max and eval.max. |
nstarts | ncores | Total number of independent starts; defaults to ncores. Fix it when comparing numbers of workers, so that the work is the same. The second and later starts perturb the free parameters only, in a reproducible way. |
F_structure | c("group_year", "year") | "group_year" (default) gives F a two-dimensional first-order autoregressive (AR(1)) field over age (ACL) or length (ALSCL) and time. "year" uses one F per time step with AR(1) correlation over time; the correlation between groups is then fixed and left out of the reports. Letter case does not matter. |
polish | TRUE | Logical. TRUE (default) refines the selected fit with safeguarded Newton steps; FALSE skips this. The raw optimizer codes are kept, and |
structure | list() | Optional model structures, the name of a set or a named list of settings. The default (an empty list) and "original" are the original structure for every setting, which implements the model of Zhang and Cadigan (2022). "von_bertalanffy" selects |
start_spread | 0.15 | Standard deviation of the normal deviates added to the starting values (on the scale of the optimizer, mostly logarithms) of the second and later starts. For results that will be reported, use several starts and a larger value (for example 0.5); see the paragraphs after the return value. |
t0_lower | 0 | Lower limit of the von Bertalanffy parameter t0 in years. The model uses t0 = t0_lower + exp(log_t0). The default 0 is the original parameterization, in which t0 is positive. Set a negative value, for example -1, to allow negative t0; a known t0 is then supplied as |
survey_q | NULL | Optional survey catchability at length, a numeric vector with one positive value per length bin. It is used in place of the logistic curve from sel_L50 and sel_L95, for example for a dome-shaped curve; |
survey_q_age | NULL | Optional survey catchability multiplier by age, a numeric vector with one positive value per age class. The default NULL is 1 for every age. The expected survey index at length is then q(length) times the sum over ages of |
Value
A list of class alscl_fit, whose elements are read with $. report stores population quantities and survey predictions; opt stores the selected optimizer parameters, objective and raw status; obj is the session-specific TMB object; est_std, vcov and pdHess describe approximate uncertainty and Hessian status. gradient, max_abs_gradient (also final_outer_mgc), convergence_code, bound_hit and diagnostics support numerical checks. raw_opt, optimizer_history and refinement retain optimization records. year, age, length metadata, growth_step, F_structure and elapsed record coordinates, structure and timing. starts, start_diagnostics, nstarts and workers record the starting values, the process IDs of the workers, timestamps and the work performed. recipe stores complete inputs and fitting settings. The start with the lowest finite objective is selected; check the numerical status separately. Evaluating obj requires the DLL to remain loaded in the fitting session. structure records the model structure used, t0_lower the lower limit of t0 and start_spread the spread of the starts. start_summary gives the number of converged starts, the range of their objectives and the number that agree with the best one; a range above 2 is added to diagnostics$issues. clamped_starts lists the starting values that were moved into their bounds, zero_observations is the number of zero survey observations treated as missing, and restricted_random names the process-deviation arrays that the map ties or fixes. diagnostics also holds limit_parameters (parameters at their limit in practice, with their natural values), at_limit, advice (what to do about such parameters and about upper bounds that can be widened), plausibility (notes that do not change the verdict) and check_thresholds. The messages of a fit and summary() show the advice and the notes, and summary() shows a line Fixed inputs when the fit used a natural mortality rate by age or length, survey_q or survey_q_age; the result of summary() holds them as advice, plausibility and inputs.
Details
run_acl(x) and run_alscl(x) both accept a complete input bundle. For YTF_example, they read the three tables and x$fit_args, then the matching x$fit_config$acl or x$fit_config$alscl. Explicit call arguments have highest priority, for example run_acl(x, M = 0.25, nstarts = 4, ncores = 2). List-valued overrides (parameters, map, control) replace the whole stored list, and explicit NULL is retained. The simulation settings in x$parameters and the generating x$truth are not fitting arguments.
For your own data, x can instead be a flat named list containing data.CatL, data.wgt, data.mat, rec.age, nage, M, sel_L50 and sel_L95 (or survey_q) and any optional fitting arguments. A structured bundle may omit fit_config to use the model defaults; a model without an entry in fit_config uses the shared fit_args only. A fitting argument stored at the top level of the bundle, for example x$M <- 0.3, is not used, and fitting warns about it. Duplicate, unnamed, unknown or missing required arguments produce an error before fitting. All forms of the call use the same fitting code and the alscl_speed() settings; fit$sd_info records how the standard errors were computed. ncores controls the workers for independent starts, while sd_cores in alscl_speed() controls standard errors.
Natural and fishing mortality are instantaneous rates per model step; growth k is annual. Fixing survey catchability anchors the abundance scale. Zeros are excluded with zero_action="missing"; decide whether that is appropriate for your observations. nstarts sets the total number of starts and ncores limits the simultaneous socket workers; by default nstarts equals ncores. train_times sets the successive optimizer passes from each start. Inspect start_diagnostics for worker PIDs, timing and convergence. A convergence code of zero alone does not show that the fit can be used. Keep the DLL loaded to evaluate obj in the same R session.
Starting values do not fix parameters. A whole map = NULL or list() applies the model defaults. ACL fixes log_std_log_F, logit_log_F_y, logit_log_F_a and t0; ALSCL fixes log_sigma_log_F and log_t0. Pass named NULL entries directly to release default fixes; single-bracket assignment preserves them. See the own-data case study for the complete parameter checklist and working example.
Optimization refinement and F shared across groups
run_acl(x) and run_alscl(x) finish the selected fit with up to five safeguarded Newton steps (polish = TRUE). Each step requires a positive-definite numerical Hessian, parameters strictly inside their bounds, a smaller maximum absolute gradient, and an objective increase no greater than 10⁻⁸ for floating-point roundoff. Refinement stops if a condition fails; it cannot repair insufficient information or an inappropriate model. Set polish = FALSE to skip it. Refinement can change estimates at numerical precision.
Repeated optimizer passes retain their raw parameters, objective, code and message in fit$optimizer_history. A failed restart does not replace an actual successful pass when the objective values differ by at most 10⁻⁸ and every parameter differs by at most 1e-6 * max(1, abs(p1), abs(p2)). These tolerances identify numerically equivalent repeated passes; when the objective improves materially or the parameter vectors are far apart, the pass with the lower objective is kept. All raw codes and messages remain in optimizer_history, and raw_opt$selected_pass identifies the retained pass. The final gradient, Hessian and boundary checks remain separate from the optimizer code. fit$raw_opt records the selected result before refinement; fit$refinement records accepted steps and before/after gradients. convergence_code is the raw code of the selected optimizer run, also after refinement. The start is selected by the lowest finite objective before refinement; starts and start_diagnostics describe the starts before refinement.
fit$diagnostics holds the numerical checks, which require a maximum gradient below 0.001, a positive-definite Hessian and covariance, and no parameter at an optimizer bound or a natural-scale bound. Free correlations within 0.0001 of 0 or 1 and free standard deviations of the processes or the observations at or below 0.0001 are flagged. high_correlations lists the parameter pairs with an absolute correlation of at least 0.95, which are worth investigating. The covariance condition number depends on the scaling of the parameters. diagnose_model() prints the raw optimizer status and the numerical checks separately; inspect residuals, alternative starts, profiles and sensitivity as well.
F_structure="group_year" estimates an age-by-time (ACL) or length-by-time (ALSCL) F process. F_structure="year" shares one F across all groups within each model time step, including one F per quarter for quarterly data. The unused group-correlation parameter is inactive in the shared structure; summary() lists it with the fixed parameters, marked as not used with this F structure.
Both fitting functions check the time grid directly. Consecutive numeric column labels must differ by growth_step. For annual data, 2000, 2001, 2003 is rejected because 2002 is absent. Keep 2002 as an all-NA survey column, and provide complete weight and maturity columns for that time step. Quarterly labels such as 2000, 2000.25, 2000.5 require growth_step = 0.25. The model does not interpolate missing time steps or reinterpret irregular intervals.
Supply each nlminb() option once by name, for example control = list(iter.max = 3000L). Both preflight and fitting check the names and values before optimization.
When the refinement of a fit (polish = TRUE) needs a Hessian, it shares the sd_cores limit, with at most one process per free scalar parameter. It runs in parallel only with forked processes and a checked TMB version; fits with one free parameter, socket sessions and unchecked TMB versions compute it sequentially. If forking fails, a warning is given and the Hessian is computed sequentially. fit$refinement$hessian_calculations records the method, the cores and any fallback for each Hessian computed. An empty table means that no Hessian was returned; fit$refinement$status tells whether refinement was skipped or an evaluation failed.
structure selects optional model structures; the default is the original structure, which implements the model of Zhang and Cadigan (2022). The argument table and Choose the fitting settings describe each setting.
With growth_transition = "midpoint" every fish of a length bin grows from the bin midpoint. Growth then stops at the length where the increment in one time step falls well below half the bin width, whatever the value of Linf; this happens with short time steps and wide bins (for example quarterly steps with 5 cm bins, or annual steps with 5 cm bins for a slow-growing stock). The fit stores growth_check. When the fitted transition has a length bin, with a midpoint below 90% of the estimated Linf, in which fish stay with a probability of at least 0.99 per time step, the fit reports it in a message (unless silent = TRUE) and summary() prints it. Consider a refit with structure = "von_bertalanffy" in that case. The original structure and the "von_bertalanffy" set have the same number of parameters, so their objective values can be compared directly.
A single start can stop at a local optimum that passes every numerical check, particularly for the growth parameters of ALSCL. The checks in diagnostics concern the solution found and do not show whether a better optimum exists. A fit with one start (nstarts = 1, the default) therefore gives a message unless silent = TRUE; a function that runs several fits in one call gives it once. For results that will be reported, use at least three starts (nstarts = 3 or more) with a wider start_spread (for example 0.5) and compare the objectives in start_diagnostics.
Besides the gradient, the Hessian and the optimizer bounds, the numerical checks in diagnostics look for parameters that are at their limit in practice although they have not reached a bound. These are log_t0 below -10 (ALSCL; t0 then equals t0_lower), the logarithm of a standard deviation below -9 (a variance of zero) and a logit correlation with an absolute value above 15 (a correlation at the end of its range). Such a fit fails the checks (numerical_ok = FALSE), as a fit that stopped at a bound does. diagnostics$limit_parameters lists these parameters with their values on the natural scale, diagnostics$at_limit says whether there is one, and diagnostics$advice says what to do, which is to fix the parameter with map at a chosen value and refit or, for a correlation at zero, to use structure = list(correlation_range = "symmetric"). diagnostics$plausibility lists notes that do not change the verdict of the checks. A note is given when the mean length of recruits lies more than two length-bin widths below the lower border of the second length bin, when the estimated standard deviation of the observation error on the log scale is above 0.9, when an estimated coefficient of variation of length at age (cv_len) or of the growth increment (cv_grow, ALSCL) is above 0.3 (the example range of cv_len in the Stock Synthesis manual is 0.10 to 0.25), or when the estimated initial total mortality rate is below the smallest natural mortality rate. Except for the mean length of recruits, the notes concern estimated parameters only, not values fixed with map. The thresholds are stored in diagnostics$check_thresholds. The messages of a fit and summary() show the advice and the notes; the result of summary() holds them as advice and plausibility when there are any. A saved fit keeps the verdict stored with it.
With M by age and time step or by length, M replaces the single rate in survival, in the catch equation and in total mortality (Z) and F at age. In the plus group, the fish that enter from the age before it and the fish already in it each have the M of their own age class. Two reported quantities then need a definition, because fish of one age have different lengths and fish of one length have different ages. F at age (FA) is Z at age minus the mean of M over lengths, weighted by the numbers at length of that age. Z at length (ZL) is F at length plus the mean of M over ages, weighted by the numbers at age of that length; it is a summary and not the rate that any one age experiences. The report holds the rates used as M_LAY (length by age by time step). The default start of init_Z uses the median of M in the first time step. A constant given in a non-scalar form, survey_q equal to the logistic curve, a survey_q matrix with equal columns, or survey_q_age of ones gives the fit of the default inputs up to rounding error. M, survey_q and survey_q_age are assumptions. The survey index does not inform the split of total mortality into fishing and natural mortality, nor the level or the descending part of survey catchability, so the objective of a fit is not a basis for choosing them. For a fit that uses these forms, summary() shows a line Fixed inputs, and the result of summary() has the element inputs.
A map that ties entries of dev_log_R, dev_log_F or dev_log_N0 to shared values, or fixes entries with NA, is accepted only when the matching standard deviation and correlation parameters are fixed too; otherwise their estimates would be biased and the fit is rejected. For one F deviation per time step shared by all groups, use F_structure = "year". The objective of a fit with tied or fixed entries cannot be compared (for example by AIC) with fits that use another map for these deviations.
Starting values outside their bounds are moved to the nearest bound, with a warning when the start was supplied and a message for default starts.
Unless supplied, the start of Linf is 1.1 times the largest length-bin midpoint and its bounds are 0.7 and 2 times that midpoint. Supply parameters.L$log_Linf when the bins extend well beyond the largest fish. len_lower and len_upper are deprecated and cannot change a fit; leave both NULL.
Additional details from R help
M and F are rates per time step, and vbk is a rate per year. ALSCL
estimates F at length; F at age (FA) summarizes the survival of a
cohort over a time step. Input bundles, the rules for map, the starts,
the bounds of starting values and the refinement work as described in
the Details of run_acl(); the sections below give what differs.
Estimated and fixed parameters
By default ALSCL fixes log_sigma_log_F and log_t0, which leaves 13
scalar parameters to estimate; release one with
map = list(log_sigma_log_F = NULL).
Starts, bounds and refinement
Unless supplied, the start of Linf is 1.1 times the largest length-bin
midpoint and its bounds are 0.7 and 2 times that midpoint. Supply
parameters.L$log_Linf when the bins extend well beyond the largest
fish, because a Linf below 0.7 times the largest midpoint is otherwise
excluded. The other rules are those of run_acl().
Numerical checks
The numerical checks are those of run_acl(), with two additions. A
log_t0 below -10 is a parameter at its limit in practice (t0 then
equals t0_lower), and an estimated coefficient of variation of the
growth increment (cv_grow) above 0.3 gives a plausibility note, as
cv_len does.
Model structures
The original structure implements the model of Zhang and Cadigan (2022). The settings and their values, with the default first:
growth_increment"logistic": the expected growth increment is a decreasing logistic function of length, multiplied bygrowth_step. Zhang and Cadigan (2022) define this function but give neither the lengths at which the increment is 50% and 95% of its maximum (0.5 Linf and 0.05 Linf in the code) nor its conversion to a time step shorter than one year."von_bertalanffy": the expected increment over one time step is (Linf - L)(1 - exp(-vbk * growth_step)) for a length L below Linf and declines smoothly to zero above Linf, so Linf acts as an upper limit of length after the first time step.growth_transition"midpoint": every fish in a length bin grows from the bin midpoint."bin": starting lengths are uniform within the bin and the transition is integrated over the bin, so fish keep moving to the next bin when the increment per time step is small relative to the bin width.initial_length"length_at_age": in the first time step every age has the length-at-age distribution with coefficient of variation cv_len."growth": the first age has that distribution, and each older age is the previous age after survival at init_Z and one growth step.initial_plus_group"single_cohort": the plus group of the first time step holds one cohort."equilibrium": it holds the sum of all older cohorts at total mortality init_Z.correlation_range"positive": the AR(1) correlations of recruitment and of F lie between 0 and 1, and a correlation rho isqlogis(rho)on the optimizer scale."symmetric": they lie between -1 and 1, and rho isqlogis((rho + 1) / 2).initial_deviations"cumulative": the deviations of the log numbers at age in the first time step accumulate over ages, anddev_log_N0hasnage - 1entries."independent": Equation 11 of Zhang and Cadigan (2022), withnageindependent deviations; the recruitment reported for the first time step then includes the deviation of the first age, anddev_log_Rkeeps its density.
The set "von_bertalanffy" selects the first four settings together,
so that the first time step and the growth transition follow one growth
model; correlation_range and initial_deviations do not belong to
it. Fits with only some of the four can fail when the growth increment
per time step is small relative to the bin width, so a structure list
that changes one, two or three of them gives a message that names the
settings left at their original values (unless silent = TRUE; once per
call of a function that runs several fits). A list that names the set
and replaces one of its settings, for example
list(set = "von_bertalanffy", growth_transition = "midpoint"), gives
no message. "von_bertalanffy" is also a value of growth_increment,
so structure = list(growth_increment = "von_bertalanffy") changes
that one setting. The structure element of the fit stores the
settings, and initial_deviations only when it is "independent".
Choose an optional model structure
explains the settings and how they combine.
With growth_transition = "midpoint", growth stops at the length where
the increment in one time step falls well below half the bin width,
whatever the value of Linf, for example with quarterly time steps and
5 cm bins. The fit stores the result in growth_check. When the fitted
transition has a length bin, with a midpoint below 90% of the estimated
Linf, in which fish stay with a probability of at least 0.99 per time
step, the fit reports it in a message (unless silent = TRUE) and
summary() prints it. Consider a refit with
structure = "von_bertalanffy"; the two structures have the same number
of parameters, so their objectives can be compared directly.
Negative t0
The model uses t0 = t0_lower + exp(log_t0), and t0 lies below rec.age.
With a negative t0_lower, supply a known t0 as
parameters = list(log_t0 = log(t0 - t0_lower)). When log_t0 is not
supplied, its default start is converted so that t0 keeps its default
value (1/60 year, fixed by default); a supplied log_t0 is read with the
new limit. When t0_lower and log_t0 come from different places, one
from the call and the other from the bundle or a saved recipe (for
example run_alscl(YTF_example, t0_lower = -1), whose bundle stores a
log_t0 chosen for t0_lower = 0), the fit gives a message with the t0
that it means (unless silent = TRUE). There is no message when both are
stored in the bundle, as in whiting_example, or both are given in the
same call. Reported t0 values are on the natural scale.
Natural mortality
With M by age and time step or by length, M replaces the single rate in
survival, in the catch equation and in total mortality (Z) and F at age.
In the plus group, the fish that enter from the age before it and the
fish already in it each have the M of their own age class. F at age
(FA) is then Z at age minus the mean of M over lengths, weighted by
the numbers at length of that age, and Z at length (ZL) is F at length
plus the mean of M over ages, weighted by the numbers at age of that
length, a summary that no single age experiences
(Growth transition matrix).
The report holds the rates used as M_LAY (length by age by time
step). The default start of init_Z uses the median of M in the first
time step, and a constant given in another form gives the fit of a
single M up to rounding error. M, survey_q and survey_q_age are
assumptions; the Details of run_acl() say why the fit cannot choose
them.
Examples
Run the setup before the example. Fitting examples require an R-compatible C++ toolchain; simulation and export examples may write files.
Example setup
library(ALSCL)
library(ggplot2)
library(patchwork)
data("YTF_example")
x <- YTF_example
inputs <- x[c("data.CatL", "data.wgt", "data.mat")]
dat <- x$data.CatL
# Use objects defined above
b <- run_alscl(x)