| Title: | Fits the Multispecies Assessment Model (CEATTLE) Using TMB |
|---|---|
| Description: | Implements the CEATTLE model using Template Model Builder ('TMB'; Kristensen et al. 2015), which can be installed following <https://github.com/kaskr/adcomp/wiki/Download>. Structured similar to the original manuscript in terms of modularization. Separate functions estimate retrospective temperature- and size-specific predator rations, prey preference, and weight-at-age. These are then used as inputs to the CEATTLE model to evaluate how predation mortality, recruitment, and survival of three target species change under historical climate conditions and harvest rates. |
| Authors: | Grant Adams [aut, cre] (ORCID: <https://orcid.org/0000-0003-0297-8347>) |
| Maintainer: | Grant Adams <[email protected]> |
| License: | GPL (>= 2) |
| Version: | 5.66.1 |
| Built: | 2026-10-26 23:36:43 UTC |
| Source: | https://github.com/grantdadams/Rceattle |
Returns the model's derived population quantities in long form so that
custom plots and post-processing don't have to walk the deeply nested
quantities list or inherit the dimnames decisions in
rename_output(). Two shapes are flattened into one tidy frame:
species-by-year quantities (e.g. biomass, ssb, R, F_spp) and
species-by-sex-by-age-by-year quantities (e.g. N_at_age,
biomass_at_age, M_at_age). For the species-level shapes, sex
and age are returned as NA. Cells of the 4D arrays that are
padded out to max(nsex) / max(nages) for species with fewer
sexes or ages are dropped.
## S3 method for class 'Rceattle' as.data.frame( x, row.names = NULL, optional = FALSE, which = c("biomass", "ssb", "R", "biomass_depletion", "ssb_depletion", "F_spp"), ci_level = 0.95, ... )## S3 method for class 'Rceattle' as.data.frame( x, row.names = NULL, optional = FALSE, which = c("biomass", "ssb", "R", "biomass_depletion", "ssb_depletion", "F_spp"), ci_level = 0.95, ... )
x |
An object of class |
row.names, optional
|
Ignored; present for the |
which |
Character vector of quantity names to extract, or
|
ci_level |
Confidence level for |
... |
Currently unused. |
Standard errors (se) and confidence intervals (lwr, upr) are
populated from the TMB sdreport for any quantity that was
ADREPORT'd (biomass, ssb, R, exploitable_biomass,
biomass_depletion, ssb_depletion); other quantities and fits produced
with getsd = FALSE get NA for se / lwr / upr. Set ci_level to
widen or narrow the band.
A strictly positive series takes its interval on the log scale, so it is
right-skewed and cannot reach zero. This is the same construction
plot_timeseries() draws, so the table and the figure agree.
A data.frame with columns year, species, sex, age,
quantity, value, se, lwr, upr. species is the character
species name from data_list$spnames. Rows are sorted in the order
which was given.
A data list containing inputs for a single-species CEATTLE model fit to
Aleutian Islands Atka mackerel data through 2022. See
BS2017SS for format details.
Atka2022Atka2022
A list with the same structure as BS2017SS.
A data list containing inputs for the three-species (walleye pollock,
Pacific cod, arrowtooth flounder) multispecies CEATTLE model for the
Eastern Bering Sea. See BS2017SS for format details.
BS2017MSBS2017MS
A list with the same structure as BS2017SS.
A data list of inputs for the single-species Eastern Bering Sea CEATTLE model (walleye pollock, Pacific cod, and arrowtooth flounder), covering 1979-2017.
BS2017SSBS2017SS
Control
Number of species included in CEATTLE
Start year of the hindcast
End year of the hindcast
End year of the forecast
Number of sexes to model in the population (1 = sexes combined, 2 = females and males modeled separately)
Spawning month of the population to adjust the numbers spawning
Percent of recruitment that is female (ignored if nsex = 1)
Number of ages of each species included in the hindcast
Minimum age for each population (i.e. does recruitment correspond to age 0, 1, 2?)
Number of lengths of each species included in the hindcast
Weight-at-age (weight) index to use for calculation of each species population derived quantities (SSB, Consumption/Ration, Suitability, etc)
Weight-at-age index used to compute each species' female spawning-stock biomass (SSB)
Age transition matrix (e.g. growth trajectory) index to use for derived quantities of the population to convert age to length (also used in length-based predation estimation)
Standard deviation of the log-scale recruitment deviations (fixed, or an initial value if estimated)
Other food in the ecosystem for each species, in metric tons: it is summed into the available-food denominator beside numbers-at-age (thousands) times weight-at-age (kg)
Estimate or fix numbers-at-age. Accepts integer codes or the equivalent readable strings: 0 / "Estimated" = estimate dynamics; 1 / "Fixed" = use input numbers-at-age in NByageFixed; 2 / "FixedScaled" = multiply input numbers-at-age (NByageFixed) by a single scaling coefficient, estimated under predation (msmMode > 0) and fixed at 1 otherwise.
Estimate residual (multi-species mode) or total natural mortality (single-species mode). 0 = use fixed natural mortality from M1_base, 1 = estimate sex- and age-invariant M1, 2 = sex-specific (two-sex model), age-invariant M1, 3 = estimate sex- and age-specific M1.
Survey and fishery data specifications
Survey index in weight (mt) or numbers (thousands of fish) data. The Observation column is on the NATURAL scale in the units fleet_control$Observation_units names, never a log: the likelihood takes the log itself, and a fitted observation must be positive. A negative Year predicts the row without fitting it.
Optional named list of survey-index variance-covariance matrices, keyed by Fleet_name (or Fleet_code), used only by fleets whose fleet_control Index_distribution == "MVN". Each matrix must be square and symmetric with dimension equal to the number of fitted survey observations for that fleet (Year in styr:endyr, Observation > 0), ordered as in index_data. Inverted once internally to the precision matrix used in 0.5 * r' Sigma^-1 r. Leave unset for the default lognormal likelihood.
Total catch in weight (mt) or numbers (thousands of fish) data
Survey/fishery age or length composition data. Note if sex is 3, put female composition data then male composition data (similar to SS).
Empirical/fixed selectivity for surveys and fisheries (leave empty if not used)
Age transition matrix (e.g. growth trajectory) used to convert age to length for length comp data. Can have multiple matrices for a species specified by Age_transition_index.
Ageing error matrices, one row per true age. One per species by default; give several and select them per fleet with the 'Ageing_error_index' column of both this table and fleet_control.
Weight-at-age (weight) to use for calculation of derived quantities (SSB, Consumption/Ration, Suitability, Total Catch, Survey Biomass, etc). Can have multiple weight-at-age data-sets for each species, but must be full for all years of the hindcast.
Maturity-at-age for each species
Percent female at age for each species
Residual natural mortality for each species
Parameters for weight-at-length power function for each species. Used when estimating time-variant length-based gamma suitability (suitMode = 2) or time-variant length-based lognormal suitability (suitMode = 5)
Which bioenergetics equation to use for each species for ft to scale max consumption: 1 = Exponential (Stewart et al 1983), 2 = Temperature-dependence for warm-water species (Kitchell et al 1977; sensu Holsman et al 2015), 3 = temperature dependence for cool and cold-water species (Thornton and Lessem 1979)
Which environmental index in env_data to use to drive bioenergetics
This scales the maximum consumption used for ration for each species; Pvalue is in CmaxfTPvalue*ration_data
Number of foraging days per year for each species
Intercept of allometric mass function for calculating maximum consumption: CA * Weight ^ CB
Slope of allometric mass function for calculating maximum consumption: CA * Weight ^ CB
Parameter for temperature scaling function of maximum consumption specified by Ceq
Parameter for temperature scaling function of maximum consumption specified by Ceq
Parameter for temperature scaling function of maximum consumption specified by Ceq
Parameter for temperature scaling function of maximum consumption specified by Ceq
Parameter for temperature scaling function of maximum consumption specified by Ceq
Parameter for temperature scaling function of maximum consumption specified by Ceq
Environmental indices such as bottom temperature data to incorporate into ration equation specified by Ceq and Cindex. Also used to drive catchability if Catchability = 5. Will use the mean for missing years. Temperature should be in Celsius.
Annual relative foraging rate by age or input consumption at age. Multiplied by pvalue and fday to scale maximum consumption to the number of days in a year that foraging occurs.
Stomach proportion by weight for each predator, prey, predator age, prey age combination. Can also be year specific by including the column, "Year"
fleet_control: controls for survey and fisheries data
Name of survey or fishery
Index of survey/fishery ACROSS species
0 or 'Off' = Do not estimate; 1 = 'Fishery'; 2 = 'Survey'
Species number
Index used to give fleets the same selectivity (otherwise, same as Fleet_code). Fleets sharing a value share one selectivity parameter block, with its penalties and priors accumulated once on the group's first non-Off fleet. Sharing the parameters is not enough on its own: the columns that shape the curve are read per fleet and must agree across the group, or the fleets end up with different selectivities. data_check() reports any that differ. To mirror a fleet, copy its fleet_control row and change only the identity and catchability columns. See vignette("model-options-and-functionality").
Selectivity form: 0 = "Fixed"; 1 = "Logistic"; 2 = "NonParametric" (Ianelli et al. 2018); 3 = "DoubleLogistic"; 4 = "DescendingLogistic"; 5 = "Hake" non-parametric (Taylor et al. 2014); 6 = "2DAR1"; 7 = "3DAR1" (Cheng et al. 2024); 8 = "DoubleNormal"; 9 = "NonParametricPM" (non-parametric random walk with penalized increments, AMAK "pm"; not integrable under random_sel); 11 = "LogisticPM" (logistic with a free age-1 selectivity, AMAK "pm"); 13 = "NonParametricIntegrable" (the Ianelli base curve whose deviations have a proper density, so random_sel integrates them; Time_varying_sel picks the structure: "Off", "IID" or "RandomWalk"); 15 = "DoubleNormalSS3" (Stock Synthesis size pattern 24, six parameters on SS3's scales, varied through selectivity linkages). Whether a form is age- or length-based is set by Selectivity_dimension.
"Age" or "Length".
Number of bins (ages or length bins) to estimate for non-parametric selectivity.
Whether a time-varying selectivity should be estimated. 0 = "Off"; 1 = "IID" penalized deviates given Time_varying_sel_sd, or random effects with that sd estimated under random_sel; 2 = "AR1" REMOVED in 5.16.0, it was scored as "IID", so data_check() errors on it; use "IID" for the same fit, or linkage_spec(~ ar1(1 | Year)) for a real one; 3 = "Block" time blocks with no penalty; 4 = "RandomWalk" following Dorn; 5 = "RandomWalkAscending" on the ascending limb of double logistic only.
The fixed or initial sd to use for time varying selectivity; always required by the 2DAR1 and 3DAR1 forms.
First year the fleet's time-varying selectivity deviations are estimated and penalized. Deviations before this year are fixed at 0: they have no data and no penalty (the selectivity penalties are anchored at this year), so estimating them would leave unidentified flat directions. Defaults to the earliest year of data across all fleets sharing the fleet's Selectivity_index (fleets sharing an index share one selectivity curve), bounded below by styr. Only used for time-varying selectivity; set explicitly to override.
Age/length bin at which selectivity is non-zero
Selectivity penalties expressed as standard deviations (an intuitive alternative to the raw penalty weights in Sel_curve_pen1/2/3). Each penalty is a Gaussian SSQ, so the weight is 1 / (2 * sd^2): Sel_shape_sd is the shape/smoothness penalty (Sel_curve_pen1), Sel_curvature_sd the 2nd-difference curvature penalty (Sel_curve_pen2), Sel_devmag_sd the deviation-magnitude penalty (Sel_curve_pen3). Supplying an SD sets the corresponding Sel_curve_pen column; a legacy Sel_curve_pen value is never overwritten. Sel_shape_sd applies to NonParametric (2/9/13) and LogisticPM (11), Sel_devmag_sd to "NonParametricPM" (9) and "LogisticPM" (11) only, the slot being unread by "NonParametric" (2) and "NonParametricIntegrable" (13); Sel_curvature_sd is NonParametric-only (2/9/13; LogisticPM does not use Sel_curve_pen2). The 2DAR1/3DAR1 forms reuse Sel_curve_pen for logit-scale correlations and keep those columns.
Direction of the shape penalty when Sel_shape_sd is used: "Decreasing" (default, penalize decreasing selectivity) or "Increasing" (sets the sign of Sel_curve_pen1). Only "NonParametricPM" (9) with Sel_shape_mode = "Directional" branches on the sign; every other form, that one under "Smooth" included, applies Sel_curve_pen1 as written, so "Increasing" is refused there rather than negating it.
Raw shape/smoothness penalty weight for non-parametric (type 2/9/13) and LogisticPM (11) selectivity. The intuitive alternative is Sel_shape_sd, which sets this to 1 / (2 * sd^2). The 2DAR1/3DAR1 forms reuse this column as a logit-scale correlation.
Raw 2nd-difference curvature penalty weight for non-parametric selectivity (the intuitive alternative is Sel_curvature_sd). Reused as a logit-scale correlation by the 2DAR1/3DAR1 forms.
Raw deviation-magnitude penalty weight, read only by "NonParametricPM" (9) and "LogisticPM" (11) (the intuitive alternative is Sel_devmag_sd).
First bin (age or length, on the fleet's Selectivity_dimension) for the non-parametric shape penalty. NA defaults to Bin_first_selected.
Last (left) bin of the shape-penalty pairs. NA defaults to nbins - 2.
Shape-penalty mode: "Directional" (default) or "Smooth" (two-sided second-difference penalty, RTMB).
Weight on the AMAK average-selectivity base-level penalty (type 9 only): 0 = off (default), 10 matches AMAK.
NonParametricPM selectivity bin cap. NA (default) applies no cap.
Where selectivity is normalized to 1. "Max"
normalizes by the largest value, "Off" (or blank, the default) not at
all, and "All" on a LogisticPM fleet covers its whole penalty range.
A number is an absolute age for an age-based fleet (6 means age 6, not the
6th bin) or a 1-based length-bin ordinal for a length-based one, and must
lie in the range the fleet is selected over; below it the curve is zeroed,
so a value there is read as "Max". In a two-sex model this says only
where the reference is taken, whether it is pooled across the sexes is
Sel_norm_scope. See the sex-structure section of
vignette("model-options-and-functionality").
Optional upper age/length bin. "Off" (or blank, the default) normalizes at a single bin; a number normalizes by mean selectivity between Sel_norm_bin and this bin, on the same scale and within the same range.
Whether selectivity normalization pools its reference
across sexes, orthogonal to Sel_norm_bin (which says where the
reference is taken). "WithinSex" divides each sex by its own
reference, so both reach 1 and only the shape differs by sex;
"AcrossSexes" (default) pools one reference over both sexes, so the
less-selected sex stays below 1 and relative sex-specific selectivity is
retained. No effect on a one-sex species or where Sel_norm_bin is
NA.
Units of the observation: 1 = weight (mt), 2 = numbers caught (thousands of fish). Drives both catch and index prediction.
Weight-at-age (weight) index to use for calculation of derived quantities
Age transition matrix (e.g. growth trajectory) index to use for derived quantities to convert age to length
Ageing error matrix index, matching Ageing_error_index in age_error. Fleets sharing a value read the same matrix. Omit the column, or leave it NA, to use the fleet's own species, which is what a model with one matrix per species has always done.
Index used to give fleets the same catchability (otherwise, same as Fleet_code). Fleets sharing a value share one q parameter, so the group holds only one answer to whether q is estimated: the group's first non-Off fleet decides for all of them, regardless of fleet type. Give a fleet its own value when it should be estimated independently. "Analytical" and "AnalyticalArith" are the exception, they solve q from each fleet's own index observations, so a group containing one does not share a catchability. data_check() reports that case, a Fixed lead that leaves fleets on different inits, and a Catchability or Time_varying_q that differs within a group. See vignette("model-options-and-functionality").
Estimate catchability? 0 or "Fixed" = fixed at prior; 1 or "Estimated" = estimate a single parameter; 2 or "Estimated-with-prior" = estimate a single parameter with a prior; 3 or "Analytical" = geometric-mean analytical q (Walters and Ludwig 1994); 4 = power equation (not yet implemented); 5 or "Environmental" = linear equation log(q_y) = q_mu + beta * index_y; 6 or "AR1" = removed, and data_check() errors on it, the deviates were never estimated, so q came back constant; express the Rogers et al. (2024) form as a q linkage with ar1(1 | Year) and observe, passed to fit_mod(qFun = ); 7 or "AnalyticalArith" = arithmetic-mean analytical q = mean(obs)/mean(pred), the AMAK/ebswp form used with the MVN survey likelihood.
Starting value (or fixed value) for catchability. When Catchability = "Estimated-with-prior" this also centers the q prior.
Log-scale standard deviation of the q prior: dnorm(log_q, log(Catchability_init) - bias_adjust_proc * sd^2/2, sd). Used only when Catchability = "Estimated-with-prior".
Whether a time-varying q should be estimated. 0 = "Off"; 1 = "IID" penalized deviate or random effect; 2 = "AR1" REMOVED in 5.16.0, it was scored as "IID", so data_check() errors on it; use "IID" for the same fit, or linkage_spec(~ ar1(1 | Year)) for a real one; 3 = "Block" time blocks with no penalty; 4 = "RandomWalk" from the mean following Dorn 2018. Under Catchability = "Environmental" this column instead holds the env_data column index, not a mode.
The sd to use for the random walk of time varying q if set to 1
Estimate survey/index observation SD. Accepts integer codes or readable strings: 0 / "Fixed" = use the fixed SD from the data CV; 1 / "Estimated" = estimate; 2 / "Analytical" = analytically estimate following Walters and Ludwig 1994.
Starting/fixed value for the index observation SD, used when Estimate_index_sd = "Estimated".
Estimate fishery/catch observation SD. Accepts integer codes or readable strings: 0 / "Fixed" = use the fixed SD from the data CV; 1 / "Estimated" = estimate; 2 / "Analytical" = analytically estimate following Walters and Ludwig 1994.
Starting/fixed value for the catch observation SD, used when Estimate_catch_sd = "Estimated".
Survey/index biomass observation likelihood family. 0 or "Lognormal" (default) = independent lognormal on the log observation. 1 or "MVN" and 2 or "MVNORM" = multivariate normal on the natural-scale residual (obs - q*pred), with a user-supplied covariance in index_cov (e.g. a VAST-derived Sigma); "MVN" reports the bare quadratic form matching AMAK/ebswp and ADMB, "MVNORM" the properly normalized density, and the two give an identical fit. Pair either with Catchability = "AnalyticalArith". 3 or "Normal" = independent normal on the same residual, with an ABSOLUTE sd from Log_sd, not a log-scale CV; reproduces AMAK avo_like/cpue_like term for term. 4 or "TruncatedNormal" = that normal left-truncated at zero. Prefer it to "Normal" unless an exact ADMB comparison is needed: an index cannot be negative, so it is the only natural-scale family whose likelihood and simulator are the same distribution. See vignette("model-options-and-functionality").
Age/length composition data distribution. Accepts integer codes or readable strings: -1 or "MultinomialAFSC" (default) = AFSC multinomial; 0 or "Multinomial" = full multinomial; 1 or "DirichletMultinomial".
Composition weight. Its scale follows Comp_distribution: under a multinomial it is the natural-scale multiplier on the input sample size, while under a Dirichlet-multinomial the model uses exp(Comp_weights), so the column holds the log of the starting weight, a value of 1 is a starting weight of ; use 0 for a weight of 1. It is read when a model is built from scratch, so a refit keeps whatever weight it is given. A fit reports the weight its residuals imply, a harmonic mean of the ratio of effective to input sample size (McAllister & Ianelli 1997), in Comp_weights_mcallister; reweight_comps tunes towards it.
Conditional age-at-length composition distribution. Accepts integer codes or readable strings: -1 or "MultinomialAFSC" = AFSC multinomial; 0 or "Multinomial" (default) = full multinomial; 1 or "DirichletMultinomial".
Conditional age-at-length (CAAL) composition weight. Its scale follows CAAL_distribution exactly as Comp_weights follows Comp_distribution: a natural-scale sample-size multiplier under a multinomial, the log of the starting weight under a Dirichlet-multinomial.
Young-tail composition accumulation bin (AFSC ac_yng): a 1-based ordinal on the fleet's composition dimension; age/length bins below it are folded into it before the likelihood. NA (default) or 1 = no young accumulation.
Old-tail composition accumulation bin (AFSC ac_old): a 1-based ordinal on the fleet's composition dimension; age/length bins above it are folded into it before the likelihood. NA (default), 0, or a value at/above the number of bins = no old accumulation.
Observation month for the fleet (0 = not specified).
The proportion of future fishing mortality assigned to this fleet.
Function to build parameter bounds based on Holsman et al 2015 and Kinzey and Punt 2010
build_bounds(param_list = NULL, data_list)build_bounds(param_list = NULL, data_list)
param_list |
Parameter list object built from |
data_list |
a Rceattle data object |
List of upper and lower bounds
Holds environmental linkages on survey/index catchability q. The effect of
an env_data covariate is written as a formula and can hold priors, bounds,
and an estimation phase like any other linkage.
build_catchability(linkages = NULL)build_catchability(linkages = NULL)
linkages |
Optional named list of |
Catchability is the one process that accepts
link = "exponential", Stock Synthesis's environmental link type 1:
q^exp(beta * x), which MULTIPLIES log q where "log" shifts it. It
needs an estimated base q and a lognormal or t index likelihood, and
cannot share a fleet with a random-effect q linkage; each of those is
refused with the reason. See
vignette("environmental-linkages-and-priors").
A list of catchability settings for fit_mod().
# One temperature effect on q per fleet. `by = ~ fleet` is the default, and a # fleet without an estimated survey catchability is not linkable, so at fit time # restrict the linkage to the estimated-q fleets (here fleet 7 of BS2017SS). build_catchability(linkages = list( q = linkage_spec(~ temp, fleet = 7))) # Restrict it to fleets 1 and 3, with a prior on the slope build_catchability(linkages = list( q = linkage_spec(~ temp, fleet = c(1, 3), priors = list(temp = prior_normal(0, 1)))))# One temperature effect on q per fleet. `by = ~ fleet` is the default, and a # fleet without an estimated survey catchability is not linkable, so at fit time # restrict the linkage to the estimated-q fleets (here fleet 7 of BS2017SS). build_catchability(linkages = list( q = linkage_spec(~ temp, fleet = 7))) # Restrict it to fleets 1 and 3, with a prior on the slope build_catchability(linkages = list( q = linkage_spec(~ temp, fleet = c(1, 3), priors = list(temp = prior_normal(0, 1)))))
Holds priors on the Dirichlet-multinomial composition-weighting overdispersion. The DM weight (the "theta" that scales the effective sample size) is otherwise an unpenalized free parameter; a linkage lets you put a prior on it through the same grammar as every other parameter. The three parameters target the three DM likelihoods:
theta_compage / length composition weight (comp_weights), per
fleet.
theta_caalconditional-age-at-length weight (caal_weights), per
fleet.
theta_dietdiet composition weight (diet_comp_weights), per
predator.
This is a prior-only process: the DM weight is a scalar, not a
year-varying quantity, so only intercept formulas (~ 1) with a priors
entry are meaningful. The prior is placed on the natural-scale DM weight
theta = exp(weight), so a gamma() prior reads naturally. A linkage on a
fleet whose Comp_distribution (or CAAL_distribution) is not
"DirichletMultinomial" errors, since the weight has no effect there.
build_composition(linkages = NULL)build_composition(linkages = NULL)
linkages |
Optional named list of |
A list of composition-weighting settings for fit_mod().
# A weak gamma prior on the DM overdispersion of every fleet's age comps build_composition(linkages = list( theta_comp = linkage_spec(~ 1, by = ~ fleet, priors = list(`(Intercept)` = gamma(2, 0.5)))))# A weak gamma prior on the DM overdispersion of every fleet's age comps build_composition(linkages = list( theta_comp = linkage_spec(~ 1, by = ~ fleet, priors = list(`(Intercept)` = gamma(2, 0.5)))))
Assemble (or edit) an Rceattle data list in R code rather than from an xlsx
workbook. Supply only the data
blocks a model uses, dimensions, biology (weight, maturity,
sex_ratio, M1_base), a fleet_control, and the observation tables
(catch_data, index_data, comp_data, ...), and the optional blocks a
single-species model does not need (caal_data, emp_sel, diet_data, ...)
are default-filled by clean_data(). The result is the same bare list
read_data() returns and round-trips through write_data() unchanged.
build_data(base = NULL, file = NULL, ..., .check = TRUE)build_data(base = NULL, file = NULL, ..., .check = TRUE)
base |
Optional existing Rceattle data list to start from and override. |
file |
Optional path to an Rceattle xlsx workbook; read via |
... |
Named top-level data-list elements to set or override (e.g.
|
.check |
Logical; run the presence pre-check (default |
Three entry points, which may be combined:
from blocks: pass the elements as named arguments:
build_data(nspp = 1, styr = 1977, ..., fleet_control = fc, catch_data = catch).
from a file: build_data(file = "model.xlsx", projyr = 2060)
reads the workbook via read_data(), then applies the overrides.
from an existing object: build_data(base = BS2017SS, projyr = 2060)
starts from a data list (e.g. a bundled dataset or a combine_data()
result) and overrides the named blocks. This is the common
copy-and-edit / combine-and-restamp workflow.
Element names are checked against the recognized schema: an override whose
name is a near-miss of a known element (e.g. maturty) errors with a
suggestion, so a typo is caught here rather than surfacing much later in a
fit. Legacy top-level names (fsh_biom, srv_biom, wt, pmature, Pyrs)
are mapped to their canonical equivalents.
Full validation runs at fit time, inside fit_mod(). build_data() runs only
a light presence pre-check (.check = TRUE) so a missing required block is
reported at construction with a clear message. The pre-check reads an attached
model_config(), so a configuration held on the object is accounted for.
Requirements that depend on fit-time settings passed directly to fit_mod()
and stored nowhere on the data list are not knowable here and are left to
that fit-time validation; see data_requirements() to preview them.
An Rceattle data list (a bare list, as from read_data()).
read_data(), clean_data(), data_requirements(),
combine_data(), fit_mod().
# Copy-and-edit a bundled dataset. dat <- build_data(base = BS2017SS, projyr = 2060) # Preview what a configuration needs before building it. data_requirements(msmMode = 0)# Copy-and-edit a bundled dataset. dat <- build_data(base = BS2017SS, projyr = 2060) # Preview what a configuration needs before building it. data_requirements(msmMode = 0)
Specify the growth model for Rceattle
build_growth( fun = "empirical", growth_age_L1 = NA, sd_plus_group = NA, linkages = NULL, sd_form = NA, plus_group_length = NA, plus_group_decay = NA, pop_lengths = NULL )build_growth( fun = "empirical", growth_age_L1 = NA, sd_plus_group = NA, linkages = NULL, sd_form = NA, plus_group_length = NA, plus_group_decay = NA, pop_lengths = NULL )
fun |
Growth function: a string (GROWTH_FUNS: |
growth_age_L1 |
Von Bertalanffy / Richards anchor age, where mean length
equals |
sd_plus_group |
How the oldest age class's SD-at-age is treated, and
only for estimated growth. |
linkages |
Optional named list of |
sd_form |
What the two variability endpoints ( |
plus_group_length |
How the plus group's mean length is set: |
plus_group_decay |
Annual decay rate for
|
pop_lengths |
Population length bins (lower edges, cm) on which the age-length key, weight-at-length and maturity-at-length are computed before being summed into the data length bins: SS3's population length bins. Every data-bin lower edge must also be a population-bin edge. A vector applies to every species, a list gives one per species, and the fallback is the data bins. |
Every switch above takes a scalar, recycled across species, or a
length-nspp vector for per-species values. Each defaults to NA, which
inherits the matching field from data_list when it is set – so a refit, or
a model built by the SS3 converter, keeps the original choice – and
otherwise uses the fallback named with it.
Plus-group mean length. Fish older than the oldest age are pooled, so the plus group's mean length lies between the growth curve at the oldest age, L_A, and L-infinity:
"M1": mean of L_A + (a/n)(Linf - L_A) over a = 0..n (n = nages),
weighted by survival at the oldest age's base M1.
"none": L_A (SS3 Linf_decay = -998).
"SS3.24": as "M1" with weights exp(-0.2 a) and a = 0..A, A the oldest
age (SS3 Linf_decay = -999).
"decay": L_A and 2A further ages, each one more year along the von
Bertalanffy curve, weighted by exp(-d a) with d = plus_group_decay
(SS3 Linf_decay = d).
Under "none", "SS3.24" and "decay" the plus group also grows within the
year like every other age, as SS3 does; under "M1" it keeps its Jan-1
length through the year.
Maturity-at-length is set in the data, not here: the per-species control
columns L50_mat_len and slope_mat_len.
A list of switches defining the growth model.
# Sex-specific von Bertalanffy with temperature on K, by species + sex build_growth( fun = "vonBertalanffy", # or fun = 1 linkages = list( K = linkage_spec( formula = ~ temp, by = ~ species + sex, priors = list(temp = normal(0, 1)) ) ) )# Sex-specific von Bertalanffy with temperature on K, by species + sex build_growth( fun = "vonBertalanffy", # or fun = 1 linkages = list( K = linkage_spec( formula = ~ temp, by = ~ species + sex, priors = list(temp = normal(0, 1)) ) ) )
Defines the harvest control rule and its associated reference
points. The rules are tabulated, with which ones work under predation, in
vignette("projections-and-reference-points"); the formulations of
the three ramped rules are below.
build_hcr( HCR = 0, DynamicHCR = FALSE, Ftarget = 0.4, Flimit = 0.35, Ptarget = 0.4, Plimit = 0, Alpha = 0.05, Pstar = 0.45, Sigma = 0.5, Fmult = 1, HCRorder = 1 )build_hcr( HCR = 0, DynamicHCR = FALSE, Ftarget = 0.4, Flimit = 0.35, Ptarget = 0.4, Plimit = 0, Alpha = 0.05, Pstar = 0.45, Sigma = 0.5, Fmult = 1, HCRorder = 1 )
HCR |
Harvest control rule, as an integer or string alias:
|
DynamicHCR |
TRUE/FALSE. Use dynamic rather than static reference points (default FALSE). |
Ftarget |
Target fishing mortality rate (yr^-1), SPR- or depletion-based, or the input F for projections. For SPR F40%, enter 0.40. |
Flimit |
Limit fishing mortality rate (yr^-1), SPR- or depletion-based. For SPR F35%, enter 0.35. |
Ptarget |
Target spawning-stock biomass as a proportion of static or dynamic spawning-stock biomass at F = 0. For B40%, enter 0.40. |
Plimit |
Limit spawning-stock biomass on the same basis. For B10%, enter 0.10. |
Alpha |
Parameter used in the NPFMC Tier 3 rule. |
Pstar |
Quantile for the uncertainty buffer, given |
Sigma |
Standard deviation of the normal uncertainty buffer, given
|
Fmult |
Multiplier on the target F (default 1), scaling it following NEFSC convention. |
HCRorder |
For multispecies models, the order in which to project fishing (predators first, then prey, for instance). |
hcr = 5 or "NPFMC", the North Pacific Fishery Management
Council Tier 3 spawner-per-recruit rule:
Stock status:
Stock status:
Stock status: or
hcr = 6 or "PFMC", the Pacific Fishery Management Council
category 1 40-10 annual catch limit rule (PFMC 2020), using Fspr in single
species or the F reaching X% of SSB0 under predation. The uncertainty buffer
is qnorm(Pstar, Flimit, Sigma), which equals
Flimit + qnorm(Pstar, 0, Sigma) and so sits below Flimit
when . The taper runs between and
, so the 40-10 shape needs Ptarget = 0.40 and
Plimit = 0.10; the default Plimit = 0 gives a 40-0 rule.
Stock status:
Stock status:
Stock status:
hcr = 7 or "SESSF", the Southern and Eastern Scalefish and
Shark Fishery Tier 1 spawner-per-recruit rule, with F_Limit = F_(20%) and
B_Limit = SB_20 (AFMA 2017):
Stock status:
Stock status:
Stock status:
A list containing the harvest control rule and associated
biological reference points.
# Tier 3 NPFMC control rule: F40% as FABC, F35% as FOFL. build_hcr(HCR = "NPFMC", DynamicHCR = FALSE, Ftarget = 0.4, Flimit = 0.35) # No fishing: the projection a B0 reference point is read from. build_hcr(HCR = "NoFishing")# Tier 3 NPFMC control rule: F40% as FABC, F35% as FOFL. build_hcr(HCR = "NPFMC", DynamicHCR = FALSE, Ftarget = 0.4, Flimit = 0.35) # No fishing: the projection a B0 reference point is read from. build_hcr(HCR = "NoFishing")
Reads a data list and map to update the map argument based on the HCR specified in build_hcr
build_hcr_map( data_list, map, debug = FALSE, all_params_on = FALSE, HCRiter = 1 )build_hcr_map( data_list, map, debug = FALSE, all_params_on = FALSE, HCRiter = 1 )
data_list |
an Rceattle data_list |
map |
a map object created from |
debug |
logical. If TRUE, turns off all parameters for debugging (default = FALSE). |
all_params_on |
logical. If TRUE, leaves all hindcast parameters turned on (default = FALSE). |
HCRiter |
for multi-species models, the order in which to project fishing (e.g. predators first, then prey) |
a list of map arguments for each parameter
Specify the residual natural mortality (M1) model for Rceattle
build_M1( M1_model = 0, M1_re = 0, updateM1 = FALSE, M1_use_prior = FALSE, M2_use_prior = FALSE, M_prior = 0.4, M_prior_sd = 0.35, M1_indices = NA, linkages = NULL )build_M1( M1_model = 0, M1_re = 0, updateM1 = FALSE, M1_use_prior = FALSE, M2_use_prior = FALSE, M_prior = 0.4, M_prior_sd = 0.35, M1_indices = NA, linkages = NULL )
M1_model |
Vector or scalar specifying the M1 structural fixed- effects model. Either an integer code or the equivalent string alias (both forms are accepted; the integer code is canonical):
|
M1_re |
Vector or scalar specifying the M1 random-effects model, as an
integer code or the equivalent string alias: |
updateM1 |
If using initial parameters, use M1 fixed effects
from data ( |
M1_use_prior |
Vector or scalar; if |
M2_use_prior |
Vector or scalar; if |
M_prior |
Natural-scale mean of the lognormal prior on M (its median when |
M_prior_sd |
SD (log-scale) of the lognormal prior on M. |
M1_indices |
Soft-deprecated. Vector of column indices into
|
linkages |
Optional named list of |
Which M1_re families work with which M1_model. Anything but 0 needs
an M1_model of 0, 1, 2, or 3 with a by-year family (2 / 5); the
by-age families are refused under 3 because an age-varying deviation and an
age-specific level are not separately identifiable, and 4 and 5 are
refused entirely (use a catchability-style linkage instead). M1_model = 2
needs two sexes under every M1_re family, because a single-sex species would
take its deviations in the padding sex slot, free and scored by no density.
fit_mod() downgrades M1_model to 1 there, so the distinction shows only
in a direct build_map() call.
A list of switches for defining the M1 model.
M1_base completenessM1_base needs a finite, positive residual M (per year) for every age of
every sex the species has; it is taken on the log scale, so a blank or a zero
is refused, naming the offending (species, sex, age) cells. Columns past a
species' own nages are ignored, so a row may stop at its last age.
# Sex/age-invariant M with a temperature linkage on M1 build_M1( M1_model = "sex_age_invariant", linkages = list( M1 = linkage_spec( formula = ~ temp, by = ~ species, priors = list(temp = normal(0, 0.5)) ) ) )# Sex/age-invariant M with a temperature linkage on M1 build_M1( M1_model = "sex_age_invariant", linkages = list( M1 = linkage_spec( formula = ~ temp, by = ~ species, priors = list(temp = normal(0, 0.5)) ) ) )
Builds the TMB map, which tells TMB which parameters to estimate
and which to hold fixed (a fixed parameter is mapped to NA), and which
parameters share a single estimated value. One helper handles each process
block (recruitment, M1, predation, selectivity, catchability, ...).
build_map( data_list, params, debug = FALSE, random_rec = FALSE, random_sel = FALSE, random_q = NULL )build_map( data_list, params, debug = FALSE, random_rec = FALSE, random_sel = FALSE, random_q = NULL )
data_list |
an Rceattle data_list |
params |
A parameter list created from |
debug |
Logical. If TRUE, fixes every parameter except the dummy
(maps all to |
random_rec |
Logical. If TRUE, treats recruitment deviations as random effects,
meaning the variance parameter ( |
random_sel |
Logical. If TRUE, treats selectivity deviations as random effects,
meaning the variance parameter ( |
random_q |
Logical. If TRUE, treats catchability deviations as random effects,
meaning the variance parameter ( |
Fleets sharing a Selectivity_index or a Catchability_index have the lead
fleet's map slice copied over the rest of the group, so a per-fleet setting
that differs within a group is resolved here rather than reported. Those
disagreements are checked in data_check(), which fit_mod() runs first;
build_map() does not call it, so a caller invoking build_map() directly
should run data_check() too.
A list containing the factorized TMB map (mapFactor) and the
original map matrix/array list (mapList).
Maps catchability base parameters (index_log_q),
time-varying deviations (index_q_dev), and environmental linkages
(index_q_beta) for every fleet that holds
fitted index_data, a fishery with a CPUE series as much as a
survey. A fleet with no index rows gets none of them, whatever its
Catchability says, since a q with no index to inform it is a flat
direction. Sharing overrides this: adjust_map_shared_params() then
copies the lead fleet's slice across each Catchability_index group.
build_map_catchability(map_list, data_list, nyrs_hind, random_q = FALSE)build_map_catchability(map_list, data_list, nyrs_hind, random_q = FALSE)
map_list |
The current TMB map list. |
data_list |
The data list containing model settings. |
nyrs_hind |
Number of historical years. |
random_q |
Logical. If TRUE, the deviation sd ( |
Updated map_list.
Sets all parameters in the map list to NA, except the
dummy parameter, for use in debug or testing modes.
build_map_debug(map_list, debug)build_map_debug(map_list, debug)
map_list |
The current TMB map list. |
debug |
Logical. If TRUE, debug mode is activated. |
Updated map_list.
Maps fishing mortality parameters (log_F) and related targets.
Also maps data weighting parameters (catch_log_sd, comp_weights, caal_weights).
build_map_f_and_data_weights(map_list, data_list, nyrs_hind)build_map_f_and_data_weights(map_list, data_list, nyrs_hind)
map_list |
The current TMB map list. |
data_list |
The data list containing model settings. |
nyrs_hind |
Number of historical years. |
Updated map_list.
Turns off (sets to NA) most population and fleet parameters for
species where the dynamics are fixed (estDynamics > 0).
build_map_fixed_natage(map_list, data_list)build_map_fixed_natage(map_list, data_list)
map_list |
The current TMB map list. |
data_list |
The data list containing model settings. |
Updated map_list.
Maps the growth parameters (log_growth_pars,
growth_log_sd, weight_length_pars) according to
growth_model. Everything starts mapped off and each growth function
turns on the parameters it uses.
Time-varying growth comes from the linkage grammar
(build_growth(linkages = )), whose random effects hold their own
density and map.
build_map_growth(map_list, data_list, nyrs_hind)build_map_growth(map_list, data_list, nyrs_hind)
map_list |
The current TMB map list. |
data_list |
The data list containing model settings. |
nyrs_hind |
Number of historical years. |
Updated map_list.
Maps the fixed parameters (log_M1) and the random effects
parameters (log_M1_dev, M1_dev_log_sd, M1_rho) based on
M1_model and M1_re settings.
build_map_m1(map_list, data_list, nyrs_hind)build_map_m1(map_list, data_list, nyrs_hind)
map_list |
The current TMB map list. |
data_list |
The data list containing model settings. |
nyrs_hind |
Number of historical years. |
Updated map_list.
Maps predation suitability parameters (log_gam_a, log_gam_b,
log_phi) and diet weight parameters based on msmMode and
suitMode.
build_map_predation(map_list, data_list)build_map_predation(map_list, data_list)
map_list |
The current TMB map list. |
data_list |
The data list containing model settings. |
Updated map_list.
Maps the recruitment deviations (rec_dev, init_dev),
stock-recruitment parameters (rec_pars) and Rec dev variances (R_log_sd)
see build_srr() for options,
build_map_recruitment(map_list, data_list, nyrs_hind, nyrs_proj, random_rec)build_map_recruitment(map_list, data_list, nyrs_hind, nyrs_proj, random_rec)
map_list |
The current TMB map list. |
data_list |
The data list containing model settings. |
nyrs_hind |
Number of historical years. |
nyrs_proj |
Total number of years (historical + projected). |
random_rec |
Logical indicating if recruitment deviations are random effects. |
Updated map_list.
Maps base selectivity parameters (log_sel_slp, sel_inf,
sel_coff) and time-varying deviations, based on Selectivity
and Time_varying_sel settings in fleet_control.
build_map_selectivity(map_list, data_list, nyrs_hind, random_sel)build_map_selectivity(map_list, data_list, nyrs_hind, random_sel)
map_list |
The current TMB map list. |
data_list |
The data list containing model settings. |
nyrs_hind |
Number of historical years. |
random_sel |
Logical indicating if selectivity deviations are random effects. |
Selectivity sets the curve's shape and Time_varying_sel whether it
varies over time; for the allowed values of both, see
"3. Selectivity (per fleet)" in
vignette("model-options-and-functionality"), or
rceattle_switch_maps for the code-to-name maps themselves.
N_sel_bins is how many age or length bins the non-parametric and AR1 forms
estimate (Selectivity 2, 5, 6, 7, 9 or 13); it is unused otherwise.
random_sel in fit_mod() treats the deviations as random effects and
estimates their variance.
The double-normal forms blend Gaussian ascending and descending limbs at the
peak. DoubleNormal reads its four parameters from the shared arrays:
sel_inf[1] = peak, sel_inf[2] = logit(right_floor) (the right-tail floor,
SS3 P6/end_logit), log_sel_slp[1] = log(sigma_asc) and
log_sel_slp[2] = log(sigma_desc). right_floor -> 0 is dome-shaped;
right_floor -> 1 is logistic ascending only. DoubleNormalSS3 instead
carries its own six-parameter array (sel_dn6).
Updated map_list.
Construct the TMB parameter list, with every parameter set to its starting value, for an Rceattle model.
build_params(data_list)build_params(data_list)
data_list |
an Rceattle data_list |
a named list of model parameters at their starting values
Holds environmental linkages on selectivity parameters. An effect is written
as a formula and composes additively with any Time_varying_sel process
error on the same fleet, the two being separate mechanisms: a covariate
effect against a deviation.
The linkages keys are the shape parameters of the parametric forms, so
which apply depends on the fleet's Selectivity:
slp_asc, slp_desc
ascending / descending logistic slope (log
scale); the double-normal widths, aliased sigma_asc / sigma_desc.
inf_asc, inf_desc
ascending / descending inflection age or
length (natural scale); the double-normal peak and logit right-floor,
aliased peak / right_floor.
coffnon-parametric selectivity-at-bin coefficients.
apicala log-scale multiplier on one sex's whole curve, applied after the form and before normalization, so every estimated form takes it. See Details.
DoubleNormalSS3 (code 15) carries its own six under Stock Synthesis's
names – dn_peak, top_logit, ascend_se, descend_se, start_logit,
end_logit – and a linkage is the only way to vary that form over time,
since Time_varying_sel is refused on it. A time block is
~ cut(Year, ...); annual deviations are a random-effect term.
Every parameter but apical takes link = "log" (multiplicative on the
natural parameter) or link = "identity" (additive); apical is already a
multiplier and takes "log" only.
build_selectivity(linkages = NULL)build_selectivity(linkages = NULL)
linkages |
Optional named list of |
The apical offset. Fishing mortality is one log_F per fleet and year
shared by the sexes, and no form has a height parameter, so a sex difference
in F can only come from selectivity. apical multiplies one sex's curve by
exp(log_sel_apical) bin by bin, as Stock Synthesis's male-offset option
does. Name the fleet and the sex that holds it (fleet = 3,
sex = "male"; by defaults to ~ fleet + sex here) and the other sex is
the reference. It equals the ratio of the sexes' peak heights only where
their shapes peak equally, so for a sex-specific dome read it as the
multiplier and take the peak ratio from fit$quantities$sel_at_age.
Only the contrast between sexes is identified, the common level being
log_F, so one sex holds it and the fit is refused if both do, if no fleet
or sex is named, if the species has one sex, on a Fixed, AR1 or
Fleet_type = "Off" fleet, on a fleet sharing another's
Selectivity_index, under link = "identity" (which could drive the
multiplier negative), or where Sel_norm_scope = "WithinSex" would divide it
straight back out. The contrast is informed only by joint composition
(comp_data$Sex = 3); with single-sex compositions it rests on its prior,
and fit_mod() warns when a fleet has neither. An intercept prior is on the
multiplier's natural scale, so a lognormal() centred on 1 means no offset.
See vignette("environmental-linkages-and-priors").
Priors on a selectivity parameter. An intercept-only formula (~ 1) with
a priors entry puts a prior on the parameter itself, adding no
year-to-year offset. Read it on the parameter's own scale: the slopes are log
scale (lognormal()), the inflections natural scale (normal()). A prior
targets one parameter, so in a two-sex model an unstratified ~ 1 prior
constrains sex 1 only – use by = ~ sex. An init on a selectivity
intercept has no effect, since the starting value comes from the data, and a
prior on the double-normal right_floor is unsupported. Fleets sharing a
Selectivity_index estimate one block, so place the prior on the group's
lead fleet (its first that is not Off): a prior on a follower would
penalize the shared block once per sharing fleet. On an Off fleet a prior
is dropped with a warning and the fleet's linkage coefficients are held at
their starting values, since the fleet has no data; on an Off member of a
shared block it moves to the block's lead instead.
Like every selectivity linkage, a covariate acts in the hindcast years; projection years hold the last hindcast year's curve.
A list of selectivity settings for fit_mod().
# A cold-pool effect on the ascending inflection of a logistic fleet build_selectivity(linkages = list( inf_asc = linkage_spec(~ cold_pool, by = ~ fleet))) # A normal prior on the ascending inflection (intercept-only formula) build_selectivity(linkages = list( inf_asc = linkage_spec(~ 1, priors = list(`(Intercept)` = normal(0, 3)))))# A cold-pool effect on the ascending inflection of a logistic fleet build_selectivity(linkages = list( inf_asc = linkage_spec(~ cold_pool, by = ~ fleet))) # A normal prior on the ascending inflection (intercept-only formula) build_selectivity(linkages = list( inf_asc = linkage_spec(~ 1, priors = list(`(Intercept)` = normal(0, 3)))))
Sets the stock-recruit curve and how recruitment is estimated.
Relationships currently implemented:
srr_fun = 0 or "mean": no stock-recruit relationship.
Recruitment is (log scale) plus annual deviates, and the
reported steepness holds its placeholder 0.99 rather than being
estimated.
srr_fun = 2 or "BevertonHolt":
srr_fun = 4 or "Ricker":
Both curves are the deterministic mean; realized recruitment applies the
annual log deviation, . For numerical stability
the Ricker is estimated divided by 1,000,000, so the fitted
beta is 1e6 times the coefficient above. Bmsy_lim is on the
natural scale: the template divides it by 1e6 before comparing, so supply it
in metric tons.
With srr_pred_fun > 0 and srr_fun = 0, the hindcast estimates
recruitment as in the mean form while the curve is fitted between
srr_hat_styr and srr_hat_endyr as a penalty, then used in the
projection.
Multispecies models. Spawning biomass per recruit is undefined once
mortality includes predation, so under msmMode > 0 a curve fitted in
the hindcast estimates its initial recruitment level (R0) rather than
deriving it, and under the fished initModes (3, 4) that level trades off
against the initial F. A steepness prior is refused and steepness is
reported as 0; priors on alpha or beta go through linkages.
Two refusals worth knowing before you write a linkage: under a curve fitted
in the hindcast a single-species R0 is derived from alpha and beta, so
an R0 linkage is refused (a multispecies model accepts an
intercept-only one), and a Ricker lognormal linkage prior on alpha duplicates
the deprecated srr_est_mode = "LognormalPrior", so using both is
refused.
build_srr( srr_fun = 0, srr_pred_fun = srr_fun, proj_mean_rec = TRUE, srr_mse_switchyr = NULL, srr_hat_styr = NULL, srr_hat_endyr = NULL, srr_est_mode = 1, srr_prior = 4, srr_prior_sd = 1, srr_alpha_init = NULL, srr_beta_init = NULL, srr_indices = NA, Bmsy_lim = NA, linkages = NULL )build_srr( srr_fun = 0, srr_pred_fun = srr_fun, proj_mean_rec = TRUE, srr_mse_switchyr = NULL, srr_hat_styr = NULL, srr_hat_endyr = NULL, srr_est_mode = 1, srr_prior = 4, srr_prior_sd = 1, srr_alpha_init = NULL, srr_beta_init = NULL, srr_indices = NA, Bmsy_lim = NA, linkages = NULL )
srr_fun |
Stock-recruit function used in the hindcast estimation (see below). Default = 0 |
srr_pred_fun |
Stock-recruit function used for projection, reference
points and penalties. When |
proj_mean_rec |
Recruitment used in the projection: |
srr_mse_switchyr |
Year at which an MSE switches from the annual recruitment-penalty estimate to the stock-recruit function. |
srr_hat_styr, srr_hat_endyr
|
First and last year used to estimate the
recruitment-penalty function (active when |
srr_est_mode |
The curve's built-in prior, as a code or string:
1 / |
srr_prior |
Natural-scale prior mean of Beverton-Holt steepness under
modes 2 and 3 (the median of a lognormal prior when
|
srr_prior_sd |
Prior standard deviation: log scale for the lognormal prior (mode 2), natural scale for the beta prior (mode 3). |
srr_alpha_init, srr_beta_init
|
Optional natural-scale starting values for alpha and beta, one per species, used only where the curve estimates them. |
srr_indices |
Defunct: supplying it is an error; express an
environmental effect through |
Bmsy_lim |
Upper limit on Ricker SSB-MSY (1/beta) in metric tons, adding
a likelihood penalty once estimated SSB-MSY rises above it. Default |
linkages |
Named list of |
A list containing the stock recruitment relationship settings
None of the starting values knows the stock's scale, and a bad one fails the
fit rather than fitting badly. Mean recruitment (R0) starts at
thousand fish; alpha starts at srr_prior (default 4)
wherever that is an alpha and at otherwise; beta starts at 3. Set
them with srr_alpha_init / srr_beta_init or a linkage
init.
sets the density dependence in ,
so it must be on the order of , typically
or smaller for a stock measured in tonnes. Starting three orders
of magnitude away drives predicted recruitment to near zero and the optimizer
returns NA/NaN gradient evaluation. From a steepness and
unfished spawning biomass per recruit :
Under predation, where is undefined, seed them from a curve
fitted to an earlier fit's SSB-recruitment pairs.
# Mean recruitment: no stock-recruit relationship fitted. build_srr(srr_fun = "mean") # Beverton-Holt with a lognormal prior on alpha (mean 5, log-scale SD 0.5), # species 1 only. build_srr(srr_fun = "BevertonHolt", linkages = list(alpha = linkage_spec(~ 1, species = 1, priors = list(`(Intercept)` = prior_lognormal(log(5), 0.5))))) # Mean recruitment with the curve as a penalty (Ianelli form). build_srr(srr_fun = "mean", srr_pred_fun = "BevertonHolt") # A prior on Beverton-Holt steepness, the one prior linkages cannot express # (single-species only). build_srr(srr_fun = "BevertonHolt", srr_est_mode = "LognormalPrior", srr_prior = 0.8, srr_prior_sd = 0.2)# Mean recruitment: no stock-recruit relationship fitted. build_srr(srr_fun = "mean") # Beverton-Holt with a lognormal prior on alpha (mean 5, log-scale SD 0.5), # species 1 only. build_srr(srr_fun = "BevertonHolt", linkages = list(alpha = linkage_spec(~ 1, species = 1, priors = list(`(Intercept)` = prior_lognormal(log(5), 0.5))))) # Mean recruitment with the curve as a penalty (Ianelli form). build_srr(srr_fun = "mean", srr_pred_fun = "BevertonHolt") # A prior on Beverton-Holt steepness, the one prior linkages cannot express # (single-species only). build_srr(srr_fun = "BevertonHolt", srr_est_mode = "LognormalPrior", srr_prior = 0.8, srr_prior_sd = 0.2)
Check which saved MSE simulation files can be loaded
check_mse(dir = NULL, file = NULL)check_mse(dir = NULL, file = NULL)
dir |
Directory used to save files from |
file |
file name used to save files from |
list of MSE simulations/run
Fills optional blocks with correctly-shaped empties, filters observations to the model's year range, extends catch to the projection years, and re-keys any survey-index covariance matrices. Whether a missing block is actually a problem is left to the fit-time validation, which knows the model configuration.
clean_data(data_list)clean_data(data_list)
data_list |
Rceattle data list |
Extract estimated parameters from an Rceattle fit
## S3 method for class 'Rceattle' coef(object, ...)## S3 method for class 'Rceattle' coef(object, ...)
object |
An object of class |
... |
Currently unused. |
A named numeric vector of estimated fixed-effect parameters
(the optimizer's par). Returns NULL if the model was not
estimated.
Concatenate two data lists into one. env_data is taken from data_list1,
and diet data must be updated afterward.
combine_data(data_list1 = NULL, data_list2 = NULL)combine_data(data_list1 = NULL, data_list2 = NULL)
data_list1 |
Rceattle data_list 1 |
data_list2 |
Rceattle data_list 2 |
Function to evaluate the simulation performance with regard to bias using the median relative error (MRE) and precision using the coefficient of variation.
compare_sim(operating_mod, simulation_mods, object = "quantities")compare_sim(operating_mod, simulation_mods, object = "quantities")
operating_mod |
CEATTLE model object exported from |
simulation_mods |
List of CEATTLE model objects exported from |
object |
character string specifying which part of the model to compare (default = "quantities") |
A data frame summarizing simulation performance metrics
Compares against operating_mod only, so it is valid when the
replicates redrew the observations alone. If they were produced with
sim_mod(process = ) / self_test(process = ), the operating
model's deviations are no longer what generated the data and the bias this
reports is an artefact. Compare against
attr(sims, "process_sim") in that case. Passing a
self_test result that holds process draws warns, since the
attribute makes that case detectable rather than only documented.
Runs the post-fit convergence battery and returns a single structured
object. Each check yields a record with a common schema
(id, tier, severity, message, data);
severity is one of "OK", "NOTE", "WARN",
"FAIL". The object's status is the worst severity present.
convergence_diagnostics(object, ...)convergence_diagnostics(object, ...)
object |
An object of class |
... |
Currently unused. |
fit_mod() runs this automatically and attaches the result as
fit$convergence; call convergence_diagnostics() directly to
re-run it on any fit. Checks cover the optimizer gradient, a requested
sdreport that did not return, an sdreport that was never
requested, Hessian positive-definiteness and conditioning, parameters on
bounds, parameters past them, a deviation variance estimated to zero, phasing,
parameter estimability, a numbers-at-age, Ricker-intercept or recruitment floor that
was reached, and the stock-recruit curve.
An object of class "Rceattle_convergence": a list with
status (overall worst severity) and checks (named list of
records).
Introspects the Rceattle data-element catalogue and reports, for a given model
configuration, which top-level data_list elements are Required,
Optional (used if supplied, otherwise default-filled by clean_data()), or
Ignored (not consulted because the feature that would use them is switched
off). It answers "what do I actually need to supply for this model?" without
having to read the validation code or the switch tables, the same conditions
enforced at fit time (they share one declarative table).
data_requirements( data_list = NULL, msmMode = 0, growth_model = 0, estDynamics = 0, Selectivity = NULL, Index_distribution = NULL, Ceq = NULL )data_requirements( data_list = NULL, msmMode = 0, growth_model = 0, estDynamics = 0, Selectivity = NULL, Index_distribution = NULL, Ceq = NULL )
data_list |
Optional. An existing Rceattle data list (e.g. from
|
msmMode |
Predation mode used to build the configuration when |
growth_model |
Growth mode (scalar or per-species). |
estDynamics |
Numbers-at-age mode (scalar or per-species). |
Selectivity |
Optional character vector of per-fleet selectivity forms
(used only when |
Index_distribution |
Optional character vector of per-fleet index
likelihood families (used only when |
Ceq |
Optional per-species consumption-equation codes (used only when
|
The configuration can be given either as an existing (possibly partial)
data_list, its switches are normalized through clean_data() /
switch_check() so the conditions evaluate against filled defaults, or,
when no data_list is supplied, built from the convenience arguments.
Requirements are conditional: e.g. diet_data, ration_data and the
bioenergetics scalars are Ignored under single-species (msmMode = 0) but
Required under multispecies (msmMode > 0); caal_data is Optional unless
growth_model > 0; NByageFixed is Ignored unless estDynamics > 0;
emp_sel is Required only for fleets with Selectivity = "Fixed";
index_cov only for Index_distribution = "MVN".
A data.frame with one row per data element and columns:
elementthe data_list element name.
categorygrouping (dimensions / biology / fishery / composition / predation / environment).
status"Required", "Optional", or "Ignored".
conditionthe condition under which the element is required
("always" for the core backbone).
defaultfor Optional elements, the clean_data() default used
when the element is absent.
Rows are ordered Required, then Optional, then Ignored.
# Single-species: predation/diet inputs are Ignored, comp_data Optional. data_requirements(msmMode = 0) # Multispecies: diet_data and bioenergetics become Required. data_requirements(msmMode = 1) # From a bundled dataset. data_requirements(BS2017SS)# Single-species: predation/diet inputs are Ignored, comp_data Optional. data_requirements(msmMode = 0) # Multispecies: diet_data and bioenergetics become Required. data_requirements(msmMode = 1) # From a bundled dataset. data_requirements(BS2017SS)
A fitted Rceattle model object for the multispecies run of CEATTLE
for the Eastern Bering Sea (walleye pollock, Pacific cod, arrowtooth
flounder).
EBS_ms_runEBS_ms_run
An object of class Rceattle.
A fitted Rceattle model object for the single-species run of CEATTLE
for the Eastern Bering Sea with natural mortality estimated.
EBS_ss_M_runEBS_ss_M_run
An object of class Rceattle.
A fitted Rceattle model object for the single-species run of CEATTLE
for the Eastern Bering Sea (walleye pollock, Pacific cod, arrowtooth
flounder) without estimating natural mortality.
EBS_ss_runEBS_ss_run
An object of class Rceattle.
fit_mod()
Collects the optimizer and reporting settings into one object, so a call to
fit_mod() stays about the model rather than how it is fit. Pass the result
through fit_mod()'s fit_control argument, where it overrides the
equivalent individual arguments, which are kept for back-compatibility.
fit_control( bias.correct = FALSE, getsd = TRUE, getJointPrecision = TRUE, getReportCovariance = FALSE, projection_uncertainty = FALSE, selectivity_se = FALSE, comp_offset = NULL, bias_adjust_obs = TRUE, bias_adjust_proc = TRUE, use_gradient = TRUE, rel_tol = 1, loopnum = 5, newtonsteps = 0, phase = FALSE, TMBfilename = NULL, verbose = 1, nlminb_control = list(eval.max = 1e+09, iter.max = 1e+09, trace = 0) )fit_control( bias.correct = FALSE, getsd = TRUE, getJointPrecision = TRUE, getReportCovariance = FALSE, projection_uncertainty = FALSE, selectivity_se = FALSE, comp_offset = NULL, bias_adjust_obs = TRUE, bias_adjust_proc = TRUE, use_gradient = TRUE, rel_tol = 1, loopnum = 5, newtonsteps = 0, phase = FALSE, TMBfilename = NULL, verbose = 1, nlminb_control = list(eval.max = 1e+09, iter.max = 1e+09, trace = 0) )
bias.correct |
logical. Apply bias correction via |
getsd |
logical. Run |
getJointPrecision |
logical. Return the full Hessian of fixed and
random effects. Default |
getReportCovariance |
logical. Return the variance-covariance of
|
projection_uncertainty |
logical. Carry hindcast parameter uncertainty
into an HCR projection, by refitting with the hindcast and
biological-reference-point parameters turned on. Default |
selectivity_se |
logical. Also return a standard error for log
selectivity-at-age. Default |
comp_offset |
Numeric or |
bias_adjust_obs |
logical, default |
bias_adjust_proc |
logical, default |
use_gradient |
logical. Use the analytic gradient during phasing.
Default |
rel_tol |
Numeric tolerance for flagging a discontinuous likelihood,
comparing |
loopnum |
Integer. Times to restart optimization; |
newtonsteps |
Integer. Extra unconstrained Newton steps after
optimization, an alternative to |
phase |
|
TMBfilename |
Optional path (without |
verbose |
|
nlminb_control |
Control parameters passed to |
A list of class "Rceattle_fit_control".
selectivity_se needs getsd = TRUE, and reports the error belonging to
whichever sdreport the fit ends on. Under estimateMode = "Estimate" with
an HCR that re-optimizes, that is the projection fit, where every
selectivity parameter is mapped off, so every error comes back exactly 0;
"Projection" estimates no selectivity at all. Use "Hindcast", or
"Estimate" with projection_uncertainty = TRUE, to get an error from a fit
that estimated the curve. fit_mod() warns in each of these cases.
It is off by default because the delta method forms a Jacobian of every
reported value against every parameter, so the cost is their product: on
Atka2022, 1,012 values against 584 parameters. The error is on the log
scale rather than the logit, because the non-parametric forms normalize to
mean selectivity 1 instead of a maximum of 1 – 58% of Atka2022's
sel_at_age exceeds 1, up to 3.06 – so a logit is undefined over most of
the array.
Rows cover estimated, age-based lead fleets only, starting at each fleet's
first selected bin. Four kinds of cell are a structural zero (a Fixed
fleet's empirical curve, a length-based fleet's growth-matrix projection, a
bin below Bin_first_selected, and array padding), and one log(0) = -Inf
on the tape turns every quantity in the sdreport to NaN, biomass and
SSB included. All four are identified from the data, so the reported set
never depends on a parameter value, and a value that underflows to zero is
floored so it cannot reintroduce the -Inf. See plot_selectivity(), which
draws the interval.
# Quick-and-dirty fit: skip sdreport, single optimizer pass ctl <- fit_control(getsd = FALSE, loopnum = 1) # Production fit with bias correction and joint precision ctl <- fit_control(bias.correct = TRUE, getJointPrecision = TRUE)# Quick-and-dirty fit: skip sdreport, single optimizer pass ctl <- fit_control(getsd = FALSE, loopnum = 1) # Production fit with bias correction and joint precision ctl <- fit_control(bias.correct = TRUE, getJointPrecision = TRUE)
Estimate CEATTLE population parameters by maximum likelihood, and optionally project the stock and apply a harvest control rule.
fit_mod( data_list = NULL, inits = NULL, map = NULL, bounds = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, random_q = FALSE, random_sel = FALSE, HCR = build_hcr(), niter = 3, recFun = build_srr(), M1Fun = build_M1(), growthFun = build_growth(), qFun = build_catchability(), selFun = build_selectivity(), compFun = build_composition(), msmMode = 0, avgnMode = 0, initMode = "NonEquilibrium", suitMode = 0, suit_styr = NULL, suit_endyr = NULL, fit_control = NULL, config = NULL, quiet_data_check = FALSE, ... )fit_mod( data_list = NULL, inits = NULL, map = NULL, bounds = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, random_q = FALSE, random_sel = FALSE, HCR = build_hcr(), niter = 3, recFun = build_srr(), M1Fun = build_M1(), growthFun = build_growth(), qFun = build_catchability(), selFun = build_selectivity(), compFun = build_composition(), msmMode = 0, avgnMode = 0, initMode = "NonEquilibrium", suitMode = 0, suit_styr = NULL, suit_endyr = NULL, fit_control = NULL, config = NULL, quiet_data_check = FALSE, ... )
data_list |
A data list read in via |
inits |
(Optional) A named list of initial parameter values, as returned by
|
map |
(Optional) A map object from |
bounds |
(Optional) A bounds object from |
file |
(Optional) Filename to save to. If NULL, no file is saved. |
estimateMode |
What to fit, as a string alias or integer code:
|
random_rec |
logical; treat recruitment deviations as random effects via the Laplace approximation. Default FALSE. |
random_q |
logical; integrate the |
random_sel |
logical; the same for |
HCR |
HCR list object from |
niter |
Number of iterations for multispecies model |
recFun |
The stock recruit-relationship parameterization from |
M1Fun |
M1 parameterizations and priors. Use |
growthFun |
The weight-at-age parameterization from |
qFun |
Catchability specification from |
selFun |
Selectivity specification from |
compFun |
Composition-weighting specification from
|
msmMode |
The predation-mortality mode, as a string alias or integer
code: |
avgnMode |
the average abundance-at-age approximation in the predation
equations. Only mode 0, |
initMode |
how the population is initialized, as a string alias or
integer code: |
suitMode |
how predator-prey suitability is derived, per predator (one
value or a vector of length |
suit_styr |
The first year used to calculate mean suitability, as one
integer for every predator or a vector of length |
suit_endyr |
The last year used to calculate mean suitability, in the
same form. Defaults to |
fit_control |
A list from |
config |
(Optional) An |
quiet_data_check |
Drop the warnings fit-time validation raises; errors
still stop the fit. |
... |
Deprecated optimizer / sdreport / phasing arguments, forwarded
into |
CEATTLE is an age-structured population model, fit with or without predation
mortality; msmMode selects which.
What config overlays, at two levels. The estimation controls
(estimateMode, random_rec / random_q / random_sel, suit_styr /
suit_endyr, fit_control) overlay only arguments you did not pass, so an
explicit argument always wins. The stored model_config merges into the data
object's field by field: only fields the config actually set are imposed,
so a config built with model_config() keeps the linkages held on the data
object. Where both set a field and disagree, the config wins and the
difference is warned about by name. A config written before that field record
existed counts as having set its non-default fields.
A list of class "Rceattle" including:
data_list: List of data inputs
initial_params: List of starting parameters
bounds: Parameter bounds used for estimation
map: List of map used in TMB
obj: TMB model object
opt: Optimized model object from nlminb
sdrep: Object of class sdreport from TMB, with standard errors
estimated_params: List of estimated parameters
quantities: Derived quantities from CEATTLE
run_time: Model run time
data(BS2017SS) ss_run <- fit_mod( data_list = BS2017SS, estimateMode = 0, msmMode = 0, fit_control = fit_control(phase = FALSE, verbose = 0) )data(BS2017SS) ss_run <- fit_mod( data_list = BS2017SS, estimateMode = 0, msmMode = 0, fit_control = fit_control(phase = FALSE, verbose = 0) )
A data list containing inputs for a multispecies CEATTLE model fit to
three groundfish species on Georges Bank. See BS2017SS for
format details.
GeorgesBank3sppGeorgesBank3spp
A list with the same structure as BS2017SS.
This function calculates a probability transition matrix that defines the probability of a fish of a given age belonging to specific length bins. It supports Von Bertalanffy and Richards growth models and includes a Stock Synthesis (SS) style plus-group correction.
get_growth_matrix_r( fracyr, nsex_sp, nages_sp, nlengths_sp, nyrs, lengths_sp, minage_sp, maxage_sp, growth_params_sp, growth_log_sd_sp, growth_model_sp, M_plus_sp )get_growth_matrix_r( fracyr, nsex_sp, nages_sp, nlengths_sp, nyrs, lengths_sp, minage_sp, maxage_sp, growth_params_sp, growth_log_sd_sp, growth_model_sp, M_plus_sp )
fracyr |
Numeric. Fraction of the year (0 = Jan 1st). |
nsex_sp |
Integer. Number of sexes for the species. |
nages_sp |
Integer. Number of age classes. |
nlengths_sp |
Integer. Number of length bins. |
nyrs |
Integer. Number of years in the simulation. |
lengths_sp |
Vector. Boundaries of the length bins. |
minage_sp |
Numeric. The reference age (L1) for growth estimation. |
maxage_sp |
Unused by the body; |
growth_params_sp |
Array. Dimensions (sex, yr, 4). Params: K, L1, Linf, Richards m. |
growth_log_sd_sp |
Array. Dimensions (sex, 2). Log-SD of length: 1st param is SD at minage, 2nd param is SD at maxage. |
growth_model_sp |
Integer. 1 = Von Bertalanffy, 2 = Richards. |
M_plus_sp |
Numeric. Natural mortality at the oldest age (one value, or one per sex), which weights the ages pooled in the plus group by survival, as the template does. |
A 4D array of probabilities with dimensions (sex, age, length, year).
Converts a growth matrix (length-at-age probabilities) into mean weight-at-age using a length-weight relationship (W = a * L^b).
get_weight_at_age_r( nsex_sp, nages_sp, nlengths_sp, nyrs, lengths_sp, length_at_age, growth_matrix, lw_params )get_weight_at_age_r( nsex_sp, nages_sp, nlengths_sp, nyrs, lengths_sp, length_at_age, growth_matrix, lw_params )
nsex_sp |
Integer. Number of sexes. |
nages_sp |
Integer. Number of age classes. |
nlengths_sp |
Integer. Number of length bins. |
nyrs |
Integer. Number of years. |
lengths_sp |
Vector. Boundaries of the length bins. |
length_at_age |
Array. Mean length at age from get_growth_matrix_r. |
growth_matrix |
Array. 4D array (sex, age, length, year) from get_growth_matrix_r. |
lw_params |
Array. Dimensions (sex, yr, 2). Params: 1st is alpha (a), 2nd is beta (b). |
The function calculates midpoints for length bins to avoid bias. For the first bin, it assumes the width is equal to the second bin's width. The final weight-at-age is the expected value across all length bins for that age.
A 3D array of mean weights with dimensions (sex, age, year).
A data list containing inputs for a single-species CEATTLE model fit to
Gulf of Alaska groundfish data through 2018. See BS2017SS
for format details.
GOA2018SSGOA2018SS
A list with the same structure as BS2017SS.
A data list containing inputs for a single-species CEATTLE model fit to
Gulf of Alaska arrowtooth flounder data. See BS2017SS
for format details.
GOAatfGOAatf
A list with the same structure as BS2017SS.
A data list containing inputs for a single-species CEATTLE model fit to
Gulf of Alaska arrowtooth flounder data through 2023. See
BS2017SS for format details.
GOAatf2023GOAatf2023
A list with the same structure as BS2017SS.
A data list containing inputs for a single-species CEATTLE model fit to
Gulf of Alaska Pacific cod data. See BS2017SS for format
details.
GOAcodGOAcod
A list with the same structure as BS2017SS.
A data list containing inputs for a single-species CEATTLE model fit to
Gulf of Alaska walleye pollock data. See BS2017SS for
format details.
GOApollockGOApollock
A list with the same structure as BS2017SS.
A list containing biomass, spawning stock biomass, and recruitment reference values from the 2018 Gulf of Alaska Stock Assessment and Fishery Evaluation (SAFE) report.
GOAsafe2018GOAsafe2018
A list with components:
Total biomass time series
Spawning stock biomass time series
Recruitment time series
Refits the Rceattle model from starting values perturbed by N(0, sd) around the model's initial (pre-fit) parameters, to check convergence robustness.
jitter( object = NULL, njitter = 50, sd = 0.2, phase = FALSE, seed = 123, cores = NULL, getsd = NULL, timeout = Inf, fit_control = NULL, ..., Rceattle = NULL )jitter( object = NULL, njitter = 50, sd = 0.2, phase = FALSE, seed = 123, cores = NULL, getsd = NULL, timeout = Inf, fit_control = NULL, ..., Rceattle = NULL )
object |
an Rceattle model fit using |
njitter |
the number of jitters to run |
sd |
standard deviation for jitter (default = 0.2) |
phase |
as in |
seed |
random number seed. Each jitter |
cores |
Number of cores for the parallel refits. Default |
getsd |
whether each jitter runs |
timeout |
elapsed-second limit per jitter, |
fit_control |
optional |
... |
for a numeric |
Rceattle |
deprecated name for |
a list of 1. Rceattle_list, the converged jitters, and
2. nll, their objective values. Non-converged (or timed-out) starts
are dropped and reported in a message, so both can be shorter than
njitter, and that count is itself the result, since the whole point
is what fraction of random starts reach the same optimum.
Attaching Rceattle masks jitter, because that
function is not generic and this name is exported, so the mask cannot be
removed by making this an S3 method. It is harmless for the spellings base
callers use: a numeric first argument is handed straight to
base::jitter(), so jitter(1:5) and
jitter(1:5, factor = 2) behave as base does. jitter(x = 1:5)
and a positional second argument do not. x is not a parameter here,
so it is refused as an unused argument; a positional second argument binds
njitter, so jitter(1:5, 2) jitters with base's defaults and
silently drops the 2. Name base's arguments, or call
base::jitter() directly.
data(BS2017SS) ss_run <- fit_mod(data_list = BS2017SS, inits = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, msmMode = 0, avgnMode = 0, phase = FALSE, verbose = 0) jitters <- jitter(ss_run, njitter = 10)data(BS2017SS) ss_run <- fit_mod(data_list = BS2017SS, inits = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, msmMode = 0, avgnMode = 0, phase = FALSE, verbose = 0) jitters <- jitter(ss_run, njitter = 10)
Capture a linkage specification
linkage_spec( formula, param = NULL, data = NULL, by = ~species, species = NULL, sex = NULL, fleet = NULL, link = "log", init = NULL, bounds = NULL, priors = NULL, est_phase = 1L, observe = NULL, obs_sd = NULL, obs_sd_est = FALSE, integrate = TRUE )linkage_spec( formula, param = NULL, data = NULL, by = ~species, species = NULL, sex = NULL, fleet = NULL, link = "log", init = NULL, bounds = NULL, priors = NULL, est_phase = 1L, observe = NULL, obs_sd = NULL, obs_sd_est = FALSE, integrate = TRUE )
formula |
one-sided R formula whose RHS describes the linear predictor
for |
param |
target parameter name on the natural scale (e.g. |
data |
Optional data frame for formula validation; validation happens at
fit time inside |
by |
one-sided formula naming stratifying factors that each get their
own coefficients: |
species |
optional species this spec applies to, as 1-based ids
( |
sex |
optional sex ids, as integers ( |
fleet |
optional fleets, as 1-based |
link |
how the linear predictor reaches the natural-scale parameter:
|
init |
optional named list of initial values keyed by design-matrix
column (e.g. |
bounds |
optional named list of |
priors |
optional named list of Rceattle_priors objects keyed by
design-matrix column. Inside this argument |
est_phase |
optional integer estimation phase, default |
observe |
optional |
obs_sd |
optional positive measurement SD for the |
obs_sd_est |
estimate the |
integrate |
whether the random effect's deviations are integrated out by
the Laplace approximation, default |
The reserved keys sigma and rho in init / priors route the
random-effect deviation SD and, for ar1, the correlation. sigma means
different things by structure – the innovation (per-step) SD for rw(),
the marginal (stationary) SD for ar1() – so the two are not comparable
across structures; see vignette("environmental-linkages-and-priors").
integrate = FALSE leaves the deviations in the objective as a plain
penalty and reports them with standard errors. That reproduces the
ADMB/AMAK convention behind the legacy Time_varying_sel /
Time_varying_q switches, which a Laplace-integrated rw() cannot match,
because the marginal likelihood carries a log-determinant term the
penalized form has no counterpart for. Permitted only with a fixed SD
(init = list(sigma = ), no sigma prior, plus a fixed rho for ar1),
since estimating deviations and their SD jointly as fixed effects is
degenerate, and never with observe, which must stay integrated.
An Rceattle_linkage_spec object.
# A covariate on a growth parameter, one coefficient per species. Attach to a # parametric build_growth(); the default "empirical" form consumes no linkages. linkage_spec(~ temp, param = "K") # A covariate on catchability for one fleet, named rather than numbered. # `by` defaults to ~ fleet for catchability, so it need not be given. linkage_spec(~ temp, fleet = "Pollock_survey_1_shelikof_acoustic") # IID annual deviations; rw() for a random walk, ar1() for AR1. linkage_spec(~ (1 | Year)) # A random walk estimated as a penalized fixed effect, which requires a fixed # SD: the ADMB/AMAK convention behind the legacy Time_varying_* switches. linkage_spec(~ rw(1 | Year), init = list(sigma = 0.05), integrate = FALSE) # Intercept-only: a prior on the base parameter itself. linkage_spec(~ 1, priors = list(`(Intercept)` = normal(0, 1)))# A covariate on a growth parameter, one coefficient per species. Attach to a # parametric build_growth(); the default "empirical" form consumes no linkages. linkage_spec(~ temp, param = "K") # A covariate on catchability for one fleet, named rather than numbered. # `by` defaults to ~ fleet for catchability, so it need not be given. linkage_spec(~ temp, fleet = "Pollock_survey_1_shelikof_acoustic") # IID annual deviations; rw() for a random walk, ar1() for AR1. linkage_spec(~ (1 | Year)) # A random walk estimated as a penalized fixed effect, which requires a fixed # SD: the ADMB/AMAK convention behind the legacy Time_varying_* switches. linkage_spec(~ rw(1 | Year), init = list(sigma = 0.05), integrate = FALSE) # Intercept-only: a prior on the base parameter itself. linkage_spec(~ 1, priors = list(`(Intercept)` = normal(0, 1)))
The inverse of save_config(): reads a run-config YAML file and rebuilds the
model_config() structure, estimation controls, and fit_control() bundle
(reconstructing linkage formulas and priors). Attach the result to a fit with
fit_mod(data_list, config = load_config("run.yaml")), or read
$model_config off it to attach to a data list.
load_config(file)load_config(file)
file |
Path to a YAML file written by |
An Rceattle_run_config.
f <- file.path(tempdir(), "run.yaml") save_config(model_config(msmMode = 1, initMode = "Equilibrium"), f) cfg <- load_config(f) cfg$model_config$msmMode # Apply with fit_mod(data_list, config = cfg). unlink(f)f <- file.path(tempdir(), "run.yaml") save_config(model_config(msmMode = 1, initMode = "Equilibrium"), f) cfg <- load_config(f) cfg$model_config$msmMode # Apply with fit_mod(data_list, config = cfg). unlink(f)
Load saved MSE simulation runs
load_mse(dir = NULL, file = NULL, exclude = NULL, include_em = TRUE)load_mse(dir = NULL, file = NULL, exclude = NULL, include_em = TRUE)
dir |
Directory used to save files from |
file |
file name used to save files from |
exclude |
index of MSE simulations not to load |
include_em |
whether the EMs should be loaded or not (default = TRUE) |
list of MSE simulations/run
Returns the joint negative-objective from nlminb, sign-flipped, as
a "logLik" object. df is the number of estimated fixed-effect
parameters. The nobs attribute is intentionally omitted: counting
"observations" in a stock assessment likelihood (with composition
cells, indices, catches, and priors) is not well-defined, so
stats::AIC() works (uses df) while stats::BIC() does not.
## S3 method for class 'Rceattle' logLik(object, ...)## S3 method for class 'Rceattle' logLik(object, ...)
object |
An object of class |
... |
Currently unused. |
An object of class "logLik", or NULL if the model was
not estimated.
Model average of derived quantities
model_average( object = NULL, weights = NULL, uncertainty = FALSE, nboot = 10000, Rceattle = NULL )model_average( object = NULL, weights = NULL, uncertainty = FALSE, nboot = 10000, Rceattle = NULL )
object |
list of Rceattle model objects |
weights |
vector of weights to be used for weighting models |
uncertainty |
TRUE/FALSE Sample uncertainty across derived quantities using weighted bootstrap from the asymptotic distribution of MLEs |
nboot |
Number of bootstraps taken from asymptotic distribution of MLEs. Default = 10000 |
Rceattle |
deprecated name for |
an Rceattle object with derived quantities weighted by the specified weights. The length of the derived quantities spans the years which overlap across all models.
## Not run: # Equal weights across two candidate models. model_average(list(fit1, fit2), weights = c(1, 1)) # Weighted by AIC, with bootstrapped uncertainty. model_average(list(fit1, fit2), weights = c(0.7, 0.3), uncertainty = TRUE) ## End(Not run)## Not run: # Equal weights across two candidate models. model_average(list(fit1, fit2), weights = c(1, 1)) # Weighted by AIC, with bootstrapped uncertainty. model_average(list(fit1, fit2), weights = c(0.7, 0.3), uncertainty = TRUE) ## End(Not run)
Bundles the model-structure arguments of fit_mod(), predation mode,
initialization, harvest control rule, and the build_*() process
specifications, into a single validated object that can be stored on a data
list (data_list$model_config, e.g. via
build_data(..., model_config = model_config(...))). A configuration then
travels with the data instead of living only in the fit_mod() call.
model_config( msmMode = 0, initMode = "NonEquilibrium", avgnMode = 0, suitMode = 0, niter = 3, HCR = build_hcr(), recFun = build_srr(), M1Fun = build_M1(), growthFun = build_growth(), qFun = build_catchability(), selFun = build_selectivity(), compFun = build_composition() )model_config( msmMode = 0, initMode = "NonEquilibrium", avgnMode = 0, suitMode = 0, niter = 3, HCR = build_hcr(), recFun = build_srr(), M1Fun = build_M1(), growthFun = build_growth(), qFun = build_catchability(), selFun = build_selectivity(), compFun = build_composition() )
msmMode |
Predation-mortality mode (see |
initMode |
Population initialization (see |
avgnMode |
Average-N mode. Default |
suitMode |
Suitability mode. Default |
niter |
Number of predation iterations. Default |
HCR |
A harvest-control-rule specification from |
recFun |
A stock-recruit specification from |
M1Fun |
A natural-mortality specification from |
growthFun |
A growth specification from |
qFun |
A catchability specification from |
selFun |
A selectivity specification from |
compFun |
A composition specification from |
The defaults are exactly fit_mod()'s own argument defaults, so a data list
holding model_config() fits identically to one with no slot at all. When a
data list has a model_config, fit_mod() reads each field only for
arguments the caller did not pass explicitly, an argument passed to
fit_mod() always wins, even when passed at its default. Omit an argument to
let the stored configuration take effect for that field.
An object of class "Rceattle_model_config" (a named list) to be
stored as data_list$model_config.
The configuration is code-side model structure, not one of the workbook data
sheets, so it is not written by write_data() and does not survive an
xlsx round-trip, build_data(base = x, model_config = cfg) piped through
write_data() then read_data() returns without the slot. Re-attach it in
code, store it alongside the data, or persist it as a documented, git-diffable
YAML with save_config() / load_config() and apply it with
fit_mod(data_list, config = load_config("run.yaml")).
fit_mod(), build_data(), save_config(), load_config().
cfg <- model_config(msmMode = 1, initMode = "NonEquilibrium") dat <- build_data(base = BS2017MS, model_config = cfg) # fit_mod(dat) would then fit as multispecies without passing msmMode.cfg <- model_config(msmMode = 1, initMode = "NonEquilibrium") dat <- build_data(base = BS2017MS, model_config = cfg) # fit_mod(dat) would then fit as multispecies without passing msmMode.
Management strategy evaluation performance metric summary
mse_summary(mse, om_only = FALSE)mse_summary(mse, om_only = FALSE)
mse |
|
om_only |
If TRUE, report only operating-model (true) status and skip the estimation-model (EM) perception metrics. |
A named list, one element per entity dimension so each metric lives only where it applies (no NA padding):
species, a data.frame with one row per species (keyed by Species)
of the conservation / status metrics: per-species average catch, catch
inter-annual variability (IAV), and P(Closed) = the probability the
fishery is closed (catch ~ 0); the relative mean-squared error of
terminal and average SSB; the estimation-model- and operating-model-
perceived overfishing / overfished probabilities (via
build_hcr) and the probability each status is misclassified
(estimation model disagrees with the operating-model truth); and terminal
biomass, SSB, dynamic SB0, SSB depletion (equilibrium and dynamic),
average SSB depletion, and SSB-collapse counts.
fleet, a data.frame with one row per fishery fleet (keyed by
Fleet_code / Fleet_name) of average catch, catch IAV, and P(Closed).
total, a named numeric of the across-fleet total average catch and
catch IAV.
meta, run provenance (nsim, nspp, nflts, HCR, projection-year
range).
All metrics are averaged across projection years and simulations.
Metric columns hold syntactic names, so they can be typed without
backticks: avg_catch, catch_iav, p_closed, ssb_rmse_avg,
ssb_rmse_terminal, em_p_overfishing, em_p_overfished,
om_p_overfishing, om_p_overfished, p_overfishing_false_pos,
p_overfishing_false_neg, p_overfished_false_pos,
p_overfished_false_neg, om_terminal_biomass, om_terminal_ssb,
om_terminal_dynamic_sb0, om_terminal_depletion,
om_terminal_depletion_dynamic, om_avg_depletion, om_sims_collapsed,
om_no_f_sims_collapsed, om_sims_collapsed_from_f. An om_ prefix is
the operating model's truth and em_ the estimation model's perception;
the four *_false_pos / *_false_neg metrics are the probability the two
disagree. The three *_sims_collapsed metrics are counts of
simulations, not probabilities.
The three depletions divide by different references:
om_terminal_depletion_dynamic: terminal SSB over the OM's own
DynamicSB0, its history with no fishing on the stock-recruit curve with
the realized recruitment deviations and, under predation, the suitability
fitted in the hindcast. Defined for single- and multispecies OMs. A
species with input numbers-at-age (estDynamics > 0) keeps those numbers
in the dynamic run, so its dynamic depletion is near 1 and says nothing
about fishing.
om_terminal_depletion: terminal SSB over SB0, the equilibrium value
for a single-species OM. Under msmMode > 0 it is MSSB0, SSB at the end
of a no-fishing projection, which fit_mod() derives only when a harvest
control rule is present; without one (HCR = "NoFishing") this is NA.
om_avg_depletion: the OM's own ssb_depletion averaged over the
projection. Under predation with no HCR that series divides by SSB in the
last projection year, not by an unfished reference.
The collapse metrics compare the OM with OM_no_F, the OM refit with no
fishing after the original operating model's endyr (remove_F()).
Each frame holds a "labels" attribute mapping those names to the long
display strings (e.g. om_terminal_depletion_dynamic ->
"OM: Terminal SSB Depletion (Dynamic)") for plots and tables:
attr(summ$species, "labels").
## Not run: mse <- load_mse(dir = "mse_runs") s <- mse_summary(mse) s$species # one row per species s$fleet # one row per fleet s$total # across the whole system s$meta # nsim, nspp, nflts, HCR ## End(Not run)## Not run: mse <- load_mse(dir = "mse_runs") s <- mse_summary(mse) s$species # one row per species s$fleet # one row per fleet s$total # across the whole system s$meta # nsim, nspp, nflts, HCR ## End(Not run)
A data list containing inputs for a single-species CEATTLE model fit to
Gulf of Alaska northern rockfish data through 2022. See
BS2017SS for format details.
NorthernRockfish2022NorthernRockfish2022
A list with the same structure as BS2017SS.
Computes the Stewart and Monnahan (2025) statistical diagnostics for a set of OSA residuals: the standard deviation of the normalized residuals (SDNR) and the lower/upper tail statistics, each with the 95% interval expected under the standard normal null hypothesis (so departures can be judged objectively rather than by eye). Computed per data source (type x fleet) and overall.
Under a correctly specified model OSA residuals are already iid standard
normal, so the SDNR is simply their sample standard deviation. Its null
interval follows the chi-square result for the sample standard deviation of
n standard normals (Francis 2014). Each tail statistic is the r-th
order statistic of the residuals, at index round(p * (n + 1)), and its
null interval is exact: the r-th order statistic of n uniforms is
Beta(r, n - r + 1). Nothing is simulated.
osa_diagnostics(osa, nsim = 10000, probs = c(0.025, 0.975), seed = 123)osa_diagnostics(osa, nsim = 10000, probs = c(0.025, 0.975), seed = 123)
osa |
An |
nsim |
Ignored from 5.29.0, when the tail null intervals became exact; retained so existing calls keep working, and warns when supplied. |
probs |
Lower/upper tail probabilities. Default |
seed |
Ignored from 5.29.0, as |
A data frame (class "rceattle_osa_diagnostics", so it prints as a
compact severity-tagged summary; every column is still there and $ works
as before) with one row per data source plus an "all" row, with columns:
group (the "<source> fleet <n>" label), source, fleet, n, sdnr,
sdnr_lo, sdnr_hi, lower, lower_lo, lower_hi, upper, upper_lo,
upper_hi, the order statistic each tail was read at (lower_r, upper_r)
and its exact nominal probability r/(n + 1) (lower_p, upper_p,
which differ from probs at small n), and the logical flags sdnr_ok,
lower_ok, upper_ok (TRUE when the statistic is inside its null
interval). On the "all" row source and fleet are NA.
Francis, R.I.C.C. 2014. Replacing the multinomial in stock assessment models: a first step. Fish. Res. 151:70-84.
Stewart, I.J., and Monnahan, C.C. 2025. Can. J. Fish. Aquat. Sci. 82:1-13.
One-step-ahead residuals, also called forecast or quantile residuals
(Thygesen et al. 2017), computed via TMB::oneStepPredict(). Unlike Pearson
residuals they are iid standard normal under a correctly specified model even
when observations are correlated through composition bins or the model holds
random effects, so they support objective goodness-of-fit testing (Trijoulet
et al. 2023; Stewart and Monnahan 2025). The residualization runs inside the
assessment, so it also accounts for correlation induced by the model's own
random effects.
osa_residuals( object = NULL, source = c("ecov", "index", "catch", "comp", "caal"), method = "oneStepGaussianOffMode", discrete = NULL, parallel = TRUE, seed = 123, trace = FALSE, ..., fit = NULL )osa_residuals( object = NULL, source = c("ecov", "index", "catch", "comp", "caal"), method = "oneStepGaussianOffMode", discrete = NULL, parallel = TRUE, seed = 123, trace = FALSE, ..., fit = NULL )
object |
A fitted |
source |
Observation sources to residualize: any of |
method |
How the conditional distribution is read: one of
|
discrete |
Whether to treat composition observations as the discrete
counts they are. |
parallel |
Compute the per-observation loop with
|
seed |
Seed passed to |
trace |
Print |
... |
Further arguments passed to |
fit |
Deprecated name for |
Computed post hoc and expensive – TMB re-optimizes the random effects as
each observation is added – so fit_mod() does not produce them, and the fit
must have been optimized at estimateMode < 3. Composition data are
decomposed into univariate conditional residuals (binomial / beta-binomial;
Trijoulet et al. 2023), and the last bin of each composition is fixed by the
sum-to-N constraint, so it has no residual (NA).
Choosing between the methods, what each costs, how they behave under random
effects, the ceiling on |residual| under "cdf", and where compositions at
scale defeat it are in vignette("model-diagnostics"), with the measurements
behind each.
A data frame of class rceattle_osa, one row per residualized
observation, with columns source, fleet, fleet_name, species,
sex, year, age_length_bin, accumulated (the bin folds neighbouring
ages, so it stands for a range rather than the age named), length (the
conditioning length bin for caal, NA otherwise), index_label,
observed, predicted, sd and residual.
observed and predicted are on the residualization scale: log for
lognormal catch and index, natural scale for "Normal" and
"TruncatedNormal", whitened by the lower Cholesky of the survey
covariance for "MVN"/"MVNORM", and bin counts for compositions. Three
cases read differently, and none is an error:
Under method = "cdf", predicted is NA on every row because the
method forms no conditional mode. sd is NA under the default method
too; only "oneStepGaussian" returns one.
On a "TruncatedNormal" fleet under a Gaussian method, predicted is the
truncated conditional mean E[x | x > 0], which sits above the fitted
index (163.8 against a fitted 100.0 on the package fixture), and sd is
NA. The residual is unaffected.
A composition predicted can go slightly negative where a bin holds
almost no fish, and the function warns, naming the count and the years.
The bin's own count drives it, not the composition's sample size – median
observed count 0.05 on those rows against 4.9 elsewhere – so the warning
is not by itself evidence of thin data. Those residuals are biased
positive.
Adding a "TruncatedNormal" fleet can move the other fleets' residuals on
a random-effects model, because its rows interleave with the other index
fleets by year instead of forming a contiguous block: a contiguous group
reproduces a single call to 1.5e-14, while an interleaved split moved a
residual by 5.8e-2. Both orderings are valid probability-integral-transform
sequences, so neither is wrong. Fixed-effect models are unaffected.
Attributes carry seed and method – the string that was passed, or a
named vector where a group of rows ran under its own, such as
TruncatedNormal = "oneStepGeneric". Where composition types are present a
"pearson" attribute holds the matching Pearson residuals, on proportions
with the sample size in sample_size rather than the bin counts above, so
the two are not comparable column by column.
Thygesen, U.H., et al. 2017. Validation of ecological state space models using the Laplace approximation. Environ. Ecol. Stat. 24:317-339.
Trijoulet, V., et al. 2023. Model validation for compositional data in stock assessment models. Fish. Res. 257:106487.
Stewart, I.J., and Monnahan, C.C. 2025. Diagnosing common sources of lack of fit to composition data using one-step-ahead residuals. Can. J. Fish. Aquat. Sci. 82:1-13.
osa_diagnostics(), plot.rceattle_osa(), process_residuals(),
vignette("model-diagnostics")
## Not run: data(BS2017SS) fit <- fit_mod(BS2017SS, estimateMode = "Hindcast") osa <- osa_residuals(fit, source = c("index", "comp")) plot(osa) ## End(Not run)## Not run: data(BS2017SS) fit <- fit_mod(BS2017SS, estimateMode = "Hindcast") osa <- osa_residuals(fit, source = c("index", "comp")) plot(osa) ## End(Not run)
The TMB parameter vector uses transformed, abbreviated names,
log_M1, R_log_sd, index_log_q. This returns the table mapping each one
to the quantity it represents on its natural scale, which process it belongs
to, what it means, and its dimensions.
parameter_dictionary(internal = NULL, process = NULL)parameter_dictionary(internal = NULL, process = NULL)
internal |
Character vector of internal parameter names, as they appear
in |
process |
Character vector restricting the table to one or more parts of
the model: |
A name beginning log_, or ending _log_sd, is estimated on the log scale,
so exp() turns it into the quantity named in the natural column. Most
fitted values are already back-transformed in fitted$quantities, so this is
mainly needed when reading estimated_params or an sdreport() directly.
Dimensions use the model's own notation: nspp species, nsex sexes,
nages age bins, nyrs years including the projection, nyrs_hind hindcast
years only, n_flt fleets and n_sel selectivity blocks. n_sel equals
n_flt: fleets sharing a Selectivity_index share one block through the
map, not through a narrower array.
A data frame with one row per parameter and columns internal,
natural, process, meaning and dims.
fit_mod() for the fitted object these names come from.
# The whole table head(parameter_dictionary()) # What is R_log_sd? parameter_dictionary("R_log_sd") # Everything governing selectivity parameter_dictionary(process = "selectivity") # Search the meanings by keyword dict <- parameter_dictionary() dict[grep("catchability", dict$meaning, ignore.case = TRUE), ]# The whole table head(parameter_dictionary()) # What is R_log_sd? parameter_dictionary("R_log_sd") # Everything governing selectivity parameter_dictionary(process = "selectivity") # Search the meanings by keyword dict <- parameter_dictionary() dict[grep("catchability", dict$meaning, ignore.case = TRUE), ]
One row per estimated (fixed-effect) parameter, giving the fleet, species, sex, age, bin, year or slot it occupies.
parameter_index(object)parameter_index(object)
object |
A fitted Rceattle model from |
TMB names each element of obj$par after its parameter block, so a
convergence diagnostic can report that sel_coff_dev is non-identifiable but
not which of its elements.
The mapping is recovered by pushing a tagged parameter vector back through
TMB's own parList(), so it reflects build_map() exactly: parameters
mapped off are absent, and fleets sharing a Selectivity_index or
Catchability_index appear once, as the single parameter they are, with
n_cells recording how many array cells they drive.
Ages are absolute. init_dev holds one deviation per age from minage + 1
upward, since age minage in the first year is recruitment.
Coordinate columns are NA where the axis does not apply to a block. The
linkage and environmental-covariate blocks (beta_linkage, M1_beta, ...)
are indexed by a linkage-table row rather than a model coordinate, so they
hold no coordinates and are reported by element number.
A selectivity slot is named from the fleet's Selectivity: slot 2 of
sel_inf is a descending inflection for the double-logistic family, the
right-tail floor under DoubleNormal, and the age-1 selectivity under
LogisticPM.
Under estimateMode = "Estimate" with any HCR but "NoFishing", object$obj
is the projection object, whose only free parameters are log_Ftarget /
log_Flimit, so the index describes those, not the hindcast.
fit$convergence reads the hindcast index that fit_mod() captured before
the projection remapped the model, and checks it against the vector it is
labelling either way.
A data frame with one row per estimated parameter and columns
par_index (position in obj$par), block, species, fleet, sex,
age, bin, year, slot, n_cells and label.
parameter_dictionary() for what each block means.
Total biomass of each species consumed by its predators, summed over sex and age. For an MSE object the projection is summarized across simulations with a mean and a 95% interval.
plot_b_eaten( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, width = 7, height = 6.5, minyr = NULL, incl_proj = FALSE, mod_cex = 1, alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, maxyr = NULL, lty = 1, incl_mean = FALSE, top_adj = 0.15 )plot_b_eaten( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, width = 7, height = 6.5, minyr = NULL, incl_proj = FALSE, mod_cex = 1, alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, maxyr = NULL, lty = 1, incl_mean = FALSE, top_adj = 0.15 )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
species |
Species to include, as indices ( |
spnames |
Species labels, length |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
lwd |
Line width on the base-graphics scale: the default |
save |
Ignored. Only the time-series plotters write their series to CSV. |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
width, height
|
Saved figure size in inches. |
minyr, maxyr
|
First / last year to plot. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
mod_cex |
Ignored. Base-graphics leftover: legend text size. Use
|
alpha |
Transparency of confidence ribbons and shaded areas, between 0 and 1. |
mod_avg |
TRUE/FALSE |
mse |
|
OM |
if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting? |
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
incl_mean |
Add a horizontal line at the hindcast mean of each series. |
top_adj |
Ignored. Base-graphics leftover; see |
Function that plots the biomass consumed trends as estimated from Rceattle. Returns and saves a figure with the biomass eaten trajectory.
plot_b_eaten_prop( Rceattle, file = NULL, model_names = NULL, line_col = NULL, spnames = NULL, species = NULL, lwd = 3, right_adj = 0, top_adj = 0.15, minyr = NULL, mohns = NULL, width = 7, height = 6.5, incl_proj = FALSE, incl_mean = FALSE, add_ci = FALSE, mod_cex = 1, maxyr = NULL, lty = 1 )plot_b_eaten_prop( Rceattle, file = NULL, model_names = NULL, line_col = NULL, spnames = NULL, species = NULL, lwd = 3, right_adj = 0, top_adj = 0.15, minyr = NULL, mohns = NULL, width = 7, height = 6.5, incl_proj = FALSE, incl_mean = FALSE, add_ci = FALSE, mod_cex = 1, maxyr = NULL, lty = 1 )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
spnames |
Species labels, length |
species |
Species to include, as indices ( |
lwd |
Line width on the base-graphics scale: the default |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
top_adj |
Ignored. Base-graphics leftover; see |
minyr, maxyr
|
First / last year to plot. |
mohns |
Ignored. Formerly annotated the figure with Mohn's rho from
|
width, height
|
Saved figure size in inches. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
incl_mean |
Add a horizontal line at the hindcast mean of each series. |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
mod_cex |
Ignored. Base-graphics leftover: legend text size. Use
|
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
Colour separates predators; line type separates models. Panels are prey species.
Plots the mean minage+ biomass (million mt) and 95\
plot_biomass( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )plot_biomass( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
species |
Species to include, as indices ( |
spnames |
Species labels, length |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
lwd |
Line width on the base-graphics scale: the default |
save |
Write the plotted series to CSV alongside the figure. |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
legend.pos |
Ignored. Base-graphics leftover: legend placement. Use
|
width, height
|
Saved figure size in inches. |
minyr, maxyr
|
First / last year to plot. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
mod_cex |
Ignored. Base-graphics leftover: legend text size. Use
|
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
alpha |
Transparency of confidence ribbons and shaded areas, between 0 and 1. |
mod_avg |
TRUE/FALSE |
mse |
|
OM |
if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting? |
reference |
A model to overlay for comparison, drawn at 1.5x |
ylab |
Y-axis label. |
Returns and saves a figure with the biomass trajectory.
Plots fitted fishery catch: observed points with lognormal 95% intervals and the model-predicted catch, faceted by fishery fleet. For MSE objects the projection period is summarized with 50% / 95% ribbons across simulations.
plot_catch( Rceattle, file = NULL, model_names = NULL, species = NULL, incl_proj = FALSE, width = 7, height = 6.5, error = TRUE, maxyr = NULL, mse = FALSE, fleets = NULL, line_col = NULL, right_adj = 0, top_adj = 1.2, single.plots = FALSE, alpha = 0.4, lwd = 2, ymax = NULL )plot_catch( Rceattle, file = NULL, model_names = NULL, species = NULL, incl_proj = FALSE, width = 7, height = 6.5, error = TRUE, maxyr = NULL, mse = FALSE, fleets = NULL, line_col = NULL, right_adj = 0, top_adj = 1.2, single.plots = FALSE, alpha = 0.4, lwd = 2, ymax = NULL )
Rceattle |
A single |
file |
Optional file stem; if given the figure is written to
|
model_names |
Legend labels for the models. |
species |
Species (indices) to include. Default all. |
incl_proj |
Include projection years. |
width, height
|
Saved figure size (inches). |
error |
Draw observed points and error bars. |
maxyr |
Last year to plot. |
mse |
Is |
fleets |
Fishery fleets to include (indices into the sorted fleet codes). Default all. |
line_col, right_adj, top_adj, single.plots
|
Deprecated base-graphics arguments, retained for back-compatibility and ignored. |
alpha, lwd, ymax
|
Deprecated base-graphics arguments, ignored. |
The predicted line is the MEDIAN, as in plot_index():
catch_hat * exp(-bias_adjust_obs * sd^2 / 2). The catch likelihood is
lognormal for every fishery, so this applies throughout.
A ggplot object.
Plots the fitted survey catchability q by year, faceted by fleet. Every
fleet holding index_data is drawn, a fishery with a CPUE series as much as
a survey.
plot_catchability( Rceattle, file = NULL, model_names = NULL, species = NULL, spnames = NULL, mse = FALSE, minyr = NULL, maxyr = NULL, incl_mean = FALSE, log = FALSE, line_col = NULL, lwd = 3, lty = 1, width = 7, height = 6.5, right_adj = 0, top_adj = 0.05, single.plots = FALSE )plot_catchability( Rceattle, file = NULL, model_names = NULL, species = NULL, spnames = NULL, mse = FALSE, minyr = NULL, maxyr = NULL, incl_mean = FALSE, log = FALSE, line_col = NULL, lwd = 3, lty = 1, width = 7, height = 6.5, right_adj = 0, top_adj = 0.05, single.plots = FALSE )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
species |
Species to include, as indices ( |
spnames |
Species labels, length |
mse |
Is |
minyr, maxyr
|
First / last year to plot. |
incl_mean |
Add a horizontal line at the hindcast mean of each series. |
log |
Plot catchability on the log scale. |
line_col |
Line colours; names, hex, or base-graphics integers. |
lwd |
Line width on the base-graphics scale: the default |
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
width, height
|
Saved figure size in inches. |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
top_adj |
Ignored. Base-graphics leftover; see |
single.plots |
Ignored. Base-graphics leftover: one device per panel. The ggplot facets instead. |
The value plotted is the realized catchability the model scaled the survey by,
whichever route produced it: an estimated or fixed mean, annual deviations
under Time_varying_q, an environmental regression (Catchability = "Environmental"), a q linkage such as rw(1 | Year) or ar1(1 | Year), or
the closed-form value under "Analytical" / "AnalyticalArith". A fleet with
a time-invariant catchability draws a flat line, which is the honest picture
of a constant q rather than an empty panel.
Hindcast years only. The model applies catchability over the hindcast and
does not project it, so the series stops at endyr regardless of the
projection horizon. There is no incl_proj.
line_col and lty separate the models, so overlaying several fits
compares their catchability series panel by panel.
A ggplot object.
data(BS2017SS) fit <- Rceattle::fit_mod(data_list = BS2017SS, msmMode = 0) plot_catchability(fit) plot_catchability(fit, log = TRUE)data(BS2017SS) fit <- Rceattle::fit_mod(data_list = BS2017SS, msmMode = 0) plot_catchability(fit) plot_catchability(fit, log = TRUE)
Diagnostic plots for age / length composition data from a fitted Rceattle
model, drawn with ggplot2 for a consistent look with plot.rceattle_osa().
With the default residual_type = "pearson" three figures are produced per
fleet x composition type:
Pearson residual bubbles by year and bin, faceted by fleet (and,
for joint-sex data, by sex); red = positive, blue = negative, sized by
magnitude. The Pearson residual is
the same form used by residuals.Rceattle(), standardized by the
variance the fleet's own likelihood assumes, so the weight column and any
Dirichlet-multinomial overdispersion are already in the denominator.
Annual composition: observed (shaded area) vs fitted (line) proportion at age / length, one panel per year. Joint-sex data are mirrored (females up, males down).
Aggregated composition: observed vs fitted, counts pooled over the fitted hindcast years. The interval holds 95% of the data the model predicts (not a confidence interval on the mean), so observations outside it indicate misfit. Poor where the expected count is below about 10, and slightly narrow throughout, because it treats the fitted proportions as known rather than estimated from these same data.
The shaded area and fitted line span only the observed bins (they do not
extend past the first/last bin), and bins with zero observed proportion are
retained (only NA bins are dropped), so the curves are not interpolated
across gaps.
plot_comp( Rceattle, file = NULL, model_names = NULL, species = NULL, cex = 3, lwd = 3, right_adj = 0, residual_type = c("pearson", "osa"), add_agg_ci = TRUE, add_agg_n = TRUE )plot_comp( Rceattle, file = NULL, model_names = NULL, species = NULL, cex = 3, lwd = 3, right_adj = 0, residual_type = c("pearson", "osa"), add_agg_ci = TRUE, add_agg_n = TRUE )
Rceattle |
A single fitted |
file |
Optional filename stem; when supplied, each figure is also saved as a PNG. |
model_names |
Unused (kept for back-compatibility). |
species |
Optional species code(s) to plot (matched against the
|
cex |
Unused (kept for back-compatibility). |
lwd |
Width of the fitted-composition line. Default |
right_adj |
Unused (kept for back-compatibility). |
residual_type |
|
add_agg_ci |
Logical. Draw the 95% prediction interval on the aggregated
composition figure. Default |
add_agg_n |
Logical. Annotate the aggregated composition figure with the
input sample size, the effective sample size the likelihood assumed, and
the McAllister-Ianelli effective sample size this fit implies. Default
|
Invisibly, a named list of the ggplot objects. Called for its side
effect of drawing (and optionally saving) the figures.
Plots a timeline of presence/absence (and optionally relative quantity) of
the data sources contributing to an Rceattle model's likelihood, by year and
fleet. Modeled after Stock Synthesis's r4ss::SSplotData().
plot_data( Rceattle, file = NULL, subplots = 1:2, datatypes = "all", fleets = "all", species = "all", ghost = FALSE, fleetcol = "default", width = 7, height = 5, res = 200, ptsize = 10, margins = c(5.1, 2.1, 2.1, 10.1), cex = 2, lwd = 12, maxsize = 1, alphasize = 1, mainTitle = FALSE, cex.main = 1 )plot_data( Rceattle, file = NULL, subplots = 1:2, datatypes = "all", fleets = "all", species = "all", ghost = FALSE, fleetcol = "default", width = 7, height = 5, res = 200, ptsize = 10, margins = c(5.1, 2.1, 2.1, 10.1), cex = 2, lwd = 12, maxsize = 1, alphasize = 1, mainTitle = FALSE, cex.main = 1 )
Rceattle |
Either a single Rceattle model object exported from
|
file |
Path/prefix used to save the figure. If |
subplots, res, ptsize, margins, cex, lwd, maxsize, mainTitle, cex.main
|
Deprecated base-graphics arguments, retained for back-compatibility and
ignored. One faceted figure is drawn; size, resolution and titles come
from the ggplot theme and from |
datatypes |
Either |
fleets |
Either |
species |
Either |
ghost |
Logical. If |
fleetcol |
Either |
width, height
|
Figure dimensions in inches. |
alphasize |
Bubble fill transparency (0-1). |
Years with Year > 0 contribute to the likelihood; rows with Year < 0
(kept for fitting comparison only) are shown when ghost = TRUE. Diet data
uses Year == 0 for the fixed reference stomach composition; those entries
are plotted at the model endyr and labeled per predator species.
Invisibly, a list with typetable, the long data frame underlying
the plot (year, fleet, data type, relative size). Point area is scaled
within each data type: catch in metric tons, 1/SE for indices, sample
size for compositions.
Plots the mean biomass depletion and 95\
plot_depletion( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )plot_depletion( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
species |
Species to include, as indices ( |
spnames |
Species labels, length |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
lwd |
Line width on the base-graphics scale: the default |
save |
Write the plotted series to CSV alongside the figure. |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
legend.pos |
Ignored. Base-graphics leftover: legend placement. Use
|
width, height
|
Saved figure size in inches. |
minyr, maxyr
|
First / last year to plot. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
mod_cex |
Ignored. Base-graphics leftover: legend text size. Use
|
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
alpha |
Transparency of confidence ribbons and shaded areas, between 0 and 1. |
mod_avg |
TRUE/FALSE |
mse |
|
OM |
if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting? |
reference |
A model to overlay for comparison, drawn at 1.5x |
ylab |
Y-axis label. |
Returns and saves a figure with the biomass depletion trajectory.
Deprecated alias for plot_ssb_depletion, which is
the snake_case spelling the rest of the package uses. Please use
plot_ssb_depletion() instead.
plot_depletionSSB(...)plot_depletionSSB(...)
... |
passed unchanged to |
If year == 0, diet data are averaged from suit_styr to suit_endyr If prey_age >= 0 diet data are diet proportion of prey-at-age in predator-at-age If prey_age < 0 diet data are diet proportion of prey-spp in predator-at-age (sum across prey ages) If prey_age < 0 and pred_age < 0, diet data are mean diet proportion of prey-spp in predator-spp (sum across prey ages and take mean across predator ages) If prey_age < 0 and pred_age < -500, diet data are weighted mean diet proportion of prey-spp in predator-spp (sum across prey ages and take weighted mean across predator ages)
plot_diet_comp(Rceattle, file = NULL, species = NULL)plot_diet_comp(Rceattle, file = NULL, species = NULL)
Rceattle |
Single or list of Rceattle model objects exported from |
file |
Path/prefix for the saved figure. |
species |
Species names for legend |
Returns and saves a figure
plot_diet_comp1() is an alias of plot_diet_comp(): it produces the
predator-age x prey-age bubble grids (observed / estimated / Pearson residual)
for each predator-prey-year interaction. It is provided as a named entry point
alongside plot_diet_comp2() (the aggregation-aware line / bar / bubble plots)
for scripts that call both by name.
plot_diet_comp1(Rceattle, file = NULL, species = NULL)plot_diet_comp1(Rceattle, file = NULL, species = NULL)
Rceattle |
Single Rceattle model object exported from |
file |
Optional file-name prefix for saved figures. |
species |
Optional species names for the legend. |
Invisibly returns a list of the printed plot grids (see
plot_diet_comp()).
plot_diet_comp(), plot_diet_comp2()
## Not run: plot_diet_comp1(my_msm_fit) ## End(Not run)## Not run: plot_diet_comp1(my_msm_fit) ## End(Not run)
Diagnostic plots for diet-composition fits that adapt to how each
predator-prey interaction is aggregated (see plot_diet_comp() for the
aggregation conventions):
prey-age aggregated (predator age resolved): line plot of observed vs estimated diet proportion against predator age, with 95% CI ribbons;
predator aggregated (prey age resolved): line plot against prey age;
both aggregated: dodged bar plot of observed vs estimated proportion;
fully disaggregated: predator-age x prey-age bubble grids (observed / estimated / Pearson residual).
The observed proportions, fitted proportions and Pearson residuals come from
the diet data path (quantities$diet_hat / residuals(source = "diet") /
data_list$diet_data) via the internal .diet_plot_data() helper. Observed
95% CI ribbons are a normal approximation to the binomial proportion from
Sample_size. Estimated 95% CI ribbons are drawn only when the sdreport
exposes a diet_hat standard error; the C++ template REPORT()s but does
not ADREPORT() diet_hat, so the estimated ribbon is unavailable unless the
template is changed to ADREPORT(diet_hat) (the code path is retained so it
activates automatically if that ever happens, or when sdrep is NULL).
plot_diet_comp2(Rceattle, file = NULL, species = NULL)plot_diet_comp2(Rceattle, file = NULL, species = NULL)
Rceattle |
A single Rceattle model object. |
file |
Optional file-name prefix for saved figures. |
species |
Optional species names for the legend. |
Invisibly returns a list of the printed plot objects.
plot_diet_comp(), plot_diet_comp1()
## Not run: plot_diet_comp2(my_msm_fit) ## End(Not run)## Not run: plot_diet_comp2(my_msm_fit) ## End(Not run)
Plots the mean exploitable biomass (million mt) and 95\
plot_exploitable_biomass( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )plot_exploitable_biomass( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
species |
Species to include, as indices ( |
spnames |
Species labels, length |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
lwd |
Line width on the base-graphics scale: the default |
save |
Write the plotted series to CSV alongside the figure. |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
legend.pos |
Ignored. Base-graphics leftover: legend placement. Use
|
width, height
|
Saved figure size in inches. |
minyr, maxyr
|
First / last year to plot. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
mod_cex |
Ignored. Base-graphics leftover: legend text size. Use
|
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
alpha |
Transparency of confidence ribbons and shaded areas, between 0 and 1. |
mod_avg |
TRUE/FALSE |
mse |
|
OM |
if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting? |
reference |
A model to overlay for comparison, drawn at 1.5x |
ylab |
Y-axis label. |
Returns and saves a figure with the exploitable biomass trajectory.
Fishing mortality over time, one panel per species, with the Ftarget (blue) and Flimit (red) reference points drawn per panel.
plot_f( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )plot_f( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
species |
Species to include, as indices ( |
spnames |
Species labels, length |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
lwd |
Line width on the base-graphics scale: the default |
save |
Write the plotted series to CSV alongside the figure. |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
legend.pos |
Ignored. Base-graphics leftover: legend placement. Use
|
width, height
|
Saved figure size in inches. |
minyr, maxyr
|
First / last year to plot. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
mod_cex |
Ignored. Base-graphics leftover: legend text size. Use
|
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
alpha |
Transparency of confidence ribbons and shaded areas, between 0 and 1. |
mod_avg |
TRUE/FALSE |
mse |
|
OM |
if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting? |
reference |
A model to overlay for comparison, drawn at 1.5x |
ylab |
Y-axis label. |
Returns and saves a figure with the fishing mortality trajectory.
Function to plot the functional form estimated or specified by Rceattle
plot_form(params = NULL, pred = 1, pred_age = 1, prey = 1, msmMode = 3)plot_form(params = NULL, pred = 1, pred_age = 1, prey = 1, msmMode = 3)
params |
Parameter list object from |
pred |
Predator index |
pred_age |
Predator age |
prey |
Prey index |
msmMode |
Multispecies mode integer specifying functional form |
Plots fitted index series: observed points with 95% observation intervals and
the model-predicted index, faceted by fleet. Every fleet holding
index_data is drawn, a fishery with a CPUE series as much as a survey.
plot_index( Rceattle, file = NULL, model_names = NULL, species = NULL, incl_proj = FALSE, width = 7, height = 6.5, error = TRUE, log = FALSE, line_col = NULL, right_adj = 0, top_adj = 0.05, single.plots = FALSE )plot_index( Rceattle, file = NULL, model_names = NULL, species = NULL, incl_proj = FALSE, width = 7, height = 6.5, error = TRUE, log = FALSE, line_col = NULL, right_adj = 0, top_adj = 0.05, single.plots = FALSE )
Rceattle |
A single |
file |
Optional file stem; if given the figure is written to
|
model_names |
Legend labels for the models. |
species |
Species (indices) to include. Default all. |
incl_proj |
Include projection years. |
width, height
|
Saved figure size (inches). |
error |
Draw observed points and error bars. |
log |
Plot the index on the log scale. |
line_col, right_adj, top_adj, single.plots
|
Deprecated base-graphics arguments, retained for back-compatibility and ignored. |
The interval follows the fleet's Index_distribution: lognormal quantiles on
a "Lognormal" fleet, and observed +/- 1.96 sd truncated at zero on a
natural-scale one ("MVN", "MVNORM", "Normal", "TruncatedNormal"),
whose sd is absolute and in the units of the index.
The predicted line is the MEDIAN of the fitted observation distribution,
index_hat * exp(-bias_adjust_obs * sd^2 / 2), which is where the lognormal
likelihood is centred, so about half the observations should fall below it.
It equals the reported index_hat where bias_adjust_obs = FALSE. A
natural-scale fleet has no such offset and is drawn unchanged.
A ggplot object.
Plots survey index residuals by year, faceted by survey fleet
(residual_type = "pearson", the default), or one-step-ahead (OSA) residual
diagnostics for a single fit (residual_type = "osa", via osa_residuals() /
plot.rceattle_osa()).
plot_index_residual( Rceattle, file = NULL, model_names = NULL, species = NULL, width = 7, height = 6.5, residual_type = c("pearson", "osa"), line_col = NULL, right_adj = 0, top_adj = 0.05, incl_proj = FALSE, single.plots = FALSE )plot_index_residual( Rceattle, file = NULL, model_names = NULL, species = NULL, width = 7, height = 6.5, residual_type = c("pearson", "osa"), line_col = NULL, right_adj = 0, top_adj = 0.05, incl_proj = FALSE, single.plots = FALSE )
Rceattle |
A single |
file |
Optional file stem; if given the figure is written to
|
model_names |
Legend labels for the models. |
species |
Species (indices) to include. Default all. |
width, height
|
Saved figure size (inches). |
residual_type |
|
line_col, right_adj, top_adj, single.plots
|
Deprecated base-graphics arguments, retained for back-compatibility and ignored. |
incl_proj |
Include projection years. |
The residual is observed minus predicted, standardized by the sd the row was
fitted with – the same quantity residuals.Rceattle() returns for
type = "pearson". On a log-scale fleet it is measured against the
likelihood's centre, log(hat) - bias_adjust_obs * sd^2 / 2; on a
natural-scale fleet ("MVN", "MVNORM", "Normal",
"TruncatedNormal" in Index_distribution), whose sd is absolute, it is
(obs - hat) / sd. A covariance fleet ("MVN", "MVNORM") takes that sd
from sqrt(diag(index_cov)), which its likelihood actually scores, so the
residual is marginal rather than whitened. A positive residual means the
survey saw more than the
model predicted. The y scale stays free per fleet, since residual spread
differs by fleet.
A ggplot object.
Deprecated alias for plot_index_residual,
which is the snake_case spelling the rest of the package uses. Please
use plot_index_residual() instead.
plot_indexresidual(...)plot_indexresidual(...)
... |
passed unchanged to |
Function that plots the natural mortality at age (M1 + M2) as estimated from Rceattle. Returns and saves a figure with the M-at-age trajectory.
plot_m_at_age( Rceattle, file = NULL, age = 1, model_names = NULL, line_col = NULL, spnames = NULL, species = NULL, lwd = 3, lty = 1, right_adj = 0, minyr = NULL, width = 7, height = 6.5, incl_proj = FALSE, incl_mean = FALSE, add_ci = FALSE, maxyr = NULL, top_adj = 0.15 )plot_m_at_age( Rceattle, file = NULL, age = 1, model_names = NULL, line_col = NULL, spnames = NULL, species = NULL, lwd = 3, lty = 1, right_adj = 0, minyr = NULL, width = 7, height = 6.5, incl_proj = FALSE, incl_mean = FALSE, add_ci = FALSE, maxyr = NULL, top_adj = 0.15 )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
age |
Age to plot M at, on the species' own age scale (so |
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
spnames |
Species labels, length |
species |
Species to include, as indices ( |
lwd |
Line width on the base-graphics scale: the default |
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
minyr, maxyr
|
First / last year to plot. |
width, height
|
Saved figure size in inches. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
incl_mean |
Add a horizontal line at the hindcast mean of each series. |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
top_adj |
Ignored. Base-graphics leftover; see |
Colour separates the models; line type separates the sexes. A
sex-combined model has one sex, so a varying lty has nothing to key on
and warns.
Share of the predation mortality (M2) on each prey age that is attributable to each predator species. The shares sum to 1 across predators for every prey age and year; a year with no predation on that age leaves them undefined and draws nothing.
plot_m2_at_age_prop( Rceattle, file = NULL, age = 1, model_names = NULL, line_col = NULL, spnames = NULL, species = NULL, lwd = 3, right_adj = 0, top_adj = 0.15, minyr = NULL, width = 7, height = 6.5, incl_proj = FALSE, incl_mean = FALSE, add_ci = FALSE, maxyr = NULL, lty = 1 )plot_m2_at_age_prop( Rceattle, file = NULL, age = 1, model_names = NULL, line_col = NULL, spnames = NULL, species = NULL, lwd = 3, right_adj = 0, top_adj = 0.15, minyr = NULL, width = 7, height = 6.5, incl_proj = FALSE, incl_mean = FALSE, add_ci = FALSE, maxyr = NULL, lty = 1 )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
age |
Prey age to plot the M2 proportions at, on the prey species' own age scale rather than as an age-bin index. A prey species that has no such age is dropped, with a warning. |
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
spnames |
Species labels, length |
species |
Species to include, as indices ( |
lwd |
Line width on the base-graphics scale: the default |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
top_adj |
Ignored. Base-graphics leftover; see |
minyr, maxyr
|
First / last year to plot. |
width, height
|
Saved figure size in inches. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
incl_mean |
Add a horizontal line at the hindcast mean of each series. |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
Colour separates predators; line type separates models. Panels are prey species (and sex, where the prey is sexed).
Function that plots the maturity of each species
plot_maturity( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, width = 4, height = 5.5, lwd = 3 )plot_maturity( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, width = 4, height = 5.5, lwd = 3 )
Rceattle |
Single or list of Rceattle model objects exported from |
file |
Path/prefix for the saved figure. |
model_names |
Names of models to be used in legend |
line_col, lwd
|
Deprecated base-graphics arguments, retained for back-compatibility and ignored; colour comes from the shared model palette and the line width is fixed. |
species |
Species labels for the facet strips, length |
width |
Figure width in inches |
height |
Figure height in inches |
Mortality-at-age over the hindcast for one model: predation
mortality (M2, the default) or residual natural mortality (M1). One
component at a time, never their sum, plot_m_at_age() draws total M
(M1 + M2) as a time series.
plot_mortality( Rceattle, file = NULL, incl_proj = FALSE, zlim = NULL, type = "lines", width = 8, height = 5.5, title = NULL, log = FALSE, minyr = NULL, theta = 155, species = NULL, maxage = NULL, title_cex = 10, M2 = TRUE )plot_mortality( Rceattle, file = NULL, incl_proj = FALSE, zlim = NULL, type = "lines", width = 8, height = 5.5, title = NULL, log = FALSE, minyr = NULL, theta = 155, species = NULL, maxage = NULL, title_cex = 10, M2 = TRUE )
Rceattle |
A single |
file |
Path/prefix for the saved figure. |
incl_proj |
Include the projection years (TRUE/FALSE) |
zlim |
Ignored. Base-graphics leftover: the fill range of the tile
plot. Use |
type |
|
width |
Plot width when saved "inches" |
height |
Plot height when saved "inches" |
title |
Additional title to add. Will also add species names if not NULL |
log |
TRUE/FALSE plot the series on a log scale |
minyr |
First year to plot |
theta |
Ignored. Base-graphics leftover: viewing angle of a |
species |
Species to plot. Plots all if null. |
maxage |
Oldest age to draw, on the species' own age scale rather than
as a count of age bins. |
title_cex |
Ignored. Base-graphics leftover: title font size. Use
|
M2 |
Draw predation mortality M2 (TRUE, the default) or residual natural mortality M1 (FALSE). Neither is the sum of the two. |
A ggplot.
Draws each negative log-likelihood component against the
profiled parameter, with the total overlaid, in the style of
r4ss::SSplotProfile(). Where the curves disagree about which value they
prefer, the data sources are in conflict, which is what the total on its
own cannot show.
plot_profile( Rceattle_profile, model_names = NULL, weighted = TRUE, relative = c("own", "scaled", "minimum", "none"), minfraction = 0.01, add_cutoff = FALSE, cutoff = 1.92, xlab = NULL, ylab = NULL, line_col = NULL, lwd = 3, lty = 1, file = NULL, width = 7, height = 5 )plot_profile( Rceattle_profile, model_names = NULL, weighted = TRUE, relative = c("own", "scaled", "minimum", "none"), minfraction = 0.01, add_cutoff = FALSE, cutoff = 1.92, xlab = NULL, ylab = NULL, line_col = NULL, lwd = 3, lty = 1, file = NULL, width = 7, height = 5 )
Rceattle_profile |
A single |
model_names |
Legend labels for the models. |
weighted, relative, minfraction
|
Passed to |
add_cutoff |
Draw a horizontal line at |
cutoff |
Height of that line. Default |
xlab |
X-axis label. Default names the profiled parameter and cell in the units the grid is in. |
ylab |
Y-axis label. Default follows |
line_col |
Line colours; names, hex, or base-graphics integers. |
lwd |
Line width on the base-graphics scale: the default |
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
file |
Optional file stem; the figure is written to
|
width, height
|
Saved figure size in inches. |
Read the figure 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 that minimum, so the
spread of the points along the x axis is the disagreement: components whose
points sit together support the same value, and one whose point sits far from
the total's is pulling against the rest. Where one component dwarfs the
others it sets the y axis and the rest flatten onto the bottom;
relative = "scaled" puts every curve on 0 to 1 so the minima stay
comparable, and relative = "minimum" re-zeroes every series at the total's
minimum, showing what each gives up by moving away from the fitted value.
profile_components() documents all of them, and the magnitude "scaled"
discards.
The total is drawn solid and black at 1.6 times lwd, and kept out of the
colour legend, so it stays the reference line whatever the components are
styled as; line_col, lwd and lty therefore apply to the
components. Series are ordered, in the legend and the palette, by how
much each moves over the grid. Under joint = "multiply" or "add" a dotted
vertical line marks the fitted model (a multiplier of 1, an offset of 0).
Non-converged grid points leave a gap.
A ggplot object. Its $data is the plotted frame, so the numbers
behind the figure can be read back off it.
Taylor, I.G., et al. (2021) Beyond visualizing catch-at-age models: Lessons learned from the r4ss package about software to support stock assessments. Fisheries Research 239: 105924.
profile_components() for the same numbers as a data frame,
profile.Rceattle() to run the profile, print.Rceattle_profile() for
whether the grid brackets the minimum.
data(BS2017SS) ss_run <- fit_mod(data_list = BS2017SS, inits = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, msmMode = 0, avgnMode = 0, phase = FALSE, verbose = 0) # Profile M for species 1 and see which data sources disagree about it prof <- profile(ss_run, param = "M1", slots = list(c(1, 1, 1)), values = list(seq(0.2, 0.5, by = 0.05))) plot_profile(prof, xlab = "M at age 1") # Two model configurations side by side plot_profile(list(prof, prof), model_names = c("Base", "Alternative"))data(BS2017SS) ss_run <- fit_mod(data_list = BS2017SS, inits = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, msmMode = 0, avgnMode = 0, phase = FALSE, verbose = 0) # Profile M for species 1 and see which data sources disagree about it prof <- profile(ss_run, param = "M1", slots = list(c(1, 1, 1)), values = list(seq(0.2, 0.5, by = 0.05))) plot_profile(prof, xlab = "M at age 1") # Two model configurations side by side plot_profile(list(prof, prof), model_names = c("Base", "Alternative"))
Population-level consumption for ages minage+: the individual
annual ration (kg/yr) multiplied by average numbers-at-age and summed over
age, in million mt. This is how the model forms total consumption
(avgN_at_age * ration, predation.hpp), so it is the consumption that
generates the predation mortality in plot_m2_at_age_prop() and the
biomass in plot_b_eaten(), plus the other-food term.
plot_ration( Rceattle, file = NULL, minage = 1, model_names = NULL, line_col = NULL, spnames = NULL, species = NULL, lwd = 3, lty = 1, right_adj = 0, minyr = NULL, width = 7, height = 6.5, incl_proj = FALSE, incl_mean = FALSE, add_ci = FALSE, maxyr = NULL, top_adj = 0.15 )plot_ration( Rceattle, file = NULL, minage = 1, model_names = NULL, line_col = NULL, spnames = NULL, species = NULL, lwd = 3, lty = 1, right_adj = 0, minyr = NULL, width = 7, height = 6.5, incl_proj = FALSE, incl_mean = FALSE, add_ci = FALSE, maxyr = NULL, top_adj = 0.15 )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
minage |
Youngest age to sum consumption over, so the figure is
"age |
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
spnames |
Species labels, length |
species |
Species to include, as indices ( |
lwd |
Line width on the base-graphics scale: the default |
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
minyr, maxyr
|
First / last year to plot. |
width, height
|
Saved figure size in inches. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
incl_mean |
Add a horizontal line at the hindcast mean of each series. |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
top_adj |
Ignored. Base-graphics leftover; see |
Colour separates the models; line type separates the sexes.
Plots the mean minage recruitment (millions) and 95\
plot_recruitment( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )plot_recruitment( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
species |
Species to include, as indices ( |
spnames |
Species labels, length |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
lwd |
Line width on the base-graphics scale: the default |
save |
Write the plotted series to CSV alongside the figure. |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
legend.pos |
Ignored. Base-graphics leftover: legend placement. Use
|
width, height
|
Saved figure size in inches. |
minyr, maxyr
|
First / last year to plot. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
mod_cex |
Ignored. Base-graphics leftover: legend text size. Use
|
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
alpha |
Transparency of confidence ribbons and shaded areas, between 0 and 1. |
mod_avg |
TRUE/FALSE |
mse |
|
OM |
if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting? |
reference |
A model to overlay for comparison, drawn at 1.5x |
ylab |
Y-axis label. |
Returns and saves a figure with the recruitment trajectory.
Selectivity over the hindcast, one panel per fleet. Each fleet
is drawn on the dimension it was estimated on: age for an age-based fleet,
length bin for a length-based one (Selectivity_dimension). A model mixing
the two gets one figure per dimension.
plot_selectivity( Rceattle, file = NULL, model_names = NULL, line_col = NULL, width = 7, height = 6.5, species = NULL, lwd = 3, spnames = NULL, lty = 1, minyr = NULL, maxyr = NULL, alpha = 0.25, colour_by = c("auto", "year", "model"), add_ci = FALSE )plot_selectivity( Rceattle, file = NULL, model_names = NULL, line_col = NULL, width = 7, height = 6.5, species = NULL, lwd = 3, spnames = NULL, lty = 1, minyr = NULL, maxyr = NULL, alpha = 0.25, colour_by = c("auto", "year", "model"), add_ci = FALSE )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
width, height
|
Saved figure size in inches. |
species |
Species to include, as indices ( |
lwd |
Line width on the base-graphics scale: the default |
spnames |
Species labels, length |
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
minyr, maxyr
|
First / last year to plot. |
alpha |
Transparency of the faintest year when the fan is drawn by
transparency, i.e. under |
colour_by |
What colour separates: |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
A ggplot, or for a model mixing age- and length-based fleets a
named list of them, one per dimension.
With one model, colour is the year, so time-varying selectivity reads as a
fan and a time-invariant fleet collapses to a single line. With several
models, colour separates the models and the year fan moves to transparency,
faintest at the earliest year drawn. The transparency scale spans the years
shown across all models, so the same year is the same shade everywhere and a
short retrospective peel stops short of solid. colour_by overrides the
choice either way, and alpha sets the faintest end.
Line type separates the sexes, and lty supplies its values. Panels are
fleets, so spnames does not label anything here, it only lets species
select by name.
add_ci = TRUE draws exp(log(sel) +/- 1.96 * sd), so the band is positive
and right-skewed. It needs a fit run with fit_control(selectivity_se = TRUE).
Only estimated, age-based fleets hold one. A length-based fleet is drawn on
sel_at_length, which is what was fitted and holds no error; a
Selectivity = "Fixed" fleet estimates nothing; and no fleet gets a band
below its first selected bin (Bin_first_selected, a 1-based bin ordinal,
not an absolute age), where selectivity is 0 by construction. A
fleet mirroring another's Selectivity_index has no errors of its own and
borrows its lead's, but only where the two curves agree, data_check() only
warns when a shared group differs in a shaping column such as Sel_norm_bin.
Every year drawn gets its own band, so a time-varying fleet is dense. Pair it
with minyr / maxyr on a single year, or use it on a time-invariant fleet.
The interval is relative to the normalization anchor, so quote the anchor
with it. Selectivity is identified only up to a scalar, jointly with F for a
fishery and q for a survey, so Sel_norm_bin fixes the level rather than
measuring it: the bin it pins has a standard error of exactly 0 and the band
widens away from it. On a penalized fit (random_sel = FALSE) the band is also
conditional on the smoothing, and it is marginal rather than joint. See
vignette("model-options-and-functionality") for both, and for the
estimateMode that determines whether the fit reports an error at all.
Overlays terminal-year fishery selectivity-at-age against input maturity-at-age, faceted by species. Useful for debugging SPR-based reference points (the two curves drive spawning-potential ratio).
plot_selectivity_vs_maturity( Rceattle, file = NULL, model_names = NULL, line_col = NULL, width = 7, height = 6.5, species = NULL, lwd = 3 )plot_selectivity_vs_maturity( Rceattle, file = NULL, model_names = NULL, line_col = NULL, width = 7, height = 6.5, species = NULL, lwd = 3 )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names, line_col, lwd
|
Deprecated base-graphics arguments, retained for back-compatibility and ignored. |
width, height
|
Saved figure size (inches). |
species |
Species names for the facet labels. Default: model species names. |
A ggplot object.
Plots the mean SSB (million mt) and 95\
plot_ssb( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )plot_ssb( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
species |
Species to include, as indices ( |
spnames |
Species labels, length |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
lwd |
Line width on the base-graphics scale: the default |
save |
Write the plotted series to CSV alongside the figure. |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
legend.pos |
Ignored. Base-graphics leftover: legend placement. Use
|
width, height
|
Saved figure size in inches. |
minyr, maxyr
|
First / last year to plot. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
mod_cex |
Ignored. Base-graphics leftover: legend text size. Use
|
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
alpha |
Transparency of confidence ribbons and shaded areas, between 0 and 1. |
mod_avg |
TRUE/FALSE |
mse |
|
OM |
if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting? |
reference |
A model to overlay for comparison, drawn at 1.5x |
ylab |
Y-axis label. |
Returns and saves a figure with the SSB trajectory.
Plots the mean SSB depletion and 95\ Depletion reference lines for Ptarget and Plimit are drawn in blue and red respectively.
plot_ssb_depletion( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )plot_ssb_depletion( Rceattle, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, right_adj = 0, legend.pos = "topright", width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mod_avg = rep(FALSE, length(Rceattle)), mse = FALSE, OM = TRUE, reference = NULL, ylab = NULL )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
species |
Species to include, as indices ( |
spnames |
Species labels, length |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
lwd |
Line width on the base-graphics scale: the default |
save |
Write the plotted series to CSV alongside the figure. |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
legend.pos |
Ignored. Base-graphics leftover: legend placement. Use
|
width, height
|
Saved figure size in inches. |
minyr, maxyr
|
First / last year to plot. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
mod_cex |
Ignored. Base-graphics leftover: legend text size. Use
|
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
alpha |
Transparency of confidence ribbons and shaded areas, between 0 and 1. |
mod_avg |
TRUE/FALSE |
mse |
|
OM |
if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting? |
reference |
A model to overlay for comparison, drawn at 1.5x |
ylab |
Y-axis label. |
The denominator differs by configuration, so say which one a figure
uses. DynamicHCR = TRUE gives that year's DynamicSB0. Otherwise it is
static SB0, except under HCR = 0 with msmMode > 0, where it is female
SSB in the last projection year – which approximates multispecies SB0
only once projyr is far enough out to equilibrate. An msmMode = 0 fit
and an msmMode = 1, HCR = 0 fit drawn on one axis are therefore two
different ratios.
Returns and saves a figure with the SSB depletion trajectory.
report_tables(), which states the same multispecies denominator.
Plots the stock-recruit relationship estimated by Rceattle:
spawning stock biomass (x) against recruitment (y) as points, with the
fitted stock-recruit curve (mean recruitment, Beverton-Holt, or Ricker)
overlaid, faceted by species. A 95% normal data ellipse of the SSB-R
cloud is added when add_ci = TRUE.
plot_stock_recruit( Rceattle, file = NULL, model_names = NULL, line_col = NULL, width = 7, height = 6.5, species = NULL, spnames = NULL, lwd = 3, lty = 1, incl_proj = FALSE, plot_env = FALSE, mod_cex = 1, add_ci = TRUE )plot_stock_recruit( Rceattle, file = NULL, model_names = NULL, line_col = NULL, width = 7, height = 6.5, species = NULL, spnames = NULL, lwd = 3, lty = 1, incl_proj = FALSE, plot_env = FALSE, mod_cex = 1, add_ci = TRUE )
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
line_col, lwd, lty, plot_env, mod_cex
|
Deprecated base-graphics arguments, retained for back-compatibility and ignored. |
width, height
|
Saved figure size (inches). |
species |
Species (indices) to include. Default all. |
spnames |
Species names for the facet labels. |
incl_proj |
Currently unused (kept for back-compatibility). |
add_ci |
Add a 95% normal data ellipse of the SSB-R points. |
A ggplot object.
Function that plots the time-series (SSB/B/R/Depletion) 95% CI trends as estimated from Rceattle
plot_timeseries( Rceattle, output = "biomass", ylab = NULL, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, legend.pos = "topright", right_adj = 0, width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mse = FALSE, OM = TRUE, reference = NULL, zero_y = FALSE, ref_lines = NULL, suffix = NULL, mod_avg = rep(FALSE, length(Rceattle)) )plot_timeseries( Rceattle, output = "biomass", ylab = NULL, file = NULL, model_names = NULL, line_col = NULL, species = NULL, spnames = NULL, add_ci = FALSE, lwd = 3, save = FALSE, legend.pos = "topright", right_adj = 0, width = 7, height = 6.5, minyr = NULL, maxyr = NULL, incl_proj = FALSE, mod_cex = 1, lty = rep(1, length(Rceattle)), alpha = 0.4, mse = FALSE, OM = TRUE, reference = NULL, zero_y = FALSE, ref_lines = NULL, suffix = NULL, mod_avg = rep(FALSE, length(Rceattle)) )
Rceattle |
A single |
output |
derived quantity of interest: recruitment, biomass, ssb, depletion, or ssb_depletion. Uses same name as ".cpp" file. |
ylab |
Y-axis label. |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
line_col |
Line colours; names, hex, or base-graphics integers. |
species |
Species to include, as indices ( |
spnames |
Species labels, length |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
lwd |
Line width on the base-graphics scale: the default |
save |
Write the plotted series to CSV alongside the figure. |
legend.pos |
Ignored. Base-graphics leftover: legend placement. Use
|
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
width, height
|
Saved figure size in inches. |
minyr, maxyr
|
First / last year to plot. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
mod_cex |
Ignored. Base-graphics leftover: legend text size. Use
|
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
alpha |
Transparency of confidence ribbons and shaded areas, between 0 and 1. |
mse |
|
OM |
if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting? |
reference |
A model to overlay for comparison, drawn at 1.5x |
zero_y |
Anchor the y-axis at zero. TRUE for the absolute series (biomass, SSB, recruitment), where a truncated axis exaggerates change; FALSE for the depletions, which are already on a relative scale. |
ref_lines |
Internal. |
suffix |
Internal. Overrides the |
mod_avg |
TRUE/FALSE |
Returns and saves a figure with the population trajectory.
The model holds numbers-at-age in thousands and weight-at-age in
kg, so every biomass series (biomass, ssb, exploitable_biomass)
comes out of the model in mt and recruitment comes out in thousands of
fish. For display these are divided by 1e6 (million mt) and 1e3 (millions
of recruits) respectively; depletion is a ratio and is not rescaled. Supply
the model's inputs on that convention, catch and index in mt, weight-at-age
in kg, or the axis labels will not describe what is plotted.
add_ci = TRUE draws a 95% interval. Every strictly positive series takes it
on the log scale as exp(log(x) +/- qnorm(0.975) * sd_log). These quantities are
built multiplicatively, so log(x) is close to linear in the estimated
parameters where x is exponential in them: the interval is both a better
linearization and right-skewed, and it cannot cross zero the way a symmetric
natural-scale interval does for weak year classes and depleted stocks.
sd_log comes from the model's own log_biomass / log_ssb / log_R where
those are reported, and is otherwise recovered as sd(x) / x, the delta
method's own identity, which matches the reported values to machine
precision. That covers exploitable_biomass and the two depletions, which
cannot be reported on the log scale (exploitable_biomass is identically 0
without projection F), and models fit before the log_* series existed. A
non-positive or unreported value keeps the symmetric interval.
Thin S3 dispatcher around the package's existing plot_*() functions
so that plot(fit) works the way users expect. Pick the panel with
what; everything in ... is forwarded to the underlying function.
## S3 method for class 'Rceattle' plot(x, what = "biomass", ...)## S3 method for class 'Rceattle' plot(x, what = "biomass", ...)
x |
An object of class |
what |
Character. One of |
... |
Passed to the underlying plotting function. |
Invisibly returns NULL. Called for the side effect of
producing a plot.
Diagnostic plots for an rceattle_osa object (from osa_residuals()),
following the recommendations of Stewart and Monnahan (2025) and the styling
of the NOAA-AFSC afscOSA package. Under a correctly specified model OSA
residuals are iid standard normal, so the headline diagnostic is statistical
(the Q-Q plot with its annotated SDNR / tail statistics).
Up to two separate figures are drawn, depending on which data are present:
Aggregate (index / catch): a Q-Q panel faceted by data source.
These series have no age/length bin, so no bubble plots are drawn.
Composition (comp / caal): a Q-Q panel, a signed OSA-residual
bubble panel, and a signed Pearson-residual bubble panel (the Pearson
residuals held on the rceattle_osa object). By default age-based bins
(age composition and conditional age-at-length) are shown in the left
column and length-based bins in the right column, each with its own bin
axis; set combine = FALSE to draw the age and length composition as two
separate figures instead (useful when a model has many fleets/species).
Panel headers use the fleet name from fleet_control. Process residuals
(from process_residuals()) are drawn as a Q-Q panel plus a
residual-by-year panel.
## S3 method for class 'rceattle_osa' plot( x, source = "all", species = NULL, combine = TRUE, add_sdnr_ci = TRUE, add_qq_quantiles = TRUE, ... )## S3 method for class 'rceattle_osa' plot( x, source = "all", species = NULL, combine = TRUE, add_sdnr_ci = TRUE, add_qq_quantiles = TRUE, ... )
x |
An |
source |
Data source(s) to plot: any of |
species |
Optional species code(s) to include (matched against the
|
combine |
Logical. When |
add_sdnr_ci |
Logical. Show the chi-square null interval beside the SDNR
annotation on each Q-Q panel. Default |
add_qq_quantiles |
Logical. Annotate each Q-Q panel with the tail order
statistics and their exact null intervals. Default |
... |
Unused. |
Invisibly, a named list of the assembled ggplot / cowplot
objects (some of aggregate, composition / composition_age /
composition_length, and process). Called for its side effect of drawing
the plot(s).
Stewart, I.J., and Monnahan, C.C. 2025. Can. J. Fish. Aquat. Sci. 82:1-13.
osa_residuals(), osa_diagnostics()
Shorthand for plot_profile(): draws the likelihood components
against the profiled parameter, with the total overlaid.
## S3 method for class 'Rceattle_profile' plot(x, ...)## S3 method for class 'Rceattle_profile' plot(x, ...)
x |
An |
... |
Passed to |
A ggplot object.
Provides a compact summary so that auto-printing inside R Markdown / knitr / RStudio does not recurse into the (very deep) data and TMB objects stored on the fit. Only structural metadata, convergence status, headline derived quantities, and the package / TMB-DLL versions used to produce the fit are printed.
## S3 method for class 'Rceattle' print(x, ...)## S3 method for class 'Rceattle' print(x, ...)
x |
An object of class |
... |
Currently unused. |
For operational use, the package version line is meant to make it
obvious which version of Rceattle produced an archived fit so that
results can be reproduced even if main has moved on. Tag a
release (devtools::install_github("afsc-assessments/[email protected]"),
bare version, no leading v)
and the same version string will reappear here on a fresh run.
The input x, invisibly.
Shows the model specification as an indented tree, dimensions, fleets and
their selectivity / catchability forms, configured processes, active
linkages, and any attached model_config(), rather than dumping the full
data list.
## S3 method for class 'Rceattle_data' print(x, config = TRUE, ...) ## S3 method for class 'Rceattle_data' summary(object, config = FALSE, ...)## S3 method for class 'Rceattle_data' print(x, config = TRUE, ...) ## S3 method for class 'Rceattle_data' summary(object, config = FALSE, ...)
x |
An |
config |
Show the attached |
... |
Currently unused. |
object |
An |
print() includes the configuration block; summary() omits it and reports
the data structure alone. Either can be overridden with config.
x, invisibly.
Reports what the run was for: how many random starts reached the best optimum found. The objective values alone cannot say that, non-converged starts are dropped before the result is returned, so the count of returned fits is not the count attempted.
## S3 method for class 'Rceattle_jitter' print(x, tol = 0.01, ...)## S3 method for class 'Rceattle_jitter' print(x, tol = 0.01, ...)
x |
A |
tol |
Objective units within which a start counts as reaching the same
optimum. Default |
... |
Currently unused. |
x, invisibly.
Says what the summary holds. The object is deliberately ragged, per-species, per-fleet and whole-system metrics have different shapes and cannot share one frame, so it reports the blocks and their dimensions rather than printing them end to end.
## S3 method for class 'Rceattle_mse_summary' print(x, ...)## S3 method for class 'Rceattle_mse_summary' print(x, ...)
x |
An |
... |
Currently unused. |
x, invisibly.
Reports whether the grid actually brackets the minimum. A profile whose lowest point is its first or last grid value has not found the optimum, it has run out of grid, and the curve drawn from it understates how far the parameter can move. That is the failure the numbers alone hide, since a partial profile plots as a perfectly ordinary line.
## S3 method for class 'Rceattle_profile' print(x, cutoff = 1.92, ...)## S3 method for class 'Rceattle_profile' print(x, cutoff = 1.92, ...)
x |
A |
cutoff |
Objective units above the minimum that bound the reported
interval. Default |
... |
Currently unused. |
For a one-dimensional profile the interval reported is the usual
profile-likelihood one: the grid values within cutoff of the minimum, where
the default 1.92 is . It is read off the grid, so it is
no finer than the spacing of values, and it is reported as open on either
side the grid does not close. It is also referenced to the best GRID point
rather than to the unconstrained MLE, which the object does not hold: the
grid minimum sits at or above the MLE, so the interval errs wide. And it is
reported as a range, so a profile with a second basin, or a failed point
inside the range, is called out as not contiguous rather than left to read
as one interval. No interval is given for a cross-profile over
two or more cells, the cutoff would be and the region
is not an interval.
Under random_rec = TRUE the objective is the Laplace-approximated marginal
likelihood, so this is a profile of that, with the usual caveat that the
approximation is what is being profiled.
x, invisibly.
Print method for a set of assessment reporting tables
## S3 method for class 'rceattle_report' print(x, ...)## S3 method for class 'rceattle_report' print(x, ...)
x |
An |
... |
Currently unused. |
x, invisibly.
Reports Mohn's rho against a reference band rather than as a
bare number. The default band is +/- 0.2 on SSB, the rule of thumb
vignette("model-diagnostics") states; Hurtado-Ferro et al. (2015) give the
asymmetric, life-history-dependent alternatives (-0.15 to 0.20 for
long-lived, -0.22 to 0.30 for short-lived), which is why the band is an
argument rather than a constant.
Only the terminal-year peel (Forecast year 0) is judged. The forecast-skill
rows are reported for information: a rho computed over a forecast horizon is
not the quantity the +/- 0.2 rule was calibrated on.
## S3 method for class 'Rceattle_retro' print(x, band = 0.2, ...)## S3 method for class 'Rceattle_retro' print(x, band = 0.2, ...)
x |
A |
band |
Symmetric reference band for Mohn's rho. Default |
... |
Currently unused. |
x, invisibly.
Hurtado-Ferro, F., et al. 2015. Looking in the rear-view mirror: bias and retrospective patterns in integrated, age-structured stock assessment models. ICES J. Mar. Sci. 72:99-110.
Reports what a self-test is run to find out: how many simulations the estimator brought back to an optimum, and under what the replicates were generated. The returned list cannot say the first on its own: non-converged runs are dropped before it is returned, so the number of fits returned is not the number attempted.
## S3 method for class 'Rceattle_selftest' print(x, rate = 0.9, ...)## S3 method for class 'Rceattle_selftest' print(x, rate = 0.9, ...)
x |
A |
rate |
Fraction of simulations that must converge before the run counts
as clean. Default |
... |
Currently unused. |
The status is the convergence RATE, since that is the quantity the run
produces: FAIL if nothing converged, WARN below rate, NOTE if any
replicate was dropped, OK otherwise. The table beneath tallies each
returned fit's own $convergence$status, which is a separate question,
a replicate can reach a zero gradient and still hold a NOTE or WARN,
and those are not folded into the header for that reason.
The last line says what generated the replicates, because it decides what the
spread means. With processes held fixed (the default) sim_mod() redraws the
observations alone, so the spread reflects observation error only and is a
lower bound on estimation uncertainty, do not read it against the model's
own uncertainty bands, which include process error. See
Interpreting the spread in self_test().
x, invisibly.
Print method for an Rceattle model summary
## S3 method for class 'summary.Rceattle' print(x, n = 10, ...)## S3 method for class 'summary.Rceattle' print(x, n = 10, ...)
x |
A |
n |
Number of parameters to show, in |
... |
Currently unused. |
x, invisibly.
Standard Beta(shape1, shape2) on (0, 1), matching stats::dbeta().
For priors on stock-recruit steepness on the standard (0.2, 1)
interval, transform inside the model and use prior_beta() on the
rescaled quantity.
prior_beta(shape1, shape2)prior_beta(shape1, shape2)
shape1, shape2
|
positive shape parameters. |
An Rceattle_prior of family "beta".
Shape-rate parameterization, matching stats::dgamma().
prior_gamma(shape, rate)prior_gamma(shape, rate)
shape |
positive shape parameter. |
rate |
positive rate parameter. |
An Rceattle_prior of family "gamma".
A normal density on the log of the coefficient. Under
fit_control(bias_adjust_proc = TRUE), the default, it is centred at
meanlog - sdlog^2/2, so exp(meanlog) is the prior mean; with FALSE it
matches stats::dlnorm() and exp(meanlog) is the prior median.
prior_lognormal(meanlog, sdlog)prior_lognormal(meanlog, sdlog)
meanlog |
log of the prior mean (of the median when |
sdlog |
prior standard deviation of the log (must be positive). |
An Rceattle_prior of family "lognormal".
Normal prior on a linkage coefficient
prior_normal(mean, sd)prior_normal(mean, sd)
mean |
prior mean. |
sd |
prior standard deviation (must be positive). |
An Rceattle_prior of family "normal".
One-sample process residuals for the model's random-effect (or penalized)
process deviations, in the style of SAM's procres() (Nielsen and Berg
2014). They validate the process model, whether the deviations behave like
their assumed iid normal process, a complement to the observation-based
osa_residuals().
Each set of deviations holds a Gaussian process prior in the model. The
posterior mode of the deviations is shrunk toward that prior, so, following
SAM, a single draw is taken from the joint posterior of the deviations (from
the joint precision when they are random effects, or the fixed-effect
covariance when they are penalized fixed effects) and standardized by the
process standard deviation. Under a correctly specified process these are
approximately iid N(0, 1). Because a random draw is used the residuals are
stochastic; set seed for reproducibility.
Supported processes and their deviations:
"recruitment"rec_dev, prior N(-bias_adjust_proc * R_sd^2/2, R_sd^2) per species.
"initial"init_dev, prior N(-bias_adjust_proc * R_sd^2/2, R_sd^2) per species.
"catchability"index_q_dev, prior N(0, q_dev_sd^2) per index.
"all" returns every supported process present in the fit. Selectivity and
natural-mortality deviations (which use random-walk / 2D-AR1 priors) are not
yet supported. Recruitment and initial-abundance residuals are exact (their
priors are iid). Catchability residuals are exact only for the iid deviate
prior (Time_varying_q = 1 or 2); for a random-walk or AR1 catchability
prior the marginal-SD standardization ignores the prior correlation, so those
residuals are approximate and a warning is emitted.
process_residuals( object = NULL, process = c("recruitment", "initial", "catchability", "all"), seed = 123, fit = NULL )process_residuals( object = NULL, process = c("recruitment", "initial", "catchability", "all"), seed = 123, fit = NULL )
object |
A fitted |
process |
One of |
seed |
Seed for the posterior draw. Default 123. |
fit |
deprecated name for |
A data frame of class rceattle_osa (so it can be passed to
osa_diagnostics() and plot.rceattle_osa()) with one row per deviation:
columns source (the process), fleet, species, year,
age_length_bin, and residual.
Nielsen, A., and Berg, C.W. 2014. Estimation of time-varying selectivity in stock assessments using state-space models. Fish. Res. 158:96-101.
osa_residuals(), osa_diagnostics()
Pulls the per-fleet and per-species negative log-likelihood
components out of every fit in a profile() and returns them as one long
data frame, one row per grid point per component.
The total is the least informative curve on a profile: a well-behaved
quadratic total can hide two data sources pulling the parameter in
opposite directions, and their conflict shows only once the components are
drawn separately. This is the extractor behind plot_profile(); use it to
tabulate, or to draw the figure yourself.
profile_components( object, weighted = TRUE, relative = c("own", "scaled", "minimum", "none"), minfraction = 0, include_total = TRUE )profile_components( object, weighted = TRUE, relative = c("own", "scaled", "minimum", "none"), minfraction = 0, include_total = TRUE )
object |
An |
weighted |
Report the weighted components the optimizer minimized
( |
relative |
How to place each series on the y axis: |
minfraction |
Drop components whose change over the grid is less than
this fraction of the total's change, as in |
include_total |
Include the |
Which cells are reported. jnll_comp's columns mean different things on
different rows – fleets on the data, selectivity and catchability rows,
species on the priors, penalties and predation rows – so each cell is
labelled from the axis its row uses, giving e.g.
"Shelikof acoustic: Index data". The unit is dropped from the label when
the model has only one fleet (or species) to distinguish. Cells that are zero
at every grid point are dropped as components the model does not fit.
What Total is. The "Total" series is object$nll, the objective each
grid fit minimized. Under random_rec = TRUE that is the
Laplace-approximated marginal likelihood while the components are the inner
joint negative log-likelihood, so they will not sum to it, and the function
says so when they differ. Compare the shapes, not the sums.
Non-converged grid points keep their row with a value of NA, so a
failed fit leaves a gap in the curve rather than a segment drawn across it.
Weighted or unweighted components (weighted). Conflict is normally read
off the weighted components, since those are what moved the fit.
unweighted_jnll_comp scores the composition, CAAL and stomach-content
rows without their data weights (Comp_weights, CAAL_weights,
Diet_comp_weights); every other row equals jnll_comp, so
weighted = FALSE changes only those three components. A
Dirichlet-multinomial row is scored at theta = 1, an effective sample size of
about (1 + N)/2 rather than N, so it is not comparable with a multinomial row.
Placing each series on the y axis (relative).
"own"(default) subtract each series' own minimum, so every curve starts at zero and its minimum marks the value that component prefers. Objective units, so depth still says how strongly.
"scaled"as "own", then divide by each series' own change over
the grid, so every curve runs 0 to 1. Use it where one component dwarfs
the rest and flattens them onto the axis. It discards magnitude – a
component moving 0.02 draws like one moving 40 – so raise minfraction
with it. A series that does not move stays at zero.
"minimum"subtract each series' value at the grid point where the total is lowest, showing each component's change away from the fitted optimum.
"none"the raw negative log-likelihoods.
minfraction and the series ordering are always computed on the raw change
over the grid, before any of this, so "scaled" cannot quietly disable the
filter by making every span 1.
A data frame with one row per grid point per retained component: the
profile's grid columns (slot_1, ...), then fit (grid row index),
component (the jnll_comp row), unit (fleet or species name, NA for
model-wide rows), axis ("fleet", "species" or "model"), series
(the plotting label) and value (the re-zeroed negative log-likelihood).
Series are ordered by decreasing change over the grid, "Total" first. The
profile's param, alias and the relative used are attributes.
plot_profile() to draw it, profile.Rceattle() to produce the
profile.
data(BS2017SS) ss_run <- fit_mod(data_list = BS2017SS, inits = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, msmMode = 0, avgnMode = 0, phase = FALSE, verbose = 0) prof <- profile(ss_run, param = "M1", slots = list(c(1, 1, 1)), values = list(seq(0.2, 0.5, by = 0.05))) comps <- profile_components(prof) head(comps)data(BS2017SS) ss_run <- fit_mod(data_list = BS2017SS, inits = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, msmMode = 0, avgnMode = 0, phase = FALSE, verbose = 0) prof <- profile(ss_run, param = "M1", slots = list(c(1, 1, 1)), values = list(seq(0.2, 0.5, by = 0.05))) comps <- profile_components(prof) head(comps)
Re-fits an Rceattle model while holding selected cells of a
parameter fixed. Profiles a single cell (R_log_sd[species = 1]) or
crosses several, such as log_M1[1, 1, 1] against
log_M1[1, 2, 1] for residual M in males versus females. For each
grid point the targeted cells are fixed in the TMB map and everything else
is re-estimated.
## S3 method for class 'Rceattle' profile( fitted = NULL, param = NULL, slots = NULL, values = NULL, transform = "log", cores = NULL, getsd = NULL, joint = c("none", "multiply", "add", "value"), ... )## S3 method for class 'Rceattle' profile( fitted = NULL, param = NULL, slots = NULL, values = NULL, transform = "log", cores = NULL, getsd = NULL, joint = c("none", "multiply", "add", "value"), ... )
fitted |
an Rceattle model fit using |
param |
Name of the parameter to profile: a raw slot in
|
slots |
A list of integer index vectors, one per cell to fix, each as
long as the resolved parameter has dimensions: 1 for |
values |
A list of numeric vectors, one per entry of |
transform |
How user values map onto the internal scale before
substitution: |
cores |
Cores for the parallel fits. |
getsd |
Whether each grid fit runs |
joint |
How the grid moves the cells in |
... |
Unused; present for consistency with the |
Natural-scale aliases. An alias implies transform = "log"
and, for rec_pars, fills in the column so slots needs only the
species index. transform is ignored with a warning when an alias is
used. A raw slot instead has slots index the full array and
transform set the scale.
"sigmaR", "R_sd"
R_log_sd
"M1"log_M1
"R0", "alpha", "beta"
rec_pars
columns 1, 2 and 3
"q"index_log_q, base catchability, one entry per
fleet; slots takes a fleet index or name. Fleets sharing a
Catchability_index share one q, so naming any of them profiles
the group: the rest are added with a message and joint becomes
"value".
Joint modes. A joint mode profiles a vector-valued parameter such as
an empirical age-based M, where "none" over ten ages and 13 values
would be 13^10 fits.
"none"(default) each slot gets its own grid and they cross.
"multiply"one grid multiplying every cell, so the schedule
keeps its shape; 1 is the fitted model.
"add"one grid added to every cell, so the schedule keeps
the differences between cells; 0 is the fitted model.
"value"one grid; every cell takes that value.
A joint mode needs values to be one vector, and
"multiply"/"add" work in natural units, so transform
must be "log" or "identity". A value that would take a
log-scale parameter to zero or below is an error naming the cell, not a
failed fit.
A list of class "Rceattle_profile" with elements:
the fitted models, one per grid row, NULL
where a fit did not converge so positions stay aligned with
grid.
grid values on the user scale, one column per profiled cell,
named slot_1, slot_2, ...
joint negative log-likelihoods, NA where the fit did
not converge.
the profiled parameter name.
the slots list, echoed for plotting.
the natural-scale name asked for, or NA. Profiling
"M1" returns param = "log_M1" because the model estimates
M on the log scale, while grid holds the M values supplied, so a
figure can label the axis in the units profiled.
the mode used, so a figure can say whether grid holds
a multiplier, an offset or a value.
Printing it reports whether the grid brackets the minimum; see
print.Rceattle_profile.
data(BS2017SS) ss_run <- fit_mod(data_list = BS2017SS, inits = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, msmMode = 0, avgnMode = 0, phase = FALSE, verbose = 0) # 1-D profile of sigmaR for species 1, natural scale via the alias p1 <- profile(ss_run, param = "sigmaR", slots = list(1), values = list(seq(0.1, 1.5, by = 0.1))) # 2-D cross-profile of M1 across species 1 and 2 (sex 1, age 1) p2 <- profile(ss_run, param = "M1", slots = list(c(1, 1, 1), c(2, 1, 1)), values = list(seq(0.1, 0.4, length.out = 3), seq(0.1, 0.4, length.out = 3))) # An empirical age-based M moved as a whole: one slot per age bin on ONE grid # of multipliers, so the schedule keeps its shape and 1 is the fitted model. sp <- 1 p3 <- profile(ss_run, param = "M1", slots = lapply(seq_len(ss_run$data_list$nages[sp]), function(a) c(sp, 1, a)), values = list(seq(0.6, 1.4, by = 0.05)), joint = "multiply") # Profiling catchability by fleet name, and reading a profile for where the # data disagree, are in vignette("model-diagnostics").data(BS2017SS) ss_run <- fit_mod(data_list = BS2017SS, inits = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, msmMode = 0, avgnMode = 0, phase = FALSE, verbose = 0) # 1-D profile of sigmaR for species 1, natural scale via the alias p1 <- profile(ss_run, param = "sigmaR", slots = list(1), values = list(seq(0.1, 1.5, by = 0.1))) # 2-D cross-profile of M1 across species 1 and 2 (sex 1, age 1) p2 <- profile(ss_run, param = "M1", slots = list(c(1, 1, 1), c(2, 1, 1)), values = list(seq(0.1, 0.4, length.out = 3), seq(0.1, 0.4, length.out = 3))) # An empirical age-based M moved as a whole: one slot per age bin on ONE grid # of multipliers, so the schedule keeps its shape and 1 is the fitted model. sp <- 1 p3 <- profile(ss_run, param = "M1", slots = lapply(seq_len(ss_run$data_list$nages[sp]), function(a) c(sp, 1, a)), values = list(seq(0.6, 1.4, by = 0.05)), joint = "multiply") # Profiling catchability by fleet name, and reading a profile for where the # data disagree, are in vignette("model-diagnostics").
fit$quantities uses the model's own abbreviated names. This returns the
table mapping each one to what it means, the units it is in, how it is
shaped, whether it holds a standard error, and what the same quantity is
called in the NOAA standardized assessment output.
quantity_dictionary(quantity = NULL, process = NULL)quantity_dictionary(quantity = NULL, process = NULL)
quantity |
Report names as they appear in |
process |
Character vector restricting the table to one or more parts of
the model: |
Units follow the model throughout: numbers-at-age are thousands of fish
and weight-at-age is kg, so their product is mt. A quantity whose
units read "mt or thousands of fish" follows its fleet's
Observation_units column.
se = TRUE means the TMB template ADREPORTs the quantity, so fit$sdrep
holds a standard error for it and as.data.frame.Rceattle() can fill se,
lwr and upr. se = FALSE means no standard error exists anywhere on the
fit for that quantity. Nothing has a standard error when the fit was produced
with fit_control(getsd = FALSE), which leaves sdrep NULL.
standard_label gives the name the quantity takes in the NOAA standardized
assessment output that stockplotr and asar consume, so a table can be
relabelled for those tools; NA marks a quantity that standard has no
equivalent for. Rceattle's own names are kept as the primary vocabulary
because several quantities (predation, multispecies) have no standard name.
Every per-recruit reference point (SPR0, SPRlimit, SPRtarget,
SPRFinit, NbyageSPR) is computed only under msmMode = 0 and is exactly
zero on a multispecies fit: M there holds predation mortality, which
scales with predator abundance, so spawning output per recruit is not a
property of the prey stock alone.
A data frame with one row per quantity and columns quantity,
process, meaning, units, dims, se and standard_label.
parameter_dictionary() for the estimated parameters,
as.data.frame.Rceattle() for these quantities in tidy form, and
fit_mod() for the fitted object they come from.
# The whole table head(quantity_dictionary()) # What is ssb_depletion, and what units is it in? quantity_dictionary("ssb_depletion") # Everything that holds a standard error dict <- quantity_dictionary() dict[dict$se, c("quantity", "meaning")] # Every reference point quantity_dictionary(process = "reference_points") # Search the meanings by keyword dict[grep("depletion", dict$meaning, ignore.case = TRUE), ]# The whole table head(quantity_dictionary()) # What is ssb_depletion, and what units is it in? quantity_dictionary("ssb_depletion") # Everything that holds a standard error dict <- quantity_dictionary() dict[dict$se, c("quantity", "meaning")] # Every reference point quantity_dictionary(process = "reference_points") # Search the meanings by keyword dict[grep("depletion", dict$meaning, ignore.case = TRUE), ]
A common vocabulary, documented here once and inherited by the plotters that
take it: plot_timeseries() and its wrappers (plot_biomass(), plot_ssb(),
plot_recruitment(), the depletions, plot_exploitable_biomass(),
plot_f()), the predation plotters (plot_b_eaten(), plot_b_eaten_prop(),
plot_m_at_age(), plot_m2_at_age_prop(), plot_ration()), and
plot_selectivity(). Each argument means the same thing wherever it appears,
but not every plotter takes every one, incl_mean is on the predation
plotters, add_ci only where the quantity holds standard errors, and
alpha only where the figure has a ribbon or a fan. The remaining
plot_*() functions still take their own arguments; see each one's help.
Rceattle |
A single |
file |
Optional file stem; the figure is written to
|
model_names |
Legend labels for the models. |
species |
Species to include, as indices ( |
spnames |
Species labels, length |
line_col |
Line colours; names, hex, or base-graphics integers. |
lwd |
Line width on the base-graphics scale: the default |
lty |
Line type. A vector varies it across the levels of whatever the figure separates by line type. |
alpha |
Transparency of confidence ribbons and shaded areas, between 0 and 1. |
add_ci |
Add a 95% confidence interval. Only available where the plotted quantity holds standard errors; warns and draws none otherwise. |
minyr, maxyr
|
First / last year to plot. |
incl_proj |
Include the projection years, with a dashed divider at the last hindcast year. |
incl_mean |
Add a horizontal line at the hindcast mean of each series. |
width, height
|
Saved figure size in inches. |
right_adj |
Ignored. Base-graphics leftover: the figure widened its right margin to fit the legend. Set margins on the returned ggplot instead. |
top_adj |
Ignored. Base-graphics leftover; see |
mod_cex |
Ignored. Base-graphics leftover: legend text size. Use
|
legend.pos |
Ignored. Base-graphics leftover: legend placement. Use
|
single.plots |
Ignored. Base-graphics leftover: one device per panel. The ggplot facets instead. |
theta |
Ignored. Base-graphics leftover: viewing angle of a |
ymax |
Ignored. Base-graphics leftover: y-axis maximum. Use
|
cex |
Ignored. Base-graphics leftover: point expansion. |
A ggplot object.
line_col and lty are appliedThey supply values for whichever discrete variable the plot already encodes with that aesthetic, matched in level order, which is not always the model. Each function's help says what its own figure separates.
Where colour encodes a continuous variable, the year fan in
plot_selectivity(), line_col supplies the ramp anchors instead: one
colour draws the fan in that colour, several interpolate between them.
A common vocabulary, documented here once and inherited by the diagnostics
that refit the model: retrospective(), jitter() and self_test(). Each
argument means the same thing wherever it appears. phase, getsd and
timeout are deliberately not here, their defaults and their
consequences for the diagnostic differ, so each function documents its own.
profile() refits too but takes only cores and a bare getsd.
object |
an Rceattle model fit using |
Rceattle |
deprecated name for |
cores |
Number of cores for the parallel refits. Default |
fit_control |
optional |
fit_control() reachesThese diagnostics refit through an internal helper that forwards phase and
getsd and nothing else. Every other field either comes off the fitted
model's own data_list (loopnum, comp_offset, the bias-adjustment flags)
or takes fit_control()'s default. Setting one of those is an error rather
than a silent no-op, so a field you set is a field the refit used.
Only the fields you set are applied, named in the fit_control() call, or
assigned to afterwards (ctl$getsd <- TRUE). One you never touch keeps the
diagnostic's own default, which is not always fit_control()'s,
retrospective() phases its peels where fit_control() does not, so
fit_control(getsd = FALSE) asks about standard errors and changes nothing
else. Setting a field to the value that is already fit_control()'s default
still counts as setting it.
Read a CEATTLE excel data file
read_data(file = "Rceattle_data.xlsx")read_data(file = "Rceattle_data.xlsx")
file |
Filename to read. Must end in '.xlsx' |
build_data() to assemble or edit a data list in R (and to read a
workbook then override blocks in one call, build_data(file = ...)),
data_requirements() to see which inputs a configuration needs.
library(Rceattle) data(BS2017SS) out_file <- file.path(tempdir(), "BS2017SS.xlsx") write_data(data_list = BS2017SS, file = out_file) data_list <- read_data(file = out_file) # Or read + override blocks in one call: data_list <- build_data(file = out_file, projyr = 2060) file.remove(out_file)library(Rceattle) data(BS2017SS) out_file <- file.path(tempdir(), "BS2017SS.xlsx") write_data(data_list = BS2017SS, file = out_file) data_list <- read_data(file = out_file) # Or read + override blocks in one call: data_list <- build_data(file = out_file, projyr = 2060) file.remove(out_file)
Function to rearrange a data_list object to be read into TMB
rearrange_dat() is a deprecated alias for rearrange_data(),
kept so older scripts keep running. It is scheduled for removal in 6.0.0;
use rearrange_data().
rearrange_data(data_list, build_osa = FALSE) rearrange_dat(data_list)rearrange_data(data_list, build_osa = FALSE) rearrange_dat(data_list)
data_list |
an Rceattle data_list |
build_osa |
Logical. Passed to |
Refits the model with fishing mortality set to 0 from styr on, keeping
every other parameter. The projection after endyr is always unfished.
run_mse() uses it for the no-fishing run (OM_no_F) behind the collapse
metrics.
remove_F(object = NULL, styr = NULL, Rceattle = NULL)remove_F(object = NULL, styr = NULL, Rceattle = NULL)
object |
A fitted Rceattle model object |
styr |
First year with F = 0; default |
Rceattle |
deprecated name for |
styr may be any year from the model's own styr to endyr + 1; the
projection is unfished whatever harvest control rule the model was fit under.
Under predation, empirical suitability (suitMode = 0) is derived from the
fitted abundance over each predator's suit_styr:suit_endyr, so styr must
fall after that window for every predator with suitMode = 0 and diet data
in it.
Attaches dimension names (species, sex, age, length bin, year, fleet) to the report objects returned by the TMB model, and names the rows/columns of the likelihood-component matrices, so the fitted quantities read as labeled arrays rather than bare numbers.
rename_output(data_list = NULL, quantities = NULL)rename_output(data_list = NULL, quantities = NULL)
data_list |
an Rceattle data_list |
quantities |
list of "report" objects from Rceattle. |
Collects the quantities a stock assessment reports into one set
of tidy tables, so a SAFE chapter or a model comparison comes from a single
call rather than a dozen ad-hoc extractions. Every table holds a model
column, so passing several fits gives a like-for-like comparison.
report_tables( object, model_names = NULL, retro = NULL, jitter = NULL, osa = NULL, ci_level = 0.95, quantities = c("biomass", "ssb", "R", "biomass_depletion", "ssb_depletion", "F_spp") )report_tables( object, model_names = NULL, retro = NULL, jitter = NULL, osa = NULL, ci_level = 0.95, quantities = c("biomass", "ssb", "R", "biomass_depletion", "ssb_depletion", "F_spp") )
object |
An Rceattle fit from |
model_names |
Names for the models, defaulting to the names of |
retro |
A |
jitter |
A |
osa |
An |
ci_level |
Confidence level for the |
quantities |
Time-series quantities to include, from the set
|
The sections follow the AFSC Alaska Groundfish Stock Assessment Guidelines for what a chapter reports:
modelOne row per fit: dimensions, switches, the marginal and joint negative log-likelihoods, estimated parameter count, AIC, maximum gradient, whether the Hessian was positive definite, and run time.
parametersEvery estimated parameter with its standard error and
its natural-scale name and process from parameter_dictionary(), which
is where sigma_R and an estimated M are found. Estimates are on the
parameter's own scale, so a log_ name needs exp(). A fixed M is
absent, never having been estimated: read it off M_at_age.
likelihoodNegative log-likelihood by component and fleet or species, weighted and unweighted.
timeseriesBiomass, female spawning-stock biomass, recruitment,
depletion and fishing mortality by species and year, with standard errors
and intervals, split into hindcast (era = "time") and projection
(era = "fore").
reference_pointsThe executive-summary quantities: SPR-based F
proxies, unfished and target female spawning-stock biomass, the biomass
proxies implied by Ptarget / Plimit, and terminal status. A basis
column says whether each was estimated, and if not why.
fitsObserved against predicted index and catch, with the standard deviation of normalized residuals (SDNR) per fleet.
retrospective, jitter, osa
Present only when the corresponding object is supplied.
Nothing here refits: the three diagnostics are tens to hundreds of
optimizations each, so they are passed in already computed, and a section
whose object is NULL is absent from the result.
The standard harvest scenarios of guideline section 4.11.3 are not
produced; they need a standard projection module, which Rceattle does not
have. Projected biomass under the model's own control rule is in
timeseries at era = "fore".
Reference points a fit never estimated come back as NA, with the reason
in basis. The reported array leaves a plausible number in each, which
is how a wrong figure reaches an executive summary:
Ftarget / Flimit are estimated only under a control rule that
defines them, and are off for a species with no projected fishery or with
fixed numbers-at-age. Unestimated, they sit at exp(0) = 1, reading as
an F of 1.0/yr.
SB0 / B0 under msmMode > 0 come from the MSSB0 / MSB0
inputs, which hold a placeholder until fit_mod() derives them from a
no-fishing projection. B_target and B_limit are fractions of SB0
and go with it.
The per-recruit quantities (SPR0, SPRtarget, SPRlimit) are
computed only under msmMode = 0.
The depletions are not blanked alongside SB0: under a no-fishing
control rule in multispecies mode the model divides by last-projection-year
biomass, the equilibrated unfished reference, so the series is meaningful.
A list of data frames with class "rceattle_report", one per section
above, each holding a model column.
model reports both, and both are minimized, so smaller is the better
fit. marginal_nll is what the optimizer minimized, random effects
integrated out by Laplace, and is what AIC is built from. joint_nll is
what the template evaluated at the conditional modes, so it is what
likelihood sums to, on the same scale as jnll_comp. They are equal when
n_random is 0 and differ by the Laplace correction otherwise.
A diagnostics list is matched to models by name, so
list(alt = ..., base = ...) pairs correctly whatever the order. An unnamed
list is paired positionally, with a message. A name that is not a model name
is an error, which catches passing one model's osa_residuals() result
stored as a list of parts.
quantity_dictionary() for what each quantity means and its units,
as.data.frame.Rceattle() for the time series alone, and
standard_output() to relabel the result into the NOAA standardized
assessment output that stockplotr and asar consume.
## Not run: fit <- fit_mod(data_list = BS2017SS, estimateMode = 1) tabs <- report_tables(fit) tabs$reference_points # Compare two models, with diagnostics attached tabs <- report_tables(list(base = fit0, alt = fit1), retro = list(retro0, retro1)) ## End(Not run)## Not run: fit <- fit_mod(data_list = BS2017SS, estimateMode = 1) tabs <- report_tables(fit) tabs$reference_points # Compare two models, with diagnostics attached tabs <- report_tables(list(base = fit0, alt = fit1), retro = list(retro0, retro1)) ## End(Not run)
Returns a long-format data frame of residuals, following the convention of
stats::residuals.glm() where type selects the kind of residual. By
default residuals are returned for every applicable data source, survey
indices, fishery catches, age/length composition (comp), and conditional
age-at-length (caal); use source to restrict to particular ones.
## S3 method for class 'Rceattle' residuals( object, type = "response", source = "all", scale = "log", species = NULL, ... )## S3 method for class 'Rceattle' residuals( object, type = "response", source = "all", scale = "log", species = NULL, ... )
object |
An object of class |
type |
Residual kind: one of |
source |
Data source(s) to include: any of |
scale |
|
species |
Optional species code(s) to include (matched against the
|
... |
Passed to |
Residual kinds (type):
"response"Observed minus fitted. For index / catch this is on
the log scale by default (matching the lognormal likelihood; set
scale = "natural" for the arithmetic difference); for comp / caal
it is the difference in proportions, observed minus fitted.
"pearson"Standardized residuals. For catch and a log-scale
survey index,
using the model's
realized observation log-SD and the observation
bias-adjustment flag (bias_adjust_obs, default 1). A
natural-scale index fleet (Index_distribution "MVN", "MVNORM",
"Normal" or "TruncatedNormal") holds an ABSOLUTE and is
standardized as instead. Two caveats there: a
covariance fleet ("MVN", "MVNORM") takes from
sqrt(diag(index_cov)), since its likelihood never reads the reported
scalar sd, and so gets its marginal residual rather than the whitened one
(use type = "osa" for that); and "TruncatedNormal" is standardized on the
untruncated moments, so it is approximate where is
small enough for truncation to shift the mean. For comp / caal,
with input sample size
N.
"osa"One-step-ahead residuals via osa_residuals(), which builds
the composition observation data on demand from any fit. Pass its
arguments through ...; note that method = "cdf" forms no conditional
mean, so Fitted is NA for every row under it.
"process"Process residuals via process_residuals() for the
model's random-effect deviations; source does not apply.
Composition rows are returned in long form (one row per observation x
age/length bin) and hold the Age0_Length1 flag from comp_data (0 age,
1 length); CAAL rows hold both the conditioning Length and the age Bin.
Where a fleet uses tail accumulation (Comp_accum_young /
Comp_accum_old), composition residuals describe the bins the likelihood
actually fit: the tails are folded into their boundary bin and the bins
outside the window are not reported, because the model never fit them
separately. Bin names the age or length each residual belongs to and
Accumulated marks the boundary bins, which stand for a range rather than
the single bin they are named for. Fleets without accumulation are unchanged.
A data.frame with columns Source, Fleet_code, Fleet_name,
Species, Sex, Year, Length, Bin, Age0_Length1, Sample_size,
Accumulated, Observed, Fitted, Residual. Columns are NA where they
do not apply; Accumulated is FALSE except on a composition bin that
absorbed a folded tail.
Calculate Mohn's rho and run retrospective peels for an Rceattle model, and evaluate retrospective forecast skill. Each peel uses TMB's map to:
filter the data and fixed inputs and map out time-varying parameters for the peeled years, holding them at that peel's terminal year;
fit the peeled model;
turn the hindcast parameters off and F for the peeled years on, and fit to the peeled catch series, updating the "forecast" dynamics given the projection assumptions and the observed catch.
retrospective( object = NULL, peels = 5, rescale = FALSE, nyrs_forecast = 3, cores = NULL, getsd = NULL, phase = TRUE, fit_control = NULL, Rceattle = NULL )retrospective( object = NULL, peels = 5, rescale = FALSE, nyrs_forecast = 3, cores = NULL, getsd = NULL, phase = TRUE, fit_control = NULL, Rceattle = NULL )
object |
an Rceattle model fit using |
peels |
number of retrospective peels used for rho and estimation |
rescale |
TRUE/FALSE whether to subset and rescale environmental predictors over the peel years. |
nyrs_forecast |
forecast years over which to calculate Mohn's rho, in addition to the terminal year |
cores |
Number of cores for the parallel refits. Default |
getsd |
whether each peel runs |
phase |
whether each peel is refitted in phases, default |
fit_control |
optional |
Rceattle |
deprecated name for |
Each peel is fitted twice: a peeled hindcast, then a forecast refit
estimating only the peeled years' F. The second holds every hindcast
parameter fixed, so on its own it reports a standard error of zero across the
hindcast. Under getsd = TRUE the peel is therefore rebuilt at those same
parameters with the hindcast free in the map and reported from there; nothing
is re-estimated, so no point estimate moves. Where that rebuild fails – it
throws, or comes back with a Hessian it could not factor, or with no finite
standard error – the peel keeps its point estimates and carries no sdrep
at all, rather than the forecast refit's zero standard errors. The reason is
named in one warning per call and carried on the peel; print() reports how
many peels could not report standard errors.
a list of 1. a list of Rceattle models and 2. Mohn's rho per species.
A peel that did not converge is dropped, so Rceattle_list can be
shorter than peels + 1, with a message. Entries are named for their
own terminal year (Year_2017, ...), so index by name:
Rceattle_list[[3]] is not necessarily the 3-year peel. With no peel
left, rho is NaN and the function warns. Each peel reports its own
terminal year as data_list$endyr, so plots draw it only as far as it
was fit.
A peel still estimates the years it dropped: that is its retrospective
forecast, fit to observed catch with the survey and composition data
withheld. Its recruitment deviation is the one sample_rec() sets with
sample_rec = FALSE, computed from the peel's own fit. Three years matter,
and every peel carries all three:
endyr, endyr_peel
the peel's terminal year, what it was fit through. Equal to each other.
endyr_fullthe unpeeled model's terminal year, where the retrospective forecast ends.
projyrthe end of the harvest-control-rule projection.
A peel whose standard errors could not be rebuilt carries
attr(peel, "sd_report_error"), a one-line reason naming the peel and
its terminal year; it is absent on every other peel.
Take the forecast years as
endyr_peel + seq_len(endyr_full - endyr_peel), which is empty for the
unpeeled model, rather than (endyr_peel + 1):endyr_full, which counts
down there. Mohn's rho is computed from endyr_peel and is
unaffected by any of this.
Catchability is estimated only for a fleet holding fitted index rows (see
build_map), and a peel moves endyr, so a survey whose
index observations all fall in the peeled-off years has no q estimated in
that peel: the parameter count is not constant across peels. That is
deliberate, since a q with no index to inform it is a flat direction in the
likelihood. Rho is computed from SSB and is unaffected, but npar and
the reported catchability do differ between a shallow and a deep peel for
such a fleet.
data(BS2017SS) ss_run <- fit_mod(data_list = BS2017SS, inits = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, msmMode = 0, avgnMode = 0, phase = FALSE, verbose = 0) retro <- retrospective(ss_run, peels = 10)data(BS2017SS) ss_run <- fit_mod(data_list = BS2017SS, inits = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, msmMode = 0, avgnMode = 0, phase = FALSE, verbose = 0) retro <- retrospective(ss_run, peels = 10)
Tunes multinomial composition weights by refitting: each pass sets a fleet's weight to the McAllister & Ianelli (1997) weight implied by the previous fit, and stops once the weights settle. The weight multiplies the input sample size, so changing it changes the fit and hence the next implied weight, which is why the weights are tuned iteratively rather than in one step.
reweight_comps( object = NULL, n_iter = 10, tol = 0.01, fleets = NULL, verbose = TRUE, fit = NULL )reweight_comps( object = NULL, n_iter = 10, tol = 0.01, fleets = NULL, verbose = TRUE, fit = NULL )
object |
An |
n_iter |
Maximum number of iterations (default 10). |
tol |
Relative change in the weights below which to stop (default 0.01). |
fleets |
Fleets to tune, as |
verbose |
Print the weights each iteration (default |
fit |
deprecated name for |
Only multinomial fleets are tuned. A Dirichlet-multinomial fleet estimates
its own weight within the likelihood, so tuning it externally would compete
with that estimate; those fleets are named and skipped, as are any requested
through fleets that have no fitted composition data.
Only the age/length composition weight (Comp_weights) is tuned. The
conditional age-at-length and diet weights have McAllister-Ianelli analogues
of their own (CAAL_weights, Diet_comp_weights), but they are not tuned
here; set them by hand if needed.
Tuning stops when the largest relative change in any weight falls below
tol. Hitting n_iter first gives a warning, not an error, the partly
tuned fit is returned either way, and $reweight$history shows whether the
weights were still settling.
The weight is a parameter, not a data input, so each pass holds it to the
next through inits; fleet_control$Comp_weights supplies the value only
when a model is built from scratch, and editing that column then refitting
from an existing fit has no effect (fit_mod() warns when it detects this).
Each pass writes the new weight to both, so the returned model's data list
rebuilds the tuned model from scratch.
The model refitted with the final weights, holding a reweight
element: history (one row per fleet per iteration), iterations, and
converged. The last rows of history are the weights the returned model
was fitted with.
McAllister, M.K. and 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.
Francis, R.I.C.C. (2011) Data weighting in statistical fisheries stock assessment models. Canadian Journal of Fisheries and Aquatic Sciences 68:1124-1138. (The main alternative; applied by hand rather than by this function.)
## Not run: fit <- fit_mod(BS2017SS, estimateMode = "Hindcast") tuned <- reweight_comps(fit) tuned$reweight$history # weight per fleet, per iteration ## End(Not run)## Not run: fit <- fit_mod(BS2017SS, estimateMode = "Hindcast") tuned <- reweight_comps(fit) tuned$reweight$history # weight per fleet, per iteration ## End(Not run)
A subset of rich.colors by Arni Magnusson from the gplots package, with the addition of alpha transparency (which is now available in the gplots version as well)
rich.colors.short(n, alpha = 1)rich.colors.short(n, alpha = 1)
n |
Number of colors to generate. |
alpha |
Alpha transparency value for all colors in vector. Value is passed to rgb function. |
Arni Magnusson, Ian Taylor
Returns the model_config() structure plus the estimation controls and
fit_control() bundle as a single Rceattle_run_config. Accepts a fitted
Rceattle object, a data list holding $model_config, an
Rceattle_run_config, or an Rceattle_model_config. Estimation controls and
fit_control supplied via ... override any found on the object.
run_config(x, ...)run_config(x, ...)
x |
A fitted Rceattle object, a data list, an |
... |
Estimation controls / |
An Rceattle_run_config.
save_config(), load_config(), model_config().
# Coerce a model_config() into a full run configuration, overriding the # estimation controls. A fitted model or a data list works the same way. rc <- run_config(model_config(msmMode = 1), estimateMode = "Hindcast") rc$estimateMode # Optimizer and uncertainty settings belong inside fit_control(), not here; # an unrecognized field is an error rather than a silent no-op. rc <- run_config(rc, fit_control = fit_control(getsd = FALSE))# Coerce a model_config() into a full run configuration, overriding the # estimation controls. A fitted model or a data list works the same way. rc <- run_config(model_config(msmMode = 1), estimateMode = "Hindcast") rc$estimateMode # Optimizer and uncertainty settings belong inside fit_control(), not here; # an unrecognized field is an error rather than a silent no-op. rc <- run_config(rc, fit_control = fit_control(getsd = FALSE))
Runs a forward-projecting management strategy evaluation (MSE).
Projected selectivity, catchability, foraging days and weight-at-age are
held at the operating model's terminal hindcast year, survey SD is the
average over the historical series, and composition sample size is held at
the last year. There is no implementation error and no observation error on
catch. Fixed numbers-at-age (estDynamics > 0) are an input rather than a
forecast, so they are NOT held forward: supply NByageFixed rows for every
projection year, or the uncovered years read 0 and that species contributes
nothing, with a warning naming it.
run_mse( om, em, nsim = 10, start_sim = 1, assessment_period = 1, sampling_period = 1, simulate_data = TRUE, regenerate_past = FALSE, sample_rec = TRUE, rec_trend = 0, fut_sample = 1, cap = NULL, catch_mult = NULL, seed = 666, regenerate_seed = seed, loopnum = 1, file = NULL, dir = NULL, timeout = 999, endyr = NA, cores = NULL )run_mse( om, em, nsim = 10, start_sim = 1, assessment_period = 1, sampling_period = 1, simulate_data = TRUE, regenerate_past = FALSE, sample_rec = TRUE, rec_trend = 0, fut_sample = 1, cap = NULL, catch_mult = NULL, seed = 666, regenerate_seed = seed, loopnum = 1, file = NULL, dir = NULL, timeout = 999, endyr = NA, cores = NULL )
om |
CEATTLE model object exported from |
em |
CEATTLE model object exported from |
nsim |
Number of simulations to run (default 10) |
start_sim |
First simulation number to start at, useful when a run stops at a particular seed (default 1). |
assessment_period |
Assessment schedule. A single number is the period in years between assessments, counted from the operating model's terminal year; a vector is the explicit set of assessment years, which must name two or more years inside the projection horizon. Default 1. |
sampling_period |
Period of years data sampling is conducted. Single value or vector the same length as the number of fleets. |
simulate_data |
Include simulated random error proportional to that estimated or provided for the data from the OM. |
regenerate_past |
Refit the EM to historical conditioning data before
the MSE, generated from the OM with or without sampling error according to
|
sample_rec |
Include resampled hindcast recruitment deviations in the OM
projection. Resampled rather than drawn from N(0, sigmaR) because the
initial deviations bias R0 low. |
rec_trend |
Linear change in mean recruitment from |
fut_sample |
Future sampling effort relative to the last year:
|
cap |
A ceiling on projected catch. A single number is an ANNUAL
ceiling on total removals summed across species, shared between them in
proportion to the catch the control rule recommended; a vector of length
|
catch_mult |
A multiplier on the catch the control rule recommends,
applied before |
seed |
seed for the simulation |
regenerate_seed |
seed for regenerating data |
loopnum |
Number of times to restart optimization; |
file |
(Optional) Filename where each OM simulation with EMs is saved. If NULL, no files are saved. |
dir |
(Optional) Directory where each OM simulation is saved |
timeout |
Minutes estimation runs before a sim is stopped (default 999) |
endyr |
Terminal year of the MSE projection. Default NA uses
|
cores |
Cores for the parallel simulations. |
Designing a schedule, comparing monitoring scenarios, and what the common
random numbers do and do not share across schedules are in
vignette("hcrs-and-mses").
One piece of arithmetic to get right when buffering a missed assessment: the
assessment in year Y sets catch for Y + 1 onward. So dropping 2031 from a
biennial cycle leaves 2032 and 2033 on 2029's advice, and 2031 itself is
set by the 2029 assessment either way – buffering 2031 changes a year the
missed assessment never touched.
Catch recorded past a model's terminal year is blanked to NA at setup, with
a warning naming the years: the MSE sets those years from the control rule,
and the likelihood never scored them, since it fits only Year <= endyr.
That is what a workbook looks like when endyr has fallen behind the catch
series, and it is worth resolving first, because conditioning on those years
is a different question from projecting over them.
A list of operating models (differing by simulated recruitment, per
nsim) and estimation models fit to each (differing by terminal year).
## Not run: data(BS2017SS) om <- fit_mod(BS2017SS, estimateMode = "Estimate", HCR = build_hcr("NPFMC")) # Closed loop: assess every 2 years, survey every year, 10 simulations. mse <- run_mse(om = om, em = om, nsim = 10, assessment_period = 2, sampling_period = 1) mse_summary(mse)$species ## End(Not run)## Not run: data(BS2017SS) om <- fit_mod(BS2017SS, estimateMode = "Estimate", HCR = build_hcr("NPFMC")) # Closed loop: assess every 2 years, survey every year, 10 simulations. mse <- run_mse(om = om, em = om, nsim = 10, assessment_period = 2, sampling_period = 1) mse_summary(mse)$species ## End(Not run)
Sample historical recruitment deviations into the projection
sample_rec( object = NULL, sample_rec = TRUE, update_model = TRUE, rec_trend = 0, Rceattle = NULL )sample_rec( object = NULL, sample_rec = TRUE, update_model = TRUE, rec_trend = 0, Rceattle = NULL )
object |
CEATTLE model object exported from |
sample_rec |
Include resampled recruitment deviations from the hindcast in the OM projection. Resampled deviations are used rather than drawing from N(0, sigmaR) because the initial deviations bias R0 low. If FALSE, uses one deviation (plus the log of the |
update_model |
Update model dynamics. Default = TRUE |
rec_trend |
Linear increase or decrease in mean recruitment from |
Rceattle |
deprecated name for |
Rceattle model
Round-trips a full run configuration, the model_config() structure plus
the estimation controls and fit_control() bundle, to a
git-diffable YAML file, with each field's documentation emitted as a comment
and a spec-tree + provenance header. Only fields that differ from their
defaults are written, so two configurations diff to just their real
differences. The parameter values (inits/map/bounds) are NOT stored;
pair the config with a saved fit for those.
save_config(x, file = "Rceattle_config.yaml", ...)save_config(x, file = "Rceattle_config.yaml", ...)
x |
A fitted Rceattle object, a data list holding |
file |
Output path for the |
... |
Estimation controls / |
Invisibly, the Rceattle_run_config that was written.
load_config(), run_config(), model_config(), fit_mod().
cfg <- model_config(msmMode = 1, initMode = "OffsetEquilibrium") f <- file.path(tempdir(), "run.yaml") save_config(cfg, f) identical(load_config(f)$model_config$msmMode, 1)cfg <- model_config(msmMode = 1, initMode = "OffsetEquilibrium") f <- file.path(tempdir(), "run.yaml") save_config(cfg, f) identical(load_config(f)$model_config$msmMode, 1)
Simulates data from an Rceattle model and refits the model to
the simulated data, to check that the fitting procedure recovers the
operating-model parameters. Pass process to redraw a process as well as
the observations.
self_test( object = NULL, nsim = 50, simulate = TRUE, seed = 123, cores = NULL, getsd = NULL, phase = NULL, start = c("initial", "estimated"), debug = FALSE, timeout = Inf, process = FALSE, fit_control = NULL, Rceattle = NULL )self_test( object = NULL, nsim = 50, simulate = TRUE, seed = 123, cores = NULL, getsd = NULL, phase = NULL, start = c("initial", "estimated"), debug = FALSE, timeout = Inf, process = FALSE, fit_control = NULL, Rceattle = NULL )
object |
an Rceattle model fit using |
nsim |
number of simulations |
simulate |
passed to |
seed |
random number seed. Simulation |
cores |
Number of cores for the parallel refits. Default |
getsd |
whether each refit runs |
phase |
as in |
start |
Which parameter set each refit starts from: |
debug |
return every simulation rather than only the converged ones. The
dropped runs are the interesting ones when a self-test comes back short,
and each holds its own |
timeout |
elapsed-second limit per simulation, |
process |
passed to |
fit_control |
optional |
Rceattle |
deprecated name for |
What start costs. "initial" uses
initial_params, so the estimator travels the same distance to the
optimum on simulated data as it did on the real data. "estimated"
starts from the generating values instead – the fixed effects, and under
random_rec = TRUE the inner Laplace problem too – so it is much
faster and far likelier to converge, but on a multimodal or weakly
identified surface the optimizer never leaves the basin containing them, so
recovery is close to guaranteed by construction. Read it as optimistic about
recovery, not merely less powerful. It is not a complete warm start either –
fit_mod() resets log_Ftarget, proj_F_prop and the
stock-recruit / under both settings – and
non-identifiability stays visible either way through $convergence's
Hessian conditioning and estimability checks. What a warm start stops
testing is reachability.
A list of Rceattle models named Sim_1, Sim_2, ... By
default only the converged simulations, renumbered contiguously, with a
message reporting how many were dropped. The list has class
"Rceattle_selftest" and carries the number attempted in
attr(, "nsim"), so printing it reports the convergence rate; it is
otherwise the plain list it always was.
With debug = TRUE, every simulation, Sim_i being simulation
i so it pairs with seed seed + i, plus the convergence
verdicts in attr(, "converged"). A refit that errored outright comes
back as the condition object rather than a model, so it cannot abort the
run.
Where process redrew something, attr(, "process_sim") holds
the deviations that generated each replicate, keyed by the same
Sim_i names and subset alongside the models. Each entry names
whichever of rec_dev, init_dev, log_M1_dev and
beta_linkage_re were drawn, each with a same-shaped _drawn
logical marking the cells the draw touched. Restrict any recovery statistic
to those cells, and compare estimates against these rather than against the
operating model, whose fitted deviations are no longer what generated the
data.
sim_mod redraws the observations only, and warns about each row
it leaves alone: a predator with empirical rather than estimated suitability
has no predicted diet to draw from, and a covariance (MVN/MVNORM) survey
fleet has no covariance outside its fitted years. Those data are identical in
every replicate, so recovery of whatever they inform is optimistic.
By default recruitment is not redrawn, so under random_rec = TRUE
every replicate shares the operating model's single realization – its shrunk
empirical-Bayes modes, not a draw from N(0, sigmaR). The spread across
replicates is then observation error alone and a lower bound on estimation
uncertainty in SSB and recruitment, so do not read it against the model's own
uncertainty bands, which include process error; and sigmaR is re-estimated
from deviations shrunk toward zero the same way every time, a downward bias
averaging does not remove. process = "recruitment" removes both, at
the cost of asking a different question. See
vignette("model-diagnostics").
data(BS2017SS) ss_run <- fit_mod(data_list = BS2017SS, inits = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, msmMode = 0, avgnMode = 0, phase = FALSE, verbose = 0) sims <- self_test(ss_run, nsim = 10)data(BS2017SS) ss_run <- fit_mod(data_list = BS2017SS, inits = NULL, file = NULL, estimateMode = 0, random_rec = FALSE, msmMode = 0, avgnMode = 0, phase = FALSE, verbose = 0) sims <- self_test(ss_run, nsim = 10)
Default phasing order for CEATTLE parameters
set_phases()set_phases()
Tagged list mapping each parameter name to its estimation phase.
Simulates the data an Rceattle model would have produced, as
expected values or as a random draw. Every observation type is covered:
survey biomass (under the fleet's own Index_distribution – lognormal,
natural-scale normal, or the correlated MVN/MVNORM draw from its covariance),
total catch (lognormal), age/length composition and conditional age-at-length,
and stomach contents (multinomial or Dirichlet-multinomial).
sim_mod(object = NULL, simulate = FALSE, process = FALSE, Rceattle = NULL)sim_mod(object = NULL, simulate = FALSE, process = FALSE, Rceattle = NULL)
object |
A CEATTLE model object exported from |
simulate |
Logical. |
process |
Which process error to redraw alongside the observations.
|
Rceattle |
deprecated name for |
Every draw is taken by the TMB model itself, in a SIMULATE block beside
the likelihood that defines it, so simulate = TRUE needs a model to
evaluate. A model loaded from a file has one, and a fit whose $obj was
dropped to save space is rebuilt from its data_list and estimates,
provided the rebuild reproduces the fit's own expected values.
model_average output cannot be simulated from at all: its
quantities are an average over models, so no parameters produced them.
simulate = FALSE reads only $quantities and draws no random
numbers, so it works on any model.
Rows the model predicts nothing for are left alone, and all but the last of
these is reported by a warning: a composition for a fleet with no catch that
year comes back empty, while a stomach whose predator has empirical
suitability, and a covariance fleet's observations outside its fitted window,
keep their observed values. A composition, CAAL or diet row whose sample size
times its weight rounds below one observation also comes back empty, with
Sample_size dropped to zero so a refit does not score a row with no
data behind it. A hindcast survey year with no observation (NA) stays
NA and is NOT warned about, since the likelihood never scored it,
while the independent survey families still draw their projection rows
(negative Year), which run_mse reveals as each
assessment's new data.
One deliberate exception to draw-equals-density: compositions are drawn from
the predicted proportions before comp_offset (the constant added to
observed and predicted alike to keep log(0) out of the density,
default 1e-5), so a bin predicted at zero is drawn at zero while the density
scores it at comp_offset. That is about 4e-4 relative on a 20-bin
composition and does not bias the round trip, since the offset is applied to
both sides on the next fit.
Drawn values are left in the object's report environment under names ending
_sim; the estimates, the data and the objective are untouched, so a
later osa_residuals() or vcov() on the same model is unaffected.
A data_list of the simulated or expected data, formatted for
Rceattle. Where process redrew something, the deviations that
generated the data are attached as attr(x, "process_sim"), a named
list holding whichever of rec_dev, init_dev,
log_M1_dev and beta_linkage_re were drawn. Those are the
truth a refit has to recover; without them the only comparison available is
against the original fitted deviations, which are no longer what generated
the data.
Each comes with a same-shaped logical named *_drawn, TRUE
where the draw touched that cell. Draws cover the hindcast only, and
beta_linkage_re is one vector over every random-linkage slot whether
or not its process was asked for, so the arrays hold fitted values beside
simulated ones. Restrict any recovery statistic to the _drawn
cells; over the full array it reports perfect recovery on the cells that
were never redrawn.
## Not run: data(BS2017SS) fit <- fit_mod(BS2017SS, estimateMode = "Hindcast") # Expected values only, no observation error drawn. sim_mod(fit) # One stochastic replicate, drawn from each fleet's own likelihood. sim_mod(fit, simulate = TRUE) ## End(Not run)## Not run: data(BS2017SS) fit <- fit_mod(BS2017SS, estimateMode = "Hindcast") # Expected values only, no observation error drawn. sim_mod(fit) # One stochastic replicate, drawn from each fleet's own likelihood. sim_mod(fit, simulate = TRUE) ## End(Not run)
The stats::simulate() method for CEATTLE fits: draws nsim
replicate data sets from the fitted observation model, and optionally from
the process model as well.
## S3 method for class 'Rceattle' simulate(object, nsim = 1, seed = NULL, process = FALSE, ...)## S3 method for class 'Rceattle' simulate(object, nsim = 1, seed = NULL, process = FALSE, ...)
object |
An object of class |
nsim |
Number of replicate data sets to draw. Default 1. |
seed |
Optional seed. The caller's random state is restored afterwards,
per |
process |
Which process error to redraw alongside the observations.
|
... |
Currently unused. |
A wrapper on sim_mod(), which documents the observation model in full. For
expected values rather than draws, call sim_mod(simulate = FALSE).
Draws are taken by the TMB model, so simulate() needs a live $obj: a
model loaded from disk has one, a model_average() result does not, see
sim_mod().
A list of nsim data_list objects, always a list, including at
nsim = 1, so callers do not have to special-case the length. When
process redrew something, each element holds the deviations that
generated it as attr(, "process_sim"): a named list of whichever of
rec_dev, init_dev, log_M1_dev and beta_linkage_re were drawn, each
with a _drawn logical of the same shape marking the cells the draw
touched. Compare estimates against those rather than against object,
see sim_mod().
sim_mod() for the observation model and the process options,
self_test() for simulating and refitting in one step.
## Not run: fit <- fit_mod(data_list = BS2017SS, estimateMode = 1) reps <- simulate(fit, nsim = 10, seed = 1) # ...and with recruitment redrawn as well: reps <- simulate(fit, nsim = 10, seed = 1, process = "recruitment") truth <- attr(reps[[1]], "process_sim")$rec_dev ## End(Not run)## Not run: fit <- fit_mod(data_list = BS2017SS, estimateMode = 1) reps <- simulate(fit, nsim = 10, seed = 1) # ...and with recruitment redrawn as well: reps <- simulate(fit, nsim = 10, seed = 1, process = "recruitment") truth <- attr(reps[[1]], "process_sim")$rec_dev ## End(Not run)
Relabels report_tables() output into the standardized
assessment output that the stockplotr and asar packages consume, so
Rceattle results can be plotted and written into a report by the same tools
used for SS3, BAM, WHAM and FIMS.
standard_output(x, species = NULL, model = NULL)standard_output(x, species = NULL, model = NULL)
x |
An |
species |
Which stock to emit: a species name, or an index into the species this report holds, required when it holds more than one. |
model |
Which model to emit when |
Quantity names are translated through the standard_label column of
quantity_dictionary(), so ssb becomes spawning_biomass, R becomes
recruitment, F_spp becomes fishing_mortality, and so on. A quantity the
standard has no name for keeps its Rceattle name, so nothing is silently
dropped.
The standard has no species dimension. It describes one stock, so a
multispecies CEATTLE fit cannot be represented in it as a whole. A species
column is held alongside the standard columns and species selects one
stock; with several species in the fit and no selection, this errors rather
than returning a frame in which two stocks' biomass share a year.
era follows the standard's own vocabulary: "time" for the hindcast the
model was fit to, "fore" for the projection.
A data frame with the standardized columns, in the standard's own
order, plus species and model.
report_tables() for the native tables and
quantity_dictionary() for the name crosswalk.
## Not run: fit <- fit_mod(data_list = BS2017SS, estimateMode = 1) std <- standard_output(fit, species = 1) # ...then, with the stockplotr package installed: # stockplotr::plot_spawning_biomass(std) ## End(Not run)## Not run: fit <- fit_mod(data_list = BS2017SS, estimateMode = 1) std <- standard_output(fit, species = 1) # ...then, with the stockplotr package installed: # stockplotr::plot_spawning_biomass(std) ## End(Not run)
Compact summary method for Rceattle fits
## S3 method for class 'Rceattle' summary(object, ...)## S3 method for class 'Rceattle' summary(object, ...)
object |
An object of class |
... |
Currently unused. |
Function to check for missing switches for map and parameter functions
switch_check(data_list)switch_check(data_list)
data_list |
Rceattle data list |
TMBAIC calculates AIC for a given model fit
TMBAIC(opt, p = 2, n = Inf)TMBAIC(opt, p = 2, n = Inf)
opt |
the output from |
p |
the penalty on additional fixed effects (default=2, for AIC) |
n |
the sample size, for use in AICc calculation (default=Inf, for which AICc=AIC) |
AIC, where a parsimonious model has a AIC relative to other candidate models
Fits a TMB model in phases, like ADMB: parameters are switched on in stages
rather than all at once, which stabilizes a difficult optimization. The
optimizer (nlminb by default) runs once per phase; at each phase the map holds
fixed any parameter whose phase is greater than the current phase, so
parameters turn on progressively as the phase counter advances. phases is a
tagged list giving each named parameter its integer phase; parameters not
listed are estimated from the first phase onward.
TMBphase( data, parameters, map, random, phases, model_name, silent, use_gradient = TRUE, control = list(eval.max = 1e+09, iter.max = 1e+09, trace = 0) )TMBphase( data, parameters, map, random, phases, model_name, silent, use_gradient = TRUE, control = list(eval.max = 1e+09, iter.max = 1e+09, trace = 0) )
data |
A list to be passed to TMB |
parameters |
A list of parameters of the model |
map |
a list of map object from the model |
random |
A character vector of names of parameters that are random effects |
phases |
Tagged list assigning each named parameter its integer phase (as returned by |
model_name |
A string describing the model name. Must be the name of your .cpp file |
silent |
logical. Suppress TMB's output. No default; phased fits set it. |
use_gradient |
logical. If TRUE, uses gradient in optimization (default = TRUE). |
control |
A list of control parameters. For details see |
The parameter list estimated in the final phase, with a per-phase convergence log attached as the phase_log attribute.
Gavin Fay https://github.com/kaskr/TMB_contrib_R/blob/master/TMBphase/R/TMBphase.R
Returns the fixed-effect covariance matrix produced by
TMB::sdreport(). Random-effect covariance is not returned here,
use object$sdrep for the full report.
## S3 method for class 'Rceattle' vcov(object, ...)## S3 method for class 'Rceattle' vcov(object, ...)
object |
An object of class |
... |
Currently unused. |
A numeric matrix, or NULL if sdreport was not run
(i.e. the fit was produced with getsd = FALSE).
A data list containing inputs for a CEATTLE model that uses growth
estimated from the Woods Hole Assessment Model (WHAM). See
BS2017SS for format details. Its two 2DAR1 fleets ship with
Time_varying_sel_sd = 0 and no N_sel_bins, so
data_check() refuses it as shipped; the vignettes set a different
selectivity before fitting.
whamGrowthDatawhamGrowthData
A list with the same structure as BS2017SS.
Write a data list to a CEATTLE xlsx workbook
write_data(data_list, file = "Rceattle_data.xlsx")write_data(data_list, file = "Rceattle_data.xlsx")
data_list |
Rceattle data_list object |
file |
Filename to write. Must end in '.xlsx' |
build_data() to assemble or edit a data list in R, read_data()
to read one back. A model_config() slot is not written to the
workbook and does not survive the round-trip (a warning is issued); persist
it separately with save_config() / load_config().
library(Rceattle) data(BS2017SS) out_file <- file.path(tempdir(), "BS2017SS.xlsx") write_data(data_list = BS2017SS, file = out_file) file.remove(out_file)library(Rceattle) data(BS2017SS) out_file <- file.path(tempdir(), "BS2017SS.xlsx") write_data(data_list = BS2017SS, file = out_file) file.remove(out_file)
Emits a small, structurally complete single-species workbook, one survey
and one fishery, flat placeholder data, that a user can open and edit as a
starting point. fleet_control is built on the canonical column names with
schema defaults filled by switch_check, so the template is
always in sync with the current schema. The template round-trips through
read_data and data_check and builds under
fit_mod(estimateMode = 3); replace the placeholder observations with
real data before fitting.
write_template( file = "Rceattle_data_template.xlsx", nages = 10, nyrs = 30, nprojyrs = 12, minage = 1 )write_template( file = "Rceattle_data_template.xlsx", nages = 10, nyrs = 30, nprojyrs = 12, minage = 1 )
file |
Output path for the |
nages |
Number of ages to template (default 10). |
nyrs |
Number of hindcast years (default 30). |
nprojyrs |
Number of projection years beyond the hindcast (default 12). |
minage |
Minimum age (recruitment age; default 1). |
Invisibly, the minimal data_list that was written.
f <- file.path(tempdir(), "template.xlsx") dat <- write_template(f, nages = 8, nyrs = 20) # The workbook is correctly shaped but holds placeholder observations; # data_requirements() reports what a given configuration still needs. head(data_requirements(dat), 4) unlink(f)f <- file.path(tempdir(), "template.xlsx") dat <- write_template(f, nages = 8, nyrs = 20) # The workbook is correctly shaped but holds placeholder observations; # data_requirements() reports what a given configuration still needs. head(data_requirements(dat), 4) unlink(f)