Can the fitted model reproduce observations and predict withheld time steps?
View source ↗On this page
On this page you check a fitted model from two sides. Fitted-model simulation draws new survey data from the fit and refits them, to see whether the estimates recover the known values; hindcast validation fits on the earlier time steps and scores the predictions of the withheld later ones against the observations. You need the package installed (Install ALSCL); the code uses the synthetic YTF_example. Steps 3 and 4 refit the models several times, so allow time for the optimizations; runtime depends on your computer and the fitting settings. For hindcast validation alone, run step 1 and go to step 4. At the end you have simulated datasets with their truth, a table of bias, RMSE and interval coverage, the prediction scores of both models against a persistence baseline, and a saved fit.
1. Load the input bundle
library(ALSCL)
data("YTF_example")
x <- YTF_example
x contains the three survey tables and the model settings. For hindcast validation alone, continue directly to step 4, which fits the training windows from x and requires no full-data fit. For simulation, continue to step 2.
2. Generate survey observations from the fit
Fit the source model for simulation
b <- run_alscl(x, silent = TRUE)
b$diagnostics
stopifnot(b$diagnostics$numerical_ok)
b is the ALSCL fit that the simulations start from. Its numerical_ok must be TRUE, because simulate_fit() rejects a fit that failed the numerical checks unless allow_failed_fit = TRUE; if it is FALSE, follow Judge whether a fit can be used before simulating. The teaching example fixes growth and several process parameters through map; with your own bundle choose supported biological settings (Choose the fitting settings). Each simulated x preserves the source fit's effective fixed scalar values, including mean_log_R when its value was derived from the original data. To choose a particular fixed value yourself, provide it in parameters when fitting the source model.
Keep the fitted population states
conditional <- simulate_fit(b, nsim = 3, seed = 20261101,
process = "conditional")
conditional$metadata
conditional$simulations[[1]]$observations[1:3, 1:3]
process = "conditional" keeps the fitted population and redraws only the observation error, the shortest way to see repeated surveys of the same states. metadata records the model, the process, the seed, the original observation mask, the status of the source fit and the assumption parameter_uncertainty = "none".
Generate new population trajectories
resampled <- simulate_fit(b, nsim = 3, seed = 20261101,
process = "resample")
resampled$simulations[[1]]$truth$SSB
simulated_x <- resampled$simulations[[1]]$x
process = "resample" also draws new process deviations of recruitment, fishing mortality and initial abundance at the fitted scalar parameter values. Recruitment and F follow the fitted stationary AR(1) processes (one shared F time series across groups, with one F value per time step, under F_structure = "year"), the deviations of the initial numbers at age are drawn in the form that the fit uses (accumulated over age classes by default, independent by age class with structure = list(initial_deviations = "independent")), and the C++ population model turns the draws into a new population. Conditional draws use the source fit's Elog_index; resampled draws use Elog_index recomputed from the new process states. Each mode adds observation noise on the log scale using the fitted observation SD, so exp(Elog_index) for that state is the observation median; scalar parameters, biology and survey catchability stay fixed, so neither mode carries parameter uncertainty. Each element of $simulations holds observations (length bins by time steps), truth (population quantities, scalar parameters and the deviations used) and x, an input bundle for run_alscl() that keeps the fitting configuration of b except output, ncores and silent, which you choose when fitting it. Missing and zero cells of the original survey stay as they are unless preserve_missing = FALSE; the seed makes the draws repeatable, and the caller's random-number state is restored afterwards. A map that fixes or ties the process deviations stops the resample mode, while conditional draws still work. For an operating model with its own recruitment assumptions, use Simulate survey data.

The figure shows three draws per mode, conditional on the left and resampled on the right, in one row for each of the length bins 6, 28 and 50 cm; the black dashed line is the fitted log median. Conditional draws scatter around the same fitted states, and resampled draws also move the trajectory. Each curve is one draw, an example of the generating distribution.
3. Refit the replicates and compare with the truth
replicate_fits <- lapply(resampled$simulations, function(s) {
tryCatch(run_alscl(s$x, nstarts = 2, ncores = 1, silent = TRUE),
error = function(e) list(error = conditionMessage(e)))
})
truth <- lapply(resampled$simulations, function(s) s$truth)
performance <- summarize_simulations(replicate_fits, truth,
quantities = c("SSB", "Rec"))
performance$replicates
performance$summary
Each refit is an ordinary fit of the simulated bundle, run_alscl(s$x) here and run_acl(s$x) for draws from an ACL fit, with two starts each; tryCatch() keeps the error message of a failed replicate so that it stays in the summary. summarize_simulations() matches the fits with the truth by replicate name and year and returns replicates (numerical checks, time and error of each fit) and summary (per quantity: failure rate, bias, relative bias, RMSE and interval coverage with their denominators); bias and RMSE use the fits that passed the checks, and coverage uses only intervals with a finite standard error (Simulate survey data explains the denominators). In the recorded run all three refits passed, with coverage of the default lognormal intervals 0.98 for spawning stock biomass (SSB) and 0.95 for recruitment over 60 pairs (1.0 and 0.95 with interval = "wald") (simulation-performance.csv). The elapsed column of performance$replicates records seconds per refit. Three replicates show the mechanics; a study of bias or coverage needs enough replicates for the failure rate to mean something, and a parametric bootstrap also needs a stated refitting protocol and interval construction, for which simulate_fit() supplies only the generating step. For replicates already on disk, sim_model() fits them in batch (Simulate survey data).
Run a self-test in one call
a <- run_acl(x, silent = TRUE)
st <- self_test(a, nsim = 5, seed = 20261101, process = "conditional")
st
head(st$by_year)
plot_self_test(st)
self_test() does steps 2 and 3 in one call. It simulates nsim data sets with simulate_fit(), refits the same model to each with the settings stored in the fit, and compares the estimates with the values used to simulate them. The example uses an ACL fit, a, because one ACL fit takes a few seconds; self_test(b) works in the same way for ALSCL. process has the meaning of step 2. With "conditional" the population stays that of the source fit, so the truth is the same in every replicate; with "resample" new recruitment, F and initial deviations are drawn from their estimated distribution, so each replicate has its own truth and the test also covers the estimated process variances. By default each refit starts from the starting values of the source fit, with its number of starts, so that a refit that stops at a local optimum counts as an error, as it would with real data. start = "estimates" starts each refit at the values used to simulate; this is faster but can hide local optima and parameters that the data do not determine. ncores fits several data sets in parallel.
With "conditional" the deviations of the source fit are kept as they were fitted, and their arithmetic mean need not be zero. The truth of every scalar parameter, mean_log_F and mean_log_R included, is still its estimate in the source fit. At the estimate, the mean parameter of an AR(1) process is close to a weighted mean of the fitted process in which the first and last time steps weigh more, and a refit that recovers the process recovers this weighted mean. The level of F and recruitment is measured by the time series, whose truth is the realized process. Parameters that can trade off with the deviations, such as init_Z with the initial deviations, are also better judged by the time series.
Printing st shows how many refits pass the numerical checks and, for each time series and estimated parameter, the median relative error (the bias), its 10th and 90th percentiles, the median absolute relative error and the coverage of the approximate 95% intervals. The relative error is (estimate - truth) / truth. F is the mean over ages here and has no standard error, so it has no coverage. st$by_year gives the same summaries by year, st$replicates the checks of each refit, and st$series and st$parameters every estimate with its truth; refits that fail the checks stay in these tables but not in the summaries. In the recorded run all five refits passed. The median relative error was -0.2% for SSB, -0.5% for recruitment and 1.9% for mean F, and 99 and 98 of the 100 intervals of SSB and recruitment contained the truth (self-test-summary.csv). Five data sets show how the function works; Deroba et al. (2015) used 100 simulated data sets for each self-test.

The upper panels show the median relative error by year (line) and its 10th to 90th percentiles across the refits (band); the dashed line marks no error. The lower panel shows the median (point) and the 10th to 90th percentiles (line) for the estimated parameters, on the natural scale and named in words, for example "Median recruitment" for mean_log_R. Here the medians stay within 8% of the truth in every year; with five data sets most of their change from year to year is noise. A self-test in which the estimates recover the truth shows that the model can estimate its parameters from data like these when its assumptions hold. It says nothing about the bias from a wrong natural mortality rate, survey catchability or growth form. In the North Sea whiting case, another M or another shape of survey catchability changed the level of F, SSB or recruitment while their trends hardly changed; testing such errors needs simulations from an operating model with different assumptions (Simulate survey data).
4. Predict time steps withheld from fitting
acl_validation <- hindcast_model(x, model = "acl", horizon = 1,
nfolds = 2, min_train = 8, nstarts = 1, ncores = 2)
alscl_validation <- hindcast_model(x, model = "alscl", horizon = 1,
nfolds = 2, min_train = 8, nstarts = 1, ncores = 2)
acl_validation$diagnostics
alscl_validation$diagnostics
acl_validation$scores
alscl_validation$scores
head(alscl_validation$predictions)
hindcast_model() fits each model using data through a forecast origin, the last time step in that training dataset, then predicts the next horizon survey-index steps. It uses the last nfolds eligible origins, starting each fit afresh from x with the stored configuration. Here each model uses data through 2017 to predict 2018, and through 2018 to predict 2019.
| Setting | Meaning in this annual example |
|---|---|
horizon = 1 |
Predict one time step ahead |
nfolds = 2 |
Use the last two eligible forecast origins |
min_train = 8 |
Require at least eight training time steps |
ncores = 2 |
Run at most two training folds in parallel; the starts inside a fold run one after another |
horizon and min_train count time steps (quarters for quarterly data); each fold truncates the three tables and the time-varying maps, and a map that fixes or ties the process deviations over time stops the call. Read $diagnostics first. It has one row per fold with origin, the numerical checks, prediction_ok, warnings and errors; a fold that failed stays in the table and contributes no predictions or scores. $predictions lists every withheld cell with the observed, predicted and persistence log index and an inclusion flag.

The figure has one row for each of the length bins 6, 28 and 50 cm and one column for each model, and compares the withheld log survey index ("Observed") of 2018 and 2019 with two predictions. The naive forecast (naive method), "Last observed value" in the figure, repeats the latest positive training observation in that bin. For the "Model prediction", the model advances the population using the fitted AR(1) paths for log recruitment and log F deviations (the last deviation times phi raised to the forecast horizon). On this path, predicted numbers at each length multiplied by the specified survey catchability give the median survey index on the original scale. The last training weights and maturity are reused for biomass. These point predictions hold parameters fixed and omit future process innovations. Choose fixed values and starting values using training data only, and compare models on the same forecast origins, horizons and observations.
5. Read the scores and save the analysis
Read the scores and their sample sizes together
| Output | How to read it |
|---|---|
n_positive, n_prediction, n |
Positive withheld observations, those with a model prediction, and cells scored for both model and persistence |
log_RMSE, log_MAE |
Prediction error on the log-index scale; smaller is better on those cells |
naive_log_RMSE, naive_log_MAE |
The persistence errors on the same cells |
log_MASE, naive_log_MASE, n_scaled |
Scaled absolute errors and the number of cells with a usable training scale |
Scores use natural-log survey indices; zero and missing withheld observations are excluded, and model and persistence errors use the same cells. For MASE, divide each absolute log error by the mean absolute log-index change between adjacent training time steps in that length bin, using pairs whose two observations are positive. The time grid is retained across missing or zero observations. Bins without a usable pair, or with a zero scaling denominator, receive no scaled score; check n_scaled before interpreting the result. In the recorded run both models scored the same 46 positive observations of 2018-2019 and all four training fits passed the checks (hindcast-scores.csv):
| Prediction | Scored observations | Log RMSE | Log MAE | Log MASE |
|---|---|---|---|---|
| ACL | 46 | 0.097 | 0.081 | 0.42 |
| ALSCL | 46 | 0.22 | 0.18 | 0.95 |
| Persistence | 46 | 0.17 | 0.15 | 0.74 |
On this synthetic dataset, with the teaching maps and two origins, ACL predicts better than persistence and ALSCL worse. All four training fits passed the numerical checks, so the difference does not come from a failed fit. The data come from an age-based operating model whose growth structure is that of ACL (Do ACL and ALSCL give different answers?), and two validation time steps give no general ranking of the models.
Save the validation results
validation_file <- tempfile(fileext = ".rds")
saveRDS(list(acl = acl_validation, alscl = alscl_validation),
validation_file)
The validation results are plain lists, so saveRDS() keeps both models together. Replace the temporary path with a permanent file. This completes the hindcast-only route.
Save the source fit after simulation
Run this block if you fitted b in step 2. If you only ran hindcast validation, continue to What next.
archive <- tempfile(fileext = ".rds")
save_assessment(b, archive)
saved <- read_assessment(archive)
saved$recipe$implementation
again <- simulate_fit(saved, nsim = 1, seed = 20261101,
process = "conditional")
save_assessment() writes the saved fit without the live TMB object, and simulate_fit() accepts what read_assessment() returns, so a new session can simulate without refitting; the same seed gives the same draws. saved$recipe$implementation records the package versions, the source revision and the hashes of the model source, which refit_model() compares with the current installation, warning on a difference. Keep the simulation objects and truth beside this fit in permanent files.
What next
| What you want to do | Read |
|---|---|
| Examine residual patterns of the source fit | Judge whether a fit can be used |
| See how the estimates change when recent time steps are removed | Do estimates change when recent data are removed? |
| Test the sensitivity to the fixed values | How sensitive is an assessment, and what happens under future F scenarios? |
| Fit many simulated replicates in batch | Simulate survey data |
| Regenerate the figures and tables of this page | From the repository root: pkgload::load_all("."); source("scripts/model_validation.R"); run_model_validation_guide() |