On this page

Fit the age-structured catch-at-length model (ACL) 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_acl(
  data.CatL,
  data.wgt,
  data.mat,
  rec.age,
  nage,
  M,
  sel_L50 = NULL,
  sel_L95 = NULL,
  parameters = NULL,
  parameters.L = NULL,
  parameters.U = NULL,
  map = NULL,
  len_mid = NULL,
  len_border = NULL,
  output = FALSE,
  train_times = 1,
  ncores = 1,
  silent = FALSE,
  growth_step = NULL,
  zero_action = c("missing", "error"),
  control = list(),
  nstarts = ncores,
  F_structure = c("group_year", "year"),
  polish = TRUE,
  structure = list(),
  start_spread = 0.15,
  survey_q = NULL,
  survey_q_age = NULL,
  bounds = c("default", "wide")
)

Arguments

ArgumentDefaultDescription
data.CatLrequired

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.wgtrequired

Weight table (mean individual weight by length bin), with the labels, columns and dimensions of the survey index table.

data.matrequired

Maturity table (proportion mature by length bin, 0-1), with the layout of the survey index table.

rec.agerequired

Recruitment age in years, greater than t0.

nagerequired

Number of age classes including the plus group (at least two).

Mrequired

Nonnegative natural mortality rate (M) per model time step (for quarterly time steps, the annual rate divided by 4). A single number is one rate for all 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; M by age that is constant over time is matrix(M_at_age, ncol = 1). A numeric vector without dimensions is read as M by length, which run_alscl() accepts and ACL rejects, because ACL follows numbers at age only and fish do not keep their length. Any other object is rejected with the expected dimensions.

sel_L50NULL

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_L95NULL

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.

parametersNULL

Named list of starting values of the scalar parameters, on the optimizer scale.

parameters.LNULL

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.UNULL

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.

mapNULL

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_midNULL

Finite length-bin midpoints, one per row of the data; they replace the values read from the length labels.

len_borderNULL

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.

outputFALSE

Save diagnostic tables and plots below output/ when TRUE.

train_times1

Positive integer. Number of successive optimization passes from each start; it does not add independent starts.

ncores1

Maximum number of socket workers that fit independent starts, at most nstarts; it does not set threads within one start.

silentFALSE

Suppress fitting progress messages when TRUE.

growth_stepNULL

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.

zero_actionc("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.

controllist()

Named list of nlminb control settings, such as iter.max and eval.max.

nstartsncores

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_structurec("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.

polishTRUE

Logical. TRUE (default) refines the selected fit with safeguarded Newton steps; FALSE skips this. The raw optimizer codes are kept, and refinement$hessian_calculations records the Hessian method and the number of cores.

structurelist()

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, which implements the model of Zhang and Cadigan (2022). "von_bertalanffy" selects initial_plus_group = "equilibrium" for ACL (see run_alscl() for the ALSCL settings of this set), and a list can name a set and add single settings, for example list(set = "von_bertalanffy", correlation_range = "symmetric"). "published" and "consistent" are other names of "original" and "von_bertalanffy". ACL has three settings. initial_plus_group is "single_cohort" (default; the plus group of the first time step holds one cohort) or "equilibrium" (it holds the sum of all older cohorts at total mortality init_Z, so a population with constant recruitment, no fishing and init_Z equal to M stays constant over time). correlation_range is "positive" (default; AR(1) correlations between 0 and 1, the logistic transform of the logit_* parameters) or "symmetric" (between -1 and 1, as 2 * logistic - 1; a correlation rho is then qlogis((rho + 1) / 2) on the optimizer scale). initial_deviations is "cumulative" (default; the log numbers at age in the first time step are those of the previous age minus init_Z plus a normal deviation, so the deviations accumulate over ages and dev_log_N0 has nage - 1 entries) or "independent" (Equation 11 of Zhang and Cadigan 2022, log N(a) = log R(1) - init_Z (a - 1) + e(a) for ages a = 1 to nage, with independent normal deviations e(a), so dev_log_N0 has nage entries and the reported recruitment Rec of the first time step is the number at the first age in that time step, e(1) included; with an equilibrium plus group, the deviation of the plus group multiplies the sum of the older cohorts). The settings used are stored in the structure element of the fit; initial_deviations is stored only when it is "independent". Letter case does not matter.

start_spread0.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.

survey_qNULL

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_catchability() computes logistic and dome-shaped curves. A matrix with one row per length bin and one column per time step gives survey catchability by length and time step, for example after a change of survey gear; a matrix with one column is read as the vector. Supplying survey_q together with sel_L50 or sel_L95 is an error; when an input bundle or a stored fit already holds these two, add sel_L50 = NULL, sel_L95 = NULL to the call. The values are fixed inputs and are not estimated.

survey_q_ageNULL

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 survey_q_age[age] times numbers at age times the probability of that length at that age, where q(length) is the survey catchability at length from sel_L50 and sel_L95 or from survey_q. When survey_q_age is supplied and parameters holds no start for mean_log_R, the default start of mean_log_R is raised by -log(survey_q_age[1]), because the survey then sees only that fraction of the recruits. The fit gives a message with this change unless silent = TRUE, once per call of a function that runs several fits.

boundsc("default", "wide")

"default" uses the standard ACL bounds. "wide" gives ACL the bounds that ALSCL has for five parameters, the initial total mortality rate (upper bound 10 instead of 1 per time step), the median fishing mortality rate (2 instead of 1 per time step), the standard deviations of the initial numbers at age and of recruitment on the log scale (10 instead of 1) and the von Bertalanffy growth rate k (0.05 to 2 instead of 0.1 to 1 per year); see create_parameters(). Entries of parameters.L and parameters.U replace these bounds. When an ACL fit stops at one of the default upper bounds, diagnostics$advice and the message of the fit name this argument. Letter case does not matter.

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 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.

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, total mortality at age (Z) is F plus the M of that age and time step, in survival and in the catch equation. The default start of init_Z uses the median of M in the first time step. A constant given as a matrix, 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 is an assumption. The survey index informs total mortality but not its split into fishing and natural mortality, so an error in M enters F directly, and the objective of a fit is not a basis for choosing M. Supply M by age and time step only when independent estimates exist, for example from a multispecies model. survey_q and survey_q_age are assumptions of the same kind. A survey catchability that declines with length or age is otherwise fitted as higher mortality. 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.

The default start (60) and bounds (10 to 100) of Linf are in the length units of the yellowtail flounder example. When the upper bound is below 1.2 times the largest length-bin midpoint, or the start is outside 0.7 to 2 times that midpoint, the start and bounds that were not supplied are set from the data. The start is 1.1 times the length below which 99 percent of the summed survey index lies, the upper bound is 2 times the largest midpoint, and the lower bound is the smaller of the default (10) and half of that 99 percent length, so that length bins extending beyond the largest fish do not exclude the true Linf.

Additional details from R help

M and F are rates per time step, and vbk is a rate per year. The first and last length bins take in the tails of the length distribution. The model template is compiled into a writable cache of the session. Choose the fitting settings explains the settings.

Input bundles

run_acl(x) also takes an input bundle, either a named list of fitting arguments or a structured bundle such as YTF_example with data.CatL, data.wgt and data.mat, the shared settings in fit_args and optional ACL settings in fit_config$acl. Each source replaces the one before in this order: the tables, fit_args, fit_config$acl, the arguments of the call. A parameters, map or control given in the call replaces the whole stored list, also when it is NULL, and the fit names the stored starting values that such a parameters list leaves out (unless silent = TRUE). Other elements of a structured bundle, such as simulation parameters and true values, are not fitting settings.

Estimated and fixed parameters

Every scalar parameter is estimated unless map fixes it. By default ACL fixes log_std_log_F, logit_log_F_y, logit_log_F_a and t0, which leaves 10 scalar parameters to estimate. To release one, pass map = list(log_std_log_F = NULL). In a stored map, write the release as map["name"] <- list(NULL), because map$name <- NULL deletes the entry and the default fix then applies again. M, survey catchability, weights, maturity and the age and length-bin settings are inputs. The process deviations are random effects and are not in opt$par.

A map that fixes or ties entries of dev_log_R, dev_log_F or dev_log_N0 is accepted only when the standard deviation and the correlations of that process are fixed too, because the process densities are evaluated on the complete arrays; otherwise the estimates would be biased, and the fit stops. A tied value then has a smaller prior standard deviation than the stated one, the objective cannot be compared (for example by AIC) with fits that use another map for these deviations, and restricted_random in the fit names the arrays concerned. For one F per time step, use F_structure = "year".

Starts, bounds and refinement

A single start can stop at a local optimum that passes every numerical check, so a fit with one start (the default) gives a message unless silent = TRUE. For results that will be reported, use at least three starts with a wider spread, for example ⁠nstarts = 3, start_spread = 0.5⁠, and compare the starts in start_diagnostics and start_summary (Control the optimizer).

Starting values outside their bounds are moved to the nearest bound, with a warning when the start was supplied and a message for a default start; clamped_starts lists them. The default start (60) and bounds (10 to 100) of Linf suit the yellowtail flounder example. When the upper bound is below 1.2 times the largest length-bin midpoint, or the start is outside 0.7 to 2 times that midpoint, the start and the bounds that were not supplied are set from the survey index (Set starting values and bounds).

With polish = TRUE the selected fit takes up to five Newton steps. A step is kept only when the Hessian is positive definite, the parameters stay within their bounds, the maximum gradient decreases and the objective rises by at most 1 x 10^-8 (roundoff). When the gradient is still 0.001 or more, a second pass of up to five steps accepts a rise within the working precision of the objective, sqrt(.Machine$double.eps) times its size. The steps can change estimates at numerical precision and leave the raw optimizer codes as they were; optimizer_history and refinement record them, and Speed settings says how their Hessian is computed.

Numerical checks

Besides the optimizer code, the gradient, the Hessian and the bounds, the numerical checks fail a fit with a parameter at its limit in practice, that is, the logarithm of a standard deviation below -9 (a variance of zero) or a logit correlation with an absolute value above 15. diagnostics$limit_parameters lists such parameters and diagnostics$advice says what to do. diagnostics$plausibility holds notes that do not change the verdict, with the thresholds in diagnostics$check_thresholds. Judge whether a fit can be used explains each check and note.

Model structures

The original structure implements the model of Zhang and Cadigan (2022). ACL has three settings, each with its default first: initial_plus_group ("single_cohort" or "equilibrium"), correlation_range ("positive" or "symmetric") and initial_deviations ("cumulative" or "independent"). For ACL, the set "von_bertalanffy" is initial_plus_group = "equilibrium". A correlation rho is qlogis(rho) on the optimizer scale under correlation_range = "positive" and qlogis((rho + 1) / 2) under "symmetric". Under initial_deviations = "independent", dev_log_N0 has nage entries in place of nage - 1, and the recruitment of the first time step includes the deviation of the first age. The structure element of the fit stores the settings, and initial_deviations only when it is "independent". Choose an optional model structure describes each setting.

Natural mortality and survey catchability

With M by age and time step, total mortality at age is F plus the M of that age and time step, in survival and in the catch equation, and the default start of init_Z uses the median of M in the first time step. A constant given as a matrix, 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 that the survey index cannot check, because it informs total mortality but not its split into fishing and natural mortality. The objective of a fit is not a basis for choosing them (Natural mortality and survey catchability in other forms).

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
a <- run_acl(x)

See also

Search documentation