
Calibrating Atlantis model with atlantio and calibrar
2026-10-20
Source:vignettes/calibration/index.Rmd
index.RmdSemi-automatic calibration of an Atlantis model using
calibrar, following the approach described in Morell et al. (2026).
Overall approach
As described in Morell et al. (2026), the goal
of using calibrar is to automate the running of batches of
simulations to improve model fit, while letting modellers nudge the
model in the right direction. The model is run many times, and the set
of parameters to shuffle is optionally revisited as calibration
progresses.
An Atlantis model includes a tremendous number of parameters, so
calibrating them all at once is out of reach. Instead, calibration
proceeds in rounds: a small set of parameters is chosen (e.g. growth and
clearance rates of a few groups), an optimizer such as
calibrar (https://CRAN.R-project.org/package=calibrar) searches
their values, the results are inspected, and the set of parameters or
their bounds are revised before the next round.
Each round involves the same steps:
- choosing the parameters to calibrate, with their bounds and scale;
- assembling the model inputs and a way to run the model;
- designing an objective function that runs the model for a candidate parameter set and returns a score;
- running the optimization, usually in parallel;
- inspecting the results, including the runs that crashed.
atlantio handles the Atlantis-specific parts: checking
the input files, reading and writing the parameter files, expanding a
calibration table, transforming parameter values, reading the model
output and scoring it. calibrar handles the optimization.
Morell et al. (2026) use
atlantis2ls (https://github.com/alaiam/atlantis2ls) for the same role
as atlantio.
How calibrar works
See https://roliveros-ramos.github.io/calibrar/articles/calibrar.html.
calibrar::calibrate() minimizes an objective function
fn(par, ...) over a parameter vector par
bounded by lower and upper. With the
evolutionary strategy method = "AHR-ES", every generation
evaluates a population of popsize parameter sets; with
parallel = TRUE, these evaluations are spread over the
workers of a registered foreach backend. The state of the
optimization is saved in a restart file every REPORT
generations, so an interrupted calibration resumes where it stopped.
Everything therefore boils down to writing one R function that takes
a parameter vector, writes the corresponding Atlantis input files, runs
the model, reads its output and returns a single number. The rest of
this vignette walks through building that function and running it with
calibrar.
Step 1: choose the parameters to calibrate
The parameters to calibrate are described in a YAML file, one entry
per parameter name. The <GRP> placeholder is expanded
over the listed group codes, and min, max and
transf give the bounds and the transformation used during
the search. Searching on a log scale (pow10,
exp) is recommended for rate parameters that span several
orders of magnitude.
- name: mum_<GRP>
GRP: [GRP1, GRP2, GRP3]
min: -5
max: -1
transf: pow10 # or exp, pow2
- name: C_<GRP>
GRP: [GRP1, GRP2, GRP3]
min: -5
max: -1
transf: pow10generate_calibration_table() expands this file into a
table with one row per value to optimize: array parameters (e.g. one
value per cohort) yield one row per position. It needs the biology
parameter file and the group file loaded first, so that it knows the
groups and the array lengths.
mod <- new_atlantis() |>
atlantis_load_files(c("biology.prm", "groups.csv"))
calib_table <- generate_calibration_table(mod, "calibration.yaml")The columns min and max of
calib_table are passed to calibrar as bounds;
name, position and transf are
used by the objective function to write the values back into the biology
file.
Step 2: assemble the inputs and a model runner
Input files
Gather every input file the model needs (run, physics, biology, forcing, initial conditions, groups, fisheries, geometry) in a base directory. Each evaluation copies this directory and rewrites only the parameter files that contain calibrated parameters, typically the biology file.
Large forcing data (often several GB) should not be copied per run: mount it read-only into the container, or symlink it into each run directory.
Checking the inputs
A calibration multiplies the cost of every input error by the number
of runs, and many errors do not stop Atlantis: they silently change what
it reads. Check the base inputs once before launching anything.
check_prm() scans the parameter files line by line and
reports, among others, arrays whose declared length does not match their
values (Atlantis pads or truncates them, read_prm()
aborts), duplicated keys, Windows line endings, time units that Atlantis
ignores (it then reads the time in seconds), and the stocking flag
combinations known to give wrong results. check_init()
checks the initial-conditions file in the cells Atlantis actually uses:
NaN or negative values, cells left unset where Atlantis silently uses a
non-zero _FillValue, groups switched on but missing or
empty, and pools orders of magnitude away from the other groups of their
type.
check_prm(bio = "biology.prm", run = "run.prm", force = "force.prm")
check_init("init.nc", "groups.csv")Both return an atlantis_check table with one row per
finding (file, check, severity,
key, message), sorted from errors to notes, so
it can be filtered or used to stop a script:
findings <- rbind(
check_prm(bio = "biology.prm", run = "run.prm", force = "force.prm"),
check_init("init.nc", "groups.csv")
)
if (any(findings$severity == "error")) {
print(findings[findings$severity == "error", ])
stop("fix the input files before calibrating")
}Values of the initial-conditions file reported by
check_init() can be fixed with
set_init_values(), which sets a variable per box (and
layer) from a table, in place or in a copy of the file:
# fill the cells left unset of the refractory detritus in boxes 1 and 2
set_init_values(
"init.nc",
"Refractory_detritus_N",
data.frame(box = 1:2, layer = 1, value = 30),
file = "init_fixed.nc"
)
check_init("init_fixed.nc", "groups.csv")Running the model
write_run_script() writes the Atlantis command line
(run.sh, from the template
inst/run_scripts/script.sh) for the input files of a run
directory, and creates its output folder. run_atlantis()
runs it with the run directory as working directory, either directly
(when atlantisMerged is installed in the same environment
as R, as on most HPC clusters) or in a Docker container. Set a timeout:
a full run can take hours.
write_run_script(
run_dir,
init = "init.nc",
run = "run.prm",
force = "force.prm",
physics = "physics.prm",
biology = "biology.prm",
groups = "groups.csv",
fisheries = "fisheries.csv"
)
res <- run_atlantis(run_dir, timeout = 86400)binary gives the path to atlantisMerged
when it is not on the PATH. With Docker, give the image: the run
directory is mounted as the working directory /model, other
folders (e.g. forcing data shared by all runs, rather than copied into
each) can be mounted read-only with mounts, and the
container runs as the current user so that the files it writes remain
owned by the R session.
res <- run_atlantis(
run_dir,
docker = "atlantis",
mounts = c("/data/inputs" = "/model/inputs"),
timeout = 86400
)Detecting crashed runs
An Atlantis fatal error ends in quit(), which exits with
status 0 after printing to stderr. A crash therefore usually shows as a
truncated output.nc rather than a non-zero exit status.
check_run() compares the last time step of the output with
the end of the run: a run counts as complete only if it reaches
tstop, within one output interval (toutinc).
Both are read from the run file as Atlantis reads them:
tstop 15000 day is 15000 days, but Atlantis ignores a unit
it does not know as written (e.g. days or Day)
and reads the value in seconds, as a bare number;
check_prm() reports such units.
check_run("outputFolder/output.nc", "run.prm")Like the other checks, it returns an atlantis_check
table: empty when the run completed, otherwise one error,
"missing" (no output), "unreadable" or
"incomplete", whose message gives the day the run stopped
at. run_atlantis() runs it on the output and run file named
in the script: its result holds the table as check, and
complete is TRUE only if the run exited with
status 0, within the time limit, and check is empty.
Step 3: design the objective function
The score
The score turns the model output into a single number that is small when the model behaves as desired. Morell et al. (2026) combine a fit to observed biomasses with a stability penalty on the trend of each group. When observations are scarce, a useful first target is persistence: every group should stay close to its initial state over the whole run rather than collapse or explode.
atlantio implements this persistence score. For every
group and age class, the tracers of interest (numbers, structural and
reserve weight) are aggregated over boxes and layers, compared with
their initial values on the log scale
(log(x(t) + tiny) - log(x(0) + tiny), as in
calibrar’s lnorm2), and only the excess beyond
a tolerance band (20% by default) is penalized, squared, which keeps the
objective continuous at the edge of the band. Only the last years of the
run are scored, so that the model is allowed a spin-up period.
The model output is first read into a tracer table.
atlantis_load_files() reads the output NetCDF into the
model object, and create_time_series_biomass() returns a
tidy table of the age-structured tracers. With
aggregate = TRUE, the series are reduced over boxes and
layers while they are read, one cohort at a time, so the per-box table
of a whole run (several GB for a long run) is never held in memory,
which matters when many runs are scored in parallel on the same
node:
out <- atlantis_load_files(mod, "outputFolder/output.nc")
ts <- create_time_series_biomass(out, group = groups, aggregate = TRUE)aggregate_time_series() does the same reduction on a
table already read per box and layer (numbers are summed,
StructN and ResN are weighted by numbers). The
biomass of every living group, including those without age structure
(plankton, benthos), is in the biomass index Atlantis writes next to the
output file, read with read_biomass_index():
biomass <- read_biomass_index("outputFolder/outputBiomIndx.txt", mod@group)score_table() then returns the penalty of every series
(group x age class x tracer, and group for the biomass), and
compute_score() their sum, the single number
calibrar minimizes:
score_table(ts, biomass = biomass)
compute_score(ts, biomass = biomass)The score is tuned with a few arguments:
-
tolerance: the half-width of the no-penalty band, one value or one per tracer, e.g. a looser band on numbers than on weights; -
window_yearsandsummary: the scoring window (counted back from the last output step) and the statistic each series is scored on over it. The default,"snapshot", compares yearly snapshots taken at the same phase of the seasonal cycle, which avoids mistaking seasonal oscillations for drift;"mean","median","min","max"or a function are also accepted; -
exclude: groups left out of the score, e.g. those known to be poorly initialized and not targeted by this round; -
weight: the weight of the penalty of each tracer, e.g. to make the biomass count more than the individual weights; -
target_factor: the factor applied to the initial value of a tracer to get its target, e.g. a target biomass above the initial one.
compute_score(
ts,
biomass = biomass,
tolerance = c(Nums = 0.5, StructN = 0.2, ResN = 0.2, Biomass = 0.3),
summary = c(Biomass = "mean"),
window_years = 5,
exclude = "Detritus_feeders"
)The objective function of Morell et al.
method = "lnorm2" scores instead the objective function
of Morell et al. (2026), as
implemented in their calibration code with calibrar’s
lnorm2, where the targets are built from the initial state.
There is no tolerance band: every scored value is penalized by its
squared log ratio to the target,
(log(x(t) + tiny) - log(b x(0) + tiny))^2, and these are
summed (not averaged) over the scored values of each series. The tracers
scored are those of Morell et al.: the weight-at-age
(Weight, the wet weight of the average individual in kg,
(StructN + ResN) * 5.7 * 20 / 1e6) and, when
biomass is given, the biomass of every living group:
score_table(ts, biomass = biomass, method = "lnorm2")For the unfished phase of their calibration, the target biomass of a
theoretical unfished system is the initial biomass times a factor
b = 1.3 (values between 1.2 and 1.5 are suggested depending
on the system), set with target_factor; the weight-at-age
keeps its initial value as target:
compute_score(
ts,
biomass = biomass,
method = "lnorm2",
target_factor = c(Biomass = 1.3)
)With this method, a named weight also selects the
tracers scored, among Nums, StructN,
ResN, Weight and Biomass, e.g. to
give the biomass twice the weight of the weight-at-age:
compute_score(
ts,
biomass = biomass,
method = "lnorm2",
weight = c(Weight = 1, Biomass = 2)
)Two terms of Morell et al.’s objective are not covered: the catches,
which are not read by atlantio, and the stability penalty
on the year-to-year change of the biomass, which is not part of their
calibration code.
window_values(), used internally, shows which values of
a series are scored for a given window and statistic:
walleye <- ts[ts$group == "Walleye" & ts$age == 1, ]
window_values(walleye$time, walleye$Nums, "snapshot", years = 5)Whatever the score, it must be robust to the failure cases: a crashed
run, a truncated output or a scoring error must return a large penalty
(e.g. 1e8) rather than abort the whole generation of the
optimizer.
The function
The objective function chains one calibration iteration:
-
apply the parameters:
apply_parameters()maps the values from the calibration scale to the model scale and sets them in the parameter files loaded in the model object; -
create a unique run directory and write the inputs
there with
write_parameter_folder(): it copies the base inputs and writes the biology file with only the calibrated values changed, keeping its comments and units; then add the run script; -
run the model and check, with
check_run(), that it completed; - read the output and compute the score;
- save the time series and the parameter values with their score, and remove the bulky run files.
run_model <- function(par, atlantis, calib_table, base_dir, results_dir,
groups) {
# the names <name>.<position> make every parameters.rds self-describing,
# and are what read_calibration_runs() expects
names(par) <- paste(calib_table$name, calib_table$position, sep = ".")
# 1. parameter values, on the model scale in the biology file
atlantis <- apply_parameters(atlantis, calib_table, par)
par_model <- vapply(seq_len(nrow(calib_table)), function(i) {
atlantis@biology[[calib_table$name[i]]][calib_table$position[i]]
}, numeric(1))
names(par_model) <- names(par)
# 2. run directory and input files
run_dir <- tempfile("run_", tmpdir = results_dir)
dir.create(run_dir)
write_parameter_folder(atlantis, run_dir, from = base_dir, overwrite = TRUE)
write_run_script(run_dir, init = "init.nc", run = "run.prm",
force = "force.prm", physics = "physics.prm", biology = "biology.prm",
groups = "groups.csv", fisheries = "fisheries.csv")
# 3. model run; a zero exit status does not mean the run completed
res <- run_atlantis(run_dir, timeout = 86400)
out_file <- file.path(run_dir, "outputFolder", "output.nc")
if (!res$complete) {
reason <- if (nrow(res$check)) res$check$message[1] else
if (res$timeout) "time limit reached" else
sprintf("exit status %s", res$status)
return(failed_run(run_dir, par, par_model, res, reason))
}
# 4. output and score; an error makes the run a failed one
out <- NULL
score <- tryCatch({
out <- atlantis_load_files(atlantis, out_file)
ts <- create_time_series_biomass(out, group = groups, aggregate = TRUE)
biomass <- read_biomass_index(
file.path(run_dir, "outputFolder", "outputBiomIndx.txt"),
atlantis@group
)
saveRDS(list(ts = ts, biomass = biomass),
file.path(run_dir, "time_series.rds"))
compute_score(ts, biomass = biomass)
}, error = function(e) e)
# the output is read through an open file handle: close it
if (!is.null(out)) try(ncdf4::nc_close(out@main_output), silent = TRUE)
if (inherits(score, "error")) {
return(failed_run(run_dir, par, par_model, res, conditionMessage(score)))
}
# 5. results
saveRDS(
list(par = par, par_model = par_model, score = score, failed = FALSE),
file.path(run_dir, "parameters.rds")
)
unlink(setdiff(
list.files(run_dir, full.names = TRUE),
file.path(run_dir, c("time_series.rds", "parameters.rds"))
), recursive = TRUE)
score
}Keeping the results directory outside tempdir() matters:
it must survive the R session, and it is what makes the calibration
inspectable afterwards. For failed runs, failed_run()
should record the same parameters.rds with the penalty as
score, failed = TRUE and the failure reason,
keep the tail of the model output (where Atlantis prints its
quit() message), and return the penalty:
failed_run <- function(run_dir, par, par_model, res, reason) {
saveRDS(
list(par = par, par_model = par_model, score = 1e8, failed = TRUE,
reason = reason),
file.path(run_dir, "parameters.rds")
)
writeLines(
c(reason, utils::tail(strsplit(res$stderr, "\n")[[1]], 100)),
file.path(run_dir, "failure_log.txt")
)
1e8
}Naming the run directories after their generation, e.g. with the
prefix gen003_, lets summarise_calibration()
follow the values from one generation to the next (see Step 5).
calibrar does not pass the generation to the objective
function, but evaluates every generation in full before the next one, so
it can be derived from the number of run directories already present and
popsize.
Starting values
The natural starting point is the current set of values in the
biology file, mapped back to the calibration scale with
inverse_transform_parameter_value() and clamped into the
bounds. Evaluate the objective function once at this point before
launching the calibration: this checks the whole chain and gives the
reference score to beat.
start <- vapply(seq_len(nrow(calib_table)), function(i) {
inverse_transform_parameter_value(
mod@biology[[calib_table$name[i]]][calib_table$position[i]],
calib_table$transf[i]
)
}, numeric(1))
start <- pmin(pmax(start, calib_table$min), calib_table$max)
score0 <- run_model(start, mod, calib_table, base_dir, results_dir, groups)Step 4: run the optimization in parallel
A generation of calibrar evaluates popsize
parameter sets, each one a full model run, so parallel evaluation is
essential. calibrar uses foreach’s
%dopar%, which needs a registered backend; the simplest is
a cluster from the base parallel package registered with
doParallel. The workers must share the master’s filesystem
and be able to run the model.
library(parallel)
library(doParallel)
cl <- makeCluster(n_workers)
registerDoParallel(cl)
# %dopar% ships the objective function to the workers, but not the global
# objects it relies on: export them and load the packages explicitly
clusterExport(cl, "failed_run")
clusterEvalQ(cl, library(atlantio))Sensible controls for a first round: a population of one run per
worker (calibrar raises it to its internal minimum if too
small), a handful of generations, and a restart file saved every
generation. The restart file must be a relative path.
control <- list(
maxit = 5, # generations
popsize = n_workers, # parameter sets per generation
ncores = n_workers,
REPORT = 1, # generations between restart-file saves
restart.file = "calib_restart",
trace = 3
)
res_calib <- calibrar::calibrate(
par = start,
fn = run_model,
lower = calib_table$min,
upper = calib_table$max,
method = "AHR-ES",
control = control,
parallel = TRUE,
# extra arguments are forwarded to run_model()
atlantis = mod,
calib_table = calib_table,
base_dir = base_dir,
results_dir = results_dir,
groups = groups
)
stopCluster(cl)
res_calib$par
res_calib$valueRelaunching the same script after an interruption resumes from the last restart file. On an HPC cluster, wrap the script in a job asking for one node with many CPUs (the cluster above is single-node), restore the modules needed by Atlantis and R, and pass the number of workers and the results directory through environment variables so that the same script runs unchanged on a laptop with Docker and on the cluster with the bare binary.
Step 5: inspect the results and iterate
Every evaluation leaves its time series, parameter values and score in one folder of the results directory, which allows three kinds of inspection.
The tuned parameters
read_calibration_runs() gathers the
parameters.rds of every run into one table (one row per run
and parameter value, with the score, whether the run failed and why, and
the generation read from the genNNN_ prefix of the folder
name). summarise_calibration() summarises it per parameter
value of the calibration table:
runs <- read_calibration_runs(results_dir)
res <- summarise_calibration(runs, calib_table, n_best = 5, n_top = 20)
res$parametersFor each parameter value, res$parameters gives the
starting value, the value of the best run, the range over the
n_best best runs and the median over the n_top
best runs. Values are given as a factor of the starting value when the
start lies within the bounds, and as values otherwise (e.g. a rate
started at a placeholder far below its search range); set
relative to choose. Two more columns flag what to revise
before the next round:
-
at_bound, the number of then_topbest runs at a bound: a parameter pushed against its bound wants a wider range; -
failed_shift, the mean value of the failed runs minus that of the completed runs, on the calibration scale: a large shift points at the region (and the bound) where the model crashes. Tightening these bounds in the YAML file is the “nudging” that keeps the optimizer in the region where the model makes sense.
res$generations follows the median of the best runs of
each generation, to see whether the values have settled, and
res$scores gives the number of runs, of failed runs, and
the best and median scores per generation. Runs outside the
optimization, such as the evaluation at the starting values or a final
re-evaluation of the best set, can be filtered out of runs
first.
The best runs
The time series of the best runs show which groups drive the score
and whether the tolerance band or the scoring window need adjusting.
score_table() on the saved time series breaks the score
down per series:
The next parameter folder
The next round starts from the calibrated values, possibly with a new
set of parameters, which is how Morell et al. (2026) describe
calibration as a semi-automated process rather than a single
optimization. apply_parameters() sets the values of a run
in the model object, here on the model scale as saved in
parameters.rds, and write_parameter_folder()
writes the new parameter folder from the previous one. Only the
calibrated values change in the biology file; the files not loaded in
the object (physics, forcing) are copied from from:
best <- readRDS(file.path(best_run_dir, "parameters.rds"))
mod_next <- apply_parameters(mod, calib_table, best$par_model,
scale = "model")
changes <- write_parameter_folder(mod_next, "params_calibration_v2",
from = "params_calibration_v1")
changescompare_prm() compares two parameter files by parameter
name, so moved lines, comments and layout do not show up, only the
values that differ and the parameters present in one file only:
compare_prm(
"params_calibration_v1/biology.prm",
"params_calibration_v2/biology.prm"
)