Package 'Rceattle'

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: 4.5.0
Built: 2026-06-10 02:51:24 UTC
Source: https://github.com/grantdadams/Rceattle

Help Index


Helper to adjust map for shared catchability/selectivity indices

Description

Enforces parameter sharing by mapping parameters for fleets with a common Selectivity_index or Q_index to the same value as the initial index.

Usage

adjust_map_shared_params(map_list, data_list)

Arguments

map_list

The current TMB map list.

data_list

The data list containing model settings.

Value

Updated map_list.


Tidy long-format derived quantities from an Rceattle fit

Description

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.

Usage

## 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,
  ...
)

Arguments

x

An object of class "Rceattle" returned by fit_mod().

row.names, optional

Ignored; present for the as.data.frame() generic.

which

Character vector of quantity names to extract, or "all" for every quantity with a known shape. Defaults to a common population-level summary. See names(Rceattle:::.RCEATTLE_QUANTITIES) for the full list.

ci_level

Confidence level for lwr and upr. Default 0.95.

...

Currently unused.

Details

Standard errors (se) and confidence intervals (lwr, upr) are populated from the TMB sdreport for any quantity that was ADREPORT'd (currently biomass, ssb, R); other quantities and fits produced with getsd = FALSE get NA for se / lwr / upr. Set ci_level to widen or narrow the band.

Value

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.


Data inputs for Atka mackerel CEATTLE model (2022)

Description

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.

Usage

Atka2022

Format

A list with the same structure as BS2017SS.


Data inputs for multispecies CEATTLE of the Bering Sea from 1979 to 2017

Description

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.

Usage

BS2017MS

Format

A list with the same structure as BS2017SS.


Data inputs for single species CEATTLE of the Bering Sea from 1979 to 2017

Description

A dataset containing the inputs used for CEATTLE

Usage

BS2017SS

Format

Control

nspp

Number of species included in CEATTLE

styr

Start year of the hindcast

endyr

End year of the hindcast

projyr

End year of the forecast

nsex

Number of sexes to model in the population (1 = combined/1sex, 2 = models both female/male)

spawn_month

Spawning month of the population to adjust the numbers spawning

R_sexr

Percent of recruitment that is female (ignored if nsex = 1)

nages

Number of ages of each species included in the hindcast

minage

Minimum age for each population (i.e.does recruitment correspond to age 0, 1, 2?)

nlengths

Number of lengths of each species included in the hindcast

pop_wt_index

Weight-at-age (weight) index to use for calculation of each species population derived quantities (SSB, Consumption/Ration, Suitability, etc)

ssb_wt_index

Weight-at-age (weight) index to use for calculation of each species spawning biomass

pop_age_transition_index

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)

sigma_rec_prior

Standard deviation to use for recruitment

other_food

Other food in the ecosystem for each species

estDynamics

Estimate or fix numbers-at-age: 0 = estimate dynamics, 1 = use input numbers-at-age in NbyageFixed, 2 = multiply input numbers-at-age (NbyageFixed) by a single scaling coefficient, 3 = multiply input numbers-at-age (NbyageFixed) by age specific scaling coefficient.

est_M1

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.

fleet_control

Survey and fishery data specifications

index_data

Survey index in weight (kg) or numbers data

catch_data

Total catch in weight (kg) or numbers data

comp_data

Survey/fishery age or length composition data. Note if sex is 3, put female composition data then male composition data (similar to SS).

emp_sel

Empirical/fixed selectivity for surveys and fisheries (leave empty if not used)

age_trans_matrix

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.

age_error

Aging error matrices. Can have only one per species.

weight

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

Maturity-at-age for each species

sex_ratio

Percent female at age for each species

M1_base

Residual natural mortality for each species

aLW

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)

Ceq

Which bioenergetics equation to use for each species for ft to scale max consumtion: 1 = Exponential (Stewart et al 1983), 2 = Temperature-dependendence 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)

Cindex

Which environmental index in env_data to use to drive bioenergetics

Pvalue

This scales the maximum consumption used for ration for each species; Pvalue is in CmaxfTPvalue*ration_data

fday

Number of foraging days per year for each species

CA

Intercept of allometric mass function for calculating maximum consumption: CA * Weight ^ CB

CB

Slope of allometric mass function for calculating maximum consumption: CA * Weight ^ CB

Qc

Parameter for temperature scaling function of maximum consumption specified by Ceq

Tco

Parameter for temperature scaling function of maximum consumption specified by Ceq

Tcm

Parameter for temperature scaling function of maximum consumption specified by Ceq

Tcl

Parameter for temperature scaling function of maximum consumption specified by Ceq

CK1

Parameter for temperature scaling function of maximum consumption specified by Ceq

CK4

Parameter for temperature scaling function of maximum consumption specified by Ceq

env_data

Environmental indices such as bottom temperature data to incorporate into ration equation specificed by Ceq and Cindex. Also used to drive catchability if Catchability = 5. Will use the mean for missing years. Temperature should be in celcius.

ration_data

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.

UobsAge

Stomach proportion by numbers for each predator, prey, predator age, prey age combination. Can also be year specific by including the column, "Year"

UobsWtAge

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

Fleet_name

Name of survey or fishery

Fleet_code

Index of survey/fishery ACROSS species

Fleet_type

0 or 'Off' = Do not estimate; 1 = 'Fishery'; 2 = 'Survey'

Species

Species number

Selectivity_index

index to use if selectivities of different surveys are to be the same

Selectivity

Selectivity to use for the species: 0 = "Fixed"; 1 = "Logistic"; 2 = "NonParametric" sensu Ianelli et al 2018; 3 = "DoubleLogistic"; 4 = "DescendingLogistic"; 5 = "Hake" non-parametric sensu Taylor et al; 6 = "2DAR1"; 7 = "3DAR1" sensu Cheng et al 2024; 8 = "DoubleNormal" (Gaussian ascending and descending limbs blended at a common peak — similar to SS3 pattern 24). Parameters: sel_inf[1] = peak bin/length; sel_inf[2] = logit(right_floor), right-tail floor analogous to SS3 P6/end_logit (logit=-10 → dome-shaped, logit=+10 → logistic ascending-only); log_sel_slp[1] = log(sigma_ascending); log_sel_slp[2] = log(sigma_descending). Supports the same time-varying modes as DoubleLogistic (IID, Block, RandomWalk).

Selectivity_dimension

"Age" or "Length".

Nselages

Number of ages to estimate non-parametric selectivity.

Time_varying_sel

Whether a time-varying selectivity should be estimated for logistic, double logistic selectivity, or descending logistic. 0 = "Off", 1 = "IID" penalized deviates given sel_sd_prior or random effect, 2 = "AR1" (TODO), 3 = "Block" time blocks with no penalty, 4 = "RandomWalk" following Dorn, 5 = "RandomWalkAscending" on ascending portion of double logistic only.

Time_varying_sel_sd_prior

The fixed or initial sd to use for time varying selectivity.

Bin_first_selected

Age/length bin at which selectivity is non-zero

Acuumulation_age_lower

Ages below this will be grouped to this age for composition data. For example, if set to 2, comp data for age 2 will include 1 and 2 year olds.

Acuumulation_age_upper

Ages above this will be grouped to this age for composition data. For example, if set to 9 for a species with 10 ages, comp data for age 9 will include 9 and 10 year olds.

weight1_Numbers2

Is the observation in weight (kg) set as 1, if the observation is in numbers caught, set as 2

Weight_index

Weight-at-age (weight) index to use for calculation of derived quantities

Age_transition_index

Age transition matrix (e.g. growth trajectory) index to use for derived quantities to convert age to length

Q_index

index to use if catchability coefficients are to be set the same

Catchability

Estimate catchability? (0 or "Fixed" = fixed at prior; 1 or "Estimated" = Estimate single parameter; 2 or "Estimated-with-prior" = Estimate single parameter with prior; 3 or "Analytical" = Estimate analytical q from Ludwig and Walters 1994; - 4 = Estimate power equation; - 5 or "Environmental" = Linear equation log(q_y) = q_mu + beta * index_y; 6 or "AR1" = annual AR1 catchability deviates are fit to environmental index sensu Rogers et al 2025)

Q_prior

Starting value or fixed value for catchability

Q_sd_prior

Variance of q prior: dnorm (log_q, log_q_prior, q_sd_prior)

Time_varying_q

Whether a time-varying q should be estimated. 0 = "Off", 1 = "IID" penalized deviate or random effect, 2 = "AR1" (TODO), 3 = "Block" time blocks with no penalty; 4 = "RandomWalk" random walk from mean following Dorn 2018 (dnorm(q_y - q_y-1, 0, sigma). If Catchability = 5 or 6, this determines the environmental index to be used in the equation log(q_y) = q_mu + beta * index_y

Time_varying_q_sd_prior

The sd to use for the random walk of time varying q if set to 1

Estimate_survey_sd

Estimate survey variance (0 = use CV from index_data, 1 = yes, 2 = analytically estimate following (Ludwig and Walters 1994)

Survey_sd_prior

Starting value to be used if Estimate_sigma_index = 1

Estimate_catch_sd

Estimate fishery variance (0 = use CV from index_data, 1 = yes, 2 = analytically estimate following (Ludwig and Walters 1994)

Catch_sd_prior

Starting value to be used if Estimate_sigma_catch = 1

Comp_weights

Composition weights to be used for multinomial likelihood. These are multiplied. After running model, these will update to McAllister & Ianelli 1997 weights using the harmonic mean.

Catch_units

Units used for survey: 1 = kg; 2 = numbers

proj_F_prop

The proportion of future fishing mortality assigned to this fleet

Sex

sex codes: 0=combined; 1=use female only; 2=use male only; 3 = joint female and male


Build parameter bounds

Description

Function to build parameter bounds based on Holsman et al 2015 and Kinzey and Punt 2010

Usage

build_bounds(param_list = NULL, data_list)

Arguments

param_list

Parameter list object built from build_params

data_list

a Rceattle data object

Value

List of upper and lower bounds


Specify the growth model for Rceattle

Description

Specify the growth model for Rceattle

Usage

build_growth(fun = "empirical", growth_age_L1 = NA, linkages = NULL)

Arguments

fun

Growth function. Either a string (GROWTH_FUNS: "empirical" (default), "vonBertalanffy", "Richards") or the equivalent integer code (0, 1, 2). The canonical string form is stored on the returned object.

growth_age_L1

Von Bertalanffy / Richards anchor age (the age at which mean length equals L1). Matches SS3's Growth_Age_for_L1 control input. Scalar (recycled across species) or a length-nspp vector for per-species values. Default NA inherits data_list$growth_age_L1 if supplied (e.g. from the SS3 converter), otherwise falls back to max(0.5, minage[sp]) so minage >= 1 models stay backwards-compatible and minage = 0 models pick up an SS3-consistent half-year anchor.

linkages

Optional named list of linkage_spec() objects keyed by parameter name (must be one of GROWTH_LINKAGE_PARAMS). The mean-growth keys (K, L1, Linf, m) accept arbitrary one-sided formulas and produce year-varying offsets applied inside growth.hpp. The SD-endpoint keys (sd_L1, sd_Linf) only honor intercept-bearing formulas (typically ~ 1) – they thread init, bounds, and priors onto the underlying growth_log_sd parameter, giving the SDs the same prior/fix/initial-value contract as the mean parameters. Slope rows on SD specs raise a warning and have no effect; slope-only formulas (~ 0 + temp) error. Materialization into the global linkage table happens inside fit_mod() once data_list$env_data is in scope.

Value

A list of switches defining the growth model.

Examples

## Not run: 
# 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))
    )
  )
)

## End(Not run)

Specify the harvest control rule (HCR) used for Rceattle

Description

Defines the harvest control rule and associated reference points used in the Rceattle model.

Usage

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
)

Arguments

HCR

Harvest control rule to use. Accepts an integer or equivalent string alias. Default = 0. See Details for the full list of available options.

DynamicHCR

TRUE/FALSE. Whether to use static or dynamic reference points (default = FALSE).

Ftarget

Target fishing mortality rate (yr^-1) (SPR or depletion based) or input F for projections. For example, if Ftarget is spr F40%, enter 0.40.

Flimit

Limit fishing mortality rate (yr^-1) (SPR or depletion based). For example, if Flimit is spr F35%, enter 0.35.

Ptarget

Target spawning-stock biomass as a percentage of static or dynamic spawning-stock-biomass at F = 0 (accounts for recruitment).

Plimit

Limit spawning-stock biomass as a percentage of static or dynamic spawning-stock-biomass at F = 0 (accounts for recruitment).

Alpha

Parameter used in NPFMC Tier 3 HCR.

Pstar

Quantile used for uncertainty buffer given Flimit and Sigma.

Sigma

Standard deviation used for normally distributed uncertainty buffer given Flimit and Pstar.

Fmult

Multiplier on the target F (default = 1). Used to scale the target fishing mortality following NEFSC convention.

HCRorder

For multi-species models, the order in which to project fishing (e.g., predators first, then prey).

Details

Harvest control rule formulations currently implemented in Rceattle:

hcr = 0 or "NoFishing": No catch. Estimate the hindcast.

hcr = 1 or "CMSY": CMSY. Maximize catch across all species simultaneously. CMSY can be constrained such that depletion does not fall below Plimit.

hcr = 2 or "ConstantF": Constant input F set at Ftarget for each species (vector or single F). SPR (single-species only) based Flimit is specified via Flimit.

hcr = 3 or "ConstantFSSB": F that achieves Ftarget% of SSB0 in the end of the projection.

hcr = 4 or "ConstantFSPR": Constant Fspr set at Ftarget for each species. Can be multiplied by Fmult following NEFSC.

hcr = 5 or "NPFMC": The North Pacific Fishery Management Council (NPFMC) Tier 3 spawner-per-recruit-based harvest control rule: Stock status: SB>SBatFtargetSB > SB at Ftarget

Fofl=FlimitFofl = Flimit

Fuse=FtargetFuse = Ftarget

Stock status: Alpha<SB/SBatFtarget1Alpha < SB / SB at Ftarget \le 1

Fofl=Flimit(SB/PtargetAlpha)/(1Alpha)Fofl = Flimit * (SB / Ptarget - Alpha) / (1 - Alpha)

Fuse=Ftarget(SB/PtargetAlpha)/(1Alpha)Fuse = Ftarget * (SB / Ptarget - Alpha) / (1 - Alpha)

Stock status: SB/SBatFtargetAlphaSB / SB at Ftarget \le Alpha or SB<PlimitSB0SB < Plimit * SB0

Fofl=0Fofl = 0

Fuse=0Fuse = 0

hcr = 6 or "PFMC": An HCR based on the The Pacific Fishery Management Council (PFMC) category 1 40-10 annual catch limit (ABC) harvest control rule assuming Fofl is normally distributed with a standard deviation (sigma) = 0.5 and an uncertainty quantile buffer (P*) of 0.45 (PFMC 2020). The model uses Fspr if single-species or F that achieves X% of SSB0 for multi-species. Target biological reference points are calculated based on the normal cumulative distribution function (Phi(quantile,mean,standard deviation)), P*, and sigma as follows: Stock status: SB>SB0PtargetSB > SB0 * Ptarget

Fofl=FlimitFofl = Flimit

Fuse=Phi(Pstar,Flimit,Sigma)Fuse = Phi(Pstar, Flimit, Sigma)

Stock status: SB0Plimit<SBSB0PtargetSB0 * Plimit < SB \le SB0 * Ptarget

Fofl=FlimitFofl = Flimit

Fuse=Phi(Pstar,Flimit,Sigma)SB0Ptarget(SBSB0Plimit)SBSB0(PtargetPlimit)Fuse = Phi(Pstar, Flimit, Sigma) * \frac{SB0 * Ptarget * (SB - SB0 * Plimit)}{SB * SB0 * (Ptarget - Plimit)}

Stock status: SB<SB0PlimitSB < SB0 * Plimit

Fofl=0Fofl = 0

Fuse=0Fuse = 0

hcr = 7 or "SESSF": An HCR based on the The Southern and Eastern Scalefish and Shark Fishery (SESSF) spawner-per-recruit-based Tier 1 harvest control rule where F_Limit=F_(20%), B_Limit=SB_20, F_Target (AFMA 2017) calculated as follows: Stock status: SB>SB0PtargetSB > SB0 * Ptarget

Fofl=FlimitFofl = Flimit

Fuse=FtargetFuse = Ftarget

Stock status: Ptarget>SB>SB0PlimitPtarget > SB > SB0 * Plimit

Fofl=Flimit(SB/(SB0Ptarget)1)Fofl = Flimit * (SB / (SB0 * Ptarget) - 1)

Fuse=Ftarget(SB/(SB0Ptarget)1)Fuse = Ftarget * (SB / (SB0 * Ptarget) - 1)

Stock status: SB<SB0PlimitSB < SB0 * Plimit

Fofl=0Fofl = 0

Fuse=0Fuse = 0

NOTE: only HCRs 1, 2, 3, and 6 will work in multi-species mode.

Value

A list containing the harvest control rule and associated biological reference points.


Function to construct the TMB map argument for CEATTLE for projecting under alternative harvest control rules

Description

Reads a data list and map to update the map argument based on the HCR specified in build_hcr

Usage

build_hcr_map(
  data_list,
  map,
  debug = FALSE,
  all_params_on = FALSE,
  HCRiter = 1
)

Arguments

data_list

an Rceattle data_list

map

a map object created from build_map.

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)

Value

a list of map arguments for each parameter


Define M1 specifications

Description

Define M1 specifications

Usage

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
)

Arguments

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):

  • 0 / "fixed" – use the input M1_base (no estimation).

  • 1 / "sex_age_invariant" – estimate one ⁠M1_{spp}⁠.

  • 2 / "sex_specific" – estimate ⁠M1_{spp, sex}⁠.

  • 3 / "sex_age_specific" – estimate ⁠M1_{spp, sex, age}⁠.

  • 4, 5 – soft-deprecated env-driven codes; use the linkages argument instead. See vignette("environmental-linkages-and-priors").

M1_re

Vector or scalar specifying the M1 random-effects model. Either an integer code or the equivalent string alias: 0 / "none", 1 / "iid_age", 2 / "iid_year", 3 / "iid_age_year", 4 / "ar1_age", 5 / "ar1_year", 6 / "ar1_age_year".

updateM1

If using initial parameters, use M1 fixed effects from data (M1_base) instead. Default FALSE.

M1_use_prior

Vector or scalar; if TRUE, apply the lognormal M_prior / M_prior_sd to M1 directly.

M2_use_prior

Vector or scalar; if TRUE, apply the lognormal prior to M1 + M2 in multi-species models.

M_prior

Mean (natural-scale) of the lognormal prior on M.

M_prior_sd

SD (log-scale) of the lognormal prior on M.

M1_indices

Soft-deprecated. Vector of column indices into env_data (excluding Year) for environmentally linked M1 when M1_model %in% c(4, 5). Use the linkages argument instead; see vignette("environmental-linkages-and-priors").

linkages

Optional named list of linkage_spec() objects keyed by M parameter name (currently the only valid key is "M1"). Each spec describes how M1 depends on environmental covariates and on stratifying factors (species, sex, age). The offset enters additively (on the log scale) inside the M1_at_age compute. A row's age_bin == NA broadcasts the offset across ages; specific values pin it to that age slice.

Value

A list of switches for defining the M1 model.

Examples

## Not run: 
# 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))
    )
  )
)

## End(Not run)

Main function to construct the TMB map argument for CEATTLE

Description

Orchestrates the building of the TMB map object by calling specialized helper functions for each parameter block (Recruitment, M1, Predation, Selectivity, Catchability, etc.).

Usage

build_map(
  data_list,
  params,
  debug = FALSE,
  random_rec = FALSE,
  random_sel = FALSE
)

Arguments

data_list

an Rceattle data_list

params

A parameter list created from build_params.

debug

Logical. If TRUE, sets all map values to NA except the dummy parameter, running the model without parameter estimation.

random_rec

Logical. If TRUE, treats recruitment deviations as random effects, meaning the variance parameter (R_log_sd) is estimated.

random_sel

Logical. If TRUE, treats selectivity deviations as random effects, meaning the variance parameter (sel_dev_log_sd) is estimated.

Value

A list containing the factorized TMB map (mapFactor) and the original map matrix/array list (mapList).


Helper to set map for Catchability parameters

Description

Maps survey catchability base parameters (index_log_q), time-varying deviations (index_q_dev), and environmental linkages (index_q_beta, index_q_rho).

Usage

build_map_catchability(map_list, data_list, nyrs_hind)

Arguments

map_list

The current TMB map list.

data_list

The data list containing model settings.

nyrs_hind

Number of historical years.

Value

Updated map_list.


Helper to set map for debug mode

Description

Sets all parameters in the map list to NA, except the dummy parameter, for use in debug or testing modes.

Usage

build_map_debug(map_list, debug)

Arguments

map_list

The current TMB map list.

debug

Logical. If TRUE, debug mode is activated.

Value

Updated map_list.


Helper to set map for Fishing Mortality and Data Weights

Description

Maps fishing mortality parameters (log_F) and related targets. Also maps data weighting parameters (catch_log_sd, comp_weights, caal_weights).

Usage

build_map_f_and_data_weights(map_list, data_list, nyrs_hind)

Arguments

map_list

The current TMB map list.

data_list

The data list containing model settings.

nyrs_hind

Number of historical years.

Value

Updated map_list.


Helper to set map for Fixed N-at-Age models

Description

Turns off (sets to NA) most population and fleet parameters for species where the dynamics are fixed (estDynamics > 0).

Usage

build_map_fixed_natage(map_list, data_list)

Arguments

map_list

The current TMB map list.

data_list

The data list containing model settings.

Value

Updated map_list.


Helper to set map for growth parameters

Description

Maps the fixed parameters (log_growth_pars) and the random effects parameters (log_growth_par_devs, growth_dev_log_sd, growth_rho) based on growth_model and growth_re settings.

Usage

build_map_growth(map_list, data_list, nyrs_hind)

Arguments

map_list

The current TMB map list.

data_list

The data list containing model settings.

nyrs_hind

Number of historical years.

Value

Updated map_list.


Helper to set map for Natural Mortality (M1) parameters

Description

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.

Usage

build_map_m1(map_list, data_list, nyrs_hind)

Arguments

map_list

The current TMB map list.

data_list

The data list containing model settings.

nyrs_hind

Number of historical years.

Value

Updated map_list.


Helper to set map for Predation Mortality (M2) parameters

Description

Maps predation suitability parameters (log_gam_a, log_gam_b, log_phi) and diet weight parameters based on msmMode and suitMode.

Usage

build_map_predation(map_list, data_list)

Arguments

map_list

The current TMB map list.

data_list

The data list containing model settings.

Value

Updated map_list.


Helper to set map for Recruitment parameters

Description

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,

Usage

build_map_recruitment(map_list, data_list, nyrs_hind, nyrs_proj, random_rec)

Arguments

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.

Value

Updated map_list.


Helper to set map for Selectivity parameters

Description

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.

Selectivity in fleet_control of the data determines shape of selectivity curve: 0 = "Fixed" empirical selectivity provided in emp_sel in the data 1 = "Logistic" 2 = "NonParametric" selecitivty sensu Ianelli et al 2018 3 = "DoubleLogistic" 4 = "DescendingLogistic" 5 = "Hake" non-parametric selectivity sensu Taylor et al 2014 (Hake) 6 = "2DAR1" across age x year 7 = "3DAR1" across age x cohort x year (Cheng et al 2024) 8 = "DoubleNormal" Gaussian ascending/descending limbs blended at peak (analogous to SS3 pattern 24). Parameters: sel_inf[1] = peak; sel_inf[2] = logit(right_floor) (right-tail floor, SS3 P6/end_logit); log_sel_slp[1] = log(sigma_asc); log_sel_slp[2] = log(sigma_desc). right_floor→0: dome-shaped; right_floor→1: logistic ascending only.

N_sel_bins Number of age/length bins to estimate non-parametric selectivity when Selectivity = 2 or 5. Not used otherwise

Time_varying_sel determines if time-varying selectivity should be estimated for logistic, double logistic selectivity, descending logistic , non-parametric, or hake (Selectivity = 1, 2, 3, 4, or 5). 0 = 'None' 1 = 'IID' penalized deviates given sel_sd_prior 3 = 'Block' time blocks with no penalty 4 = 'RandomWalk' random walk following Dorn 5 = 'RandomWalkAscending' random walk on ascending portion of double logistic only. random_sel in fit_mod treats random deviates and random walk parameters as random effects, estimating the variance.

Usage

build_map_selectivity(map_list, data_list, nyrs_hind, random_sel)

Arguments

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.

Value

Updated map_list.


Build parameter list from cpp file

Description

Function to read a TMB cpp file and construct parameter list object for Rceattle

Usage

build_params(data_list)

Arguments

data_list

an Rceattle data_list

Value

a list of map arguments for each parameter


Specify the stock-recruit relationship (SRR) for Rceattle

Description

Stock recruitment relationships currently implemented in Rceattle:

  • srr_fun = 0 or "mean": No stock recruit relationship. Recruitment is a function of R0 and annual deviates (i.e. steepness = 0.99).

    Ry=exp(R0+Rdev,y)R_y = exp(R0 + R_{dev,y})

  • srr_fun = 2 or "BevertonHolt": Beverton-holt stock-recruitment relationship

    Ry=αsrrSByminage1+βsrrSByminageR_y = \frac{\alpha_{srr} * SB_{y-minage}}{1+\beta_{srr} * SB_{y-minage}}

  • srr_fun = 4 or "Ricker": Ricker stock-recruitment relationship

    Ry=αsrrSByminageexp(βsrrSByminage)R_y = \alpha_{srr} * SB_{y-minage} * exp(-\beta_{srr} * SB_{y-minage})

When srr_pred_fun > 0 and srr_fun = 0 recruitment in the hindcast is estimated as in srr_fun = 0

Ry=exp(R0+Rdev,y)R_y = exp(R0 + R_{dev,y})

, but an additional stock recruitment relationship defined by srr_pred_fun is estimated between srr_hat_styr and srr_hat_endyr and treated as an additional penalty. The stock recruitment relationship defined by srr_pred_fun is then used in the projection.

Usage

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_indices = NA,
  Bmsy_lim = NA,
  linkages = NULL
)

Arguments

srr_fun

Stock recruit function to be used for hindcast estimation of Rceattle (see @description below). Default = 0

srr_pred_fun

stock recruit function for projection, reference points, and penalties to be used for Rceattle (see below). When srr_fun == 0, it treats the stock-recruit curve as an additional penalty onto the annualy estimated recruitment from the hindcast (sensu AMAK and Jim Ianelli's pollock model). If srr_fun > 0 then srr_pred_fun = srr_fun and no additional penalty is included.

proj_mean_rec

Project the model using: 0 = mean recruitment (average R of hindcast) or 1 = SRR(omega, srr_devs)

srr_mse_switchyr

is used for MSEs to deal with AMAK and Jim Ianelli's estimation where a stock recruit function is estimated as an additional penalty (srr_fun = 0 and srr_pred_fun > 0). It tells the model in what year to switch to the stock recruit function.

srr_hat_styr

Integer. The first year used for estimating the recruitment function as an additional penalty. It will add additional penalties sensu AMAK and Jim Ianelli's pollock model when srr_pred_fun > 0 and srr_fun = 0, starting at styr + 1. Defaults to $styr + 1$ in $data_list$. Useful if environmental data used to condition stock-recruit relationships is not available until end-year, but projections are desired.

srr_hat_endyr

Integer. The last year used for estimating the recruitment function as an additional penalty. It will add an additional penalties sensu AMAK and Jim Ianelli's pollock model when srr_pred_fun > 0 and srr_fun = 0. Recruitment Defaults to $endyr$ in $data_list$. Useful if environmental data used to condition stock-recruit relationships is not available for the full time-series, but projections are desired.

srr_est_mode

Switch to determine estimation mode. 0 = fix alpha to prior mean, 1 = freely estimate R0, alpha, and/or beta (default), 2 = use lognormally distributed prior for alpha (Ricker) or steepness (Beverton), 3 = use beta distributed prior for steepness (Beverton) given mean and sd.

srr_prior

mean for normally distributed prior for stock-recruit parameter

srr_prior_sd

Prior standard deviation for stock-recruit parameter

srr_indices

Soft-deprecated. Use the linkages argument instead. See vignette("environmental-linkages-and-priors").

Bmsy_lim

Upper limit for Ricker based SSB-MSY (e.g 1/Beta). Will add a likelihood penalty if beta is estimated above this limit. Default NA is not used.

linkages

Optional named list of linkage_spec() objects keyed by recruitment parameter name (must be one of "R0", "alpha", "beta"). Each spec describes how that parameter depends on environmental covariates and on stratifying factors (species, sex). The offset enters additively (on the log scale) inside the recruitment compute. See vignette("environmental-linkages-and-priors") for details.

Value

A list containing the stock recruitment relationship settings


Function to load .RDs files from MSE runs

Description

Function to load .RDs files from MSE runs

Usage

check_mse(dir = NULL, file = NULL)

Arguments

dir

Directory used to save files from run_mse

file

file name used to save files from run_mse

Value

list of MSE simulations/run


Function to clean data prior to Rceattle runs

Description

Function to clean data prior to Rceattle runs

Usage

clean_data(data_list)

Arguments

data_list

Rceattle data list


Extract estimated parameters from an Rceattle fit

Description

Extract estimated parameters from an Rceattle fit

Usage

## S3 method for class 'Rceattle'
coef(object, ...)

Arguments

object

An object of class "Rceattle" returned by fit_mod().

...

Currently unused.

Value

A named numeric vector of estimated fixed-effect parameters (the optimizer's par). Returns NULL if the model was not estimated.


Combine data sets. Will use the env_data data set from data_set1 and diet data will have to be updated.

Description

Combine data sets. Will use the env_data data set from data_set1 and diet data will have to be updated.

Usage

combine_data(data_list1 = NULL, data_list2 = NULL)

Arguments

data_list1

Rceattle data_list 1

data_list2

Rceattle data_list 2


Evaluate simulation performance

Description

Function to evaluate the simulation performance with regard to bias using the median relative error (MRE) and precision using the coefficient of variation.

Usage

compare_sim(operating_mod, simulation_mods, object = "quantities")

Arguments

operating_mod

CEATTLE model object exported from Rceattle to be used as the operating model

simulation_mods

List of CEATTLE model objects exported from Rceattle fit to simulated data

object

character string specifying which part of the model to compare (default = "quantities")

Value

A data frame summarising simulation performance metrics


Convergence diagnostics for a fitted Rceattle model

Description

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.

Usage

convergence_diagnostics(object, ...)

Arguments

object

An object of class "Rceattle" returned by fit_mod().

...

Currently unused.

Details

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, Hessian positive-definiteness and conditioning, parameters on bounds, phasing, and parameter estimability.

Value

An object of class "Rceattle_convergence": a list with status (overall worst severity) and checks (named list of records).


Fitted multispecies CEATTLE model for the Eastern Bering Sea

Description

A fitted Rceattle model object for the multispecies run of CEATTLE for the Eastern Bering Sea (walleye pollock, Pacific cod, arrowtooth flounder).

Usage

EBS_ms_run

Format

An object of class Rceattle.


Fitted single-species CEATTLE model with estimated M for the Eastern Bering Sea

Description

A fitted Rceattle model object for the single-species run of CEATTLE for the Eastern Bering Sea with natural mortality estimated.

Usage

EBS_ss_M_run

Format

An object of class Rceattle.


Fitted single-species CEATTLE model for the Eastern Bering Sea

Description

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.

Usage

EBS_ss_run

Format

An object of class Rceattle.


Bundle the optimizer / sdreport / phasing controls for fit_mod()

Description

fit_mod() carries roughly a dozen optimizer- and reporting-related arguments (bias.correct, getsd, loopnum, newtonsteps, ...). That is a lot of surface area when the user mostly cares about "what model am I fitting" rather than "how is it being fit." fit_control() collects those knobs into a single object so calls to fit_mod() can stay focused on the model spec:

Usage

fit_control(
  bias.correct = FALSE,
  getsd = TRUE,
  getJointPrecision = TRUE,
  getReportCovariance = FALSE,
  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)
)

Arguments

bias.correct

logical. If TRUE, applies bias correction via TMB::sdreport(). Default FALSE.

getsd

logical. If TRUE, run TMB::sdreport() after optimization. Default TRUE.

getJointPrecision

logical. Return the full Hessian of fixed and random effects. Default TRUE (matches fit_mod() default).

getReportCovariance

logical. Return the variance-covariance of ADREPORT variables. Default FALSE.

use_gradient

logical. Use the analytic gradient during phasing. Default TRUE.

rel_tol

Numeric tolerance used to flag discontinuous likelihood warnings (compares the TMB and nlminb objectives). Default 1.

loopnum

Integer. Number of times to re-start optimization (loopnum = 3 sometimes achieves a lower final gradient than loopnum = 1). Default 5.

newtonsteps

Integer. Number of extra Newton steps to take after optimization (alternative to loopnum). Default 0.

phase

TRUE/FALSE or a list. If FALSE, the model is not phased. If TRUE, default phasing is used. Can also accept a list of parameter object names with corresponding phase. Default FALSE.

TMBfilename

Optional character. Path (without .cpp) to an alternate TMB template for development. Default NULL (use the bundled ceattle_v01_11).

verbose

0 = silent, 1 = print updates of model fit, 2 = print updates of model fit and TMB estimation progress. Default 1.

nlminb_control

A list of control parameters passed to stats::nlminb(). See ?nlminb. Default list(eval.max = 1e9, iter.max = 1e9, trace = 0).

Details

fit <- fit_mod(
  data_list   = BS2017SS,
  msmMode     = 0,
  fit_control = fit_control(loopnum = 1, getsd = FALSE)
)

Pass the result via the fit_control argument to fit_mod(). When supplied, the values in the fit_control object override the corresponding individual arguments to fit_mod(). Individual arguments are kept for backward compatibility.

Value

A list of class "Rceattle_fit_control".

Examples

# 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)

This function runs CEATTLE

Description

This function estimates population parameters of CEATTLE using maximum likelihood in TMB.

Usage

fit_mod(
  data_list = NULL,
  inits = NULL,
  map = NULL,
  bounds = NULL,
  file = NULL,
  estimateMode = 0,
  projection_uncertainty = FALSE,
  random_rec = FALSE,
  random_q = FALSE,
  random_sel = FALSE,
  HCR = build_hcr(),
  niter = 3,
  recFun = build_srr(),
  M1Fun = build_M1(),
  growthFun = build_growth(),
  msmMode = 0,
  avgnMode = 0,
  initMode = "NonEquilibrium",
  suitMode = 0,
  suit_styr = NULL,
  suit_endyr = NULL,
  fit_control = NULL,
  ...
)

Arguments

data_list

A data list read in via read_data or built directly in R; see vignette("data-without-excel", package = "Rceattle").

inits

(Optional) A named list of initial parameter values, as returned by build_params or extracted from a previous fit (model$estimated_params). If NULL, parameters are initialized from scratch via build_params.

map

(Optional) A map object from build_map.

bounds

(Optional) A bounds object from build_bounds.

file

(Optional) Filename where files will be saved. If NULL, no file is saved.

estimateMode

0 = Fit the hindcast model and projection with HCR specified via HCR. 1 = Fit the hindcast model only (no projection). 2 = Run the projection only with HCR specified via HCR given the initial parameters in inits. 3 = debug mode 1: runs the model through MakeADFun, but not nlminb, 4 = runs the model through MakeADFun and nlminb (will all parameters mapped out).

projection_uncertainty

logical. If TRUE, accounts for hindcast parameter uncertainty in projections when using an HCR. Default is FALSE for speed.

random_rec

logical. If TRUE, treats recruitment deviations as random effects using the laplace approximation.The default is FALSE.

random_q

logical. If TRUE, treats annual catchability deviations as random effects using the laplace approximation.The default is FALSE.

random_sel

logical. If TRUE, treats annual selectivity deviations as random effects using the laplace approximation.The default is FALSE.

HCR

HCR list object from build_hcr

niter

Number of iterations for multispecies model

recFun

The stock recruit-relationship parameterization from build_srr.

M1Fun

M1 parameterizations and priors. Use build_M1.

growthFun

The weight-at-age parameterization from build_growth.

msmMode

The predation mortality functions to used. Defaults to no predation mortality used.

avgnMode

The average abundance-at-age approximation to be used for predation mortality equations. 0 (default) is the N/Z(1exp(Z))N/Z ( 1 - exp(-Z) ), 1 is Nexp(Z/2)N exp(-Z/2), 2 is NN.

initMode

how the population is initialized. 0 = initial age-structure estimated as free parameters; 1 = equilibrium age-structure estimated out from R0 + mortality (M1); 2 = non-equilibrium age-structure estimated out from R0, mortality (M1), and initial population deviates; 3 = non-equilibrium age-structure estimated out from initial fishing mortality (Finit), R0, mortality (M1), and initial population deviates; 4 = non-equilibrium age-structure version 2 where initial fishing mortality (Finit) scales R0.

suitMode

Switch for suitability derivation for each predator (single value or vector). 0 = empirical based on diet data (Holsman et al. 2015), 1 = length-based gamma suitability, 2 = weight-based gamma suitability, 3 = length-based lognormal suitability, 4 = weight-based lognormal suitability, 5 = length-based normal suitability, 6 = weight-based normal suitability.

suit_styr

Integer. The first year used to calculate mean suitability. Defaults to $styr$ in $data_list$. Used when diet data were sampled from a subset of years.

suit_endyr

Integer. The last year used to calculate mean suitability. Defaults to $endyr$ in $data_list$. Used when diet data were sampled from a subset of years.

fit_control

A list returned by fit_control() that bundles the optimizer / sdreport / phasing knobs (phase, bias.correct, getsd, getJointPrecision, getReportCovariance, use_gradient, rel_tol, loopnum, newtonsteps, TMBfilename, verbose, nlminb_control). Defaults to fit_control(). See fit_control() for the meaning and defaults of each field.

...

Deprecated optimizer / sdreport / phasing arguments (e.g. phase, getsd, bias.correct, use_gradient, rel_tol, control, getJointPrecision, getReportCovariance, loopnum, newtonsteps, verbose, TMBfilename). These are forwarded into fit_control with a deprecation warning; pass them via fit_control() instead.

Details

CEATTLE is an age-structured population dynamics model that can be fit with or without predation mortality. The default is to exclude predation mortality by setting msmMode to 0. Predation mortality can be included by setting msmMode with the following options:

  • 0. Single species mode

  • 1. Holsman et al. 2015 predation based on multi-species virtual population analysis (MSVPA) based predation formation.

  • 2. MSVPA Holling Type III

Values 3 through 9 (Kinzey & Punt 2009 functional responses – Holling Type I/II/III, predator interference, predator preemption, Hassell-Varley, Ecosim) are blocked at runtime by data_check() because the implementations have not been validated against the current parameter set. See src/TMB/predation.hpp.

Value

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 exported by TMB including the standard errors of estimated parameters

  • estimated_params: List of estimated parameters

  • quantities: Derived quantities from CEATTLE

  • run_time: Model run time

Examples

data(BS2017SS)
ss_run <- fit_mod(
  data_list    = BS2017SS,
  estimateMode = 0,
  msmMode      = 0,
  fit_control  = fit_control(phase = FALSE, verbose = 0)
)

Data inputs for a three-species Georges Bank CEATTLE model

Description

A data list containing inputs for a multispecies CEATTLE model fit to three groundfish species on Georges Bank. See BS2017SS for format details.

Usage

GeorgesBank3spp

Format

A list with the same structure as BS2017SS.


Generate Length-at-Age Transition Matrix

Description

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.

Usage

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
)

Arguments

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

Numeric. The age at which growth enters the asymptotic phase.

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.

Value

A 4D array of probabilities with dimensions (sex, age, length, year).


Calculate Predicted Weight-at-Age

Description

Converts a growth matrix (length-at-age probabilities) into mean weight-at-age using a length-weight relationship (W = a * L^b).

Usage

get_weight_at_age_r(
  nsex_sp,
  nages_sp,
  nlengths_sp,
  nyrs,
  lengths_sp,
  length_at_age,
  growth_matrix,
  lw_params
)

Arguments

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

Details

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.

Value

A 3D array of mean weights with dimensions (sex, age, year).


Data inputs for a single-species Gulf of Alaska CEATTLE model (2018)

Description

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.

Usage

GOA2018SS

Format

A list with the same structure as BS2017SS.


Data inputs for Gulf of Alaska arrowtooth flounder CEATTLE model

Description

A data list containing inputs for a single-species CEATTLE model fit to Gulf of Alaska arrowtooth flounder data. See BS2017SS for format details.

Usage

GOAatf

Format

A list with the same structure as BS2017SS.


Data inputs for Gulf of Alaska arrowtooth flounder CEATTLE model (2023)

Description

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.

Usage

GOAatf2023

Format

A list with the same structure as BS2017SS.


Data inputs for Gulf of Alaska Pacific cod CEATTLE model

Description

A data list containing inputs for a single-species CEATTLE model fit to Gulf of Alaska Pacific cod data. See BS2017SS for format details.

Usage

GOAcod

Format

A list with the same structure as BS2017SS.


Data inputs for Gulf of Alaska walleye pollock CEATTLE model

Description

A data list containing inputs for a single-species CEATTLE model fit to Gulf of Alaska walleye pollock data. See BS2017SS for format details.

Usage

GOApollock

Format

A list with the same structure as BS2017SS.


Gulf of Alaska 2018 SAFE report reference values

Description

A list containing biomass, spawning stock biomass, and recruitment reference values from the 2018 Gulf of Alaska Stock Assessment and Fishery Evaluation (SAFE) report.

Usage

GOAsafe2018

Format

A list with components:

biomass

Total biomass time series

ssb

Spawning stock biomass time series

recruitment

Recruitment time series


Jitter analysis

Description

Run's the Rceattle model at initial values that are +- N(0, sd) from the initial parameters.

Usage

jitter(
  Rceattle = NULL,
  njitter = 50,
  sd = 0.2,
  phase = FALSE,
  seed = 123,
  cores = NULL
)

Arguments

Rceattle

an Rceattle model fit using fit_mod

njitter

the number of jitters to run

sd

standard deviation for jitter (default = 0.2)

phase

as in fit_mod default = FALSE

seed

random number seed. Each jitter i uses seed + i so results are reproducible under both sequential and parallel execution.

cores

Number of cores to use for parallel jitters. Default NULL picks parallel::detectCores() - 6, capped at 2 when running under R CMD check (which sets _R_CHECK_LIMIT_CORES_). Set to 1 to force sequential execution.

Value

a list of Rceattle models

Examples

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

Description

Capture a linkage specification

Usage

linkage_spec(
  formula,
  param = NULL,
  data = NULL,
  by = ~species,
  species = NULL,
  sex = NULL,
  link = "log",
  init = NULL,
  bounds = NULL,
  priors = NULL,
  re_group = NA_character_,
  est_phase = 1L
)

Arguments

formula

one-sided R formula whose RHS describes the linear predictor for param (e.g. ~ 1, ~ temp, ~ temp + PDO).

param

target parameter name on the natural scale (e.g. "alpha", "M1", "K"). May be NULL when the spec is built inside a ⁠build_*()⁠ call that infers the parameter name from the enclosing list key (see build_growth()).

data

(Optional) data frame for formula validation. Currently validation happens at materialization time inside fit_mod().

by

one-sided formula naming stratifying factors that should each get their own coefficients. Allowed names are species, sex, and age_bin. The default ~species produces one coefficient set per species (the typical multispecies assessment use case); pass ~species + sex for per-(species, sex) coefficients, or NULL to share a single coefficient set across every species/sex.

species

optional integer vector of 1-based species ids that this spec applies to. NULL (default) means every species in strata$species at materialization time. Use this to give different species different formulas, e.g. by registering multiple specs against the same parameter – see build_growth() for the multi-spec syntax.

sex

optional vector of sex ids that this spec applies to. May be supplied as integers (1L = female, 2L = male) or as character strings ("Females"/"Males", case-insensitive; "female", "male", "f", "m" are also accepted). NULL (default) means every sex in strata$sex at materialization time. Only meaningful when by includes sex; otherwise the filter is a no-op. Use this to register separate specs per sex (e.g. one prior on females, another on males) against the same parameter.

link

link function relating the linear predictor to the natural-scale target parameter. One of "log" (default) or "identity". With link = "log", log(param) = X * beta – slope contributions are multiplicative on the natural-scale parameter. With link = "identity", param = X * beta – slope contributions are additive on the natural scale. All linkage targets currently expose log-scale TMB parameters, so "log" is the natural default; "identity" is reserved for future processes (e.g. logit for steepness).

init

optional named numeric vector of initial values keyed by the design-matrix column name (e.g. ⁠c(⁠(Intercept)⁠ = 4, temp = 0)⁠). Missing entries default to 0.

bounds

optional named list of c(lower, upper) keyed the same way as init.

priors

optional named list whose entries are Rceattle_priors objects, keyed by design-matrix column name. Inside this argument the unprefixed shorthand normal(), lognormal(), gamma(), and beta() resolves to the corresponding ⁠prior_*⁠ constructors via a private data mask, so priors = list(temp = normal(0, 1)) works without masking base::gamma() or base::beta() at the package level. Equivalent to priors = list(temp = prior_normal(0, 1)).

re_group

optional character: name of a random-effect grouping for these coefficients. NA (default) means fixed.

est_phase

optional integer estimation phase. Default 1L.

Value

An Rceattle_linkage_spec object.


Function to load .RDs files from MSE runs

Description

Function to load .RDs files from MSE runs

Usage

load_mse(dir = NULL, file = NULL, exclude = NULL, include_em = TRUE)

Arguments

dir

Directory used to save files from run_mse

file

file name used to save files from run_mse

exclude

index of MSE simulations not to load

include_em

whether the EMs should be loaded or not (default = TRUE)

Value

list of MSE simulations/run


Log-likelihood of an Rceattle fit

Description

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.

Usage

## S3 method for class 'Rceattle'
logLik(object, ...)

Arguments

object

An object of class "Rceattle" returned by fit_mod().

...

Currently unused.

Value

An object of class "logLik", or NULL if the model was not estimated.


Model average of derived quantities

Description

Model average of derived quantities

Usage

model_average(Rceattle, weights = NULL, uncertainty = FALSE, nboot = 10000)

Arguments

Rceattle

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

Value

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.


Management strategy evaluation performance metric summary

Description

Management strategy evaluation performance metric summary

Usage

mse_summary(mse, om_only = FALSE)

Arguments

mse

MSE runs from run_mse or load_mse

om_only

only include performance metrics from OMs

Value

Alist of two data.frames with MSE summary statistics of performance metrics including: data.frame 1

  1. Average annual catch across projection years and simulations per fleet and across fleets

  2. Average interannual variation in catch (IAV) across projection years (n) per fleet and across fleets

  3. % of years in which the fishery is closed across simulations (s)

  4. Average relative mean squared error in estimate of spawning biomass in the terminal year across simulations

  5. % of years in which the population is perceived as undergoing overfishing as determined from F_Limit across simulations via build_hcr in the EM

  6. % of years in which the population is perceived to be overfished as determined from B_Limit across simulations via build_hcr in the EM

  7. % of years in which the population is undergoing overfishing as determined from the “true” F_Limit across simulations via build_hcr in the OM

  8. % of years in which the population is overfished as determined from the “true” B_Limit across simulations via build_hcr in the OM

  9. Average ratio of spawning biomass over B_target in the terminal year across simulations in the OM 10-14. Terminal biomass, SSB, SSB depletion (relative to equilibrium), SSB depletion (relative to dynamic SB0)


Data inputs for Northern Rockfish CEATTLE model (2022)

Description

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.

Usage

NorthernRockfish2022

Format

A list with the same structure as BS2017SS.


Plot biomass eaten

Description

Function that plots the biomass consumed trends as estimated from Rceattle. Returns and saves a figure with the biomass eaten trajectory.

Usage

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
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

Which species to plot e.g. c(1,4). Default = NULL plots them all

spnames

Species names for legend

add_ci

TRUE/FALSE, includes 95 percent confidence interval

lwd

Line width as specified by user

save

Save figure to file?

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

width

Figure width in inches

height

Figure height in inches

minyr

first year to plot

incl_proj

TRUE/FALSE include projections years

mod_cex

Cex of text for model name legend

alpha

Shading for confidence intervals

mod_avg

TRUE/FALSE

mse

Is an MSE object from load_mse or run_mse

OM

if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting?


Plot biomass consumed of each prey species by predator

Description

Function that plots the biomass consumed trends as estimated from Rceattle. Returns and saves a figure with the biomass eaten trajectory.

Usage

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
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

spnames

Species names for legend

species

Which species to plot e.g. c(1,4). Default = NULL plots them all

lwd

Line width as specified by user

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

top_adj

Adjustment for top margin

minyr

first year to plot

mohns

data.frame of mohn's rows extracted from retrospective

width

Figure width in inches

height

Figure height in inches

incl_proj

TRUE/FALSE include projections years

incl_mean

TRUE/FALSE include horizontal long term mean

add_ci

TRUE/FALSE, includes 95 percent confidence interval

mod_cex

Cex of text for model name legend


Plot biomass

Description

Plots the mean minage+ biomass (million mt) and 95\

Usage

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
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

What species to include 1:nspp

spnames

Species names for legend

add_ci

If the confidence interval is to be added

lwd

Line width as specified by user

save

Save derived quantity?

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

legend.pos

Position of the legend as used by legend (default = "topright").

width

Figure width in inches

height

Figure height in inches

minyr

First year to plot

maxyr

max year to plot

incl_proj

TRUE/FALSE, include projection years

mod_cex

Cex of text for model name legend

lty

line type

alpha

shading for confidence intervals

mod_avg

TRUE/FALSE

mse

Is an MSE object from load_mse or run_mse

OM

if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting?

reference

Reference model

Value

Returns and saves a figure with the biomass trajectory.


Landings fits

Description

Plot of fitted landings data on natural-scale (r4ss-style)

Usage

plot_catch(
  Rceattle,
  file = NULL,
  model_names = NULL,
  line_col = NULL,
  species = NULL,
  right_adj = 0,
  top_adj = 1.2,
  incl_proj = FALSE,
  single.plots = FALSE,
  width = NULL,
  height = NULL,
  alpha = 0.4,
  lwd = 2,
  ymax = NULL,
  maxyr = NULL,
  mse = FALSE,
  error = TRUE,
  fleets = NULL
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

Species names for legend

right_adj

How much right side of the x-axis for fitting the legend. As percentage.

top_adj

How much top side of the y-axis for fitting the legend. As percentage (default = 1.2).

incl_proj

TRUE/FALSE include projections years

single.plots

if TRUE plot invidual fits else make multiplot

width

plot width

height

plot hight

alpha

Transparency of lines for MSE plots

lwd

Line width

ymax

Fleet specific upper ylim

maxyr

Max year to plot

mse

Is if an MSE object from load_mse or run_mse. Will plot data from OMs.

error

Include observed data with error bars?

fleets

Which fishing fleets to include (defaults to all = NULL)


Plot time series of comp data

Description

Function the plots the comp data as estimated from Rceattle

Usage

plot_comp(
  Rceattle,
  file = NULL,
  model_names = NULL,
  species = NULL,
  cex = 3,
  lwd = 3,
  right_adj = 0
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

species

Species names for legend

cex

Line width as specified by user

lwd

Line width for observed data lines

right_adj

How many units of the x-axis to add to the right side of the figure for fitting the legend.

Value

Returns and saves a figure


Timeline of data used in the model likelihoods

Description

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. Modelled after Stock Synthesis's r4ss::SSplotData().

Usage

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
)

Arguments

Rceattle

Either a single Rceattle model object exported from Rceattle::fit_mod(), or a raw data_list (e.g. one of the bundled datasets such as BS2017MS).

file

Path/prefix used to save the figure. If NULL (default) the plot is drawn to the active device only. When supplied, the figure is written to paste0(file, "_data_plot.png") (and ⁠_data_plot2.png⁠ for the bubble subplot).

subplots

Integer vector controlling which subplots are produced:

  • 1 — equal-size points showing presence/absence by year/fleet

  • 2 — points scaled to relative quantity / precision within each data type (catch tonnage, 1/SE for indices, sample size for comps)

datatypes

Either "all" or a subset of c("catch", "index", "agecomp", "lencomp", "caal", "diet").

fleets

Either "all" or an integer vector of Fleet_codes to include. Diet "fleets" are encoded after the regular fleets (one per predator species).

species

Either "all" or an integer vector of species indices to include.

ghost

Logical. If TRUE, also include rows excluded from the likelihood (Year < 0). Defaults to FALSE.

fleetcol

Either "default" or a vector of colors (one per fleet shown after subsetting). Diet entries get an additional color appended.

width, height

Figure dimensions in inches.

res

Resolution (dpi) for the saved PNG.

ptsize

Pointsize passed to png().

margins

par("mar") for the plot. Increase the right margin if long fleet names are clipped.

cex

Character expansion for points showing isolated years.

lwd

Line width for runs of consecutive years (subplot 1).

maxsize

Max bubble radius (in plot units) for subplot 2.

alphasize

Bubble fill transparency (0–1).

mainTitle

Logical; if TRUE add a default title.

cex.main

Title character expansion.

Details

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 labelled per predator species.

Value

Invisibly, a list with typetable — the long data frame underlying the plot (year, fleet, data type, relative size).


Plot biomass depletion

Description

Plots the mean biomass depletion and 95\

Usage

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
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

What species to include 1:nspp

spnames

Species names for legend

add_ci

If the confidence interval is to be added

lwd

Line width as specified by user

save

Save derived quantity?

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

legend.pos

Position of the legend as used by legend (default = "topright").

width

Figure width in inches

height

Figure height in inches

minyr

First year to plot

maxyr

max year to plot

incl_proj

TRUE/FALSE, include projection years

mod_cex

Cex of text for model name legend

lty

line type

alpha

shading for confidence intervals

mod_avg

TRUE/FALSE

mse

Is an MSE object from load_mse or run_mse

OM

if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting?

reference

Reference model

Value

Returns and saves a figure with the biomass depletion trajectory.


Plot SSB depletion

Description

Plots the mean SSB depletion and 95\ Depletion reference lines for Ptarget and Plimit are drawn in blue and red respectively.

Usage

plot_depletionSSB(
  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
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

What species to include 1:nspp

spnames

Species names for legend

add_ci

If the confidence interval is to be added

lwd

Line width as specified by user

save

Save derived quantity?

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

legend.pos

Position of the legend as used by legend (default = "topright").

width

Figure width in inches

height

Figure height in inches

minyr

First year to plot

maxyr

max year to plot

incl_proj

TRUE/FALSE, include projection years

mod_cex

Cex of text for model name legend

lty

line type

alpha

shading for confidence intervals

mod_avg

TRUE/FALSE

mse

Is an MSE object from load_mse or run_mse

OM

if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting?

reference

Reference model

Value

Returns and saves a figure with the SSB depletion trajectory.


Plot diet composition fits

Description

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)

Usage

plot_diet_comp(Rceattle, file = NULL, species = NULL)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

species

Species names for legend

Value

Returns and saves a figure


Plot exploitable biomass

Description

Plots the mean exploitable biomass (million mt) and 95\

Usage

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
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

What species to include 1:nspp

spnames

Species names for legend

add_ci

If the confidence interval is to be added

lwd

Line width as specified by user

save

Save derived quantity?

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

legend.pos

Position of the legend as used by legend (default = "topright").

width

Figure width in inches

height

Figure height in inches

minyr

First year to plot

maxyr

max year to plot

incl_proj

TRUE/FALSE, include projection years

mod_cex

Cex of text for model name legend

lty

line type

alpha

shading for confidence intervals

mod_avg

TRUE/FALSE

mse

Is an MSE object from load_mse or run_mse

OM

if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting?

reference

Reference model

Value

Returns and saves a figure with the exploitable biomass trajectory.


plot F

Description

Function that plots the F time series per species from Rceattle

Usage

plot_f(
  Rceattle,
  file = NULL,
  model_names = NULL,
  line_col = NULL,
  species = NULL,
  spnames = NULL,
  add_ci = FALSE,
  lwd = 3,
  right_adj = 0,
  width = 7,
  height = 6.5,
  minyr = NULL,
  maxyr = NULL,
  incl_proj = FALSE,
  mod_cex = 1,
  alpha = 0.4,
  mod_avg = rep(FALSE, length(Rceattle)),
  mse = FALSE,
  OM = TRUE
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

Which species to plot e.g. c(1,4). Default = NULL plots them all

spnames

Species names for legend

add_ci

NOT WORKING If the confidence interval is to be added

lwd

Line width as specified by user

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

width

plot width

height

plot height

minyr

First year to plot

maxyr

max year to plot

incl_proj

TRUE/FALSE, include projection years

mod_cex

Cex of text for model name legend

alpha

shading for confidence intervals

mod_avg

is the list a model average? (DEPRECATED)

mse

Is an MSE object from load_mse or run_mse

OM

if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting?

Value

Returns and saves a figure with the population trajectory.


Plot functional form

Description

Function to plot the functional form estimated or specified by Rceattle

Usage

plot_form(params = NULL, pred = 1, pred_age = 1, prey = 1, msmMode = 3)

Arguments

params

Parameter list object from build_params or Rceattle

pred

Predator index

pred_age

Predator age

prey

Prey index

msmMode

Multispecies mode integer specifying functional form


CPUE fits

Description

Plot of fitted CPUE indices on natural-scale (r4ss-style)

Usage

plot_index(
  Rceattle,
  file = NULL,
  model_names = NULL,
  line_col = NULL,
  species = NULL,
  right_adj = 0,
  top_adj = 0.05,
  incl_proj = FALSE,
  single.plots = FALSE,
  width = NULL,
  height = NULL,
  error = TRUE
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

Species names for legend

right_adj

How much right side of the x-axis for fitting the legend. As percentage.

top_adj

How much top side of the y-axis for fitting the legend. As percentage.

incl_proj

TRUE/FALSE include projections years

single.plots

if TRUE plot invidual fits else make multiplot

width

plot width

height

plot hight

error

include observed data and error bars?


CPUE residual

Description

Plot of residuals CPUE indices on log-scale (r4ss-style)

Usage

plot_indexresidual(
  Rceattle,
  file = NULL,
  model_names = NULL,
  line_col = NULL,
  species = NULL,
  right_adj = 0,
  top_adj = 0.05,
  incl_proj = FALSE,
  single.plots = FALSE,
  width = NULL,
  height = NULL
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

Species names for legend

right_adj

How much right side of the x-axis for fitting the legend. As percentage.

top_adj

How much top side of the y-axis for fitting the legend. As percentage.

incl_proj

TRUE/FALSE include projections years

single.plots

if TRUE plot invidual fits else make multiplot

width

plot width

height

plot hight


log(CPUE) fits

Description

Plot of fitted CPUE indices on log-scale (r4ss-style)

Usage

plot_logindex(
  Rceattle,
  file = NULL,
  model_names = NULL,
  line_col = NULL,
  species = NULL,
  right_adj = 0,
  top_adj = 0.05,
  incl_proj = FALSE,
  single.plots = FALSE,
  width = NULL,
  height = NULL
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

Species names for legend

right_adj

How much right side of the x-axis for fitting the legend. As percentage.

top_adj

How much top side of the y-axis for fitting the legend. As percentage.

incl_proj

TRUE/FALSE include projections years

single.plots

if TRUE plot invidual fits else make multiplot

width

plot width

height

plot hight


Plot natural mortality by age

Description

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.

Usage

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
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

age

Age to plot M at age

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

spnames

Species names for legend

species

Which species to plot e.g. c(1,4). Default = NULL plots them all

lwd

Line width as specified by user

lty

Line type

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

minyr

first year to plot

width

Figure width in inches

height

Figure height in inches

incl_proj

TRUE/FALSE include projections years

incl_mean

TRUE/FALSE include time series mean as horizontal line

add_ci

TRUE/FALSE, includes 95 percent confidence interval


Plot predation mortality by age and predator

Description

Function that plots the predation mortality at age (M2) by predator as estimated from Rceattle. Returns and saves a figure with the M-at-age trajectory.

Usage

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
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

age

Age to plot M at age

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

spnames

Species names for legend

species

Which species to plot e.g. c(1,4). Default = NULL plots them all

lwd

Line width as specified by user

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

top_adj

Adjustment for top margin

minyr

first year to plot

width

Figure width in inches

height

Figure height in inches

incl_proj

TRUE/FALSE include projections years

incl_mean

TRUE/FALSE include time series mean as horizontal line

add_ci

TRUE/FALSE, includes 95 percent confidence interval


Plot maturity

Description

Function that plots the maturity of each species

Usage

plot_maturity(
  Rceattle,
  file = NULL,
  model_names = NULL,
  line_col = NULL,
  species = NULL,
  width = 4,
  height = 5.5,
  lwd = 3
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

Species names for legend

width

Figure width in inches

height

Figure height in inches

lwd

Line width as specified by user


Plot M1 + M2

Description

Function that plots the M1 and M2 as estimated from Rceattle

Usage

plot_mortality(
  Rceattle,
  file = NULL,
  incl_proj = FALSE,
  zlim = NULL,
  type = 0,
  width = 8,
  height = 5.5,
  title = NULL,
  log = FALSE,
  minyr = NULL,
  theta = 155,
  species = NULL,
  maxage = NULL,
  title_cex = 10,
  M2 = TRUE
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

incl_proj

Include the projection years (TRUE/FALSE)

zlim

zlim for M1 + M2 plots. Character - use max range across species in model. NULL - use species specific ranges. Vector of two.

type

0 = Tiles, 1 = contour, 2 = facet lines, 3 = persp

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 use log M1 + M2

minyr

First year to plot

theta

theta for persp plot

species

Species to plot. Plots all if null.

maxage

Plot up to this age. Plots all ages if NULL

title_cex

Font size for title

M2

TRUE/FALSE Use M2 only (True) or total M (False)


Plot ration

Description

Function that plots the ration across ages (minage:nages) as estimated from Rceattle. Returns and saves a figure with the ration trajectory. Ration is multiplied by biomass-at-age/sex to get population level estimates

Usage

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
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

minage

minage to plot ration (i.e. age "minage"+)

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

spnames

Species names for legend

species

Which species to plot e.g. c(1,4). Default = NULL plots them all

lwd

Line width as specified by user

lty

Line type

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

minyr

first year to plot

width

Figure width in inches

height

Figure height in inches

incl_proj

TRUE/FALSE include projections years

incl_mean

TRUE/FALSE include time series mean as horizontal line

add_ci

TRUE/FALSE, includes 95 percent confidence interval


Plot recruitment

Description

Plots the mean minage recruitment (millions) and 95\

Usage

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
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

What species to include 1:nspp

spnames

Species names for legend

add_ci

If the confidence interval is to be added

lwd

Line width as specified by user

save

Save derived quantity?

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

legend.pos

Position of the legend as used by legend (default = "topright").

width

Figure width in inches

height

Figure height in inches

minyr

First year to plot

maxyr

max year to plot

incl_proj

TRUE/FALSE, include projection years

mod_cex

Cex of text for model name legend

lty

line type

alpha

shading for confidence intervals

mod_avg

TRUE/FALSE

mse

Is an MSE object from load_mse or run_mse

OM

if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting?

reference

Reference model

Value

Returns and saves a figure with the recruitment trajectory.


Plot selectivity

Description

Function that plots the fishery and survey selectivity as estimated from Rceattle

Usage

plot_selectivity(
  Rceattle,
  file = NULL,
  model_names = NULL,
  line_col = NULL,
  width = 7,
  height = 6.5,
  species = c("Walleye pollock", "Pacific cod", "Arrowtooth flounder"),
  lwd = 3
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

width

Figure width in inches

height

Figure height in inches

species

Species names for legend

lwd

Line width as specified by user


Plot fishery selectivity and maturity

Description

Function the plots the fishery selectivity and input maturity. Useful for debugging SPR based reference points.

Usage

plot_selectivity_vs_maturity(
  Rceattle,
  file = NULL,
  model_names = NULL,
  line_col = NULL,
  width = 7,
  height = 6.5,
  species = c("Walleye pollock", "Pacific cod", "Arrowtooth flounder"),
  lwd = 3
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

width

Figure width in inches

height

Figure height in inches

species

Species names for legend

lwd

Line width as specified by user


Plot spawning stock biomass (SSB)

Description

Plots the mean SSB (million mt) and 95\

Usage

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
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

What species to include 1:nspp

spnames

Species names for legend

add_ci

If the confidence interval is to be added

lwd

Line width as specified by user

save

Save derived quantity?

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

legend.pos

Position of the legend as used by legend (default = "topright").

width

Figure width in inches

height

Figure height in inches

minyr

First year to plot

maxyr

max year to plot

incl_proj

TRUE/FALSE, include projection years

mod_cex

Cex of text for model name legend

lty

line type

alpha

shading for confidence intervals

mod_avg

TRUE/FALSE

mse

Is an MSE object from load_mse or run_mse

OM

if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting?

reference

Reference model

Value

Returns and saves a figure with the SSB trajectory.


Plot SSB depletion (deprecated name)

Description

Deprecated alias for plot_ssb_depletion. Please use plot_ssb_depletion() instead.

Usage

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
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

What species to include 1:nspp

spnames

Species names for legend

add_ci

If the confidence interval is to be added

lwd

Line width as specified by user

save

Save derived quantity?

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

legend.pos

Position of the legend as used by legend (default = "topright").

width

Figure width in inches

height

Figure height in inches

minyr

First year to plot

maxyr

max year to plot

incl_proj

TRUE/FALSE, include projection years

mod_cex

Cex of text for model name legend

lty

line type

alpha

shading for confidence intervals

mod_avg

TRUE/FALSE

mse

Is an MSE object from load_mse or run_mse

OM

if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting?

reference

Reference model


Plot stock recruit function

Description

Function the plots the stock recruit function as estimated from Rceattle

Usage

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
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

width

Figure width in inches

height

Figure height in inches

species

Which species to plot e.g. c(1,4). Default = NULL plots them all

spnames

Species names for legend

lwd

Line width as specified by user

lty

Line type

incl_proj

TRUE/FALSE, include projection years for environmental relationship

plot_env

TRUE/FALSE, plot environmental covariate relationship

mod_cex

Cex of text for model name legend


Plot time-series

Description

Function that plots the time-series (SSB/B/R/Depletion) 95% CI trends as estimated from Rceattle

Usage

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,
  mod_avg = rep(FALSE, length(Rceattle))
)

Arguments

Rceattle

Single or list of Rceattle model objects exported from Rceattle

output

derived quantity of interest: recruitment, biomass, ssb, depletion, or ssb_depletion. Uses same name as ".cpp" file.

ylab

Y-axis label

file

name of a file to identified the files exported by the function.

model_names

Names of models to be used in legend

line_col

Colors of models to be used for line color

species

What species to include 1:nspp

spnames

Species names for legend

add_ci

If the confidence interval is to be added

lwd

Line width as specified by user

save

Save derived quantity?

legend.pos

Position of the legend as used by legend (default = "topright").

right_adj

Multiplier for to add to the right side of the figure for fitting the legend.

width

Figure width in inches

height

Figure height in inches

minyr

First year to plot

maxyr

max year to plot

incl_proj

TRUE/FALSE, include projection years

mod_cex

Cex of text for model name legend

lty

line type

alpha

shading for confidence intervals

mse

Is an MSE object from load_mse or run_mse

OM

if mse == TRUE, use the OM (TRUE) or EM (FALSE) for plotting?

reference

Reference model

mod_avg

TRUE/FALSE

Value

Returns and saves a figure with the population trajectory.


Plot method for fitted Rceattle models

Description

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.

Usage

## S3 method for class 'Rceattle'
plot(x, what = "biomass", ...)

Arguments

x

An object of class "Rceattle" returned by fit_mod().

what

Character. One of "biomass" (default), "ssb", "recruitment", "depletion", "index", "catch", "selectivity", "mortality", or "data".

...

Passed to the underlying plotting function.

Value

Invisibly returns NULL. Called for the side effect of producing a plot.


Print method for fitted Rceattle models

Description

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.

Usage

## S3 method for class 'Rceattle'
print(x, ...)

Arguments

x

An object of class "Rceattle" returned by fit_mod().

...

Currently unused.

Details

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 master has moved on. Tag a release (devtools::install_github("grantdadams/[email protected]")) and the same version string will reappear here on a fresh run.

Value

The input x, invisibly.


Beta prior on a linkage coefficient

Description

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.

Usage

prior_beta(shape1, shape2)

Arguments

shape1, shape2

positive shape parameters.

Value

An Rceattle_prior of family "beta".


Gamma prior on a linkage coefficient

Description

Shape-rate parameterization, matching stats::dgamma().

Usage

prior_gamma(shape, rate)

Arguments

shape

positive shape parameter.

rate

positive rate parameter.

Value

An Rceattle_prior of family "gamma".


Lognormal prior on a linkage coefficient

Description

Parameterized on the log scale (mean and sd of the log of the coefficient), matching stats::dlnorm().

Usage

prior_lognormal(meanlog, sdlog)

Arguments

meanlog

prior mean of the log of the coefficient.

sdlog

prior standard deviation of the log (must be positive).

Value

An Rceattle_prior of family "lognormal".


Normal prior on a linkage coefficient

Description

Normal prior on a linkage coefficient

Usage

prior_normal(mean, sd)

Arguments

mean

prior mean.

sd

prior standard deviation (must be positive).

Value

An Rceattle_prior of family "normal".


Likelihood profile across one or more parameter cells

Description

Re-fits an Rceattle model while holding selected cells of a parameter fixed at user-specified values. Supports profiling a single cell (e.g. R_log_sd[species = 1]) and arbitrary N-dimensional cross-profiles over multiple cells – e.g. log_M1[1, 1, 1] and log_M1[1, 2, 1] jointly, to profile residual M for males against females. For each grid point the targeted cells are fixed in the TMB map and the remaining parameters are re-estimated; the result is a grid of Rceattle models for downstream NLL surfaces.

Usage

## S3 method for class 'Rceattle'
profile(
  fitted = NULL,
  param = NULL,
  slots = NULL,
  values = NULL,
  transform = "log",
  cores = NULL,
  ...
)

Arguments

fitted

an Rceattle model fit using fit_mod

param

Name of the parameter to profile. Two ways to specify it:

Raw parameter slot

any name in Rceattle$estimated_params; tested for "R_log_sd", "rec_pars", and "log_M1". slots must index into the full array and transform controls the scale.

Natural-scale alias

convenience shortcut for the three documented parameters. Aliases imply transform = "log" (values are taken in natural units and log'd before being substituted) and, for rec_pars, fill in the column from the alias name so slots only needs the species index:

  • "sigmaR", "R_sd" -> R_log_sd

  • "M1" -> log_M1

  • "R0" -> rec_pars[, 1]

  • "alpha" -> rec_pars[, 2]

  • "beta" -> rec_pars[, 3]

If transform is supplied with an alias it is ignored (with a warning).

slots

A list whose entries are integer index vectors, one entry per cell to fix. Each entry's length must equal the number of dimensions of the resolved parameter – 1 for vectors (R_log_sd), 2 for matrices (rec_pars), 3 for 3-D arrays (log_M1). When using the "R0"/"alpha"/"beta" aliases, supply only the species index (length 1); the column is filled in from the alias. E.g. list(c(1, 2, 1)) fixes log_M1[1, 2, 1]; list(c(1, 1, 1), c(1, 2, 1)) fixes both sex cells for a males-vs-females cross-profile of species 1; list(1, 2) with param = "sigmaR" cross-profiles species 1 and 2. If omitted, defaults to a single species-1 slot shaped to match the resolved parameter (e.g. list(1) for R_log_sd, list(c(1, 1, 1)) for log_M1, list(1) for the rec_pars aliases) and emits a warning; pass slots explicitly to silence the warning. Defaulting requires length(values) == 1L (otherwise the user must explicitly say which cell each grid targets).

values

A list of numeric vectors, one per entry of slots. The full grid of fits is expand.grid(values), so a single slot gives a 1-D profile and k slots give a k-D cross-profile.

transform

How to map user values onto the internal parameter scale before substituting them into inits. Either "log" (default), "identity", or a unary function (e.g. qlogis). Applied element-wise to every grid value. Aliases override this with "log".

cores

Number of cores to use for parallel fits. Default NULL picks parallel::detectCores() - 6, capped at 2 when running under R CMD check (which sets _R_CHECK_LIMIT_CORES_). Set to 1 to force sequential execution.

...

Unused; present for consistency with the stats::profile generic.

Value

A list with elements:

Rceattle_list

list of fitted Rceattle models, one per grid row; entries for non-converged fits are NULL so positions stay aligned with grid.

grid

data frame of grid values on the user scale (before transform); one column per profiled cell, named slot_1, slot_2, ...

nll

numeric vector of joint negative log-likelihoods (opt$objective); NA where the fit did not converge.

param

the profiled parameter name (echoed).

slots

the slots list (echoed for downstream plotting).

Examples

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 (alias form -- natural scale)
p1 <- profile(ss_run,
    param  = "sigmaR",
    slots  = list(1),
    values = list(seq(0.1, 1.5, by = 0.1)))

# Equivalent raw form (log scale -- user does the transform)
p1_raw <- profile(ss_run,
    param     = "R_log_sd",
    slots     = list(1),
    values    = list(log(seq(0.1, 1.5, by = 0.1))),
    transform = "identity")

# 2-D cross-profile of M1 across species 1 and 2 (sex 1, age 1).
# BS2017SS is single-sex; with a multi-sex model the same form
# (e.g. c(1, 1, 1), c(1, 2, 1)) would cross-profile males vs females.
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)))

# 1-D profile of SRR alpha for species 1 (alias drops the rec_pars column)
p3 <- profile(ss_run,
    param  = "alpha",
    slots  = list(1),
    values = list(seq(2, 80, length.out = 20)))

Read a CEATTLE excel data file

Description

Read a CEATTLE excel data file

Usage

read_data(file = "Rceattle_data.xlsx")

Arguments

file

Filname to be used. Must end with '.xlsx'

Examples

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)
file.remove(out_file)

Rearrange a data_list for TMB

Description

Function to rearrange a data_list object to be read into TMB

rearrange_dat() is a deprecated alias for rearrange_data() kept for backwards compatibility; please use rearrange_data().

Usage

rearrange_data(data_list)

rearrange_dat(data_list)

Arguments

data_list

an Rceattle data_list


Rerun with F = 0.

Description

Function to update hindcast and set F to 0. Useful for determining dynamic reference points for multi-species models under climate-change.

Usage

remove_F(Rceattle)

Arguments

Rceattle

A fitted Rceattle model object


Function to rename derived quantities from Rceattle

Description

Function to rename derived quantities from Rceattle

Usage

rename_output(data_list = NULL, quantities = NULL)

Arguments

data_list

an Rceattle data_list

quantities

list of "report" objects from Rceattle.


Observed-vs-fitted residuals from an Rceattle fit

Description

Returns a long-format data frame of residuals across one or more of the four fitted data sources: "index" (survey indices), "catch" (fishery catches), "comp" (age- or length-composition proportions), and "caal" (conditional age-at-length proportions).

Usage

## S3 method for class 'Rceattle'
residuals(object, type = "index", scale = "log", ...)

Arguments

object

An object of class "Rceattle" returned by fit_mod().

type

One or more of "index", "catch", "comp", "caal", or "all" (default "index").

scale

"log" (default) or "natural". Only affects "index" and "catch" residuals.

...

Currently unused.

Details

For "index" and "catch", the Residual column is on the log scale by default (matching the lognormal observation likelihood) and can be switched to the natural scale via scale = "natural". For "comp" and "caal", residuals are Pearson residuals on the fitted proportions:

r=(pp^)/p^(1p^)/Nr = (p - \hat p)/\sqrt{\hat p (1 - \hat p)/N}

where N is the input sample size. Composition rows are returned in long form: one row per (observation, age/length bin).

Composition rows carry the Age0_Length1 flag from comp_data (0 for age comps, 1 for length comps) so age and length comps can be filtered apart. CAAL rows carry both the conditioning Length and the age Bin.

Value

A data.frame with columns Source, Fleet_code, Fleet_name, Species, Sex, Year, Length, Bin, Age0_Length1, Sample_size, Observed, Fitted, Residual. Sex, Length, Bin, Age0_Length1, and Sample_size are NA where they do not apply (e.g. for index/catch rows).


Retrospective peels

Description

Calculate Mohn's rho and run retrospective peels for an Rceattle model. The function also evaluates retrospective forecast skill. To evaluate both retrospective bias and forecast skill, the function uses the map functionality of TMB to peel the model:

  1. Filters data, filters fixed inputs, and maps out time-varying parameters for the peeled years. All time-varying parameters for the peeled years are set to the terminal year of the model for that peel.

  2. Fits the peeled model.

  3. Turns off all hindcast parameters, turns on F for the peeled years, and fits to the peeled catch series to update the "forecast" dynamics given projection assumptions and observed catch from the peeled years.

Usage

retrospective(
  Rceattle = NULL,
  peels = 5,
  rescale = FALSE,
  nyrs_forecast = 3,
  cores = NULL
)

Arguments

Rceattle

an Rceattle model fit using fit_mod

peels

the number of retrospective peels to use in the calculation of rho and for model estimation

rescale

TRUE/FALSE whether to subset and rescale environmental predictors for the range of peel years.

nyrs_forecast

Number of forecast years to calculate Mohn's Rho in addition to terminal year

cores

Number of cores to use for parallel peels. Default NULL picks parallel::detectCores() - 6, capped at 2 when running under R CMD check (which sets _R_CHECK_LIMIT_CORES_). Set to 1 to force sequential execution.

Value

a list of 1. list of Rceattle models and 2. vector of Mohn's rho for each species

Examples

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)

Make a vector of colors.

Description

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)

Usage

rich.colors.short(n, alpha = 1)

Arguments

n

Number of colors to generate.

alpha

Alpha transparency value for all colors in vector. Value is passed to rgb function.

Author(s)

Arni Magnusson, Ian Taylor


Run a management strategy evaluation

Description

Runs a forward projecting MSE. Main assumptions are the projected selectivity/catchability, foraging days, and weight-at-age are the same as the terminal year of the hindcast in the operating model. Assumes survey sd is same as average across historic time series, while comp data sample size is same as last year. No implementation error and no observation error for catch!

Usage

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
)

Arguments

om

CEATTLE model object exported from Rceattle

em

CEATTLE model object exported from Rceattle

nsim

Number of simulations to run (default 10)

start_sim

First simulation number to start at. Useful if the code stops at specific seed/sim (default = 1).

assessment_period

Period of years that each assessment is taken

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/provided for the data from the OM.

regenerate_past

Refits the EM to historical/conditioning data prior to the MSE, where the data are generated from the OM with simulate_data = TRUE or without simulate_data = FALSE sampling error.

sample_rec

Include resampled recruitment deviates from the"hindcast" in the projection of the OM. Resampled deviates are used rather than sampling from N(0, sigmaR) because initial deviates bias R0 low. If false, uses mean of recruitment deviates.

rec_trend

Linear increase or decrease in mean recruitment from endyr to projyr. This is the terminal multiplier mean rec * (1 + (rec_trend/projection years) * 1:projection years). Can be of length 1 or of length nspp. If length 1, all species get the same trend.

fut_sample

future sampling effort relative to last year. Log_sd * 1 / fut_sample for index and Sample_size * fut_sample for comps

cap

A cap on the catch in the projection. Can be a single number applied to all species (proportional to recommended catch) or vector of length nspp applied to each species. Default = NULL

catch_mult

A multiplier for the catch in the projection. Can be a single number or vector of length nspp. Default = NULL

seed

seed for the simulation

regenerate_seed

seed for regenerating data

loopnum

number of times to re-start optimization (where loopnum=3 sometimes achieves a lower final gradient than loopnum=1)

file

(Optional) Filename where each OM simulation with EMs will be saved. If NULL, no files are saved.

dir

(Optional) Directory where each OM simulation is saved

timeout

length of time (minutes) estimation will run before stopping a sim (default 999 minutes)

endyr

Terminal year of the MSE projection. Default = NA uses projyr from the operating model.

cores

Number of cores to use for parallel simulations. Default NULL picks parallel::detectCores() - 6, capped at 2 when running under R CMD check (which sets _R_CHECK_LIMIT_CORES_). Set to 1 to force sequential execution.

Value

A list of operating models (differ by simulated recruitment determined by nsim) and estimation models fit to each operating model (differ by terminal year).


Sample historical recruitment deviates and place in the projection

Description

Sample historical recruitment deviates and place in the projection

Usage

sample_rec(Rceattle, sample_rec = TRUE, update_model = TRUE, rec_trend = 0)

Arguments

Rceattle

CEATTLE model object exported from Rceattle

sample_rec

Include resampled recruitment deviates from the"hindcast" in the projection of the OM. Resampled deviates are used rather than sampling from N(0, sigmaR) because initial deviates bias R0 low. If false, uses mean of recruitment deviates.

update_model

Update model dynamics. Default = TRUE

rec_trend

Linear increase or decrease in mean recruitment from endyr to projyr. This is the terminal multiplier mean rec * (1 + (rec_trend/projection years) * 1:projection years). Can be of length 1 or of length nspp. If length 1, all species get the same trend.

Value

Rceattle model


Self test simulation analysis analysis

Description

Simulates data from an Rceattle model and refits the model to the simulated data. TODO add process variation (i.e. random devs) to simulation.

Usage

self_test(
  Rceattle = NULL,
  nsim = 50,
  simulate = TRUE,
  seed = 123,
  cores = NULL
)

Arguments

Rceattle

an Rceattle model fit using fit_mod

nsim

number of simulations

simulate

passed to sim_mod. If TRUE (default), data are simulated with observation error; if FALSE, expected values from the model are used.

seed

random number seed. Each simulation i uses seed + i so results are reproducible under both sequential and parallel execution.

cores

Number of cores to use for parallel simulations. Default NULL picks parallel::detectCores() - 6, capped at 2 when running under R CMD check (which sets _R_CHECK_LIMIT_CORES_). Set to 1 to force sequential execution.

Value

a list of Rceattle models

Examples

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)

Function to set phasing order

Description

Function to set phasing order

Usage

set_phases()

Value

list of parameter names with associated phase


Simulate Rceattle data

Description

Simulates data used in Rceattle from the expected values estimated from an existing Rceattle model. The variances and uncertainty are consistent with those used in the operating model. The function simulates: survey biomass (log-normal), catch-at-age/length composition (multinomial or dirichlet-multinomial), conditional-age-at-length (CAAL; multinomial or dirichlet-multinomial), and total catch (log-normal).

Usage

sim_mod(Rceattle, simulate = FALSE)

Arguments

Rceattle

A CEATTLE model object exported from Rceattle.

simulate

Logical. If TRUE, simulates data from distributions. If FALSE, returns the expected values (hats).

Value

A data_list object containing the simulated or expected data values, formatted for use in Rceattle.


Compact summary method for Rceattle fits

Description

Compact summary method for Rceattle fits

Usage

## S3 method for class 'Rceattle'
summary(object, ...)

Arguments

object

An object of class "Rceattle" returned by fit_mod().

...

Currently unused.


Function to check for missing switches for map and parameter functions

Description

Function to check for missing switches for map and parameter functions

Usage

switch_check(data_list)

Arguments

data_list

Rceattle data list


#https://www.dataanalytics.org.uk/make-transparent-colors-in-r/

Description

#https://www.dataanalytics.org.uk/make-transparent-colors-in-r/

Usage

t_col(color, percent = 50, name = NULL)

Arguments

color

color name

percent

% transparency

name

an optional name for the color


Calculate marginal AIC for a fitted model

Description

TMBAIC calculates AIC for a given model fit

Usage

TMBAIC(opt, p = 2, n = Inf)

Arguments

opt

the output from nlminb or optim

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)

Value

AIC, where a parsimonious model has a AIC relative to other candidate models


Run TMB using phases

Description

This function runs TMB with ADMB-like phasing of parameter estimation. Function with normal inputs, passed via "...", plus two additional arguments, "phase" Optimizer by default is nlminb phase is a tagged list where missing elements are populated with a vector of 1s, and non-missing elements are integers, and where the optimizer loops through values of phase while progressively changing map to turn on parameters

Usage

TMBphase(
  data,
  parameters,
  map,
  random,
  phases,
  model_name,
  silent,
  use_gradient = TRUE,
  control = list(eval.max = 1e+09, iter.max = 1e+09, trace = 0)
)

Arguments

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

A list of the phases for the parameters of the model (same structure as your parameter list)

model_name

A string describing the model name. Must be the name of your .cpp file

silent

logical. If TRUE, suppresses output from TMB (default = TRUE).

use_gradient

logical. If TRUE, uses gradient in optimization (default = TRUE).

control

A list of control parameters. For details see ?nlminb

Value

A list of parameter estimates and their standard errors

Author(s)

Gavin Fay https://github.com/kaskr/TMB_contrib_R/blob/master/TMBphase/R/TMBphase.R


Variance-covariance matrix for an Rceattle fit

Description

Returns the fixed-effect covariance matrix produced by TMB::sdreport(). Random-effect covariance is not returned here — use object$sdrep for the full report.

Usage

## S3 method for class 'Rceattle'
vcov(object, ...)

Arguments

object

An object of class "Rceattle" returned by fit_mod().

...

Currently unused.

Value

A numeric matrix, or NULL if sdreport was not run (i.e. the fit was produced with getsd = FALSE).


Data inputs for CEATTLE model with WHAM-estimated growth

Description

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.

Usage

whamGrowthData

Format

A list with the same structure as BS2017SS.


Write data file

Description

Write data file

Usage

write_data(data_list, file = "Rceattle_data.xlsx")

Arguments

data_list

Rceattle data_list object

file

Filname to be used. Must end with '.xlsx'

Examples

library(Rceattle)
data(BS2017SS)
out_file <- file.path(tempdir(), "BS2017SS.xlsx")
write_data(data_list = BS2017SS, file = out_file)
file.remove(out_file)