Skip to contents

How to check a fitted model, using the 2022 Northern Rockfish assessment as the example:

  • convergence diagnostics: attached automatically to every fit made with estimateMode "Estimate" or "Hindcast"
  • S3 methods: residuals(), logLik(), and the like
  • fit plots: compare predicted to observed data
  • one-step-ahead (OSA) and process residuals: goodness-of-fit tests for the observation and process models
  • retrospective analysis: peel off recent years to detect systematic bias
  • jitter testing: perturb starting values to check the optimizer found a global minimum
  • self-testing (simulation–estimation): check the model recovers its own estimates from simulated data
  • likelihood profiling: check how informative the data are about a given parameter

Printing any of them opens with one line (the object, an overall status, and a verdict) before the detail:

<Rceattle convergence>  status: OK
  all checks OK

<Rceattle OSA diagnostics>  status: WARN
  7 of 7 source(s) outside a null interval; overall SDNR 1.82 (0.91-1.09)
          source  fleet  n     sdnr   null
  [WARN]  index      4     36  2.52   0.77-1.23
  ...

<Rceattle retrospective>  status: WARN
  4 peel(s); 3 of 12 terminal Mohn's rho outside +/-0.2
          quantity  N     Pollock  Cod      Arrowtooth flounder
  [WARN]  R            3  0.511    0.283    -0.221

<Rceattle jitter>  status: OK
  4 of 4 start(s) reached the best optimum (within 0.01)

<Rceattle self-test>  status: NOTE
  47 of 50 simulation(s) converged
          convergence  n
  [OK  ]  OK           41
  [NOTE]  NOTE          6
  observations redrawn, processes held at their fitted values: the spread is a lower bound

<Rceattle profile>  status: WARN
  sigmaR over 29 grid point(s); all converged
  minimum -log L : 1274.8831  at slot_1 = 1.5
  within 1.92 of the minimum : 1.3 to >=1.5
  the minimum is at a grid edge (slot_1), so the grid does not bracket it -- widen `values`

The severity is OK, NOTE, WARN or FAIL, and the overall status is the worst present. Only the printing gives a verdict: each object is a data frame or list (retro$mohns, jit$nll, diag$sdnr, prof$grid$slot_1, sims[["Sim_1"]]), and c(sims, list(fit)) gives a plain list of fits to plot.

Four print methods take a threshold:

  • print(retro, band = ): Mohn’s rho threshold. The default 0.2 is the rule of thumb below; Hurtado-Ferro et al. (2015) give asymmetric, life-history-dependent alternatives (−0.15 to 0.20 long-lived, −0.22 to 0.30 short-lived).
  • print(jit, tol = ): how close an objective must be to count as having reached the same optimum.
  • print(sims, rate = ): the fraction of simulations that must converge before a self-test counts as clean.
  • print(prof, cutoff = ): bounds the reported interval; the default 1.92 is the 95% profile-likelihood cutoff for one parameter, half the 0.95 quantile of a chi-square on one degree of freedom.

A self-test’s header gives the convergence rate against nsim and its last line says what generated the replicates (see the self-test section). A profile whose minimum sits at the first or last grid value has run out of grid; it plots as an ordinary curve, so the print says so and asks for a wider values.

Setup and plotting data

library(Rceattle)

# Fit a single-species model for the 2022 Northern Rockfish assessment.
data("NorthernRockfish2022")
nrdata <- NorthernRockfish2022
nrdata$fleet_control$Proj_F_proportion <- 1
plot_data(nrdata)

Fit the model.

model_1 <- Rceattle::fit_mod(
  data_list = nrdata,
  estimateMode = 0,  # Estimate
  initMode = 1,      # Assume unfished equilibrium
  M1Fun = build_M1(
    updateM1 = TRUE,
    M1_model = 1,
    M1_use_prior = TRUE,
    M_prior = 0.06,
    M_prior_sd = 0.05),
  fit_control = fit_control(phase = TRUE, verbose = 0)
)
summary(model_1)

S3 Methods

summary(model_1)              # same compact summary
coef(model_1)                 # estimated fixed-effect parameters
logLik(model_1)               # logLik with df attribute (AIC works)
AIC(model_1)
vcov(model_1)                 # fixed-effect covariance from sdreport
residuals(model_1)                    # response residuals, all data sources
residuals(model_1, type = "pearson")  # Pearson residuals (glm-style `type`)
as.data.frame(model_1)

Convergence diagnostics

After optimization, fit_mod() runs a battery of convergence checks and attaches them as model$convergence; status is the worst severity present. WARN and FAIL checks are reported by message() during the fit, and print(model) shows the overall status. A non-converged fit is still returned, never an error, so you decide whether to trust it.

model_1$convergence            # overall status + any non-OK checks
print(model_1$convergence, all = TRUE)   # show every check, including OK ones

Re-run the battery on any fit with convergence_diagnostics():

The checks cover:

  • max_gradient: maximum absolute marginal gradient and the parameter holding it (WARN > 1e-3, FAIL > 1). With an sdreport of the same parameters, the message also gives the distance to the optimum in standard errors (largest in $data$newton_step_se, signed vector in $data$step_se), which unlike the raw gradient is comparable across log, logit and natural-scale parameters: 0.02 means finishing the optimization would move no estimate by more than 2% of its standard error. The severity is read on the gradient.
  • pdHess: whether the Hessian is positive definite (FAIL if not).
  • sdreport_failed: FAIL when an sdreport was requested but the Hessian could not be inverted.
  • hessian_not_run: NOTE when the fit was made with getsd = FALSE, so pdHess, hessian_conditioning, sdreport_failed and estimability never ran; refit with getsd = TRUE before reading the status as convergence.
  • zero_n_penalty: the “Zero n-at-age penalty” likelihood row is non-zero for a species: its numbers-at-age, Ricker intercept or (under an identity-link recruitment linkage) recruitment sat on the 0.001 floor, so the fit is of a floored model rather than the one specified. WARN when the root-sum-square excursion is under 1 (a thousand fish), FAIL above.
  • hessian_conditioning: how much better the data pin down some parameter combinations than others: the condition number of the correlation matrix of the estimates (WARN above 1e6, FAIL above 1e10), the multi-parameter version of a 0.999 pairwise correlation. On a fishery it usually means F traded against selectivity. Its square root is a ratio of standard errors on the standardized scale (each parameter divided by its own standard error): 13,634 means the least-determined combination is 13,634 times more uncertain than the best-determined one. The covariance condition number, which is not scale-invariant, is reported as covariance_condition_number.
  • parameters_on_bounds: parameters that sit on a configured build_bounds() limit (often unidentified or mis-scaled). WARN: the edge of the plausible range is still a well-posed optimum.
  • parameters_outside_bounds: parameters past one, a FAIL. nlminb respects the bounds but the Newton refinement fit_control(newtonsteps) asks for afterwards does not; refit with newtonsteps = 0, the default.
  • variance_collapse: a deviation standard deviation estimated to zero (WARN below 1e-3): a process configured as time-varying has fitted as time-invariant. Covers the recruitment, selectivity, catchability, M1 and linkage random-effect standard deviations. WARN rather than FAIL because a variance at the boundary is a well-posed optimum; it can occur with a clean gradient.
  • stock_recruit: whether the fitted curve is one the data informed. In a single-species model it is read against the replacement line through steepness. Under predation steepness does not exist (it needs spawning biomass per recruit), so the curve is read over the observed SSB range instead: WARN when it is flat there (recruitment independent of SSB), linear (no density dependence), when a Ricker peaks below the lowest observed SSB, when log alpha or log beta sits at its +/-30 bound, or when a log-scale standard error exceeds
    1. A curve held at its inputs is a NOTE.
  • exponential_q_near_one: WARN for a fleet with an exponential catchability linkage whose fitted catchability is within 0.1% of 1. That link multiplies log q, so at q = 1 the covariate moves the index by nothing whatever the coefficient is, and the coefficient is unidentified.
  • phasing: phases that ended with a high gradient, localizing which parameter block is hard to fit.
  • estimability: surfaces TMBhelper::check_estimability when it ran.

Naming the parameter, not just the block

max_gradient, estimability, the two bounds checks and hessian_conditioning name the flagged element by fleet, sex, age, bin and year, from parameter_index(), not just its parameter block (sel_coff_dev, say), and follow the block name with the quantity it estimates, from [parameter_dictionary()]:

  [WARN] max_gradient     Maximum absolute marginal gradient = 0.00222 on log_M1 (M1): Pollock, age 1.
  [WARN] hessian_conditioning Condition number = 2.4e+06: standard errors span 1.5e+03x across parameter combinations; loads on: log_F (F): 67% + rec_dev (recruitment deviations): 26%.
  log_F (F)                        Hake_fishery, 38 years in 1980-2021  (38 of 44 parameters; 67% of the direction)
  rec_dev (recruitment deviations) 24 years in 1981-2013  (24 of 44 parameters; 26% of the direction)

A scattered set of years or ages is counted against its span (“38 years in 1980-2021”); a consecutive run prints as a range. The count in parentheses is how many of the block’s parameters carry 90% of its loading.

max_gradient, estimability and the two bounds checks are captured from the hindcast optimization; hessian_conditioning reads the sdreport, which under an estimating HCR belongs to the projection fit and holds only log_Ftarget / log_Flimit. A check prints block names alone when the index does not describe the vector it is about to label.

parameter_index() itself describes fit$obj, which under any HCR but "NoFishing" is that projection object. Pass a fit run with estimateMode = "Hindcast" to browse the hindcast parameters directly.

Fit plots

Composition data

plot_comp() draws composition Pearson-residual bubbles and overlays the observed (shaded area) and predicted (line) age or length compositions for every fleet, both annually and aggregated across years. Joint-sex data are drawn on a single bin axis with females above and males below zero.

plot_comp(model_1)

Survey indices

plot_index() shows observed vs. predicted survey biomass; pass log = TRUE for the log scale. The predicted line is the median of the fitted observation distribution, so about half the observations should fall below it. plot_index_residual() plots the Pearson residual (observed minus predicted, standardized by the sd the row was fitted with), a first check for time trends or heteroscedasticity. A positive residual means the survey saw more than the model predicted. These return ggplot objects.

plot_index(model_1)
plot_index(model_1, log = TRUE)
plot_index_residual(model_1)

plot_catchability() draws the realized catchability the model scaled each survey by, faceted by fleet, so one figure covers an estimated or fixed mean, annual deviations under Time_varying_q, an environmental regression, a q linkage such as rw(1 | Year), and the closed-form "Analytical" value. A time-invariant q draws a flat line. Hindcast years only; the model does not project catchability.

plot_catchability(model_1)
plot_catchability(model_1, log = TRUE)

Catch

plot_catch(model_1)

One-step-ahead (OSA) residuals

Pearson residuals on composition data are not standard normal even when the model is correct: the age/length bins are correlated (more fish in one bin means fewer in another), and random effects induce correlation across years. (They are standardized by the variance the fleet’s own likelihood assumes, so composition weighting or Dirichlet-multinomial overdispersion does not inflate them.) One-step-ahead (OSA) residuals remove both problems. Each observation is residualized conditional on the observations added before it, integrating out the random effects, so under a correctly specified model the residuals are iid standard normal (Thygesen et al. 2017; Trijoulet et al. 2023).

osa_residuals() computes them post hoc for any combination of the fitted data types: survey indices ("index"), fishery catch ("catch"), age/length composition ("comp"), conditional age-at-length ("caal"), predator diet ("diet"), and, where a linkage holds an observed state-space covariate, the covariate observation itself ("ecov"). Composition data use the conditional binomial / beta-binomial decomposition of Trijoulet et al. (2023), using code adapted from WHAM (Stock and Miller 2021). OSA re-optimizes the random effects for each observation, so it is expensive; run it on a converged fit (estimateMode < 3). A requested source the model has no observations for is skipped (the call errors only if none of them have any). "diet" is not in the default set (multispecies only, and can be slow); pass source = "all" to include it. It needs a predicted diet, which means msmMode > 0 and estimated suitability (suitMode 2, 4 or 6); under empirical suitability the diet diagnostics refuse rather than report every observation as a complete misfit.

# Aggregate (catch + index) residuals
osa <- osa_residuals(model_1, source = c("index", "catch"))
head(osa)

# Statistical diagnostics (Stewart & Monnahan 2025): SDNR and lower/upper tail
# statistics, each with the interval expected under the standard-normal null.
osa_diagnostics(osa)

# Q-Q plot (with SDNR / tail annotation) + residual-by-year
plot(osa)

# residuals() also exposes them in the common residual schema (`source` selects
# the data, like `type` in stats::residuals.glm()):
residuals(model_1, type = "osa", source = c("index", "catch"))

# Composition OSA residuals, no special fit required
plot_comp(model_1, residual_type = "osa")              # Q-Q + signed bubbles
residuals(model_1, type = "osa", source = "comp")

A triangle marks an outlier. On the OSA panel the cut is qnorm(1 - 0.05 / (2 n)) for the panel’s n residuals, so under the model a panel shows 0.05 triangles on average whatever its size. The Pearson panel keeps |resid| > 3: those residuals are sum-constrained and overdispersed, not N(0, 1).

Choosing the one-step-ahead method

method selects how the conditional distribution is read. The default, "oneStepGaussianOffMode" (WHAM’s and SAM’s), approximates it as Gaussian. method = "cdf" asks the model for the conditional CDF and returns qnorm(F(x)): a binomial for a composition bin (defined at fractional counts), pnorm for the aggregate series. On a fixed-effect model nothing is approximated; with random effects see below.

The two disagree on composition data. Scored by simulating from a fitted model and residualizing at the generating parameters, where the right answer is exactly standard normal (BS2017SS, 20 replicates of 4538 composition bins):

method mean sd lag-1 acf within a composition KS rejects
oneStepGaussianOffMode +0.103 0.918 +0.060 every replicate
cdf, discrete = FALSE +0.610 1.262 +0.434 every replicate
cdf, discrete = TRUE −0.007 0.995 +0.001 none

The null standard error on the autocorrelation is 0.015, so only the last row is consistent with iid standard normal residuals. A composition bin holds a count, so its conditional CDF is a step function; the randomized quantile residual qnorm(F(x) − U f(x)) (Dunn and Smyth 1996, as Trijoulet et al. 2023 prescribe) removes the step, which is why discrete defaults to TRUE under "cdf". On the aggregate index and catch series, which really are Gaussian, all three agree to 5e-5 wherever the 8.04 ceiling below does not bind.

The step is the model’s, not the data’s: the likelihood reads counts as proportion × Sample_size, so on a fleet whose sample size has been tuned they are not whole fish, and a heavily down-weighted fleet is residualized against a multinomial it was never sampled from.

osa_cdf <- osa_residuals(model_1, source = c("index", "comp"), method = "cdf")
osa_diagnostics(osa_cdf)

Three things to know before switching:

  • predicted is NA on every row: the method forms no conditional mean. Fitted values are in model_1$quantities and in residuals(model_1, type = "pearson"). (sd is NA under the default method as well; only method = "oneStepGaussian" returns one.)

  • A Dirichlet-multinomial fleet cannot use it. Its beta-binomial conditional has no closed-form CDF and cannot be summed at a fractional count. Those fleets are residualized with "oneStepGaussianOffMode", announced in a message and recorded in the object’s method attribute, and their predicted is blanked too.

  • |residual| is censored at 8.04, in both directions: double precision sets the upper end, and the lower is matched so that a one-sided ceiling does not look like skewness. osa_diagnostics() computes SDNR and the tail statistics on the censored values, so the censoring bites hardest on a short series where one observation holds the statistic. osa_residuals() warns when any residual sits there. On a 12-year survey with one observation multiplied by 200:

    method min max non-finite SDNR
    oneStepGaussianOffMode −11.77 0.19 1 NA
    oneStepGaussian −11.77 38.98 0 12.89
    oneStepGeneric −3.95 3.33 0 2.21
    cdf −8.04 8.04 0 4.59

    Only "oneStepGaussian" reports the uncensored value here: the package default returns NaN on that row, so its SDNR is unusable, and "oneStepGeneric" compresses the outlier harder than the ceiling does. The default’s failure is magnitude-dependent (at a ×20 outlier it is finite and matches "oneStepGaussian"), so use "oneStepGaussian" itself, on the fleet in question: it costs an nlminb per observation.

With random effects, the choice reverses for the aggregate series

"cdf" is exact only on a fixed-effect model: with random effects its Laplace integration over the latent states is approximate, while for a Gaussian observation the Gaussian methods are exact. Measured against the exact Kalman innovations of a linear-Gaussian state space model, as the latent state becomes more informative relative to the observation:

latent/observation sd fullGaussian oneStepGaussian cdf
0.56 4e-16 3e-14 7e-04
1.12 1e-15 4e-14 6e-03
2.24 1e-15 3e-14 4e-02

That does not transfer wholesale: the Gaussian methods are exact when the one-step-ahead predictive is Gaussian, which needs the model to be linear in the random effects, and Rceattle’s index and catch are exp() of cumulated log recruitment deviations pushed through the population dynamics. On a 17-deviation fixture fullGaussian and oneStepGaussian, which cannot differ for a Gaussian conditional, differ by 0.091 on both index and catch, while "cdf" differs from oneStepGaussian by 0.017 on index. No method is exact for index or catch under random effects.

"ecov" is the exception, and there a Gaussian method is right. Its conditional (a Gaussian measurement of an AR1 latent) genuinely is linear-Gaussian: the two Gaussian methods agree to 4e-14 on the QAR1 fixture, while "cdf" sits 0.139 away, about a quarter of the residual sd.

The choice does not reverse for compositions, whose discrete, skewed conditional the Gaussian methods get wrong by much more. Simulating from a 22-random-effect model with the recruitment deviations redrawn and residualizing at the generating parameters (1680 residuals, 120 replicates):

method mean sd KS rejects
oneStepGaussianOffMode +0.513 0.404 120 of 120
cdf, discrete = TRUE +0.006 1.002 6 of 120 (the nominal 5%)

What limits "cdf" on compositions is the depth of the conditioning rather than the random effects themselves. On BS2017SS with random_rec = TRUE (159 random effects, 4538 composition bins) it returns 1879 non-finite residuals, against 0 for "oneStepGaussianOffMode" on the same fit, and takes hours; the same rows residualized on their own come back clean. Try it, read the warning it issues, and where the residuals come back non-finite in bulk fall back to a Gaussian method for that source, remembering that its composition residuals are the under-dispersed ones in the comparison above. Within one call every source uses method, apart from the automatic Dirichlet-multinomial, discrete = TRUE and TruncatedNormal overrides; discrete applies only to composition sources. (SAM’s authors split the method by data type, across two packages: stockassessment::residuals.sam() takes oneStepPredict()’s "oneStepGaussianOffMode" default with discrete = FALSE, while compResidual::resMulti(), the implementation Trijoulet et al. (2023) cite, hardcodes method = "cdf", discrete = TRUE.)

For every method, Estimate_index_sd = "Analytical", Estimate_catch_sd = "Analytical" and the analytical Catchability forms concentrate their parameter out using all the observations, including the one being residualized, so the residuals are approximate, by an amount that shrinks as the series lengthens.

Fleets with tail accumulation

Where a fleet folds its composition tails into a boundary bin (Comp_accum_young / Comp_accum_old), both the OSA and the Pearson residuals describe the bins the likelihood actually fit, not the raw bins in comp_data. A fleet on 10 ages with Comp_accum_young = 3 reports bins 3 to 10: bin 3 holds ages 1 to 3 combined, and the accumulated column (Accumulated from residuals()) marks it. The one-step-ahead decomposition drops each composition’s last bin, fixed by the sum-to-sample-size constraint, so under an old-tail accumulation the upper boundary bin appears in the Pearson residuals and not in the OSA residuals.

Following Stewart and Monnahan (2025), a practical workflow is:

  1. Inspect the aggregate fit (plot_comp(model_1), pooled across the fitted hindcast years): systematic lack of fit points to structural misspecification (e.g. the wrong selectivity shape). The interval holds 95% of the data the model predicts, not a confidence interval on the mean, so observations outside it are the ones to explain. The panel gives the input sample size, the effective sample size the likelihood assumed (ESS (likelihood)), and the one this fit’s residuals imply (ESS (McAllister-Ianelli)); the gap between the last two is the reweighting decision.
  2. Compare the SDNR to its null interval (from osa_diagnostics()): a value outside the interval flags over- or under-dispersion, often a data-weighting or effective-sample-size issue.
  3. Compare the lower/upper tail statistics to their null intervals, to localize departures to the tails. They are order statistics: lower_r / upper_r name which one and lower_p / upper_p its nominal probability (near but not exactly 2.5%), against the exact Beta(r, n - r + 1) null. osa_diagnostics() does not simulate, so its nsim / seed arguments are ignored.
  4. Inspect Pearson bubble plots (plot_comp(model_1), the default): the sign pattern across age/year can show where lack of fit occurs; Stewart and Monnahan recommend keeping these alongside OSA residuals.
  5. Revise the model or data weighting where misspecification is found, using this together with the other diagnostics rather than as an accept/reject test.

When the diagnosis is a weighting problem rather than a structural one, reweight_comps() runs the McAllister-Ianelli (1997) tuning loop, refitting the model as it was fitted and updating each fleet’s Comp_weights until the implied weights settle.

tuned <- reweight_comps(model_1, n_iter = 10, tol = 0.01)
tuned$reweight$history    # weight per fleet, per iteration

Restrict it with fleets =, giving Fleet_code values or names matching fleet_control$Fleet_name, not a mix (R coerces c(1, "Survey") to character).

tuned <- reweight_comps(model_1, fleets = c("Bottom_trawl", "Fishery"))

Only multinomial fleets are tuned: a Dirichlet-multinomial fleet estimates its own weight inside the likelihood, so those fleets are named and skipped.

The alternatives are Francis (2011) reweighting, applied by hand, and estimating the weights directly with a Dirichlet-multinomial likelihood (Thorson et al. 2017; Comp_distribution = "DirichletMultinomial"), with no iteration. Under that likelihood Comp_weights is the log of the starting weight, so the model default of 1 is a starting weight of e, and a weight of 1 is written 0.

Under discrete = TRUE (the default only for method = "cdf"), composition residuals are randomized quantile residuals, so stochastic; osa_residuals() takes a seed for reproducibility.

Process residuals

process_residuals() checks the process model: it standardizes the random-effect deviations (recruitment, initial abundance, catchability) against their process prior, drawing once from the joint posterior (SAM’s procres; Nielsen and Berg 2014). Under a correct process model these too are approximately iid standard normal.

pr <- process_residuals(model_1, process = "recruitment")
osa_diagnostics(pr)
plot(pr)

# residuals() exposes them too:
residuals(model_1, type = "process")

Retrospective analysis

A retrospective analysis removes the most recent years of data one peel at a time and re-fits the model. Mohn’s rho (Mohn 1999), averaged over peels as in Hurtado-Ferro et al. (2015), summarizes how the terminal estimates shift across peels; for SSB, a rho outside ±0.2 generally signals a problem worth investigating.

model_1_retro <- retrospective(model_1, peels = 5)

# Mohn's rho for each quantity
model_1_retro$mohns

# Plot historical trajectories across peels
plot_biomass(model_1_retro$Rceattle_list)

# Include the projection period to see how the forecast changes
plot_biomass(model_1_retro$Rceattle_list, incl_proj = TRUE)

Each peel holds its own terminal year as data_list$endyr, so the first plot draws every peel only as far as it was fit. retrospective() returns:

Element Description
Rceattle_list the fitted peels, deepest first, then the full run, each named for its terminal year (Year_2017, …, Year_2022)
mohns Mohn’s rho (mean relative error) by Object ("biomass", "ssb", "R", "F_spp") and Forecast year (0 = terminal-year bias; 1 to nyrs_forecast, default 3, = forecast skill), with N the peels used in that row and one column per species
peels_requested the peels asked for

A peel is refitted as a model ending at its terminal year. The years it dropped are then its retrospective forecast: F is fitted to the observed catch, with those years’ survey and composition data withheld, and so is their env_data, except the columns ?retrospective lists. The forecast years are endyr_peel + seq_len(endyr_full - endyr_peel), where endyr_peel is the peel’s terminal year and endyr_full the unpeeled one; the harvest control rule takes over after endyr_full, through projyr, and incl_proj = TRUE plots both. A series known ahead, such as a climate projection, goes in projected_env_data_known = "<column>" so the peels keep it, and rescale = "<column>" standardizes a covariate on each peel’s retained years.

print(model_1_retro) counts the peels that were dropped or flagged:

  • A peel whose hindcast did not converge is dropped with a warning (under getsd = TRUE, so is one whose hindcast Hessian is not positive definite), so index Rceattle_list by name rather than position. If no peel converges, Mohn’s rho is NaN and the call warns.
  • A peel whose forecast refit did not fit F to the peeled catch is kept with no warning, but only in the $mohns rows with Forecast year 0; attr(peel, "forecast_refit_error") gives the reason. plot_biomass() and the other plot_timeseries() wrappers warn when they draw that peel’s forecast years; plot_catch(), the other plotters and as.data.frame() do not.
  • Under getsd = TRUE (the default when the input model has standard errors), a peel whose standard-error rebuild fails after its forecast refit is kept with no warning, but plot_biomass(), as.data.frame() and vcov() read none from it, since peel$sdrep may then hold no valid standard errors; attr(peel, "sd_report_error") gives the reason.

?retrospective covers the standard-error bands, how a peel treats each env_data column, and rescale.

Jitter testing

Jitter testing re-fits the model from many randomly perturbed starting values and checks whether the optimizer keeps returning the same minimum negative log-likelihood (NLL); a spread of NLL values points to multiple local minima. Each start re-fits under the fit’s own map (which parameters are estimated and which are fixed), so a parameter you fixed keeps its value, and the NLL values compare with the fit’s unless it used fit_mod(bounds = ). A projection-only fit (estimateMode = "Projection") re-fits under the default map from build_map(), so nothing fixed in its map carries over and its NLL values do not compare; see ?jitter.

jitters <- jitter(model_1, njitter = 10, phase = TRUE)  # default njitter = 50

# Histogram of NLL differences relative to the best run
hist(log(jitters$nll - min(jitters$nll)),
     main = "Jitter NLL spread (log scale)",
     xlab = "log(NLL - min NLL)")

# Overlay biomass trajectories, tight overlap indicates a stable optimum
plot_biomass(jitters$Rceattle_list)

# Number of runs that converged
length(jitters$Rceattle_list)

Non-converging runs are dropped from Rceattle_list and reported in a message, so if length(jitters$Rceattle_list) is well below njitter, convergence is fragile; the dropped starts are the ones that wandered off, so the successes alone understate the spread. A run is dropped when its maximum absolute gradient exceeds 1 (the FAIL threshold in convergence_diagnostics()) or when a requested sdreport failed or gave pdHess = FALSE.

retrospective() and jitter() both fit peels / starts in parallel by default, on parallel::detectCores() - 6 cores (2 under R CMD check); pass cores = 1 to run them sequentially.

Self-test (simulation–estimation)

self_test() simulates nsim datasets from a fitted model (holding its estimated parameters fixed) and re-fits the model to each. If the refit estimates cluster around the values used to simulate them, the model can at least recover its own estimates from data it generated; persistent bias or a wide spread in a quantity means the data are not informative about it. Each simulation re-fits under the fit’s own map, so a parameter you fixed keeps its value.

sims <- self_test(model_1, nsim = 10)            # default nsim = 50

# Number of simulations that converged (non-converged runs are dropped)
length(sims)

# Overlay biomass / SSB trajectories across simulations, the original fit's
# trajectory should sit inside the spread of the refits.
plot_biomass(c(list(model_1), sims), model_names = c("fit", names(sims)))
plot_ssb(c(list(model_1), sims),     model_names = c("fit", names(sims)))

Each simulation uses seed + i as its RNG seed, so results are reproducible whether or not cores > 1. Set simulate = FALSE to refit against the model’s expected values (no observation error), to confirm that the estimator returns the generating parameters in the noise-free limit. cores behaves as in retrospective() and jitter().

Every refit starts from the fitted model’s starting values, not its estimates, and phase defaults to whatever the input model was fit with; pass phase = TRUE if you fit the model some other way and the refits are being dropped. start = "estimated" starts from the fitted estimates instead: much faster, but the optimizer then begins inside the basin containing the generating values, so recovery is close to guaranteed by construction; read it as optimistic.

When reading the result:

  • Non-converged refits are dropped (reported in a message) because they behaved badly, so any spread or bias computed over the rest (including compare_sim()’s CV) understates the truth.
  • By default only the observations are redrawn: every replicate shares the operating model’s single realization of recruitment and mortality, so the spread is observation error alone, a lower bound on estimation uncertainty in SSB and recruitment, not comparable to the model’s own uncertainty bands.
  • Watch for a truncation warning on a natural-scale index. A fleet with Index_distribution = "Normal", "MVN" or "MVNORM" is drawn on the natural scale with an absolute sd, so a draw can come out negative, which data_check() rejects. Those draws are redrawn, sampling the fleet from a normal truncated at zero rather than the untruncated normal the likelihood maximises. Occasional truncation is harmless; a lot is not. sim_mod() warns above 2% truncation: for a Normal fleet, when any row puts more than 2% of its probability at or below zero, Phi(-mu/sd), read off the fit, so it does not vary between replicates; for an MVN/MVNORM fleet, whenever that replicate rejected a whole-vector draw, so it varies between replicates.

The fix for a Normal fleet is Index_distribution = "TruncatedNormal", which fits the truncated density, renormalized by log Φ(µ/σ) over (0, ∞), and draws from it by inverse CDF, so draw and likelihood agree and no draw is rejected. "Normal" reproduces the AMAK avo_like / cpue_like term for term, which is what an ADMB bridge compares against; use it there and "TruncatedNormal" elsewhere (data_check() refuses "TruncatedNormal" with Catchability = "Analytical"). MVN/MVNORM have no truncated option, so the gap stays. Either way, an absolute sd that large relative to the index means the natural-scale normal was a poor observation model to begin with.

"TruncatedNormal" OSA residuals need nothing from you. The Gaussian methods (including the default oneStepGaussianOffMode) would return the untruncated (obs - µ)/σ, so osa_residuals() overrides method for those rows only, integrating the truncated density to give qnorm(F(x)); under method = "cdf" the model supplies the truncated F in closed form. The correction is the size of the truncated mass: on a fleet predicting 100 with an absolute sd of 150, an observation exactly at the prediction moves from a residual of 0 to −0.44.

Redrawing process error

The default process = FALSE asks whether the estimator recovers its own parameters from new observations; naming a process redraws that process too, and asks whether it recovers something it was not shown.

# Recruitment deviations redrawn as well as the observations
sims <- self_test(model_1, nsim = 10, process = "recruitment")

# "dynamics" covers recruitment, M and growth; "observation" covers
# catchability and selectivity; TRUE covers everything.
sims <- self_test(model_1, nsim = 10, process = "dynamics")

Recruitment covers the initial age structure as well as the hindcast deviations, since the initial numbers-at-age are recruitment from before styr. Natural mortality covers the M1_re random effects, and growth, catchability and selectivity are redrawn wherever they are written as a random linkage (see vignette("environmental-linkages-and-priors")). A process the model gives no distribution to (asking for M when M1_re = 0, say) is left alone and reported in a warning. Redrawing a deviation the fit’s map fixes also warns, because the refit holds it fixed and cannot recover the draw.

Recruitment has one such case. Under srr_fun = 0 with srr_pred_fun > 0 (the AMAK/Ianelli configuration, where recruitment is estimated annually and the stock-recruit curve is fitted as a penalty on those same deviations) the deviations are scored by two densities at once, which do not compose into a distribution to draw from: the penalty couples them to the stock-recruit parameters, which are estimated too, so drawing from either term alone would test recovery against a process the model does not assume. The deviations are not redrawn and sim_mod() says why; a random linkage on a recruitment parameter is a separate latent and is still drawn. Set srr_fun to the stock-recruit function itself to redraw the deviations.

The fitted deviations are not what generated the data; the values that did are attached to each replicate, each with a mask of the cells the draw touched:

truth <- attr(sims, "process_sim")[["Sim_1"]]
rec   <- truth$rec_dev[truth$rec_dev_drawn]

Compare estimates against those, not against the operating model, and only over the mask: the process draws cover the hindcast only, and beta_linkage_re spans every random linkage whether or not its process was asked for. For the same reason compare_sim(), which compares against the operating model, is not valid for process-drawn replicates.

Read a self-test that redraws M as a test of deviation recovery rather than of variance recovery. On BS2017SS with a year-varying M random effect, refits recover the simulated deviations (correlation around 0.5, positive in every replicate) but their standard deviation roughly 70% low, collapsing to zero in a third of replicates: a year-varying M is weakly informed, since it trades off against selectivity and catchability.

When the returned list is shorter than nsim, debug = TRUE returns every simulation, so the failures can be read directly:

sims <- self_test(model_1, nsim = 10, debug = TRUE)

failed <- names(which(!attr(sims, "converged")))
sims[[failed[1]]]$convergence          # which check failed, and on which parameter

Likelihood profile

profile() re-fits the model across a grid of fixed values for a chosen parameter and returns the NLL surface. A flat profile means the data say little about the parameter; a minimum away from the MLE means the fit has not truly settled there.

Specify the parameter with a natural-scale alias, which takes natural-scale values directly: "sigmaR" (the standard deviation of the log-scale recruitment deviations, not a CV of recruitment in thousands of fish), "M1" (natural mortality), or the stock–recruit parameters "R0", "alpha", and "beta". slots gives the cell(s) to profile (usually just the species index) and values the grid of values for each; more than one slot profiles over the full grid of combinations.

# 1-D profile: sigmaR for species 1 (natural-scale alias)
prof_sigmaR <- profile(
  fitted = model_1,
  param    = "sigmaR",
  slots    = list(1),
  values   = list(seq(0.1, 1.5, by = 0.1))
)

plot(prof_sigmaR)   # components, with the total overlaid; see below

# 1-D profile: SRR alpha for species 1
# (alias fills in the rec_pars column; slot is just the species index)
prof_alpha <- profile(
  fitted = model_1,
  param    = "alpha",
  slots    = list(1),
  values   = list(seq(2, 80, length.out = 20))
)

# Profile M1 for species 1, sex 1, age 1
prof_M_sex <- profile(
  fitted = model_1,
  param    = "M1",
  # One slot per sex on a two-sex model. This one is single-sex, so sex 1 is
  # the only slot there is -- asking for sex 2 is out of bounds for log_M1.
  slots    = list(c(1, 1, 1)),
  values   = list(seq(0.10, 0.40, by = 0.05))
)

Moving a set of cells together

slots cross, so k slots give a k-dimensional profile: an empirical age-based M profiled over 13 values across ten ages would be 13^10 fits. joint puts every named cell on one grid instead: "multiply" scales each cell’s current value, preserving the shape of the schedule (1 is the fitted model), and "add" shifts it, preserving the increments (0 is the fitted model).

sp <- 1
prof_M_all <- profile(
  fitted = model_1,
  param  = "M1",
  slots  = lapply(seq_len(model_1$data_list$nages[sp]),
                  function(a) c(sp, 1, a)),   # every age bin of species 1
  values = list(seq(0.7, 1.3, by = 0.05)),
  joint  = "multiply"
)

plot_profile(prof_M_all)

Catchability

param = "q" profiles a fleet’s base catchability, and slots takes a fleet name. Fleets sharing a Catchability_index share one q, so naming any member profiles the whole group; the others are added with a message.

prof_q <- profile(
  fitted = model_1,
  param  = "q",
  slots  = list("Bottom_trawl"),
  values = list(seq(0.5, 2.0, by = 0.1))
)

profile() returns Rceattle_list (one fit per grid row, NULL where the fit failed), grid (the user-scale value grid, a multiplier or offset under joint), nll (joint NLL aligned with grid, NA for non-converged fits), alias (the natural-scale name you profiled under, if you used one), joint, and echoes of param and slots. To cross-profile across species, supply one slot per species (e.g. slots = list(1, 2, 3) with param = "sigmaR"); across sex on a two-sex model with sex-specific M1 (M1_model 2 or 3), one slot per sex (e.g. slots = list(c(1, 1, 1), c(1, 2, 1)) with param = "M1"). cores behaves as in the other diagnostic functions.

Where the data disagree

The total says how well the data determine the parameter, not whether the data sources agree about it: a smooth quadratic total can be two surveys pulling in opposite directions. plot_profile() draws the components separately, as r4ss::SSplotProfile() does.

prof_M <- profile(
  fitted = model_1,
  param  = "M1",
  slots  = list(c(1, 1, 1)),
  values = list(seq(0.20, 0.45, by = 0.025))
)

plot_profile(prof_M, xlab = "M at age 1")

Read it by where each curve bottoms out, not by how deep it is: every series is re-zeroed at its own minimum and a point marks it, so the spread of those points along the x axis is the disagreement. The heavy black line is the total.

When one component dwarfs the rest, the others flatten onto the axis; relative = "scaled" puts every curve on 0 to 1 so the minima can be compared. It discards magnitude, so raise minfraction alongside it.

profile_components() returns the same numbers, one row per grid point per component, each labelled with the fleet or species it belongs to.

comps <- profile_components(prof_M)
head(comps)

Under random_rec = TRUE the total is the Laplace-approximated marginal likelihood while the components are the inner joint negative log-likelihood, so they will not sum; compare the shapes, not the sums. See ?plot_profile for relative, minfraction, model overlays, and which components weighted = FALSE changes.

Comparing runs

Overlaying sensitivity runs is itself a diagnostic: large divergences in biomass or mortality deserve scrutiny.

mod_list  <- list(model_1, model_1_retro$Rceattle_list$Year_2019)
mod_names <- 1:length(mod_list)

plot_biomass(Rceattle = mod_list, model_names = mod_names)
plot_recruitment(Rceattle = mod_list, model_names = mod_names, add_ci = TRUE)
plot_ssb_depletion(Rceattle = mod_list, model_names = mod_names)

Collecting it into report tables

report_tables() gathers into tidy tables the fit, the likelihood decomposition, the time series with uncertainty, the reference points, the fits to index and catch, and whichever diagnostics you pass it:

tabs <- report_tables(model_1,
                      retro = model_1_retro, jitter = jitters, osa = osa)
tabs
tabs$retrospective          # Mohn's rho by species and forecast year
tabs$osa                    # SDNR and tail statistics per fleet

It never refits, so a diagnostic you have not run is an absent section. Check the basis column of tabs$reference_points before quoting a reference point: quantities the fit never estimated are returned as NA with the reason. standard_output() relabels the result for the stockplotr and asar reporting packages.

Model average

To average estimates across model variants, see ?model_average.

mod_avg <- model_average(list(model_1, model_1), weights = c(1,1))
plot_biomass(mod_avg)

With uncertainty = TRUE, each fit’s parameters are drawn from its asymptotic covariance. Under any harvest control rule but "NoFishing", an estimateMode = "Estimate" fit is refused unless it used fit_control(projection_uncertainty = TRUE), which works for fixed-effects fits under any rule but "ConstantF"; ?model_average gives the refits. A "Hindcast" refit projects with no fishing, so its averaged projection is of an unfished stock.

References

  • Dunn, P.K., Smyth, G.K. (1996). Randomized quantile residuals. Journal of Computational and Graphical Statistics, 5, 236-244.
  • Francis, R.I.C.C. (2011). Data weighting in statistical fisheries stock assessment models. Canadian Journal of Fisheries and Aquatic Sciences, 68, 1124-1138.
  • Hurtado-Ferro, F., Szuwalski, C.S., Valero, J.L., Anderson, S.C., Cunningham, C.J., Johnson, K.F., Licandeo, R., McGilliard, C.R., Monnahan, C.C., Muradian, M.L., Ono, K., Vert-Pre, K.A., Whitten, A.R., Punt, A.E. (2015). Looking in the rear-view mirror: bias and retrospective patterns in integrated, age-structured stock assessment models. ICES Journal of Marine Science, 72, 99-110.
  • McAllister, M.K., Ianelli, J.N. (1997). Bayesian stock assessment using catch-age data and the sampling-importance resampling algorithm. Canadian Journal of Fisheries and Aquatic Sciences, 54, 284-300.
  • Mohn, R. (1999). The retrospective problem in sequential population analysis: an investigation using cod fishery and simulated data. ICES Journal of Marine Science, 56, 473-488.
  • Nielsen, A., Berg, C.W. (2014). Estimation of time-varying selectivity in stock assessments using state-space models. Fisheries Research, 158, 96-101.
  • Stewart, I.J., Monnahan, C.C. (2025). Diagnosing common sources of lack of fit to composition data in fisheries stock assessment models using one-step-ahead (OSA) residuals. Canadian Journal of Fisheries and Aquatic Sciences, 82, 1-13.
  • Stock, B.C., Miller, T.J. (2021). The Woods Hole Assessment Model (WHAM): a general state-space assessment framework that incorporates time- and age-varying processes via random effects and links to environmental covariates. Fisheries Research, 240, 105967.
  • Thorson, J.T., Johnson, K.F., Methot, R.D., Taylor, I.G. (2017). Model-based estimates of effective sample size in stock assessment models using the Dirichlet-multinomial distribution. Fisheries Research, 192, 84-93.
  • Thygesen, U.H., Albertsen, C.M., Berg, C.W., Kristensen, K., Nielsen, A. (2017). Validation of ecological state space models using the Laplace approximation. Environmental and Ecological Statistics, 24, 317-339.
  • Trijoulet, V., Albertsen, C.M., Kristensen, K., Legault, C.M., Miller, T.J., Nielsen, A. (2023). Model validation for compositional data in stock assessment models: calculating residuals with correct properties. Fisheries Research, 257, 106487.