Package 'MSEtool'

Title: Management Strategy Evaluation Toolkit
Description: Development, simulation testing, and implementation of management procedures for fisheries (see Carruthers & Hordyk (2018) <doi:10.1111/2041-210X.13081>).
Authors: Adrian Hordyk [aut, cre], Quang Huynh [aut], Tom Carruthers [aut], Chris Grandin [ctb] (iSCAM functions)
Maintainer: Adrian Hordyk <[email protected]>
License: GPL-3
Version: 4.0.0
Built: 2026-06-08 20:14:57 UTC
Source: https://github.com/Blue-Matter/MSEtool

Help Index


Access and Assign Slots from Compatible S4 Objects

Description

Generic accessor and replacement functions to retrieve and assign named slots from compatible S4 objects across the openMSE package ecosystem. Functions work on any S4 object that contains the corresponding slot.

Usage

AC(x)

AC(x) <- value

Beta(x)

Beta(x) <- value

Bias(x)

Bias(x) <- value

Classes(x)

Classes(x) <- value

Compliance(x)

Compliance(x) <- value

CPUE(x)

CPUE(x) <- value

CV(x)

CV(x) <- value

CVatAge(x)

CVatAge(x) <- value

Dist(x)

Dist(x) <- value

DiscardsAtAge(x)

DiscardsAtAge(x) <- value

DiscardsAtSize(x)

DiscardsAtSize(x) <- value

Error(x)

Error(x) <- value

Exploitation(x)

Exploitation(x) <- value

LandingsAtAge(x)

LandingsAtAge(x) <- value

LandingsAtSize(x)

LandingsAtSize(x) <- value

LifeHistory(x)

LifeHistory(x) <- value

Mean(x)

Mean(x) <- value

MeanAtAge(x)

MeanAtAge(x) <- value

MeanAtLength(x)

MeanAtLength(x) <- value

MeanAtWeight(x)

MeanAtWeight(x) <- value

Misc(x)

Misc(x) <- value

Model(x)

Model(x) <- value

Name(x)

Name(x) <- value

nSim(x)

nSim(x) <- value

nArea(x, st = 1)

nAge(x, st = NULL)

nComplex(x)

nStock(x)

nFleet(x)

Pars(x)

Pars(x) <- value

Period(x)

Period(x) <- value

Random(x)

Ref(x)

Ref(x) <- value

RefCV(x)

RefCV(x) <- value

Reference(x)

Reference(x) <- value

Size(x)

Size(x) <- value

SD(x)

SD(x) <- value

Survey(x)

Survey(x) <- value

Timing(x)

TruncSD(x)

TruncSD(x) <- value

Units(x)

Units(x) <- value

Value(x)

Value(x) <- value

YearLH(x)

YearLH(x) <- value

Arguments

x

An S4 object with the corresponding slot.

value

The value to assign to the slot

st

Integer. Stock index used when x contains multiple stocks. Default 1 for nArea() and NULL for nAge() (returns all stocks as a list when NULL).

Value

  • Accessor functions return the value stored in the named slot of x.

  • Replacement functions return x with the named slot updated to value.

Examples

MyLength <- Length()
MeanAtAge(MyLength)

Add Auto-Correlation to a Vector of Values

Description

Applies an AR(1) auto-correlation structure to a vector of independent values, conditioning on a provided last observed value. The transformation scales each value to preserve the marginal variance under the AR(1) process.

Usage

AddAutoCorrelation(values, ac, last_value)

Arguments

values

numeric vector. Independent values to be transformed with auto-correlation (e.g., log recruitment deviations).

ac

numeric scalar. Auto-correlation coefficient, typically in [-1, 1].

last_value

numeric scalar. The last observed value from the preceding time period, used to condition the first element of values.

The AR(1) recursion applied is:

xt=ρxt1+ϵt1ρ2x_t = \rho \cdot x_{t-1} + \epsilon_t \cdot \sqrt{1 - \rho^2}

where ρ\rho is ac and ϵt\epsilon_t are the input values. The 1ρ2\sqrt{1 - \rho^2} scaling ensures the marginal variance of xtx_t equals the variance of ϵt\epsilon_t.

Value

A numeric vector of the same length as values with AR(1) auto-correlation applied.

See Also

GenMultiStockRecDevs()


Add a Fleet to an Operating Model

Description

Adds a new fleet to an om object, appending a fleet, an obs, and an imp object for every stock in the OM.

Usage

AddFleet(OM, FleetName, Fleet = NULL, Obs = NULL, Imp = NULL)

Arguments

OM

An object of class om.

FleetName

A length-1 character string giving the name of the new fleet. Must not already exist in OM.

Fleet

Optional. An object of class fleet. If NULL (default), an empty fleet object is created with Name = FleetName.

Obs

Optional. An obs object. If NULL (default), an empty obs object is created with Name = FleetName.

Imp

Optional. An imp object. If NULL (default), an empty imp object is created with Name = FleetName

Value

The om object with the new fleet appended to OM@Fleet and OM@Obs for every stock.

Examples

OM <- SingleStockOM
FleetNames(OM)
OM2 <- AddFleet(OM, 'DummyFleet')
FleetNames(OM2)

Utility functions for multiMSE objects

Description

addMMPs() adds additional management procedures to a MMSE object by combining multiple MMSE objects that have identical historical OM values, and population/ fleet structures.

Usage

addMMPs(MMSEobjs)

Arguments

MMSEobjs

A list MMSE object

Value

An object of class MMSE

Author(s)

Q. Huynh

See Also

addMPs()


Management Advice Constructor and Accessors

Description

Construct an advice object defining management advice returned by a management procedure.

Usage

Advice(
  TAC = NULL,
  TACType = "Removals",
  TACUnit = "Biomass",
  Effort = NULL,
  EffType = "Rel",
  Closure = NULL,
  Selectivity = NULL,
  Retention = NULL,
  DiscardMortality = NULL,
  ApicalF = NULL,
  BagLimit = NULL,
  SpeciesLimit = NULL,
  LimitType = "angler",
  ClosureMode = "discard",
  Misc = list()
)

Arguments

TAC

Numeric vector or matrix specifying total allowable catch. See Details

TACType

Character. Does the TAC refer to "Removals" (default) or "Landings". Either length 1 (applied to all fleets) or a character vector of length nFleet.

TACUnit

Character. Units in which the TAC is expressed: "Biomass" (default) or "Number". Either length 1 (applied to all fleets) or a character vector of length nFleet.

Effort

Numeric vector or matrix specifying relative or absolute fishing effort. See Details

EffType

Character. Effort interpretation: "Rel" for relative to the last historical year, or "Abs" for absolute effort units (in units of Effort()). Either length 1 (applied to all fleets) or a character vector of length nFleet. Default is "Rel".

Closure

Numeric vector or array specifying spatial closures. See Details

Selectivity

A Selectivity() object or an nFleet-length list of such objects. See Details

Retention

A Retention() object or an nFleet-length list of such objects. See Details

DiscardMortality

A DiscardMortality() object or an nFleet-length list of such objects. See Details

ApicalF

Numeric array specifying target apical fishing mortality. Not currently used

BagLimit

Numeric vector or NULL. Aggregate bag limit in fish per angler per trip (when LimitType = "angler") or fish per vessel per trip (when LimitType = "boat"). Accepted forms:

  • NULL (default): no bag limit regulation is active for any fleet.

  • Single numeric value: the same limit applied to all fleets.

  • Numeric vector of length nFleet: fleet-specific bag limits. NA for a given fleet position means no aggregate limit applies to that fleet.

The bag limit regulation persists across time steps until a new Advice() object is returned by the MP. See Details.

SpeciesLimit

Numeric matrix or NULL. Species-specific bag limits (fish per angler or vessel per trip) within a complex. Accepted forms:

  • NULL (default): no species-specific limits are active.

  • Numeric matrix with dimensions ⁠nFleet x nStock⁠: fleet- and species-specific limits. NA in a given fleet-stock position means no species-specific limit applies to that fleet-stock combination.

SpeciesLimit operates simultaneously with BagLimit — a trip is constrained whenever either limit is reached first. The regulation persists across time steps until a new Advice() object is returned by the MP. See Details.

LimitType

Character or NULL. Whether BagLimit and SpeciesLimit are per-angler or per-vessel regulations. Either length 1 (applied to all fleets) or a character vector of length nFleet. Valid values:

  • "angler" (default): limits are per angler per trip; the fleet-level retention cap is BfAf,tTf,tB_f \cdot A_{f,t} \cdot T_{f,t}, where Af,tA_{f,t} is mean anglers per trip (AnglerPerTrip()) and Tf,tT_{f,t} is the number of trips (TripsScalar()).

  • "boat": limits are per vessel per trip; the fleet-level retention cap is BfTf,t)B_f \cdot T_{f,t)}, and AnglerPerTrip() is not used.

ClosureMode

Character or NULL. Determines how the OM handles catch that exceeds the bag limit. Either length 1 (applied to all fleets) or a character vector of length nFleet. Valid values:

  • "discard" (default): catch exceeding the bag limit is converted to discards; discard mortality is applied via the fleet's DiscardMortality() object.

  • "stop": effort is reduced so that projected catch does not exceed the bag limit retention cap; no additional discards are generated beyond the baseline discard rate from non-retention of undersized fish.

Misc

Miscellaneous list. Will be passed to Data@Misc in following time steps.

Details

Advice() constructs a container for management regulations returned by a management procedure. All slots are optional; any regulation not supplied will remain unchanged from the previous time step.

The management regulations in an Advice object will be applied in the year/time-step that the Advice object is produced (i.e., when the MP is run) and will apply to all future time-steps until a new Advice object is returned by an MP.

The Closure, Selectivity, Retention, and DiscardMortality regulations (if any) are applied first before calculating the fishing mortality corresponding with TAC.

If both TAC and Effort regulations are returned, the expected fishing effort will be calculated to achieve a catch equal to the TAC. If the expected effort is greater than that set in Effort, the catch will be constrained to that corresponding with Effort. Otherwise, the actual fishing effort will be lower than Effort.

Valid Configurations for Management Regulations

There are several options for populating the slots in an Advice object:

TAC

Total allowable catch in units of "Biomass" (default) or "Number" (see TACUnit). TACType and TACUnit are each either length 1 (applied uniformly across all fleets) or a character vector of length nFleet specifying per-fleet values.

  • single numeric value: global TAC distributed across the stocks and fleets in the Data() object according to Allocation(OM).

  • numeric vector length nFleet: fleet-specific TAC.

Effort

Either in absolute units corresponding with fleet-specific effort (EffType = "Abs"), or relative to the effort in the last historical year (EffType = "Rel"; default). EffType is either length 1 (applied uniformly across all fleets) or a character vector of length nFleet specifying per-fleet values.

Note that when Effort is supplied as a matrix (fleet x area), it is always treated as absolute regardless of EffType.

  • single numeric value:

    • If EffType="Rel": Effort relative to last historical year, applied to all fleets. E.g., if Effort=0.5, effort for all fleets will be set to half the effort in the last historical year.

    • If EffType="Abs": the total effort (summed over fleets unless provide as a length nFleet vector); Note that in this case all fleets in the OM must have the same units for Effort).

  • numeric vector length nFleet: Fleet-specific relative or absolute Effort.

  • numeric matrix: Fleet- and Area-specific relative or absolute Effort. Must have nFleet rows and nArea columns.

Closure

Can only be 0 (closed) or 1 (open). Otherwise will be converted to 0 (Closure<0.5) or 1

  • vector length nArea

  • matrix with nFleet rows and nArea columns: fleet-specific closures.

Selectivity

Either a Selectivity() object, or a list length nFleet of Selectivity objects.

If a single Selectivity object, the prescribed selectivity schedule is applied to all fleets.

See section below for more details.

Retention

Same as described for Selectivity, but for Retention() objects.

Discard Mortality

Same as described for Selectivity, but for DiscardMortality() objects.

Bag Limit

BagLimit, SpeciesLimit, LimitType, and ClosureMode together define a bag-limit regulation. The bag limit caps the number of fish an angler (or vessel) may retain per trip for either a single species or across all species within a complex.

BagLimit sets an aggregate limit across all species in the complex.

SpeciesLimit sets species-specific limits within the complex. Both may be active simultaneously, a trip is constrained whenever either limit is reached first. NA in a fleet position of BagLimit, or in a fleet-stock position of SpeciesLimit, means no limit applies for that fleet or fleet-stock combination respectively.

When ClosureMode = "discard", catch exceeding the retention cap is converted to discards and discard mortality is applied via the fleet's DiscardMortality() object. When ClosureMode = "stop", effort is reduced to prevent exceeding the bag limit and no additional discards are generated.

ApicalF

Not currently used.

Misc

A list of miscellaneous information that needs to be stored and accessed by the MP in future timesteps. Contents of Advice@Misc will be available in the Data@Misc slot in subsequent time steps.

Populating Selectivity, Retention, and Discard Mortality Objects

The Selectivity, Retention, and DiscardMortality objects are used to set the selectivity-, retention-, and discard mortality- at-age or -at-size schedules.

If values are provided for these slots in the Advice object, the new regulations/specifications will apply to all future time steps until modified again by the MP.

Values can be set for these objects in the following ways:

  • MeanAtAge:

    • A numeric vector length nAge, where nAge is the number of age classes for the stock (or stocks) that are being managed by the MP.

    • For area-specific schedules, a numeric matrix with nAge rows and nArea columns.

  • MeanAtLength:

    • A numeric vector length nClass, where nClass is the number of length classes for the stock (or stocks) that are being managed by the MP. The Classes slot can be used to set the size classes corresponding with MeanAtLength. Otherwise, the classes will be taken from the corresponding Length object in the OM(if they exist, otherwise an error).

    • For area-specific schedules, a numeric matrix with nClass rows and nArea columns.

  • MeanAtWeight:

    • A numeric vector length nClass, where nClass is the number of weight classes for the stock (or stocks) that are being managed by the MP. The Classes slot can be used to set the size classes corresponding with MeanAtWeight. Otherwise, the classes will be taken from the corresponding Weight object in the OM (if they exist, otherwise an error).

    • For area-specific schedules, a numeric matrix with nClass rows and nArea columns.

  • Pars and Model: for Selectivity and Retention only.

These slots can be used to set the age- or size-schedules using parameters and a model. See SelectivityModels() and RetentionModels() for a details of built-in models.

Pars should be a named list of parameters, where each parameter can be either a single numeric value, or a numeric vector length nArea for area-specific schedules.

Value

An advice object.

See Also

Examples

Advice(TAC = 1000)

Advice(
  Effort  = c(1, 0.8),
  EffType = "Rel"
)

# Aggregate bag limit: 10 fish per angler per trip, discard excess
Advice(
  BagLimit    = 10,
  LimitType   = "angler",
  ClosureMode = "discard"
)

# Aggregate limit with a species-specific sub-limit 
# (2-fish sub-limit for stock 1)
Advice(
  BagLimit     = 10,
  SpeciesLimit = matrix(c(2, NA, NA, NA), nrow = 1, ncol = 4),
  LimitType    = "angler",
  ClosureMode  = "discard"
)

# Fleet-specific TAC & aggregate bag limits; no TAC for fleet 1, 
# no bag limit for fleet 2
Advice(
  TAC         = c(NA, 1000)
  BagLimit    = c(10, NA),
  LimitType   = "angler",
  ClosureMode = "discard"
)

The advice S4 Class

Description

The advice class defines management advice produced by a management procedure. Advice may include output controls (e.g. total allowable catch), input controls (e.g. effort), spatial controls (closures), gear effects, direct fishing mortality rates, or bag-limit regulations. See Advice() for details on valid entries and options for each slot.

Slots

TAC

Numeric vector length 1 or numeric length nFleet specifying total allowable catch in units of TACUnit.

TACType

Character. Does the TAC refer to "Removals" (default) or "Landings". Either length 1 (applied to all fleets) or a character vector of length nFleet.

TACUnit

Character. Units of the TAC: "Biomass" (default) or "Number". Either length 1 (applied to all fleets) or a character vector of length nFleet.

Effort

Numeric vector length 1 or numeric length nFleet specifying relative or absolute fishing effort (in units of Fleet@Effort@Effort). Can also be a matrix with dimensions nFleet x nArea to set area-specific effort limits.

EffType

Character. Are effort regulations relative to last historical year ("Rel") or absolute ("Abs"; in units of Effort()). Either length 1 (applied to all fleets) or a character vector of length nFleet. Default is "Rel".

Closure

Numeric vector length nArea or array with dimensions nFleet x nArea specifyin an area open (1; default) or closed (0) to fishing.

Selectivity

A Selectivity() object or an nFleet long list of Selectivity() objects defining gear selectivity prescribed by the MP

Retention

A Retention() object or an nFleet long list of Retention() objects defining retention prescribed by the MP

DiscardMortality

A DiscardMortality() object or an nFleet long list of DiscardMortality() objects defining discard mortality set in the MP

ApicalF

Numeric array specifying target apical fishing mortality. Not currently used

BagLimit

Numeric vector or NULL. Aggregate bag limit in fish per angler per trip (when LimitType = "angler") or fish per vessel per trip (when LimitType = "boat"). Either length 1 (applied to all fleets) or a numeric vector of length nFleet for fleet-specific limits. NULL (default) means no bag limit regulation is active. NA for a given fleet position means no aggregate limit applies to that fleet. See Advice().

SpeciesLimit

Numeric matrix or NULL. Species-specific bag limits (fish per angler or vessel per trip) within a complex, with dimensions ⁠nFleet x nStock⁠. See Advice().

LimitType

Character or NULL. Specifies whether BagLimit and SpeciesLimit are per-angler ("angler"; default) or per-vessel ("boat") regulations. Either length 1 (applied to all fleets) or a character vector of length nFleet. See Advice().

ClosureMode

Character or NULL. Determines how the OM handles catch that exceeds the bag limit: "discard" (default) converts excess catch to discards, with discard mortality applied via the fleet's DiscardMortality() object; "stop" reduces effort to prevent the limit from being exceeded. Either length 1 (applied to all fleets) or a character vector of length nFleet. See Advice().

Misc

Miscellaneous list. Will be passed to Data@Misc in following time steps.

Log

List used internally to store diagnostics

See Also

Advice(), Selectivity(), Retention(), DiscardMortality()


The advicedata S4 Class

Description

Stores management advice outputs generated during a model run or provided as input. Used in the Advice slot of a data object and accessed by LastTAC() when retrieving the most recent catch limit.

Usage

AdviceData()

Value

AdviceData() returns a advicedata object.

Slots

TAC

A numeric vector, array, or list of Total Allowable Catch (TAC) values. When a vector, elements correspond to successive advice years.

Effort

A numeric vector, array, or list of advised fishing effort values. Structured analogously to TAC.

Misc

A named list for any additional advice-level metadata (e.g., harvest control rule outputs, reference point comparisons).

AdviceData() creates a new advicedata object.

See Also

data, Data(), LastTAC()


Ages Constructor and Accessors

Description

Construct an ages object defining the discrete age structure of a stock, or access and replace the Ages slot of a stock object and its individual slots.

Usage

Ages(MaxAge, MinAge = 0, Units = "year", PlusGroup = TRUE)

Ages(x) <- value

MaxAge(x)

MaxAge(x) <- value

MinAge(x)

MinAge(x) <- value

PlusGroup(x)

PlusGroup(x) <- value

Arguments

MaxAge

numeric(1). Maximum age in units of Units. When PlusGroup = TRUE (the default), fish at or older than this age are pooled into an open-ended plus group. Required for a non-empty object; if omitted the constructor returns an uninitialised ages suitable for placeholder use inside a stock. Alternatively, a stock object, in which case Ages() returns x@Ages directly — see Pass-Through Access.

MinAge

numeric(1). Minimum (youngest) age class in units of Units. Must be non-negative and less than or equal to MaxAge. Default 0.

Units

character(1). Time unit for MinAge and MaxAge. Must be one of the strings returned by ValidUnits() (e.g., "year", "month"). Default "year".

PlusGroup

logical(1). If TRUE, MaxAge is an open-ended plus group that accumulates all fish at or beyond that age. If FALSE, the age classes terminate at exactly MaxAge with no pooling. Default TRUE.

x

An ages object for slot accessors (MaxAge(), MinAge(), PlusGroup()), or a stock object for ⁠Ages<-⁠.

value

For ⁠Ages<-⁠: an ages object. For ⁠MaxAge<-⁠, ⁠MinAge<-⁠, ⁠PlusGroup<-⁠: the replacement value for the corresponding slot (see Slot Accessors).

Details

Age Class Calculation

The Classes slot — a numeric vector of age classes expressed in years — is derived automatically from MinAge, MaxAge, and Units via CalcAgeClasses() and cannot be set directly. For seasonal models (Units != "year"), fractional year values are produced (e.g., 0, 0.25, 0.5, … for quarterly seasons with MinAge = 0). Retrieve the computed vector with Classes(x).

Plus Group

When PlusGroup = TRUE, the final age class absorbs all individuals at or beyond MaxAge. Mortality, growth, and selectivity at the plus-group age represent the average for that pooled cohort. Setting PlusGroup = FALSE treats MaxAge as an exact terminal age with no accumulation.

Uninitialised Objects

Calling Ages() without MaxAge returns an object with empty MaxAge and MinAge slots (numeric(0)). Validity checks are skipped for uninitialised objects, so they can be stored as placeholders inside a stock before parameters are specified. The model will not run until MaxAge is supplied.

Pass-Through Access from a Stock

When MaxAge is a stock object, Ages() acts as an accessor:

Ages(my_stock)          # returns my_stock@Ages
Ages(my_stock) <- a     # replaces my_stock@Ages with ages-class object `a`

Slot Accessors

Individual slots can be read or replaced using functions that match the slot names. All replacement functions re-validate the object after assignment:

MaxAge(a)        <- 20
MinAge(a)        <- 1
PlusGroup(a)     <- FALSE

Value

Ages() returns an ages object. If MaxAge is a stock, returns x@Ages.

⁠Ages<-⁠ returns the stock x with the Ages slot replaced by value and the object re-validated.

MaxAge(), MinAge(), PlusGroup() return the value of the corresponding slot from x.

⁠MaxAge<-⁠, ⁠MinAge<-⁠, ⁠PlusGroup<-⁠ return x with the named slot updated and the object re-validated.

See Also

ages for the class definition and slot-level documentation. Stock() for the enclosing stock constructor. ValidUnits() for accepted unit strings. Classes() to retrieve the derived age-class vector.

Other ages: ages-class

Examples

# Basic construction
a <- Ages(MaxAge = 20)
a

# Seasonal model: quarterly age classes
a_qtr <- Ages(MaxAge = 20, Units = "quarter")
Classes(a_qtr)

# No plus group
a_exact <- Ages(MaxAge = 20, PlusGroup = FALSE)

# Slot accessors
MaxAge(a)
MaxAge(a) <- 25

MinAge(a)
MinAge(a) <- 1

PlusGroup(a)
PlusGroup(a) <- FALSE

# Pass-through access from a stock
s <- Stock(Name = "Cod", Ages = Ages(MaxAge = 15))
Ages(s)
Ages(s) <- Ages(MaxAge = 20)

The ages S4 Class

Description

Defines the discrete age structure of a stock object. Objects are typically created via Ages(), which documents all parameters and validates inputs.

Details

An object is considered uninitialised when MaxAge or MinAge is numeric(0).

Validity is enforced on non-empty objects: MaxAge and MinAge must be finite scalars, MinAge must be non-negative, MaxAge >= MinAge, and Units must be a scalar string accepted by ValidUnits().

Direct construction via methods::new() is not recommended; use Ages() instead, which populates Classes automatically.

Slots

MaxAge

numeric(1). Maximum age in units of Units. When PlusGroup = TRUE, fish older than this age are pooled into the plus group.

MinAge

numeric(1). Minimum (youngest) age class in units of Units. Must be non-negative and less than or equal to MaxAge.

Units

character(1). Time unit for MinAge and MaxAge. Must be one of the values returned by ValidUnits() (e.g., "year").

PlusGroup

logical(1). If TRUE, MaxAge is treated as an open-ended plus group that accumulates all fish at or beyond that age.

Classes

numeric. Vector of age classes in years, derived automatically from MinAge, MaxAge, and Units by CalcAgeClasses(). Not intended to be set directly; use Ages() to trigger recalculation.

See Also

  • Ages() for the constructor and slot-accessor functions.

  • stock for the enclosing object.

  • ValidUnits() for accepted unit strings.

  • Classes() to retrieve the computed age-class vector.

Other ages: Ages()


Age-Structured Observation Model

Description

An obs object representing a data-moderate scenario suitable for age-structured stock assessment. Landings, dicards, a fishery-independent survey, and annual age-composition samples from both landed and discarded fish are simulated.

Usage

AgeStructuredObs

Format

An obs object. Populated slots:

  • Landings (catchobs): precisely reported landings with CV in ⁠[0.05, 0.10]⁠ and near-unbiased reporting ⁠[0.95, 1.05]⁠.

  • Discards (catchobs): less precisely reported discards with CV in ⁠[0.15, 0.25]⁠ and near-unbiased reporting ⁠[0.95, 1.05]⁠.

  • Survey (indicesobs): annual survey targeting spawning biomass with CV in ⁠[0.10, 0.20]⁠ and negligible autocorrelation ⁠[0.0, 0.1]⁠.

  • LandingsAtAge (compobs): age-composition samples of landed fish from a port-sampling programme. Nominal sample size ⁠[200, 400]⁠ fish per year; ESS ⁠[50, 100]⁠ reflecting within-trip clustering; Dirichlet-Multinomial dispersion Theta in ⁠[0.5, 1.0]⁠.

  • DiscardsAtAge (compobs): age-composition samples of discarded fish from at-sea observers. Nominal sample size ⁠[100, 200]⁠; ESS ⁠[30, 80]⁠; Theta in ⁠[0.4, 0.8]⁠, reflecting higher uncertainty relative to port sampling.

Empty slots (no data simulated): Effort, CPUE, LandingsAtSize, DiscardsAtSize.

See Also

obs, Obs(), CatchObs(), IndicesObs(), CompObs(), CatchAndSurveyObs, CommercialFleetObs, LengthStructuredObs, DataRichObs

Other obs-examples: CatchAndSurveyObs, CommercialFleetObs, DataRichObs, LengthStructuredObs

Examples

AgeStructuredObs
LandingsAtAge(AgeStructuredObs)
DiscardsAtAge(AgeStructuredObs)

Stock class objects

Description

Example objects of class Stock

Usage

Albacore

Blue_shark

Bluefin_tuna

Bluefin_tuna_WAtl

Butterfish

Herring

Mackerel

Porgy

Rockfish

Snapper

Sole

Toothfish

Format

An object of class Stock of length 1.

An object of class Stock of length 1.

An object of class Stock of length 1.

An object of class Stock of length 1.

An object of class Stock of length 1.

An object of class Stock of length 1.

An object of class Stock of length 1.

An object of class Stock of length 1.

An object of class Stock of length 1.

An object of class Stock of length 1.

An object of class Stock of length 1.

An object of class Stock of length 1.

Examples

avail("Stock")

MOM class objects

Description

Example objects of class MOM

Usage

Albacore_TwoFleet

Format

An object of class MOM of length 1.

Examples

avail("MOM")

Albacore Example Stock

Description

An example stock object representing an Albacore tuna (Thunnus alalunga) stock. This is a long-lived, slow-growing, large pelagic species with low natural mortality. See also ButterfishExStock for a contrasting short-lived, fast-growing example.

Usage

AlbacoreExStock

Format

A stock object with the following slots populated:

  • Name: "AlbacoreExStock".

  • CommonName: "Albacore".

  • Species: "Thunnus alalunga".

  • Ages: An Ages() object with MaxAge = 20 years.

  • Length: A Length() object with von Bertalanffy parameters — Linf (121–135 cm), K (0.16–0.22 yr^-1^), t0 (-1.86 to -1.41 yr) — and CVatAge (0.1–0.15).

  • Weight: A Weight() object with allometric parameters alpha = 1.34e-05 and beta = 3.106.

  • NaturalMortality: A NaturalMortality() object with M = 0.35–0.45 yr^-1^.

  • Maturity: A Maturity() object with logistic maturity-at-length parameters L50 (81–91 cm) and L50_95 (10–12 cm).

  • Fecundity: An empty Fecundity() object; fecundity-at-age is computed internally during population (see Details).

  • SRR: A SRR() object with Beverton-Holt steepness h (0.65–0.85), unfished recruitment R0 = 1000, recruitment variability SD (0.15–0.3), and autocorrelation AC (0.1–0.9).

  • Spatial: A Spatial() object with UnfishedDist (0.095–0.105), ProbStaying (0.8–0.9), and RelativeSize (0.095–0.105).

  • Depletion: A Depletion() object with current biomass sampled from 5–60% of B0.

  • nYear, pYear, nSim, CurrentYear, Years, Seasons: Set by PopulateStock().

  • Misc: Empty list for user-defined information.

  • Log: Internal list for tracking object state.

Two-element numeric vectors in the slot descriptions above are uniform bounds. PopulateStock() samples from these bounds across simulations and expands the results into ⁠[nSim x nAge x nYear]⁠ arrays. The sections below describe what each component-level ⁠Populate*()⁠ function produces.

Ages

CalcAgeClasses() generates the integer age vector Ages@Classes (0:20), which is used as the age dimension in all subsequent arrays.

Length

PopulateLength() samples Linf, K, and t0 independently for each simulation from uniform distributions defined by the bounds, then computes mean length-at-age using the von Bertalanffy growth equation. CVatAge is expanded across simulations and, when ALK = TRUE, an age–length key is constructed.

See also LengthModels().

Weight

PopulateWeight() applies the allometric relationship W = alpha × L^beta^ to the mean length-at-age array to produce mean weight-at-age. An age–weight key is optionally constructed when AWK = TRUE.

See also WeightModels().

Natural Mortality

PopulateNaturalMortality() samples M for each simulation from the uniform bounds and expands the result into a natural mortality-at-age array. Stochastic annual deviates are added via PopulateRandom().

See also NaturalMortalityModels().

Maturity

PopulateMaturity() applies the logistic maturity-at-length curve, parameterised by L50 and L50_95, to the populated length-at-age array to produce a maturity-at-age array.

See also MaturityModels().

Fecundity

Because the Fecundity slot is empty, PopulateFecundity() computes fecundity-at-age as the element-wise product of weight-at-age and maturity-at-age, representing spawning output per individual.

See also FecundityModels().

Stock–Recruitment

PopulateSRR() samples h for each simulation from the uniform prior and generates a time series of log-normal recruitment deviates with standard deviation SD and autocorrelation AC.

Spatial

PopulateSpatial() samples UnfishedDist, ProbStaying, and RelativeSize for each simulation and uses them to construct a full inter-area movement matrix, then expands all spatial arrays across simulations and years. The relatively high ProbStaying (0.8–0.9) reflects low connectivity between the two areas.

See also SRRModels().

Depletion

PopulateDepletion() samples current biomass depletion relative to B0 for each simulation from the uniform prior, setting the initial conditions of the operating model.

See Also

ButterfishExStock, Stock(), PopulateStock(), Populate(), stock

Examples

AlbacoreExStock

## Not run: 
PopulatedStock <- PopulateStock(
  AlbacoreExStock,
  nYear = 50,
  pYear = 30,
  nSim = 48,
  seed = 42
)

## End(Not run)

Apply AR(1) autocorrelation to residuals, skipping NAs

Description

Applies AR(1) propagation to a numeric matrix of residuals (⁠sim x year⁠), respecting missing values (NAs). Autocorrelation is applied only across non-NA values within each simulation.

Usage

ApplyAC(LogResid, AC, LastError)

Arguments

LogResid

Numeric matrix of log residuals, dimensions nSim x nYear.

AC

Numeric vector of length nSim, autocorrelation coefficient per simulation (must be in between -1 & 1).

LastError

Numeric vector of length nSim, starting value for each simulation.

Value

Numeric matrix of same dimensions as LogResid with autocorrelated residuals.

See Also

GenResiduals(), CalcResidualStats()


Apply multi Management Procedures (class MMP) to a hierarchical list of Data class objects

Description

Apply multi Management Procedures (class MMP) to a hierarchical list of Data class objects

Usage

applyMMP(
  DataList,
  MP = NA,
  reps = 1,
  nsims = NA,
  silent = FALSE,
  parallel = snowfall::sfIsRunning()
)

Arguments

DataList

A hierarchical list of Data objects (Fleets nested in Stocks)

MP

Name of the MMP to run

reps

Number of samples

nsims

Optional. Number of simulations.

silent

Logical. Should messages be suppressed?

parallel

Logical. Whether to run MPs in parallel

Value

A hierarchical list of management recommendations (object class Rec), Fleets nested in Stocks


Apply Management Procedures to an object of class Data

Description

Apply Management Procedures to an object of class Data

Usage

applyMP(
  Data,
  MPs = NA,
  reps = 100,
  nsims = NA,
  silent = FALSE,
  parallel = snowfall::sfIsRunning()
)

Arguments

Data

An object of class Data

MPs

Name(s) of the MPs to run

reps

Number of samples

nsims

Optional. Number of simulations.

silent

Logical. Should messages be suppressed?

parallel

Logical. Whether to run MPs in parallel. Can be a vector of length(MPs)

Value

A list with the first element a list of management recommendations, and the second the updated Data object


Convert Between Arrays and Data Frames

Description

Array2DF() converts a matrix or array to a tidy data frame, with dimension names mapped to columns (Sim, Stock, Age, Year, Fleet, Area) and values in a Value column. Numeric columns are coerced with as.numeric(); Stock and Fleet are returned as ordered factors.

Usage

Array2DF(array)

DF2Array(DF)

Arguments

array

A matrix or array object.

DF

A data.frame containing a Value column and at least one dimension column (Sim, Stock, Age, Year, Fleet, Area).

Details

DF2Array() is the inverse: it reshapes a tidy data frame back into a named array, using any columns whose names match Sim, Stock, Age, Year, Fleet, or Area as array dimensions.

Value

  • Array2DF() returns a data.frame with one row per array element and one column per dimension plus a Value column.

  • DF2Array() returns a named array whose dimensions and dimnames are derived from the unique values of the dimension columns in DF.

Examples

# Round-trip: array -> data frame -> array
a <- array(1:24, dim = c(2, 3, 4),
           dimnames = list(Sim = 1:2, Year = 1:3, Age = 1:4))
df <- Array2DF(a)
df
DF2Array(df)

Perform Operations on Two Arrays

Description

Multiply, divide, subtract, or add two arrays together.

Usage

ArraySum(array1, array2)

ArrayDivide(array1, array2)

ArrayMultiply(array1, array2)

ArraySubtract(array1, array2)

ArrayExtend(array1, array2)

ArrayFill(object) <- value

Arguments

array1

An array with named dimensions.

array2

An array with the same named dimensions as array1.

object

An array with named dimensions

value

An array with the same dimension names as object

Details

The arrays must have the same named dimensions, but do not need to have the same length for each dimension.

  • ArraySum: Sum array1 and array2

  • ArrayDivide: Divide array1 by array2

  • ArrayMultiply: Multiply array1 and array2

  • ArraySubtract: Subtract array2 from array1

  • ArrayExtend: extends the arrays to have matching dimensions (see Extend())

  • ArrayFill: Update array object with the values in value

Value

The resulting array

Examples

# Array with Sim, Year 
array1 <- array(1:20, 
                dim=c(2,5),
                dimnames = list(
                  Sim=1:2,
                  Year=2021:2025
                ))

array2 <- array(1:20, 
                dim=c(1,3),
                dimnames = list(
                  Sim=1,
                  Year=2024:2026
                ))

ArrayExtend(array1, array2)

ArraySum(array1, array2)
ArrayDivide(array1, array2)
ArrayMultiply(array1, array2)
ArraySubtract(array1, array2)



# Array with Age, Year 
array1 <- array(1:20, 
                dim=c(5,2),
                dimnames = list(
                  Age=1:5,
                  Year=2021:2022
                ))

array2 <- array(1:20, 
                dim=c(1,3),
                dimnames = list(
                  Age=1,
                  Year=2024:2026
                ))

ArrayExtend(array1, array2)

ArraySum(array1, array2)
ArrayDivide(array1, array2)
ArrayMultiply(array1, array2)
ArraySubtract(array1, array2)


# ArrayFill

## Same dimensions
object <- array(NA, 
               dim=c(3,5),
               dimnames=list(Sim=1:3,
                             Year=2021:2025)
)

value <- array(1:2, 
               dim=c(1,2),
               dimnames=list(Sim=2,
                             Year=2022:2023)
)

ArrayFill(object) <- value
object


## Extend Dimensions
object <- array(NA, 
                dim=c(3,5),
                dimnames=list(Sim=1:3,
                              Year=2021:2025)
)

value <- array(1:12, 
               dim=c(3,4),
               dimnames=list(Sim=1:3,
                             Year=c(2019, 2025:2027))
)

ArrayFill(object) <- value
object

Convert ASAP 3 assessments into an operating model

Description

Reads a fitted ASAP model and uses the MLE estimates with identical reconstruction among simulations. Future recruitment is sampled from a lognormal distribution with autocorrelation. ASAP2Data imports a Data object.

Usage

ASAP2OM(
  asap,
  nsim = 48,
  proyears = 50,
  mcmc = FALSE,
  spawn_time_frac = 0,
  Name = "ASAP Model",
  Source = "No source provided",
  nyr_par_mu = 3,
  Author = "No author provided",
  report = FALSE,
  silent = FALSE
)

ASAP2Data(asap, Name = "ASAP assessment")

Arguments

asap

A list returned by ASAP, e.g., asap <- dget("asap3.rdat").

nsim

The number of simulations in the operating model

proyears

The number of MSE projection years

mcmc

Logical, whether to use mcmc samples. Currently unsupported.

spawn_time_frac

Numeric, the fraction of a year when spawning takes place (e.g., 0.5 is the midpoint of the year)

Name

The name of the operating model

Source

Reference to assessment documentation e.g. a url

nyr_par_mu

integer, the number of recent years to estimate vulnerability over for future projections

Author

Who did the assessment

report

Logical, should a comparison of biomass reconstruction be produced?

silent

Logical, should progress reporting be printed to the console?

Details

Length at age is not used in ASAP so arbitrary placeholder values are used for length-based parameters. Update these parameters to model length in the operating model.

Value

An operating model OM class.

Author(s)

Q. Huynh

See Also

Assess2OM


Reads bootstrap estimates from a stock assessment model into a multi-fleet operating model.

Description

A function that develops a multiple fleet operating model (MOM) and either models a unisex or 2-sex stock from arrays of abundance, fishing mortality, and biological parameters. The user still needs to parameterize most of the observation and implementation portions of the operating model.

Usage

Assess2MOM(
  Name = "MOM created by Assess2MOM",
  proyears = 50,
  interval = 2,
  CurrentYr = as.numeric(format(Sys.Date(), "%Y")),
  h = 0.999,
  Obs = MSEtool::Imprecise_Unbiased,
  Imp = MSEtool::Perfect_Imp,
  naa,
  faa,
  waa,
  Mataa,
  Maa,
  laa,
  fecaa,
  nyr_par_mu = 3,
  LowerTri = 1,
  recind = 0,
  plusgroup = TRUE,
  altinit = 0,
  fixq1 = TRUE,
  report = FALSE,
  silent = FALSE,
  ...
)

Arguments

Name

Character string. The name of the multi-OM.

proyears

Positive integer. The number of projection years for MSE.

interval

Positive integer. The interval at which management procedures will update the management advice in multiMSE, e.g., 1 = annual updates.

CurrentYr

Positive integer. The current year (e.g., final year of fitting to data)

h

The steepness of the stock-recruitment curve. Either a single numeric or a length nsim vector.

Obs

Either a single observation model to be used for all sexes and populations (class Obs), or a list where Obs[[f]] is the Obs object for fleet f (identical between sexes).

Imp

Either a single implementation model to be used for all sexes and populations (class Imp), or a list where Imp[[f]] is the Obs object for fleet f (identical between sexes).

naa

Numbers-at-age by sex ⁠[first age is age zero]⁠. Four-dimensional numeric array ⁠[sim, ages, year, p]⁠. ⁠[p]⁠ indexes the population, where ⁠[p = 1]⁠ for females and ⁠[p = 2]⁠ for males.

faa

Fishing mortality rate-at-age by sex and fleet ⁠[first age is age zero]⁠. Five-dimensional numeric array ⁠[sim, ages, year, p, f]⁠ where ⁠[f]⁠ indexes fishery fleet.

waa

Weight-at-age ⁠[first age is age zero]⁠. Four-dimensional numeric array ⁠[sim, ages, year, p]⁠.

Mataa

Maturity (spawning fraction)-at-age ⁠[first age is age zero]⁠. Four-dimensional numeric array ⁠[sim, ages, year, p]⁠.

Maa

Natural mortality rate-at-age ⁠[first age is age zero]⁠. Four-dimensional numeric array ⁠[sim, ages, year, p]⁠.

laa

Length-at-age ⁠[first age is age zero]⁠. Four-dimensional numeric array ⁠[sim, ages, year, p]⁠.

fecaa

Fecundity at age ⁠[first age is age zero]⁠. If missing, default fecundity is the product of maturity and weight at age.

nyr_par_mu

Positive integer. The number of recent years that natural mortality, age vulnerability, weight, length and maturity parameters are averaged over for defining future projection conditions.

LowerTri

Integer. The number of recent years for which model estimates of recruitment are ignored (not reliably estimated by the assessment)

recind

Positive integer. The first age class that fish 'recruit to the fishery'. The default is 0 - ie the first position in the age dimension of naa is age zero

plusgroup

Logical. Does the assessment assume that the oldest age class is a plusgroup?

altinit

Integer. Various assumptions for how to set up the initial numbers. 0: standard, 1: no plus group, 2: temporary fix for MSEtool plus group initialization

fixq1

Logical. Should q be fixed (ie assume the F-at-age array faa is accurate?

report

Logical, if TRUE, a diagnostic will be reported showing the matching of the OM reconstructed numbers at age vs the assessment.

silent

Whether to silence messages to the console.

...

Additional arguments (for all, either a numeric or a length nsim vector):

  • SRrel Stock-recruit relationship. (1 for Beverton-Holt (default), 2 for Ricker)

  • R0 unfished recruitment

  • phi0 unfished spawners per recruit associated with R0 and h. With time-varying parameters, openMSE uses the mean phi0 in the first ageM (age of 50 percent maturity) years for the stock-recruit relationship. Assess2OM will re-calculate R0 and h in the operating model such that the stock-recruit alpha and beta parameters match values implied in the input.

  • Perr recruitment standard deviation (lognormal distribution) for sampling future recruitment

  • AC autocorrelation in future recruitment deviates.

Details

Use a seed for the random number generator to sample future recruitment.

Value

An object of class MOM

Author(s)

Q. Huynh

See Also

SS2MOM multiMSE Assess2OM


Reads bootstrap estimates from a stock assessment model (including VPA) into an operating model. Assess2OM is identical to VPA2OM.

Description

A function that uses a set of bootstrap estimates of numbers-at-age, fishing mortality rate-at-age, M-at-age, weight-at-age, length-at-age and Maturity-at-age to define a fully described MSEtool operating model. The user still needs to parameterize most of the observation and implementation portions of the operating model.

Usage

Assess2OM(
  Name = "A fishery made by VPA2OM",
  proyears = 50,
  interval = 2,
  CurrentYr = as.numeric(format(Sys.Date(), "%Y")),
  h = 0.999,
  Obs = MSEtool::Imprecise_Unbiased,
  Imp = MSEtool::Perfect_Imp,
  naa,
  faa,
  waa,
  Mataa,
  Maa,
  laa,
  nyr_par_mu = 3,
  LowerTri = 1,
  recind = 0,
  plusgroup = TRUE,
  altinit = 0,
  fixq1 = TRUE,
  report = FALSE,
  silent = FALSE,
  ...
)

VPA2OM(
  Name = "A fishery made by VPA2OM",
  proyears = 50,
  interval = 2,
  CurrentYr = as.numeric(format(Sys.Date(), "%Y")),
  h = 0.999,
  Obs = MSEtool::Imprecise_Unbiased,
  Imp = MSEtool::Perfect_Imp,
  naa,
  faa,
  waa,
  Mataa,
  Maa,
  laa,
  nyr_par_mu = 3,
  LowerTri = 1,
  recind = 0,
  plusgroup = TRUE,
  altinit = 0,
  fixq1 = TRUE,
  report = FALSE,
  silent = FALSE,
  ...
)

Arguments

Name

Character string. The name of the operating model.

proyears

Positive integer. The number of projection years for MSE.

interval

Positive integer. The interval at which management procedures will update the management advice in runMSE, e.g., 1 = annual updates.

CurrentYr

Positive integer. The current year (final year of fitting to data)

h

The steepness of the stock-recruitment curve (greater than 0.2 and less than 1, assumed to be close to 1 to match VPA assumption). Either a single numeric or a length nsim vector.

Obs

The observation model (class Obs). This function only updates the catch and index observation error.

Imp

The implementation model (class Imp). This function does not update implementation parameters.

naa

Numeric array ⁠[sim, ages, year]⁠. Numbers-at-age ⁠[first age is age zero]⁠.

faa

Numeric array ⁠[sim, ages, year]⁠. Fishing mortality rate-at-age ⁠[first age is age zero]⁠.

waa

Numeric array ⁠[sim, ages, year]⁠. Weight-at-age ⁠[first age is age zero]⁠.

Mataa

Numeric array ⁠[sim, ages, year]⁠. Maturity (spawning fraction)-at-age ⁠[first age is age zero]⁠.

Maa

Numeric array ⁠[sim, ages, year]⁠. Natural mortality rate-at-age ⁠[first age is age zero]⁠.

laa

Numeric array ⁠[sim, ages, year]⁠. Length-at-age ⁠[first age is age zero]⁠.

nyr_par_mu

Positive integer. The number of recent years that natural mortality, age vulnerability, weight, length and maturity parameters are averaged over for defining future projection conditions.

LowerTri

Integer. The number of recent years for which model estimates of recruitment are ignored (not reliably estimated by the assessment)

recind

Positive integer. The first age class that fish 'recruit to the fishery'. The default is 0 - ie the first position in the age dimension of naa is age zero

plusgroup

Logical. Does the assessment assume that the oldest age class is a plusgroup?

altinit

Integer. Various assumptions for how to set up the initial numbers. 0: standard, 1: no plus group, 2: temporary fix for MSEtool plus group initialization

fixq1

Logical. Should q be fixed (ie assume the F-at-age array faa is accurate?

report

Logical, if TRUE, a diagnostic will be reported showing the matching of the OM reconstructed numbers at age vs the assessment.

silent

Whether to silence messages to the console.

...

Additional arguments (for all, either a numeric or a length nsim vector):

  • fecaa Fecundity at age. Default fecundity is the product of maturity and weight at age.

  • SRrel Stock-recruit relationship. (1 for Beverton-Holt (default), 2 for Ricker)

  • R0 unfished recruitment

  • phi0 unfished spawners per recruit associated with R0 and h. With time-varying parameters, openMSE uses the mean phi0 in the first ageM (age of 50 percent maturity) years for the stock-recruit relationship. Assess2OM will re-calculate R0 and h in the operating model such that the stock-recruit alpha and beta parameters match values implied in the input.

  • Perr recruitment standard deviation (lognormal distribution) for sampling future recruitment

  • AC autocorrelation in future recruitment deviates.

  • spawn_time_frac The fraction of a year when spawning takes place (e.g., 0.5 is the midpoint of the year)

Details

Use a seed for the random number generator to sample future recruitment.

Value

An object of class OM.

Author(s)

T. Carruthers

See Also

SS2OM iSCAM2OM WHAM2OM ASAP2OM


Asymptotic Selectivity Example Fleet

Description

An example fleet object demonstrating a fleet with effort that stabilises early in the historical period and asymptotic length-based selectivity. Intended for use with AlbacoreExStock or ButterfishExStock to illustrate fleet parameterization in MSEtool. See also DomeExFleet for a contrasting dome-shaped selectivity example.

Usage

AsympExFleet

Format

A fleet object with the following slots populated:

  • Name: "AsympExFleet". Unique fleet identifier.

  • Effort: An Effort() object with a piecewise-linear historical effort trajectory defined at four relative time points (0, 0.3, 0.6, 1.0), with lower and upper bounds of (0, 0.4, 1, 1) and (0, 0.6, 1, 1) respectively, and CV = 0.1 controlling stochastic variation around the trend.

  • Selectivity: A Selectivity() object with asymptotic length-based selectivity parameters — L5 (0.4–0.5), LFS (0.7–0.8), and Vmaxlen = 1 (fixed) — with isRel = TRUE indicating that L5 and LFS are expressed relative to maturity L50.

  • Catchability: An empty Catchability() object; efficiency defaults to 1 across all years during population (see Details).

  • Retention: An empty Retention() object; full retention is assumed during population (see Details).

  • DiscardMortality: An empty DiscardMortality() object.

  • Closure: NULL. No spatial or temporal closures defined.

  • WeightFleet: NA. Fleet-specific weight-at-age is set to the stock weight-at-age during population (see Details).

  • Bioeconomic: An empty Bioeconomic() object.

  • nYear, pYear, nSim, CurrentYear, Years, Seasons: Inherited from the paired Stock() object by PopulateFleet().

  • Misc: Empty list for user-defined information.

Details

PopulateFleet() expands the input parameters into ⁠[nSim x nAge x nYear]⁠ arrays using the age, length, and spatial structure of the paired populated stock. The sections below describe what each component-level ⁠Populate*()⁠ function produces.

Effort

PopulateEffort() interpolates the piecewise-linear effort trajectory across all historical years for each simulation, then applies log-normal stochastic deviates scaled by CV = 0.1. The trajectory rises from 0 to 40–60% of maximum effort by 30% of the historical period, then reaches full effort by 60% of the period and remains stable thereafter. This contrasts with DomeExFleet, where effort continues to rise through to the final historical year.

Catchability

Because the Catchability slot is empty, PopulateCatchability() sets catchability efficiency to 1 across all simulations and years. No trend (qInc) or inter-annual variability (qCV) is applied.

Selectivity

PopulateSelectivity() samples L5 and LFS for each simulation from uniform distributions defined by the prior bounds. Because isRel = TRUE, both are scaled by the maturity L50 of the paired stock before computing the selectivity curve. Vmaxlen = 1 is fixed, so selectivity reaches 1.0 at maximum length in all simulations, producing a strictly asymptotic curve. The resulting selectivity-at-length is converted to selectivity-at-age using the stock age–length key, and an area dimension is added.

Retention

Because the Retention slot is empty, PopulateRetention() sets full retention (1.0) across all ages, lengths, simulations, and years.

Discard Mortality

Because the DiscardMortality slot is empty, PopulateDiscardMortality() applies default discard mortality values. All discarded fish are assumed to survive (discard mortality = 0) unless overridden.

Spatial Closures

Because Closure is NULL, PopulateClosure() applies no spatial or temporal closures; all areas are open to fishing in all years.

Fleet Weight-at-Age

Because WeightFleet is NA, PopulateFleet() sets it equal to the stock mean weight-at-age array, so fleet-level biomass calculations use the same weight schedule as the stock.

See Also

DomeExFleet, AlbacoreExStock, ButterfishExStock, Fleet(), PopulateFleet(), Populate(), fleet

Examples

AsympExFleet

## Not run: 
PopulatedStock <- PopulateStock(AlbacoreExStock, nYear = 50, pYear = 30, nSim = 48)
PopulatedFleet <- PopulateFleet(AsympExFleet, Stock = PopulatedStock, seed = 42)

## End(Not run)

Data class objects

Description

Example objects of class Data

Usage

Atlantic_mackerel

China_rockfish

Cobia

Example_datafile

Gulf_blue_tilefish

ourReefFish

Red_snapper

Simulation_1

Format

An object of class Data of length 1.

An object of class Data of length 1.

An object of class Data of length 1.

An object of class Data of length 1.

An object of class Data of length 1.

An object of class Data of length 1.

An object of class Data of length 1.

An object of class Data of length 1.

Examples

avail("Data")

What objects of this class are available

Description

Generic class finder

Usage

avail(classy, package = NULL, msg = TRUE, abc = FALSE)

Arguments

classy

A class of object (character string, e.g. 'Fleet')

package

Optional. Names(s) of the package to search for object of class classy. String Default is all openMSE packages. Always searches the global environment as well.

msg

Print messages?

abc

Logical, whether to alphabetize the results. By default, the function returns results found in the global environment, then core openMSE packages, and any additional packages in argument package.

Details

Finds objects of the specified class in the global environment or the openMSE packages.

Author(s)

T. Carruthers

See Also

Can Cant avail

Examples

avail("OM", msg=FALSE)
Stocks <- avail("Stock")
Fleets <- avail("Fleet")
MPs <- avail("MP")

Reads MCMC estimates from Awatea (Paul Starr) processed r file structure into an operating model

Description

A function that generates an operating model from the MCMC samples of an Awatea model. Code optimized for the BC Pacific ocean perch assessment (Haigh et al. 2018).

Usage

Awatea2OM(
  AwateaDir,
  nsim = 48,
  proyears = 50,
  Name = "OM made by Awatea2OM",
  Source = "No source provided",
  Author = "No author provided",
  verbose = TRUE
)

Arguments

AwateaDir

A folder with Awatea files

nsim

The number of simulations

proyears

The number of projection years for the MSE

Name

The name of the operating model

Source

Reference to assessment documentation e.g. a url

Author

Who did the assessment

verbose

Return detailed messages?

Details

This function averages biological parameters across sex and then sends arrays to VPA2OM, assumes unfished status (B/B0 = 1) in the first year, and assumes a single fishing fleet.

Author(s)

Q. Huynh and T. Carruthers

References

Haigh, R., et al. 2018. Stock assessment for Pacific Ocean Perch (Sebastes alutus) in Queen Charlotte Sound, British Columbia in 2017. Canadian Science Advisory Secretariat (CSAS) Research Document 2018/038. 232 pp. https://www.dfo-mpo.gc.ca/csas-sccs/Publications/ResDocs-DocRech/2018/2018_038-eng.html


Import a multi-stock, multi-fleet OM from a BAM object

Description

Import a multi-stock, multi-fleet OM from a BAM object

Usage

BAM2MOM(
  rdat,
  nsim = 48,
  proyears = 50,
  interval = 1,
  stock_name = NULL,
  fleet_name = NULL,
  LowerTri = 0,
  report = FALSE,
  ...
)

BAM2OM(rdat, nsim = 48, proyears = 50, interval = 2, report = FALSE, ...)

Arguments

rdat

A list object from the BAMextras package. Use bamExtras::standardize_rdat(rdat)

nsim

the number of simulations

proyears

the number of projection years

interval

the management interval

stock_name

Name of the stock(s)

fleet_name

Name of the fleet(s)

LowerTri

Integer. The number of recent years for which model estimates of recruitment are ignored (not reliably estimated by the assessment)

report

Logical, if TRUE, a diagnostic will be reported showing the matching of the OM reconstructed numbers at age vs the assessment.

...

Additional arguments passed to MSEtool::Assess2MOM

Value

An object of class MOM

Functions

  • BAM2OM(): Create a single stock/fleet OM from a BAM object


Get and Fix BAM Fleet Names

Description

GetBAMFleetNames() extracts and classifies fleet names from a BAM stock assessment, separating retained (landings) fleets from discard fleets. FixFleetNames() is a helper that standardises raw BAM fleet name strings by stripping leading "L." prefixes and converting leading "D." prefixes to trailing ".D" suffixes.

Usage

GetBAMFleetNames(Stock)

FixFleetNames(FleetNames)

Arguments

Stock

A character string matching a stock name available in bamExtras (e.g., 'Red Snapper'), or a list of BAM output objects containing elements rdat and dat.

FleetNames

A character vector of raw fleet name strings as extracted from BAM output.

Value

GetBAMFleetNames() returns a named list with four elements:

  • ⁠$FleetNames⁠: character vector of all fleet names, cleaned via FixFleetNames().

  • ⁠$RetainFleets⁠: character vector of landings (retained catch) fleets, i.e. all fleets not classified as discard fleets.

  • ⁠$DiscardFleets⁠: character vector of discard fleets, identified as those ending in ".D" or, if none found, starting with "D.".

  • ⁠$FleetNamesOrig⁠: character vector of original fleet names as they appear in BAMdata$parms, before cleaning.

FixFleetNames() returns a character vector the same length as FleetNames with standardised names.

See Also

GetBAMOutput()

Examples

## Not run: 
GetBAMFleetNames('Red Snapper')

## End(Not run)

FixFleetNames(c('L.cHL', 'D.rHB', 'cPT'))

Extract Biological Time Series

Description

Biomass(), SBiomass(), and SProduction() extract total biomass, spawning biomass, and spawning production, respectively, from a hist or mse object.

Usage

Biomass(
  object,
  df = TRUE,
  byAge = FALSE,
  byArea = FALSE,
  Reduce = TRUE,
  IncYear = FALSE
)

SBiomass(
  object,
  df = TRUE,
  byAge = FALSE,
  byArea = FALSE,
  Reduce = TRUE,
  IncYear = FALSE
)

SProduction(
  object,
  df = TRUE,
  byAge = FALSE,
  byArea = FALSE,
  Reduce = TRUE,
  IncYear = FALSE
)

Arguments

object

A hist or mse object.

df

Logical. If FALSE the raw array slot is returned. If TRUE (default) a tidy data.frame is returned.

byAge

Logical. If TRUE the data frame retains the Age dimension. Values are derived by multiplying numbers-at-age by the relevant biological schedule before optionally summing over age. Ignored when df = FALSE.

byArea

Logical. If TRUE the data frame retains the Area dimension. Ignored when df = FALSE.

Reduce

Logical. If TRUE (default) simulation dimensions are reduced using ReduceDims() before conversion to a data frame.

IncYear

Logical. Passed to ReduceDims(); controls whether the year dimension is retained during reduction. Default FALSE.

Details

When applied to an mse object the historical and projection periods are row-bound and labelled via the Period column; historical rows carry MP = "Historical".

Value

  • df = FALSE — the raw array slot (Biomass, SBiomass, or SProduction).

  • df = TRUE — a tidy data.frame with columns Sim, Stock, Year, Period, MP (MSE only), and optionally Age / Area, plus Value, Variable, and Units.

See Also

Number()

Examples

Hist <- Simulate(SingleStockOM)
MSE <- Project(Hist, 'CurrentEffort')

# Raw array
Biomass(Hist)
Biomass(MSE)

# Tidy data frames
Biomass(Hist, df = TRUE)
Biomass(MSE,  df = TRUE)

# Retain age and area structure
Biomass(MSE, df = TRUE, byAge = TRUE)
Biomass(MSE, df = TRUE, byArea = TRUE)
Biomass(MSE, df = TRUE, byAge = TRUE, byArea = TRUE)

# Spawning biomass and production follow the same structure
SBiomass(MSE, df = TRUE, byAge = TRUE)
SProduction(MSE, df = TRUE, byArea = TRUE)

Bioeconomic

Description

Construct and manipulate a bioeconomic object storing revenue, cost, and investment dynamics for fleet-level or stock-level bioeconomic analyses.

Usage

Bioeconomic(
  Revenue = NULL,
  Cost = NULL,
  Investment = NULL,
  Disinvestment = NULL,
  Depreciation = NULL,
  Discount = NULL,
  Misc = list()
)

Bioeconomic(x) <- value

Revenue(x)

Revenue(x) <- value

Cost(x)

Cost(x) <- value

Investment(x)

Investment(x) <- value

Disinvestment(x)

Disinvestment(x) <- value

Depreciation(x)

Depreciation(x) <- value

Discount(x)

Discount(x) <- value

Arguments

Revenue

Numeric array or NULL. Revenue by simulation, fleet, and year. Default NULL.

Cost

Numeric or NULL. Operating cost per unit of effort. Default NULL.

Investment

Numeric or NULL. Cost of adding a unit of effort. Default NULL.

Disinvestment

Numeric or NULL. Cost of removing a unit of effort. Default NULL.

Depreciation

Numeric or NULL. Depreciation rate of effort units. Default NULL.

Discount

Numeric or NULL. Discount factor applied to future values. Default NULL.

Misc

List. Miscellaneous additional inputs. Default list().

x

A bioeconomic object, or a fleet object for ⁠Bioeconomic<-⁠.

value

For ⁠Bioeconomic<-⁠: a bioeconomic object. For slot replacement functions: the new value for the corresponding slot.

Details

Note: The bioeconomic is not currently used by the MSE framework. It is included for future development and is available for custom analyses outside the standard model loop.

A bioeconomic object stores parameters and outputs for fleet-level bioeconomic modelling, including revenue, effort costs, and discounting. All slots are optional and default to NULL.

This class is not currently used by the MSE framework. It is included for future development.

Attaching to a Fleet

A bioeconomic object can be attached to a Fleet() with Bioeconomic(Fleet) <- MyBioeconomic and retrieved with Bioeconomic(Fleet).

Individual slots may be accessed or modified using Revenue(), Cost(), Investment(), Disinvestment(), Depreciation(), and Discount().

Value

  • Bioeconomic() returns a bioeconomic object. If Revenue is a fleet object, the Bioeconomic slot of that fleet is returned.

  • ⁠Bioeconomic<-⁠ returns x with the Bioeconomic slot replaced by value.

  • Revenue(), Cost(), Investment(), Disinvestment(), Depreciation(), Discount() return the corresponding slot from x.

  • Their replacement forms return x with the corresponding slot updated.

See Also

  • bioeconomic for the class definition and slot-level documentation.

  • Fleet() for the enclosing fleet constructor.

Other fleet: Catchability(), DiscardMortality(), Effort(), Fleet(), Retention(), Selectivity(), bioeconomic-class, catchability-class, discardmortality-class, effort-class, fleet-class, retention-class, selectivity-class

Examples

b <- Bioeconomic(Cost = 100, Discount = 0.05)
Cost(b)
Cost(b) <- 200
Discount(b)

# Attach to a Fleet
f <- Fleet(Name = "Trawl")
Bioeconomic(f) <- Bioeconomic(Cost = 100, Investment = 500, Discount = 0.05)
Cost(Bioeconomic(f))
Discount(Bioeconomic(f))

The bioeconomic S4 Class

Description

Stores revenue, cost, and investment dynamics for fleet-level or stock-level bioeconomic analyses. Objects are typically created via the Bioeconomic() constructor, which documents all parameters in detail.

Details

Note: The bioeconomic is not currently used by the MSE framework. It is included for future development.

Slots

Revenue

numeric array or NULL. Revenue by simulation, fleet, and year. See Bioeconomic().

Cost

numeric or NULL. Operating cost per unit of effort. See Bioeconomic().

Investment

numeric or NULL. Cost of adding a unit of effort. See Bioeconomic().

Disinvestment

numeric or NULL. Cost of removing a unit of effort. See Bioeconomic().

Depreciation

numeric or NULL. Depreciation rate of effort units. See Bioeconomic().

Discount

numeric or NULL. Discount factor applied to future values. See Bioeconomic().

Misc

list. Miscellaneous additional inputs.

See Also

Bioeconomic() for the constructor and full parameter documentation. fleet for the enclosing fleet object.

Other fleet: Bioeconomic(), Catchability(), DiscardMortality(), Effort(), Fleet(), Retention(), Selectivity(), catchability-class, discardmortality-class, effort-class, fleet-class, retention-class, selectivity-class


Boxplot of TAC recommendations

Description

Boxplot of TAC recommendations

Usage

## S3 method for class 'Data'
boxplot(x, upq = 0.9, lwq = 0.1, ylim = NULL, outline = FALSE, col = NULL, ...)

Arguments

x

An object of class MSE

upq

Upper quantile of TACs for max ylim

lwq

Lower quantile of TACs for min ylim

ylim

Optional numeric vector of length 2 to specify limits of y-axis.

outline

Logical. Include outliers in plot?

col

Optional colours to pass to boxplot

...

Optional additional arguments passed to boxplot

Value

Returns a data frame containing the information shown in the plot

Author(s)

A. Hordyk


Butterfish Example Stock

Description

An example stock object representing a Butterfish (Peprilus triacanthus) stock. This is a short-lived, fast-growing forage species with high natural mortality and wide uncertainty on recruitment and maturity. See also AlbacoreExStock for a contrasting long-lived, slow-growing example.

Usage

ButterfishExStock

Format

A stock object with the following slots populated:

  • Name: "ButterfishExStock".

  • CommonName: "Butterfish".

  • Species: "Peprilus triacanthus".

  • Ages: An Ages() object with MaxAge = 8.

  • Length: A Length() object with von Bertalanffy parameters — Linf (38–42 cm), K (0.16–0.24 yr^-1^), t0 (-0.032 to -0.028 yr) — and CVatAge (0.1–0.15).

  • Weight: A Weight() object with allometric parameters alpha = 1.59e-05 and beta = 3.1.

  • NaturalMortality: A NaturalMortality() object with M = 0.7–0.9 yr^-1^.

  • Maturity: A Maturity() object with logistic maturity-at-length parameters L50 (4.5–10.2 cm) and L50_95 (1–8 cm). The wide ranges reflect substantial uncertainty in maturity schedule.

  • Fecundity: An empty Fecundity() object; fecundity-at-age is computed internally during population (see Details).

  • SRR: A SRR() object with Beverton-Holt steepness h (0.4–0.8), unfished recruitment R0 = 1000, recruitment variability SD (0.7–1.1), and autocorrelation AC (0.1–0.9). The high SD reflects the characteristically variable recruitment of forage species.

  • Spatial: A Spatial() object with UnfishedDist (0.095–0.105), ProbStaying (0.4–0.6), and RelativeSize (0.095–0.105).

  • Depletion: A Depletion() object with current biomass sampled from 5–60% of B0.

  • nYear, pYear, nSim, CurrentYear, Years, Seasons: Set by PopulateStock().

  • Misc: Empty list for user-defined information.

  • Log: Internal list for tracking object state.

Details

Two-element numeric vectors in the slot descriptions above are uniform bounds. PopulateStock() samples from these bounds across simulations and expands the results into ⁠[nSim x nAge x nYear]⁠ arrays. The sections below describe what each component-level ⁠Populate*()⁠ function produces.

Ages

CalcAgeClasses() generates the age vector Ages@Classes (0:8), which is used as the age dimension in all subsequent arrays.

Length

PopulateLength() samples Linf, K, and t0 independently for each simulation from uniform distributions defined by the bounds, then computes mean length-at-age using the von Bertalanffy growth equation. CVatAge is expanded across simulations and, when ALK = TRUE, an age–length key is constructed.

Weight

PopulateWeight() applies the allometric relationship W = alpha × L^beta^ to the mean length-at-age array to produce mean weight-at-age. An age–weight key is optionally constructed when AWK = TRUE.

Natural Mortality

PopulateNaturalMortality() samples M for each simulation from the uniform prior and expands the result into a natural mortality-at-age array. Stochastic annual deviates are added via PopulateRandom(). The high M range (0.7–0.9 yr^-1^) is consistent with the short lifespan of this species.

Maturity

PopulateMaturity() applies the logistic maturity-at-length curve, parameterised by L50 and L50_95, to the populated length-at-age array to produce a maturity-at-age array. The wide priors on both parameters result in high inter-simulation variability in the maturity schedule.

Fecundity

Because the Fecundity slot is empty, PopulateFecundity() computes fecundity-at-age as the element-wise product of weight-at-age and maturity-at-age, representing spawning output per individual.

Stock–Recruitment

PopulateSRR() samples h for each simulation from the uniform prior and generates a time series of log-normal recruitment deviates with standard deviation SD and autocorrelation AC. The high SD (0.7–1.1) produces strongly variable recruitment, typical of forage fish.

Spatial

PopulateSpatial() samples UnfishedDist, ProbStaying, and RelativeSize for each simulation and uses them to construct a full inter-area movement matrix, then expands all spatial arrays across simulations and years. The moderate ProbStaying (0.4–0.6) allows substantial mixing between the two areas.

Depletion

PopulateDepletion() samples current biomass depletion relative to B0 for each simulation from the uniform prior, setting the initial conditions of the operating model.

See Also

AlbacoreExStock, Stock(), PopulateStock(), Populate(), stock

Examples

ButterfishExStock

## Not run: 
PopulatedStock <- PopulateStock(
  ButterfishExStock,
  nYear = 50,
  pYear = 30,
  nSim = 48,
  seed = 42
)

## End(Not run)

Calculate Age Classes

Description

Computes the numeric vector of age classes (in years) from an Ages() object, respecting sub-annual time steps.

Usage

CalcAgeClasses(Ages)

Arguments

Ages

An Ages() object with slots MinAge, MaxAge, and Units set.

Details

Age classes are always expressed in years, regardless of the time unit used to define MinAge and MaxAge. Units controls the within-year resolution via CalcSeasons(), which maps unit strings to a seasons divisor:

Units Seasons Step size (yr)
"year" 1 1
"half-year" 2 0.5
"quarter" 4 0.25
"month" 12 0.0833
"week" 52 0.0192

The sequence runs from MinAge / Seasons to MaxAge / Seasons in steps of 1 / Seasons, rounded to three decimal places.

Returns NULL if Units, MinAge, or MaxAge are not set.

Value

A numeric vector of age classes in years, or NULL if any of Ages@Units, Ages@MinAge, or Ages@MaxAge are empty.

See Also

Ages(), ages, PopulateStock()

Examples

# Annual age classes 0–5
CalcAgeClasses(Ages(MinAge = 0, MaxAge = 5, Units = "year"))
#> [1] 0 1 2 3 4 5

# Quarterly age classes 0–1
CalcAgeClasses(Ages(MinAge = 0, MaxAge = 4, Units = "quarter"))
#> [1] 0.00 0.25 0.50 0.75 1.00

Calculate an Age-Size Key

Description

Generates an Age-Size key given mean and standard deviation of size-at-age. The size-at-age can be normally or log-normally distributed. By default the distribution is truncated at 2 standard deviations.

Usage

CalcAgeSizeKey(
  MeanAtAge,
  CVatAge,
  Classes,
  TruncSD = 2,
  Dist = c("normal", "lognormal"),
  silent = FALSE,
  type = "Length"
)

Arguments

MeanAtAge

Numeric vector, matrix, or 3D array of mean size-at-age, or a Length() object.

CVatAge

Numeric vector, matrix, or 3D array of coefficient of variation (CV) at age. Same structure as MeanAtAge.

Classes

Numeric vector of midpoints of size classes for the age-size key.

TruncSD

Numeric value for the number of standard deviations at which the distribution is truncated.

Dist

Character string, either "normal" or "lognormal" indicating the distribution of size-at-age.

silent

Logical; if TRUE, suppress progress bar.

type

Character; currently only "Length" is supported.

Value

A 4D array with dimensions Sim, Age, Class, and Year.

Examples

nSim <- 5
nAge <- 15
nYear <- 2
ages <- 0:(nAge-1)
years <- 2001:2002

TruncSD <- 2
Dist <- 'normal'

set.seed(123)
Linf <- runif(nSim, min = 150, max = 200)
K <- 0.3      
t0 <- 0   

MeanAtAge <- array(0, 
                   dim = c(nSim, nAge, nYear),
                   dimnames = list(Sim = 1:nSim, Age = ages, Year = years))

for (sim in 1:nSim) {
  for (yr in 1:nYear) {
    MeanAtAge[sim, , yr] <- Linf[sim] * (1 - exp(-K * (ages - t0)))
  }
}

# Coefficient of variation (CV)
CVatAge <- array(0.1, dim = dim(MeanAtAge), dimnames = dimnames(MeanAtAge))

# Define size classes
SDatAge <- MeanAtAge * CVatAge
class_min <- floor(min(MeanAtAge - TruncSD * SDatAge))
class_max <- ceiling(max(MeanAtAge + TruncSD * SDatAge))

Classes <- seq(class_min, class_max, by = 10)


# Calculate Age-Size Key
ASK <- CalcAgeSizeKey(
  MeanAtAge = MeanAtAge,
  CVatAge = CVatAge,
  Classes = Classes,
  TruncSD = TruncSD,
  Dist = Dist
)

dim(ASK)


# Inspect first simulation, first year
ASK[1,,,1]

Calculate the Asymptotic Spatial Distribution of a Movement Matrix

Description

Computes the stationary (asymptotic) distribution of a Markov chain movement matrix — the long-run proportion of the population expected to occupy each area. For a 2-area matrix a closed-form solution is used. For larger matrices, either a linear-algebra or iterative Markov chain approach is available.

Usage

CalcAsymDist(Movement, method = c("la", "mc"), tol = 1e-10, maxiter = 10000)

Arguments

Movement

A square row-stochastic matrix of dimensions ⁠nArea × nArea⁠, where Movement[i, j] is the probability of moving from area i to area j. All rows must sum to 1.

method

Character. Solution method for matrices larger than 2 × 2. One of "la" (linear algebra; default) or "mc" (Markov chain iteration). Partially matched.

tol

Numeric. Convergence tolerance. Used to check row sums, detect reducible 2-area chains, clamp near-zero negative probabilities, and assess convergence of the "mc" method. Default 1e-10.

maxiter

Integer. Maximum number of iterations for the "mc" method. A warning is emitted if convergence is not reached. Default 1e4.

Details

The movement matrix is treated as a row-stochastic transition matrix, where Movement[i, j] is the probability of moving from area i to area j. Diagonal entries represent the probability of remaining in an area. All rows must sum to 1.

Two solution methods are available for matrices larger than 2 × 2 via the method argument:

  • "la" (default): solves the system pi * P = pi subject to sum(pi) = 1 using least-squares linear algebra (solve(t(A) %*% A, t(A) %*% B)). Exact and fast for well-conditioned matrices.

  • "mc": iteratively multiplies the current distribution by Movement until convergence. More robust for nearly-reducible chains but slower.

For 2-area matrices the stationary distribution is computed analytically regardless of method:

pi[1] = P[2,1] / (P[1,2] + P[2,1])

pi[2] = P[1,2] / (P[1,2] + P[2,1])

Value

A numeric vector of length nArea giving the stationary probability of occupying each area. Values sum to 1.

See Also

Spatial(), CalcUnfishedDist()

Examples

# 2-area movement matrix
M <- matrix(c(0.8, 0.2,
              0.3, 0.7), nrow=2, byrow=TRUE)
CalcAsymDist(M)

# 3-area movement matrix using linear algebra (default)
M3 <- matrix(c(0.7, 0.2, 0.1,
               0.1, 0.8, 0.1,
               0.2, 0.2, 0.6), nrow=3, byrow=TRUE)
CalcAsymDist(M3)

# Using Markov chain iteration
CalcAsymDist(M3, method="mc")

Calculate Absolute Equilibrium Quantities

Description

For a given vector of apical fishing mortality values, computes absolute equilibrium abundance and yield by combining per-recruit calculations with stock-recruitment relationship scaling. Results span all complexes defined in the operating model.

Usage

CalcEquilibrium(OM, apicalF = NULL, Years = NULL, Complex = NULL)

Arguments

OM

An om or hist object. If a hist object is supplied, Hist@OM is used.

apicalF

Numeric vector of apical fishing mortality values at which equilibrium quantities are evaluated. If NULL (default), a log-spaced sequence of 30 values is generated automatically, spanning from ⁠0.001 × max(M)⁠ to ⁠2 × max(M)⁠ with zero prepended, where max(M) is the maximum natural mortality across all stocks and complexes in scope.

Years

Numeric years for which equilibrium quantities are evaluated. Biological and fishery parameters are subset to this year. Must match years in Years(OM). If NULL (default), the final historical year is used.

Complex

Character vector of complex names to evaluate. If NULL (default), all complexes are evaluated.

Details

Default apicalF grid

When apicalF = NULL, a log-spaced sequence of 30 values is generated automatically, spanning from ⁠0.01 × max(M)⁠ to ⁠2 × max(M)⁠ with zero prepended, where max(M) is the maximum natural mortality across all stocks.

Log-spacing is used because population dynamics are approximately linear in log(F): yield and biomass change rapidly at low F relative to M but become increasingly insensitive at high F, so equal spacing on the log scale concentrates resolution where the equilibrium curve is most informative.

Supply an explicit vector to override, for example apicalF = seq(0, 2, by = 0.01).

Complexes

Per-recruit and equilibrium quantities are calculated separately for each complex, with apicalF defined as the maximum fishing mortality across all stocks within the complex.

Single year

Unlike CalcPerRecruit(), this function accepts only a single Year value. For multi-year equilibrium curves, call the function separately for each year.

Value

An equilibrium object containing absolute equilibrium numbers, biomass, spawning biomass, spawning production, removals, and landings evaluated at each value of apicalF, with results reported per stock.

See Also

CalcPerRecruit(), CalcMSY(), equilibrium


Calculate Innovation Covariance Matrix for Multivariate AR(1)

Description

Computes the innovation covariance matrix (Σϵ\Sigma_\epsilon) for a multivariate AR(1) process given the stationary covariance matrix (ΣZ\Sigma_Z) and lag-1 autocorrelation coefficients (ϕ\phi).

Usage

CalcInnovationCov(Sigma_Z, phi)

Arguments

Sigma_Z

Numeric covariance matrix (nStock x nStock) representing the stationary covariance of the process.

phi

Numeric vector of length nStock containing lag-1 autocorrelation coefficients for each stock.

Details

The relationship used is:

Σϵ=ΣZΦΣZΦT\Sigma_\epsilon = \Sigma_Z - \Phi \Sigma_Z \Phi^T

where Φ\Phi is a diagonal matrix of autocorrelation coefficients.

Only stocks with positive stationary variance (active stocks) are included in the computation. The result is embedded back into a full zero matrix, so inactive stocks contribute no innovation variance.

The active submatrix is forced to be symmetric and positive semi-definite. If negative eigenvalues are detected, Matrix::nearPD() is used to find the nearest PSD matrix. After correction, the diagonal is capped at the theoretical upper bound σZ,i2(1ϕi2)\sigma^2_{Z,i}(1 - \phi_i^2) to prevent Matrix::nearPD() from inflating innovation variance beyond what is consistent with the stationary distribution.

Value

A numeric covariance matrix (nStock x nStock) representing the innovation covariance (Σϵ\Sigma_\epsilon). Rows and columns corresponding to inactive stocks (zero diagonal in Sigma_Z) are set to zero.

See Also

GenerateStockTargeting(), FitStockTargeting()

Examples

Sigma_Z <- matrix(c(1, 0.5, 0.5, 1), 2, 2)
phi <- c(0.7, 0.6)

CalcInnovationCov(Sigma_Z, phi)

Calculate MSY Reference Points

Description

Computes maximum sustainable yield (MSY) biological reference points for all complexes in a hist or om object by identifying the apical fishing mortality that maximises total yield, accounting for the stock-recruitment relationship. Results are stored in Hist@Reference@MSY and the updated hist object is returned.

Usage

CalcMSY(Hist, Years = NULL, type = c("Removals", "Landings"), silent = FALSE)

Arguments

Hist

A hist or om object. If an om is supplied it is first converted to a hist object.

Years

Integer vector of years for which reference points are evaluated. Biological and fishery parameters are subset to these years. If NULL (default), the final historical year is used.

type

Character. Whether MSY is defined in terms of total removals (landings plus dead discards) or landings only. One of 'Removals' (default) or 'Landings'.

silent

Logical. If TRUE, suppresses progress messages. Default FALSE.

Details

Complexes

Reference points are calculated separately for each complex defined in Hist@OM@Complexes. Within each complex:

  • FMSY is the single apical fishing mortality maximising total yield across all stocks in the complex.

  • Fleet-specific F is distributed according to effort-weighted catchability and selectivity.

  • Stock-level quantities (BMSY, SBMSY, etc.) are reported for each stock evaluated at the complex-level FMSY.

Value

An a refpointsMSY object.

See Also

CalcPerRecruit(), CalcSPR0(), refpointsMSY,


Calculate Per-Recruit Quantities

Description

Extracts biological and fishery parameters from a hist or om object and evaluates per-recruit quantities at a given apical fishing mortality.

Usage

CalcPerRecruit(OM, apicalF = 0.1, Years = NULL, Complex = NULL)

Arguments

OM

A om or hist object. If an om is supplied it is first converted to a hist object.

apicalF

Numeric vector of apical fishing mortality values at which per-recruit quantities are evaluated. Default 0.1.

Years

Integer vector of years for which per-recruit quantities are evaluated. Biological and fishery parameters are subset to these years If NULL (default), the final historical year is used.

Complex

Character vector of complex names to evaluate. If NULL (default), all complexes are evaluated.

Details

Complexes

Per-recruit quantities are calculated separately for each complex, with apicalF defined as the maximum fishing mortality across all ages and stocks within the complex. Results are reported per stock and reassembled into a single perrecruit object spanning all stocks. The Complex argument can be used to restrict calculations to a subset of complexes.

Fleet allocation

The relative contribution of each fleet to total fishing mortality is computed as the effort-weighted catchability (i.e. ⁠Effort × Efficiency⁠) normalised across fleets. These proportions are used to distribute apicalF across fleets before selectivity is applied.

Years

When Years contains multiple values, biological and fishery parameters are subset to those years and the per-recruit calculations are evaluated for each year independently. When Years = NULL, only the final historical year is used, giving a single set of per-recruit quantities representative of current conditions.

Value

A perrecruit object containing numbers-per-recruit, spawning-per-recruit, biomass-per-recruit, removals, and landings evaluated at each value of apicalF, with results reported per stock and apical F defined as the maximum F across all stocks within each complex.

See Also

CalcSPR0(), perrecruit


Calculate Reference Yield

Description

Calculate Reference Yield

Usage

calcRefYield(x, StockPars, FleetPars, pyears, Ncurr, nyears, proyears)

Arguments

x

Integer, the simulation number

StockPars

List of Stock Parameters

FleetPars

List of Fleet Parameters

pyears

The number of years to project forward. Equal to 'nyears' for optimizing for q.

Ncurr

Array with current numbers-at-age (dim=c(nsim, maxage+1, nareas))

nyears

Number of historical years

proyears

Number of projection years

Author(s)

A. Hordyk


Calculate residual statistics for log-space index residuals

Description

Computes standard deviation and lag-1 autocorrelation of log residuals for a simulated index (⁠sim x year⁠).

Usage

CalcResidualStats(LogResiduals, nSeasons = 1)

Arguments

LogResiduals

A numeric matrix or array with dimensions ⁠sim x year⁠.

nSeasons

Number of seasons in the array (default 1).

Details

Contiguous NA values are handled by splitting into separate groups for autocorrelation calculation within each simulation. Seasons with all NA values across all years are dropped.

Value

A data.frame with columns:

  • AC: weighted lag-1 autocorrelation of residuals

  • SD: standard deviation of residuals

  • NA_Season: a list length nSim with each element containing integer vector indicating which (if any) seasons have NA values for all years

See Also

ApplyAC(), GenResiduals()


Unfished Spawning Production Per Recruit

Description

Calculates the unfished spawning production per recruit (SPR0) — the denominator of the spawning potential ratio — under equilibrium conditions. SPR0 is computed as the element-wise ratio of unfished spawning production SP0() to unfished recruitment R0(), with array broadcasting handled by ArrayDivide().

Usage

CalcSPR0(OM, silent = FALSE)

Arguments

OM

Either a om or hist object. If an om object is provided, the historical dynamics are populated internally via Populate() and CalcUnfished_Equilibrium(), which may be computationally expensive. If a hist object is provided (the output of Simulate()), it is used directly.

silent

Logical. If TRUE, suppresses progress messages during population and simulation. Only used when object is an om. Default is FALSE.

Value

An array with dimensions ⁠[Sim, Stock, Year]⁠ containing the unfished spawning production per recruit. Dimensions where values are identical across simulations or years are collapsed by ReduceDims().

See Also

SP0(), R0(), ArrayDivide()


Calculate Cumulative Survival-at-Age

Description

Computes cumulative survival from recruitment to each age class, accounting for natural mortality, optional fishing mortality, spawn timing within a time step, and optional semelparous mortality. The calculation follows:

Usage

CalcSurvival(
  NaturalMortality,
  FishingMortality = NULL,
  PlusGroup = TRUE,
  SpawnTimeFrac = 0,
  Semelparous = FALSE
)

Arguments

NaturalMortality

Numeric array of natural mortality-at-age. Either a 2D array (⁠Age × Year⁠) or 3D array (⁠Sim × Age × Year⁠), with named dimensions.

FishingMortality

Optional numeric array of fishing mortality-at-age, matching the dimensions of NaturalMortality. If NULL (default), only natural mortality is used.

PlusGroup

Logical. If TRUE (default), the plus-group survival is adjusted for ongoing mortality beyond the maximum age class.

SpawnTimeFrac

Numeric. Fractional position of spawning within a time step, between 0 (start; default) and 1 (end). Either length 1 (applied to all simulations) or length nSim.

Semelparous

Either FALSE (default) to ignore semelparous mortality, or a numeric array of semelparous mortality-at-age matching the dimensions of NaturalMortality.

Details

  • Age 1: S[1] = exp(-Z[1] * SpawnTimeFrac)

  • Age a: S[a] = S[a-1] * exp(-(Z[a-1] * (1 - f) + Z[a] * f)) * (1 - Semelparous[a-1])

where Z = M + F and f = SpawnTimeFrac.

If PlusGroup = TRUE, the plus-group age class is adjusted to account for ongoing mortality: S[nAge] = S[nAge] / (1 - exp(-Z[nAge])).

Value

A numeric array of cumulative survival-at-age with the same dimensions and dimnames as NaturalMortality. Each value represents the probability of surviving from recruitment to that age class in that year.


Convert Between Season Count and Time Unit Labels

Description

Two complementary functions for converting between the integer number of seasons per year and the corresponding time unit label used throughout the package:

Usage

CalcTSUnits(Seasons)

CalcSeasons(Units)

Arguments

Seasons

Integer. Number of seasons per year. Must be one of 1, 2, 4, 12, 52, or 365. NULL is treated as 1 (annual). (CalcTSUnits() only.)

Units

Character. Time unit label. Case-insensitive. Must be one of "year", "half-year", "quarter", "month", or "week". (CalcSeasons() only.)

Details

  • CalcTSUnits(): converts a season count to a time unit label string.

  • CalcSeasons(): converts a time unit label string to a season count.

Supported conversions:

Seasons Units
1 "year"
2 "half-year"
4 "quarter"
12 "month"
52 "week"
365 "day"

Value

  • CalcTSUnits(): a character string time unit label.

  • CalcSeasons(): an integer season count.

See Also

CalcYears()

Examples

CalcTSUnits(1)    # "year"
CalcTSUnits(4)    # "quarter"
CalcTSUnits(NULL) # "year"

CalcSeasons("year")    # 1
CalcSeasons("Quarter") # 4

Calculate Dynamic Unfished Population Dynamics

Description

Calculate dynamic unfished population quantities for all Stock() objects in an operating model. Quantities include unfished number-at-age, total biomass, spawning biomass, and spawning production, evaluated dynamically over historical and projection years.

Usage

CalcUnfished_Dynamic(Hist, IdenticalHist = NULL, silent = FALSE)

Arguments

Hist

A Hist() object containing historical operating model data.

IdenticalHist

Logical; if TRUE, assumes all simulations are identical and calculates only a single simulation. If NULL (default), determined automatically via IdenticalSims().

silent

Logical; if TRUE, suppress messages during calculation.

Value

A popdynamics object containing dynamic unfished Number, Biomass, SBiomass, and SProduction arrays with dimensions ⁠Sim × Stock × Year⁠.

See Also

CalcUnfished_Equilibrium()


Calculate Equilibrium Unfished Population Dynamics

Description

Calculate equilibrium unfished population quantities for all Stock() objects in an operating model. Quantities include unfished number-at-age, total biomass, spawning biomass, and spawning production, evaluated under equilibrium unfished conditions.

Usage

CalcUnfished_Equilibrium(OM, silent = FALSE)

Arguments

OM

An OM() or Hist() object.

silent

Logical; if TRUE, suppress messages during calculation.

Details

If a Hist() object is supplied, its embedded operating model is used. The operating model is populated if required prior to calculation.

  • Biomass is calculated as the sum over ages of unfished number-at-age multiplied by mean weight-at-age.

  • Spawning biomass additionally applies maturity-at-age.

  • Spawning production is calculated using fecundity-at-age and may be reassigned across stocks using the SPFrom slot of the stocks SRR() objects.

Value

A popdynamics object containing equilibrium unfished Number, Biomass, SBiomass, and SProduction arrays with dimensions ⁠Sim × Stock × Year⁠.

See Also

CalcUnfished_Dynamic()


Calculate the Unfished Spatial Distribution

Description

Computes the asymptotic unfished spatial distribution for each simulation, age class, and year by applying CalcAsymDist() to each ⁠nArea × nArea⁠ slice of Spatial@Movement. The result is stored in Spatial@UnfishedDist.

Usage

CalcUnfishedDist(Spatial, Ages = NULL, Years = NULL)

Arguments

Spatial

A Spatial() object with a populated Movement slot. The Movement array must have dimensions ⁠Sim × FromArea × ToArea × Age × Year⁠.

Ages

An ages object supplying age class labels. If NULL (default), DefaultAges() is used.

Years

Numeric vector of year labels. If NULL (default), DefaultYears() is used.

Details

For a single-area model, all values are set to 1. For multi-area models, the stationary distribution of the movement matrix is computed for each ⁠Sim × Age × Year⁠ combination using CalcAsymDist().

Value

Spatial with Spatial@UnfishedDist populated as a named ⁠Sim × Area × Age × Year⁠ array, where each Area vector gives the stationary probability of occupying each area under unfished conditions.

See Also

CalcAsymDist(), Spatial()


Calculate Equilibrium Unfished Number-at-Age

Description

Calculates the equilibrium unfished number-at-age

Usage

CalcUnfishedNumber(OM, SP = FALSE)

Arguments

OM

An OM() object

SP

Logical. Account for SpawnTimeFrac? Accounts for spawning timing within a time step to calculate the number-at-age at the time of spawning

Details

Equilibrium N-at-Age is calculated from R0 (which may vary over time) but does NOT account for expected recruitment from the stock-recruit relationship.

Any changes in R0 due to time-varying biology (Fecundity-at-Age changes over time) should be accounted for in R0.

Value

A named list of length nStock() with each element an array with dimensions Sim, Age, and Year


Calculate Unfished Survival

Description

Calculate Unfished Survival

Usage

CalcUnfishedSurvival(
  OM,
  SP = FALSE,
  Years = NULL,
  silent = FALSE,
  Extend = TRUE
)

Arguments

OM

An OM() object, a Stock() object, or a list of Stock() objects.

SP

Logical. Account for SpawnTimeFrac? Accounts for spawning timing within a time step to calculate the number-at-age at the time of spawning

Years

Numeric vector of years to calculate

silent

Logical. Print messages?

Extend

Logical. Extend the array to include all Sims and Years?

Value

A list of length nStock() with an array with the unfished survival for each Stocks

Examples

## Not run: 
CalcUnfishedSurvival(OM)

## End(Not run)

Simplifies the CAL slot of data object

Description

A function that condenses the number of catch-at-length bins in a data object

Usage

CALsimp(Data, nbins = 10, simno = 1)

Arguments

Data

An object of class 'Data'.

nbins

Integer. The target number of catch at length bins

simno

Integer. An optional argument to specify the simulation number if writing simulated data

Author(s)

T. Carruthers


Identify management procedures (MPs) based on data availability

Description

Diagnostic tools that look up the slot requirements of each MP and compares to the data available in the Data object.

Usage

Can(Data, timelimit = 1, MPs = NA, dev = FALSE, silent = FALSE)

Cant(Data, timelimit = 1, silent = FALSE)

DLMdiag(
  Data,
  command = c("available", "not available", "needed"),
  reps = 5,
  timelimit = 1,
  funcs1 = NA,
  dev = FALSE,
  silent = FALSE
)

Needed(Data, timelimit = 1, silent = FALSE)

Arguments

Data

A data-limited methods data object (class Data)

timelimit

The maximum time (seconds) taken for an MP to undertake 5 reps (this filters out methods that are too slow)

MPs

Optional list of MP names

dev

Logical. Run in development mode?

silent

Logical Display messages?

command

What to calculate? Character. Options = c("available", "not available", "needed")

reps

The number of replicates for the MP

funcs1

A character vector of the MP names (optional)

Functions

  • Can(): Identifies MPs that have the correct data, do not produce errors, and run within the time limit.

  • Cant(): Identifies MPs that don't have sufficient data, lead to errors, or don't run in time along with a list of their data requirements.

  • DLMdiag(): Internal function called by Can and Cant

  • Needed(): Identifies what data are needed to run the MPs that are currently not able to run given a Data object

See Also

avail Data-legacy

Examples

CanMPs <- Can(MSEtool::Cobia)
CantMPs <- Cant(MSEtool::Cobia)
Needs <- Needed(MSEtool::Cobia)

Extract or Assign Catch Time Series

Description

Interactions(), Landings(), Discards(), and Removals() extract total interactions (encounters), retained landings, discards, and removals (landings + discards) respectively.

Usage

Interactions(
  object,
  df = TRUE,
  byAge = FALSE,
  byArea = FALSE,
  byFleet = FALSE,
  Reduce = TRUE,
  IncYear = FALSE
)

Landings(
  object,
  df = TRUE,
  byAge = FALSE,
  bySize = FALSE,
  byArea = FALSE,
  byFleet = TRUE,
  Reduce = TRUE,
  IncYear = FALSE
)

Landings(x) <- value

Discards(
  object,
  df = TRUE,
  byAge = FALSE,
  bySize = FALSE,
  byArea = FALSE,
  byFleet = TRUE,
  Reduce = TRUE,
  IncYear = FALSE
)

Discards(x) <- value

Removals(
  object,
  df = TRUE,
  byAge = FALSE,
  bySize = FALSE,
  byArea = FALSE,
  byFleet = TRUE,
  Reduce = TRUE,
  IncYear = FALSE
)

Arguments

object

A hist, mse, obs, or data object.

df

Logical. Applies to hist and mse objects only. If FALSE the raw array slot is returned. If TRUE (default) a tidy data.frame is returned. Ignored for obs and data objects.

byAge

Logical. If TRUE the data frame retains the Age dimension. Otherwise values are summed over ages. Mutually exclusive with bySize. Applies to hist and mse objects only.

byArea

Logical. If TRUE the data frame retains the Area dimension. Otherwise values are summed over areas. Applies to hist and mse objects only.

byFleet

Logical. If TRUE (default for Landings() and Discards()) the data frame retains the Fleet dimension. Otherwise values are summed over fleets. Applies to hist and mse objects only.

Reduce

Logical. If TRUE (default) simulation dimensions are reduced using ReduceDims() before conversion to a data frame. Applies to hist and mse objects only.

IncYear

Logical. Passed to ReduceDims(); controls whether the year dimension is retained during reduction. Default FALSE. Applies to hist and mse objects only.

bySize

Logical. If TRUE the data frame retains the Size (length-bin) dimension using the ⁠*AtSize⁠ slots. Otherwise values are summed over size classes. Mutually exclusive with byAge. Not available for Interactions(). Applies to hist and mse objects only.

x

An obs or data object.

value

A catchobs object (when x is obs) or a catchdata object (when x is data) to assign.

Details

When called on a hist or mse object, the functions return simulated catch arrays or tidy data frames as described below.

When called on an obs object, the functions return the corresponding catchobs slot directly (the observation error structure, not simulated values). When called on a data object, they return the corresponding catchdata slot directly (the observed or simulated values). In both cases no data frame conversion is performed, regardless of any df argument.

The assignment forms ⁠Landings<-⁠ and ⁠Discards<-⁠ replace the corresponding slot of an obs or data object.

When byAge = FALSE or bySize = FALSE for hist or mse objects, the catch data are in units of biomass (⁠N x Weight⁠), where Weight is the fleet-specific weight-at-age schedule from Fleet(). When byAge = TRUE or bySize = TRUE the values are in units of numbers. When byArea = TRUE the values are always in units of numbers.

When applied to an mse object the historical and projection periods are row-bound and labelled via the Period column; historical rows carry MP = "Historical".

Value

  • For obs: the catchobs object stored in the Landings or Discards slot.

  • For data: the catchdata object stored in the Landings or Discards slot.

  • For hist or mse with df = FALSE: the raw array slot (Interactions, Landings, or Discards).

  • For hist or mse with df = TRUE: a tidy data.frame with columns Sim, Stock, Year, Period, MP (MSE only), and optionally Age, Size, Area, and/or Fleet, plus Value and Variable.

  • Assignment forms return x with the named slot replaced by value.

Examples

Hist <- Simulate(SingleStockOM)
MSE <- Project(Hist, 'CurrentEffort')

# Raw arrays from Hist / MSE
Interactions(Hist, df = FALSE)
Landings(MSE, df = FALSE)

# Tidy data frames
Interactions(Hist)
Landings(MSE)
Discards(MSE)
Removals(MSE)

# Retain fleet, age, and area structure
Landings(MSE, byFleet = TRUE, byAge = TRUE, byArea = TRUE)
Discards(MSE, byFleet = TRUE, bySize = TRUE)

# Direct slot access for obs and data objects
obs <- Obs(Landings = CatchObs(CV = 0.2))
Landings(obs)
Landings(obs) <- CatchObs(CV = 0.3)

dat <- Data(Landings = CatchData(Value = matrix(100, 1, 1)))
Landings(dat)
Landings(dat) <- CatchData()

Catchability Constructor and Accessors

Description

Construct and manipulate a catchability object defining fishing gear or vessel efficiency for a Fleet() object.

Usage

Catchability(Efficiency = NULL, qCV = NULL, qInc = NULL, Misc = list())

Catchability(x) <- value

Efficiency(x)

Efficiency(x) <- value

qCV(x)

qCV(x) <- value

qInc(x)

qInc(x) <- value

Theta(x)

Theta(x) <- value

Arguments

Efficiency

Numeric, array, or NULL. Gear or vessel catchability coefficient (q) relating fishing effort to fishing mortality (encounters, see Interactions()). Accepted forms:

  • NULL (default): creates an empty catchability object. PopulateCatchability() initialises Efficiency to 1 across all simulations and years.

  • Scalar numeric (e.g. 0.01): constant efficiency applied across all simulations and years.

  • Numeric array with dimensions ⁠Sim x Year⁠ and named dimnames. The Sim dimension may be length 1 (replicated internally) or match nSim. The Year dimension may be length 1 or span a subset of years; PopulateCatchability() extends it to cover all historical and projected years.

If Efficiency is a fleet object, the Catchability slot of that fleet is returned (see Details).

qCV

Numeric or NULL. Coefficient of variation for lognormal stochastic variation in catchability. Applied to projected years only (see Details). Default NULL. Included primarily for backwards compatibility; users may find it simpler to supply a fully specified Efficiency array directly.

qInc

Numeric or NULL. Annual percentage increase in catchability (e.g. 2 = 2% per year; negative values indicate declining efficiency). Applied to projected years only (see Details). Default NULL. Included primarily for backwards compatibility; users may find it simpler to supply a fully specified Efficiency array directly.

Misc

List. Miscellaneous additional inputs. Default list().

x

A catchability object for accessor and replacement functions.

value

The replacement value for the corresponding slot.

Theta

Numeric, array, or NULL. Overdispersion parameter θ\theta of the negative binomial within-trip catch distribution. Accepted forms:

  • NULL (default): Theta is not populated; bag-limit management procedures will error if Theta is required and not supplied.

  • Scalar numeric (e.g. 1.2): constant overdispersion applied across all simulations.

  • Numeric vector length 2. Treated as lower and upper bounds of a uniform distribution.

  • Numeric vector length nSim.

Details

A catchability object defines the efficiency with which a fleet converts fishing effort into fishing mortality (encounters/interactions, see Interactions()).

A constant scalar is sufficient for most applications; time-varying or simulation-varying efficiency can be specified via a full ⁠Sim x Year⁠ array.

Efficiency Array Format

When supplied as a scalar, Efficiency is wrapped internally into a ⁠1 x 1⁠ array and replicated across all simulations and years during PopulateCatchability(), producing constant efficiency. When supplied as an array, the Sim dimension may be length 1 or match nSim, and the Year dimension is extended to cover all historical and projected years if it does not already do so.

When Efficiency is NULL, PopulateCatchability() initialises it to 1 across all simulations and years, equivalent to supplying Efficiency = 1.

Projected-Year Adjustments: qInc and qCV

qInc and qCV modify efficiency in projected years only and have no effect on historical years.

qInc specifies a percentage annual increase compounded over projection years: efficiency in projection year index t is scaled by (1 + qInc / 100)^t. Negative values model declining gear efficiency over the projection period.

qCV introduces lognormal inter-annual variation in efficiency during projection years. Each projected year's efficiency is multiplied by a mean-1 lognormal deviate with the specified coefficient of variation.

Both parameters are included primarily for backwards compatibility. For most applications, supplying a fully specified Efficiency array gives more direct control over time-varying catchability across both historical and projected periods.

Within-Trip Overdispersion: Theta

Theta (θ\theta) parameterises the negative binomial distribution used by bag-limit management procedures to model within-trip catch counts:

nf,s(t)NegBin(μf,s(t),  θf,s)n_{f,s}(t) \sim \text{NegBin}(\mu_{f,s}(t),\; \theta_{f,s})

where μf,s(t)\mu_{f,s}(t) is the mean catch per trip at time tt, computed internally by the OM from the unfished equilibrium catch and current depletion (assuming γ=1\gamma = 1; see Note). The variance of within-trip catch is:

Var(nf,s)=μf,s+μf,s2θf,s\text{Var}(n_{f,s}) = \mu_{f,s} + \frac{\mu_{f,s}^2}{\theta_{f,s}}

It determines the fraction of trips that catch at or above the bag limit at any given mean catch rate, and therefore how strongly the regulation constrains total retention as stock abundance changes. Theta is a fixed property of the fleet-stock pair and has no Year dimension.

Theta does not have a Year dimension. Overdispersion is treated as a fixed behavioural property of the fleet-stock pair that does not vary over time.

Smaller values (e.g. 0.5–2) produce high trip-to-trip variability with many zero-catch trips and occasional large catches, typical of recreational marine fisheries.

Larger values approach the Poisson distribution. Only required when a bag-limit management procedure isactive for this fleet-stock combination.

When trip-level creel data are available, Theta is estimated by maximum likelihood fitting of the negative binomial to observed per-trip counts. In the absence of creel data, Theta must be assumed.

Attaching to a Fleet

A catchability object can be attached to a Fleet() with Catchability(Fleet) <- MyCatchability and retrieved with Catchability(Fleet).

Value

  • Catchability() returns a catchability object. If Efficiency is a fleet object, the Catchability slot of that fleet is returned.

  • ⁠Catchability<-⁠ returns x with the Catchability slot replaced by value.

  • Efficiency(), qCV(), qInc() return the corresponding slot from the catchability object x.

  • Their replacement forms return x with the corresponding slot updated.

See Also

  • catchability for the class definition and slot-level documentation.

  • Fleet() for the enclosing fleet constructor.

  • Effort() for the effort object that is scaled by efficiency to produce fishing mortality.

  • PopulateCatchability() for how efficiency arrays are extended and stochastic adjustments are applied.

Other fleet: Bioeconomic(), DiscardMortality(), Effort(), Fleet(), Retention(), Selectivity(), bioeconomic-class, catchability-class, discardmortality-class, effort-class, fleet-class, retention-class, selectivity-class

Examples

# See man-examples/class-Catchability.R

The catchability S4 Class

Description

Defines gear or vessel efficiency for use in a fleet object. Objects are typically created via the Catchability() constructor, which documents all parameters in detail.

Slots

Efficiency

numeric, array, or NULL. Gear efficiency (q). See Catchability().

qCV

numeric or NULL. Coefficient of variation for stochastic variation in catchability during projected years. See Catchability().

qInc

numeric or NULL. Annual percentage increase in catchability during projected years. See Catchability().

Theta

numeric, array, or NULL. Overdispersion parameter θ\theta of the negative binomial within-trip catch distribution (Sim). Used by bag-limit management procedures to compute the probability that a single trip catches at or above the bag limit. See Catchability().

Misc

list. Miscellaneous additional inputs. Used internally.

See Also

  • Catchability() for the constructor and full parameter documentation.

  • fleet for the enclosing fleet object.

Other fleet: Bioeconomic(), Catchability(), DiscardMortality(), Effort(), Fleet(), Retention(), Selectivity(), bioeconomic-class, discardmortality-class, effort-class, fleet-class, retention-class, selectivity-class


Catch-and-Survey Observation Model

Description

An obs object representing a moderate data scenario combining reported landings with a fishery-independent survey index. No effort, CPUE, or composition data are simulated.

Usage

CatchAndSurveyObs

Format

An obs object. Populated slots:

  • Landings (catchobs): reported landings with CV in ⁠[0.10, 0.25]⁠ and multiplicative bias in ⁠[0.80, 1.00]⁠, capturing moderate reporting uncertainty with a tendency toward under-reporting.

  • Survey (indicesobs): fishery-independent index assuming biomass-proportional selectivity, with CV in ⁠[0.15, 0.30]⁠ and autocorrelation in ⁠[0.0, 0.2]⁠.

Empty slots (no data simulated): Effort, Discards, CPUE, LandingsAtAge, DiscardsAtAge, LandingsAtSize, DiscardsAtSize.

CatchAndSurveyObs represents a stock for which total catch is reported and a survey provides a relative abundance index, but finer-scale data (effort, CPUE, age or length compositions) are unavailable.

See Also

obs, Obs(), CatchObs(), IndicesObs(), CommercialFleetObs, AgeStructuredObs, LengthStructuredObs, DataRichObs

Other obs-examples: AgeStructuredObs, CommercialFleetObs, DataRichObs, LengthStructuredObs

Examples

CatchAndSurveyObs
Landings(CatchAndSurveyObs)
Survey(CatchAndSurveyObs)

CatchData Constructor

Description

Construct a catchdata object storing observed landed or discarded catch and associated uncertainty.

Usage

CatchData(
  Name = NULL,
  Value = NULL,
  CV = NULL,
  Units = NULL,
  Ref = NULL,
  RefCV = NULL
)

Arguments

Name

character or NULL. Fleet names, length nFleet. Default NULL.

Value

array or NULL. Observed catch values with dimensions ⁠[nYear x nFleet]⁠. Default NULL.

CV

array or NULL. Coefficients of variation for the catch observations, matching the dimensions of Value. Default NULL.

Units

character or NULL. Units of catch measurement, one element per fleet (e.g., "t" for tonnes, "numbers"). Default NULL.

Ref

array or NULL. Reference catch values (e.g., a historical baseline), matching the dimensions of Value. Default NULL.

RefCV

array or NULL. Coefficients of variation for the reference values, matching the dimensions of Ref. Default NULL.

Details

Usage

All arguments are optional; an empty object is valid and slots are populated later (e.g., by GenHistData_Catch()).

Attaching to a Data Object

Landings(data) <- CatchData(Value = myArray, CV = myCVArray)
Discards(data) <- CatchData(Value = myArray, CV = myCVArray)

Value

A catchdata object.

See Also

Other data: CompData(), EffortData(), catchdata-class, compdata-class, effortdata-class

Examples

# Empty object
cd <- CatchData()

# With values
yrs <- 2000:2020
fleets <- c("Trawl", "Longline")
val <- array(runif(length(yrs) * length(fleets)),
             dim = c(length(yrs), length(fleets)),
             dimnames = list(Year = yrs, Fleet = fleets))
cd <- CatchData(Name  = fleets,
                Value = val,
                CV    = array(0.1, dim = dim(val), dimnames = dimnames(val)),
                Units = c("t", "t"))

The catchdata S4 Class

Description

Stores time series observations of landed or discarded catch and associated uncertainty. Used in the Landings and Discards slots of a data object. Objects are typically created via CatchData(), which documents all parameters in detail.

Slots

Name

character or NULL. Fleet names, length nFleet.

Value

array or NULL. Observed catch values with dimensions ⁠[nYear x nFleet]⁠. See CatchData().

CV

array or NULL. Coefficients of variation matching the dimensions of Value. See CatchData().

Units

character or NULL. Units of catch measurement per fleet (e.g., "t" for tonnes, "numbers"). See CatchData().

Ref

array or NULL. Reference catch values (e.g., a historical baseline), matching the dimensions of Value. See CatchData().

RefCV

array or NULL. Coefficients of variation for the reference values, matching the dimensions of Ref. See CatchData().

See Also

CatchData() for the constructor and full parameter documentation. data for the enclosing data object.

Other data: CatchData(), CompData(), EffortData(), compdata-class, effortdata-class


CatchObs Constructor and Accessors

Description

Construct a catchobs object defining observation error for landed or discarded catch, or access and replace individual slots.

Usage

CatchObs(
  CV = NULL,
  Bias = NULL,
  Error = NULL,
  Years = NULL,
  Units = NULL,
  Ref = NULL,
  Misc = list()
)

Arguments

CV

numeric or NULL. Coefficient of variation of the lognormal catch observation error. Accepted forms:

  • NULL (default): no observation error is generated unless Error is supplied directly.

  • Length-1 scalar: a single CV applied uniformly across all simulations and years when generating the Error array internally.

  • Length-2 vector c(mean, sd): CV is itself drawn stochastically — a unique CV per simulation is generated via StructurePars() before being used to generate the Error array.

  • Length-nSim named array: used directly, one CV per simulation.

When conditioning on real data via ConditionObs(), CV is replaced by the simulation-specific standard deviation of historical log-residuals.

Bias

numeric or NULL. Multiplicative observation bias. Accepted forms:

  • NULL (default): bias defaults to 1 (unbiased) internally.

  • Positive scalar: interpreted as the CV of a lognormal distribution; a unique bias is drawn per simulation as rlnorm(nSim, mconv(1, Bias), sdconv(1, Bias)).

  • Length-nSim vector or named array: used directly, one bias per simulation.

When conditioning on real data via ConditionObs(), Bias is replaced by the mean ratio of simulated to observed catch across historical years, per simulation.

Error

numeric array or NULL. Pre-specified lognormal observation error multipliers with dimensions ⁠nSim x nYear⁠ and named dimnames (Sim, Year). When supplied, Error is used directly and CV is ignored for error generation. Values should be positive multipliers centred near 1. Default NULL, in which case Error is generated from CV internally. When conditioning on real data via ConditionObs(), any user-supplied Error is replaced.

Years

numeric vector or NULL. Calendar years over which to condition the observation error when real catch data are provided. When NULL (default), all historical years in the Data object are used. Has no effect when no real data are supplied.

Units

character(1) or NULL. Units of catch measurement. Must be "Biomass" or "Number". Determines how simulated catch is aggregated when generating pseudo-observed data. Default NULL (treated as "Biomass").

Ref

numeric or NULL. Reference catch value. Accepted forms:

  • NULL (default): no reference value.

  • Positive scalar: interpreted as the CV of a lognormal distribution; a unique reference value is drawn per simulation as rlnorm(nSim, mconv(1, Ref), sdconv(1, Ref)) internally.

  • Length-nSim vector or named array: used directly.

Misc

list. Miscellaneous additional objects. Default list().

Details

Observation Error Generation

The error applied to simulated catch is Bias[sim] * Error[sim, year]. The Error array (⁠nSim x nYear⁠) is obtained in one of three ways, in order of precedence:

  1. User-supplied Error: stored directly; CV is not used.

  2. Stochastic from CV: if Error is NULL and CV is specified, Internally the model generates a lognormal array where each cell is rlnorm(1, mconv(1, CV[sim]), sdconv(1, CV[sim])).

  3. Conditioned from real data: ConditionObs() estimates CV, Bias, and Error from historical residuals; any user-supplied values are replaced.

Bias is expanded internally: a scalar input is treated as the CV of a lognormal from which one bias per simulation is drawn; a length-nSim input is used directly.

Ref is expanded internally using the same convention as Bias.

Conditioning on Real Data

When real catch data are provided (via OM@Data) and ConditionObs() is run, CV and Bias are estimated from the historical residuals between simulated and observed catch, and Error is populated to cover both historical and projection years. Any user-supplied CV, Bias, and Error values are replaced.

Attaching to an Obs Object

Landings(obs) <- CatchObs(CV = 0.2)
Discards(obs) <- CatchObs(CV = 0.3, Bias = 1.1)

Value

  • CatchObs() returns a catchobs object.

  • Landings() and Discards(), when called on an obs or data object, return the corresponding catchobs or catchdata slot directly (no data frame conversion).

  • ⁠Landings<-⁠ and ⁠Discards<-⁠ return x with the slot replaced.

See Also

  • catchobs for the class definition.

  • Obs() for the enclosing observation model constructor.

  • ConditionObs() for how these slots are estimated from real data.

Other obs: CompObs(), EffortObs(), ExploitationObs(), IndicesObs(), LifeHistoryObs(), Obs(), catchobs-class, compobs-class, effortobs-class, exploitationobs-class, indicesobs-class, lifehistoryobs-class, obs-class

Examples

# Uniform 20% CV — same CV used for all simulations
co <- CatchObs(CV = 0.2)

# Stochastic CV — unique CV per simulation drawn from lognormal(mean=0.2, sd=0.05)
co <- CatchObs(CV = c(0.2, 0.05))

# Bias as a CV — unique bias per simulation drawn from lognormal(mean=1, sd=0.1)
co <- CatchObs(CV = 0.2, Bias = 0.1)

# Pre-specified error array — bypasses CV entirely
err <- array(rlnorm(48 * 20), dim = c(48, 20),
             dimnames = list(Sim = 1:48, Year = 2001:2020))
co <- CatchObs(Error = err)

# Attach to an obs object
obs <- Obs(Landings = CatchObs(CV = 0.2),
           Discards = CatchObs(CV = 0.3, Bias = 0.05))

# Access slots via the generic Landings() / Discards() functions
Landings(obs)
Discards(obs)

The catchobs S4 Class

Description

Defines the observation error structure for landed or discarded catch data. Used in the Landings and Discards slots of an obs object. Objects are typically created via CatchObs(), which documents all parameters in detail.

Slots

CV

numeric or NULL. Coefficient of variation of catch observation error. See CatchObs().

Error

numeric array or NULL. Realised lognormal observation error multipliers (⁠nSim x nYear⁠). Populated internally during conditioning or simulation; see CatchObs().

Bias

numeric or NULL. Multiplicative observation bias. See CatchObs().

Years

numeric or NULL. Calendar years over which the observation error is conditioned. See CatchObs().

Units

character or NULL. Units of catch ("Biomass" or "Number"). See CatchObs().

Ref

numeric array or NULL. Reference catch values, one per simulation. See CatchObs().

Misc

list. Miscellaneous additional objects.

See Also

  • CatchObs() for the constructor and full parameter documentation.

  • obs for the enclosing observation model object.

Other obs: CatchObs(), CompObs(), EffortObs(), ExploitationObs(), IndicesObs(), LifeHistoryObs(), Obs(), compobs-class, effortobs-class, exploitationobs-class, indicesobs-class, lifehistoryobs-class, obs-class


Check catch data availability and units

Description

Warns if a catch slot (Landings or Discards) contains no data, or if any catch values are not in units of biomass

Usage

CheckCatch(Data, incUnits = TRUE, slot_names = c("Landings", "Discards"))

Arguments

Data

A data object.

incUnits

Logical. If TRUE (default) an additional warning is issued when any values in slot_name are not in units of biomass.

slot_names

Slots to check. Defaults are Landings and Discards

Details

If no Landings or Discards data are available, and a finite TAC value cannot be produced, the MP will likely fall back to setting effort to last historical effort - ie same as CurrentEffort() (the default for empty Advice() objects).

If the Landings or Discards data are not in units of Biomass the subsequent TAC values may be incorrect because the TAC is always set in units of Biomass.

Future versions of MSEtool may allow an option to set TAC in units of Number.

Warnings are suppressed after the last historical year (i.e. once max(Data@Years) > Data@YearLH) so that they appear only on the first call within a projection, not on every subsequent timestep.

Value

NULL invisibly, called for its side-effect warnings.


Check for duplicated MPs names

Description

Custom MPs cannot have the same names of MPs in MSEtool and related packages

Usage

CheckDuplicate(MPs)

Arguments

MPs

Character vector of MP names

Value

An error if duplicated MP names, otherwise nothing


Check that specified MPs are valid and will run on MSEtool::SimulatedData

Description

Check that specified MPs are valid and will run on MSEtool::SimulatedData

Usage

CheckMPs(MPs = NA, silent = FALSE)

Arguments

MPs

Character vector of MP names

silent

Logical. Report messages?

Value

MP names


Utility functions for MSE objects

Description

Utility functions for MSE objects

Usage

checkMSE(MSEobj)

addMPs(MSEobjs)

joinMSE(MSEobjs = NULL)

joinHist(Hist_List)

updateMSE(MSEobj, save.name = NULL)

Arguments

MSEobj

A MSE object

MSEobjs

A list of MSE objects

Hist_List

A list of objects of class Hist

save.name

Character string. Optional file name to save the updated MSE object to disk.

Value

An object of class MSE

A new object of class Hist

Functions

  • checkMSE(): Check that an MSE object includes all slots in the latest version of DLMtool

  • addMPs(): Adds additional MPs to an MSE object by combining multiple MSE objects that have identical historical OM values but different MPs.

  • joinMSE(): Joins two or more MSE objects together across simulations. MSE objects must have identical number of historical years, and projection years.

  • joinHist(): Join objects of class Hist. Does not join slot OM

  • updateMSE(): Updates an existing MSE object (class MSE) from a previous version of the MSEtool to include slots new to the latest version. Also works with Stock, Fleet, Obs, Imp, and Data objects. The new slots will be empty, but avoids the 'slot doesn't exist' error that sometimes occurs. Returns an object of class matching class(MSEobj)

Author(s)

A. Hordyk

See Also

addMMPs()

joinData


Check OM object is complete

Description

Check OM object is complete

Usage

CheckOM(OM, msg = TRUE, stop_if_missing = TRUE)

Arguments

OM

An object of class OM

msg

Logical. Display messages?

stop_if_missing

Logical. Stop with error is values are missing and there is no default?

Value

The OM object with default values (if needed)

Examples

SingleStockOM <- CheckOM(SingleStockOM)

Check that a required package is installed

Description

Checks if a required package and (if applicable) package version are installed and if not, provides an error with installation instructions

Usage

CheckPackage(pkg, version = NULL, pkg.path = NULL)

Arguments

pkg

Character string with the name of the package

version

Optional. Character string specifying required version number

pkg.path

Optional. Character string specifying the install command. See Examples

Examples

# Not installed
## Not run: 
CheckPackage("MadeUp")

## End(Not run)

# Already installed
CheckPackage("MSEtool")

# Needs updating
## Not run: 
CheckPackage("MSEtool", "99")

## End(Not run)

# Update and specify installation path
## Not run: 
CheckPackage("MSEtool", "99", "pak::pgk_install('blue-matter/MSEtool')")

## End(Not run)

Manually map parameters for the historical period of operating model

Description

Interactive plots to specify trends and variability in fishing effort, fleet selectivity, and natural mortality for the operating model.

Usage

ChooseEffort(Fleet, Years = NULL)

ChooseM(OM, type = c("age", "length"), x = NULL, y = NULL)

ChooseSelect(Fleet, Stock, FstYr = NULL, SelYears = NULL)

Arguments

Fleet

A fleet object.

Years

An optional vector of years. Should be nyears long.

OM

An object of class 'OM'

type

A character string - is M to be mapped by 'age' or 'length'?

x

Optional vector for x-axis

y

Optional vector for y-axis

Stock

Optional Stock object. If provided, average length-at-maturity is included on plot for reference.

FstYr

Optional value for first historical year. If empty, user must specify the year in console.

SelYears

Optional vector of values for each year where selectivity pattern changed. If empty, user must specify the years in console (comma separated).

Details

ChooseEffort Interactive plot which allows users to specify the relative trajectory and variability in the historical fishing effort and populates Fleet object.
ChooseM Interactive plot which allows users to specify M by age or size class
ChooseSelect Input the first historical year, and all years where selectivity pattern changed (separated by comma). Interactive plot which allows users to specify a range for the length at 5\ selectivity at maximum length for each year. Produces a simple plot which shows the range in selectivity pattern for each break-point year. Selectivity-at-length is fixed in between break-point years. Note that this function replaces 'nyears' in the Fleet object with the value defined here (FstYr:current year).

Value

ChooseEffort and ChooseSelect return a Fleet object while ChooseM returns an OM object.

Author(s)

A. Hordyk


Combine Multiple Fleets into a Single Fleet

Description

Combines several fleets into a new aggregated fleet within an Operating Model, preserving the overall fishery dynamics that would result from the disaggregated fleets.

Usage

CombineFleets(OM, FleetList, silent = FALSE)

Arguments

OM

An OM() object.

FleetList

A named list of character vectors. Each element names the fleets to merge, and the element's name becomes the name of the new combined fleet. Multiple entries combine multiple sets of fleets simultaneously.

silent

logical(1). If TRUE, suppresses informational console messages. Defaults to FALSE.

Value

An updated OM() object in which each set of fleets named in FleetList has been replaced by a single aggregated fleet across all stocks.

For each entry in FleetList, the first named fleet is replaced in-place by the combined fleet and the remaining fleets are dropped. Combination preserves aggregate fishing mortality, selectivity, retention, discard mortality, and weight-at-age. S

Combination equations

Let FfapicalF^{apical}_f be the apical fishing mortality for fleet ff, and sf(a)s_f(a), rf(a)r_f(a), df(a)d_f(a) be selectivity, retention, and discard mortality at age aa.

Apical F and effort

Fcombinedapical=fFfapicalF^{apical}_{combined} = \sum_f F^{apical}_f

Effort is recovered as Fcombinedapical/qF^{apical}_{combined} / q, where qq is taken from the first fleet.

F-at-age (interaction)

Fcombined(a)=fFfapicalsf(a)F_{combined}(a) = \sum_f F^{apical}_f \cdot s_f(a)

Selectivity

scombined(a)=Fcombined(a)/maxaFcombined(a)s_{combined}(a) = F_{combined}(a) \,/\, \max_a F_{combined}(a)

Retention

rcombined(a)=fFfapicalsf(a)rf(a)Fcombined(a)r_{combined}(a) = \frac{\sum_f F^{apical}_f \cdot s_f(a) \cdot r_f(a)}{F_{combined}(a)}

Discard mortality (age-specific F-weighted average on the instantaneous-rate scale)

mcombined(a)=1exp ⁣(fFcombined,f(a)(log(1df(a)))Fcombined(a))m_{combined}(a) = 1 - \exp\!\left( -\frac{\sum_f F_{combined,f}(a)\cdot(-\log(1-d_f(a)))}{F_{combined}(a)} \right)

WeightFleet (age-specific F-weighted average)

Wcombined(a)=fFcombined,f(a)Wf(a)Fcombined(a)W_{combined}(a) = \frac{\sum_f F_{combined,f}(a)\cdot W_f(a)}{F_{combined}(a)}


Create a blank MP recommendations object (class Rec) of the right dimensions

Description

Create a blank MP recommendations object (class Rec) of the right dimensions

Usage

CombineMMP(temp, nareas)

Arguments

temp

A list of nsim simulations.

nareas

The number of areas.

Author(s)

T. Carruthers


Combine Multiple Operating Models into One

Description

Combine multiple om objects into a single unified operating model. Each element of OM_List represents a distinct stock or stock complex (e.g., sex-structured populations). The resulting object spans the full union of historical and projection years across all inputs.

Usage

CombineOMs(
  OM_List,
  Name = "Combined OM",
  FillEffort = list(nYears = 3, SD = 0.1, Mean = NULL, Values = NULL),
  FillEfficiency = list(nYears = 3, SD = 0.1, Mean = NULL, Values = NULL),
  StandardizeEffort = TRUE,
  silent = FALSE
)

Arguments

OM_List

Named list of om objects. All elements must share the same nSim, Seasons, and fleet names in identical order. See FleetNames().

Name

character(1). Name assigned to the combined OM. Default "Combined OM"

FillEffort

List controlling effort forward-filling. See Details.

FillEfficiency

List controlling efficiency forward-filling. See Details.

StandardizeEffort

logical(1). If TRUE (default), calls StandardizeEffort() after combining, which equalises effort across stocks for each fleet and back-calculates stock targeting weights.

silent

logical(1). If TRUE, suppresses informational messages. Default FALSE.

Details

Processing steps

  1. Validate that all OMs share nSim, Seasons, and fleet names.

  2. Standardize each OM via PopulateOM().

  3. Construct unified historical and projection year ranges: historical years are the union across all OMs; projection years are those strictly greater than the maximum historical year.

  4. Extend every stock and fleet object to the unified year range. Missing early years are back-filled; missing later historical years are forward-filled using FillEffort and FillEfficiency.

  5. Concatenate stocks and fleets.

  6. Generate correlated recruitment deviations for the projection period via GenMultiStockRecDevs().

  7. Optionally standardize effort across stocks via StandardizeEffort(), which populates ⁠@StockTargeting⁠

Fill Controls

Both FillEffort and FillEfficiency accept:

  • nYears (integer): Number of trailing historical years used to compute a reference mean

  • SD (numeric): Lognormal standard deviation applied during stochastic filling

  • Mean (numeric): Optional override (length 1 or nSim)

  • Values (array): Optional ⁠nSim x n_fill_years⁠ matrix used directly

If Values is supplied, all other parameters are ignored.

Metadata

The following slots are copied verbatim from OM_List[[1]]: Agency, Author, Email, Region, Latitude, Longitude, Sponsor, nSim, Seasons, DataLag, Interval, nReps, pStar, maxF, Seed, Control. Ensure the first OM contains the desired global configuration.

Value

An om object with:

  • ⁠@Stock⁠: concatenation of all stocks across input OMs, in list order.

  • ⁠@Fleet⁠: concatenation of all fleet lists across input OMs.

  • ⁠@nYear⁠: length of the unified historical year range.

  • ⁠@pYear⁠: number of projection years strictly after the latest historical year.

  • ⁠@CurrentYear⁠: the latest historical year across all input OMs.

  • Administrative metadata (Agency, Author, nSim, Seed, etc.) copied from OM_List[[1]].

See Also

GenMultiStockRecDevs(), StandardizeEffort()

Examples

## Not run: 
combined <- CombineOMs(
  OM_List = list(StockA = om_a, StockB = om_b),
  Name = "Combined OM",
  FillEffort = list(nYears = 5, SD = 0.05),
  FillEfficiency = list(nYears = 5, SD = 0.05)
)

## End(Not run)

Commercial-Fleet Observation Model

Description

An obs object representing a fleet-monitored data scenario in which landings, discards, effort, and a commercial CPUE index are all observed, but no fishery-independent survey or composition data are available.

Usage

CommercialFleetObs

Format

An obs object. Populated slots:

  • Landings (catchobs): reported landings with CV in ⁠[0.05, 0.15]⁠ and a positive bias in ⁠[1.00, 1.15]⁠, reflecting some misreporting.

  • Discards (catchobs): estimated discards with CV in ⁠[0.20, 0.40]⁠ and bias in ⁠[0.80, 1.20]⁠, capturing the greater uncertainty in at-sea discard estimation.

  • Effort (effortobs): vessel-days from logbooks with CV in ⁠[0.02, 0.08]⁠ and near-unbiased reporting ⁠[0.95, 1.05]⁠.

  • CPUE (indicesobs): standardised commercial CPUE with CV in ⁠[0.15, 0.25]⁠ and autocorrelation in ⁠[0.0, 0.3]⁠.

Empty slots (no data simulated): Survey, LandingsAtAge, DiscardsAtAge, LandingsAtSize, DiscardsAtSize.

See Also

obs, Obs(), CatchObs(), EffortObs(), IndicesObs(), CatchAndSurveyObs, AgeStructuredObs, LengthStructuredObs, DataRichObs

Other obs-examples: AgeStructuredObs, CatchAndSurveyObs, DataRichObs, LengthStructuredObs

Examples

CommercialFleetObs
Effort(CommercialFleetObs)
CPUE(CommercialFleetObs)

Compare BAM and OM Output

Description

Compares key population time series between BAM output and a simulated operating model (OM), reporting the mean absolute relative error (MARE) for recruits, total numbers, total biomass, and landings and discards by fleet.

Usage

CompareBAM(Stock, OM = NULL, plot = FALSE, thresh = 1)

Arguments

Stock

Character string matching a stock in bamExtras, a list of BAM output objects containing elements rdat and dat, or an object of class BAMdata as returned by GetBAMOutput().

OM

Optional OM or hist object. If NULL (default), one is constructed internally via ImportBAM().

plot

Logical. Plot the timeseries for the OM and BAM output? If plot=FALSE (default) the plots will only be printed if MARE>thresh in some years.

thresh

Numeric. MARE threshold (as a percentage) above which a comparison is flagged, printed, and plotted. Default ⁠1%⁠.

Details

Series with MARE exceeding thresh are plotted automatically.

Value

Invisibly returns a named list with elements Stock, Recruits, Number, and Biomass. Each of Recruits, Number, and Biomass is a list with elements df (long-format data.frame of OM and BAM values by year) and MARE (absolute relative error by year).

See Also

ImportBAM(), GetBAMOutput()


Compare SS3 and OM fishery dynamics

Description

Generates plots of timeseries of total Number and total Biomass for each stock for users to visually compare the fishery dynamics from the two models.

Usage

CompareSS(SSDir, Hist, sim = 1, silent = FALSE, ...)

CompareSS_Number(SSDir, Hist, sim = 1, silent = FALSE, ...)

CompareSS_Biomass(SSDir, Hist, sim = 1, silent = FALSE, ...)

Arguments

SSDir

Character string giving the path to a directory containing SS3 output files, or a list returned by ImportSSReport().

Hist

A hist-class or om-class object. If an om-class object is supplied to CompareSS(), Simulate() is called automatically before comparison.

sim

Integer. Simulation index used to select both the SS3 report element and the OM simulation row. Default 1. Only used where ImportSSReport() is applied to multiple SS3 output directories.

silent

Logical. Passed to ImportSSReport() and Simulate() to suppress console output. Default FALSE.

...

Additional arguments forwarded to ImportSSReport().

Details

The fishery dynamics generated by Simulate() should match those from the SS3 output. If there are significant differences, this indicates either a problem with the OM import process or a mismatch in the population dynamics models.

Value

  • CompareSS() returns NULL invisibly (called for its side-effects).

  • CompareSS_Number() and CompareSS_Biomass() each print a ggplot2::ggplot() object and return the combined data.frame of OM and SS3 values invisibly, with columns Year, Value, Stock, and Model.

See Also

ImportSSReport(), Simulate(), Number(), Biomass()


CompData Constructor

Description

Construct a compdata object storing age or size composition observations of catch samples.

Usage

CompData(
  Name = NULL,
  Value = NULL,
  Classes = NULL,
  Units = NULL,
  Log = list(),
  Misc = list()
)

Arguments

Name

character or NULL. Fleet names, length nFleet. Default NULL.

Value

array or NULL. Composition counts with dimensions ⁠[nYear x nFleet x nClass]⁠. Values represent counts scaled to sum to SampleSize within each year and fleet — see CompObs() for the simulation model. Default NULL.

Classes

numeric or NULL. Class midpoints — ages in years for age compositions, or bin midpoints in the appropriate length unit for size compositions. Length nClass. Default NULL.

Units

character or NULL. Units of the class variable (e.g., "years", "cm", "mm"). Default NULL.

Log

list. Named list for diagnostic and audit logging. Default list().

Misc

list. Named list for additional metadata. Default list().

Details

Usage

All arguments are optional; an empty object is valid and slots are populated later (e.g., by GenHistData_AgeComp() or GenHistData_SizeComp().

Value Dimensions and Units

Value stores counts, compositions are normalised to sum to SampleSize within each year-fleet combination. The simulation model that generates Value is defined in CompObs().

Attaching to a Data Object

LandingsAtAge(data)  <- CompData(Value = myArray, Classes = ages)
DiscardsAtAge(data)  <- CompData(Value = myArray, Classes = ages)
LandingsAtSize(data) <- CompData(Value = myArray, Classes = bins)
DiscardsAtSize(data) <- CompData(Value = myArray, Classes = bins)

Value

A compdata object.

See Also

  • compdata for the class definition.

  • data and Data() for the enclosing data object.

  • CompObs() for the observation error structure that generates compdata objects during simulation.

Other data: CatchData(), EffortData(), catchdata-class, compdata-class, effortdata-class

Examples

# Empty object
cd <- CompData()

# With values
yrs    <- 2000:2020
ages   <- 1:10
fleets <- c("Trawl", "Longline")
val <- array(0L,
             dim = c(length(yrs), length(fleets), length(ages)),
             dimnames = list(Year = yrs, Fleet = fleets, Age = ages))
cd <- CompData(Name    = fleets,
               Value   = val,
               Classes = ages,
               Units   = "years")

The compdata S4 Class

Description

Stores age or size composition observations of catch samples. Used in the LandingsAtAge, DiscardsAtAge, LandingsAtSize, and DiscardsAtSize slots of a data object. Objects are typically created via CompData(), which documents all parameters in detail.

Slots

Name

character or NULL. Fleet names, length nFleet.

Value

array or NULL. Composition counts with dimensions ⁠[nYear x nFleet x nClass]⁠. See CompData().

Classes

numeric or NULL. Class midpoints — ages in years for age compositions, or bin midpoints in the appropriate length unit for size compositions. See CompData().

Units

character or NULL. Units of the class variable (e.g., "years", "cm", "mm"). See CompData().

Log

list. Named list used for diagnostic and audit logging.

Misc

list. Named list for additional composition-level metadata.

See Also

  • CompData() for the constructor and full parameter documentation.

  • data for the enclosing data object.

Other data: CatchData(), CompData(), EffortData(), catchdata-class, effortdata-class


Stock Complex Example Operating Model

Description

An example om object representing two stocks managed jointly as a single complex, each exploited by one fleet. The Complexes slot groups both stocks so that data and management advice are aggregated across the complex. Intended to illustrate stock complex construction. Pairings of stocks, fleets, and observation models are for illustration only and should not be taken as ecologically meaningful. See also SingleStockOM, TwoFleetOM, and MultiStockOM for structural variants.

Usage

ComplexOM

Format

An om object with the following slots populated:

  • Name: "Stock Complex - Single Fleet".

  • nSim: 8. Number of stochastic simulations.

  • nYear: 20. Number of historical years.

  • pYear: 30. Number of projection years.

  • Stock: a length-2 list of ⁠[[AlbacoreExStock, ButterfishExStock]]⁠.

  • Fleet: a length-2 list, each containing a length-1 list of AsympExFleet. Structure is ⁠[[stock]][[fleet]]⁠. Both stocks are fished by the same fleet type.

  • Obs: a length-1 list containing a length-1 list of AgeStructuredObs. Structure is ⁠[[complex]][[fleet]]⁠. A single observation model applies to the whole complex, since data are aggregated across both stocks before being observed.

  • Complexes: list(Stock_Complex = 1:2). Both stocks are assigned to a single complex named "Stock_Complex", so data and management advice are aggregated across stocks 1 and 2.

  • Imp: NULL. Implementation error is not specified; the Imp slot retains its class default. See Imp() for details.

Details

Stocks

Two biologically contrasting stocks are included:

See AlbacoreExStock and ButterfishExStock for full parameter details.

Stock Complex

Setting Complexes = list(Stock_Complex = 1:2) instructs the operating model to treat both stocks as a single management unit. Catch and index data are aggregated across the complex when generating management advice, while population dynamics are simulated independently for each stock.

Fleet

AsympExFleet is applied to both stocks, representing a single fleet type with asymptotic length-based selectivity. See AsympExFleet for full parameter details.

Observation Model

Because both stocks are aggregated into a single complex, the Obs slot is indexed by complex and fleet rather than by individual stock. A single AgeStructuredObs object applies to the complex as a whole: landings, a spawning-biomass survey, and annual age-composition samples from landed and discarded fish. See AgeStructuredObs for full parameter details.

Implementation Error

The Imp slot is NULL. The imp is currently a placeholder and implementation error is not applied during simulation. See Imp() for details.

See Also

SingleStockOM, TwoFleetOM, MultiStockOM for structural variants. AlbacoreExStock, ButterfishExStock, AsympExFleet, AgeStructuredObs for the component objects. OM(), om, runMSE(), PopulateOM(), ExampleMPs()

Other om: MultiStockOM, OM(), OM-accessors, SingleStockOM, TwoFleetOM, om-class

Examples

ComplexOM
ComplexOM@Complexes
nStock(ComplexOM)

## Not run: 
Hist <- runMSE(ComplexOM, MPs = ExampleMPs())

## End(Not run)

CompObs Constructor and Accessors

Description

Construct a compobs object defining the observation error structure for age or length composition data, or access and replace composition observation slots of an obs object.

Usage

CompObs(
  SampleSize = NULL,
  ESS = NULL,
  Theta = NULL,
  Years = NULL,
  Shift = NULL,
  Misc = list()
)

Arguments

SampleSize

numeric or NULL. Nominal sample size (number of fish aged or measured per year), used as the count argument of the final multinomial draw. NULL (default) suppresses composition data generation for this data type entirely. Accepted input forms:

  • Scalar: constant across all simulations and years.

  • Length-2 vector c(lower, upper): bounds of a Uniform distribution from which one value per simulation is drawn, constant across years.

  • Named matrix with dimensions Sim and/or Year: specifying values at change-point years, expanded to ⁠[nSim x nYear]⁠ by PopulateCompObs(). See Specifying Biological and Fleet Schedules for the full matrix input convention.

ESS

numeric or NULL. Effective sample size, which scales the Dirichlet-Multinomial concentration vector (see Details). Controls stochastic variability in the composition draw independently of SampleSize. Accepted input forms are identical to those for SampleSize above. NULL (default) uses SampleSize as the effective sample size. Typically ESS <= SampleSize; values of ESS < SampleSize produce overdispersion relative to a pure multinomial with SampleSize draws.

Theta

numeric or NULL. Dirichlet-Multinomial dispersion parameter in ⁠(0, 1]⁠. Theta = 1 (default) recovers the standard multinomial. Values less than 1 produce overdispersed compositions, with Theta -> 0 giving maximum overdispersion. Accepted input forms are identical to those for SampleSize above.

Years

numeric vector or NULL. Calendar years of observed composition data to use during conditioning via ConditionObs_Comp(). Only relevant when real composition data are supplied in OM@Data; has no effect during simulation-only runs. NULL (default) uses all available historical years during conditioning.

Shift

numeric or NULL. Systematic per-bin offset on the log-concentration scale applied to the Dirichlet concentration vector before drawing, capturing directional bias between observed and OM-predicted compositions. The concentration for bin bb is scaled as αb=ESS×qb×exp(Shiftb)\alpha_b' = \mathrm{ESS} \times q_b \times \exp(\mathrm{Shift}_b), so Shift = 0 leaves a bin unchanged, positive values inflate its concentration, and negative values deflate it. Because the transformation is log-multiplicative, Shift cannot produce invalid (negative) concentrations regardless of magnitude. NULL (default) applies no shift. Accepted input forms:

  • Scalar: constant offset across all simulations, years, and bins.

  • Vector of length nBin: bin-specific offset, constant across simulations and years.

  • Named matrix with any subset of Sim, Year, and Bin dimensions, with change-point years: expanded to ⁠[nSim x nYear x nBin]⁠ by PopulateCompObs().

  • Full ⁠[nSim x nYear x nBin]⁠ array. In conditioning mode, Shift is populated internally by ConditionObs_Comp() from the mean per-bin log-concentration residual across historical years and should not be set by the user.

Misc

list. Reserved for internal use. Default list().

Details

Composition generation model

Let q be the OM-predicted composition vector (length nBin, sums to 1) for a given simulation, year, and fleet. The observation error model proceeds as follows:

Step 1 — Base concentration vector

α=ESS×q\alpha = \mathrm{ESS} \times \mathbf{q}

Step 2 — Apply log-concentration offset (if Shift non-NULL)

αb=αb×exp(Shift[sim,year,b])\alpha_b' = \alpha_b \times \exp(\mathrm{Shift}[\mathrm{sim}, \mathrm{year}, b])

When Shift is NULL, α=α\alpha' = \alpha.

Step 3 — Dirichlet draw

pDirichlet(α/Theta)\mathbf{p}^* \sim \mathrm{Dirichlet}(\alpha' / \mathrm{Theta})

where Theta (0,1]\in (0, 1] controls overdispersion. Theta = 1 recovers the standard Dirichlet with concentration α\alpha'. Smaller values of Theta shrink the total concentration and increase variance.

Step 4 — Multinomial draw

obsMultinomial(SampleSize,p)\mathrm{obs} \sim \mathrm{Multinomial}(\mathrm{SampleSize},\, \mathbf{p}^*)

Conditioning mode

When real composition data are supplied via OM@Data, ConditionObs_Comp() compares observed compositions with OM-predicted compositions across the historical years specified in Years, and populates Shift (mean per-bin log-concentration residual) as well as estimating an appropriate ESS and Theta. Users should not set these slots manually when conditioning on real data.

Note: when observed compositions differ substantially from OM-predicted compositions (e.g. a length distribution shifted far left or right, or with markedly different spread), the resulting Shift values will be large. This is treated as observation error rather than model mis-specification — an assumption that should be evaluated carefully. See the technical manual for a full discussion.

Attaching to an Obs object

obs <- Obs()
LandingsAtAge(obs)  <- CompObs(SampleSize = 200, ESS = 50)
LandingsAtSize(obs) <- CompObs(SampleSize = 150, ESS = 40, Theta = 0.5)

Value

  • CompObs() returns a compobs object.

  • LandingsAtAge(), DiscardsAtAge(), LandingsAtSize(), DiscardsAtSize() return the corresponding compobs slot from an obs object x.

  • Their replacement forms return x with the corresponding slot updated and the object revalidated.

See Also

Other obs: CatchObs(), EffortObs(), ExploitationObs(), IndicesObs(), LifeHistoryObs(), Obs(), catchobs-class, compobs-class, effortobs-class, exploitationobs-class, indicesobs-class, lifehistoryobs-class, obs-class

Examples

# Default multinomial draw: 200 fish sampled, ESS = 50
co <- CompObs(SampleSize = 200, ESS = 50)

# With Dirichlet-Multinomial overdispersion (Theta = 0.5)
co_dm <- CompObs(SampleSize = 200, ESS = 50, Theta = 0.5)

# Stochastic sample size drawn from Uniform(150, 250) across simulations
co_stoch <- CompObs(SampleSize = c(150, 250), ESS = 50)

# Bin-specific shift (e.g. 7 age classes): inflate older ages
co_shift <- CompObs(
  SampleSize = 200,
  ESS        = 50,
  Shift      = c(-2, -1, 0, 0, 1, 2, 3)
)

# Attach to an obs object
obs <- Obs(
  LandingsAtAge  = CompObs(SampleSize = 200, ESS = 50),
  LandingsAtSize = CompObs(SampleSize = 150, ESS = 40, Theta = 0.5)
)

The compobs S4 Class

Description

Defines the observation error structure for age or length composition data (catch-at-age, catch-at-length). Used in the LandingsAtAge, DiscardsAtAge, LandingsAtSize, and DiscardsAtSize slots of an obs object. Objects are typically created via CompObs(), which documents all parameters and accepted input forms in detail.

Details

Composition generation model

During simulation, PopulateCompObs() applies the following steps:

  1. Shift non-NULL: user-specified (or conditioned) per-bin log-concentration offsets are exponentiated and applied to the OM-predicted concentration vector:

    αb=ESS×qb×exp(Shiftb)\alpha_b' = \mathrm{ESS} \times q_b \times \exp(\mathrm{Shift}_b)

  2. Shift NULL (default): pure Dirichlet-Multinomial draw from the OM-predicted composition with concentration scaled by ESS and dispersion Theta:

    α=ESS×q\alpha' = \mathrm{ESS} \times \mathbf{q}

Note on large compositional shifts

When observed compositions differ substantially from OM-predicted compositions (e.g. a length distribution shifted far left or right, or with markedly different spread), ConditionObs_Comp() will produce large values in Shift. These are treated as observation error rather than model mis-specification — an assumption that should be evaluated carefully. See the technical manual for a full discussion of this assumption and its implications for simulation performance.

Slots

SampleSize

numeric or NULL. Nominal sample size (number of fish aged or measured) applied when drawing the final multinomial sample. Accepted input forms are documented in CompObs(). After population by PopulateCompObs(), stored as a named ⁠[nSim x nYear]⁠ array. NULL (default) suppresses composition data generation for this data type; EmptyObject() returns TRUE when SampleSize is NULL.

ESS

numeric or NULL. Effective sample size, which scales the Dirichlet-Multinomial concentration vector and therefore controls stochastic variability in the composition draw independently of SampleSize. Accepted input forms are the same as for SampleSize; see CompObs(). After population, stored as a named ⁠[nSim x nYear]⁠ array. NULL (default) uses SampleSize as the effective sample size.

Theta

numeric or NULL. Dirichlet-Multinomial dispersion parameter in ⁠(0, 1]⁠. Values less than 1 produce overdispersed compositions relative to a standard multinomial; Theta = 1 (default) recovers the standard multinomial. Accepted input forms are the same as for SampleSize; see CompObs(). After population, stored as a named ⁠[nSim x nYear]⁠ array.

Years

numeric vector or NULL. Calendar years of observed composition data to be used during the conditioning step (see ConditionObs_Comp()). NULL (default) uses all available historical years during conditioning.

Shift

numeric or NULL. Systematic per-bin offset on the log-concentration scale applied to the Dirichlet concentration vector before drawing, capturing directional bias between observed and OM-predicted compositions. After population by PopulateCompObs(), stored as a named ⁠[nSim x nYear x nBin]⁠ array. NULL (default) applies no shift. In conditioning mode, populated internally by ConditionObs_Comp() from the mean per-bin log-concentration residual across historical years.

Misc

list. Reserved for internal use.

See Also

Other obs: CatchObs(), CompObs(), EffortObs(), ExploitationObs(), IndicesObs(), LifeHistoryObs(), Obs(), catchobs-class, effortobs-class, exploitationobs-class, indicesobs-class, lifehistoryobs-class, obs-class


Default OM Control Options

Description

A named list of default control options for Control(OM).

Usage

ControlDefault

Format

An object of class list of length 2.

Details

Can be modified if you know what you're doing!


Check Convergence

Description

Have I undertaken enough simulations (nsim)? Has my MSE converged on stable (reliable) performance metrics?

Usage

Converge(
  MSEobj,
  PMs = c("Yield", "P10", "AAVY"),
  maxMP = 15,
  thresh = 0.5,
  ref.it = 20,
  inc.leg = FALSE,
  all.its = FALSE,
  nrow = NULL,
  ncol = NULL,
  silent = FALSE
)

Arguments

MSEobj

An MSE object of class 'MSE'

PMs

A character vector of names of the PM methods or a list of the PM methods

maxMP

Maximum number of MPs to include in a single plot

thresh

The convergence threshold. Maximum root mean square deviation over the last ref.it iterations

ref.it

The number of iterations to calculate the convergence statistics. For example, a value of 20 means convergence diagnostics are calculated over last 20 simulations

inc.leg

Logical. Should the legend be displayed?

all.its

Logical. Plot all iterations? Otherwise only (nsim-ref.it):nsim

nrow

Numeric. Optional. Number of rows

ncol

Numeric. Optional. Number of columns

silent

Hide the messages printed in console?

Details

Performance metrics are plotted against the number of simulations. Convergence diagnostics are calculated over the last ref.it (default = 20) iterations. The convergence diagnostics are:

  1. Is the order of the MPs stable over the last ref.it iterations?

  2. Is the average difference in performance statistic over the last ref.it iterations < thresh?

By default three commonly used performance metrics are used:

  1. Average Yield Relative to Reference Yield

  2. Probability Spawning Biomass is above 0.1BMSY

  3. Probability Average Annual Variability in Yield is < 20 per cent

Additional or alternative performance metrics objects can be supplied. Advanced users can develop their own performance metrics.

Value

A table of convergence results for each MP

Author(s)

A. Hordyk

Examples

## Not run: 
MSE <- runMSE()
Converge(MSE)

## End(Not run)

Convert legacy S4 objects to new S4 object classes

Description

Converts legacy openMSE S4 objects to their equivalent new S4 class representations. Dispatches to the appropriate conversion function based on the class of x.

Usage

Convert(x, ...)

Arguments

x

A legacy S4 object of class OM-legacy, MOM-legacy, Stock-legacy, Fleet-legacy, Obs-legacy, Imp-legacy, or Data-legacy.

...

Additional named arguments passed to the underlying conversion function (ConvertOM(), ConvertMOM(), ConvertStock(), ConvertFleet(), ConvertObs(), ConvertImp(), or ConvertData()).

Details

Not all slots from Obs-legacy objects exist in the new obs objects. Slots without a direct equivalent are silently dropped.

Legacy Data objects do not contain discard data. It is assumed that Data@Cat represents landings only, with no discards. If Data@Cat represents total removals, the resulting data object must be updated manually after conversion.

Value

A new S4 object of the corresponding updated class:

See Also

ConvertOM(), ConvertMOM(), ConvertStock(), ConvertFleet(), ConvertObs(), ConvertImp(), ConvertData()

Examples

# Stock 
stock <- Convert(Herring)

# Fleet 
fleet <- Convert(Generic_Fleet)

# Obs 
obs <- Convert(Generic_Obs)

# Imp 
imp <- Convert(Perfect_Imp)

# OM 
om <- Convert(testOM)

# MOM 
om <- Convert(Albacore_TwoFleet)

# Data 
data <- Convert(China_rockfish)

Convert a Legacy Data Object to a New data Class

Description

Converts a legacy Data-legacy object to the current data for a single simulation, mapping observations, life history parameters, and advice to their corresponding new S4 slots.

Usage

ConvertData(Data, Seasons = 1, sim = 1, silent = FALSE)

Arguments

Data

A Data-legacy object to convert.

Seasons

Integer. Number of seasons per year. Default 1.

sim

Integer. Simulation index to extract from the legacy object. Default 1.

silent

Logical. If TRUE, suppresses progress messages. Default FALSE.

Details

Legacy Data objects do not distinguish between landings and discards. Data@Cat is mapped to Landings only; Discards will be empty in the resulting data object. If Data@Cat represents total removals, the Discards slot must be populated manually after conversion.

The following legacy slots are not currently converted and are silently dropped:

  • Additional indices: SpInd, VInd, AddInd, AddIndType, AddIndV, AddIunits (a warning is emitted if AddInd is non-empty)

  • Mean lengths: ML, Lc, Lbar

  • Abundance: Abun, SpAbun

  • Reference points: FMSY_M, BMSY_B0, Bref, Iref

  • Recruitment: Rec

  • Average catch/depletion: AvC, Dt

  • Ref slot: Ref, Ref_type

Value

A data object populated from simulation sim of Data.

See Also

Convert(), ConvertOM(), ConvertMOM()

Examples

## Not run: 
Datalegacy <- readRDS("MyLegacyData.rds")
data_new <- ConvertData(Datalegacy, sim = 1)

## End(Not run)

Convert a Legacy Fleet Object to the Current fleet Class

Description

Converts a legacy Fleet-legacy object to the current fleet by mapping each component to its corresponding new S4 sub-object.

Usage

ConvertFleet(Fleet, silent = FALSE)

Arguments

Fleet

A Fleet-legacy object to convert. An OM-legacy object with a legacy Fleet slot is also accepted, in which case the Fleet slot is extracted and converted.

silent

Logical. If TRUE, suppresses progress messages. Default FALSE.

Details

Slot Mapping

The following legacy slots are mapped to their current equivalents:

Legacy slot New location
Name fleet@Name
EffYears, EffLower, EffUpper, Esd Effort@Effort (data frame)
qcv, qinc Catchability@qCV, ⁠@qInc⁠
L5, LFS, Vmaxlen Selectivity@Pars, ⁠@Model = DoubleNormal⁠
LR5, LFR, Rmaxlen Retention@Pars, ⁠@Model = DoubleNormalRetention⁠

Effort

Historical effort is constructed as a data frame with columns Year, Lower, Upper, and CV, passed to Effort(). The legacy Esd slot contains a two-element vector of lower and upper bounds for a uniform distribution of effort variability. Only Esd[1] is currently used as a scalar CV; Esd[2] is silently dropped.

Selectivity

L5, LFS, and Vmaxlen map to the DoubleNormal() double-normal selectivity-at-length model. Vmaxlen < 1 produces a dome-shaped selectivity curve. See SelectivityModels() for the full set of available selectivity models.

Retention

LR5, LFR, and Rmaxlen map to the DoubleNormalRetention() double-normal retention-at-length model. Rmaxlen < 1 produces a dome-shaped retention curve. See RetentionModels() for the full set of available retention models.

Slots Not Converted

The following slots have no equivalent in the legacy Fleet-legacy and retain their default values in the converted object:

  • DiscardMortality: new functionality; no legacy equivalent.

  • Closure: new functionality; no legacy equivalent.

  • Targeting: new functionality; no legacy equivalent.

  • WeightFleet: new functionality; no legacy equivalent.

Value

A fleet object.

See Also

Convert(), ConvertOM(), ConvertMOM(), ConvertStock(), ConvertObs(), ConvertImp(), Effort(), Catchability(), Selectivity(), Retention(), SelectivityModels(), RetentionModels()

Examples

## Not run: 
fleet_legacy <- readRDS("MyLegacyFleet.rds")
fleet_new <- ConvertFleet(fleet_legacy)

## End(Not run)

Convert a Legacy Imp Object to a New imp Class

Description

Converts a legacy Imp-legacy object to the current imp by mapping implementation error parameters to their corresponding new S4 slots.

Usage

ConvertImp(Imp, silent = FALSE)

Arguments

Imp

An Imp-legacy object to convert.

silent

Logical. If TRUE, suppresses progress messages. Default FALSE.

Value

An imp object with TAC, Effort, and Size implementation error slots populated.

See Also

Convert(), ConvertOM(), ConvertMOM(), ConvertObs()

Examples

## Not run: 
Implegacy <- readRDS("MyLegacyImp.rds")
imp_new <- ConvertImp(Implegacy)

## End(Not run)

Convert Legacy MOM Object to New om Class

Description

Converts a legacy MOM-legacy object to the current om, copying attributes, updating year vectors, and optionally populating the object via PopulateOM().

Usage

ConvertMOM(
  MOM,
  Author = "",
  CurrentYear = NULL,
  Seasons = 1,
  Populate = TRUE,
  silent = FALSE
)

Arguments

MOM

A MOM-legacy object to convert.

Author

Character. Author of the OM. Default "".

CurrentYear

Numeric. Last historical calendar year. If NULL (default), taken from MOM@Fleets[[1]][[1]]@CurrentYr; if that is less than 1000, defaults to the current system year.

Seasons

Integer. Number of seasons per year. Default 1.

Populate

Logical. If TRUE (default), calls PopulateOM() on the converted object.

silent

Logical. If TRUE, suppresses progress messages. Default FALSE.

Value

An om object.

See Also

Convert(), ConvertOM(), ConvertStock(), ConvertFleet(), ConvertObs(), ConvertImp(), PopulateOM()

Examples

## Not run: 
MOMlegacy <- readRDS("MyLegacyMOM.rds")
om_new <- ConvertMOM(MOMlegacy)

## End(Not run)

Convert a Legacy Obs Object to the Current obs Class

Description

Converts a legacy Obs-legacy object to the current obs by mapping observation error parameters to their corresponding sub-object slots.

Usage

ConvertObs(Obs, silent = FALSE)

Arguments

Obs

An Obs-legacy object to convert. An om object with a legacy Obs slot is also accepted, in which case the Obs slot is extracted and converted.

silent

Logical. If TRUE, suppresses progress messages. Default FALSE.

Details

Slot Mapping

The following legacy slots are mapped to their current equivalents:

Legacy slot New slot
Eobs Effort@CV
Ebiascv Effort@Bias
Cobs Landings@CV and Discards@CV
Cbiascv Landings@Bias and Discards@Bias
Iobs CPUE@CV and Survey@CV

Note that Discards@CV and Discards@Bias are set to the same values as Landings (Cobs and Cbiascv) because legacy objects do not distinguish between landings and discards observation error.

Slots Not Yet Converted

The following legacy slots do not have a corresponding slot in the current obs and are silently dropped. They will be mapped once the lifehistoryobs and exploitationobs placeholders are fully implemented:

  • Life-history bias CVs: Linfbiascv, t0biascv, Kbiascv, LenMbiascv, Mbiascv

  • Selectivity bias CVs: LFCbiascv, LFSbiascv

  • Reference point bias CVs: FMSY_Mbiascv, BMSY_B0biascv

  • Composition data: CAA_nsamp, CAA_ESS, CAL_nsamp, CAL_ESS (mapped to LandingsAtAge and LandingsAtSize once implemented)

Value

An obs object.

See Also

Convert(), ConvertOM(), ConvertMOM(), ConvertImp() for related legacy conversion functions.

Examples

## Not run: 
obs_legacy <- readRDS("MyLegacyObs.rds")
obs_new <- ConvertObs(obs_legacy)

## End(Not run)

Convert Legacy OM Object to New om Class

Description

Converts a legacy OM-legacy object to the current om, copying attributes, updating year vectors, and optionally populating the object via PopulateOM().

Usage

ConvertOM(
  OM,
  Author = "",
  CurrentYear = NULL,
  Seasons = 1,
  Populate = TRUE,
  silent = FALSE
)

Arguments

OM

An OM-legacy object to convert.

Author

Character. Author of the OM. Default "".

CurrentYear

Numeric. Last historical calendar year. If NULL (default), taken from OM@CurrentYr; if that is less than 1000, defaults to the current system year.

Seasons

Integer. Number of seasons per year. Default 1.

Populate

Logical. If TRUE (default), calls PopulateOM() on the converted object.

silent

Logical. If TRUE, suppresses progress messages. Default FALSE.

Details

Maximum length slots (Vmaxlen and Rmaxlen) are updated to reflect the maximum length class rather than Linf as in legacy objects. This changes the selectivity and retention curves if Vmaxlen or Rmaxlen are less than 1. As an alternative, users can set the MeanAtLength or MeanAtAge arrays directly in the Selectivity() and Retention() objects.

Value

An om object.

See Also

Convert(), ConvertMOM(), ConvertStock(), ConvertFleet(), ConvertObs(), ConvertImp(), PopulateOM()

Examples

## Not run: 
OMlegacy <- readRDS("MyLegacyOM.rds")
om_new <- ConvertOM(OMlegacy)

## End(Not run)

Convert a Legacy Stock Object to the Current stock Class

Description

Converts a legacy Stock-legacy object to the current stock by mapping each component to its corresponding new S4 sub-object.

Usage

ConvertStock(Stock, Seasons = 1, silent = FALSE)

Arguments

Stock

A Stock-legacy object to convert. An OM-legacy object with a legacy Stock slot is also accepted, in which case the Stock slot is extracted and converted.

Seasons

Numeric. Number of seasons in a year. Default 1.

silent

Logical. If TRUE, suppresses progress messages. Default FALSE.

Details

Slot Mapping

The following legacy slots are mapped to their current equivalents:

Legacy slot New location
Name, Common_Name, Species stock@Name, ⁠@CommonName⁠, ⁠@Species⁠
maxage Ages@MaxAge (via Ages(), MinAge = 0)
Linf, K, t0, Linfsd, Ksd, LenCV Length@Pars, ⁠@CVatAge⁠
a, b Weight@Pars$alpha, ⁠@Pars$beta⁠
M, Msd NaturalMortality@Pars
L50, L50_95 Maturity@Pars, ⁠@Model = MaturityAtLength⁠
ageM, age95 Maturity@Pars, ⁠@Model = MaturityAtAge⁠ (used only when L50 is absent)
h SRR@Pars$h
R0 SRR@R0
Perr SRR@SD
AC SRR@AC
SRrel SRR@Model (1"BevertonHolt", 2"Ricker")
Size_area_1 Spatial@RelativeSize
Prob_staying Spatial@ProbStaying
Frac_area_1 Spatial@UnfishedDist
D Depletion@Final

Maturity Priority

When both length-based (L50, L50_95) and age-based (ageM, age95) maturity parameters are present, the length-based parameters take priority and Model is set to MaturityAtLength. Age-based parameters are used only when L50 is absent or NULL.

Spatial Structure

If all three spatial parameters (Size_area_1, Prob_staying, Frac_area_1) equal 0.5, an empty spatial object is returned. This is treated by the model as a single well-mixed area with no spatial structure.

Value

A stock object.

See Also

Convert(), ConvertOM(), ConvertMOM(), ConvertFleet(), ConvertObs(), ConvertImp()

Examples

## Not run: 
stock_legacy <- readRDS("MyLegacyStock.rds")
stock_new <- ConvertStock(stock_legacy)

## End(Not run)

Current default thresholds for COSEWIC satisficing

Description

Current default thresholds for COSEWIC satisficing

Usage

Cos_thresh_tab(Ptab1)

Arguments

Ptab1

A COSEWIC performance table made by COSEWIC_tab()

Author(s)

T. Carruthers


Internal function for checking that the OM@cpars is formatted correctly

Description

Internal function for checking that the OM@cpars is formatted correctly

Usage

cparscheck(cpars)

Arguments

cpars

a list of model parameters to be sampled (single parameters are a vector nsim long, first dimension of matrices and arrays must be nsim)

Value

either an error and the length of the first dimension of the various cpars list items or passes and returns the number of simulations in cpars

Author(s)

T. Carruthers


Plot the median biomass and yield relative to last historical year

Description

Compare median biomass and yield in first year and last 5 years of projection

Usage

Cplot(
  MSEobj,
  MPs = NA,
  lastYrs = 5,
  point.size = 2,
  lab.size = 4,
  axis.title.size = 12,
  axis.text.size = 10,
  legend.title.size = 12
)

Arguments

MSEobj

An object of class MSE

MPs

Optional vector of MPs to plot

lastYrs

Numeric. Last number of years to summarize results.

point.size

Size of the points

lab.size

Size of labels

axis.title.size

Axis title size

axis.text.size

Axis text size

legend.title.size

Legend title size

Examples

## Not run: 
MSE <- runMSE()
Cplot(MSE)

## End(Not run)

Convert Between Steepness and Compensation Ratio

Description

Convert between the Beverton-Holt stock-recruitment steepness (h) and compensation ratio (CR) parameterizations.

Usage

CR2h(CR)

h2CR(h)

Arguments

CR

Numeric. Compensation ratio (see Details).

h

Numeric. Steepness value (see Details). Must be in the range (0.2, 1), exclusive.

Details

Steepness (h) is the fraction of unfished recruitment obtained when the spawning biomass is reduced to 20% of its unfished level. It is bounded between 0.2 (highly depensatory) and 1.0 (density-independent recruitment).

Compensation ratio (CR) is the ratio of recruits-per-spawner at the origin of the stock-recruitment curve relative to recruits-per-spawner at unfished equilibrium. Higher values indicate stronger density-dependent compensation. CR is bounded between 1 (no compensation) and infinity.

The relationships between the two parameters are:

h=CRCR+4CR=4h1hh = \frac{CR}{CR + 4} \qquad CR = \frac{4h}{1 - h}

Value

Numeric. CR2h() returns steepness (h) bounded between 0.2 and 1; h2CR() returns the compensation ratio (CR).

Examples

CR2h(5)
h2CR(0.7)

Constructor and Accessor for Data

Description

Creates a new data object, or extracts the Data or PPD slot from an existing om, hist, or mse class object.

Usage

Data(
  Name = "New Data Object",
  CommonName = NULL,
  Species = NULL,
  Agency = NULL,
  Author = NULL,
  Email = NULL,
  Region = NULL,
  Latitude = NULL,
  Longitude = NULL,
  Years = NULL,
  YearLH = NULL,
  Seasons = 1,
  nArea = 1,
  LifeHistory = NULL,
  Exploitation = NULL,
  Reference = NULL,
  Effort = NULL,
  Landings = NULL,
  Discards = NULL,
  CPUE = NULL,
  Survey = NULL,
  LandingsAtAge = NULL,
  DiscardsAtAge = NULL,
  LandingsAtSize = NULL,
  DiscardsAtSize = NULL,
  Advice = NULL,
  Misc = list()
)

Arguments

Name

Either a character string naming the new data object, or an existing om, hist, or mse object from which to extract data. Defaults to "New Data Object".

CommonName

Optional character string. Common name of the stock.

Species

Optional character string. Scientific name of the species.

Agency

Optional character string. Name of the managing agency.

Author

Optional character string. Name of the data author.

Email

Optional character string. Contact email for the author.

Region

Optional character string. Geographic region of the stock.

Latitude

Optional numeric. Latitude of the stock.

Longitude

Optional numeric. Longitude of the stock.

Years

Vector of calendar years covered by the data. Required

YearLH

The last historical year; separates the historical period from the projection period. Defaults to max(Years).

Seasons

A positive integer giving the number of seasons per year. Defaults to 1.

nArea

A positive integer giving the number of spatial areas. Defaults to 1.

LifeHistory

Optional. An object of class lifehistorydata .

Exploitation

Optional. An object of class exploitationdata.

Reference

Optional. An object of class referencedata.

Effort

Optional. An object of class effortdata.

Landings

Optional. An object of class catchdata for landed catch.

Discards

Optional. An object of class catchdata for discarded catch.

CPUE

Optional. An object of class indicesdata for catch-per-unit- effort indices.

Survey

Optional. An object of class indicesdata for fishery- independent survey indices.

LandingsAtAge

Optional. An object of class compdata for age composition of landings.

DiscardsAtAge

Optional. An object of class compdata for age composition of discards.

LandingsAtSize

Optional. An object of class compdata for size composition of landings.

DiscardsAtSize

Optional. An object of class compdata for size composition of discards.

Advice

Optional. An object of class advicedata containing TAC and related advice.

Misc

A named list for any additional user-defined data. Defaults to list().

Details

When Name is an om or hist object, the function returns the corresponding ⁠@Data⁠ slot. When Name is an mse object, the ⁠@PPD⁠ slot is returned instead. Otherwise, a new data object is constructed from the supplied arguments.

All slot arguments default to NULL, in which case an empty sub-object of the appropriate class is initialised automatically:

Value

A data object, or when Name is an mse object, a list of data objects from the ⁠@PPD⁠ slot.

See Also

data, LastTAC(), LastHistYearInd(), ProjectionYear()


Read in Data object from Excel spreadsheet

Description

A function to read in Data object from an Excel spreadsheet with tabs named following specific convention.

Usage

Data_xl(fname, stkname, fpath = "", saveCSV = FALSE)

Arguments

fname

Name of the Excel spreadsheet file. Must include file extension.

stkname

Name of the Stock.

fpath

Full file path, if file is not in current working directory

saveCSV

Do you also want to the Data parameters to a CSV file?

Details

The Excel spreadsheet must have tabs named with the following convention. For example if stkname is 'myFish', the Data parameters are in a tab named 'myFishData'.

Value

A object of class Data

Author(s)

A. Hordyk

Examples

## Not run: 
OM <- OM_xl(fname='OMTables.xlsx', stkname='myFish')

## End(Not run)

The data S4 Class

Description

The data class stores observed or simulated fishery data used by an OM() object. Data may include life-history information, exploitation patterns, catches, indices, age and size compositions, and management advice.

Details

Objects should be created with the Data() constructor, which initialises all sub-object slots to empty objects of the appropriate class when not supplied.

Slots

Name

Optional character string. Name of the data object.

CommonName

Optional character string. Common name of the stock.

Species

Optional character string. Scientific name of the species.

Agency

Optional character string. Name of the managing agency.

Author

Optional character string. Name(s) of the data author(s).

Email

Optional character string. Contact email(s) for the author(s).

Region

Optional character string. Geographic region of the stock.

Latitude

Optional numeric. Latitude of the stock in decimal degrees.

Longitude

Optional numeric. Longitude of the stock in decimal degrees.

Years

Numeric vector of calendar years covered by the data.

YearLH

Numeric. The last historical year, separating the historical period from the projection period. Defaults to max(Years) when not supplied to Data().

Seasons

Positive integer. Number of seasons per year. Defaults to 1.

nArea

Positive integer. Number of spatial areas. Defaults to 1.

LifeHistory

An object of class lifehistorydata containing biological parameters such as growth, maturity, and natural mortality.

Exploitation

An object of class exploitationdata containing selectivity, retention, and discard mortality parameters.

Reference

An object of class referencedata containing biological reference points such as unfished biomass and MSY-based quantities.

Effort

An object of class effortdata containing fishing effort time series.

Landings

An object of class catchdata containing landed catch time series.

Discards

An object of class catchdata containing discarded catch time series.

CPUE

An object of class indicesdata containing catch-per-unit-effort indices.

Survey

An object of class indicesdata containing fishery-independent survey indices.

LandingsAtAge

An object of class compdata containing age composition of landed catch.

DiscardsAtAge

An object of class compdata containing age composition of discarded catch.

LandingsAtSize

An object of class compdata containing size composition of landed catch.

DiscardsAtSize

An object of class compdata containing size composition of discarded catch.

Advice

An object of class advicedata containing TAC recommendations and related management advice.

Misc

A named list for any additional user-defined data. Defaults to list().

Log

Internal named list used for diagnostic and audit logging.

See Also

Data()


Class 'Data'

Description

An object for storing fishery data for analysis

Slots

Name

The name of the Data object. Single value. Character string

Common_Name

Common name of the species. Character string

Species

Scientific name of the species. Genus and species name. Character string

Region

Name of the general geographic region of the fishery. Character string

LHYear

The last historical year of the simulation (before projection). Single value. Positive integer

MPrec

The previous recommendation of a management procedure. Vector of length nsim. Positive real numbers

Units

Units of the catch/absolute abundance estimates. Single value. Character string

MPeff

The current level of effort. Vector of length nsim. Positive real numbers

nareas

Number of fishing areas. Vector of length nsim. Non-negative integer

MaxAge

Maximum age. Vector nsim long. Positive integer

Mort

Natural mortality rate. Vector nsim long. Positive real numbers

CV_Mort

Coefficient of variation in natural mortality rate. Vector nsim long. Positive real numbers

vbLinf

Maximum length. Vector nsim long. Positive real numbers

CV_vbLinf

Coefficient of variation in maximum length. Vector nsim long. Positive real numbers

vbK

The von Bertalanffy growth coefficient K. Vector nsim long. Positive real numbers

CV_vbK

Coefficient of variation in the von Bertalanffy K parameter. Vector nsim long. Positive real numbers

vbt0

Theoretical age at length zero. Vector nsim long. Non-positive real numbers

CV_vbt0

Coefficient of variation in age at length zero. Vector nsim long. Positive real numbers

wla

Weight-Length parameter alpha. Vector nsim long. Positive real numbers

CV_wla

Coefficient of variation in weight-length parameter a. Vector nsim long. Positive real numbers

wlb

Weight-Length parameter beta. Vector nsim long. Positive real numbers

CV_wlb

Coefficient of variation in weight-length parameter b. Vector nsim long. Positive real numbers

steep

Steepness of stock-recruitment relationship. Vector nsim long. Value in the range of one-fifth to 1

CV_steep

Coefficient of variation in steepness. Vector nsim long. Positive real numbers

sigmaR

Recruitment variability. Vector nsim long. Positive real numbers

CV_sigmaR

Coefficient of variation in recruitment variability. Vector nsim long. Positive real numbers

L50

Length at 50 percent maturity. Vector nsim long. Positive real numbers

CV_L50

Coefficient of variation in length at 50 per cent maturity. Vector nsim long. Positive real numbers

L95

Length at 95 percent maturity. Vector nsim long. Positive real numbers

LenCV

Coefficient of variation of length-at-age (assumed constant for all age classes). Vector nsim long. Positive real numbers

LFC

Length at first capture. Vector nsim long. Positive real numbers

CV_LFC

Coefficient of variation in length at first capture. Vector nsim long. Positive real numbers

LFS

Shortest length at full selection. Vector nsim long. Positive real numbers

CV_LFS

Coefficient of variation in length at full selection. Vector nsim long. Positive real numbers

Vmaxlen

Vulnerability of individuals at asymptotic length. Vector nsim long. Real number between 0 and 1.

Year

Years that corresponding to catch and relative abundance data. Vector nyears long. Positive integer

Cat

Total annual catches. Matrix of nsim rows and nyears columns. Non-negative real numbers

CV_Cat

Coefficient of variation in annual catches. Matrix nsim rows and either 1 or nyear columns. Positive real numbers. Note: built-in MPs use only the first value of CV_Cat for all years.

Effort

Annual fishing effort. Matrix of nsim rows and nyears columns. Non-negative real numbers

CV_Effort

Coefficient of variation in annual effort. Matrix nsim rows and either 1 or nyear columns. Positive real numbers. Note: built-in MPs use only the first value of CV_Effort for all years.

Ind

Relative total abundance index. Matrix of nsim rows and nyears columns. Non-negative real numbers

CV_Ind

Coefficient of variation in the relative total abundance index. Matrix nsim rows and either 1 or nyear columns. Positive real numbers. Note: built-in MPs use only the first value of CV_Ind for all years

SpInd

Relative spawning abundance index. Matrix of nsim rows and nyears columns. Non-negative real numbers

CV_SpInd

Coefficient of variation in the relative spawning abundance index. Matrix nsim rows and either 1 or nyear columns. Positive real numbers.

VInd

Relative vulnerable abundance index. Matrix of nsim rows and nyears columns. Non-negative real numbers

CV_VInd

Coefficient of variation in the relative vulnerable abundance index. Matrix nsim rows and either 1 or nyear columns. Positive real numbers.

AddInd

Optional additional indices. Array of dimensions nsim, n additional indices, and nyears (length Year).

CV_AddInd

Coefficient of variation for additional indices. Array of same dimensions as AddInd

AddIndV

Vulnerability-at-age schedules for the additional indices. Array with dimensions: nsim, n additional indices, MaxAge+1.

AddIunits

Units for the additional indices - biomass (1; default) or numbers (0). Numeric vector length n.ind.

AddIndType

Index calculated from total stock (1, default), spawning stock (2), or vulnerable stock (3). Numeric vector of length n.ind

Rec

Recent recruitment strength. Matrix of nsim rows and nyears columns. Non-negative real numbers

CV_Rec

Log-normal CV for recent recruitment strength. Matrix nsim rows and either 1 or nyear columns. Positive real numbers. Note: built-in MPs use only the first value of CV_Rec for all years.

ML

Mean length time series. Matrix of nsim rows and nyears columns. Non-negative real numbers

Lc

Modal length of catches. Matrix of nsim rows and nyears columns. Positive real numbers

Lbar

Mean length of catches over Lc. Matrix of nsim rows and nyears columns. Positive real numbers

Vuln_CAA

Optional vulnerability-at-age schedule for catch-at-age samples. Used to condition OM for closed-loop simulation testing. Replaces the fleet selectivity schedule in the OM used to generate CAA samples. Matrix with dimensions nsim x MaxAge+1.

CAA

Catch at Age data (numbers). Array of dimensions nsim x nyears x MaxAge+1. Non-negative integers

Vuln_CAL

Optional vulnerability-at-length schedule for catch-at-length samples. Used to condition OM for closed-loop simulation testing. Replaces the fleet selectivity schedule in the OM used to generate CAL samples. Matrix with dimensions nsim x length(CAL_mids).

CAL_bins

The values delimiting the length bins for the catch-at-length data. Vector. Non-negative real numbers

CAL_mids

The values of the mid-points of the length bins. Optional, calculated from CAL_bins if not entered. Vector. Non-negative real numbers.

CAL

Catch-at-length data. An array with dimensions nsim x nyears x length(CAL_mids). Non-negative integers. By default the CAL data will be the retained lengths (i.e, not including discards). If OM@control$CAL =="removals" then the CAL data will include all removals (retained + discards).

Dep

Stock depletion SSB(current)/SSB(unfished). Vector nsim long. Fraction.

CV_Dep

Coefficient of variation in current stock depletion. Vector nsim long. Positive real numbers

Abun

An estimate of absolute current vulnerable abundance. Vector nsim long. Positive real numbers

CV_Abun

Coefficient of variation in estimate of absolute current stock size. Vector nsim long. Positive real numbers

SpAbun

An estimate of absolute current spawning stock abundance. Vector nsim long. Positive real numbers

CV_SpAbun

Coefficient of variation in estimate of absolute spawning current stock size. Vector nsim long. Positive real numbers

FMSY_M

An assumed ratio of FMSY to M. Vector nsim long. Positive real numbers

CV_FMSY_M

Coefficient of variation in the ratio in FMSY/M. Vector nsim long. Positive real numbers

BMSY_B0

The most productive stock size relative to unfished. Vector nsim long. Fraction

CV_BMSY_B0

Coefficient of variation in the position of the most productive stock size relative to unfished. Vector nsim long. Positive real numbers

Cref

Reference or target catch level (eg MSY). Vector of length nsim. Positive real numbers

CV_Cref

Log-normal CV for reference or target catch level. Vector of length nsim. Positive real numbers

Bref

Reference or target biomass level (eg BMSY). Vector of length nsim. Positive real numbers

CV_Bref

Log-normal CV for reference or target biomass level. Vector of length nsim. Positive real numbers

Iref

Reference or target relative abundance index level (eg BMSY / B0). Vector of length nsim. Positive real numbers

CV_Iref

Log-normalCV for reference or target relative abundance index level. Vector of length nsim. Positive real numbers

t

The number of years corresponding to AvC and Dt. Single value. Positive integer

AvC

Average catch over time t. Vector nsim long. Positive real numbers

CV_AvC

Coefficient of variation in average catches over time t. Vector nsim long. Positive real numbers

Dt

Depletion over time t SSB(now)/SSB(now-t+1). Vector nsim long. Fraction

CV_Dt

Coefficient of variation in depletion over time t. Vector nsim long. Positive real numbers

Ref

A reference management level (eg a catch limit). Single value. Positive real number

Ref_type

Type of reference management level (eg 2009 catch limit). Single value. Character string

Log

A record of events. Single value. Character string

params

A place to store estimated parameters. An object. R list

PosMPs

The methods that can be applied to these data. Vector. Character strings

TAC

The calculated catch limits (function TAC). An array with dimensions PosMPs x replicate TAC samples x nsim. Positive real numbers

Sense

The results of the sensitivity analysis (function Sense). An array with dimensions PosMPs x sensitivity increments. Positive real numbers

MPs

The methods that were applied to these data. Vector. Character strings

OM

A table of operating model conditions. R table object of nsim rows. Real numbers

Obs

A table of observation model conditions. R table object of nsim rows. Real numbers

Misc

Other information for MPs. An object. R list

Objects from the Class

Objects can be created by calls of the form new('Data', stock)

Author(s)

T. Carruthers and A. Hordyk

Examples

newdata<-new('Data')

Converts a Data object into a .csv data file

Description

A function that writes a correctly formatted .csv file from a MSEtool Data object

Usage

Data2csv(Data, file = NULL, simno = 1, overwrite = F, keepNAs = T)

Arguments

Data

An object of class 'Data'.

file

Character string. The name of the location and file you wish to create (e.g. "C:/temp/mydata.csv")

simno

Integer. An optional argument to specify the simulation number if writing simulated data

overwrite

Boolean. Should existing data files be automatically overwritten.

keepNAs

Boolean. Should slots with NAs still be written to the data file.

Author(s)

T. Carruthers


DataDescription

Description

A data.frame with description of slots for class Data

Usage

DataDescription

Format

An object of class data.frame with 94 rows and 2 columns.


Directory of the data in the installed package on your computer

Description

A way of locating where the package was installed so you can find example data files and code etc.

Usage

DataDir(stock = NA)

Arguments

stock

Character string representing the name of a .csv file e.g. 'Snapper', 'Rockfish'

Value

The file path to the object

Author(s)

T. Carruthers

Examples

## Not run: 
tilefish_location <- DataDir("Gulf_blue_tilefish")
tilefish_Data <- new("Data", tilefish_location)

## End(Not run)

Data Helper Functions

Description

A collection of helper functions for extracting key values from a Data object, including TAC advice, and year indices for historical and projection time steps.

Usage

LastTAC(Data)

LastHistYearInd(Data)

ProjectionYear(Data)

Arguments

Data

An object of class data.

Value

  • LastTAC(): A numeric scalar giving the last TAC, or the sum of the most recent landings and discards if no TAC is available.

  • LastHistYearInd(): An integer giving the index of the last historical year in Data@Years.

  • ProjectionYear(): A positive integer giving the current projection year index.

Functions

  • LastTAC(): Get the last TAC (Total Allowable Catch) from the advice slot. If no TAC has been set, returns the sum of the most recent landings and discards.

  • LastHistYearInd(): Get the index of the last historical year within Data@Years. This is the position of the final year that does not exceed Data@YearLH, and is typically used to subset or index time series vectors aligned to Data@Years.

  • ProjectionYear(): Get the index of the current projection time step relative to Data@YearLH. Returns 1 in the first projection year, incrementing by one each subsequent timestep

See Also

DataTrim()


Initialize Data Input Files

Description

Creates template for the Data input file (Excel or CSV) and Data documentation file (Markdown) in the working directory or the directory specified by the dir argument

Usage

DataInit(name = "Data", ext = c("xlsx", "csv"), overwrite = FALSE, dir = NULL)

Arguments

name

Name of the data input files. Default is 'Data'. Use 'Example' to create populated example Data Input and Data Documentation files.

ext

Optional file extension for input file. 'xlsx' (default) or 'csv'

overwrite

Logical. Overwrite existing files?

dir

Optional directory path to create the Data files. Default is 'getwd()“

Value

Nothing. Creates template data files in the working directory.

Author(s)

A. Hordyk

Examples

## Not run: 
DataInit("Example") # populated example
DataInit("myData") # empty template

## End(Not run)

Data-Rich Observation Model

Description

An obs object representing a fully observed scenario in which all data types are available: landings, discards, fishing effort, a commercial CPUE index, a fishery-independent survey, and both age- and length-composition samples from landed and discarded fish.

Usage

DataRichObs

Format

An obs object with all slots populated:

  • Landings (catchobs): precisely reported landings with CV in ⁠[0.03, 0.08]⁠ and near-unbiased reporting ⁠[0.98, 1.02]⁠, reflecting well-monitored logbook compliance.

  • Discards (catchobs): observer-estimated discards with CV in ⁠[0.10, 0.20]⁠ and bias in ⁠[0.90, 1.10]⁠.

  • Effort (effortobs): electronically monitored vessel-days with CV in ⁠[0.02, 0.05]⁠ and negligible bias ⁠[0.98, 1.02]⁠.

  • CPUE (indicesobs): logbook-derived standardised CPUE with CV in ⁠[0.10, 0.20]⁠ and mild autocorrelation ⁠[0.0, 0.2]⁠.

  • Survey (indicesobs): annual spawning-biomass survey with CV in ⁠[0.08, 0.15]⁠ and negligible autocorrelation ⁠[0.0, 0.1]⁠.

  • LandingsAtAge (compobs): stratified port-sampling age compositions of landed fish. Nominal sample size ⁠[300, 500]⁠; ESS ⁠[80, 150]⁠; Theta in ⁠[0.6, 1.0]⁠.

  • DiscardsAtAge (compobs): observer age samples from discarded fish. Nominal sample size ⁠[150, 250]⁠; ESS ⁠[50, 100]⁠; Theta in ⁠[0.5, 0.9]⁠.

  • LandingsAtSize (compobs): dockside length-composition samples from landed fish. Nominal sample size ⁠[400, 700]⁠; ESS ⁠[100, 180]⁠; Theta in ⁠[0.6, 1.0]⁠.

  • DiscardsAtSize (compobs): observer-measured length compositions from discarded fish. Nominal sample size ⁠[200, 350]⁠; ESS ⁠[60, 120]⁠; Theta in ⁠[0.5, 0.9]⁠.

See Also

obs, Obs(), CatchObs(), EffortObs(), IndicesObs(), CompObs(), CatchAndSurveyObs, CommercialFleetObs, AgeStructuredObs, LengthStructuredObs

Other obs-examples: AgeStructuredObs, CatchAndSurveyObs, CommercialFleetObs, LengthStructuredObs

Examples

DataRichObs
Survey(DataRichObs)
LandingsAtAge(DataRichObs)
DiscardsAtSize(DataRichObs)

DataSlots

Description

Dataframe with details of slots in Dat object

Usage

DataSlots

Format

An object of class tbl_df (inherits from tbl, data.frame) with 101 rows and 4 columns.


Trim Data Object by Final Year

Description

Truncate a Data object so that all time-dependent arrays are trimmed to the specified final year.

Usage

DataTrim(Data, Year)

Arguments

Data

A data class object containing year-indexed information.

Year

A single numeric value specifying the final year to retain.

Arrays that are not indexed by Year are left unchanged. If the supplied year is already the maximum year in the object, the input object is returned unchanged. The Advice object is preserved from the original Data object.

  • Year must be numeric and of length one.

  • Year must be contained in Years(Data).

Value

A Data object where all year-dependent slots include only years less than or equal to Year.

See Also

  • SubsetYear() for year-based subsetting

  • Years() for extracting available years


Fleet class objects

Description

Example objects of class Fleet

Usage

DecE_Dom

DecE_HDom

DecE_NDom

FlatE_Dom

FlatE_HDom

FlatE_NDom

Generic_DecE

Generic_FlatE

Generic_Fleet

Generic_IncE

IncE_HDom

IncE_NDom

Low_Effort_Non_Target

Target_All_Fish

Targeting_Small_Fish

Format

An object of class Fleet of length 1.

An object of class Fleet of length 1.

An object of class Fleet of length 1.

An object of class Fleet of length 1.

An object of class Fleet of length 1.

An object of class Fleet of length 1.

An object of class Fleet of length 1.

An object of class Fleet of length 1.

An object of class Fleet of length 1.

An object of class Fleet of length 1.

An object of class Fleet of length 1.

An object of class Fleet of length 1.

An object of class Fleet of length 1.

An object of class Fleet of length 1.

An object of class Fleet of length 1.

Examples

avail("Fleet")

Default Ages and Years

Description

Convenience functions that return a sensible default when their argument is NULL. Used internally to allow optional Ages and Years arguments throughout the package without requiring callers to always supply them.

Usage

DefaultAges(Ages = NULL)

DefaultYears(Years = NULL)

Arguments

Ages

An ages object, or NULL (default).

Years

Numeric vector of years, or NULL (default).

Details

  • DefaultAges(): returns Ages unchanged if supplied, otherwise creates an ages object with MaxAge = 10 via Ages().

  • DefaultYears(): returns Years unchanged if supplied, otherwise generates an annual sequence from 1950 to five years beyond the current calendar year.

Value

  • DefaultAges(): an ages object.

  • DefaultYears(): a numeric vector of integer years.

See Also

Ages(), ages

Examples

DefaultAges()
DefaultYears()

Delete the Log Directory

Description

Delete the Log Directory

Usage

DeleteLogs(Dir = file.path(getwd(), "Log"))

Arguments

Dir

Directory where the logs are kept.

Value

Nothing


Depletion Constructor and Accessors

Description

Construct a depletion object defining the initial and/or final depletion assumptions for a stock, or access and replace the Depletion slot of a stock and its individual slots. Depletion is optional — see Default Behaviour below.

Usage

Depletion(Initial = NULL, Final = NULL, Reference = "B0")

Initial(x)

Initial(x) <- value

Final(x)

Final(x) <- value

Depletion(x) <- value

Arguments

Initial

numeric or NULL. Depletion relative to Reference at the start of the historical period. Accepted formats:

  • NULL (default): stock is assumed unfished at the start of the historical period. No adjustment to recruitment deviations.

  • Scalar: same depletion for all simulations.

  • Length-2 bounds vector: depletion sampled from Uniform(lower, upper) independently for each simulation.

  • Length-nSim vector: one value per simulation. When provided, early historical recruitment deviations are adjusted so that biomass relative to Reference in the first time step matches the specified value. When Initial is a stock object, Depletion() acts as a pass-through accessor and returns x@Depletion.

Final

numeric or NULL. Target depletion relative to Reference in the terminal historical time step. Accepts the same formats as Initial. When populated, the Efficiency parameter in Catchability() is optimised to achieve this depletion level, overwriting any existing Efficiency values. When NULL (default), no optimisation occurs and Catchability() must be populated directly with valid values.

Reference

character(1). Reference biomass used to scale depletion. Currently implemented options:

  • "B0" (default): total unfished equilibrium biomass.

  • "SB0": spawning biomass at unfished equilibrium. The options "BMSY", "SBMSY", "SP0", and "SPMSY" are reserved for future use and currently pass validation but are not implemented.

x

A depletion object for slot accessors, or a stock object for ⁠Depletion<-⁠.

value

For ⁠Depletion<-⁠: a depletion object. For ⁠Initial<-⁠ and ⁠Final<-⁠: a numeric scalar, length-2 bounds vector, or length-nSim vector.

Details

Default Behaviour When Omitted

Depletion is optional. When both Initial and Final are NULL (the default), the object has no effect on model behaviour:

  • The stock is assumed unfished at the start of the historical period.

  • Depletion in the terminal year is determined by the interaction between Stock() and Fleet() parameters; Catchability() must be populated directly in this case.

Initial Depletion

When Initial is supplied, the operating model adjusts early recruitment deviations so that biomass relative to Reference in the first time step matches the target. Values must be in (0, 1]:

# Fixed initial depletion across all simulations
dep <- Depletion(Initial = 0.8)

# Stochastic initial depletion — sampled from Uniform(0.6, 0.9)
dep <- Depletion(Initial = c(0.6, 0.9))

# One value per simulation
dep <- Depletion(Initial = runif(48, 0.6, 0.9))

Final Depletion

When Final is supplied, the operating model optimises Efficiency in Catchability() so that depletion in the terminal historical year matches the target. Any existing Efficiency values are overwritten. When Final is NULL, Efficiency is used as supplied:

# Force terminal depletion to 0.4 relative to B0
dep <- Depletion(Final = 0.4)

# Stochastic terminal depletion
dep <- Depletion(Final = c(0.3, 0.5))

# Both initial and final depletion specified
dep <- Depletion(Initial = 0.9, Final = 0.4)

# Relative to spawning biomass at unfished equilibrium
dep <- Depletion(Final = 0.4, Reference = "SB0")

Pass-Through Access from a Stock

When Initial is a stock object, Depletion() returns the Depletion slot directly:

Depletion(my_stock)             # returns my_stock@Depletion
Depletion(my_stock) <- my_dep   # replaces my_stock@Depletion

Slot Accessors

Individual slots can be read or replaced using generic functions matching their names. All replacement functions re-validate the object:

Initial(dep)   <- 0.8
Final(dep)     <- 0.4

Value

  • Depletion() returns a depletion object. If Initial is a stock, returns x@Depletion.

  • ⁠Depletion<-⁠ returns the stock x with the Depletion slot replaced and the object re-validated.

  • Initial() and Final() return the value of the corresponding slot from x (a nSim-length array after Populate(), or NULL).

  • ⁠Initial<-⁠ and ⁠Final<-⁠ return x with the named slot updated and the object re-validated.

See Also

  • depletion for the class definition and slot-level documentation.

  • Catchability() for the fleet catchability object whose Efficiency parameter is optimised when Final is populated.

  • Populate() for array population.

  • Stock() for the enclosing stock constructor.

Other depletion: depletion-class

Examples

# ---- Default behaviour (Depletion omitted) ----

## When Initial and Final are both NULL (the default), the object has no
## effect: stock starts unfished and terminal depletion is determined by
## the Fleet and Catchability parameters.
dep <- Depletion()
dep

# ---- Initial depletion ----

## Fixed initial depletion — same value for every simulation
dep <- Depletion(Initial = 0.8)

## Stochastic initial depletion — sampled from Uniform(0.6, 0.9)
## once per simulation
dep <- Depletion(Initial = c(0.6, 0.9))

## One value per simulation (nSim = 48)
nSim <- 48
dep  <- Depletion(Initial = runif(nSim, 0.6, 0.9))

# ---- Final depletion ----

## Force terminal-year depletion to 0.4 relative to B0.
## Catchability Efficiency is optimised to achieve this, overwriting any
## existing Efficiency values.
dep <- Depletion(Final = 0.4)

## Stochastic terminal depletion
dep <- Depletion(Final = c(0.3, 0.5))

# ---- Both initial and final ----

dep <- Depletion(Initial = 0.9, Final = 0.4)

# ---- Reference biomass ----

## Default: relative to total unfished biomass (B0)
dep <- Depletion(Final = 0.4, Reference = "B0")

## Relative to spawning biomass at unfished equilibrium (SB0)
dep <- Depletion(Final = 0.4, Reference = "SB0")

## "BMSY", "SBMSY", "SP0", and "SPMSY" pass validation but are reserved
## for future use and not currently implemented.

# ---- Slot accessors ----

dep <- Depletion(Initial = 0.8, Final = 0.4)

## Read slots
Initial(dep)    # 0.8 before Populate(); nSim-length array after
Final(dep)      # 0.4 before Populate(); nSim-length array after

## Replace slots
Initial(dep) <- c(0.7, 0.9)   # now stochastic
Final(dep)   <- 0.3

# ---- Attaching to a Stock ----

stk <- Stock(Name = "Example stock", Ages = Ages(MaxAge = 20))
Depletion(stk) <- Depletion(Initial = c(0.7, 0.8), 
                            Final = c(0.4, 0.6)
)
Depletion(stk)

## Pass-through access
Depletion(stk)           # returns stk@Depletion
Initial(Depletion(stk))  # initial depletion from the stock

# ---- Populate ----

## After Populate(), Initial and Final are nSim-length arrays (or NULL if
## not specified). Population is typically done internally.
pop_dep <- Populate(Depletion(stk), nSim = 48)
Initial(pop_dep)   # 48-element array
Final(pop_dep)     # 48-element array

The depletion S4 Class

Description

Defines the initial and final depletion assumptions for a stock object, expressed relative to a reference biomass. Objects are typically created via Depletion(), which documents all parameters and validates inputs. This object is optional — see Default Behaviour in Depletion() for what happens when it is omitted.

Details

Direct construction via methods::new() is not recommended; use Depletion() instead, which validates inputs.

Both Initial and Final may remain NULL after Populate()NULL indicates the slot is not in use rather than an uninitialised state. When both are NULL, the depletion object has no effect on model behaviour.

Slots

Initial

array or NULL. Depletion relative to Reference in the first historical time step, as a nSim-length array after Populate(). Before population, may be NULL (stock assumed dynamic unfished at the start of the historical period), a scalar, a length-2 bounds vector, or a length-nSim vector. See Depletion() for full details.

Final

array or NULL. Target depletion relative to Reference in the terminal historical time step, as a nSim-length array after Populate(). When populated, the Efficiency parameter in Catchability() is optimised to achieve this depletion level, overwriting any existing Efficiency values. When NULL, no optimisation occurs and Catchability() must be populated directly. See Depletion() for full details.

Reference

character(1). Reference biomass used to scale depletion values. Currently implemented options are "B0" (total unfished biomass, default) and "SB0" (spawning biomass at unfished equilibrium). The options "BMSY", "SBMSY", "SP0", and "SPMSY" are accepted by the validator but are reserved for future use.

Misc

list. Used internally.

See Also

  • Depletion() for the constructor and accessor functions.

  • Catchability() for the fleet catchability object whose Efficiency parameter is optimised when Final is populated.

  • Populate() for array population.

  • Stock() for the enclosing stock constructor.

Other depletion: Depletion()


Department of Fisheries and Oceans stock status bar plot

Description

A plot of biomass relative to BMSY over projected years

Usage

DFO_bar(MSEobj, yres = 10)

Arguments

MSEobj

An MSE object of class MSE produced by DLMtool function runMSE

yres

Integer: the year interval over which to calculate B/BMSY in future years

Author(s)

T. Carruthers


Department of Fisheries and Oceans historical plot

Description

A plot of current and historical stock status by simulation according to the stock status zones and reference points of DFO. http://www.dfo-mpo.gc.ca/reports-rapports/regs/sff-cpd/precaution-eng.htm

Usage

DFO_hist(OM, panel = T, nsim = 48)

Arguments

OM

An operating model object of class OM

panel

should the plots be separate or in two panels?

nsim

how many simulations should be plotted (over-ridden by OM@nsim where cpars is specified)

Author(s)

T. Carruthers


Department of Fisheries and Oceans trade-off plot

Description

A plot of mean biomass relative to BMSY and fishing mortality rate relative to FMSY over the final 5 years of the projection http://www.dfo-mpo.gc.ca/reports-rapports/regs/sff-cpd/precaution-eng.htm

Usage

DFO_plot(MSEobj, zero_origin = T)

Arguments

MSEobj

An MSE object of class MSE produced by MSEtool function runMSE

zero_origin

Logical: should plots have a zero-zero origin?

Author(s)

T. Carruthers


Department of Fisheries and Oceans default plot 2

Description

A preliminary plot for returning trade-offs plots and performance table for probability of obtaining half reference (FMSY) yield and probability of biomass dropping below 50 per cent BMSY

Usage

DFO_plot2(MSEobj, nam = NA, panel = T, Bcut = 50, Ycut = 50)

Arguments

MSEobj

An object of class MSE

nam

Title of plot

panel

Should the plots be organized in many panels in a single figure

Bcut

The cutoff biomass for satisficing (relative to BMSY)

Ycut

the cutoff yield for satisficing (relative to reference yield)

Value

A table of performance metrics.

Author(s)

T. Carruthers


Department of Fisheries and Oceans projection plot

Description

A projection plot of MP performance by simulation according to the stock status zones and reference points of DFO. http://www.dfo-mpo.gc.ca/reports-rapports/regs/sff-cpd/precaution-eng.htm

Usage

DFO_proj(MSEobj, maxplot = 6)

Arguments

MSEobj

An operating model object of class MSE

maxplot

The maximum number of MPs to be plotted per figure

Author(s)

T. Carruthers


Department of Fisheries and Oceans biomass quantile plot

Description

A plot of biomass relative to BMSY quantiles over projected years

Usage

DFO_quant(
  MSEobj,
  maxcol = 6,
  qcol = rgb(0.4, 0.8, 0.95),
  lcol = "dodgerblue4",
  curyr = 2018,
  quants = c(0.05, 0.25, 0.75, 0.95),
  addline = T,
  forreport = T
)

Arguments

MSEobj

An MSE object of class MSE produced by DLMtool function runMSE

maxcol

Integer how many columns for panel plots?

qcol

A color, the quantile coloration

lcol

A color, the mean B/BMSY line

curyr

The current calendar year

quants

A vector 2 long for the quantiles e.g. 0.1 and 0.9 for the 10th and 90th quantiles

addline

Should two individual example simulations be added to the plot?

forreport

Logical. Is it for a report? If true, one plot of six MPs in a row will be provided one after another.

Author(s)

T. Carruthers


Create a standard DFO MSE report

Description

Provides performance plots typical in the assessment of Canadian fish stocks.

Usage

DFO_report(
  MSEobj,
  output_file = NA,
  author = "Author not specified",
  title = NA,
  maxMPs = 15
)

Arguments

MSEobj

An object of class MSE

output_file

The directory and filename you wish to use for the report e.g. "C:/temp/myMSEreport.html"

author

The person who made this report

title

The title of the report

maxMPs

Maximum number of MPs to plot

Author(s)

T. Carruthers


DFO performance spider plot (top three MPs)

Description

DFO performance spider plot (top three MPs)

Usage

DFO_spider(MSEobj)

Arguments

MSEobj

An object of class MSE produced by MSEtool::runMSE()

Author(s)

T. Carruthers


Create a standard DFO performance table

Description

P_Cr_S is the probability of being in the critical zone in the first 10 projected years P_Ct_S is the probability of being in the cautious zone in the first 10 projected years P_H_S is the probability of being in the healthy zone in the first 10 projected years POF_S is the probability of overfishing in the first 10 projected years STY is the mean yield relative to FMSY management over the first 10 projected years P_Cr_L is the probability of being in the critical zone in the last 10 projected years P_Ct_L is the probability of being in the cautious zone in the last 10 projected years P_H_L is the probability of being in the healthy zone in the last 10 projected years POF_L is the probability of overfishing in the last 10 projected years LTY is the mean yield relative to FMSY management over the last 10 projected years AAVY is the average annual variability in yield over the whole projection phrased as a CV percentage P_Reb is the probability the stock has rebuilt to over BMSY in 2 mean generation times

Usage

DFO_tab(MSEobj, maxMPs = 15, rnd = 0)

Arguments

MSEobj

An object of class MSE

maxMPs

Integer: the maximum number of top ranking MPs to include in the table (ranked by long term yield)

rnd

The number of significant figures for rounding.

Author(s)

T. Carruthers


A formatted version of the standard DFO performance plot, color coded by thresholds

Description

Crit_S is the probability of being in the critical zone in the first 10 projected years Caut_S is the probability of being in the cautious zone in the first 10 projected years Health_S is the probability of being in the healthy zone in the first 10 projected years OvFish_S is the probability of overfishing in the first 10 projected years Yield_S is the mean yield relative to FMSY management over the first 10 projected years Crit is the probability of being in the critical zone in the last 10 projected years Caut is the probability of being in the cautious zone in the last 10 projected years Health is the probability of being in the healthy zone in the last 10 projected years OvFish is the probability of overfishing in the last 10 projected years Yield is the mean yield relative to FMSY management over the last 10 projected years AAVY is the average annual variability in yield over the whole projection phrased as a CV percentage Reb is the probability the stock has rebuilt to over BMSY in 2 mean generation times

Usage

DFO_tab_formatted(
  Ptab1,
  thresh = c(30, 50, 40, 60, 50, 20, 40, 50, 60, 50, 30, 50),
  ret_thresh = F
)

Arguments

Ptab1

A DFO performance table made by DFO_tab()

thresh

A vector of thresholds for each column Health, Yield and Reb are 'greater than threshold' conditions

ret_thresh

Logical: if true just the threshold levels are returned

Author(s)

T. Carruthers


Dimensions of an Object

Description

Retrieve or set the dimension of an object.

Usage

dim(x)

Arguments

x

an R object, for example a matrix, array or data frame.

This is a wrapper for base::dim. The only difference is that this function prints the dimension names (if applicable)

Examples

MyArray <- array(1:6,
  dim = c(6, 2),
  dimnames = list(
    Age = 1:6,
    Year = c(2025, 2026)
  )
)
dim(MyArray)

Add or Drop Named Dimensions of an Array

Description

Utilities to add or drop named dimensions from arrays.

Usage

AddDimension(array, name, val = 1, pos = NULL)

DropDimension(array, name, warn = TRUE)

Arguments

array

An array with named dimensions.

name

A single character string naming the dimension to add (AddDimension) or a character vector of dimension names to drop (DropDimension).

val

Value(s) to assign as the dimname of the new dimension in AddDimension. Defaults to 1.

pos

Integer giving the position at which to insert the new dimension in AddDimension. Defaults to the last position.

warn

Logical; if TRUE, warn when dropping a dimension of length > 1.

Details

AddDimension

Adds a new dimension to an array at position pos with the given name and val as its dimname values. If the dimension name already exists, the array is returned unchanged.

DropDimension

Drops one or more named dimensions from an array. All requested dimensions must exist and at least one dimension must remain. Dimensions of length > 1 are sliced at their first index, with an optional warning.

Value

An array with modified dimensions and updated dimnames.

Examples

# ---- Setup Array ----
Arr <- array(1:24, dim = c(2, 3, 4),
               dimnames = list(
                 Sim  = 1:2,
                 Age  = 0:2,
                 Year = 2020:2023
               ))

dim(Arr)

# ---- AddDimension ----

# Append an Area dimension at the end (default pos)
AddDimension(Arr, 'Area') |> dim()

# Append an Area dimension with two values
AddDimension(Arr, 'Area', val = 1:2) |> dim()

# Adding a dimension that already exists returns the array unchanged
AddDimension(Arr, 'Sim') |> dim()

# ---- DropDimension ----

# Drop a length-1 dimension (no warning)
Arr <- array(1:12, dim = c(1, 3, 4),
           dimnames = list(Sim = 1, Age = 0:2, Year = 2020:2023))

DropDimension(Arr, 'Sim')

# Drop a length > 1 dimension (warns by default)
DropDimension(Arr, 'Age')

# Suppress the warning
DropDimension(Arr, 'Age', warn = FALSE)

# Drop multiple dimensions at once
DropDimension(Arr, c('Sim', 'Year'), warn = FALSE)

Discard Mortality

Description

Construct and manipulate a discardmortality object defining the proportion of discarded catch that dies, for use in a Fleet() object. Discard mortality is optional; if not specified, all discarded fish are assumed to survive.

Usage

DiscardMortality(
  MeanAtAge = NULL,
  MeanAtLength = NULL,
  Classes = NULL,
  Misc = list()
)

DiscardMortality(x) <- value

Arguments

MeanAtAge

Numeric, numeric vector, or array, or NULL. Mean discard mortality at age. Values must be between 0 (all discards survive) and 1 (all discards die). Accepted forms:

  • NULL (default): creates an empty discardmortality object. PopulateDiscardMortality() sets discard mortality to 0 for all age and length classes.

  • Scalar: constant mortality applied to all ages. Wrapped internally to a ⁠1 x nAge x 1⁠ array.

  • Numeric vector of length nAge: mortality specified per age class. Wrapped internally to a ⁠1 x nAge x 1⁠ array.

  • Numeric array with dimensions ⁠Sim x Age x Year⁠ and named dimnames.

If MeanAtAge is a fleet object, the DiscardMortality slot of that fleet is returned.

Unlike Selectivity() and Retention(), DiscardMortality does not support model-based population via Pars and Model. Values must be supplied directly as arrays or derived from MeanAtLength.

MeanAtLength

Numeric array or NULL. Mean discard mortality at length with dimensions ⁠Sim x Length x Year⁠. If provided, takes precedence over MeanAtAge; MeanAtAge is derived from it via the age-length key during PopulateDiscardMortality().

Classes

Numeric vector or NULL. Length class midpoints corresponding to the second dimension of MeanAtLength. Default NULL.

Misc

List. Miscellaneous additional inputs. Default list().

x

A discardmortality object, or a fleet object for ⁠DiscardMortality<-⁠.

value

For ⁠DiscardMortality<-⁠: a discardmortality object.

Details

Discard mortality defines the proportion of discarded catch that dies. Fish that are selected but not retained (as defined by Retention()) are treated as discards; DiscardMortality determines how many of those fish die as a result of the capture-and-release process.

Unlike Selectivity() and Retention(), discard mortality does not support model-based population via Pars and Model. Values must be supplied directly as MeanAtAge or MeanAtLength arrays. If neither is supplied, PopulateDiscardMortality() defaults to 0 (all discards survive) for all age and length classes.

Array Format

MeanAtAge may be a scalar, a vector of length nAge, or a full ⁠Sim x Age x Year⁠ array. Scalars and vectors are wrapped internally to arrays with a single simulation and year, then extended to cover all simulations and years during population. If MeanAtLength is supplied, it takes precedence and MeanAtAge is derived from it using the age-length key.

Attaching to a Fleet

A discardmortality object can be attached to a Fleet() with DiscardMortality(Fleet) <- MyDiscardMortality and retrieved with DiscardMortality(Fleet).

Individual slots may be accessed or modified using MeanAtAge(), MeanAtLength(), and Classes().

Value

  • DiscardMortality() returns a discardmortality object. If MeanAtAge is a fleet object, the DiscardMortality slot of that fleet is returned.

  • ⁠DiscardMortality<-⁠ returns x with the DiscardMortality slot replaced by value.

See Also

Other fleet: Bioeconomic(), Catchability(), Effort(), Fleet(), Retention(), Selectivity(), bioeconomic-class, catchability-class, discardmortality-class, effort-class, fleet-class, retention-class, selectivity-class

Examples

# See man-examples/class-DiscardMortality.R

The discardmortality S4 Class

Description

Defines the proportion of discarded catch that dies, at age or at length, for use in a fleet object. Discard mortality is optional; if not specified, all discarded fish are assumed to survive. Objects are typically created via the DiscardMortality() constructor, which documents all parameters in detail.

Slots

MeanAtAge

numeric array or NULL. Mean discard mortality-at-age (⁠Sim x Age x Year x Area⁠). Values between 0 (all discards survive) and 1 (all discards die). See DiscardMortality().

MeanAtLength

numeric array or NULL. Mean discard mortality-at-length (⁠Sim x Length x Year x Area⁠). See DiscardMortality().

Classes

numeric or NULL. Length class midpoints corresponding to the second dimension of MeanAtLength.

Misc

list. Miscellaneous additional inputs. Used internally.

See Also

Other fleet: Bioeconomic(), Catchability(), DiscardMortality(), Effort(), Fleet(), Retention(), Selectivity(), bioeconomic-class, catchability-class, effort-class, fleet-class, retention-class, selectivity-class


Directory of the installed package on your computer

Description

Directory of the installed package on your computer

Usage

DLMDataDir(stock = NA)

Arguments

stock

Character string representing the name of a .csv file e.g. 'Snapper', 'Rockfish'

Value

The file path to the object


Hockey Stick Harvest control rule that modifies TAC.

Description

A hockey stick (2 inflection points) HCR that accepts estimated level relative to reference level and modifies a proposed TAC based on control points for the x axis (est/ref) and y axis (fraction of TAC)

Usage

doHCR(trial_TAC, est, ref, CP = c(0, 1), CPy = c(0, 1))

Arguments

trial_TAC

Postitive real number, the proposed total allowable catch before HCR modification.

est

Positive real number on same scale as ref, the estimated stock level (e.g. mean current index level)

ref

Positive real number on same scale as est, a reference level of stock level (e.g. index level at BMSY)

CP

Vector of real numbers, 2 positions long (c(Lx, Ux)), the lower and upper control points of a hockey stick HCR on the xaxis (est/ref). Below Lx (est/ref < Lx) the TAC is trial_TAC x Ly. Above Ux (est/ref > Ux) the TAC is trial_TAC x Uy. Between the TAC is linearly ramped between these levels.

CPy

Vector of real numbers, 2 positions long (c(Ly, Uy)), the lower and upper control points of a hockey stick HCR on the yaxis (fraction of trial_TAC).

Value

A real number (TAC advice but theoretically could be used for effort, size limits etc).

Author(s)

T. Carruthers


Create indices that are sampled at various frequencies

Description

Given an index (historical period and projected period) this function creates sparsity in the projected index to simulate varying frequency (intensity) of data collection.

Usage

doIfreq(I_hist, I_freq, LHYr, CurYr, Year)

Arguments

I_hist

Vector of real numbers, concatinated observed (historical) and simulated (projected) indices.

I_freq

Positive integer. The frequency of index sampling (e.g. 1 is every year, 2 is every 2 years - a gap every 2 years in the projected, simulated data).

LHYr

Positive integer, a year (e.g. 2023), the last historical year, demarks the historical period where observations have been collected from the projected period where sparsity is to be simulated.

CurYr

Positive integer, a year (e.g. 2043), the most recent year of the simulation.

Year

Vector of positive integers (as long as I_hist), the years corresponding with I_hist.

Value

A thinned ector I_hist long of index observations.

Author(s)

T. Carruthers


Determine dominate MPs

Description

MPs that perform worse than comparable MPs across all performance metrics are considered 'dominated' as other options are always preferable.

Usage

Dom(MSEobj, ..., PMlist = NULL, Refs = NULL, Yrs = NULL)

Arguments

MSEobj

An object of class MSE

...

Names of Performance Metrics (PMs), or other arguments to TradePlot. First PM is recycled if number of PMs is not even

PMlist

Optional list of PM names. Overrides any supplied in ... above

Refs

An optional named list (matching the PM names) with numeric values to override the default Ref values.

Yrs

An optional named list (matching the PM names) with numeric values to override the default Yrs values.

Details

The Dom function compares the probabilities calculated in the performance metric (PM) functions and determines the MPs that have a lower probability across all PMs compared to other MPs of the same management type (e.g., size limit, TAC, etc). Consequently, it is important that all PM functions are constructed so that higher probabilities = better performance (e.g, PNOF is the probability of NOT overfishing)

Value

A named list of length 2 with a character vector of non-dominated MPs in MPs and a data.frame of dominated MPs and the names of the relevant dominated MPs in DomMPs

Author(s)

A. Hordyk

Examples

## Not run: 
MSE <- runMSE(MPs=NA) # run all MPs
Nondom <- Dom(MSE, "P10", "LTY", "PNOF")
# Non-dominated MPs
Nondom$MPs

# Dominated MPs
Nondom$DomMPs


## End(Not run)

Dome-Shaped Selectivity Example Fleet

Description

An example fleet object demonstrating a fleet with increasing historical effort and dome-shaped length-based selectivity. Intended for use with AlbacoreExStock or ButterfishExStock to illustrate fleet parameterization.

Usage

DomeExFleet

Format

A fleet object with the following slots populated:

  • Name: "DomeExFleet". Unique fleet identifier.

  • Effort: An Effort() object with a piecewise-linear historical effort trajectory defined at four relative time points (0, 0.3, 0.6, 1.0), with lower and upper bounds of (0, 0.4, 0.4, 1) and (0, 0.6, 0.6, 1) respectively, and CV = 0.1 controlling stochastic variation around the trend.

  • Selectivity: A Selectivity() object with dome-shaped length-based selectivity parameters — L5 (0.2–0.4), LFS (0.75–1.1), and Vmaxlen (0.5–1.0) — with isRel = TRUE indicating that L5 and LFS are expressed relative to maturity L50.

  • Catchability: An empty Catchability() object; efficiency defaults to 1 across all years during population (see Details).

  • Retention: An empty Retention() object; full retention is assumed during population (see Details).

  • DiscardMortality: An empty DiscardMortality() object. Discard mortality is assumed to be 0.

  • Closure: NULL. No spatial or temporal closures defined.

  • WeightFleet: NA. Fleet-specific weight-at-age is set to the stock weight-at-age during population (see Details).

  • Bioeconomic: An empty Bioeconomic() object.

  • nYear, pYear, nSim, CurrentYear, Years, Seasons: Inherited from the paired Stock() object by PopulateFleet().

  • Misc: Empty list for user-defined information.

Details

PopulateFleet() expands the input parameters into ⁠[nSim x nAge x nYear]⁠ arrays using the age, length, and spatial structure of the paired populated stock object. The sections below describe what each component-level ⁠Populate*()⁠ function produces.

Effort

PopulateEffort() interpolates the piecewise-linear effort trajectory across all historical years for each simulation, then applies log-normal stochastic deviates scaled by CV = 0.1. The trajectory rises from 0 to a plateau at 40–60% of maximum effort around 30–60% of the historical period, then increases to full effort by the final historical year.

Catchability

Because the Catchability slot is empty, PopulateCatchability() sets catchability efficiency to 1 across all simulations and years. No trend (qInc) or inter-annual variability (qCV) is applied.

Selectivity

PopulateSelectivity() samples L5, LFS, and Vmaxlen for each simulation from uniform distributions defined by the prior bounds. Because isRel = TRUE, L5 and LFS are scaled by the maturity L50 of the paired stock before computing the selectivity curve. The resulting dome-shaped selectivity-at-length is converted to selectivity-at-age using the stock age–length key, and an area dimension is added. The Vmaxlen range (0.5–1.0) allows selectivity at maximum length to vary from strongly dome-shaped to asymptotic across simulations.

Retention

Because the Retention slot is empty, PopulateRetention() sets full retention (1.0) across all ages, lengths, simulations, and years.

Discard Mortality

Because the DiscardMortality slot is empty, PopulateDiscardMortality() applies default discard mortality values. All discarded fish are assumed to survive (discard mortality = 0) unless overridden.

Spatial Closures

Because Closure is NULL, PopulateClosure() applies no spatial or temporal closures; all areas are open to fishing in all years.

Fleet Weight-at-Age

Because WeightFleet is NA, PopulateFleet() sets it equal to the stock mean weight-at-age array, so fleet-level biomass calculations use the same weight schedule as the stock.

See Also

AlbacoreExStock, ButterfishExStock, Fleet(), PopulateFleet(), Populate(), fleet

Examples

DomeExFleet

## Not run: 
PopulatedStock <- PopulateStock(AlbacoreExStock, nYear = 50, pYear = 30, nSim = 48)
PopulatedFleet <- PopulateFleet(DomeExFleet, Stock = PopulatedStock, seed = 42)

## End(Not run)

Calculate a management recommendation given constraints

Description

Creates a TAC management recommendation given constraints on how much that can change from previous TAC and contraints on minimum and maximum TAC

Usage

doRec(MPrec, mod, delta_down, delta_up, TACrng)

Arguments

MPrec

Positive real number, the previous management recommendation (e.g. 100 tonnes).

mod

Imperfect fraction, the proposed modification (change to MPrec) (e.g. 1.2 is a 20% increase)

delta_down

A vector 2 positions long, the minimum and maximum levels of downward change (e.g. when mod < 1) in the recommendation.

delta_up

A vector 2 positions long, the minimum and maximum levels of upward change (e.g. when mod > 1) in the recommendation.

TACrng

A vector 2 positions long, the minimum and maximum TAC (same units as MPrec).

Value

n object of class Rec.

Author(s)

T. Carruthers


Effort Constructor and Accessors

Description

Construct and manipulate an effort object defining historical fishing effort and spatial structure for a Fleet() object.

Usage

Effort(
  Effort = NULL,
  Units = NULL,
  Distribution = NULL,
  Targeting = NULL,
  Maximum = NULL,
  Mode = NULL,
  TripsScalar = NULL,
  AnglerPerTrip = NULL,
  Misc = list(),
  df = TRUE
)

Effort(x) <- value

Distribution(x)

Distribution(x) <- value

Targeting(x)

Targeting(x) <- value

Maximum(x)

Maximum(x) <- value

Mode(x)

Mode(x) <- value

TripsScalar(x)

TripsScalar(x) <- value

AnglerPerTrip(x)

AnglerPerTrip(x) <- value

Arguments

Effort

Numeric array, data frame, or NULL. Historical fishing effort. Accepted forms:

  • NULL (default): creates an empty effort object; no effort is populated by PopulateEffort().

  • Numeric array with dimensions ⁠Sim x Year⁠ and named dimnames. The Year dimension must match the historical years of the OM.

  • Data frame in the format required by GenHistEffort(); a stochastic ⁠Sim x Year⁠ array is generated automatically during population.

If Effort is a fleet, effort, hist, obs, or mse object, the Effort slot of that object is extracted and returned (see Details).

Units

Character or NULL. Units of fishing effort (e.g., "hours", "trips"). Default NULL. Note that effort is converted to fishing mortality via gear efficiency (q) defined in the associated catchability object. When Units = "trips" the effort array is already on the absolute trips scale and TripsScalar is ignored by bag-limit management procedures.

Distribution

Numeric array or NULL. Fraction of total effort allocated to each spatial area. Used only for spatial models (nArea > 1). Must have dimensions ⁠Sim x Year x Area⁠ with named dimnames, and values must sum to 1 over the Area dimension within each simulation and year. The Sim and Year dimensions may each be length 1 (replicated internally) or match nSim and the historical years respectively. Default NULL; if not specified, PopulateEffort() initialises all cells to NA and the internal spatial allocation algorithm fills them (see Details). Any cells set to a non-NA numeric value are treated as fixed overrides and are not modified by the algorithm.

Targeting

Numeric array or NULL. Spatial targeting concentration parameter (lambda >= 0) with dimensions ⁠Sim x Year⁠. The Sim dimension may be length 1 or match nSim. The Year dimension must be length 1, match the historical years, or have named Year dimnames. Default NULL; a value of 0.8 is applied to all simulations and years during PopulateEffort(). See Details for how this parameter controls the concentration of effort across areas.

Maximum

Numeric array or NULL. Maximum allowable effort. Default NULL. Not currently used.

Mode

Character or NULL. Controls whether spatial utility is calculated per unit area or as raw biomass. "Density" (default) divides exploitable biomass by the relative area size (RelSize) before computing utility, so fleets are attracted to areas with high biomass concentration regardless of area size. "Biomass" uses raw exploitable biomass, so larger areas are intrinsically more attractive. See the Technical Manual for equations.

TripsScalar

Numeric array or NULL. Time-varying scalar αf(t)\alpha_f(t) converting the effort index to absolute angler trip counts via Tf(t)=αf(t)Ef(t)T_f(t) = \alpha_f(t) \cdot E_f(t). Must have dimensions ⁠Sim x Year⁠ with named dimnames. The Sim dimension may be length 1 (replicated internally). The Year dimension may be length 1 (replicated internally) or span the full model time series; values for projection years beyond the historical period are typically held constant at the last historical value or extended by the analyst prior to use. Default NULL. Required by bag-limit management procedures when Units != "trips". Ignored when Units = "trips". See Details.

AnglerPerTrip

Numeric array or NULL. Mean number of anglers per trip. Must have dimensions ⁠Sim x Year⁠ with named dimnames. The Sim dimension may be length 1 (replicated internally). The Year dimension may be length 1 (replicated internally) if the value does not vary over time, or span the full model time series if it does. Used by bag-limit management procedures to scale a per-angler bag limit to a fleet-level retention cap. Default NULL. See Details.

Misc

List. Miscellaneous additional inputs. Default list().

df

Logical. Only used when Effort is a hist or mse object. If TRUE (default), a tidy data.frame is returned. If FALSE, the raw Effort array is returned.

x

An effort object for accessor and replacement functions.

value

The replacement value for the corresponding slot.

Details

An effort object defines total fleet fishing activity prior to spatial allocation. Effort is converted to fishing mortality via gear efficiency (q) in the associated catchability object.

Effort Array Format

When supplied as a numeric array, Effort must have dimensions ⁠Sim x Year⁠ with named dimnames. The Sim dimension may be length 1 (replicated internally by PopulateEffort()). The Year dimension must match the historical years of the OM exactly.

When supplied as a data frame, the format must meet the requirements of GenHistEffort(), which generates a stochastic ⁠Sim x Year⁠ array during population. The Units slot is set to "unitless" automatically in this case.

Spatial Distribution

Distribution is only used for spatial models (nArea > 1). It must sum to 1 over the Area dimension within each simulation and year. The Sim and Year dimensions may be length 1 (replicated internally). When not specified (default), PopulateEffort() initialises all cells to NA.

In Simulate() and Project(), the spatial allocation algorithm only fills cells that remain NA; any non-NA values supplied in Distribution are left unchanged and act as fixed overrides for those simulation-year-area combinations.

Spatial Utility and Effort Allocation

When Distribution cells are NA, effort allocation across areas is determined internally at each timestep by a two-stage algorithm:

Stage 1 — Exploitable biomass. For each fleet and area, raw exploitable biomass is computed as the sum over ages of abundance × weight × selectivity × retention, scaled by catchability (q). When Mode = "Density" (default), this biomass is divided by the relative area size (RelSize) to give biomass density; when Mode = "Biomass", raw biomass is used.

Stage 2 — Depletion-adjusted utility. A depletion discount h(phi) = (1 - exp(-phi)) / phi is applied, where phi is the local fishing pressure (own-fleet effort × q × D0 in the area, plus a one-timestep-lagged contribution from competing fleets). This discounts utility in heavily fished areas, approximating an ideal free distribution under depletion.

Stage 3 — Softmax targeting. The depletion-adjusted utilities are normalised and passed through a softmax function with concentration parameter lambda (Targeting). The resulting probabilities are written to Distribution.

Targeting

Targeting (lambda) is a non-negative concentration parameter controlling how strongly effort is concentrated in high-utility areas. At lambda = 0, effort is distributed uniformly across all accessible areas regardless of their relative utility. As lambda increases, effort becomes progressively more concentrated in the highest-utility area. The default value of 0.8 produces moderate concentration, broadly consistent with opportunistic targeting behaviour where fleets favour productive areas but do not exclusively fish the single best one.

Values around 0.5 approach near-uniform allocation; values above 23 produce strongly directed behaviour where most effort concentrates in the top one or two areas. The parameter is open-ended with no fixed upper bound, but very large values (e.g. ⁠> 5⁠) effectively collapse all effort to the single highest-utility area in most configurations.

Effort-to-Trips Conversion and Angler Scaling

Bag-limit management procedures require the effort index to be expressed as absolute angler trip counts. When Units = "trips" the effort array is already on the trips scale and no conversion is needed.

When the bag limit is defined per angler (the default), AnglerPerTrip provides the mean number of anglers per trip Af(t)A_f(t), such that the fleet-level retention cap is:

Cfbag(t)=BfAf(t)Tf(t)C^{\text{bag}}_f(t) = B_f \cdot A_f(t) \cdot T_f(t)

where BfB_f is the bag limit in fish per angler per trip. The Year dimension of AnglerPerTrip may be length 1 if the value is assumed constant over time; it is replicated internally to match the full model time series.

When the bag limit is defined per vessel (boat limit), AnglerPerTrip is not used.

Pass-Through Extraction

When Effort is a fleet, effort, hist, obs, or mse object, Effort() returns the Effort slot of that object rather than constructing a new one. For hist and mse objects, the df argument controls whether a tidy data.frame (TRUE) or the raw array (FALSE) is returned.

Attaching to a Fleet

An effort object can be attached to a Fleet() with Effort(Fleet) <- MyEffort and retrieved with Effort(Fleet).

Value

  • Effort() returns an effort object. If Effort is a fleet, effort, hist, obs, or mse object, the Effort slot of that object is returned (as a data.frame or array for hist and mse depending on df).

  • ⁠Effort<-⁠ returns x with the Effort slot replaced by value.

  • Distribution(), Targeting(), Maximum(), Mode(), TripsScalar(), AnglerPerTrip() return the corresponding slot from the effort object x.

  • Their replacement forms return x with the corresponding slot updated.

See Also

  • effort for the class definition and slot-level documentation.

  • Fleet() for the enclosing fleet constructor.

  • GenHistEffort() for the data frame format used to generate stochastic historical effort.

  • Catchability() for the gear efficiency that converts effort to fishing mortality.

  • PopulateEffort() for how effort, distribution, and targeting arrays are expanded across simulations and years.

Other fleet: Bioeconomic(), Catchability(), DiscardMortality(), Fleet(), Retention(), Selectivity(), bioeconomic-class, catchability-class, discardmortality-class, effort-class, fleet-class, retention-class, selectivity-class

Examples

## ---- Empty Effort object ----
# An empty Effort object is created by default when constructing a Fleet.
e <- Effort()
e

## ---- Effort from a pre-specified array ----
# A Sim x Year numeric array can be supplied directly.
# Year dimnames must match the historical years of the OM.
hist_years <- 2000:2024
nSim <- 48

effort_array <- array(
  seq(0.2, 1, length.out = length(hist_years)),
  dim = c(1, length(hist_years)),
  dimnames = list(Sim = 1, Year = hist_years)
)

e_array <- Effort(Effort = effort_array, Units = "hours")

e_array_pop <- Populate(
  e_array,
  HistYears = hist_years,
  nSim      = nSim,
  nArea     = 3,
  seed      = 42
)
e_array_pop

Effort(e_array_pop)

## ---- Effort from a data frame (stochastic) ----
# A data frame of control points can be supplied to generate a stochastic
# Sim x Year effort array via GenHistEffort(). Effort is sampled uniformly
# between Lower and Upper at each control year, linearly interpolated to
# annual resolution, perturbed by lognormal process error (CV), and
# normalised to 1 in the terminal year.
effort_df <- data.frame(
  Year  = c(2000, 2008, 2016, 2024),
  Lower = c(0,    0.3,  0.7,  1),
  Upper = c(0,    0.5,  0.9,  1),
  CV    = c(0.1,  0.1,  0.1,  0.1)
)

e_df <- Effort(Effort = effort_df, Units = "hours")

e_df_pop <- Populate(
  e_df,
  HistYears = hist_years,
  nSim      = nSim,
  seed      = 42
)
e_df_pop

Effort(e_df_pop) |> head()


## ---- Spatial distribution across 3 areas ----
# Distribution must have dimensions Sim x Year x Area and sum to 1
# over the Area dimension. Here effort is fixed: 50% in area 1,
# 30% in area 2, and 20% in area 3 across all simulations and years.
# Supplying non-NA values fixes those cells; the internal allocation
# algorithm only fills NA cells.
dist_array <- array(
  c(0.5, 0.3, 0.2),
  dim      = c(1, 1, 3),
  dimnames = list(Sim = 1, Year = hist_years[1], Area = 1:3)
)

e_dist <- Effort(
  Effort       = effort_df,
  Distribution = dist_array,
  Units        = "hours"
)

e_dist_pop <- Populate(
  e_dist,
  HistYears = hist_years,
  nSim      = nSim,
  nArea     = 3,
  seed      = 42
)
Distribution(e_dist_pop)

## ---- Targeting: concentration of effort across areas ----
# Targeting (lambda) controls how strongly effort concentrates in
# high-utility areas via a softmax function.
# lambda = 0  : uniform distribution across accessible areas
# lambda = 0.8: moderate concentration (default)
# lambda = 3  : strongly directed effort toward highest-utility area

# Low targeting -- near-uniform allocation
e_low <- Effort(
  Effort    = effort_df,
  Targeting = array(0, dim = c(1, 1), dimnames = list(Sim = 1, Year = hist_years[1]))
)


# High targeting -- concentrated effort
e_high <- Effort(
  Effort    = effort_df,
  Targeting = array(3, dim = c(1, 1), dimnames = list(Sim = 1, Year = hist_years[1]))
)

## ---- Mode: Density vs Biomass ----
# Mode = "Density" (default) divides exploitable biomass by relative area
# size before computing utility, attracting fleets to high-concentration
# areas regardless of area size.
# Mode = "Biomass" uses raw exploitable biomass, making larger areas
# intrinsically more attractive.

e_density <- Effort(Effort = effort_df, Mode = "Density")
e_biomass <- Effort(Effort = effort_df, Mode = "Biomass")

## ---- Accessor and replacement functions ----
e <- Effort(Effort = effort_df, Units = "hours")

Mode(e)
Units(e)
Targeting(e)
Distribution(e)
Maximum(e)

# Modify individual slots
Mode(e) <- "Biomass"
Mode(e)

## ---- Extracting Effort from a Fleet object ----
f <- Fleet(Name = "Trawl", Effort = e)
Effort(f)

The effort S4 Class

Description

Defines historical fishing effort and associated spatial structure for use in a fleet object. Objects are typically created via the Effort() constructor, which documents all parameters in detail.

Slots

Effort

numeric array, data frame, or NULL. Historical fishing effort. See Effort() for accepted formats.

Units

character or NULL. Units of fishing effort (e.g., "hours", "trips"). When Units = "trips" the effort array is already on the absolute trips scale and TripsScalar() is ignored by bag-limit management procedures. See Effort().

Distribution

numeric array or NULL. Fraction of total effort allocated to each spatial area (⁠Sim x Year x Area⁠). See Effort().

Targeting

numeric array or NULL. Fleet targeting concentration parameter (⁠Sim x Year⁠). See Effort().

Maximum

numeric array or NULL. Maximum allowable effort. See Effort().

Mode

character or NULL. Spatial utility calculation mode: "Density" (default) or "Biomass". See Effort().

TripsScalar

numeric array or NULL. Time-varying scalar αf(t)\alpha_f(t) converting the effort index to absolute angler trip counts via Tf(t)=αf(t)Ef(t)T_f(t) = \alpha_f(t) \cdot E_f(t) (⁠Sim x Year⁠). The Year dimension may be length 1 (replicated internally) or span the full model time series. Required by bag-limit management procedures when Units != "trips". Ignored when Units = "trips". See Effort().

AnglerPerTrip

numeric array or NULL. Mean number of anglers per trip (⁠Sim x Year⁠). Used by bag-limit management procedures to convert a per-angler bag limit to a fleet-level retention cap via Cfbag(t)=BfAf(t)Tf(t)C^{\text{bag}}_f(t) = B_f \cdot A_f(t) \cdot T_f(t), where BfB_f is the bag limit (fish per angler per trip) and Tf(t)T_f(t) is the number of trips. See Effort().

Misc

list. Miscellaneous additional inputs.

See Also

Effort() for the constructor and full parameter documentation. fleet for the enclosing fleet object.

Other fleet: Bioeconomic(), Catchability(), DiscardMortality(), Effort(), Fleet(), Retention(), Selectivity(), bioeconomic-class, catchability-class, discardmortality-class, fleet-class, retention-class, selectivity-class


EffortData Constructor and Accessors

Description

Construct an effortdata object storing observed fishing effort and uncertainty, or access and replace individual slots.

Usage

EffortData(Name = NULL, Value = NULL, CV = NULL, Units = NULL)

Arguments

Name

character or NULL. Name of the dataset. Default NULL.

Value

array or NULL. Observed effort values with dimensions ⁠[nYear x nFleet]⁠. Default NULL.

CV

array or NULL. Coefficients of variation for the effort observations, matching the dimensions of Value. Default NULL.

Units

character or NULL. Units of effort measurement, one element per fleet (e.g., "days", "trips", "unitless"). Default NULL.

Details

Usage

EffortData() is the standard constructor. All arguments are optional; an empty object is valid and slots are populated later (e.g., by GenHistData_Effort()).

Attaching to a Data Object

Effort(data) <- EffortData(Value = myArray, CV = myCVArray)

Value

  • EffortData() returns an effortdata object.

  • Effort() returns the Effort slot from a data object x.

  • ⁠Effort<-⁠ returns x with the Effort slot replaced.

See Also

Other data: CatchData(), CompData(), catchdata-class, compdata-class, effortdata-class

Examples

# Empty object
ed <- EffortData()

# With values
yrs <- 2000:2020
nFleet <- 2
val <- array(runif(length(yrs) * nFleet),
             dim = c(length(yrs), nFleet),
             dimnames = list(Year = yrs, Fleet = c("Trawl", "Longline")))
ed <- EffortData(Value = val,
                 CV    = array(0.2, dim = dim(val), dimnames = dimnames(val)),
                 Units = c("hours", "hooks"))

The effortdata S4 Class

Description

Stores time series observations of fishing effort and associated uncertainty. Used in the Effort slot of a data object. Objects are typically created via EffortData(), which documents all parameters in detail.

Slots

Name

character or NULL. Names of the fleets

Value

array or NULL. Observed effort values with dimensions ⁠[nYear x nFleet]⁠. See EffortData().

CV

array or NULL. Coefficients of variation matching the dimensions of Value. See EffortData().

Units

character or NULL. Units of effort measurement per fleet (e.g., "days", "trips", "unitless"). See EffortData().

See Also

EffortData() for the constructor and full parameter documentation. data for the enclosing data object.

Other data: CatchData(), CompData(), EffortData(), catchdata-class, compdata-class


EffortObs Constructor and Accessors

Description

Construct an effortobs object defining observation error for fishing effort data, or access and replace individual slots.

Usage

EffortObs(
  CV = NULL,
  Bias = NULL,
  Error = NULL,
  Years = NULL,
  Units = NULL,
  Ref = NULL,
  Misc = list()
)

Arguments

CV

numeric or NULL. Coefficient of variation of the lognormal effort observation error. Accepted forms:

  • NULL (default): no observation error is generated unless Error is supplied directly.

  • Length-1 scalar: a single CV applied uniformly across all simulations and years when generating the Error array internally.

  • Length-2 vector c(mean, sd): CV is itself drawn stochastically — a unique CV per simulation is generated via StructurePars() before being used to generate the Error array.

  • Length-nSim named array: used directly, one CV per simulation.

Bias

numeric or NULL. Multiplicative observation bias. Accepted forms:

  • NULL (default): bias defaults to 1 (unbiased) internally.

  • Positive scalar: interpreted as the CV of a lognormal distribution; a unique bias is drawn per simulation as rlnorm(nSim, mconv(1, Bias), sdconv(1, Bias)).

  • Length-nSim vector or named array: used directly, one bias per simulation.

Error

numeric array or NULL. Pre-specified lognormal observation error multipliers with dimensions ⁠nSim x nYear⁠ and named dimnames (Sim, Year). When supplied, Error is used directly and CV is ignored for error generation. Default NULL, in which case Error is generated from CV internally.

Years

numeric vector or NULL. Calendar years over which the observation error applies. Default NULL (all historical years).

Units

character(1) or NULL. Units of effort (e.g., "hours", "trips", "unitless"). Default NULL.

Ref

numeric or NULL. Reference effort value. Accepted forms:

  • NULL (default): no reference value.

  • Positive scalar: interpreted as the CV of a lognormal distribution; a unique reference value is drawn per simulation as rlnorm(nSim, mconv(1, Ref), sdconv(1, Ref)) internally.

  • Length-nSim vector or named array: used directly.

Misc

list. Miscellaneous additional objects. Default list().

Details

Observation Error Generation

The error applied to simulated effort is Bias[sim] * Error[sim, year]. The Error array (⁠nSim x nYear⁠) is obtained in one of two ways, in order of precedence:

  1. User-supplied Error: stored directly; CV is not used.

  2. Stochastic from CV: if Error is NULL and CV is specified, Internally the model generates a lognormal array where each cell is rlnorm(1, mconv(1, CV[sim]), sdconv(1, CV[sim])). CV is first expanded to length nSim internally — a length-2 input triggers a stochastic draw of a unique CV per simulation.

Note: Effort observation error is not currently conditioned from observed data.

Bias is expanded internally: a scalar input is treated as the CV of a lognormal from which one bias per simulation is drawn; a length-nSim input is used directly.

Ref is expanded internally using the same convention as Bias.

Unlike catch and index observation error, effort observation error is not conditioned on real data; the user-supplied CV, Bias, and Error are always used as specified.

Attaching to an Obs Object

Effort(obs) <- EffortObs(CV = 0.15)

Value

  • EffortObs() returns an effortobs object.

  • Effort() (accessor) returns the Effort slot from object x.

  • ⁠Effort<-⁠ returns x with the Effort slot replaced.

  • CV(), Bias(), Units(), Years(), Ref() return the corresponding slot from an effortobs object x.

  • Their replacement forms return x with the corresponding slot updated.

See Also

  • effortobs for the class definition.

  • Obs() for the enclosing observation model constructor.

Other obs: CatchObs(), CompObs(), ExploitationObs(), IndicesObs(), LifeHistoryObs(), Obs(), catchobs-class, compobs-class, effortobs-class, exploitationobs-class, indicesobs-class, lifehistoryobs-class, obs-class

Examples

# Uniform 15% CV
eo <- EffortObs(CV = 0.15)

# Stochastic CV — unique CV per simulation drawn from lognormal(mean=0.15, sd=0.03)
eo <- EffortObs(CV = c(0.15, 0.03))

# Bias as a CV — unique bias per simulation
eo <- EffortObs(CV = 0.15, Bias = 0.05)

# Attach to obs
obs <- Obs(Effort = EffortObs(CV = 0.15))

The effortobs S4 Class

Description

Defines the observation error structure for fishing effort data. Used in the Effort slot of an obs object. Objects are typically created via EffortObs(), which documents all parameters in detail.

Slots

CV

numeric or NULL. Coefficient of variation of effort observation error. See EffortObs().

Error

numeric array or NULL. Realised lognormal observation error multipliers (⁠nSim x nYear⁠). Populated internally during simulation; see EffortObs().

Bias

numeric or NULL. Multiplicative observation bias. See EffortObs().

Years

numeric or NULL. Calendar years over which the observation error applies. See EffortObs().

Units

character or NULL. Units of fishing effort (e.g., "hours", "trips"). See EffortObs().

Ref

numeric array or NULL. Reference effort values, one per simulation. See EffortObs().

Misc

list. Miscellaneous additional objects.

See Also

EffortObs() for the constructor and full parameter documentation. obs for the enclosing observation model object.

Other obs: CatchObs(), CompObs(), EffortObs(), ExploitationObs(), IndicesObs(), LifeHistoryObs(), Obs(), catchobs-class, compobs-class, exploitationobs-class, indicesobs-class, lifehistoryobs-class, obs-class


A flexible empirical management procedure.

Description

An all-purpose empirical MP that runs of Indices of relative abundance

Usage

Emp(
  x,
  Data,
  reps = 1,
  Inds = NA,
  I_freq = NA,
  I_wt = NA,
  calib_yrs = 2,
  enp_mult = 0.3,
  Ind_fac = NA,
  TACrng = NA,
  delta_down = c(0.01, 0.5),
  delta_up = c(0.01, 0.5),
  resp = 1,
  curI_2_target = NA,
  HCR_CP_B = c(0, 0),
  HCR_CP_TAC = c(0, 1),
  Mode = 1
)

Arguments

x

Positive integer, the simulation number (a position in data object Data)

Data

An object of class 'Data' containing all fishery data (simulated or real - real has only one 'simulation')

reps

Positive integer, the number of stochastic samples of management advice (not applicable here)

Inds

Vector of positive integers. The indices (dimension 2) of the Additional Indices Data@AddInd to be used in calculation. When this is NA, the single index Data@Ind is used

I_freq

Vector of positive integers. Same length as Inds - how frequently will each index be available. 1 is every year, 2 is every 2 years, etc.

I_wt

Vector of positive real numbers. Same lengtt as Inds - the weighting of each index in the calculation of mean index level.

calib_yrs

Positive integer. The number of recent historical years used to calculate the 'current' Catch per Index value (more or less a nuisance parameter)

enp_mult

Fraction. The degree of smoothing for the polynomial function of indices. Larger numbers mean more smoothing. This is effective number of parameters. 0.3 means that the number of parameters in the polynomial smoother is 30% the length of the index.

Ind_fac

Positive real number. The factor (multiplier) of current catch(calib_yrs) / index(calib_yrs) to fish at in the future. A value of 2 means that per index the catches will be twice as high as today. If NA, the fraction of defaults to perfectly known mean((0.75 * FMSY)/last_historical_F) - mean over simulations.

TACrng

Vector 2 positions long, the minimum and maximum allowable catches. If NA this defaults to c(0, max_historical_catch*100) - essentially no TAC limit.

delta_down

Vector 2 positions long, the minimum and maximum allowable fractional downward change in TAC among management cycles.

delta_up

Vector 2 positions long, the minimum and maximum allowable fractional upward change in TAC among management cycles.

resp

Positive real number, the responsiveness of the TAC change algorithm. TAC_change = exp(log(new_TAC/old_TAC)*resp). Lower values linearly reduce the logspace TAC response and make smaller adjustements as proposed TAC changes are larger).

curI_2_target

Positive real number, the current (most recent historical year) index relative that at the target biomass level. If NA this defaults to perfectly known mean(last_historical_biomass / (1.25 * BMSY)), mean over all simulations.

HCR_CP_B

Vector of positive real numbers. Biomass control points of an HCR. These are the x-axis locations of the hockey stick inflection points. c(0,1) means a linear ramp from I/I_target. c(0.5,1) means no fishing til half I_target then a linear ramp in fishing to I_target. c(0,0) means no HCR.

HCR_CP_TAC

Vector of positive real numbers. Response control points of an HCR. These are the y-levels corresponding with the hockey stick. These are the minimum and maximum modifiers applied to the TAC recommendation.

Mode

Integer. What type of index-based MP is used? 1 = Index rate, aims to fish at a rate of index (ie TAC = f(I, current_C / current_I, Ind_fac, HCR_CP_B, HCR_CP_TAC)), 2 = Index target, makes incremental TAC adjustments based on I/I_target (i.e. TAC = f(I, curI_2_target, ))

Value

An object of class MP.

Author(s)

T. Carruthers


Test Whether an Object is Empty

Description

Returns TRUE if an object contains no user-supplied information — i.e. it is either a freshly constructed default object or all of its slots are NULL, zero-length, or entirely NA.

Usage

EmptyObject(object)

Arguments

object

An S4 object, or any R object.

For S4 objects, EmptyObject() first checks whether the object is identical to a freshly constructed default of the same class via isNewObject(). If so, it returns TRUE immediately.

Otherwise it inspects every slot recursively:

  • Slots containing functions are skipped.

  • Slots containing nested S4 objects are tested recursively via EmptyObject().

  • All other slots are considered empty if they are NULL, zero-length, or entirely NA.

EmptyObject() returns TRUE only when every slot passes the emptiness check. A single non-empty slot causes the object to be considered non-empty.

For non-S4 objects, EmptyObject() returns TRUE if the object has length zero or consists entirely of NA values.

EmptyObject() is used throughout the ⁠Populate*()⁠ functions as an early exit guard: if an object is empty, population is skipped and the object is returned unchanged.

Value

A length-1 logical.

See Also

isNewObject()

Examples

# A freshly constructed object is empty
EmptyObject(CompObs())

# An object with any slot filled is not empty
EmptyObject(CompObs(SampleSize = 200))

# Non-S4 objects
EmptyObject(NULL)
EmptyObject(numeric(0))
EmptyObject(c(NA, NA))

The equilibrium S4 Class

Description

An S4 class storing absolute-scale equilibrium quantities evaluated across a vector of apical fishing mortality values, accounting for the stock-recruitment relationship. Produced by CalcEquilibrium().

Details

Scaling from per-recruit to absolute

All F-dependent slots are obtained by multiplying the corresponding per-recruit quantity from a perrecruit object by equilibrium recruitment:

Recruitss,F=R0,sϕ(SPRs,F)\texttt{Recruits}_{s,F} = R_{0,s} \cdot \phi(\texttt{SPR}_{s,F})

where ϕ\phi is the relative recruitment function from the stock's SRR() and R0,sR_{0,s} is unfished recruitment. Values of RelRecruits below zero are floored at zero before scaling.

Complexes

When stocks belong to the same complex they share a single apical F, and SPR for each stock is computed relative to that complex-level F. The RelRecruits scaling is still applied per stock.

Slots

apicalF

Numeric vector of apical fishing mortality values at which equilibrium quantities were evaluated. Length nF.

SPR0

Spawning-per-recruit at unfished conditions. Array (⁠Sim × Stock × Year⁠).

SPR

Spawning-per-recruit relative to unfished, i.e. SPRF / SPR0. Array (⁠Sim × Stock × Year × F⁠).

RelRecruits

Relative recruitment from the stock-recruitment relationship, evaluated at each SPR value. Array (⁠Sim × Stock × Year × F⁠).

Recruits

Absolute equilibrium recruitment (⁠R0 × RelRecruits⁠). Array (⁠Sim × Stock × Year × F⁠).

Number

Absolute equilibrium numbers-at-age (⁠NPRF × Recruits⁠), summed over the age dimension. Array (⁠Sim × Stock × Year × F⁠).

Biomass

Absolute equilibrium total biomass. Array (⁠Sim × Stock × Year × F⁠).

SBiomass

Absolute equilibrium spawning biomass. Array (⁠Sim × Stock × Year × F⁠).

SProduction

Absolute equilibrium spawning production, computed from fecundity-at-age rather than weight × maturity. Array (⁠Sim × Stock × Year × F⁠).

Removals

Absolute equilibrium total removals (landings + dead discards), summed over fleets. Array (⁠Sim × Stock × Year × F⁠).

Landings

Absolute equilibrium landings, summed over fleets. Array (⁠Sim × Stock × Year × F⁠).

Misc

List reserved for internal use.

See Also

CalcEquilibrium(), perrecruit


Example Management Procedures

Description

Simple management procedures (MPs) designed for testing and demonstration. Each MP function accepts a data object and returns an advice object. MPs are assigned ⁠class "mp"⁠ so they are recognised by the MSE framework.

Usage

CurrentEffort(Data)

CurrentCatch(Data)

CurrentLandings(Data)

AverageCatch(Data)

ExampleMPs()

Arguments

Data

A data object containing historical observations.

Details

  • CurrentEffort: Fixes fishing effort at 1 (last historical effort) for all fleets, maintaining the spatial distribution of effort from the last historical timestep. The Data argument is accepted for framework compatibility but is not used.

  • CurrentCatch: Sets the TAC for each fleet to the removals observed in the last historical year. Returns an empty advice object if no landings data are available.

  • CurrentLandings: Sets the TAC for each fleet to the landings observed in the last historical year. Returns an empty advice object if no landings data are available.

  • AverageCatch: Sets the TAC to the mean total removals (summed over fleets) across all historical years. Returns an empty advice object if no landings data are available.

  • ExampleMPs: Returns a character vector naming all example MPs defined in this group, for use in batch testing or MP selection.

Value

  • CurrentEffort, CurrentCatch, AverageCatch — an advice object; see Advice() for constructor details.

  • ExampleMPs — a character vector of the example MP names.

See Also

Advice(), CheckCatch(), data, advice

Examples

## Not run: 
MSE <- runMSE(SingleStockOM, MPs=ExampleMPs())

## End(Not run)

exploitationdata Class

Description

Groups the fleet-specific exploitation process components required to describe how fishing mortality is distributed across the population. Used in the Exploitation slot of a data object.

Usage

ExploitationData()

Value

ExploitationData() returns a exploitationdata object.

Slots

Selectivity

An object of class selectivity defining the age- or length-based selectivity pattern for each fleet.

Retention

An object of class retention defining the probability of retaining a fish of a given age or length once caught.

DiscardMortality

An object of class discardmortality defining the mortality rate of discarded fish by age or length.

Misc

A named list for any additional exploitation-level metadata.

ExploitationData() creates a new exploitationdata object.

See Also

data, Data()


ExploitationObs Constructor

Description

Construct an exploitationobs object defining observation error for exploitation process parameters.

Usage

ExploitationObs(
  Selectivity = list(),
  Retention = list(),
  DiscardMortality = list(),
  Misc = list()
)

Arguments

Selectivity

list. Observation error specification for selectivity. Default list().

Retention

list. Observation error specification for retention. Default list().

DiscardMortality

list. Observation error specification for discard mortality. Default list().

Misc

list. Miscellaneous additional objects. Default list().

Details

Placeholder. This class and constructor are reserved for future development and are not currently used during model runs. Each slot will eventually mirror the structure of the corresponding slot in exploitationdata, providing bias and CV specifications for selectivity, retention, and discard mortality estimation. All slot values are silently ignored during simulation.

When converted from a legacy Obs-legacy object via ConvertObs(), the selectivity bias CVs (LFCbiascv, LFSbiascv) are not yet mapped to this class and are silently dropped.

Value

An exploitationobs object.

See Also

Other obs: CatchObs(), CompObs(), EffortObs(), IndicesObs(), LifeHistoryObs(), Obs(), catchobs-class, compobs-class, effortobs-class, exploitationobs-class, indicesobs-class, lifehistoryobs-class, obs-class

Examples

eo <- ExploitationObs()

The exploitationobs S4 Class

Description

Defines the observation error structure for exploitation process parameters (selectivity, retention, discard mortality). Used in the Exploitation slot of an obs object. Objects are created via ExploitationObs().

Details

This class is a placeholder. Each slot mirrors the corresponding sub-object of exploitationdata and will eventually hold an error structure for the associated exploitation parameter. Slots are currently untyped lists and are not populated during model runs. See ExploitationObs() for further details.

Slots

Selectivity

list. Observation error specification for selectivity. See ExploitationObs().

Retention

list. Observation error specification for retention. See ExploitationObs().

DiscardMortality

list. Observation error specification for discard mortality. See ExploitationObs().

Misc

list. Miscellaneous additional objects.

See Also

Other obs: CatchObs(), CompObs(), EffortObs(), ExploitationObs(), IndicesObs(), LifeHistoryObs(), Obs(), catchobs-class, compobs-class, effortobs-class, indicesobs-class, lifehistoryobs-class, obs-class


Extend an Array Along Named Dimensions

Description

Extends an array with named dimensions to include all simulations, ages, size classes, areas, and any missing years. Can also recurse into S4 objects and lists.

Usage

Extend(
  array,
  nSim = NULL,
  AgeClasses = NULL,
  Classes = NULL,
  Years = NULL,
  Areas = NULL,
  default = NULL,
  backfill = FALSE,
  maintain_seasonal_pattern = TRUE,
  skip_data = TRUE,
  debug = FALSE
)

ExtendSims(array, nSim = NULL)

ExtendAges(array, AgeClasses = NULL)

ExtendClasses(array, Classes = NULL)

ExtendYears(
  array,
  Years = NULL,
  default = NULL,
  backfill = FALSE,
  maintain_seasonal_pattern = TRUE
)

ExtendAreas(array, Areas = NULL)

Arguments

array

An array() with named dimensions including at least one of Sim, Year, Age, or Area. Alternatively, an S4 or list() object, in which case the function recurses over all slots or elements and extends any named arrays. Any other object is returned unchanged.

nSim

Integer. Total number of simulations, or NULL to skip.

AgeClasses

Numeric vector of age classes, or NULL to skip.

Classes

Numeric vector of size classes (length or weight bins), or NULL to skip.

Years

Numeric vector of Year values to extend to, or NULL to skip.

Areas

Numeric vector of area indices (1:nArea), or NULL to skip.

default

Default fill value for forward-filled years. If NULL (default), the value from the most recent existing year is used.

backfill

Logical. If TRUE, also back-fill years earlier than the earliest existing year. Default FALSE.

maintain_seasonal_pattern

Logical. Seasonal models only. If TRUE fills in missing year values by matching those from the closest corresponding season (e.g., maintains seasonal recruitment pattern)

skip_data

logical(1) Skip any data objects? Default TRUE

debug

Logical. If TRUE, prints the class of each object as it is processed. Default FALSE.

Details

ExtendSims

The Sim dimension must have length 1 or nSim. If length 1, it is replicated to length nSim with simulation 1 values copied to all simulations. If already length nSim, the array is returned unchanged.

ExtendAges

The Age dimension must have length 1 or nAge. If length 1, it is replicated to length nAge with the first age class copied to all ages. If already length nAge, the array is returned unchanged.

ExtendClasses

The Class dimension must have length 1 or nClass. If length 1, it is replicated to length nClass with class 1 values copied to all classes. If already length nClass, the array is returned unchanged.

ExtendYears

The Year dimension can be any length. If all values in Years are already present, the array is returned unchanged. Otherwise missing years are added by forward-filling from the most recent existing year, back-filling from the earliest (if backfill = TRUE), or step-filling for years within the existing range. If any year values are non-integer (decimal), seasonal matching is used via ExtendYears_seasonal().

ExtendAreas

The Area dimension must have length 1 or nArea. If length 1, it is replicated to length nArea with area 1 values copied to all areas. If already length nArea, the array is returned unchanged.

Value

The input object with dimensions extended as specified. The return type matches the input type (array, S4, or list).

See Also

ExtendSims(), ExtendAges(), ExtendClasses(), ExtendYears(), ExtendAreas()

Examples

# ExtendSims
array <- array(c(0.5, 0.1),
               dim = c(1,2),
               dimnames = list(Sim = 1, Year=2025:2026)
)
Extend(array, nSim=5)
ExtendSims(array, 5)

# ExtendAges 
array <- array(c(0.5, 0.1),
               dim = c(2,1,2),
               dimnames = list(Sim = 1:2, Age=0, Year=2025:2026)
)
Extend(array, AgeClasses = 0:10)
ExtendAges(array, 0:10)


# ExtendYears

## Annual
array <- array(1:8,
  dim = c(2, 4),
  dimnames = list(
    Sim = 1:2,
    Year = c(1950, 1960, 1980, 2020)
  )
)
Years <- c(1940, 1955, 1965, 1985, 2025)
Extend(array, Years=Years)
ExtendYears(array, Years)

## Seasonal
array <- array(1:8,
  dim = c(2, 4),
  dimnames = list(
    Sim = 1:2,
    Year = c(1950, 1950.25, 1950.5, 1950.75)
  )
)
Years <- c(1945.25, 1960, 1975.5)
ExtendYears(array, Years)

Unfished Reference Point Quantities

Description

Extract unfished reference point quantities from a hist object. B0() returns total biomass, SB0() spawning biomass, SP0() spawning production, and N0() numbers-at-age. All functions support both equilibrium and dynamic unfished calculations (see type argument).

Usage

B0(Hist, type = c("Equilibrium", "Dynamic"), Reduce = TRUE)

SB0(Hist, type = c("Equilibrium", "Dynamic"), Reduce = TRUE)

SP0(Hist, type = c("Equilibrium", "Dynamic"), Reduce = TRUE)

N0(Hist, type = c("Equilibrium", "Dynamic"), Reduce = TRUE)

Arguments

Hist

A hist object; the output of Simulate(), containing the simulated historical fishery dynamics.

type

Character. One of 'Equilibrium' or 'Dynamic'; partial matching is supported.

  • 'Equilibrium': unfished values assuming equilibrium conditions — no recruitment deviations and all life-history parameters constant over time.

  • 'Dynamic': unfished values calculated by running the full population dynamics model, including recruitment deviations and any time-varying parameters.

Reduce

Logical. If TRUE (default), calls ReduceDims() to collapse any Sim, Year, or Age dimensions where values are identical across that dimension, reducing array size. If FALSE, the slot contents are returned as-is with all dimensions intact.

Value

  • N0(): a named list with one element per Stock. Each element is an array with dimensions ⁠[Sim, Age, Year]⁠. The Sim and Year dimensions are collapsed by ReduceDims() when Reduce = TRUE and values do not vary across those dimensions.

  • B0(), SB0(), SP0(): an array with dimensions ⁠[Sim, Stock, Year]⁠. The Sim and Year dimensions are collapsed by ReduceDims() when Reduce = TRUE and values do not vary across those dimensions.

See Also

ReduceDims() for details on dimension collapsing.


MP feasibility diagnostic

Description

What MPs may be run (best case scenario) for various data-availability scenarios and management constraints?

Usage

Fease(
  Data = NULL,
  TAC = TRUE,
  TAE = TRUE,
  SL = TRUE,
  Spatial = TRUE,
  names.only = TRUE,
  msg = TRUE,
  include.ref = FALSE
)

Arguments

Data

An object of class 'Data'. Optional. If Data object is included, the returned MPs are both feasible (in terms of management) and possible (sufficient data to run MP)

TAC

Logical. Are catch limits feasible for this fishery?

TAE

Logical. Are effort controls feasible for this fishery?

SL

Logical. Are size-selectivity regulations (either gear changes or size-retention regulations) feasible for this fishery?

Spatial

Logical. Are spatial closures feasible for this fishery?

names.only

Logical. Should only the names of the feasible MPs be returned (default)? If FALSE, a data frame with MP name, and two columns of logical values: Can (possible given data) and Fease (feasible given management constraints) is returned

msg

Logical. Should messages be printed to the console?

include.ref

Logical. Should reference MPs (e.g. FMSYref) be included as feasible methods? Default is FALSE

Value

Either a vector of MP names that are feasible for the fishery (default) or a 3 column data frame (names.only=FALSE).

Author(s)

T. Carruthers & A. Hordyk

Examples

## Not run: 
Fease(TAC=FALSE)
Fease(SL=FALSE, Spatial=FALSE)
Fease(Atlantic_mackerel, TAE=FALSE, names.only=FALSE)

## End(Not run)

Fecundity Constructor and Accessors

Description

Construct a fecundity object defining the fecundity schedule for a stock, or access and replace the Fecundity slot of a stock and its individual slots. Fecundity is optional — see Default Behaviour below.

Usage

Fecundity(
  Pars = list(),
  Model = NULL,
  Units = "eggs",
  MeanAtAge = NULL,
  MeanAtLength = NULL,
  Classes = NULL,
  Timing = NULL,
  Misc = list()
)

Fecundity(x) <- value

Arguments

Pars

list. Named list of fecundity parameters. Element names must match the arguments of a built-in fecundity model (see FecundityModels()). When Pars is non-empty and Model is NULL, the model is inferred automatically by FindModel(). When Pars is a stock object, Fecundity() acts as a pass-through accessor and returns x@Fecundity. See also Specifying Biological and Fleet Schedules for the full set of accepted input formats. Default list().

Model

character(1) or function. Fecundity model identifier. When NULL (default), the model is inferred from Pars via FindModel(). May be set to a character string naming a built-in model or to a custom R function — see Specifying Biological and Fleet Schedules.

Units

character(1). Unit of reproductive output (e.g., "eggs"). Sets the unit of the SProduction slot in hist output objects. Default "eggs".

MeanAtAge

array or NULL. Mean fecundity-at-age with named dimensions ⁠Sim × Age × Year⁠. Supply directly when bypassing the model-based approach (Pars = list()). Only the years at which values change need to be included; Extend() fills the remainder. When Pars contains a matched model, any values here are overwritten during Populate(). A numeric vector of length nAge is also accepted and promoted to a ⁠1 × nAge × 1⁠ array automatically. Default NULL.

MeanAtLength

array or NULL. Mean fecundity-at-length with named dimensions ⁠Sim × Length × Year⁠. Populated automatically during Populate() when an at-length fecundity model is used; may also be supplied directly. When MeanAtLength is populated and MeanAtAge is not, Populate() converts it to MeanAtAge via the age-length key (ALK) from a length object. Default NULL.

Classes

numeric or NULL. Age or length class midpoints corresponding to the ⁠MeanAt*⁠ array in use. Default NULL.

Timing

array or NULL. Reserved for future use. Intended to represent the timing of spawning within the time step. Currently stored but not applied; spawning timing is controlled by SRR(). Default NULL.

Misc

list. Used internally. Default list().

x

A fecundity object for slot accessors, or a stock object for ⁠Fecundity<-⁠.

value

For ⁠Fecundity<-⁠: a fecundity object.

Details

Default Behaviour When Omitted

Fecundity is optional. When this object is empty (the default), Populate() computes spawning production (SProduction in hist output) as mature weight-at-age — the product of Weight@MeanAtAge and Maturity@MeanAtAge. In this case SProduction equals spawning biomass (SBiomass) and both slots carry the same values.

When this object is populated, SProduction is computed in the units of Units (e.g. eggs per individual multiplied through maturity), allowing reproductive output to differ from biomass. This is relevant for species where egg production is not proportional to body weight — for example, batch-spawning fish or species with strongly size-dependent clutch size.

Specifying Fecundity

There are two ways to define the fecundity schedule; see Specifying Biological and Fleet Schedules for full details on input formats and the rules that govern how Pars, Model, and ⁠MeanAt*⁠ arrays interact.

Model-based (recommended): supply Pars with named parameters matching a built-in model (see FecundityModels()). If Model = NULL and the parameter names uniquely match a model, FindModel() resolves the model automatically. MeanAtAge is then populated by Populate() when the stock is added to an OM():

# Egg production proportional to weight — model inferred from Pars names
fec <- Fecundity(Pars = list(a = 1000, b = 3.0))

# Stochastic a across simulations
fec <- Fecundity(Pars = list(a = c(800, 1200), b = 3.0))

# Time-varying a (increases in 2010; Extend() fills the rest)
a_arr <- array(c(1000, 1200), dim = c(1, 2),
               dimnames = list(Sim = 1, Year = c(1990, 2010)))
fec <- Fecundity(Pars = list(a = a_arr, b = 3.0))

# Inter-annual random walk on a (log-normal, SD = 0.1)
fec <- Fecundity(Pars = list(a = c(800, 1200), aSD = 0.1, b = 3.0))

Direct array: supply MeanAtAge (or MeanAtLength) with Pars = list(). Values are preserved during Populate():

ages  <- 0:20
fec_aa <- Fecundity(
  MeanAtAge = array(
    1000 * seq(0, 1, length.out = length(ages))^2,
    dim      = c(1, length(ages), 1),
    dimnames = list(Sim = 1, Age = ages, Year = 1990)
  )
)

At-Length Models

Models whose class contains "at-Length" produce MeanAtLength, which is converted to MeanAtAge via the ALK — a populated Length() object must be passed to Populate().

Pass-Through Access from a Stock

When Pars is a stock object, Fecundity() returns the Fecundity slot directly:

Fecundity(my_stock)             # returns my_stock@Fecundity
Fecundity(my_stock) <- my_fec   # replaces my_stock@Fecundity

Slot Accessors

Individual slots can be read or replaced using generic functions matching their names. All replacement functions re-validate the object:

Pars(fec)          <- list(a = 1000, b = 3.0)
Model(fec)         <- "EggProduction"
Units(fec)         <- "eggs"
MeanAtAge(fec)     <- my_array
MeanAtLength(fec)  <- my_length_array
Classes(fec)       <- 0:20

Value

  • Fecundity() returns a fecundity object. If Pars is a stock, returns x@Fecundity.

  • ⁠Fecundity<-⁠ returns the stock x with the Fecundity slot replaced and the object re-validated.

See Also

  • fecundity for the class definition and slot-level documentation.

  • FecundityModels() for available models and required parameter sets.

  • ValidUnits() for accepted unit strings.

  • FindModel() for automatic model inference.

  • Populate() for array population.

  • Stock() for the enclosing stock constructor.

  • Length() for the companion length schedule, required when using at-length fecundity models.

  • Weight() and Maturity() for the schedules used in the default spawning biomass calculation.

  • SRR() for spawning timing within the time step.

Other fecundity: fecundity-class

Examples

# See FecundityModels() for all available built-in fecundity models and the
# parameter names required for each. All models use a logistic 50/95
# parameterisation with an asymptote of MaxFec.
FecundityModels()

# ---- Default behaviour (Fecundity omitted) ----

## When Fecundity is left empty, Populate() computes SProduction as mature
## weight-at-age (Weight@MeanAtAge * Maturity@MeanAtAge), so SProduction
## equals SBiomass. This is appropriate for most species.
stk <- Stock(Name = "Example stock", Ages = Ages(MaxAge = 20))
Fecundity(stk)    # empty fecundity-class object

# ---- Model-based specification — age-based ----

## FecundityAtAge: logistic fecundity-at-age
## A50     = age at 50% maximum fecundity
## A50_95  = age interval from 50% to 95% maximum fecundity
## MaxFec  = asymptotic (maximum) fecundity

## Constant parameters — same value for every simulation and year
fec <- Fecundity(Pars = list(A50 = 4, A50_95 = 2, MaxFec = 1e6))

## Stochastic A50 across simulations — drawn from Uniform(lower, upper)
fec <- Fecundity(Pars = list(A50    = c(3, 5),
                             A50_95 = 2,
                             MaxFec = 1e6))


## Time-varying MaxFec with named change-point arrays
## Only the years where values change need to be supplied; Extend() fills
## all intermediate and future years by forward-filling automatically.
nSim <- 48

mf_arr <- array(
  c(rep(1e6, nSim), rep(1.2e6, nSim)),   # MaxFec increases in 2010
  dim      = c(nSim, 2),
  dimnames = list(Sim = seq_len(nSim), Year = c(1990, 2010))
)
fec <- Fecundity(Pars = list(A50    = c(3, 5),
                             A50_95 = 2,
                             MaxFec = mf_arr))


# ---- Model-based specification — length-based ----

## FecundityAtLength: logistic fecundity-at-length
## L50     = length at 50% maximum fecundity
## L50_95  = length interval from 50% to 95% maximum fecundity
fec_l <- Fecundity(Pars = list(L50    = 40,
                               L50_95 = 8,
                               MaxFec = 1e6))

## Stochastic L50 and time-varying MaxFec combined
L50_sim <- runif(nSim, 35, 45)
fec_l2  <- Fecundity(Pars = list(L50    = L50_sim,
                                 L50_95 = 8,
                                 MaxFec = mf_arr))

# ---- Model-based specification — weight-based ----

## FecundityAtWeight: logistic fecundity-at-weight
## W50     = weight at 50% maximum fecundity
## W50_95  = weight interval from 50% to 95% maximum fecundity
fec_w <- Fecundity(Pars = list(W50    = 2.0,
                               W50_95 = 0.5,
                               MaxFec = 1e6))

# ---- Direct array specification ----

## Supply MeanAtAge directly (Pars left empty).
## A plain numeric vector of length nAge is accepted; treated as a single
## simulation, single year and replicated by Extend() as needed.
ages   <- 0:20
fec_aa <- Fecundity(
  MeanAtAge = logistic_50_95(ages, x50 = 4, x50_95 = 2, asymp = 1e6)
)


## Named Sim x Age x Year array — two change-point years, single simulation.
## Extend() replicates Sim = 1 to all nSim simulations automatically.
maa <- array(
  c(logistic_50_95(ages, x50 = 4,   x50_95 = 2, asymp = 1e6),  # 1990
    logistic_50_95(ages, x50 = 4.5, x50_95 = 2, asymp = 1.2e6)),# 2010
  dim      = c(1, length(ages), 2),
  dimnames = list(Sim = 1, Age = ages, Year = c(1990, 2010))
)
fec_arr <- Fecundity(MeanAtAge = maa)

## Supply MeanAtLength directly — converted to MeanAtAge via the ALK
## during Populate() when a Length object is provided.
lens   <- seq(5, 120, by = 5)
fec_al <- Fecundity(
  MeanAtLength = array(
    logistic_50_95(lens, x50 = 40, x50_95 = 8, asymp = 1e6),
    dim      = c(1, length(lens), 1),
    dimnames = list(Sim = 1, Length = lens, Year = 1990)
  )
)

# ---- Slot accessors ----

fec <- Fecundity(Pars = list(L50 = 40, L50_95 = 8, MaxFec = 1e6))

## Read slots
MeanAtAge(fec)     # NULL until Populate() is called
MeanAtLength(fec)  # NULL unless an at-length model or direct array is used
Units(fec)

## Replace slots
Units(fec)         <- "eggs"
Classes(fec)       <- seq(5, 120, by = 5)

# ---- Attaching to a Stock ----

Fecundity(stk) <- Fecundity(Pars = list(L50 = 40, L50_95 = 8, MaxFec = 1e6))
Fecundity(stk)

# ---- Populate ----

## The final populated object (typically done internally).
## When Fecundity is populated, SProduction differs from SBiomass.
## At-length models require a populated Length object passed to Populate().
pop_fec <- Populate(Fecundity(stk), 
                    Ages   = Ages(MaxAge = 20),
                    Length = Length(Pars = 
                                      list(
                                        Linf = 100, 
                                        K = 0.2, 
                                        t0 = -0.1
                                      )
                    )
)
pop_fec

MeanAtLength(pop_fec)
MeanAtAge(pop_fec)

The fecundity S4 Class

Description

Defines the fecundity schedule for a stock object, expressed as reproductive output per individual as a function of age or length. This object is optional — see Default Behaviour in Fecundity() for what happens when it is omitted. Objects are typically created via Fecundity(), which documents all parameters, validates inputs, and infers the fecundity model automatically when possible.

Details

Direct construction via methods::new() is not recommended; use Fecundity() instead, which handles model inference and object validation.

This object is optional. When empty, Populate() computes spawning production (SProduction) as mature weight-at-age (i.e. identical to spawning biomass, SBiomass). When populated, SProduction is in the units of this object (e.g. eggs per individual), allowing reproductive output to differ from biomass — relevant for species where egg production is not proportional to weight.

Slots

Pars

list. Named list of fecundity model parameters whose names correspond to those expected by Model. See FecundityModels() for parameter sets and Specifying Biological and Fleet Schedules for accepted input formats.

Model

function or character(1). Fecundity model identifier, matched to one of FecundityModels(). Set automatically by FindModel() when Pars is supplied without an explicit model.

Units

character(1). Unit of reproductive output (e.g., "eggs"). Determines the unit of the SProduction slot in hist objects. When this object is empty, SProduction defaults to spawning biomass and Units is irrelevant.

MeanAtAge

array. Mean fecundity-at-age with named dimensions Sim, Age, and Year. Populated automatically by Populate() when Pars and Model are set; may also be supplied directly when Pars is empty. When Pars contains a matched model, any existing values are overwritten. See Specifying Biological and Fleet Schedules.

MeanAtLength

array. Mean fecundity-at-length with named dimensions Sim, Length, and Year. Populated automatically when an at-length fecundity model is used, or may be supplied directly. Converted to MeanAtAge via the ALK during Populate() when MeanAtAge is not already populated. See Specifying Biological and Fleet Schedules.

Classes

numeric. Age or length class midpoints corresponding to the ⁠MeanAt*⁠ array in use.

Timing

array or numeric. Reserved for future use. Intended to represent the timing of spawning within the time step. Currently stored but not applied; spawning timing is controlled by SRR().

Misc

list. Used internally.

See Also

Other fecundity: Fecundity()


Fecundity Models

Description

Logistic fecundity-at-age, fecundity-at-length, and fecundity-at-weight models for use in a Fecundity() object.

Usage

FecundityAtAge(Ages, A50, A50_95, MaxFec)

FecundityAtLength(Length, L50, L50_95, MaxFec)

FecundityAtWeight(Weight, W50, W50_95, MaxFec)

FecundityModels(full = TRUE, print = TRUE)

FecundityModelsLength(full = TRUE, print = TRUE)

FecundityModelsAge(full = TRUE, print = TRUE)

FecundityModelsWeight(full = TRUE, print = TRUE)

Arguments

Ages

numeric vector of age classes (for age-based models)

A50

age at 50% maximum fecundity (Logistic-at-Age)

A50_95

interval between A50 and age at 95% maximum fecundity (Logistic-at-Age)

MaxFec

Numeric. Maximum (asymptotic) fecundity. Used as the upper asymptote of the logistic curve.

Length

numeric vector of length classes (for length-based models)

L50

length at 50% maximum fecundity (Logistic-at-Length)

L50_95

interval between L50 length at 95% maximum fecundity (Logistic-at-Length)

Weight

numeric vector of weight classes (for weight-based models)

W50

weight at 50% maximum fecundity (Logistic-at-Weight)

W50_95

weight at 95% maximum fecundity (Logistic-at-Weight)

full

Logical. Provide a complete table (TRUE) or just the model names (FALSE)?

print

Logical. Print out the results (TRUE) or just return the data.frame (FALSE)?

Details

All fecundity models use a logistic 50/95 parameterisation:

F(x)=MaxFec1+exp(ln(19)xx50x95x50)F(x) = \frac{\texttt{MaxFec}}{1 + \exp\left(-\ln(19) \cdot \frac{x - x_{50}}{x_{95} - x_{50}}\right)}

where x95=x50+x50_95x_{95} = x_{50} + x_{50\_95}.

The available model functions are:

  • FecundityAtAge(): logistic fecundity as a function of age.

  • FecundityAtLength(): logistic fecundity as a function of length.

  • FecundityAtWeight(): logistic fecundity as a function of weight.

The ⁠FecundityModels*⁠ functions list available models:

  • FecundityModels(): all fecundity models.

  • FecundityModelsAge(): fecundity-at-age models only.

  • FecundityModelsLength(): fecundity-at-length models only.

  • FecundityModelsWeight(): fecundity-at-weight models only.

Value

  • FecundityAtAge(), FecundityAtLength(), FecundityAtWeight(): a numeric vector of fecundity values at each age, length, or weight class respectively.

  • FecundityModels(), FecundityModelsAge(), FecundityModelsLength(), FecundityModelsWeight(): invisibly returns a data frame (if full = TRUE) or character vector (if full = FALSE) of available models. Prints to console if print = TRUE.

Prints to console and invisible data.frame or model names

See Also

Fecundity(), Maturity(), Ages(), Length(), Weight(), Stock()

Examples

Ages <- 0:15
Length <- seq(10, 100, 10)
Weight <- seq(1, 50, 5)

F_age <- FecundityAtAge(Ages, A50 = 5, A50_95 = 3, MaxFec=1e6)

F_length <- FecundityAtLength(Length, L50 = 50, L50_95 = 20, MaxFec=1e6)

F_weight <- FecundityAtWeight(Weight, W50 = 20, W50_95 = 15, MaxFec=1e6)


plot(Ages, F_age, type = "l", lwd = 2,
     xlab = "Age (years)", ylab = "Fecundity", 
     main = "Fecundity-at-Age")

plot(Length, F_length, type = "l", lwd = 2,
     xlab = "Length", ylab = "Fecundity", 
     main = "Fecundity-at-Length")

plot(Weight, F_weight, type = "l", lwd = 2, 
     xlab = "Weight", ylab = "Fecundity", 
     main = "Fecundity-at-Weight")

Extract Fishing Mortality Time Series

Description

FInteract(), FDead(), and FRetain() extract fishing mortality for interactions (encounters), killed, and retained fish respectively, from a hist or mse object.

Usage

FInteract(
  object,
  df = TRUE,
  byAge = TRUE,
  byArea = FALSE,
  byFleet = FALSE,
  Reduce = TRUE,
  IncYear = FALSE
)

FDead(
  object,
  df = TRUE,
  byAge = TRUE,
  byArea = FALSE,
  byFleet = FALSE,
  Reduce = TRUE,
  IncYear = FALSE
)

FRetain(
  object,
  df = TRUE,
  byAge = TRUE,
  byArea = FALSE,
  byFleet = FALSE,
  Reduce = TRUE,
  IncYear = FALSE
)

Arguments

object

A hist or mse object.

df

Logical. If FALSE the raw array slot is returned. If TRUE (default) a tidy data.frame is returned.

byAge

Logical. If TRUE the data frame retains the Age dimension (sourced from the ⁠*Area⁠ slots, which always include Area). If FALSE the apical fishing mortality — the maximum over ages — is returned. Ignored when df = FALSE.

byArea

Logical. If TRUE the Area dimension is retained. When byAge = TRUE area is always included regardless of this argument. Ignored when df = FALSE.

byFleet

Logical. If TRUE the Fleet dimension is retained. If FALSE values are summed over fleets before the apical or age-structured extraction. Ignored when df = FALSE.

Reduce

Logical. If TRUE (default) simulation dimensions are reduced using ReduceDims() before conversion to a data frame.

IncYear

Logical. Passed to ReduceDims(); controls whether the year dimension is retained during reduction. Default FALSE.

Details

When byAge = FALSE the apical (maximum over ages) fishing mortality rate is returned. When byAge = TRUE the full age-structured array is retained; byArea is always included when byAge = TRUE.

When applied to an mse object the historical and projection periods are row-bound and labelled via the Period column; historical rows carry MP = "Historical".

Value

  • df = FALSE — the raw array slot (FInteract, FDead, or FRetain).

  • df = TRUE — a tidy data.frame with columns Sim, Stock, Year, Period, MP (MSE only), and optionally Age, Area, and/or Fleet, plus Value and Variable.

Examples

Hist <- Simulate(SingleStockOM)
MSE <- Project(Hist, 'CurrentEffort')

# Raw array slots
FInteract(Hist)
FDead(Hist)
FRetain(MSE)

# Age-structured F (area always included)
FInteract(Hist, df = TRUE)
FDead(MSE, df = TRUE)
FRetain(MSE, df = TRUE)

# Retain fleet dimension
FDead(MSE, df = TRUE, byFleet = TRUE)

# Apical F (max over ages) as a tidy data frame
FInteract(Hist, df = TRUE, byAge = FALSE)
FDead(MSE,      df = TRUE, byAge = FALSE)
FRetain(MSE,    df = TRUE, byAge = FALSE)

# Age + Fleet
FDead(MSE, df = TRUE, byFleet = TRUE)

# Area only (apical F per area)
FDead(MSE, df = TRUE, byAge = FALSE, byArea = TRUE)
FDead(MSE, df = TRUE, byAge = FALSE, byArea = TRUE, byFleet = TRUE)

Fit a Movement Matrix to Target Spatial Parameters

Description

Fits a row-stochastic movement matrix for a single simulation, age class, and year by numerical optimisation, so that the asymptotic (equilibrium) unfished distribution and the diagonal (staying probability) simultaneously reproduce the targets in Spatial@UnfishedDist and Spatial@ProbStaying. Dispatches to FitMovement_2_Area() for two-area models and FitMovement_Multi_Area() for three or more areas.

Usage

FitMovement(Spatial, sim = 1, age = 1, year = 1)

Arguments

Spatial

A populated spatial object whose UnfishedDist, ProbStaying, and (for multi-area models) FracOther slots have been expanded to named arrays.

sim

integer(1). Simulation index. Clamped to the Sim dimension of each slot if that dimension has length 1. Default 1.

age

integer(1). Age index (position in the Age dimension). Clamped to the Age dimension if length 1. Default 1.

year

integer(1). Year index (position in the Year dimension). Clamped to the Year dimension if length 1. Default 1.

Details

This function is called internally by Populate() for every combination of simulation, age, and year. It can also be called directly to inspect or debug the fitted movement matrix for a specific slice of a spatial object.

Value

A numeric matrix of dimensions ⁠nArea × nArea⁠. Each row gives the movement probabilities from that area to all areas (including itself), and rows sum to exactly 1.

See Also


Fit statistical properties of historical stock targeting

Description

Estimates the covariance of log-targeting deviations from historical targeting weights stored in OM@StockTargeting@Targeting, as produced by StandardizeEffort().

Usage

FitStockTargeting(OM, tol = 1e-06, active_thresh = 0.1)

Arguments

OM

An operating model object (om) with a populated ⁠@StockTargeting@Targeting⁠ array of dimension ⁠[nSim, nStock, nFleet, nYearHist]⁠, as produced by StandardizeEffort().

tol

numeric(1). Tolerance below which targeting values are treated as zero for the purpose of covariance estimation. Default 1e-6.

active_thresh

numeric(1). Minimum proportion of historical years with positive targeting weight for a stock-fleet combination to be included in covariance estimation (strictly greater than this value). Default 0.1.

Details

For each simulation, fleet, and year, the fleet-level log-effort is the geometric mean of log-targeting weights over active stocks at that time step (those with positive targeting weight):

logE^f,t=1Af,tsAf,tlogTs,f,t,Af,t={s:Ts,f,t>0}\log \hat{E}_{f,t} = \frac{1}{|\mathcal{A}_{f,t}|} \sum_{s \in \mathcal{A}_{f,t}} \log T_{s,f,t}, \quad \mathcal{A}_{f,t} = \{s : T_{s,f,t} > 0\}

Stock targeting deviations are the multiplicative departures from this fleet mean:

w~s,f,t=logTs,f,tlogE^f,t\tilde{w}_{s,f,t} = \log T_{s,f,t} - \log \hat{E}_{f,t}

The stationary covariance Σf\Sigma_f is estimated from w~s,f,t\tilde{w}_{s,f,t} across historical years for stocks that are consistently active (positive targeting in strictly more than active_thresh proportion of years). Element (Σf)s,s(\Sigma_f)_{s,s'} captures the co-variation in log-targeting deviations between stocks ss and ss' for fleet ff.

The function returns OM unchanged if ⁠@Mean⁠ and ⁠@Covariance⁠ are already fully populated, or if nStock == 1.

Value

The input OM object with the following slots populated:

  • ⁠@StockTargeting@Mean⁠: temporal mean of log-targeting deviations, exponentiated to the natural scale. Array of dimension ⁠[nSim, nStock, nFleet]⁠. Values are approximately 1 for active stocks (close to zero on the log scale by the sum-to-zero construction of StandardizeEffort(), but not guaranteed to be exactly 1) and exactly 1 for inactive stocks (neutral, log-deviation fixed at zero).

  • ⁠@StockTargeting@Covariance⁠: stationary covariance matrix of log-targeting deviations, array of dimension ⁠[nSim, nStock, nStock, nFleet]⁠. Rows and columns for inactive stocks are zero.

See Also

StandardizeEffort(), GenerateStockTargeting()


Fleet

Description

Construct and manipulate a fleet object defining the exploitation characteristics of a fleet for a stock in an operating model.

Usage

Fleet(
  Name = NULL,
  Effort = new("effort"),
  Catchability = new("catchability"),
  Selectivity = new("selectivity"),
  Retention = new("retention"),
  DiscardMortality = new("discardmortality"),
  Closure = array(),
  WeightFleet = array(),
  Bioeconomic = new("bioeconomic"),
  Dynamics = list(),
  Misc = list()
)

Closure(x)

Closure(x) <- value

WeightFleet(x)

WeightFleet(x) <- value

Fleet(x) <- value

Arguments

Name

Character or NULL. Fleet name, or an om object for pass-through access (see Details).

Effort

An effort object defining historical fishing effort, spatial distribution, and targeting. See Effort() for full documentation. Default is an empty effort. When Name is an om object, a numeric value here indexes the stock within the OM (see Details).

Catchability

A catchability object defining gear efficiency and optional projected-year stochasticity or trends. See Catchability() for full documentation. Default is an empty catchability. When Name is an om object and Effort is numeric, a numeric value here further indexes the fleet within the stock (see Details).

Selectivity

A selectivity object defining selectivity-at-age, -at-length, or -at-weight. Required for all fleets. See Selectivity() for full documentation. Default is an empty selectivity.

Retention

A retention object defining retention-at-age, -at-length, or -at-weight. Optional. If not specified, all age and length classes are assumed fully retained during PopulateFleet(). See Retention() for full documentation. Default is an empty retention.

DiscardMortality

A discardmortality object defining the proportion of discarded catch that dies. Optional. If not specified, discard mortality is set to 0 (all discards survive) during PopulateFleet(). See DiscardMortality() for full documentation. Default is an empty discardmortality.

Closure

Numeric array or NULL. Spatio-temporal closure schedule with dimensions ⁠Sim x Year x Area⁠. Values of 1 indicate an open area; 0 indicates a closed area. The Sim and Year dimensions may be length 1 (replicated internally). Default is an empty array; if not specified, PopulateClosure() sets all areas to open (1) across all simulations and years.

WeightFleet

Numeric array or NA. Fleet-specific weight-at-age (⁠Sim x Age x Year⁠). Used in fleet-level biomass calculations. If NA (default), PopulateFleet() sets WeightFleet equal to the stock weight-at-age array.

Bioeconomic

A bioeconomic object. Not currently used. Default is an empty bioeconomic.

Dynamics

List. Reserved for future use for fleet dynamics model parameters. Default list().

Misc

List. Miscellaneous additional inputs. Default list().

x

A fleet object or an om object for ⁠Fleet<-⁠.

value

A fleet object or named list of fleet objects for ⁠Fleet<-⁠.

Details

A fleet object describes the fishing characteristics of a fleet for a particular stock in an operating model, including effort dynamics, catchability, selectivity, retention, discard mortality, and spatial closures.

Required and Optional Components

Selectivity() and Effort() are required for all fleets. All other components are optional and will use default values if not specified:

  • Catchability(): defaults to efficiency = 1 across all years.

  • Retention(): defaults to full retention for all age and length classes.

  • DiscardMortality(): defaults to 0 (all discards survive).

  • Closure: defaults to 1 (all areas open) across all simulations and years.

  • WeightFleet: defaults to the stock weight-at-age array.

Pass-Through Access from an OM

When Name is an om object, Fleet() acts as an accessor rather than a constructor:

  • Fleet(om) returns the full fleet list (om@Fleet).

  • Fleet(om, st) returns all fleets for stock index st (om@Fleet[[st]]), where st is passed via the Effort argument.

  • Fleet(om, st, fl) returns fleet fl for stock st (om@Fleet[[st]][[fl]]), where fl is passed via the Catchability argument.

Assigning Fleets to an OM

Stock() objects must be added to the OM before fleets. A single fleet object assigned with Fleet(om) <- MyFleet is applied to all stocks using the fleet name. A list must be structured as a stock-indexed list of fleet lists.

Bookkeeping Slots

The slots nYear, pYear, nSim, CurrentYear, Years, and Seasons are inherited from the paired stock object automatically when PopulateFleet() is called and do not need to be set manually.

Closure Array

Closure has dimensions ⁠Sim x Year x Area⁠. The Sim and Year dimensions may be length 1 (replicated internally by PopulateClosure()). If the array is empty or NULL, all areas are set to open (1) across all simulations and years. Dimension names for Sim, Year, and Area are added automatically if missing.

Individual slots may be accessed or modified using Effort(), Catchability(), Selectivity(), Retention(), DiscardMortality(), Closure(), WeightFleet(), and Bioeconomic().

Value

  • Fleet() returns a fleet object. If Name is an om object, returns the fleet list or a specific fleet from the OM.

  • ⁠Fleet<-⁠ returns the om object x with the Fleet slot updated.

  • Closure() and WeightFleet() return the corresponding slot from the fleet object x.

  • Their replacement forms return x with the corresponding slot updated.

See Also

Other fleet: Bioeconomic(), Catchability(), DiscardMortality(), Effort(), Retention(), Selectivity(), bioeconomic-class, catchability-class, discardmortality-class, effort-class, fleet-class, retention-class, selectivity-class

Examples

# See man-examples/class-Fleet.R

The fleet S4 Class

Description

Defines the fishing characteristics of a fleet for use in an operating model. Objects are typically created via the Fleet() constructor, which documents all parameters in detail.

Slots

Name

character or NULL. Unique fleet identifier.

Effort

An effort object defining historical fishing effort, spatial distribution, and targeting behaviour. See Effort().

Catchability

A catchability object defining gear efficiency and optional projected-year trends or stochasticity. See Catchability().

Selectivity

A selectivity object defining selectivity-at-age, -at-length, or -at-weight. Required for all fleets. See Selectivity().

Retention

A retention object defining retention-at-age, -at-length, or -at-weight. Optional; defaults to full retention if not supplied. See Retention().

DiscardMortality

A discardmortality object defining the proportion of discarded catch that dies. Optional; defaults to 0 (all discards survive) if not supplied. See DiscardMortality().

Closure

numeric array or NULL. Spatio-temporal closure schedule with dimensions ⁠Sim x Year x Area⁠. Values of 1 indicate an open area; 0 indicates a closed area. Defaults to 1 (all areas open) if not supplied. See Fleet().

WeightFleet

numeric array or NULL. Fleet-specific weight-at-age (⁠Sim x Age x Year⁠). If NA, set to the stock weight-at-age during PopulateFleet(). See Fleet().

Bioeconomic

A bioeconomic object. Not currently used.

Dynamics

List. Reserved for future use for fleet dynamics model parameters. Default list(). Not currently used.#'

nYear

numeric or NULL. Number of years. Inherited from the paired stock during PopulateFleet().

pYear

numeric or NULL. Number of projection years. Inherited from the paired stock during PopulateFleet().

nSim

numeric or NULL. Number of simulation replicates. Inherited from the paired stock during PopulateFleet().

CurrentYear

numeric or NULL. Current calendar year. Inherited from the paired stock during PopulateFleet().

Years

numeric or NULL. Full year vector (historical and projected). Inherited from the paired stock during PopulateFleet().

Seasons

numeric or NULL. Number of seasons. Inherited from the paired stock during PopulateFleet().

Misc

list. Miscellaneous additional inputs.

See Also

Fleet() for the constructor and full parameter documentation. Effort(), Catchability(), Selectivity(), Retention(), DiscardMortality() for sub-object constructors.

Other fleet: Bioeconomic(), Catchability(), DiscardMortality(), Effort(), Fleet(), Retention(), Selectivity(), bioeconomic-class, catchability-class, discardmortality-class, effort-class, retention-class, selectivity-class


Class 'Fleet'

Description

The component of the operating model that controls fishing dynamics

Slots

Name

Identifying name for the fleet. Usually includes location and gear type.

nyears

The number of years for the historical simulation. Single value. For example, if the simulated population is assumed to be unfished in 1975 and this is the year you want to start your historical simulations, and the most recent year for which there is data available is 2019, then nyears equals 45.

CurrentYr

The last historical year simulated before projections begin. Single value. Note that this should match the last historical year specified in the Data object, which is usually the last historical year for which data is available.

EffYears

Vector indicating the historical years where there is information available to infer the relative fishing effort expended.This vector is specified in terms of the position of the year in the vector rather than the calendar year. For example, say our simulation starts with an unfished stock in 1975,and the current year (the last year for which there is data available) is 2019. Then there are 45 historical years simulated, and EffYears should include numbers between 1 and 45. Note that there may not be information available for every historical year, especially for data poor fisheries. In these situations, the EffYears vector should include only the positions of the years for which there is information, and the vector may be shorter than the total number of simulated historical years (nyears).

EffLower

Lower bound on relative fishing effort corresponding to EffYears. EffLower must be a vector that is the same length as EffYears describing how fishing effort has changed over time. Information on relative fishing effort can be entered in any units provided they are consistent across the entire vector because the data provided will be scaled to 1 (divided by the maximum number provided).

EffUpper

Upper bound on relative fishing effort corresponding to EffYears. EffUpper must be a vector that is the same length as EffYears describing how fishing effort has changed over time. Information on relative fishing effort can be entered in any units provided they are consistent across the entire vector because the data provided will be scaled to 1 (divided by the maximum number provided).

Esd

Additional inter-annual variability in fishing mortality rate. For each historical simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. If this parameter has a positive (non-zero) value, the yearly fishing mortality rate is drawn from a log-normal distribution with a standard deviation (in log space) specified by the value of Esd drawn for that simulation. This parameter applies only to historical projections.

qinc

Mean temporal trend in catchability (also though of as the efficiency of fishing gear) parameter, expressed as a percentage change in catchability (q) per year. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. Positive numbers indicate an increase and negative numbers indicate a decrease. q then changes by this amount for in each year of the simulation This parameter applies only to forward projections.

qcv

Inter-annual variability in catchability expressed as a coefficient of variation. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This parameter applies only to forward projections.

L5

Shortest length at which 5% of the population is vulnerable to selection by the gear used in this fleet. Values can either be specified as lengths (in the same units used for the maturity and growth parameters in the stock object) or as a percentage of the size of maturity (see the parameter isRel for more information). For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This value is the same in all years unless cpars is used to provide time-varying selection.

LFS

Shortest length at which 100% of the population is vulnerable to selection by the gear used by this fleet. Values can either be specified as lengths (in the same units used for the maturity and growth parameters in the stock object) or as a percentage of the size of maturity (see the parameter isRel for more information). For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This value is the same in all years unless cpars is used to provide time-varying selection.

Vmaxlen

Proportion of fish selected by the gear at the asymptotic length (Stock@Linf). Upper and Lower bounds between 0 and 1. A value of 1 indicates that 100% of fish are selected at the asymptotic length, and the selection curve is logistic. If Vmaxlen is less than 1 the selection curve is dome shaped. For example, if Vmaxlen is 0.4, then only 40% of fish are vulnerable to the fishing gear at the asymptotic length.

isRel

Specify whether selection and retention parameters use absolute lengths or relative to the size of maturity. Single logical value (TRUE or FALSE).

LR5

Shortest length at which 5% of the population is vulnerable to retention by the fleet. Values can either be specified as lengths (in the same units used for the maturity and growth parameters in the stock object) or as a percentage of the size of maturity (see the parameter isRel for more information). For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This value is the same in all years unless cpars is used to provide time-varying selection.

LFR

Shortest length where 100% of the population is vulnerable to retention by the fleet. Values can either be specified as lengths (in the same units used for the maturity and growth parameters in the stock object) or as a percentage of the size of maturity (see the parameter isRel for more information). For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This value is the same in all years unless cpars is used to provide time-varying selection.

Rmaxlen

Proportion of fish retained at the asymptotic length (Stock@Linf). Upper and Lower bounds between 0 and 1. A value of 1 indicates that 100% of fish are retained at the asymptotic length, and the selection curve is logistic. If Rmaxlen is less than 1 the retention curve is dome shaped. For example, if Rmaxlen is 0.4, then only 40% of fish at the asymptotic length are retained.

DR

Discard rate, defined as the proportion of fully selected fish that are discarded by the fleet. Upper and Lower bounds between 0 and 1, with a value of 1 indicates that 100% of selected fish are discarded. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided.

Spat_targ

Distribution of fishing in relation to vulnerable biomass (VB) across areas. The distribution of fishing effort is proportional to VB^Spat_targ. Upper and lower bounds of a uniform distribution. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This parameter allows the user to model either avoidance or spatial targeting behavior by the fleet. If the parameter value is 1, fishing effort is allocated across areas in proportion to the population density of that area. Values below 1 simulate an avoidance behavior and values above 1 simulate a targeting behavior.

MPA

Logical argument (TRUE or FALSE). Creates an MPA in Area 1 for all years if true is selected. Defaults to FALSE.

Misc

Miscellaneous list for bio-economic parameters

Creating Object

Objects can be created by calls of the form new('Fleet')

Author(s)

T. Carruthers and A. Hordyk

Examples

showClass('Fleet')

FleetDescription

Description

A data.frame with description of slots for class Fleet

Usage

FleetDescription

Format

An object of class data.frame with 20 rows and 2 columns.


Reference management procedures

Description

Several reference MPs for your operating model to use in the management strategy evaluation. FMSYref (and related) assume perfect information about FMSY (FMSY is taken from the operating model stored at Data@Misc$ReferencePoints$ByYear$FMSY), and set an effort limit (TAE) so that F=FMSY (or some fraction of FMSY) in each year the MP is applied. NFref sets annual catch to zero and is used for looking at variability in stock with no fishing.

Usage

FMSYref(x, Data, reps = 100, plot = FALSE)

FMSYref50(x, Data, reps = 100, plot = FALSE)

FMSYref75(x, Data, reps = 100, plot = FALSE)

NFref(x, Data, reps = 100, plot = FALSE)

curEref(x, Data, reps = 100, plot = FALSE)

Arguments

x

A position in the data object

Data

A data object

reps

The number of stochastic samples of the MP recommendation(s)

plot

Logical. Show the plot?

Details

Note that you can out-perform FMSYref easily. The requirement for fixed F is actually quite strict and is by no means the upper limit in terms of yield. Don't panic if your method beats this one for yield, especially for short-lived species of high temporal variability in productivity!

Value

An object of class Rec with the TAC slot populated with a numeric vector of length reps

Functions

  • FMSYref(): A reference FMSY method that fishes at FMSY

  • FMSYref50(): A reference FMSY method that fishes at 50% of FMSY

  • FMSYref75(): A reference FMSY method that fishes at 75% of FMSY

  • NFref(): A reference MP that sets annual catch to almost zero (1e-15)

  • curEref(): A reference MP that keeps fishing effort at the level of the last historical year

Required Data

See Data-legacy for information on the Data object

Author(s)

T. Carruthers, A. Hordyk

Examples

FMSYref(1, MSEtool::SimulatedData, plot=TRUE)
FMSYref50(1, MSEtool::SimulatedData, plot=TRUE)
FMSYref75(1, MSEtool::SimulatedData, plot=TRUE)
NFref(1, MSEtool::SimulatedData, plot=TRUE)
curEref(1, MSEtool::SimulatedData)

Generate Stochastic Stock Targeting Trajectories

Description

Simulates stochastic stock-specific targeting multipliers for each fleet using independent multivariate lognormal draws at each time step.

Usage

GenerateStockTargeting(
  OM,
  Period = c("Historical", "Projection"),
  TruncSD = 2,
  n_recent = 5,
  seed = 101
)

Arguments

OM

An operating model object (om) containing a populated ⁠@StockTargeting⁠ slot with elements:

  • ⁠@Mean⁠: geometric mean targeting weight on the natural scale (from FitStockTargeting() or user defined)

  • ⁠@Covariance⁠: stationary covariance matrix of log-targeting deviations

Period

Character string specifying which period to simulate:

  • "Historical": assigns or replaces historical targeting values

  • "Projection": appends simulated projection years

TruncSD

numeric(1). Number of standard deviations beyond which log-deviations are truncated. Prevents extreme targeting values when variance is high relative to the historical record length. Default 2. Set to Inf to disable truncation.

n_recent

integer(1). For Period = "Projection" only: number of recent historical years used to determine whether a stock has been continuously inactive at the end of history. A stock with zero targeting weight in all n_recent years is treated as inactive and receives Ts,t=0T_{s,t} = 0 throughout the projection. Default 5.

seed

numeric(1). Offset added to OM@Seed for the random number generator, ensuring independence from other stochastic processes. Default 101.

Value

The input OM object with updated ⁠@StockTargeting@Targeting⁠.

Targeting is modelled in log-space as multivariate normal deviations at each time step, centred at the bias-corrected historical log-mean:

δtMVN(0,Σw)\boldsymbol{\delta}_t \sim \mathrm{MVN}(\mathbf{0},\, \Sigma_w)

Ts,t=exp ⁣(μs+δs,t)T_{s,t} = \exp\!\left(\mu_s^* + \delta_{s,t}\right)

where:

  • Ts,tT_{s,t} is the targeting multiplier for stock ss at time tt

  • δs,t\delta_{s,t} is the log-space deviation for stock ss at time tt, drawn from the multivariate normal with mean zero and covariance Σw\Sigma_w

  • Σw\Sigma_w is the stationary covariance matrix of log-targeting deviations estimated by FitStockTargeting()

  • μs=wˉs12σw,s2\mu_s^* = \bar{w}_s - \tfrac{1}{2}\sigma^2_{w,s} is the lognormal bias correction for stock ss, where wˉs=log(Means)\bar{w}_s = \log(\texttt{Mean}_s) is the fitted log-scale mean from FitStockTargeting() and σw,s2=(Σw)ss\sigma^2_{w,s} = (\Sigma_w)_{ss} is the marginal variance. This ensures E[Ts,t]=exp(wˉs)\mathrm{E}[T_{s,t}] = \exp(\bar{w}_s), preserving the historical mean targeting level for each stock on the natural scale.

Deviations are truncated to δs,tTruncSD×σw,s|\delta_{s,t}| \le \texttt{TruncSD} \times \sigma_{w,s} to guard against extreme values when variance is poorly estimated from short historical series. When variance is low, truncation has little effect and simulated values stay close to the historical mean, as intended.

Inactive stocks (zero marginal variance or non-finite mean in ⁠@StockTargeting@Mean⁠, or continuously inactive over the last n_recent historical years when Period = "Projection") receive Ts,t=0T_{s,t} = 0 throughout.

See Also

FitStockTargeting(), StandardizeEffort()

Examples

## Not run: 
OM <- GenerateStockTargeting(OM, Period = "Projection")
OM <- GenerateStockTargeting(OM, Period = "Projection", TruncSD = 2, n_recent = 5)

## End(Not run)

Obs class objects

Description

Example objects of class Obs

Usage

Generic_Obs

Imprecise_Biased

Imprecise_Unbiased

Perfect_Info

Precise_Biased

Precise_Unbiased

Format

An object of class Obs of length 1.

An object of class Obs of length 1.

An object of class Obs of length 1.

An object of class Obs of length 1.

An object of class Obs of length 1.

An object of class Obs of length 1.

Examples

avail("Obs")

Generate Stochastic Historical Effort Time Series

Description

Generates stochastic historical fishing effort trajectories from an data.frame containing effort control points.

Usage

GenHistEffort(Effort, nSim = 5, Years = NULL)

Arguments

Effort

A data.frame with columns:

Year

Calendar years or indices defining effort control points.

Lower

Lower bound on relative effort at each control year.

Upper

Upper bound on relative effort at each control year.

CV

Coefficient of variation for lognormal annual effort noise (typically constant across years; only the first value is used).

nSim

Integer. Number of stochastic effort simulations to generate.

Years

Optional integer vector of calendar years defining the full effort time series. Required if Effort$Year is specified using indices rather than calendar years.

Details

For each simulation, effort is sampled uniformly between specified lower and upper bounds at control years, linearly interpolated to a full annual time series, optionally perturbed by lognormal process error, and finally normalised to equal 1 in the terminal year.

For each simulation:

  1. Effort at each control year is drawn independently from a uniform distribution between Lower and Upper.

  2. Effort is linearly interpolated to annual resolution across Years.

  3. If CV is non-NULL, multiplicative lognormal process error is applied with mean 1.

  4. The resulting effort trajectory is normalised so that effort in the final year equals 1.

Value

An nSim x nYear numeric array used in an Effort() object

See Also

Effort()


Generate Mean-at-Age, Length, or Weight Arrays

Description

These functions generate simulated "mean at" arrays using a model and parameters.

Usage

GenMeanAtAge(Model, Pars, Ages)

GenMeanAtLength(Model, Pars, Length)

GenMeanAtWeight(Model, Pars, Weight)

Arguments

Model

A character string naming a built-in model or a valid R function.

Pars

A named list of parameters for the model.

Ages

Numeric vector of age classes (for GenMeanAtAge).

Length

Numeric vector of length classes (for GenMeanAtLength).

Weight

Numeric vector of weight classes (for GenMeanAtWeight).

Value

A numeric array with dimensions: Sim, Age/Class, Year, and sometimes Area.

See Also

LengthModels(), WeightModels(), NaturalMortalityModels(), MaturityModels, FecundityModels(), SelectivityModels(), RetentionModels()

Examples

# List `Maturity` Models
MaturityModels()


# Mean-at-Age
GenMeanAtAge(Model="MaturityAtAge", 
             Pars=list(A50=5, A50_95=1),
             Ages=1:10)

# Mean-at-Length
GenMeanAtLength(Model="MaturityAtLength", 
                Pars=list(L50=50, L50_95=10),
                Length=seq(10,100,10))

# Mean-at-Weight
GenMeanAtWeight(Model="MaturityAtWeight",
                Pars=list(W50=3, W50_95=1),
                Weight=1:10)

Generate Correlated Multi-Stock Recruitment Deviations

Description

Generates stochastic recruitment deviations for multiple stocks using a multivariate lognormal AR(1) process, preserving both cross-stock covariance and temporal autocorrelation.

Usage

GenMultiStockRecDevs(OM, TruncSD = 2, silent = FALSE)

Arguments

OM

An operating model object of class om.

TruncSD

Numeric scalar. Number of standard deviations at which to truncate the innovation distribution. Defaults to 2.

silent

logical(1) Display messages?

Details

Deviations are simulated in log-space:

Zt=μ+Φ(Zt1μ)+ϵtZ_t = \mu + \Phi (Z_{t-1} - \mu) + \epsilon_t

Rt=exp(Zt)R_t = \exp(Z_t)

where:

  • μ\mu is a bias-corrected mean

  • Φ\Phi is a diagonal matrix of lag-1 autocorrelation coefficients

  • ϵtMVN(0,Σϵ)\epsilon_t \sim MVN(0, \Sigma_\epsilon)

The innovation covariance matrix Σϵ\Sigma_\epsilon is derived from the stationary covariance ΣZ\Sigma_Z using CalcInnovationCov().

The function proceeds as follows for each simulation:

  1. Extract stock-specific parameters (sd, ac, mu)

  2. Impute missing historical deviations using univariate AR(1)

  3. Estimate stationary covariance ΣZ\Sigma_Z from historical log deviations

  4. Compute innovation covariance via CalcInnovationCov()

  5. Simulate projection deviations using a multivariate AR(1) process

Truncation is applied to the innovation term ϵt\epsilon_t, not the deviations themselves.

Value

The input OM object with RecDevProj populated for all stocks and simulations.

See Also

CalcInnovationCov(), AddAutoCorrelation()


Generate Stock-Recruitment Deviations

Description

Generate recruitment deviations for initial ages, historical years, and projected years, with optional auto-correlation and truncation.

Usage

GenRecDevs(
  SD = 0.2,
  AC = 0,
  TruncSD = 2,
  Ages = NULL,
  HistYears = NULL,
  ProjYears = NULL,
  nSim = 48,
  RecDevInit = NULL,
  RecDevHist = NULL,
  RecDevProj = NULL
)

Arguments

SD

Numeric vector of standard deviations for recruitment deviations.

AC

Numeric vector of autocorrelation coefficients (0 = no autocorr).

TruncSD

Numeric. Number of SDs for truncation of deviations.

Ages

An Ages() object defining age classes.

HistYears

Numeric vector of historical years.

ProjYears

Numeric vector of projected years.

nSim

Integer. Number of simulation replicates.

RecDevInit

Optional array of initial age recruitment deviations.

RecDevHist

Optional array of historical recruitment deviations.

RecDevProj

Optional array of projected recruitment deviations.

GenRecDevs() generates recruitment deviations across initial ages, historical years, and projected years. Steps include:

  • Generating deviations from a truncated normal distribution with standard deviation SD and truncation at TruncSD standard deviations (default 2).

  • Applying autocorrelation using AC for each simulation replicate.

  • Returning arrays of recruitment deviations for initial ages, historical years, and projected years.

If RecDevInit, RecDevHist, or RecDevProj are provided as non-NULL arrays, they will not be overwritten and will be returned as-is.

Value

A list with three elements:

  • RecDevInit: Array of recruitment deviations for initial ages.

  • RecDevHist: Array of recruitment deviations for historical years.

  • RecDevProj: Array of recruitment deviations for projection years.

Examples

## Not run: 
# Assuming `Ages` object exists
recdevs <- GenRecDevs(
  SD = 0.2,
  AC = 0.3,
  TruncSD = 2,
  Ages = Ages,
  HistYears = 2000:2020,
  ProjYears = 2021:2030,
  nSim = 5
)

## End(Not run)

Generate (log-space) residuals with truncated log-normal distribution

Description

Generate random residuals for multiple simulations and years. Each simulation has a standard deviation SD and autocorrelation AC, and residuals are truncated to TruncSD standard deviations around the mean. The resulting residuals can be propagated with autocorrelation using ApplyAC().

Usage

GenResiduals(
  SD,
  AC,
  Years,
  nSim = NULL,
  TruncSD = 2,
  nSeasons = 1,
  NA_Season = list()
)

Arguments

SD

Numeric vector of length nSim giving standard deviation of residuals.

AC

Numeric vector of length nSim giving autocorrelation (must be between -1 and 1 inclusive).

Years

Numeric vector of years for which residuals are generated.

nSim

Optional integer number of simulations (defaults to length(SD)).

TruncSD

Numeric scalar specifying how many SDs to truncate the residuals.

nSeasons

Number of seasons in the array (default 1).

NA_Season

Optional. List length nSim with each element containing integer vector indicating which (if any) seasons have NA values for all years

Value

Numeric array of dimensions nSim x nYear containing truncated log-normal residuals.

See Also

ApplyAC(), CalcResidualStats()


get object class

Description

Internal function for determining if object is of classy

Usage

getclass(x, classy)

Arguments

x

Character string object name

classy

A class of object (character string, e.g. 'Fleet')

Value

TRUE or FALSE

Author(s)

T. Carruthers with nasty hacks from A. Hordyk


Get part of an MP specific data-list

Description

Get part of an MP specific data-list

Usage

getDataList(MSElist, mm)

Arguments

MSElist

A hierarchical list [Stock][Fleet][MP]

mm

integer the MP number

Value

a sublist of MSElist for a specific MP


Extract the first dimension of a hierarchical list of recommendation objects

Description

Extract the first dimension of a hierarchical list of recommendation objects

Usage

getfirstlev(x, name, pp, ff)

Arguments

x

Simulation number

name

Character. The slot name to extract.

pp

Integer. The stock number (second level list)

ff

Integer. The fleet number (third level list)

Author(s)

T. Carruthers


Retrieve Operating Model Metadata

Description

Extracts key metadata from an operating model (OM) object, including number of simulations, stock-specific age classes, number of areas, and stock names and fleet names

Usage

GetMetaData(OM, Period = c("Historical", "Projection", "All"), Years = NULL)

Arguments

OM

An operating model object.

Period

Character string specifying the model period. Must be one of "Historical", "Projection", or "All". Default is "All".

Years

Optional vector of years to subset the OM. If NULL, all years for the specified period are returned.

Value

A named list with the following elements:

  • nSim — number of simulations in the OM

  • AgeClasses — list of age classes for each stock

  • nAges — list of the number of age classes for each stock

  • nAreas — number of spatial areas (must be consistent across stocks)

  • StockNames — character vector of stock names

  • Years — vector of years for the specified period

  • Period — resolved period argument

  • FleetNames — character vector of fleet names (from the first stock)

Examples

## Not run: 
meta <- GetMetaData(MyOM, Period = "Historical")
meta$nSim
meta$AgeClasses

## End(Not run)

Optimization function to find a movement model that matches user specified movement characteristics modified for Rcpp.

Description

The user specifies the probability of staying in the same area and spatial heterogeneity (both in the unfished state).

Usage

getmov2(x, Prob_staying, Frac_area_1)

Arguments

x

A position in vectors Prob_staying and Frac_area_1

Prob_staying

User specified probability that individuals in area 1 remain in that area (unfished conditions)

Frac_area_1

User specified fraction of individuals found in area 1 (unfished conditions)

Details

This is paired with movfit to find the correct movement model.

Value

A markov movement matrix

Author(s)

T. Carruthers

Examples

Prob_staying<-0.8 # probability  that individuals remain in area 1 between time-steps
Frac_area_1<-0.35 # the fraction of the stock found in area 1 under equilibrium conditions
markovmat<-getmov2(1,Prob_staying, Frac_area_1)
vec<-c(0.5,0.5) # initial guess at equilibrium distribution (2 areas)
for(i in 1:300)vec<-apply(vec*markovmat,2,sum) # numerical approximation to stable distribution
c(markovmat[1,1],vec[1]) # pretty close right?

Search R session for MP

Description

Calls dynGet(), then get() in order to find the MP definition in the R session.

Usage

getMP(MP)

Arguments

MP

Character of MP name

Value

The function definition or an error message from try() if unsuccessful

Author(s)

Q. Huynh


Count independent variables for a MICE relationship at position x in a Rel list

Description

Count independent variables for a MICE relationship at position x in a Rel list

Usage

getnIVs(x, Rel)

Arguments

x

Position of a MICE relationship in the list Rel (MOM@Rel)

Rel

The list of MICE relationships (MOM@Rel)

Author(s)

T.Carruthers


Calculate selectivity curve

Description

Calculate selectivity curve

Usage

getsel(x, lens, lfs, sls, srs)

Arguments

x

Simulation number

lens

Matrix of lengths (nsim by nlengths)

lfs

Vector of length at full selection (nsim long)

sls

Vector of sigmas of ascending limb (nsim long)

srs

Vector of sigmas of descending limb (nsim long)


Get Reference Points from Stock Synthesis Output

Description

Reads biological reference points from one or more Stock Synthesis (SS3) model outputs and returns the requested quantities from the derived_quants table.

Usage

GetSSRefPoints(
  SSDir,
  Labels = c("annF_F01", "Dead_Catch_F01", "SSB_SPR", "annF_SPR", "Dead_Catch_SPR",
    "SSB_MSY", "SPR_MSY", "annF_MSY", "Dead_Catch_MSY", "Ret_Catch_MSY")
)

Arguments

SSDir

One of:

  • A character string giving the path to an SS3 output directory, passed to ImportSSReport().

  • A RepList object returned by ImportSSReport().

  • A plain list in RepList format, i.e. RepList[[1]].

Labels

Character vector of derived_quants labels to extract. Defaults to a standard set of F, catch, and biomass reference points:

  • "annF_F01", "Dead_Catch_F01" — F0.1 fishing mortality and dead catch.

  • "SSB_SPR", "annF_SPR", "Dead_Catch_SPR" — SSB, F, and dead catch at the SPR target.

  • "SSB_MSY", "SPR_MSY", "annF_MSY", "Dead_Catch_MSY", "Ret_Catch_MSY" — SSB, SPR, F, dead catch, and retained catch at MSY.

Value

If SSDir contains a single model, a data frame with columns:

  • Label — the derived_quants label.

  • Value — the point estimate.

  • StdDev — the standard deviation.

If SSDir contains multiple models, a list of such data frames, one per model.

See Also

ImportSSReport()


Stock recruit parameterization

Description

Convert stock recruit parameters from steepness parameterization to alpha/beta (and vice versa)

Usage

hconv(alpha, phi0, SR = 1, type = 1)

R0conv(alpha, beta, phi0, SR = 1, type = 1)

SRalphaconv(h, phi0, SR = 1, type = 1)

SRbetaconv(h, R0, phi0, SR = 1, type = 1)

Arguments

alpha

Alpha parameter

phi0

Unfished spawners per recruit

SR

Stock-recruit function: (1) Beverton-Holt, or (2) Ricker

type

The parameterization of the Beverton-Holt function with respect to alpha and beta. See details.

beta

Beta parameter

h

Steepness parameter

R0

Unfished recruitment parameter

Details

The Type 1 Beverton-Holt equation is

R=αS/(1+βS)R = \alpha S/(1 + \beta S)

The Type 2 Beverton-Holt equation is

R=S/(α+βS)R = S/(\alpha + \beta S)

The Ricker equation is

R=αSexp(βS)R = \alpha S \exp(-\beta S)

Value

A numeric.

Functions

  • hconv(): Returns steepness (h) from alpha and phi0

  • R0conv(): Returns unfished recruitment (R0) from alpha, beta, and phi0

  • SRalphaconv(): Returns alpha from h and phi0

  • SRbetaconv(): Returns beta from h, R0, and phi0

Author(s)

Q. Huynh


Internal Herm functions

Description

  • expandHerm expands the Herm list in SexPars to a matrix of fractions at age

  • checkHerm checks that each array in the list has dimension nsim x maxage+1 x nyears + proyears. For backwards compatibility, also converts matrices to arrays by adding the year dimension.

  • subsetHerm returns year-specific Herm values.

Usage

expandHerm(Herm, maxage, np, nsim)

checkHerm(Herm, maxage, nsim, nyears, proyears)

subsetHerm(Herm, y)

Arguments

Herm

A list of Hermaphroditic fractions at age

maxage

The maximum age of stocks being simulated

np

The total number of stocks being simulated

nsim

The number of simulations

nyears

The number of historical years

proyears

The number of projection years

y

The year to subset

Author(s)

T. Carruthers

Q. Huynh


hist Class and Accessor

Description

The hist object stores the complete historical time-series generated during a MSE spool-up, including population dynamics, exploitation history, reference points, and observational data. See hist for full documentation of all slots.

Usage

Hist(MSE = NULL)

Arguments

MSE

An mse object. If NULL (default), an empty hist object is returned.

Details

Users do not typically need to create or manipulate hist objects directly — they are generated automatically as part of Simulate() and stored in the Hist slot of the resulting mse object. Hist() is provided to extract that slot when needed.

Value

When MSE is supplied, a timeseries object extracted from the Hist slot of the mse object. Note this is a timeseries and not a hist — slots such as OM, Unfished, and Reference are stored directly on the parent mse object to avoid duplication. When MSE = NULL, an empty hist object is returned.

See Also

hist, mse, timeseries, Simulate()


hist Class

Description

The hist class stores the complete historical time-series generated from an om object. It extends the timeseries with the originating operating model, unfished reference states, biological reference points, and associated observational data. Objects of this class are typically created by running Simulate(), and serve as the starting point for forward projections in the MSE.

Slots

OM

The om object used to generate the historical time-series.

Unfished

An unfished object containing two popdynamics sub-objects:

  • Equilibrium: Unfished equilibrium population dynamics, used as the baseline for computing biological reference points such as B0 and SSB0.

  • Dynamic: Unfished dynamic population trajectories, representing the counterfactual population in the absence of fishing over the historical period.

Reference

A reference object containing biological and management reference points.

Data

A nested named list of data objects containing historical observations generated during the spool-up phase. The list has two levels:

  • Level 1 (nSim elements, or length 1 if all simulations are identical): one entry per simulation.

  • Level 2 (one entry per stock or stock complex defined in the om): a data object holding the observations for that stock/complex.

Log

Internal named list storing diagnostics, warnings, and bookkeeping information generated during the historical simulation. Not intended for direct user access.

Misc

Named list for carrying arbitrary additional objects alongside the historical results. Useful for attaching model-specific diagnostics or intermediate outputs.

Number

List of numbers-at-age arrays, one element per stock. Each array has dimensions ⁠Sim × Age × Year × Area⁠.

Biomass

Total biomass array with dimensions ⁠Sim × Stock × Year⁠.

SBiomass

Spawning biomass array with dimensions ⁠Sim × Stock × Year⁠.

SProduction

Spawning production array with dimensions ⁠Sim × Stock × Year⁠.

Interactions

Total biomass interacting with fishing gear, by stock and fleet. Array with dimensions ⁠Sim × Stock × Year × Fleet⁠.

Landings

Total landed biomass by stock and fleet. Array with dimensions ⁠Sim × Stock × Year × Fleet⁠.

Discards

Total discarded biomass by stock and fleet. Array with dimensions ⁠Sim × Stock × Year × Fleet⁠.

InteractAtAge

List of interactions-at-age arrays (numbers), one element per stock. Each array has dimensions ⁠Sim × Age × Year × Fleet × Area⁠.

LandingsAtAge

List of landings-at-age arrays (numbers), one element per stock. Each array has dimensions ⁠Sim × Age × Year × Fleet × Area⁠.

DiscardsAtAge

List of discards-at-age arrays (numbers), one element per stock. Each array has dimensions ⁠Sim × Age × Year × Fleet × Area⁠.

LandingsAtSize

Nested list of landings-at-size arrays (numbers), indexed by stock then fleet. Each array has dimensions ⁠Sim × Class × Year × Area⁠.

DiscardsAtSize

Nested list of discards-at-size arrays (numbers), indexed by stock then fleet. Each array has dimensions ⁠Sim × Class × Year × Area⁠.

Effort

Fishing effort array with dimensions ⁠Sim × Year × Fleet⁠.

Distribution

Fleet effort distribution across areas. Array with dimensions ⁠Sim × Year × Fleet × Area⁠.

FInteract

Apical fishing mortality for fish that interact with the fishing gear. Array with dimensions ⁠Sim × Stock × Year × Fleet⁠ (array.null).

FDead

Apical fishing mortality for fish killed by the fishing gear. Array with dimensions ⁠Sim × Stock × Year × Fleet⁠ (array.null).

FRetain

Apical fishing mortality for fish retained by fishers. Array with dimensions ⁠Sim × Stock × Year × Fleet⁠ (array.null).

FInteractArea

Area- and age-specific fishing mortality for fish interacting with the gear, as a list by stock. Each element has dimensions ⁠Sim × Age × Year × Fleet × Area⁠ (array.list.null).

FDeadArea

Area- and age-specific fishing mortality for fish killed by the gear, as a list by stock. Each element has dimensions ⁠Sim × Age × Year × Fleet × Area⁠ (array.list.null).

FRetainArea

Area- and age-specific fishing mortality for retained fish, as a list by stock. Each element has dimensions ⁠Sim × Age × Year × Fleet × Area⁠ (array.list.null).

See Also

om, unfished, reference, timeseries, data, popdynamics


Class 'Hist'

Description

An object for storing information generated by the end of the historical simulations

Slots

Data

The Data object at the end of the historical period

OMPars

A numeric data.frame with nsim rows with sampled Stock, Fleet, Obs, and Imp parameters.

AtAge

A named list with arrays of dimensions: c(nsim, maxage+1, nyears+proyears) or c(nsim, maxage+1, nyears, nareas)

  • Length: Length-at-age for each simulation, age, and year

  • Weight: Weight-at-age for each simulation, age, and year

  • Select: Selectivity-at-age for each simulation, age, and year

  • Retention: Retention-at-age for each simulation, age, and year

  • Maturity: Maturity-at-age for each simulation, age, and year

  • N.Mortality: Natural mortality-at-age for each simulation, age, and year

  • Z.Mortality: Total mortality-at-age for each simulation, age, year and area

  • F.Mortality: Fishing mortality-at-age for each simulation, age, year and area

  • Fret.Mortality: Fishing mortality-at-age for retained fish for each simulation, age, year and area

  • Number: Total numbers by simulation, age, year and area

  • Biomass: Total biomass by simulation, age, year and area

  • VBiomass: Vulnerable biomass by simulation, age, year and area

  • SBiomass: Spawning biomass by simulation, age, year and area

  • Removals: Removals (biomass) by simulation, age, year and area

  • Landings: Landings (biomass) by simulation, age, year and area

  • Discards: Discards (biomass) by simulation, age, year and area

TSdata

A named list with population and fleet dynamics:

  • Number: Total numbers; array dimensions c(nsim, nyears, nareas)

  • Biomass: Total biomass; array dimensions c(nsim, nyears, nareas)

  • VBiomass: Vulnerable biomass; array dimensions c(nsim, nyears, nareas)

  • SBiomass: Spawning Biomass; array dimensions c(nsim, nyears, nareas)

  • Removals: Removals (biomass); array dimensions c(nsim, nyears, nareas)

  • Landings: Landings (biomass); array dimensions c(nsim, nyears, nareas)

  • Discards: Discards (biomass); array dimensions c(nsim, nyears, nareas)

  • Find: Historical fishing mortality (scale-free); matrix dimensions c(nsim, nyears)

  • RecDev: Recruitment deviations (historical and projection); matrix dimensions c(nsim, nyears+proyears+maxage)

  • SPR: Named list with Equilibrium and Dynamic SPR (both matrices iwth dimensions c(nsim, nyears))

  • Unfished_Equilibrium: A named list with unfished equilibrium numbers and biomass-at-age

Ref

A named list with biological reference points:

  • ByYear: A named list with asymptotic reference points (i.e., calculated annually without recruitment deviations) all matrices with dimensions nsim by nyears+proyears:

    • N0: Asymptotic unfished total number

    • SN0: Asymptotic unfished spawning number

    • B0: Asymptotic unfished total biomass

    • SSB0: Asymptotic unfished spawning biomass

    • VB0: Asymptotic unfished vulnerable biomass

    • MSY: Asymptotic MSY

    • FMSY: Fishing mortality corresponding with asymptotic MSY

    • SSBMSY: Spawning stock biomass corresponding with asymptotic MSY

    • BMSY: total biomass corresponding with asymptotic MSY

    • VBMSY: Vulnerable biomass corresponding with asymptotic MSY

    • F01: Fishing mortality where the change in yield per recruit is 10% of that at F = 0

    • Fmax: Fishing mortality that maximizes yield per recruit

    • F_SPR: Fishing mortality corresponding to spawning potential ratio of 20 - 60% in increments of 5%; array dimensions c(nsim, 9, nyears+proyears)

    • Fcrash: Fishing mortality corresponding to the recruits-per-spawner at the origin of the stock-recruit relationship

    • Fmed: Fishing mortality corresponding to the median recruits-per-spawner in the historical period

    • SPRcrash: SPR corresponding to the recruits-per-spawner at the origin of the stock-recruit relationship

  • Dynamic_Unfished: A named list with dynamic unfished reference points for each simulation and year:

    • N0: Unfished total numbers

    • B0: Unfished total biomass

    • SN0: Unfished spawning numbers

    • SSB0: Unfished spawning biomass

    • VB0: Unfished vulnerable biomass

    • Rec: Unfished recruitment

  • ReferencePoints: A data.frame with nsim rows with with biological reference points calculated as an average over age-of-maturity ageM years around the current year (i.e. nyears):

    • N0: Average unfished numbers

    • B0: Average unfished biomass

    • SSB0: Average unfished spawning biomass (used to calculate depletion)

    • SSN0: Average unfished spawning numbers

    • VB0: Average unfished vulnerable biomass (used to calculate depletion if cpar$control$D='VB')

    • MSY: Average maximum sustainable yield (equilibrium)

    • FMSY: Average fishing mortality corresponding with MSY

    • SSBMSY: Average spawning stock biomass corresponding with MSY

    • BMSY: Average total biomass corresponding with MSY

    • VBMSY: Average vulnerable biomass corresponding with MSY

    • UMSY: Average exploitation rate corresponding with MSY

    • FMSY_M: Average FMSY/M ratio

    • SSBMSY_SSB0: Average ratio of SSBMSY to SSB0

    • BMSY_B0: Average ratio of BMSY to B0

    • VBMSY_VB0: Average ratio of VBMSY to VB0

    • RefY: Maximum yield obtained in forward projections with a fixed F

SampPars

A named list with all sampled Stock, Fleet, Obs, and Imp parameters

OM

The OM object (without cpars)

Misc

A list for additional information

Author(s)

A. Hordyk


Wrapper for histogram function

Description

Produces a blank plot if all values in x are equal

Usage

hist2(x, col, axes = FALSE, main = "", breaks = 10, cex.main = 1)

Arguments

x

A vector of values

col

Colour of the histogram

axes

Logical - should axes be included?

main

Character - main title

breaks

Number of breaks. See ?hist for more details

cex.main

Text size of the main title


HistDescription

Description

A data.frame with description of slots for class Hist

Usage

HistDescription

Format

An object of class data.frame with 76 rows and 2 columns.


Imp Constructor and Accessor

Description

Construct an imp object defining implementation error for TAC, effort, and size-based management controls, or extract the Imp slot from an enclosing object.

Usage

Imp(Name = NULL, TAC = NULL, Effort = NULL, Size = NULL, Misc = list())

Arguments

Name

character(1) or an S4 object. Unique identifier for this implementation error model. Default NULL.

If Name is an om object, Imp() returns Name@Imp rather than constructing a new object. See Pass-Through Access in Details.

TAC

An impslot object, or NULL (default). Implementation error for total allowable catch recommendations. When NULL, an empty impslot is created via ImpSlot().

Effort

An impslot object, or NULL (default). Implementation error for effort-based controls. When NULL, an empty impslot is created via ImpSlot().

Size

An impslot object, or NULL (default). Implementation error for size-based regulations (e.g. minimum landing size). When NULL, an empty impslot is created via ImpSlot().

Misc

List. Miscellaneous additional objects. Default list().

Details

Pass-Through Access

When Name is an om object, Imp() acts as an accessor and returns Name@Imp directly. This allows a consistent interface for both construction and retrieval:

imp_obj <- Imp(om)          # extract from OM
Imp(om) <- Imp("MyImp")    # assign to OM

Sub-object initialisation

When any of TAC, Effort, or Size is NULL, an empty impslot object is created automatically so that the returned imp object is always fully populated and valid.

Placeholder status

The imp is currently a placeholder. The class interface is subject to change.

Value

  • Imp() returns a new imp object when Name is NULL or a character string.

  • Imp() returns Name@Imp (an imp object) when Name is an om object.

  • ⁠Imp<-⁠ returns x with the Imp slot replaced.

  • TAC(), EffortImp(), SizeImp() return the corresponding impslot slot from an imp object x.

  • ⁠TAC<-⁠, ⁠EffortImp<-⁠, ⁠SizeImp<-⁠ return x with the named slot replaced.

See Also

  • imp for the class definition.

  • impslot and ImpSlot() for the sub-object constructor and slot-level accessors.

  • OM() for the operating model constructor.

  • Advice() for the advice object connected to implementation.

  • ConvertImp() for converting legacy implementation objects.

Other imp: ImpSlot(), imp-class, impslot-class


Implementation Error

Description

The imp defines implementation error associated with management advice, controlling how management recommendations (TAC, effort, and size limits) are imperfectly applied in the operating model.

Details

Each of the TAC, Effort, and Size slots is an impslot object containing Mean, SD, Compliance, and Error arrays that together describe how imperfectly the corresponding management control is implemented across simulations.

An imp object can be attached to an om object and retrieved with Imp(om).

Direct construction via methods::new() is not recommended; use Imp() instead, which initialises all sub-objects automatically.

Slots

Name

Character. Name of the implementation error model. See Imp().

TAC

An impslot object. Implementation error for total allowable catch recommendations. See Imp().

Effort

An impslot object. Implementation error for effort-based controls. See Imp().

Size

An impslot object. Implementation error for size-based regulations. See Imp().

Misc

List. Miscellaneous additional objects.

Note

The imp is currently a placeholder. The class interface is subject to change.

See Also

  • Imp() for the constructor and accessor.

  • ImpSlot() for the sub-object constructor and slot-level accessors.

  • OM() for the operating model constructor.

  • Advice() for the advice object connected to implementation.

  • ConvertImp() for converting legacy implementation objects.

Other imp: Imp(), ImpSlot(), impslot-class


Class 'Imp'

Description

An operating model component that specifies the degree of adherence to management recommendations (Implementation error)

Slots

Name

The name of the Implementation error object. Single value. Character string.

Name

The name of the Implementation error object. Single value. Character string.

TACFrac

Mean fraction of recommended TAC that is actually taken. For each historical simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This value is the mean TAC fraction obtained across all years of that simulation, and a yearly TAC frac is drawn from a log-normal distribution with the simulation mean and a coefficient of variation specified by the value of TACSD drawn for that simulation. If the value drawn is greater than 1 the amount of catch taken is greater than that recommended by the TAC, and if it is less than 1 the amount of catch taken is less than that recommended by the TAC. Positive real numbers.

TACSD

Log-normal coefficient of variation in the fraction of recommended TAC that is actually taken. For each historical simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This value is used, along with the TACFrac drawn for that simulation, to create a log-normal distribution that yearly values specifying the actual amount of catch taken are drawn from. Positive real numbers.

TAEFrac

Mean fraction of recommended TAE that is actually taken. For each historical simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This value is the mean TAE fraction obtained across all years of that simulation, and a yearly TAE frac is drawn from a log-normal distribution with the simulation mean and a coefficient of variation specified by the value of TAESD drawn for that simulation. If the value drawn is greater than 1 the amount of effort employed is greater than that recommended by the TAE, and if it is less than 1 the amount of effort employed is less than that recommended by the TAE. Positive real numbers.

TAESD

Log-normal coefficient of variation in the fraction of recommended TAE that is actually taken. For each historical simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This value is used, along with the TAEFrac drawn for that simulation, to create a log-normal distribution that yearly values speciying the actual amount of efort employed are drawn from. Positive real numbers.

SizeLimFrac

Mean fraction of recommended size limit that is actually retained. For each historical simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This value is the mean size limit fraction obtained across all years of that simulation, and a yearly size limit fraction is drawn from a log-normal distribution with the simulation mean and a coefficient of variation specified by the value of SizeLimSD drawn for that simulation. If the value drawn is greater than 1 the size of fish retained is greater than that recommended by the size limit, and if it is less than 1 the amount of size of fish retained is less than that recommended by the size limit. Positive real numbers.

SizeLimSD

Log-normal coefficient of variation in the fraction of recommended size limit that is actually retained. For each historical simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This value is used, along with the SizeLimFrac drawn for that simulation, to create a log-normal distribution that yearly values speciying the actual fraction of the size limit retained are drawn from. Positive real numbers.

Objects from the Class

Objects can be created by calls of the form new('Imp')#'

Author(s)

T. Carruthers and A. Hordyk

Examples

showClass('Imp')

ImpDescription

Description

A data.frame with description of slots for class Imp

Usage

ImpDescription

Format

An object of class data.frame with 7 rows and 2 columns.


Import BAM Output into an Operating Model

Description

Imports output from the Beaufort Assessment Model (BAM) and converts it into an operating model (OM()) object. Stock and fleet objects are populated from BAM parameters and time series, including selectivity, retention, discard mortality, recruitment deviations, and stock-recruitment relationships.

Usage

ImportBAM(
  Stock = "Red Snapper",
  nSim = 48,
  pYear = 30,
  StockName = NULL,
  Source = NULL,
  DiscMortDF = NULL,
  DiscFleets = NULL,
  DiscSelFleets = NULL,
  RetSelFleets = NULL,
  incData = TRUE,
  SurveyNames = NULL,
  UnitsLandings = NULL,
  UnitsDiscards = NULL,
  populate = TRUE,
  silent = FALSE
)

GetBAMOutput(Stock = "Red Snapper", type = c("rdat", "dat"))

ListBAMStocks(type = c("rdat", "dat"))

Arguments

Stock

Character string matching a stock name available in bamExtras (e.g., 'Red Snapper'), or a list of BAM output objects containing elements rdat and dat.

nSim

Integer. Number of simulations. Default 48.

pYear

Integer. Number of projection years. Default 30.

StockName

Optional character string to override the species name taken from the BAM output.

Source

Optional. Character string specifying the source (usually a link) for the OM.

DiscMortDF

Optional data.frame with columns Fleet, Value, and Year specifying discard mortality rates by fleet and time block. If NULL, values are extracted directly from BAM parameters.

DiscFleets

Optional named character vector mapping retain fleet names to their corresponding discard fleet names in the BAM output, for cases where naming conventions differ.

DiscSelFleets

Optional named character vector mapping retain fleet names to the selectivity series to use for discards.

RetSelFleets

Optional named character vector mapping retain fleet names to alternative retention selectivity series.

incData

Logical. Include Data in the input? Default = TRUE

SurveyNames

A character vector of user-facing names for survey indices detected in BAMdata. Must have the same length as the number of survey indices found (i.e. indices not matched to any fleet name). Use this to override the default names derived from column names. Used by ImportBAMData().

UnitsLandings

A character vector of length equal to the number of landings fleets detected. Each element must be one of:

  • "1000 lb" — values will be converted from thousands of pounds to kg.

  • "1000 n" — values will be multiplied by 1,000 (number in thousands). Used by ImportBAMData().

UnitsDiscards

A character vector of length equal to the number of discard fleets detected. Accepts the same values as UnitsLandings. Used by ImportBAMData().

populate

Logical. If TRUE (default), calls PopulateOM() to populate the OM after construction.

silent

Logical. If TRUE, suppresses console messages. Default FALSE.

type

Character. Format of BAM output to retrieve: 'rdat' (default) returns the R data object; 'dat' returns the raw input data.

Value

ImportBAM() returns a populated OM object. GetBAMOutput() returns a BAM output list of class BAMdata (for type = 'rdat'). ListBAMStocks() returns a character vector of available stock names.

ImportBAM() requires the bamExtras package, which can be installed with pak::pkg_install('nikolaifish/bamExtras').

The DiscMortDF argument accepts a data.frame with columns:

Fleet

Fleet name matching the retain fleet names in the OM.

Value

Discard mortality rate (0–1).

Year

The year which the value takes effect (i.e., the value applies to all years after this year).

When DiscFleets, DiscSelFleets, or RetSelFleets are provided, they should be named character vectors where names are the retain fleet names and values are the corresponding BAM fleet/selectivity names to use instead of the defaults.

See Also

ImportBAMData()


Import BAM Assessment Data into an Operating Model

Description

Populates the Data and Obs slots of an om object with observed time-series data extracted from a BAM stock assessment. Landings, discards, fleet CPUE indices, and independent survey indices are imported and stored in the appropriate data sub-objects. Survey selectivity schedules are stored in the corresponding obs objects so that the data object holds the observed values and the obs object records how those data were generated.

Usage

ImportBAMData(
  OM,
  BAMdata,
  SurveyNames = NULL,
  UnitsLandings = NULL,
  UnitsDiscards = NULL,
  DiscFleets = NULL
)

Arguments

OM

An om object.

BAMdata

A named list returned by GetBAMOutput() or directly from the bamExtras pacakge.

SurveyNames

A character vector of user-facing names for survey indices detected in BAMdata (i.e. ⁠U.*⁠ columns not matched to any fleet name, excluding discard indices). Must have the same length as the number of such surveys detected. If NULL, names are derived from the BAM column names directly.

UnitsLandings

A named character vector or list mapping fleet names to unit strings. Names must be a subset of FleetNames(); fleets not present are assigned NA units with no conversion applied. Supported unit strings:

  • "1000 lb": converts from thousands of pounds to kg.

  • "1000 n": multiplies by 1,000 (numbers in thousands). If NULL, "1000 lb" is assumed for all detected landings fleets with a warning.

UnitsDiscards

A named character vector or list following the same convention as UnitsLandings, applied to discard columns (⁠D.*⁠).

DiscFleets

A character vector of BAM discard column name stubs used to rename discard fleets after import. Names are expected in the form "F.FleetName.D", from which the middle component (e.g. "FleetName") is extracted and used as the fleet label. If NULL, no renaming is applied.

Details

Fleet matching

Fleet CPUE columns are identified by searching ⁠U.*⁠ column names in BAMdata$t.series for strings matching FleetNames(). Matched columns are stored in ⁠@CPUE⁠; unmatched ⁠U.*⁠ columns (excluding those containing .D., which are discard CPUE) are stored in ⁠@Survey⁠.

Unit conversion

Conversion is applied fleet-by-fleet using UnitsLandings and UnitsDiscards. Fleets present in the OM but absent from the units argument receive NA units and their values are left unconverted.

Age and length composition

Composition data are not yet imported. Planned sources are ⁠BAMdata$comp.mats$*age*⁠ (age composition) and BAMdata$comp.mats$lcomp.*.ob (length composition).

Value

The OM object with two slots updated:

  • OM@Data[[1]]: a data object containing:

    • ⁠@CPUE⁠: an indicesdata object with fleet-matched CPUE indices and CVs.

    • ⁠@Survey⁠: an indicesdata object with unmatched (non-fleet) survey indices and CVs.

    • ⁠@Landings⁠: a catchdata object with landings by fleet, converted to metric units where specified.

    • ⁠@Discards⁠: a catchdata object with discards by fleet, converted to metric units where specified.

  • OM@Obs[[1]]: updated with a named obs entry for each survey, containing the selectivity-at-age schedule matched from BAMdata$sel.age. If no matching selectivity is found for a survey, full selection across all age classes is assumed and a warning is issued.

See Also

GetBAMOutput(), Data(), CatchData(), Obs()

Examples

## Not run: 
bam <- GetBAMOutput('Red Snapper')
OM <- ImportBAMData(
  OM            = myOM,
  BAMdata       = bam,
  SurveyNames   = c("VideoSurvey", "TrawlSurvey"),
  UnitsLandings = c(CommFleet = "1000 lb", RecFleet = "1000 lb"),
  UnitsDiscards = c(CommFleet = "1000 n"),
  DiscFleets    = c("F.CommFleet.D", "F.RecFleet.D")
)

## End(Not run)

Import a Stock Synthesis Model into an Operating Model

Description

Import a Stock Synthesis 3 (SS3) model and convert it into an OM() object.

Usage

ImportSS(
  SSDir,
  Name = "Imported SS3 Model",
  nSim = 48,
  pYear = 30,
  Agency = "",
  Author = "",
  Email = "",
  Region = "",
  Latitude = numeric(),
  Longitude = numeric(),
  Sponsor = "",
  StockName = NULL,
  CommonName = NULL,
  Species = NULL,
  FleetNames = NULL,
  Interval = 1,
  DataLag = 0,
  silent = FALSE,
  Populate = TRUE,
  ...
)

Arguments

SSDir

Character string giving the path to a directory containing SS3 output files, a vector of such paths, or a list of SS3 report objects generated by ImportSSReport()

Name

Character string giving the name of the imported operating model.

nSim

Integer specifying the number of simulations. Ignored if multiple SS3 runs are detected; in that case nSim is set to the number of SS3 runs imported.

pYear

Integer specifying the number of projection years.

Agency

Character string giving the management or scientific agency.

Author

Character string giving the model author(s).

Email

Character string giving the author(s) email address.

Region

Character string describing the geographic region.

Latitude

Numeric vector giving stock latitude(s).

Longitude

Numeric vector giving stock longitude(s).

Character string giving the project sponsor.

StockName

Optional character vector of stock names. Length must match the number of stocks inferred from the SS3 model.

CommonName

Optional character vector of common names for each stock.

Species

Optional character vector of species names for each stock.

FleetNames

Optional character vector of fleet names. If NULL, fleet names are inferred from SS3 output.

Interval

Integer specifying the number of years between management actions.

DataLag

Integer specifying the observation lag in years.

silent

Logical; if TRUE, suppress informational output during import.

Populate

Logical; if TRUE (default), populate the OM using PopulateOM(). If FALSE, return the partially constructed OM.

...

Additional arguments passed to SS3 import functions.

Details

ImportSS() reads SS3 output files from SSDir and constructs an OM() object. Biological processes, fleet structure, and historical time series are inferred directly from the SS3 report output and mapped into the corresponding OM slots.

  • Multiple simulation replicates are supported when multiple SS3 runs are detected.

  • Optional metadata describing authorship, region, and stock identity are stored in the resulting OM.

  • By default, the OM is fully populated using PopulateOM().

  • Set Populate = FALSE to return the partially constructed OM.

ImportSSReport() reads SS3 output generated by Stock Synthesis 3, either from one or more directories or from existing r4ss report objects, and returns a standardized list of SS3 report lists.

Value

  • ImportSS() returns an om object containing stock, fleet, data, observation, and allocation components derived from the SS3 model.

  • ImportSSReport() returns a list of SS3 report objects.

Functions

  • ImportSS() Convert SS3 output into a fully specified operating model suitable for management strategy evaluation.

  • ImportSSReport() Read SS3 output from directories or existing r4ss report objects and return a standardized list of SS3 reports.

See Also

Examples

## Not run: 
## Path to a directory containing SS3 output
ss_dir <- "path/to/SS3/output"

## Read SS3 output only
reps <- ImportSSReport(ss_dir)

## Build an operating model from SS3 output
OM <- ImportSS(
  SSDir = reps,
  Name = "Example SS3 Import",
  Author = "A. Scientist",
  Region = "Example Region",
  StockName = "ExampleStock",
  FleetNames = c("Commercial", "Recreational")
)

## Inspect imported stocks and fleets
StockNames(OM)
FleetNames(OM)

## End(Not run)

Import SS3 data into a Data object

Description

Reads a parsed SS3 report and populates a data object with catch, index, and composition data.

Usage

ImportSSData(
  SSDir,
  Name = "Imported by ImportSSData",
  CommonName = "",
  Species = "",
  silent = FALSE,
  ...
)

Arguments

SSDir

Character vector of SS3 report directories, or a pre-parsed r4ss::SS_output list or RepList object returned by ImportSSReport().

Name

Character; name for the Data object

CommonName

Character; common name of the species

Species

Character; scientific name of the species

silent

Logical; suppress progress messages (default FALSE)

...

Additional arguments passed to ImportSSReport

Value

A populated Data() object


Import SS3 Report directories with optional parallel processing

Description

Import SS3 Report directories with optional parallel processing

Usage

ImportSSReport(SSDir, parallel = FALSE, silent = FALSE, ...)

Arguments

SSDir

Character vector of SS3 report directories, or a pre-parsed r4ss::SS_output list or RepList object

parallel

Logical; whether to use parallel processing (default FALSE)

silent

Logical; suppress progress messages (default FALSE)

...

Additional arguments passed to r4ss::SS_output and GetSSRepList

Value

A named RepList object: a list of parsed r4ss::SS_output lists, one per SS3 directory, with integer-character names ("1", "2", ...)

See Also

ImportSS(), SetupParallel(), DisableParallel()


ImpSlot Constructor and Accessors

Description

Construct an impslot object representing implementation uncertainty for a single management control, or access and replace individual slots.

Usage

ImpSlot(Mean = NULL, SD = NULL, Compliance = NULL, Error = NULL, Misc = list())

Arguments

Mean

Numeric array or list of arrays, or NULL (default). Mean implemented fraction of the management recommendation (e.g. 1 = perfect compliance with the TAC). When NULL, the slot is left at its class default.

SD

Numeric array or list of arrays, or NULL (default). Standard deviation of implementation error around Mean. When NULL, the slot is left at its class default.

Compliance

Numeric array or list of arrays, or NULL (default). Compliance rate, i.e. the proportion of the fleet that adheres to the management control. Values should be in [0,1][0, 1]. When NULL, the slot is left at its class default.

Error

Numeric array or list of arrays, or NULL (default). Realised implementation error. When supplied directly, Mean, SD, and Compliance are stored but Error is not re-derived from them during simulation — the user-supplied values are used as-is. When NULL, Error is stochastically generated from Mean, SD, and Compliance at simulation time.

Misc

List. Miscellaneous additional objects. Default list().

Details

Mean, SD, and Compliance

Mean and SD together parameterise a lognormal (or other distributional) implementation error applied to the management recommendation each simulation year. Compliance scales the effective error by the fraction of the fleet that actually adheres to the control; the remainder is assumed to operate without constraint.

Error

If Error is supplied, it is stored directly in the slot and used during simulation without further stochastic derivation. This is useful for conditioning on historically observed deviations or for deterministic sensitivity runs. If Error is NULL (the default), it is generated from Mean, SD, and Compliance at simulation time.

Placeholder status

The impslot and its enclosing imp are currently placeholders. Dimensional requirements and validation rules will be formalised in a future release.

Value

  • ImpSlot() returns a new impslot object.

  • Mean(), SD(), Compliance(), Error() return the corresponding slot from an impslot object x.

  • ⁠Mean<-⁠, ⁠SD<-⁠, ⁠Compliance<-⁠, ⁠Error<-⁠ return x with the named slot replaced.

See Also

Other imp: Imp(), imp-class, impslot-class

Examples

# Empty impslot
sl <- ImpSlot()

# With Mean and SD specified
sl <- ImpSlot(Mean = 1, SD = 0.1, Compliance = 0.9)

# Supplying Error directly (bypasses stochastic generation)
sl <- ImpSlot(Error = array(rnorm(100, 1, 0.05), dim = c(10, 10)))

The indicesdata S4 Class

Description

Stores abundance or biomass index observations from fishery-dependent (CPUE) or fishery-independent (Survey) sources, including observation uncertainty, reference values, timing, and selectivity mapping. Used in the CPUE and Survey slots of a data object.

Value

IndicesData() returns a indicesdata object.

Slots

Name

Optional character string. Name of the index.

Value

Numeric array of observed index values, with dimensions ⁠[nYear, nIndex]⁠, where nYear represents the total number of time steps.

CV

Numeric array of coefficients of variation (CVs) for the index observations, matching the dimensions of Value.

Units

Optional character string. Units of the index (e.g., "kg/trip", "numbers/tow").

Ref

Numeric vector of length nIndex giving a reference value for each index (e.g., a historical mean or target level).

RefCV

Numeric array of CVs for the reference values, matching the dimensions of Ref.

Timing

Numeric vector of length nIndex giving the within-year timing of each observation as a fraction of the year (0–1).

Selectivity

An array or character specification mapping each index to a fleet selectivity or defining an independent selectivity curve.

Misc

A named list for any additional index-level metadata.

IndicesData() creates a new indicesdata object.

See Also

data, Data()


IndicesObs Constructor and Accessors

Description

Construct an indicesobs object defining observation error for a CPUE or survey abundance index, or access and replace individual slots.

Usage

IndicesObs(
  CV = NULL,
  Error = NULL,
  Areas = NULL,
  Units = NULL,
  Selectivity = NULL,
  TruncSD = 2,
  Ref = NULL,
  Beta = NULL,
  AC = NULL,
  Misc = list()
)

Arguments

CV

numeric or NULL. Coefficient of variation of the lognormal index observation error. Accepted forms:

  • NULL (default): no observation error is generated unless Error is supplied directly.

  • Length-1 scalar: a single CV applied uniformly across all simulations and years when generating the Error array internally.

  • Length-2 vector c(mean, sd): CV is itself drawn stochastically — a unique CV per simulation is generated via StructurePars() before being used to generate the Error array.

  • Length-nSim named array: used directly, one CV per simulation.

When conditioning on real data via ConditionObs(), CV is replaced by the simulation-specific standard deviation of historical log-residuals estimated by CalcResidualStats(). Ignored if Error is supplied directly.

Error

numeric array or NULL. Pre-specified lognormal observation error multipliers with dimensions ⁠nSim x nYear⁠ and named dimnames (Sim, Year). When supplied, Error is used directly and CV is ignored for error generation. When real index data are provided and ConditionObs() is run, Error is replaced by conditioned values regardless of whether it was user-supplied. Default NULL, in which case Error is generated from CV internally.

Areas

integer vector or NULL. Indices of the spatial areas that contribute to this index (e.g., c(1, 2) for a two-area model where the index covers only the first two areas). Default NULL, in which case all areas are used.

Units

character(1) or NULL. Units determining how the simulated population is converted to an index value. Must be one of:

  • "Biomass" (default): sum of numbers-at-age multiplied by weight-at-age over the selected ages and areas.

  • "Number": sum of numbers-at-age over the selected ages and areas.

  • "Recruitment": abundance of the youngest age class, summed over areas. For seasonal models, the first non-zero age class in each simulation and year is used. Default NULL (treated as "Biomass").

Selectivity

Selectivity specification for this index. Accepted forms:

  • NULL (default): for CPUE indices, the corresponding fleet selectivity from OM@Fleet is used automatically. For survey indices with no selectivity specified, a warning is issued and flat selectivity (all ages equally selected) is assumed.

  • "Biomass": flat selectivity of 1 for all age classes (equivalent to a biomass-weighted survey).

  • "SBiomass": maturity-at-age is used as selectivity (equivalent to a spawning biomass index).

  • "Obs": the selectivity array stored in this slot is used directly. In this case Selectivity must also contain the array (or list of arrays by stock) as set by the user.

TruncSD

numeric(1). Number of standard deviations at which to truncate the lognormal residual distribution when generating observation errors for projection years via GenResiduals(). Default 2.

Ref

numeric or NULL. Reference index value. Accepted forms:

  • NULL (default): no reference value.

  • Positive scalar: interpreted as the CV of a lognormal distribution; a unique reference value is drawn per simulation as rlnorm(nSim, mconv(1, Ref), sdconv(1, Ref)) internally.

  • Length-nSim vector or named array: used directly.

Beta

numeric or NULL. Hyperstability/hyperdepletion parameter relating true population size to the observed index. Reserved for future use; currently has no effect. Default NULL.

AC

numeric, array, or NULL. Lag-1 autocorrelation of index residuals, one value per simulation

Misc

list. Miscellaneous additional objects. Default list().

Details

Observation Error Generation

The Error array (⁠nSim x nYear⁠) is obtained in one of three ways, in order of precedence:

  1. User-supplied Error: stored directly; CV is not used.

  2. Stochastic from CV: if Error is NULL and CV is specified, Internally the model generates a lognormal array where each cell is rlnorm(1, mconv(1, CV[sim]), sdconv(1, CV[sim])). CV is first expanded to length nSim internally — a length-2 input triggers a stochastic draw of a unique CV per simulation.

  3. Conditioned from real data: ConditionObs() estimates CV, Efficiency, Stats, and Error from historical residuals; any user-supplied values are replaced.

Ref is expanded internally: a scalar is treated as the CV of a lognormal from which one reference value per simulation is drawn; a length-nSim input is used directly.

Conditioning on Real Data

When real index data are provided (via OM@Data) and ConditionObs() is run, the following slots are estimated and populated internally:

  • Efficiency (q): estimated as the ratio of the mean observed index to the mean simulated nominal index, averaged over non-NA years.

  • Stats: a data frame computed by CalcResidualStats() with columns Sim, AC (weighted lag-1 autocorrelation of log-residuals), SD (standard deviation of log-residuals), and NA_Season (a list-column indicating which seasons, if any, have no observations in any year).

  • Error: lognormal error multipliers covering both historical and projection years, generated by GenResiduals() using the estimated SD and AC, with projection errors propagated via ApplyAC().

The Efficiency, Stats, and Error slots are replaced during conditioning regardless of whether the user supplied Error directly.

Selectivity Notes

CPUE indices automatically use the fleet selectivity from OM@Fleet when Selectivity is NULL. For survey indices, the selectivity must be specified explicitly via one of the four forms described under the Selectivity parameter.

Attaching to an Obs Object

CPUE(obs)   <- IndicesObs(CV = 0.3)
Survey(obs) <- IndicesObs(CV = 0.2, Selectivity = "SBiomass")

Value

  • IndicesObs() returns an indicesobs object.

  • CPUE(), Survey() return the corresponding indicesobs slot from an obs object x.

  • ⁠CPUE<-⁠, ⁠Survey<-⁠ return x with the slot replaced.

See Also

Other obs: CatchObs(), CompObs(), EffortObs(), ExploitationObs(), LifeHistoryObs(), Obs(), catchobs-class, compobs-class, effortobs-class, exploitationobs-class, indicesobs-class, lifehistoryobs-class, obs-class

Examples

# Biomass CPUE with uniform 30% CV
io <- IndicesObs(CV = 0.3, Units = "Biomass")

# Stochastic CV — unique CV per simulation drawn from lognormal(mean=0.3, sd=0.05)
io <- IndicesObs(CV = c(0.3, 0.05), Units = "Biomass")

# Spawning biomass survey using maturity as selectivity
survey_obs <- IndicesObs(CV = 0.2, Selectivity = "SBiomass", TruncSD = 3)

# Index covering only areas 1 and 2
io <- IndicesObs(CV = 0.25, Areas = c(1L, 2L))

# Pre-specified error array — bypasses CV entirely
err <- array(rlnorm(48 * 20), dim = c(48, 20),
             dimnames = list(Sim = 1:48, Year = 2001:2020))
io <- IndicesObs(Error = err)

# Attach to an obs object
obs <- Obs(CPUE   = IndicesObs(CV = 0.3),
           Survey = IndicesObs(CV = 0.2, Selectivity = "SBiomass"))

The indicesobs S4 Class

Description

Defines the observation error structure for abundance or biomass indices (CPUE or survey). Used in the CPUE and Survey slots of an obs object. Objects are typically created via IndicesObs(), which documents all parameters in detail.

Slots

CV

numeric or NULL. Coefficient of variation of index observation error. See IndicesObs().

Error

numeric array or NULL. Lognormal observation error multipliers (⁠nSim x nYear⁠). May be supplied directly via IndicesObs(), generated stochastically from CV, or estimated from real data during ConditionObs(). See IndicesObs().

Beta

numeric array or NULL. Hyperstability/hyperdepletion parameter. Reserved for future use; currently not implemented. See IndicesObs().

AC

numeric array or NULL. Lag-1 autocorrelation of index residuals, one value per simulation. When supplied by the user, overrides the value estimated during conditioning. See IndicesObs().

Years

numeric or NULL. Calendar years over which the observation error is conditioned. See IndicesObs().

Areas

numeric or NULL. Integer indices of the spatial areas contributing to this index. See IndicesObs().

Units

character or NULL. Units of the index ("Biomass", "Number", or "Recruitment"). See IndicesObs().

Selectivity

array, character, numeric, or list. Selectivity specification for this index. See IndicesObs().

Type

character. Index type identifier. See IndicesObs().

Ref

numeric array or NULL. Reference index value, one per simulation. See IndicesObs().

Efficiency

numeric array or NULL. Catchability coefficient q relating the nominal index to the population quantity. Calculated internally during conditioning as the ratio of mean observed index to mean simulated index; not set by the user.

TruncSD

numeric(1) or NULL. Number of standard deviations at which to truncate the lognormal residual distribution when generating projection errors. Default 2. See IndicesObs().

Stats

data.frame or NULL. Residual statistics computed during conditioning by CalcResidualStats(). Contains columns Sim, AC (weighted lag-1 autocorrelation), SD (standard deviation), and NA_Season (a list-column of seasons with no observations). Populated internally; not set by the user.

Misc

list. Miscellaneous additional objects.

See Also

Other obs: CatchObs(), CompObs(), EffortObs(), ExploitationObs(), IndicesObs(), LifeHistoryObs(), Obs(), catchobs-class, compobs-class, effortobs-class, exploitationobs-class, lifehistoryobs-class, obs-class


~~ Methods for Function initialize ~~

Description

~~ Methods for Function initialize ~~

Methods

list('signature(.Object = \'DLM\')')

%% ~~describe this method here~~

list('signature(.Object = \'Fleet\')')

%% ~~describe this method here~~

list('signature(.Object = \'MSE\')')

%% ~~describe this method here~~

list('signature(.Object = \'Obs\')')

%% ~~describe this method here~~

list('signature(.Object = \'OM\')')

%% ~~describe this method here~~

list('signature(.Object = \'Stock\')')

%% ~~describe this method here~~

list('signature(.Object = \'Fease\')')

%% ~~describe this method here~~

list('signature(.Object = \'DLM_general\')')

%% ~~describe this method here~~


Function to run a set of input control methods

Description

Runs a set of input control methods are returns the output in a single table

Usage

Input(Data, MPs = NA, reps = 100, timelimit = 10, CheckMPs = TRUE, msg = TRUE)

Arguments

Data

A Data object

MPs

A list of input MPs, if NA all available input MPs are run

reps

Number of repetitions (for those methods that use them)

timelimit

Maximum timelimit to run MP (in seconds)

CheckMPs

Logical, the Can function is run if this is TRUE

msg

Logical. Should messages be printed?

Author(s)

A. Hordyk

Examples

## Not run: 
library(MSEtool)
Input(MSEtool::Cobia)

## End(Not run)

Reads iSCAM files into a hierarchical R list object

Description

Internal functions for reading iSCAM input and output files into R

Usage

load.iscam.files(model.dir, burnin = 1000, thin = 1, verbose = FALSE)

fetch.file.names(path, filename)

read.report.file(fn)

read.data.file(file = NULL, verbose = FALSE)

read.control.file(
  file = NULL,
  num.gears = NULL,
  num.age.gears = NULL,
  verbose = FALSE
)

read.projection.file(file = NULL, verbose = FALSE)

read.par.file(file = NULL, verbose = FALSE)

read.mcmc(model.dir = NULL, verbose = TRUE)

Arguments

model.dir

Folder name

burnin

The initial mcmc samples to be discarded

thin

The degree of chain thinning 1 in every thin iterations is kept

verbose

should detailed results be printed to console

path

File path

filename

The filename

fn

File location

file

File location

num.gears

The number of gears

num.age.gears

The number age-gears

Functions

  • load.iscam.files(): Wrapper function to generate R list

  • fetch.file.names(): A function for returning the three types of iSCAM input and output files

  • read.report.file(): A function for returning the results of the .rep iscam file

  • read.data.file(): A function for returning the results of the .dat iscam file

  • read.control.file(): A function for returning the results of the iscam control file

  • read.projection.file(): A function for returning the results of the iscam projection file

  • read.par.file(): A function for returning the results of the iscam .par file

  • read.mcmc(): A function for returning the results of the iscam mcmc files

Author(s)

Chris Grandin (DFO PBS)

See Also

iSCAM2OM


Reads MPD or MCMC estimates and data from iSCAM file structure into an operating model

Description

Functions for importing an iSCAM assessment. From a fitted model, iSCAM2OM populates the various slots of an operating model and iSCAM2Data generates a Data object. These functions rely on several functions written by Chris Grandin (DFO PBS).

Usage

iSCAM2OM(
  iSCAMdir,
  nsim = 48,
  proyears = 50,
  mcmc = FALSE,
  spawn_time_frac = 0,
  Name = "iSCAM model",
  Source = "No source provided",
  length_timestep = 1,
  nyr_par_mu = 2,
  Author = "No author provided",
  report = FALSE,
  silent = FALSE
)

iSCAM2Data(
  iSCAMdir,
  Name = "iSCAM assessment",
  Source = "No source provided",
  length_timestep = 1,
  Author = "No author provided"
)

Arguments

iSCAMdir

A folder with iSCAM input and output files in it. Alternatively, a list returned by load.iscam.files.

nsim

The number of simulations to take for parameters with uncertainty (for OM@cpars custom parameters)

proyears

The number of MSE projection years

mcmc

Logical, whether to use mcmc samples to create custom parameters cpars. Alternatively, a list returned by read.mcmc. Set the seed for the function to sub-sample the mcmc samples.

spawn_time_frac

Numeric between 0-1 indicating when spawning occurs within the time step

Name

The name of the operating model

Source

Reference to assessment documentation e.g. a url

length_timestep

How long is a model time step in years (e.g. a quarterly model is 0.25, a monthly model 1/12) (currently only uses annual time step)

nyr_par_mu

integer, the number of recent years to estimate vulnerability over for future projections

Author

Who did the assessment

report

logical should a numbers at age reconstruction plot be produced?

silent

logical should progress reporting be printed to the console?

Biological parameters

The function calls model <- load.iscam.files(iSCAMdir) and grabs the following matrices:

  • model$mpd$d3_weight_mat - fecundity (product of weight and maturity at age)

  • model$mpd$ma - maturity at age

MPD historical reconstruction

The function calls model <- load.iscam.files(iSCAMdir) and then grabs the following matrices:

  • model$mpd$N - abundance at age

  • model$mpd$F - fishing mortality at age

  • model$mpd$M - natural mortality at age

If a delay-difference model is recognized, then the following is used instead:

  • model$mpd$F_dd - fishing mortality at age

  • model$mpd$M_dd - natural mortality at age

Abundance at age is reconstructed using model$mpd$rt (recruitment) and projected with F_dd and M_dd to match model$mpd$numbers.

MCMC historical reconstruction

If mcmc = TRUE the function calls mcmc_model <- read.mcmc(iSCAMdir), and grabs nsim sub-samples of the MCMC output through the following arrays:

  • mcmc_model$params and mcmc_model$ft - fishing mortality at age from the fleet selectivity parameters and apical F's

  • mcmc_model$m - year-specific natural mortality at age

  • mcmc_model$params$rinit and mcmc_model$rt - recruitment and abundance

Start age

While the iSCAM start age can be greater than zero, abundance at age is back-calculated to age zero with M, maturity, growth = 0. In this way, the stock-recruit dynamics from iSCAM are preserved.

These arrays are then passed to Assess2OM to generate the operating model.

Reference points

iSCAM calculates the stock-recruit relationship and subsequently a single set of MSY and unfished reference points using R0, steepness, and unfished spawners per recruit from the mean M, fecundity, and growth (mean with respect to time).

R0 and h are recalculated for the operating model by obtaining the stock-recruit alpha and beta from the iSCAM parameters and the mean unfished spawners per recruit in the first ageM (age of 50% maturity) years.

Author(s)

T. Carruthers, Q. Huynh


Combines all iSCAM age composition data across fleets

Description

iSCAM assessments are often fitted to numerous fleets that have differing age selectivities. iSCAMcomps is a simple way of providing the aggregate catch at age data. It should be noted that this process is important and in a real application would require due diligence (ie peer reviewed data workshop).

Usage

iSCAMcomps(replist, Year)

Arguments

replist

S3 class object: the output from a read from an iSCAM data folder

Year

Integer vector: the years of the data object ie Data@Year

Author(s)

T. Carruthers


Combines indices into a single index using linear modelling (** Deprecated **)

Description

iSCAM assessments often make use of multiple indices of abundance. The data object and MPs currently only make use of a single index. combiSCAMinds is a function that creates a single index from many using linear modelling. It is a simple way of providing initial calculations of management recommendations and it should be noted that this process is important and in a real application would require due diligence (ie peer reviewed data workshop).

Usage

iSCAMinds(idata, Year, fleeteffect = T)

Arguments

idata

List: the indices recorded in a read from an iSCAM data folder, e.g. replist$data$indices

Year

Integer vector: the years of the data object ie Data@Year

fleeteffect

Logical: should a fleet effect be added to the linear model?

Author(s)

T. Carruthers


Test Whether an Object is a Default-Constructed Instance

Description

Returns TRUE if object is identical to a freshly constructed default instance of its class — i.e. the object has not been modified since construction. Used internally by EmptyObject().

Usage

isNewObject(object)

Arguments

object

An S4 object.

isNewObject() constructs a default instance of the same class as object and compares the two with identical(). Before comparing, the Name slot (if present) is set to NULL on object so that a user- supplied name alone does not cause the object to be considered non-default.

The default instance is obtained as follows:

  • For a small set of classes whose constructors do not follow the standard firstup(class)() naming convention (naturalmortality, srr, om, discardmortality), the appropriate constructor is called directly.

  • For all other classes, the constructor is looked up as get(firstup(class)). If no such constructor exists, new(class) is used as a fallback.

Value

A length-1 logical. Returns FALSE for non-S4 objects.

See Also

EmptyObject()


Plot several plots with a shared legend

Description

Plot several plots with a shared legend

Usage

join_plots(
  plots,
  ncol = length(plots),
  nrow = 1,
  position = c("right", "bottom"),
  legend = TRUE
)

Arguments

plots

list of plot objects of class gg or ggplot

ncol

Optional number of columns

nrow

Optional number of rows

position

position of the legend ("bottom" or "right")

legend

Logical. Use a legend?

Note

modified from https://github.com/tidyverse/ggplot2/wiki/share-a-legend-between-two-ggplot2-graphs


Join Data objects present in a list

Description

A function that combined a list of data objects into a single data object (same dimensions but can have different numbers of simulations)

Usage

joinData(DataList)

Arguments

DataList

A list of data objects of identical dimension (except for simulation)

Author(s)

T. Carruthers

See Also

joinMSE joinHist


Join Two Objects Along the Year Dimension

Description

Recursively combines two objects of the same structure by appending object2 after object1 along the year dimension. Handles S4 objects, lists, named arrays, and numeric vectors. Intended for joining early and late year segments of MSEtool data objects (e.g. historical and projection periods).

Usage

JoinYear(object1, object2)

Arguments

object1

The earlier object. Must have years that precede those in object2. Can be an S4 object, a list, a named array with a "Year" dimension, or a numeric vector.

object2

The later object with the same structure as object1. Its years must be strictly greater than those in object1.

Details

JoinYear recurses through the structure of object1 and object2 in parallel, dispatching on the type of each element:

  • S4 objects — each slot is processed recursively via Recall().

  • Lists — each element is processed recursively via Recall().

  • Named arrays with a "Year" dimension — joined along the year axis using abind::abind(). An error is thrown if years are not strictly increasing across object1 and object2.

  • Numeric vectors — concatenated with c(). If all values exceed 1000 (i.e. are likely calendar years), strict monotonicity is checked and an error is thrown if the combined sequence is not increasing.

  • All other types — returned unchanged from object1.

Value

An object of the same class and structure as object1, with object2 appended along the year dimension. Non-array, non-numeric, and non-list slots or elements are returned unchanged from object1.

Error handling

If years are not strictly increasing across the two objects, cli::cli_abort() is called with a diagnostic message showing the year values from both objects and a hint that the arguments may be in the wrong order.

See Also

abind::abind()


KOBE plot: a projection by projection plot of F/FMSY and B/BMSY

Description

A standard KOBE plot by each method that also shows the percentage of methods that ended up in each quadrant.

Usage

Kplot(
  MSEobj,
  maxsim = 60,
  MPs = NA,
  sims = NULL,
  maxMP = 9,
  nam = NA,
  cex.leg = 1.5
)

Arguments

MSEobj

An object of class MSE

maxsim

Maximum number of simulations (lines) to plot on each panel.

MPs

Optional subset MSE object by MP

sims

Optional subset MSE object by simulation

maxMP

Maximum number of MPs to include in plot

nam

The name of the plot

cex.leg

Size of legend

Note

Apologies for the nauseating shading.

Author(s)

T. Carruthers with some additions from A. Hordyk


Lag the time-series slots in a Data object by a specified number of time-steps

Description

Lag the time-series slots in a Data object by a specified number of time-steps

Usage

Lag_Data(Data, Data_Lag = 0, msg = FALSE)

Arguments

Data

An object of class Data

Data_Lag

Either a numeric vector of length 1 with a positive number specifying the number of time-steps to lag all time-series data, or a named list with numeric values (length 1). See details for more information.

msg

Logical. Display the messages?

Details

By default, all simulated data in the forward projections are provided up to the previous time-step. That is, in projection year t, the simulated data are up to and including t-1. This function will lag the time-series values by the specified value. For example, Data_Lag=5 will mean in projection time-step t the data will be up to and including t-6.

Note: The Data@Year slot is not lagged by this function. Many built-in MPs use the length of Data@Year to determine the number of years of data for smoothing over recent years etc. This may not be appropriate so check the MP is behaving as you expect if you use Lag_Data.

Value

An object of class Data with time-series slots lagged.

Examples

# Lag all time-series slots by 2 time-steps (usually years)
Data <- Example_datafile
Lagged_1 <- Lag_Data(Data, 2)
length(Data@Year)
length(Lagged_1@Year)
length(Data@Cat[1,])
length(Lagged_1@Cat[1,])
length(Data@Ind[1,])
length(Lagged_1@Ind[1,])

# Lag CAA by 5 and Ind by 3 time-steps
Lagged_2 <- Lag_Data(Data, Data_Lag=list(CAA=5, Ind=3))
length(Lagged_2@Year)
length(Lagged_2@Cat[1,])
dim(Data@CAA[1,,])
dim(Lagged_2@CAA[1,,])

length(Data@Ind[1,])
length(Lagged_2@Ind[1,])

Dimensions of a hierarchical list object

Description

Dimensions of a hierarchical list object

Usage

ldim(x)

Arguments

x

A list

Author(s)

T. Carruthers


Length Constructor and Accessors

Description

Construct a length object defining the length-at-age schedule for a stock, or access and replace the Length slot of a stock and its individual slots. A Length object is required for all stock objects.

Usage

Length(
  Pars = list(),
  Model = NULL,
  Units = "mm",
  MeanAtAge = NULL,
  CVatAge = 0.1,
  Dist = "normal",
  TruncSD = 2,
  Timing = 0,
  Random = NULL,
  ALK = NULL,
  Classes = NULL,
  Misc = list()
)

ALK(x)

ALK(x) <- value

Length(x) <- value

Arguments

Pars

list. Named list of growth parameters. Element names must match the arguments of a built-in growth model (see LengthModels()). When Pars is non-empty and Model is NULL, the model is inferred automatically by FindModel(). When Pars is a stock object, Length() acts as a pass-through accessor and returns x@Length. See Specifying the Length-at-Age and Specifying Biological and Fleet Schedules for the full set of accepted input formats. Default list().

Model

character(1) or function. Growth model identifier. When NULL (default), the model is inferred from Pars via FindModel(). May be set to a character string naming a built-in model or to a custom R function — see Specifying Biological and Fleet Schedules.

Units

character(1). Physical unit of length measurements. Must be one of the strings returned by ValidUnits() (e.g., "mm", "cm"). Default "mm".

MeanAtAge

array or NULL. Mean length at age with named dimensions ⁠Sim × Age × Year⁠. Supply directly when bypassing the model-based approach (Pars = list()). Only the years at which values change need to be included; Extend() fills the remainder. When Pars contains a matched model, any values here are overwritten during Populate(). A numeric vector of length nAge is also accepted and is promoted to a ⁠1 × nAge × 1⁠ array automatically. Default NULL.

CVatAge

numeric(1), length-2 bounds vector, or array. Coefficient of variation of length-at-age within each age class, used to parameterise the within-age-class length distribution and to build the age-length key (ALK). A length-2 vector is treated as Uniform(lower, upper) bounds sampled once per simulation. Default 0.1.

Dist

character(1). Parametric distribution for length-at-age variability. Options are: "normal" (default) and "lognormal").

TruncSD

numeric(1). Number of standard deviations at which the length distribution is truncated, preventing unrealistic tails in the ALK. Default 2.

Timing

numeric(1). Fractional position within the time step at which length is measured: 0 = start of step, 1 = end of step. Shifts age class midpoints before computing the ALK. Relevant for seasonal models where growth occurs within a step. Default 0.

Random

array or NULL. Simulation- and year-specific random multipliers applied to growth parameters, enabling inter-annual or among-simulation variation in growth. Currently stored but not applied. Default NULL.

ALK

array or NULL. Age-length key giving the probability that an individual of a given age belongs to each length class (⁠Sim × Age × Class × Year⁠). Populated automatically during Populate() from MeanAtAge, CVatAge, Dist, and TruncSD; supply directly only when overriding the computed key. Default NULL.

Classes

numeric or NULL. Length class midpoints in units of Units. Populated automatically during Populate() if NULL. Default NULL.

Misc

list. Used internally. Default list().

x

A length object for slot accessors, or a stock object for ⁠Length<-⁠.

value

For ⁠Length<-⁠: a length object. For ⁠ALK<-⁠: a replacement age-length key array.

Details

Specifying Length-at-Age

There are two ways to define the length schedule:

  1. Model-based (recommended): supply Pars with the named parameters for your chosen growth model (e.g., list(Linf = 80, K = 0.2, t0 = -0.5) for von Bertalanffy). If Model is NULL and the parameter names uniquely identify a model, FindModel() sets Model automatically. The MeanAtAge array and ALK are then populated by Populate() when the stock is added to an OM().

  2. Direct array: supply MeanAtAge with Pars = list(). Any values already present in MeanAtAge are preserved and are not overwritten during Populate().

See Specifying Biological and Fleet Schedules for more details.

Length Distribution and the ALK

Within each age class, lengths follow the distribution given by Dist, centred on MeanAtAge with spread CVatAge, truncated at TruncSD standard deviations. These parameters are used to build the age-length key (ALK), which maps age-structured abundance to length-structured quantities throughout the operating model. Retrieve the computed key with ALK(x).

Pass-Through Access from a Stock

When Pars is a stock object, Length() returns the Length slot directly:

Length(my_stock)           # returns my_stock@Length
Length(my_stock) <- my_L   # replaces my_stock@Length

Slot Accessors

Individual slots can be read or replaced using generic functions matching their names. All replacement functions re-validate the object:

Pars(len)         <- list(Linf = 80, K = 0.2, t0 = -0.5)
Model(len)        <- "vonBert"
Units(len)        <- "cm"
MeanAtAge(len)    <- my_array
CVatAge(len)      <- 0.08
Dist(len)         <- "normal"
TruncSD(len)      <- 3
Timing(len)       <- 0
ALK(len)          <- my_alk
Classes(len)      <- seq(5, 80, by = 5)

Value

  • Length() returns a length object. If Pars is a stock, returns x@Length.

  • ⁠Length<-⁠ returns the stock x with the Length slot replaced by value and the object re-validated.

  • ALK() returns the age-length key array from x.

  • ⁠ALK<-⁠ returns x with the ALK slot updated and the object re-validated.

See Also

Other length: length-class

Examples

# See LengthModels() for all available built-in growth models and the
# parameter names required for each.
LengthModels()

# ---- Model-based specification ----

## Constant parameters (scalar) — same value for every simulation and year
len <- Length(Pars = list(Linf = 100, K = 0.2, t0 = -0.1))

## Stochastic across simulations — Linf and K drawn from Uniform(lower, upper)
## once per simulation; t0 fixed at -0.1 in all simulations
len <- Length(Pars = list(Linf = c(90, 110),
                          K    = c(0.15, 0.25),
                          t0   = -0.1))

## Inter-annual random walk on Linf — log-normal with 5% CV
## LinfSD is removed from Pars after use
len <- Length(Pars = list(Linf    = c(90, 110),
                          LinfSD  = 0.05,
                          K       = c(0.15, 0.25),
                          t0      = -0.1))

## Time-varying parameters with named change-point arrays
## Only the years where values change need to be supplied; Extend() fills
## all intermediate and future years by forward-filling automatically.
nSim <- 48
## Linf increases in 2010 (two change points: 1990 and 2010)
Linf_arr <- array(
  c(rep(80, nSim), rep(90, nSim)),
  dim      = c(nSim, 2),
  dimnames = list(Sim = seq_len(nSim), Year = c(1990, 2010))
)
len <- Length(Pars = list(Linf = Linf_arr,
                          K    = c(0.15, 0.25),
                          t0   = -0.1))

## Combine stochastic (across sims) and time-varying (across years):
## Linf is drawn per simulation AND changes in 2010
Linf_sim   <- runif(nSim, 80, 100)
Linf_arr2  <- array(
  c(Linf_sim, Linf_sim * 1.1),        # 10% increase from 2010 onward
  dim      = c(nSim, 2),
  dimnames = list(Sim = seq_len(nSim), Year = c(1990, 2010))
)
len <- Length(Pars = list(Linf = Linf_arr2,
                          K    = c(0.15, 0.25),
                          t0   = -0.1))

# ---- Direct array specification ----

## Supply MeanAtAge directly (Pars left empty).
## A plain numeric vector of length nAge is accepted; it is treated as a
## single simulation, single year and replicated by Extend() as needed.
ages   <- 0:20
len_aa <- Length(MeanAtAge = 100 * (1 - exp(-0.2 * (ages + 0.5))))

## Named Sim × Age × Year array — two change-point years, single simulation.
## Extend() replicates Sim = 1 to all nSim simulations automatically.
maa <- array(
  c(100 * (1 - exp(-0.2 * (ages + 0.5))),   # 1990 schedule
    110 * (1 - exp(-0.2 * (ages + 0.5)))),   # 2010 schedule (Linf increased)
  dim      = c(1, length(ages), 2),
  dimnames = list(Sim = 1, Age = ages, Year = c(1990, 2010))
)
len_arr <- Length(MeanAtAge = maa)

# ---- Custom length class midpoints ----

## By default, Classes and the ALK are populated automatically during
## Populate(). 
# Supply Classes explicitly to override the default bin width.
len_cls <- Length(
  Pars    = list(Linf = 100, K = 0.2, t0 = -0.1),
  Classes = seq(from = 2.5, by = 5, length.out = 26)
)

# ---- Slot accessors ----

len <- Length(Pars = list(Linf = 100, K = 0.2, t0 = -0.1))

## Read slots
MeanAtAge(len)            # NULL until Populate() is called
CVatAge(len)
Units(len)

## Replace slots
Units(len)   <- "cm"
CVatAge(len) <- 0.08
TruncSD(len) <- 3

# ---- Attaching to a Stock ----

stk <- Stock(Name = "Example stock", Ages = Ages(MaxAge = 20))
Length(stk) <- Length(Pars = list(Linf = 100, K = 0.2, t0 = -0.1))
Length(stk)

# ---- Populate ----

## The final populated object (typically done internally)
pop_len <- Populate(Length(stk))
pop_len

MeanAtAge(pop_len)

Length-at-Age Growth Models

Description

Length-at-age (LAA) growth models

Usage

vonBert(Ages, Linf, K, t0 = 0)

Brody(Ages, L0, Linf, K)

Gompertz(Ages, Linf, g, a)

Schnute(Ages, y0, y1, t0, t1, a, b)

LengthModels(full = TRUE, print = TRUE)

Arguments

Ages

Numeric vector of ages (always in years).

Linf

asymptotic length (used by von Bertalanffy, Gompertz, Brody)

K

growth coefficient (used by von Bertalanffy, Brody)

t0

theoretical age at zero length (von Bertalanffy)

L0

length at age 0 (Brody)

g

growth rate parameter (Gompertz)

a

age at inflection (Gompertz) or Schnute shape parameter

y0

length at age t0 (Schnute)

y1

length at age t1 (Schnute)

t1

second reference age (Schnute)

b

growth shape parameter (Schnute)

full

Logical. Provide a complete table (TRUE) or just the model names (FALSE)?

print

Logical. Print out the results (TRUE) or just return the data.frame (FALSE)?

Details

LengthModels() prints the list of models and parameters to the console

  • von Bertalanffy:

    L(a)=L(1eK(at0))L(a) = L_\infty (1 - e^{-K (a - t_0)})

  • Brody:

    L(a)=L(LL0)eKaL(a) = L_\infty - (L_\infty - L_0) e^{-K a}

  • Gompertz:

    L(a)=Lexp(exp(g(aa)))L(a) = L_\infty \exp(-\exp(-g (a - a)))

  • Schnute: flexible formula depending on parameters a and b

Value

  • LengthModels() invisibly returns a data frame containing the models

  • Growth models: Numeric vector of expected lengths at age.

See Also

Ages(), Length(), Stock()

Examples

Ages <- 0:15

L_vb <- vonBert(Ages, Linf = 100, K = 0.25, t0 = -0.5)
L_brody <- Brody(Ages, L0 = 10, Linf = 100, K = 0.3)
L_gompertz <- Gompertz(Ages, Linf = 100, g = 0.35, a = 3)
L_schnute <- Schnute(Ages, y0 = 12, y1 = 100, t0 = 0, t1 = 15, a = 0.5, b = 1.2)

df <- data.frame(
  Age = Ages,
  vonBert = L_vb,
  Brody = L_brody,
  Gompertz = L_gompertz,
  Schnute = L_schnute
)

matplot(df$Age, df[,-1], type = "l", lty = 1, lwd = 2,
        col = c("blue", "red", "green", "purple"),
        xlab = "Age (years)", ylab = "Length",
        main = "Length-at-Age Models")
legend("bottomright", legend = colnames(df)[-1],
       col = c("blue", "red", "green", "purple"), lty = 1, lwd = 2)

The length S4 Class

Description

Defines the length-at-age schedule for a stock object. Objects are typically created via Length(), which documents all parameters, validates inputs, and infers the growth model automatically when possible.

Details

Direct construction via methods::new() is not recommended; use Length() instead, which handles model inference and object validation.

The ALK slot is derived from MeanAtAge, CVatAge, Dist, and TruncSD during Populate() and should not be set manually.

Slots

Pars

list. Named list of growth parameters whose names correspond to those expected by Model. See LengthModels() for parameter sets and Specifying Biological and Fleet Schedules for accepted input formats.

Model

function or character(1). Growth model identifier, matched to one of LengthModels(). Set automatically by FindModel() when Pars is supplied without an explicit model.

Units

character(1). Physical unit of the length measurements (e.g., "mm", "cm"). Must be accepted by ValidUnits().

MeanAtAge

array. Mean length at age with named dimensions Sim, Age, and Year. Populated automatically by Populate() when Pars and Model are set; may also be supplied directly when Pars is empty. When Pars contains a matched model, any existing values are overwritten. See Specifying Biological and Fleet Schedules.

CVatAge

array or numeric. Coefficient of variation of length-at-age, used to generate the within-age-class length distribution.

Dist

character(1). Parametric distribution used for length-at-age variability (e.g., "normal").

TruncSD

array or numeric. Number of standard deviations at which the length distribution is truncated.

Timing

array or numeric. Fractional position within the time step at which length is measured (0 = start, 1 = end).

Random

array. Random effects on growth parameters across simulations or years.

ALK

array. Age-length key: the probability of belonging to each length class given age, derived from MeanAtAge, CVatAge, Dist, and TruncSD. Populated automatically; use ALK() to retrieve.

Classes

numeric. Length class midpoints in units of Units.

Misc

list. Used internally.

See Also

Other length: Length()


Length-Structured Observation Model

Description

An obs object representing a data-moderate scenario suitable for length-based stock assessment. Landings, discards, a fishery-independent survey, and annual length-composition samples from both landed and discarded fish are simulated.

Usage

LengthStructuredObs

Format

An obs object. Populated slots:

  • Landings (catchobs): reported landings with CV in ⁠[0.10, 0.20]⁠ and slight negative-to-neutral bias ⁠[0.90, 1.05]⁠.

  • Discards (catchobs): less precisely reported discards with CV in ⁠[0.15, 0.25]⁠ and near-unbiased reporting ⁠[0.95, 1.05]⁠.

  • Survey (indicesobs): survey index assuming biomass-proportional selectivity, with CV in ⁠[0.15, 0.30]⁠ and autocorrelation in ⁠[0.0, 0.2]⁠.

  • LandingsAtSize (compobs): length-composition samples of landed fish from dockside measurements. Nominal sample size ⁠[300, 600]⁠ fish per year; ESS ⁠[60, 120]⁠ reflecting within-haul length clustering; Theta in ⁠[0.5, 1.0]⁠.

  • DiscardsAtSize (compobs): length-composition samples of discarded fish from at-sea observers. Nominal sample size ⁠[150, 300]⁠; ESS ⁠[40, 80]⁠; Theta in ⁠[0.4, 0.8]⁠.

Empty slots (no data simulated): Effort, Discards, CPUE, LandingsAtAge, DiscardsAtAge.

See Also

obs, Obs(), CatchObs(), IndicesObs(), CompObs(), CatchAndSurveyObs, CommercialFleetObs, AgeStructuredObs, DataRichObs

Other obs-examples: AgeStructuredObs, CatchAndSurveyObs, CommercialFleetObs, DataRichObs

Examples

LengthStructuredObs
LandingsAtSize(LengthStructuredObs)
DiscardsAtSize(LengthStructuredObs)

Predict missing life-history parameters

Description

Predict missing life-history based on taxonomic information and hierarchical model fitted to FishBase life-history parameters

Usage

LH2OM(
  OM,
  dist = c("unif", "norm"),
  filterMK = FALSE,
  plot = TRUE,
  Class = "predictive",
  Order = "predictive",
  Family = "predictive",
  msg = TRUE,
  db = MSEtool::LHdatabase
)

predictLH(
  inpars = list(),
  Genus = "predictive",
  Species = "predictive",
  nsamp = 100,
  db = MSEtool::LHdatabase,
  dist = c("unif", "norm"),
  filterMK = TRUE,
  plot = TRUE,
  Class = "predictive",
  Order = "predictive",
  Family = "predictive",
  msg = TRUE
)

Arguments

OM

An object of class 'OM'

dist

Character. Should parameters be sampled from a uniform (unif) or normal (norm) distribution?

filterMK

Logical or numeric specifying percentiles. See Details. e.g. OM@M and OM@K. Empty slots or slots with all values of 0 are considered unknown.

plot

Logical. Should the plot be produced?

Class

Optional higher order taxonomic information

Order

Optional higher order taxonomic information

Family

Optional higher order taxonomic information

msg

Logical. Should messages be printed?

db

Database from FishLife model with fitted model results

inpars

A named list with lower and upper bounds of provided parameters: Linf, L50, K and M (must be length 2). Unknown or missing parameters should not be included. For example, an empty list assumes that all four life history parameters are unknown and need to be estimated. See Details below for more information.

Genus

Character string specifying the Genus name. Optional. Default is 'predictive'

Species

Character string specifying the Species name. Optional. Default is 'predictive'. If full species name (Genus + Species) is not found if FishLife database (based on FishBase) higher order taxonomy will be used (e.g., Family) for the predictions.

nsamp

The number of samples to return

Details

filterMK

If filterMK is logical: Should the predicted M and K parameters be filtered within the range specified in inparsor OM?

Otherwise, filterMK must be numeric vector of length(2) specifying lower and upper percentiles that will be applied to the predicted M or K values

The model predicts missing life-history parameters based on provided parameters and taxonomic information. If both M and K are provided in inpars or OM, K values are predicted and predictions filtered so that resulting K values are within bounds specified in inpars$K or OM@K (see filterMK).

If both Linf and L50 are provided in inpars or OM, L50 values are predicted and values in inpars$L50 or OM@L50 are ignored.

Value

LH2OM: An OM with OM@cpars populated with OM@nsim samples of M, K, Linf and L50

predictLH: A data.frame with nsamp rows with Linf, L50, K, and M values.

Functions

  • LH2OM(): Predict missing life-history and populate OM@cpars

  • predictLH(): Predict missing life-history based on taxonomic information and hierarchical model fitted to FishBase life-history parameters

Author(s)

A. Hordyk

Source

https://github.com/James-Thorson-NOAA/FishLife

References

Thorson, J. T., S. B. Munch, J. M. Cope, and J. Gao. 2017. Predicting life history parameters for all fishes worldwide. Ecological Applications. 27(8): 2262–2276


LHdatabase

Description

Database from the FishLife package with predicted life-history parameters for all species on FishBase

Usage

LHdatabase

Format

An object of class list of length 3.

Source

https://github.com/James-Thorson-NOAA/FishLife/

References

Thorson, J. T., S. B. Munch, J. M. Cope, and J. Gao. 2017. Predicting life history parameters for all fishes worldwide. Ecological Applications. 27(8): 2262–2276


lifehistorydata Class

Description

Groups the biological life-history components required to describe population dynamics. Each slot holds a dedicated sub-object defining the model and parameters for that process. Used in the LifeHistory slot of a data object.

Usage

LifeHistoryData()

Value

LifeHistoryData() returns a lifehistorydata object.

Slots

Ages

An object of class ages defining the age structure of the population (minimum age, maximum age, plus-group).

Length

An object of class length defining the growth model (e.g., von Bertalanffy) and length-at-age parameters.

Weight

An object of class weight defining the weight-at-age or length–weight relationship.

NaturalMortality

An object of class naturalmortality defining natural mortality rates, which may be age-, size-, or time-varying.

Maturity

An object of class maturity defining maturity-at-age or maturity-at-length schedules.

Fecundity

An object of class fecundity defining fecundity-at-age or fecundity-at-length relationships.

SRR

An object of class srr defining the stock–recruitment relationship (e.g., Beverton–Holt, Ricker) and associated parameters.

Spatial

An object of class spatial defining the spatial structure of the population, including movement and area allocation.

Depletion

An object of class depletion specifying the initial depletion level relative to unfished biomass.

Misc

A named list for any additional life-history metadata.

LifeHistoryData() creates a new lifehistorydata object.

See Also

data, Data()


LifeHistoryObs Constructor

Description

Construct a lifehistoryobs object defining observation error for life-history parameters.

Usage

LifeHistoryObs(
  Ages = list(),
  Length = list(),
  Weight = list(),
  NaturalMortality = list(),
  Maturity = list(),
  Fecundity = list(),
  SRR = list(),
  Spatial = list(),
  Depletion = list(),
  Misc = list()
)

Arguments

Ages

list. Observation error specification for age structure parameters. Default list().

Length

list. Observation error specification for growth parameters. Default list().

Weight

list. Observation error specification for weight-at-age or length-weight parameters. Default list().

NaturalMortality

list. Observation error specification for natural mortality. Default list().

Maturity

list. Observation error specification for maturity schedules. Default list().

Fecundity

list. Observation error specification for fecundity parameters. Default list().

SRR

list. Observation error specification for stock-recruitment parameters. Default list().

Spatial

list. Observation error specification for spatial parameters. Default list().

Depletion

list. Observation error specification for initial depletion. Default list().

Misc

list. Miscellaneous additional objects. Default list().

Details

Placeholder. This class and constructor are reserved for future development and are not currently used. Each slot will eventually mirror the structure of the corresponding slot in lifehistorydata, providing bias and CV specifications for life-history parameter estimation. Slots currently accept untyped lists and all values are silently ignored during simulation.

When converted from a legacy Obs-legacy object via ConvertObs(), the life-history bias CVs (Linfbiascv, Kbiascv, Mbiascv, etc.) are not yet mapped to this class and are silently dropped.

Value

A lifehistoryobs object.

See Also

Other obs: CatchObs(), CompObs(), EffortObs(), ExploitationObs(), IndicesObs(), Obs(), catchobs-class, compobs-class, effortobs-class, exploitationobs-class, indicesobs-class, lifehistoryobs-class, obs-class

Examples

lho <- LifeHistoryObs()

The lifehistoryobs S4 Class

Description

Defines the observation error structure for life-history parameters (growth, maturity, natural mortality, etc.). Used in the LifeHistory slot of an obs object. Objects are created via LifeHistoryObs().

Slots

Ages

list. Observation error specification for age structure parameters. See LifeHistoryObs().

Length

list. Observation error specification for growth parameters. See LifeHistoryObs().

Weight

list. Observation error specification for weight-at-age or length-weight parameters. See LifeHistoryObs().

NaturalMortality

list. Observation error specification for natural mortality. See LifeHistoryObs().

Maturity

list. Observation error specification for maturity schedules. See LifeHistoryObs().

Fecundity

list. Observation error specification for fecundity parameters. See LifeHistoryObs().

SRR

list. Observation error specification for stock-recruitment parameters. See LifeHistoryObs().

Spatial

list. Observation error specification for spatial parameters. See LifeHistoryObs().

Depletion

list. Observation error specification for initial depletion. See LifeHistoryObs().

Misc

list. Miscellaneous additional objects.

This class is a placeholder. Each slot mirrors the corresponding sub-object of lifehistorydata and will eventually hold an error structure (bias, CV) for the associated life-history parameter. Slots are currently untyped lists and are not populated during model runs. See LifeHistoryObs() for further details.

See Also

Other obs: CatchObs(), CompObs(), EffortObs(), ExploitationObs(), IndicesObs(), LifeHistoryObs(), Obs(), catchobs-class, compobs-class, effortobs-class, exploitationobs-class, indicesobs-class, obs-class


Convert Between Lists and Arrays

Description

Convert between lists of arrays and higher-dimensional arrays in a predictable and efficient way.

Usage

List2Array(x, name = "Fleet", dim1 = "Sim", pos = NULL)

Array2List(x, pos = 2, index = NULL)

Arguments

x

A list (for List2Array) or an array (for Array2List).

name

Character string giving the name of the new dimension created by List2Array.

dim1

Character string giving the name of the first dimension when combining a list of vectors. Defaults to "Sim".

pos

Integer or character specifying the position or name of the dimension to add (List2Array) or split (Array2List).

index

Optional integer vector specifying which slices to extract in Array2List. Defaults to all slices.

Details

These functions provide inverse operations for reshaping data between list and array representations while preserving dimension structure and dimnames.

List2Array

Combines a list of vectors or arrays into a single array by adding a new dimension corresponding to list elements. All list elements must have compatible dimensions. The new dimension has length equal to the length of the list.

Array2List

Splits an array into a list by extracting slices along a specified dimension. Each list element is an array with the remaining dimensions preserved.

Value

  • List2Array(): an array with one additional dimension

  • Array2List(): a named list of arrays

Examples

x <- list(
  Cod = array(
    1:6,
    dim = c(2, 3),
    dimnames = list(
      Sim  = 1:2,
      Year = 2023:2025
    )
  ),
  Haddock = array(
    7:12,
    dim = c(2, 3),
    dimnames = list(
      Sim  = 1:2,
      Year = 2023:2025
    )
  )
)

array <- List2Array(x, name = "Stock", pos = 2)
dimnames(array)

Array2List(array) # convert back to x

Load Function Arguments into an Environment

Description

Assigns the default argument values of a function to envir, skipping any argument that already exists in that environment as a non-function object. Useful during interactive development for populating the workspace with a function's expected inputs without overwriting variables already set.

Usage

LoadArgs(fun = "Simulate", envir = .GlobalEnv, debug = FALSE)

Arguments

fun

Character string naming a function, or a function object. Default "Simulate".

envir

Environment to assign default values into. Default .GlobalEnv.

debug

Logical. If TRUE, emits a message for each argument indicating whether it already exists in envir and whether it is being assigned. Default FALSE.

Value

NULL invisibly. Called for its side effect of populating envir.

Examples

# Populate the global workspace with the default arguments of [CalcSurvival()],
# without overwriting any variables that are already defined:
## Not run: 
NaturalMortality <- my_array   # already set; will not be overwritten
LoadArgs("CalcSurvival")
# FishingMortality, PlusGroup, SpawnTimeFrac, and Semelparous are now
# assigned their defaults in .GlobalEnv; NaturalMortality is unchanged.

## End(Not run)

Display Log Warnings

Description

Prints any warnings stored in the Log slot of an S4 object to the console using cli formatting.

Usage

Log(object)

Arguments

object

An S4 object with a Log slot

Value

Invisibly returns NULL. Called for its side effect of printing warnings to the console.

Examples

## Not run: 
  Log(my_object)

## End(Not run)

Logit and Inverse Logit (Sigmoid) Functions

Description

logit() transforms a probability to the log-odds scale. ilogit() is its inverse — the sigmoid function — mapping any real number back to [0, 1].

Usage

logit(p)

ilogit(x)

Arguments

p

A numeric vector of probabilities. Values must be in the open interval (0, 1); NaN is returned for values outside this range.

x

A numeric vector of real-valued log-odds.

Details

The two functions are mutual inverses:

logit(p)=log ⁣(p1p)\text{logit}(p) = \log\!\left(\frac{p}{1-p}\right)

ilogit(x)=11+ex\text{ilogit}(x) = \frac{1}{1 + e^{-x}}

so that ilogit(logit(p)) == p and logit(ilogit(x)) == x (up to floating-point precision).

Value

  • logit(p) returns a numeric vector of log-odds in (-Inf, Inf).

  • ilogit(x) returns a numeric vector of probabilities in (0, 1).

Examples

logit(0.5)   # 0
logit(0.9)   # ~2.197

ilogit(0)    # 0.5
ilogit(2)    # ~0.880

# Round-trip
p <- c(0.1, 0.5, 0.9)
all.equal(p, ilogit(logit(p)))  # TRUE

Utility for making multi-OMs

Description

Converts an OM to a single stock, single fleet MOM.

Usage

makeMOM(..., silent = FALSE)

Arguments

...

An OM.

silent

Should messages be printed out to the console?

Value

A class MOM object.

Author(s)

Q. Huynh

Examples

MOM <- makeMOM(testOM)

Calculates movement matrices from user inputs for fraction in each area (fracs) and probability of staying in areas (prob)

Description

A function for calculating a movement matrix from user specified unfished stock biomass fraction in each area. Used by simmov to generate movement matrices for an operating model.

Usage

makemov(fracs = c(0.1, 0.2, 0.3, 0.4), prob = c(0.5, 0.8, 0.9, 0.95))

Arguments

fracs

A vector nareas long of fractions of unfished stock biomass in each area

prob

A vector of the probability of individuals staying in each area or a single value for the mean probability of staying among all areas

Author(s)

T. Carruthers

See Also

simmov


Calculates movement matrices from user inputs for fraction in each area (fracs) the relative fraction moving to other areas, plus a mean probability of staying in any given area.

Description

A function for calculating a movement matrix from user specified distribution among areas (v) and relative movement to other areas (solves for positive diagonal - vector of prob staying). Used by simmov2 to generate movement matrices for an operating model. There must be a prior on the positive diagonal of the movement matrix or these will tend to 1 and hence perfectly satisfy the requirement V = MV.

Usage

makemov2(
  dist = c(0.05, 0.6, 0.35),
  prob = 0.5,
  probE = 1,
  frac_other = matrix(c(NA, 2, 1, 2, NA, 1, 1, 2, NA), nrow = 3, byrow = T),
  plot = F
)

Arguments

dist

A vector nareas long of fractions of unfished stock biomass in each area

prob

A vector of the probability of individuals staying in each area or a single value for the mean probability of staying among all areas

probE

The logit CV associated with prob (used as a penalty when optimizing for diagonal)

frac_other

A matrix nareas x nareas that specifies the relative fraction moving from one area to the others. The positive diagonal is unspecified.

plot

Should the convergence to a stable distribution be plotted?

Author(s)

T. Carruthers

See Also

simmov2


MICE relationships for multi-OM

Description

Generate a MICE Rel object, with predict and simulate methods, for multiMSE. Currently implements intra-stock dynamics via density-dependent processes.

Usage

makeRel(type = "DDM", stock = 1, CV = 0, ...)

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

## S3 method for class 'Rel'
predict(object, newdata, ...)

## S3 method for class 'Rel'
simulate(object, nsim = 1, seed = 1, ...)

Arguments

type

String to indicate the type of stock interaction. "DDM" for density-dependent natural mortality.

stock

The index position of the stock in the MOM.

CV

Coefficient of variation of the predicted value for simulate. Used to pass values to the operating model.

...

Additional arguments depending on type. See details below.

x

For print.Rel, a Rel class object from make_Rel.

object

A Rel class object from make_Rel.

newdata

A data frame to provide values of predictor variables with which to calculate the response variable.

nsim

The number of simulations.

seed

Integer to specify the seed for the random number generator.

Value

A class "Rel" object to pass to MOM@Rel.

Density-dependent M ("DDM")

Natural mortality (M) is a linear function of stock depletion in terms to total biomass (B) in year y (Forrest et al. 2018):

My=M0+(M1+M0)(1By/B0)M_y = M_0 + (M_1 + M_0) (1 - B_y/B_0)

with a constraint that My=M0M_y = M_0 if By>B0B_y > B_0

Provide the following arguments:

  • M0: Natural mortality as B approaches B0. Vector ⁠[nsim]⁠

  • M1: Natural mortality as B approaches zero. Vector ⁠[nsim]⁠

  • Optional B0: Unfished biomass. Calculated from stock-recruit alpha and beta and unfished biomass per recruit at M = M0. Vector ⁠[nsim]⁠

Author(s)

Q. Huynh

References

Forrest, R., Holt, K., and Kronlund, A. 2018. Performance of alternative harvest control rules for two Pacific groundfish stocks with uncertain natural mortality: Bias, robustness and trade-offs. Fisheries Research 206: 259–286. doi:10.1016/j.fishres.2018.04.007

Examples

# Depensatory natural mortality
Rel <- makeRel(type = "DDM", M0 = 0.8, M1 = 0.2, CV = 0.1)

# Predict M when B/B0 = 0.1
pred <- predict(Rel, newdata = data.frame(B_1 = 0.1, B0_1 = 1))

# Simulate values of M with CV = 0.1
Rel$fitted.values <- pred
simulate(Rel, nsim = 10, seed = 1)

# Add Rel to MOM
MOM <- makeMOM(testOM)
MOM@Rel <- list(Rel)

Make colors transparent

Description

Make colors transparent

Usage

makeTransparent(someColor, alpha = 100)

Arguments

someColor

Character string describing color

alpha

transparency

Author(s)

T. Carruthers


Maturity Constructor and Accessors

Description

Construct a maturity object defining the maturity schedule for a stock, or access and replace the Maturity slot of a stock and its individual slots. A Maturity object is required for all stock objects.

Usage

Maturity(
  Pars = list(),
  Model = NULL,
  MeanAtAge = NULL,
  MeanAtLength = NULL,
  MeanAtWeight = NULL,
  Classes = NULL,
  Semelparous = FALSE,
  Misc = list()
)

Semelparous(x)

Semelparous(x) <- value

Maturity(x) <- value

Arguments

Pars

list. Named list of maturity parameters. Element names must match the arguments of a built-in maturity model (see MaturityModels()). When Pars is non-empty and Model is NULL, the model is inferred automatically by FindModel(). When Pars is a stock object, Maturity() acts as a pass-through accessor and returns x@Maturity; when Pars is a list of stock objects, Model is treated as an integer index selecting which stock's Maturity slot to return — see Pass-Through Access. See also Specifying Biological and Fleet Schedules for the full set of accepted input formats. Default list().

Model

character(1), function, or integer(1). Maturity model identifier. When NULL (default), the model is inferred from Pars via FindModel(). May be set to a character string naming a built-in model or to a custom R function. When Pars is a list of stock objects, Model is an integer index — see Pass-Through Access and Specifying Biological and Fleet Schedules.

MeanAtAge

array or NULL. Mean maturity-at-age with named dimensions ⁠Sim × Age × Year⁠. Values should range from 0 (immature) to 1 (fully mature). Supply directly when bypassing the model-based approach (Pars = list()). Only the years at which values change need to be included; Extend() fills the remainder. When Pars contains a matched model, any values here are overwritten during Populate(). A numeric vector of length nAge is also accepted and promoted to a ⁠1 × nAge × 1⁠ array automatically. Default NULL.

MeanAtLength

array or NULL. Mean maturity-at-length with named dimensions ⁠Sim × Length × Year⁠. Populated automatically during Populate() when an at-length maturity model is used; may also be supplied directly. When MeanAtLength is populated and MeanAtAge is not, Populate() converts it to MeanAtAge via the age-length key (ALK) from a length object. Default NULL.

MeanAtWeight

array or NULL. Mean maturity-at-weight with named dimensions ⁠Sim × Weight × Year⁠. Populated automatically during Populate() when an at-weight maturity model is used; may also be supplied directly. When MeanAtWeight is populated and MeanAtAge is not, Populate() converts it to MeanAtAge via the age-weight key (AWK) from a weight object. Requires a populated weight with a non-NULL CVatAge slot so that the AWK exists. Default NULL.

Classes

numeric or NULL. Age, length, or weight class midpoints corresponding to the ⁠MeanAt*⁠ array in use. Default NULL.

Semelparous

logical(1) or array. Controls post-spawning mortality. FALSE (default) disables post-spawn mortality. TRUE sets post-spawn mortality equal to the maturity ogive after Populate() — see Semelparity for full details. A custom ⁠Sim × Age × Year⁠ array may also be supplied directly to specify age- and time-varying post-spawn mortality that differs from the maturity schedule.

Misc

list. Named list of optional user-defined inputs stored on the object and passed through to custom model functions. Default list().

x

A maturity object for slot accessors, or a stock object for ⁠Maturity<-⁠.

value

For ⁠Maturity<-⁠: a maturity object. For ⁠Semelparous<-⁠: a logical(1) or a ⁠Sim × Age × Year⁠ array.

Details

Specifying Maturity

There are two ways to define the maturity schedule; see Specifying Biological and Fleet Schedules for full details on input formats and the rules that govern how Pars, Model, and ⁠MeanAt*⁠ arrays interact.

Model-based (recommended): supply Pars with named parameters matching a built-in model (see MaturityModels()). If Model = NULL and the parameter names uniquely match a model, FindModel() resolves the model automatically. The relevant ⁠MeanAt*⁠ array is then populated by Populate() when the stock is added to an OM():

# Logistic length-based ogive — model inferred from Pars names
mat <- Maturity(Pars = list(L50 = 40, L50_95 = 8))

# Stochastic L50 across simulations
mat <- Maturity(Pars = list(L50 = c(35, 45), L50_95 = 8))

# Time-varying L50 (shifts in 2010; Extend() fills the rest)
L50_arr <- array(c(40, 45), dim = c(1, 2),
                 dimnames = list(Sim = 1, Year = c(1990, 2010)))
mat <- Maturity(Pars = list(L50 = L50_arr, L50_95 = 8))

# Inter-annual random walk on L50 (log-normal, SD = 0.05)
mat <- Maturity(Pars = list(L50 = c(35, 45), L50SD = 0.05, L50_95 = 8))

Direct array: supply any of MeanAtAge, MeanAtLength, or MeanAtWeight with Pars = list(). MeanAtAge takes precedence if more than one is populated:

ages   <- 0:20
mat_aa <- Maturity(MeanAtAge = 1 / (1 + exp(-0.5 * (ages - 5))))

lens   <- seq(5, 120, by = 5)
mat_al <- Maturity(
  MeanAtLength = array(
    1 / (1 + exp(-log(19) * (lens - 40) / 8)),
    dim      = c(1, length(lens), 1),
    dimnames = list(Sim = 1, Length = lens, Year = 1990)
  )
)

Semelparity

Post-spawning mortality is controlled by the Semelparous slot, which after Populate() is always a ⁠Sim × Age × Year⁠ array. Each cell gives the fraction of individuals at that age dying immediately after spawning. This mortality is applied as a multiplier (1 - Semelparous) on top of standard exp(-Z) survival — it is an additional source of mortality, not a substitute for natural mortality.

The default (Semelparous = FALSE) sets all cells to 0: no post-spawn mortality, appropriate for iteroparous species.

Setting Semelparous = TRUE sets the array equal to MeanAtAge after population:

  • Fully mature ages (maturity ≈ 1): post-spawn survival ≈ 0 — complete die-off.

  • Ages on the maturity ogive (0 < maturity < 1): proportional post-spawn mortality.

  • Immature ages (maturity ≈ 0): post-spawn survival ≈ 1 — unaffected.

This assumption — that the post-spawn mortality schedule equals the maturity ogive — is appropriate for obligate semelparous species such as Pacific salmon, where all maturing individuals spawn once and die. For species with partial semelparity, or where post-spawn mortality affects only older or larger mature fish, supply a custom ⁠Sim × Age × Year⁠ array directly:

ages <- 0:20
# Post-spawn mortality applies only to ages >= 5, ramping from 0 to 0.8
sem_arr <- array(
  pmin(pmax((ages - 5) / 10, 0), 0.8),
  dim      = c(1, length(ages), 1),
  dimnames = list(Sim = 1, Age = ages, Year = 1990)
)
mat <- Maturity(Pars = list(L50 = 40, L50_95 = 8), Semelparous = sem_arr)

Note: after Populate(), Semelparous is always an array.

At-Length and At-Weight Models

Models whose class contains "at-Length" produce MeanAtLength, which is converted to MeanAtAge via the ALK — a populated Length() object must be passed to Populate(). Models whose class contains "at-Weight" produce MeanAtWeight, converted via the AWK — a populated Weight() object with non-NULL CVatAge (so the AWK exists) must be passed to Populate(). At-weight maturity models are rare in practice.

The same conversions apply when MeanAtLength or MeanAtWeight are supplied directly by the user.

Pass-Through Access from a Stock

When Pars is a stock object, Maturity() returns the Maturity slot directly:

Maturity(my_stock)             # returns my_stock@Maturity
Maturity(my_stock) <- my_mat   # replaces my_stock@Maturity

When Pars is a list of stock objects, Model is an integer index selecting which stock's slot to return:

Maturity(stock_list, 2)   # returns stock_list[[2]]@Maturity

Slot Accessors

Individual slots can be read or replaced using generic functions matching their names. All replacement functions re-validate the object:

Pars(mat)            <- list(L50 = 40, L50_95 = 8)
Model(mat)           <- "LogisticLength"
MeanAtAge(mat)       <- my_array
MeanAtLength(mat)    <- my_length_array
MeanAtWeight(mat)    <- my_weight_array
Semelparous(mat)     <- TRUE
Classes(mat)         <- seq(0, 80, by = 5)

Value

  • Maturity() returns a maturity object. If Pars is a stock, returns x@Maturity. If Pars is a list of stocks, returns Pars[[Model]]@Maturity.

  • ⁠Maturity<-⁠ returns the stock x with the Maturity slot replaced and the object re-validated.

  • Semelparous() returns the Semelparous slot from x (a scalar before Populate(), a ⁠Sim × Age × Year⁠ array after).

  • ⁠Semelparous<-⁠ returns x with the Semelparous slot updated and the object re-validated.

See Also

  • maturity for the class definition and slot-level documentation.

  • MaturityModels() for available maturity models and required parameter sets.

  • FindModel() for automatic model inference.

  • Populate() for array population.

  • Stock() for the enclosing stock constructor.

  • Length() for the companion length schedule, required when using at-length maturity models.

  • Weight() for the companion weight schedule, required when using at-weight maturity models.

Other maturity: maturity-class

Examples

# See MaturityModels() for all available built-in maturity models and the
# parameter names required for each.
MaturityModels()

# ---- Model-based specification ----

## Constant parameters (scalar) — same value for every simulation and year
mat <- Maturity(Pars = list(L50 = 40, L50_95 = 8))

## Stochastic across simulations — L50 drawn from Uniform(lower, upper)
## once per simulation; L50_95 fixed in all simulations
mat <- Maturity(Pars = list(L50    = c(35, 45),
                            L50_95 = 8))

## Inter-annual random walk on L50 — log-normal with 5% CV
## L50SD is removed from Pars after use
mat <- Maturity(Pars = list(L50    = c(35, 45),
                            L50SD  = 0.05,
                            L50_95 = 8))

## Time-varying parameters with named change-point arrays
## Only the years where values change need to be supplied; Extend() fills
## all intermediate and future years by forward-filling automatically.
nSim <- 48

## L50 shifts in 2010 (two change points: 1990 and 2010)
L50_arr <- array(
  c(rep(40, nSim), rep(45, nSim)),
  dim      = c(nSim, 2),
  dimnames = list(Sim = seq_len(nSim), Year = c(1990, 2010))
)
mat <- Maturity(Pars = list(L50    = L50_arr,
                            L50_95 = 8))

## Combine stochastic (across sims) and time-varying (across years)
L50_sim  <- runif(nSim, 35, 45)
L50_arr2 <- array(
  c(L50_sim, L50_sim * 1.1),          # 10% increase from 2010 onward
  dim      = c(nSim, 2),
  dimnames = list(Sim = seq_len(nSim), Year = c(1990, 2010))
)
mat <- Maturity(Pars = list(L50    = L50_arr2,
                            L50_95 = 8))

# ---- Direct array specification ----

## Supply MeanAtAge directly (Pars left empty).
## A plain numeric vector of length nAge is accepted; treated as a single
## simulation, single year and replicated by Extend() as needed.
ages   <- 0:20
mat_aa <- Maturity(MeanAtAge = 1 / (1 + exp(-0.5 * (ages - 5))))

## Named Sim x Age x Year array — two change-point years, single simulation
maa <- array(
  c(1 / (1 + exp(-0.5 * (ages - 5))),    # 1990 ogive
    1 / (1 + exp(-0.5 * (ages - 7)))),   # 2010 ogive (L50 shifted later)
  dim      = c(1, length(ages), 2),
  dimnames = list(Sim = 1, Age = ages, Year = c(1990, 2010))
)
mat_arr <- Maturity(MeanAtAge = maa)

## Supply MeanAtLength directly — converted to MeanAtAge via the ALK
## during Populate() when a Length object is provided.
lens   <- seq(5, 120, by = 5)
mat_al <- Maturity(
  MeanAtLength = array(
    1 / (1 + exp(-log(19) * (lens - 40) / 8)),
    dim      = c(1, length(lens), 1),
    dimnames = list(Sim = 1, Length = lens, Year = 1990)
  )
)

# ---- Semelparity ----

## Semelparous = TRUE: post-spawn mortality equals the maturity ogive.
## Fully mature fish die with probability 1; fish on the ogive die
## proportionally; immature fish are unaffected.
## Appropriate for obligate semelparous species (e.g. Pacific salmon).
mat_sem <- Maturity(Pars = list(L50 = 40, L50_95 = 8), Semelparous = TRUE)

## Custom post-spawn mortality array — partial semelparity by age.
## Here mortality ramps from 0 at age 5 to 0.8 at age 15, then is
## constant. This differs from the maturity ogive and must be supplied
## as a named array.
sem_arr <- array(
  pmin(pmax((ages - 5) / 10, 0), 0.8),
  dim      = c(1, length(ages), 1),
  dimnames = list(Sim = 1, Age = ages, Year = 1990)
)
mat_psem <- Maturity(Pars = list(L50 = 40, L50_95 = 8), Semelparous = sem_arr)

## After Populate(), Semelparous is always an array — do not test == TRUE.
## Use any(Semelparous(mat) > 0) to check whether post-spawn mortality
## is active on a populated object.

# ---- Slot accessors ----

mat <- Maturity(Pars = list(L50 = 40, L50_95 = 8))

## Read slots
MeanAtAge(mat)      # NULL until Populate() is called
MeanAtLength(mat)   # NULL unless an at-length model or direct array is used
Semelparous(mat)    # scalar FALSE before Populate(); array after

## Replace slots
Semelparous(mat) <- TRUE
Classes(mat)     <- seq(0, 80, by = 5)

# ---- Attaching to a Stock ----

stk <- Stock(Name = "Example stock", Ages = Ages(MaxAge = 20))
Maturity(stk) <- Maturity(Pars = list(L50 = 40, L50_95 = 8))
Maturity(stk)

# ---- Populate ----

## The final populated object (typically done internally).
## At-length models require a Length object passed to Populate().
pop_mat <- Populate(Maturity(stk), 
                    Ages = Ages(MaxAge = 20),
                    Length = Length(Pars = 
                                      list(
                                        Linf = 100, 
                                        K = 0.2, 
                                        t0 = -0.1
                                        )
                                    )
)
pop_mat

The maturity S4 Class

Description

Defines the maturity schedule for a stock object. Maturity may be expressed as a function of age, length, or weight. Objects are typically created via Maturity(), which documents all parameters, validates inputs, and infers the maturity model automatically when possible.

Details

Direct construction via methods::new() is not recommended; use Maturity() instead, which handles model inference and object validation.

Only one of MeanAtAge, MeanAtLength, or MeanAtWeight need be populated; MeanAtAge takes precedence if more than one is present.

After Populate(), Semelparous is always a ⁠Sim × Age × Year⁠ array. Do not test Semelparous(mat) == TRUE on a populated object; check any(Semelparous(mat) > 0) instead.

Slots

Pars

list. Named list of maturity model parameters whose names correspond to those expected by Model. See MaturityModels() for parameter sets and Specifying Biological and Fleet Schedules for accepted input formats.

Model

function or character(1). Maturity model identifier, matched to one of MaturityModels(). Set automatically by FindModel() when Pars is supplied without an explicit model.

MeanAtAge

array. Mean maturity-at-age with named dimensions Sim, Age, and Year. Values range from 0 (immature) to 1 (fully mature). Populated automatically by Populate() when Pars and Model are set; may also be supplied directly when Pars is empty. When Pars contains a matched model, any existing values are overwritten. See Specifying Biological and Fleet Schedules.

MeanAtLength

array. Mean maturity-at-length with named dimensions Sim, Length, and Year. Populated automatically when an at-length maturity model is used, or may be supplied directly. Converted to MeanAtAge via the ALK during Populate() when MeanAtAge is not already populated. See Specifying Biological and Fleet Schedules.

MeanAtWeight

array. Mean maturity-at-weight with named dimensions Sim, Weight, and Year. Populated automatically when an at-weight maturity model is used, or may be supplied directly. Converted to MeanAtAge via the AWK during Populate() when MeanAtAge is not already populated. Requires a populated weight object with a non-NULL CVatAge slot (so that the AWK exists). See Specifying Biological and Fleet Schedules.

Classes

numeric. Age, length, or weight class midpoints corresponding to the ⁠MeanAt*⁠ array in use.

Semelparous

logical or array. Controls post-spawning mortality. Before Populate(), a scalar TRUE or FALSE. After Populate(), always a ⁠Sim × Age × Year⁠ array where each cell gives the fraction of individuals at that age dying immediately after spawning. The default (FALSE) sets all cells to 0 (no post-spawn mortality). TRUE sets the array equal to MeanAtAge, so that post-spawn mortality tracks the maturity ogive — fully mature fish die with probability 1, fish on the ogive die proportionally, and immature fish are unaffected. A custom array may also be supplied directly. See Maturity() for details.

Misc

list. Used internally.

See Also

Other maturity: Maturity()


Maturity Models: Age, Length, and Weight

Description

Logistic maturity models

Usage

MaturityModelsWeight(full = TRUE, print = TRUE)

MaturityAtAge(Ages, A50, A50_95)

MaturityAtLength(Length, L50, L50_95)

MaturityAtWeight(Weight, W50, W50_95)

MaturityModels(full = TRUE, print = TRUE)

MaturityModelsLength(full = TRUE, print = TRUE)

MaturityModelsAge(full = TRUE, print = TRUE)

Arguments

full

Logical. Provide a complete table (TRUE) or just the model names (FALSE)?

print

Logical. Print out the results (TRUE) or just return the data.frame (FALSE)?

Ages

numeric vector of age classes (for age-based models)

A50

age at 50% maturity (Logistic-at-Age)

A50_95

interval between A50 and age at 95% maturity (Logistic-at-Age)

Length

numeric vector of length classes (for length-based models)

L50

length at 50% maturity (Logistic-at-Length)

L50_95

interval between L50 length at 95% maturity (Logistic-at-Length)

Weight

numeric vector of weight classes (for weight-based models)

W50

weight at 50% maturity (Logistic-at-Weight)

W50_95

interval between W50 weight at 95% maturity (Logistic-at-Weight)

Details

Logistic models produce standard increasing maturity curves.

  • Age-based models return proportion mature by age.

  • Length-based models return proportion mature by length.

  • Weight-based models return proportion mature by weight.

All maturity models use a logistic 50/95 parameterization:

M(x)=11+exp(ln(19)xx50x95x50)M(x) = \frac{1}{1 + \exp\left(-\ln(19) \cdot \frac{x - x_{50}}{x_{95} - x_{50}}\right)}

at-length and at-weight schedules are converted internally to at-age using the age-length age-weight key respectively.

Value

Each function returns a numeric vector of proportion mature at each age, length, or weight. MaturityModels() invisibly returns a data frame describing available models.

Prints to console and invisible data.frame or model names

See Also

Ages(), Length(), Maturity(), Weight(), Stock()

Examples

Ages <- 0:15
Length <- seq(10, 100, 10)
Weight <- seq(1, 50, 5)

M_age <- MaturityAtAge(Ages, A50 = 5, A50_95 = 3)

M_length <- MaturityAtLength(Length, L50 = 50, L50_95 = 20)

M_weight <- MaturityAtWeight(Weight, W50 = 20, W50_95 = 15)


plot(Ages, M_age, type = "l", lwd = 2,
     xlab = "Age (years)", ylab = "Proportion Mature", 
     main = "Maturity-at-Age")

plot(Length, M_length, type = "l", lwd = 2, 
     xlab = "Length", ylab = "Proportion Mature", 
     main = "Maturity-at-Length")

plot(Weight, M_weight, type = "l", lwd = 2,
     xlab = "Weight", ylab = "Proportion Mature", 
     main = "Maturity-at-Weight")

Depletion and F estimation from mean length of catches

Description

A highly dubious means of getting very uncertain estimates of current stock biomass and (equilibrium) fishing mortality rate from growth, natural mortality rate, recruitment and fishing selectivity.

Usage

ML2D(OM, ML, nsim = 100, ploty = T, Dlim = c(0.05, 0.6))

Arguments

OM

An object of class 'OM'

ML

A estimate of current mean length of catches

nsim

Number of simulations

ploty

Produce a plot of depletion and F

Dlim

Limits on the depletion that is returned as a fraction of unfished biomass.

Value

An object of class 'OM' with 'D' slot populated

Author(s)

T. Carruthers


Class 'MMSE'

Description

A Multi Management Strategy Evaluation object that contains information about simulation conditions and performance of MPs for a multi-stock, multi-fleet operating model.

Slots

Name

Name of the MMSE object. Single value. Character string

nyears

The number of years for the historical simulation. Single value. Positive integer

proyears

The number of years for the projections - closed loop simulations. Single value. Positive integer

nMPs

Number of management procedures simulation tested. Single value. Positive integer.

MPs

The names of the MPs that were tested. Vector of length nMPs. Character strings.

MPcond

The MP condition. Character ('bystock': an MP per stock, 'byfleet' and MP per stock and fleet, 'MMP' an MP for all stocks and fleets)

MPrefs

The names of the MPs applied for each stock (row) and fleet (column). An array.

nsim

Number of simulations. Single value. Positive integer

nstocks

Number of stocks. Single value. Positive integer

nfleets

Number of fleets. Single value. Positive integer

Snames

Names of the stocks

Fnames

Names of the fleets (matrix nstocks x nfleets)

Stocks

The stock operating model objects. List of Stocks

Fleets

The fleet operating model objects. Hierarchical list, fleets nested in stocks.

Obss

The fleet specific observation error operating model objects. Hierarchical list, fleets nested in stocks.

Imps

The fleet specific implementation error operating model objects. Hierarchical list, fleets nested in stocks.

OM

A table of sampled parameters of the operating model. Data frame of nsim rows.

Obs

A table of sampled parameters of the observation model. Data frame of nsim rows.

SB_SBMSY

Simulated spawning biomass relative to SBMSY over the projection. An array with dimensions: nsim, nStocks, nMPs, proyears. Non-negative real numbers

F_FMSY

Simulated fishing mortality rate relative to FMSY over the projection. An array with dimensions: nsim, nStocks, nFleets, nMPs, proyears. Non-negative real numbers

N

Simulated stock numbers over the projection. An array with dimensions: nsim, nStocks, maxage+1, nMPs, proyears, nareas. Non-negative real numbers

B

Simulated stock biomass over the projection. An array with dimensions: nsim, nStocks, nMPs, proyears. Non-negative real numbers

SSB

Simulated spawning stock biomass over the projection. An array with dimensions: nsim, nStocks, nMPs, proyears. Non-negative real numbers

VB

Simulated vulnerable biomass over the projection. An array with dimensions: nsim, nStocks, nMPs, proyears. Non-negative real numbers

FM

Simulated fishing mortality rate over the projection. An array with dimensions: nsim, nStocks, nFleets, nMPs, proyears. Non-negative real numbers

SPR

A list of SPR values. Currently not used.

Catch

Simulated catches (landings) over the projection. An array with dimensions: nsim, nStocks, nFleets, nMPs, proyears. Non-negative real numbers

Removals

Simulated removals (landings+discards) over the projection. An array with dimensions: nsim, nStocks, nFleets, nMPs, proyears. Non-negative real numbers

Effort

Simulated relative fishing effort in the projection years. An array with dimensions: nsim, nStocks, nFleets, nMPs, proyears. Non-negative real numbers

TAC

Simulated Total Allowable Catch (prescribed) over the projection (this is NA for input controls). An array with dimensions: nsim, nStocks, nFleets, nMPs, proyears. Non-negative real numbers

TAE

Simulated Total Allowable Effort (prescribed) over the projection (this is NA for output controls). An array with dimensions: nsim, nStocks, nFleets, nMPs, proyears. Non-negative real numbers

BioEco

A named list of bio-economic output. Not currently used.

RefPoint

Named list of annual MSY reference points MSY, FMSY, and SBMSY. Array with dimensions: nsim, nstocks, nMPs, nyears+proyears. Will be the same as multiHist@Ref$ByYear unless selectivity is changed by MP

multiHist

The object of class multiHist containing information from the spool-up period.

PPD

Posterior predictive data. List of Data objects at the end of the projection period (length nMPs)

Misc

Miscellaneous output such as posterior predictive data

Objects from the Class

Objects can be created by calls of the form new('MMSE', Name, nyears, proyears, nMPs, MPs, nsim, OMtable, Obs, B_BMSYa, F_FMSYa, Ba, FMa, Ca, OFLa, Effort, PAA, CAA, CAL, CALbins)

Author(s)

T. Carruthers


Selectivity, Retention, Weight, Fecundity, and Maturity Model Helpers

Description

Low-level curve functions used internally by FecundityModels(), MaturityModels(), RetentionModels(), SelectivityModels(), and WeightModels().

Usage

allometric(x, scale, exponent)

dnormal(lens, lfs, sl, sr)

double_normal(x, x5, xF, xMax)

logistic_50_95(x, x50, x50_95, asymp = 1)

Arguments

x

Numeric vector of values (ages, lengths, or weights) at which to evaluate the curve.

scale

Multiplicative scale parameter (allometric).

exponent

Power exponent (allometric).

lens

Numeric vector of lengths (dnormal).

lfs

Length at full selection, the peak of the dnormal curve.

sl

Standard deviation of the ascending limb of dnormal.

sr

Standard deviation of the descending limb of dnormal. Use Inf for a flat-topped (one-sided) curve.

x5

Value of x at 5% of the maximum (ascending limb of double_normal).

xF

Value of x at the peak of the double_normal curve.

xMax

Maximum value on the descending limb of double_normal, expressed as a proportion between 0 and 1.

x50

Value of x at 50% of the asymptote (logistic_50_95).

x50_95

Interval between the 50% and 95% points (logistic_50_95).

asymp

Asymptote of the logistic curve. Defaults to 1.

Details

allometric(x, scale, exponent)

Returns scale * x ^ exponent. Suitable for length-weight and length-fecundity relationships.

dnormal(lens, lfs, sl, sr)

Double-normal (dome-shaped) selectivity curve evaluated at lens. The ascending limb uses standard deviation sl and the descending limb uses sr. Set sr = Inf for a flat-topped curve.

S(l)=2(llfss)2S(l) = 2^{-\left(\frac{l - l_{fs}}{s}\right)^2}

where s=sls = sl if llfsl \le l_{fs} and s=srs = sr otherwise.

double_normal(x, x5, xF, xMax)

Parameterises and evaluates dnormal from three inputs: the 5% ascending point x5, the peak xF, and the descending plateau xMax. Returns a flat vector of ones if both x5 and xF are zero.

logistic_50_95(x, x50, x50_95, asymp)

Standard logistic curve parameterised by the 50% point and the 50-to-95% interval:

S(x)=a1+exp ⁣(ln19x50,95(xx50))S(x) = \frac{a}{1 + \exp\!\left(-\frac{\ln 19}{x_{50,95}}(x - x_{50})\right)}

where aa is asymp.

Value

Each function returns a numeric vector of the same length as the primary input (x or lens).

See Also

FecundityModels(), MaturityModels(), RetentionModels(), SelectivityModels(), WeightModels()


Class 'MOM'

Description

An object containing all the parameters needed to control a multi-stock, multi-fleet MSE which can be build from component Stock, Fleet, Obs, and Imp objects.

Details

Almost all of these inputs are a vector of length 2 which describes the upper and lower bounds of a uniform distribution from which to sample the parameter.

Slots

Name

Name of the operating model

Agency

Name of the agency responsible for the management of the fishery. Character string

Region

Name of the general geographic region of the fishery. Character string

Sponsor

Name of the organization who sponsored the OM. Character string

Latitude

Latitude (decimal degrees). Negative values represent the South of the Equator. Numeric. Single value

Longitude

Longitude (decimal degrees). Negative values represent the West of the Prime Meridian. Numeric. Single value

nsim

The number of simulations

proyears

The number of projected years

interval

The assessment interval - how often would you like to update the management system?

pstar

The percentile of the sample of the management recommendation for each method

maxF

Maximum instantaneous fishing mortality rate that may be simulated for any given age class

reps

Number of samples of the management recommendation for each method. Note that when this is set to 1, the mean value of the data inputs is used.

cpars

A hierarchical list nstock then nfleet long of custom parameters. Time series are a matrix nsim rows by nyears columns. Single parameters are a vector nsim long. See validcpars()

seed

A random seed to ensure users can reproduce results exactly

Source

A reference to a website or article from which parameters were taken to define the operating model

Stocks

List of stock objects

Fleets

List of Fleet objects

Obs

Hierarchical List of Observation model objects Level 1 is stock, level 2 is fleet

Imps

Hierarchical List of Implementation model objects Level 1 is stock, level 2 is fleet

CatchFrac

A list nstock long, of matrices nsim x nfleet representing the fraction of current catches of the various fleets to each stock (each matrix is nsim by nfleet long and rows sum to 1 for each stock)

Allocation

A list nstock long, of matrices nsim x nfleet representing the fraction of future TACs of the various fleets to each stock (each matrix is nsim by nfleet long and rows sum to 1 for each stock).

Efactor

A list nstock long, of current effort factors by fleet (default is 1 - same as current effort)

Complexes

A list of stock complexes. Each position is a vector of stock numbers (as they appear in StockPars) for which data should be aggregated and TAC recommendations split among stocks according to vulnerable biomass

SexPars

A list of slots that control sex-specific dynamics, i.e., sex-specific spawning and hermaphroditism. More generally, controls spawning and moving abundance between stocks. See details.

Rel

A list of biological / ecological relationships among stocks over-ridden if an MP of class 'MP_F" is supplied that is a multi-fleet MP.

Objects from the Class

Objects can be created by calls of the form new('MOM', Stock_list, Fleet_list, Obs_list, Imp_list).

SexPars

  • SSBfrom A nstock x nstock matrix that specifies the proportion of the spawning output of the row p stock for the column p' stock. A diagonal matrix means each stock is responsible for its own recruitment.

  • Herm A list with each entry containing a matrix (nsim x maxage + 1) that specifies the proportion at age that moves from stock p to p' (sequential hermaphroditism). The names of the list should be of the form "H_p'_p" where p and p' are integers that identify the stock. Arrays can also be used (nsim x maxage + 1 x nyears + proyears) for time-varying values.

  • share_par Optional. Logical to indicate whether stock-recruit, depletion, and observation/implementation parameters are mirrored between stocks. By default, TRUE.

Author(s)

T. Carruthers and A. Hordyk

See Also

Article on MOM and multiMSE: https://openmse.com/features-multimse/


Apply the movement model to the stock for one time-step

Description

Apply the movement model to the stock for one time-step

Usage

movestockCPP(nareas, maxage, mov, Number)

Arguments

nareas

The number of spatial areas

maxage

The maximum age

mov

Numeric matrix (nareas by nareas) with the movement matrix

Number

A numeric matrix (maxage+1, nareas) with current numbers-at-age in each area

Author(s)

A. Hordyk


Rcpp version of the Optimization function that returns the squared difference between user specified and calculated movement parameters.

Description

The user specifies the probability of staying in the same area and spatial heterogeneity (both in the unfished state). This function returns the squared difference between these values and those produced by the three logit movement model.

Usage

movfit_Rcpp(par, prb, frac)

Arguments

par

Three parameters in the logit space that control the four probabilities of moving between 2 areas

prb

User specified probability that individuals in area 1 remain in that area (unfished conditions)

frac

User specified fraction of individuals found in area 1 (unfished conditions)

Details

This is paired with getmov to find the correct movement model.

Author(s)

T. Carruthers with an amateur attempt at converting to Rcpp by A. Hordyk (but it works!)


Fill any NAs arising from MPCalcs (hermaphroditism mode)

Description

Fill any NAs arising from MPCalcs (hermaphroditism mode)

Usage

MPCalcsNAs(MPCalcs)

Arguments

MPCalcs

A list of arrays arising fromt the DLMtool function CalcMPDynamics()

Author(s)

T. Carruthers


Management Procedure Type

Description

Management Procedure Type

Usage

MPtype(MPs = NA)

Arguments

MPs

A vector of MP names. If none are provided function is run on all available MPs

Value

A data.frame with MP names, management type (e.g "Input", "Output") and management recommendations returned by the MP (e.g, TAC (total allowable catch), TAE (total allowable effort), SL (size-selectivity), and/or or Spatial)

See Also

Required()

Examples

## Not run: 
library(openMSE)
MPtype(c("AvC", "curE", "matlenlim", "MRreal", "FMSYref"))

## End(Not run)

mse Class

Description

The mse class stores the complete results of a Management Strategy Evaluation. It extends timeseries with the operating model, management procedures, unfished reference states, biological reference points, and the historical time-series used to initialize the projections.

Slots

OM

The om object used as the operating model.

MPs

Named list of management procedures evaluated in the MSE. Each element corresponds to one MP applied across all simulations.

Unfished

An unfished object containing unfished equilibrium and dynamic reference trajectories. See unfished for details.

Reference

A reference object containing biological and management reference points derived from the historical period. See reference for details.

Hist

A timeseries object containing the historical time-series of population and fishery dynamics used to initialize the MSE projections. Typed as timeseries rather than hist because slots such as OM, Unfished, and Reference are already present directly on the mse object, making a full hist object redundant. Use Hist() to access this slot. For the full standalone historical object, see hist.

PPD

List containing posterior predictive distribution outputs and diagnostics generated during the MSE.

Log

Internal list storing MSE diagnostics and execution metadata. Not intended for direct user access.

Misc

Named list for carrying arbitrary additional objects alongside the MSE results.

The mse class inherits all time-series slots from timeseries, covering the projection period. See timeseries for full slot descriptions including Number, Biomass, Landings, Discards, Effort, and fishing mortality arrays.

See Also

hist, timeseries, om, unfished, reference, Hist(), Advice()


Class 'MSE'

Description

A Management Strategy Evaluation object that contains information about simulation conditions and performance of data-limited methods

Slots

Name

Name of the MSE object. Single value. Character string

nyears

The number of years for the historical simulation. Single value. Positive integer

proyears

The number of years for the projections - closed loop simulations. Single value. Positive integer

nMPs

Number of management procedures simulation tested. Single value. Positive integer.

MPs

The names of the MPs that were tested. Vector of length nMPs. Character strings.

nsim

Number of simulations. Single value. Positive integer

OM

Operating model parameters (last historical year used for time-varying parameters). Data.frame with nsim rows

Obs

Observation parameters (last historical year used for time-varying parameters). Data.frame with nsim rows

SB_SBMSY

Simulated spawning biomass relative to spawning BMSY over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers

F_FMSY

Simulated fishing mortality rate relative to FMSY over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers

N

Simulated total numbers over the projection. An array with dimensions: nsim, maxage+1, nMPs, proyears, nareas. Non-negative real numbers.

B

Simulated stock biomass over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers

SSB

Simulated spawning stock biomass over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers

VB

Simulated vulnerable biomass over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers

FM

Simulated fishing mortality rate over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers

SPR

Named list with equilibrium and dynamic SPR. Each element is an array with dimensions: nsim, nMPs, proyears. Non-negative real numbers.

Catch

Simulated catches (landings) over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers

Removals

Simulated removals (catch + discards) over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers

Effort

Simulated relative fishing effort in the projection years. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers

TAC

Simulated Total Allowable Catch prescribed by MPs. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers

TAE

Simulated Total Allowable Effort prescribed by MPs. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers

BioEco

Named list with bio-economic output Only used if bio-economic parameters are included in OM

RefPoint

Named list of annual MSY reference points MSY, FMSY, and SBMSY. Array with dimensions: nsim, nMPs, nyears+proyears. Will be the same as Hist@Ref$ByYear unless selectivity is changed by MP

CB_hist

Simulated catches (landings) from the spool-up period. An array with dimensions: nsim, nyears. Non-negative real numbers

FM_hist

Simulated fishing mortality rate from the spool-up period. An array with dimensions: nsim, nyears Non-negative real numbers

SSB_hist

Simulated spawning stock biomass from the spool-up period. An array with dimensions: nsim, nyears. Non-negative real numbers

Hist

Information from the historical spool-up period. Object of class Hist. Only contains slots AtAge and TSdata unless extended=TRUE in runMSE

PPD

Posterior predictive data. List of Data objects at the end of the projection period (length nMPs)

Misc

Miscellaneous output

Author(s)

T. Carruthers and A. Hordyk


Convert an mse Object to a Slick Object

Description

Converts an mse object (or a list of mse objects) into a Slick::Slick() data object for interactive visualization in the Slick App.

Usage

MSE2Slick(MSE)

Arguments

MSE

An mse object or a named list of mse objects, where each element represents a different OM. All objects in the list must have identical MPs, number of simulations, and number of time steps.

Details

A Slick::Slick() object is a standardized data structure containing MSE results, MP metadata, and performance indicators. It can be passed directly to Slick::App() for interactive exploration, or saved and uploaded to the online Slick App.

When MSE is a list, each element should represent a different Operating Model (OM) hypothesis tested with the same set of MPs. All mse objects in the list must have identical MPs, number of simulations, and number of time steps.

The resulting Slick::Slick() object includes:

  • MPs: management procedure codes, labels, and display colours.

  • Kobe: SB/SBMSY and F/FMSY time series for the Kobe plot.

  • Timeseries: projection-period time series for spawning biomass, fishing mortality, landings, SB/SBMSY, and F/FMSY.

Value

A Slick::Slick() object ready for use with Slick::App().

See Also

Slick::Slick(), Slick::App(), mse

Examples

## Not run: 
Slick <- MSE2Slick(MSE)
Slick::App(slick=Slick)

# Multiple OMs
Slick <- MSE2Slick(list(MSE_Base, MSE_LowM, MSE_HighM))
Slick::App(slick=Slick)

## End(Not run)

MSEDescription

Description

A data.frame with description of slots for class MSE

Usage

MSEDescription

Format

An object of class data.frame with 29 rows and 2 columns.


Load more data from MSEextra package

Description

Downloads the MSEextra package from GitHub

Usage

MSEextra(silent = FALSE)

Arguments

silent

Logical. Should messages to printed?


Access MSY Reference Point Slots

Description

Accessor functions for MSY-based biological reference points stored in Hist@Reference@MSY. Each function returns the corresponding array from a hist or mse object.

Usage

MSYRefs(Hist)

FMSY(Hist)

BMSY(Hist)

SBMSY(Hist)

SPMSY(Hist)

SPRMSY(Hist)

MSYLandings(Hist)

MSYDiscards(Hist)

Arguments

Hist

A hist or mse object.

Details

The available accessor functions and the quantities they return are:

  • MSYRefs(): the full refpointsMSY object containing all slots.

  • FMSY(): apical fishing mortality at MSY, defined at the complex level (⁠Sim × Complex × Year⁠).

  • BMSY(): total biomass at MSY.

  • SBMSY(): spawning biomass at MSY.

  • SPMSY(): spawning production at MSY.

  • SPRMSY(): spawning potential ratio at MSY.

  • MSYLandings(): landed catch at MSY.

  • MSYDiscards(): dead discards at MSY.

Value

A numeric array with dimensions ⁠Sim × Stock × Year⁠, except FMSY() which returns ⁠Sim × Complex × Year⁠. Returns NULL if the slot has not yet been populated (i.e. CalcMSY() has not been run).

See Also

CalcMSY(), refpointsMSY


Internal function to calculate MSY Reference Points

Description

Internal function to calculate MSY Reference Points

Usage

MSYCalcs(
  logF,
  M_at_Age,
  Wt_at_Age,
  Mat_at_Age,
  Fec_at_Age,
  V_at_Age,
  Wt_at_Age_C,
  maxage,
  relRfun,
  SRRpars,
  R0x = 1,
  SRrelx = 3L,
  hx = 1,
  SSBpR = 0,
  opt = 1L,
  plusgroup = 1L,
  spawn_time_frac = 0
)

Arguments

logF

log fishing mortality

M_at_Age

Vector of M-at-age

Wt_at_Age

Vector of stock weight-at-age

Mat_at_Age

Vector of maturity-at-age

Fec_at_Age

Vector of mature weight-at-age

V_at_Age

Vector of selectivity-at-age

Wt_at_Age_C

Vector of fishery weight-at-age

maxage

Maximum age

relRfun

Optional. A function used to calculate reference points if SRrelc =3

SRRpars

Optional. A named list of arguments for SRRfun

R0x

R0 for this simulation. Set = 1 if SRrelx = 4 for per-recruit calculations

SRrelx

SRR type for this simulation. Use 4 for per-recruit calculations, i.e. constant recruitment.

hx

numeric. Steepness value for this simulation. Not used if SRrelx = 4.

SSBpR

numeric. Unfished spawners per recruit for this simulation. Not used if SRrelx = 4.

opt

Option. 1 = return -Yield, 2= return all MSY calcs

plusgroup

Integer. Default = 0 = no plus-group. Use 1 to include a plus-group

spawn_time_frac

Numeric. Fraction of the year when spawning occurs. Default = 0.

Value

See opt


Combine data among fleets

Description

Catches, CAA, CAL are summed. LFC and LFS are weighted averages. ML, Lc and Lbar are recalculated from summed CAL. All other observations are for fleet 1 (indicative)

Usage

multiData(MSElist, StockPars, p, mm, nf)

Arguments

MSElist

A hierarchical list of data objects stock then fleet then MP

StockPars

A list of stock parameters

p

Integer the Stock number

mm

Integer the MP number

nf

The number of fleets

Author(s)

T. Carruthers


Combine data among stocks

Description

Catches, CAA, CAL are summed. Indices, LFC and LFS are weighted averages. ML, Lc and Lbar are recalculated from summed CAL. All other observations are for fleet 1 and weighted average across stocks

Usage

multiDataS(MSElist, Real.Data.Map, np, mm, nf, realVB)

Arguments

MSElist

A hierarchical list of data objects stock then fleet then MP

Real.Data.Map

Matrix describing which data are mapped across stocks

np

The number of stocks

mm

Integer the MP number

nf

The number of fleets

realVB

A matrix of real vulnerable biomass ⁠[nsim,np, year]⁠

Author(s)

T. Carruthers


A basic comparison of runMSE output (MSE) and multiMSE (MMSE)

Description

A basic comparison of runMSE output (MSE) and multiMSE (MMSE)

Usage

multidebug(MSEsingle, MSEmulti, p = 1, f = 1, MPno = 1, maxsims = 4)

Arguments

MSEsingle

An object of class MSE arising from a run of runMSE(OM, ...)

MSEmulti

An object of class MMSE arising from a run of multiMSE(MOM, ...)

p

Integer. The stock number from the MSEmulti object (to be plotted)

f

Integer. The fleet number from the MSEmulti object (to be plotted)

MPno

Integer. The MP number from the MSEmulti and MSEsingle object (to be plotted)

maxsims

Integer. The maximum number of simulations to plot.

Author(s)

T.Carruthers


Multi-Stock Multi-Fleet Example Operating Model

Description

An example om object representing the most complex structural case: two biologically contrasting stocks each exploited by two fleets, with observation models varying by both stock and fleet. Intended to illustrate multi-stock, multi-fleet OM construction in MSEtool. Pairings of stocks, fleets, and observation models are for illustration only and should not be taken as ecologically meaningful. See also SingleStockOM, TwoFleetOM, and ComplexOM for simpler structural examples.

Usage

MultiStockOM

Format

An om object with the following slots populated:

  • Name: "Multi Stock - Multi Fleet".

  • nSim: 8. Number of stochastic simulations.

  • nYear: 20. Number of historical years.

  • pYear: 30. Number of projection years.

  • Stock: a length-2 list of ⁠[[AlbacoreExStock, ButterfishExStock]]⁠.

  • Fleet: a length-2 list, each containing a length-2 list of ⁠[[AsympExFleet, DomeExFleet]]⁠. Structure is ⁠[[stock]][[fleet]]⁠. Both stocks are fished by the same two fleet types.

  • Obs: a length-2 list with structure ⁠[[stock]][[fleet]]⁠:

  • Complexes: NULL. Stocks are managed independently.

  • Imp: NULL. Implementation error is not specified; the Imp slot retains its class default. See Imp() for details.

Details

Stocks

Two biologically contrasting stocks are included:

See AlbacoreExStock and ButterfishExStock for full parameter details.

Fleets

Both stocks are fished by the same two fleet types:

  • AsympExFleet: asymptotic length-based selectivity; effort stabilises early in the historical period.

  • DomeExFleet: dome-shaped selectivity; effort increases gradually across the historical period.

See AsympExFleet and DomeExFleet for full parameter details.

Observation Models

Observation models vary by stock and fleet, illustrating a range of monitoring intensities across the two stocks:

Implementation Error

The Imp slot is NULL. The imp is currently a placeholder and implementation error is not applied during simulation. See Imp() for details.

See Also

SingleStockOM, TwoFleetOM, ComplexOM for simpler structural variants. AlbacoreExStock, ButterfishExStock, AsympExFleet, DomeExFleet, AgeStructuredObs, CommercialFleetObs, CatchAndSurveyObs, LengthStructuredObs for the component objects. OM(), om, runMSE(), PopulateOM(), ExampleMPs()

Other om: ComplexOM, OM(), OM-accessors, SingleStockOM, TwoFleetOM, om-class

Examples

MultiStockOM
nStock(MultiStockOM)
nFleet(MultiStockOM)

## Not run: 
Hist <- runMSE(MultiStockOM, MPs = ExampleMPs())

## End(Not run)

Access Stock or Fleet Names

Description

Access Stock or Fleet Names

Usage

StockNames(object)

FleetNames(object, IncSurvey = FALSE)

Arguments

object

An om, hist, stock, fleet, or mse object.

IncSurvey

Logical. Include names of survey (non-fishing) fleets? Default: FALSE

Details

These functions extract stock or fleet names from objects used in the MSE framework, including om, hist, stock, fleet, and mse objects

StockNames

Returns the names of stocks contained in the object.

FleetNames

Returns the names of fleets contained in the object. For objects containing multiple stocks, a list of character vectors is returned.

Value

  • StockNames(): a character vector of stock names

  • FleetNames(): a character vector of fleet names (always taken from the first stock)

Examples

StockNames(SingleStockOM)
FleetNames(SingleStockOM)

NaturalMortality Constructor and Accessors

Description

Construct a naturalmortality object defining the natural mortality schedule for a stock, or access and replace the NaturalMortality slot of a stock and its individual slots. A NaturalMortality object is required for all stock objects.

Usage

NaturalMortality(
  Pars = list(),
  Model = NULL,
  Units = "year",
  MeanAtAge = NULL,
  MeanAtLength = NULL,
  Random = NULL,
  Classes = NULL,
  Misc = list()
)

NaturalMortality(x) <- value

Arguments

Pars

list. Named list of natural mortality parameters. Element names must match the arguments of a built-in mortality model (see NaturalMortalityModels()). When Pars is non-empty and Model is NULL, the model is inferred automatically by FindModel(). When Pars is a stock object, NaturalMortality() acts as a pass-through accessor and returns x@NaturalMortality. See also Specifying Biological and Fleet Schedules for the full set of accepted input formats. Default list().

Model

character(1) or function. Natural mortality model identifier. When NULL (default), the model is inferred from Pars via FindModel(). May be set to a character string naming a built-in model or to a custom R function — see Specifying Biological and Fleet Schedules.

Units

character(1). Time unit in which mortality rates are expressed. Must be one of the strings returned by ValidUnits() (e.g., "year" for instantaneous annual mortality). For seasonal models, set Units to match the season length so that within-step rates are scaled correctly during Populate(). Default "year".

MeanAtAge

array or NULL. Mean instantaneous natural mortality at age with named dimensions ⁠Sim × Age × Year⁠. Supply directly when bypassing the model-based approach (Pars = list()). Only the years at which values change need to be included; Extend() fills the remainder. When Pars contains a matched model, any values here are overwritten during Populate(). A numeric vector of length nAge is also accepted and promoted to a ⁠1 × nAge × 1⁠ array automatically. Default NULL.

MeanAtLength

array or NULL. Mean natural mortality at length with named dimensions ⁠Sim × Length × Year⁠. Populated automatically during Populate() when an at-length mortality model is used; may also be supplied directly. When MeanAtLength is populated and MeanAtAge is not, Populate() converts it to MeanAtAge via the age-length key (ALK) from a length object. Default NULL.

Random

array or NULL. Reserved for future use. Intended to hold simulation- and year-specific multipliers that add stochastic variation around the average mortality schedule in MeanAtAge. Currently stored but not applied during Populate(). Default NULL.

Classes

numeric or NULL. Age or length class midpoints corresponding to the ⁠MeanAt*⁠ array in use. Default NULL.

Misc

list. Used internally. Default list().

x

A naturalmortality object for slot accessors, or a stock object for ⁠NaturalMortality<-⁠.

value

For ⁠NaturalMortality<-⁠: a naturalmortality object.

Details

Specifying Natural Mortality

There are two ways to define the mortality schedule; see Specifying Biological and Fleet Schedules for full details on input formats and the rules that govern how Pars, Model, and ⁠MeanAt*⁠ arrays interact.

Model-based (recommended): supply Pars with named parameters matching a built-in model (see NaturalMortalityModels()). If Model = NULL and the parameter names uniquely match a model, FindModel() resolves the model automatically. MeanAtAge is then populated by Populate() when the stock is added to an OM():

# Constant M — model inferred from Pars names
nm <- NaturalMortality(Pars = list(M = 0.2))

# Stochastic M across simulations
nm <- NaturalMortality(Pars = list(M = c(0.1, 0.3)))

# Time-varying M (increases in 2010; Extend() fills the rest)
M_arr <- array(c(0.2, 0.3), dim = c(1, 2),
               dimnames = list(Sim = 1, Year = c(1990, 2010)))
nm <- NaturalMortality(Pars = list(M = M_arr))

# Inter-annual random walk on M (log-normal, SD = 0.1)
nm <- NaturalMortality(Pars = list(M = c(0.1, 0.3), MSD = 0.1))

Direct array: supply MeanAtAge (or MeanAtLength) with Pars = list(). Values are preserved during Populate():

ages  <- 0:20
# Age-varying M declining from 0.5 at age 0 to 0.1 at the plus group
nm_aa <- NaturalMortality(
  MeanAtAge = array(
    seq(0.5, 0.1, length.out = length(ages)),
    dim      = c(1, length(ages), 1),
    dimnames = list(Sim = 1, Age = ages, Year = 1990)
  )
)

Units and Seasonal Models

Rates in MeanAtAge are instantaneous mortality values (M) expressed over the period defined by Units. The default Units = "year" means annual M. For seasonal models, set Ages@Units to the season length (e.g., "quarter" for quarterly steps) and make sure the rate parameters (e.g., M and K) are in the same temporal units.

At-Length Models

Models whose class contains "at-Length" produce MeanAtLength, which is converted to MeanAtAge via the ALK — a populated Length() object must be passed to Populate(). The same conversion applies when MeanAtLength is supplied directly by the user.

Pass-Through Access from a Stock

When Pars is a stock object, NaturalMortality() returns the NaturalMortality slot directly:

NaturalMortality(my_stock)           # returns my_stock@NaturalMortality
NaturalMortality(my_stock) <- my_M   # replaces it

Slot Accessors

Individual slots can be read or replaced using generic functions matching their names. All replacement functions re-validate the object:

Pars(nm)          <- list(M = 0.2)
Model(nm)         <- "Constant"
Units(nm)         <- "year"
MeanAtAge(nm)     <- my_array
MeanAtLength(nm)  <- my_length_array
Classes(nm)       <- 0:20

Value

  • NaturalMortality() returns a naturalmortality object. If Pars is a stock, returns x@NaturalMortality.

  • ⁠NaturalMortality<-⁠ returns the stock x with the NaturalMortality slot replaced and the object re-validated.

See Also

Other naturalmortality: naturalmortality-class

Examples

# See NaturalMortalityModels() for all available built-in natural mortality
# models and the parameter names required for each.
NaturalMortalityModels()

# ---- Model-based specification ----

## Constant M (scalar) — same value for every simulation and year
nm <- NaturalMortality(Pars = list(M = 0.2))

## Stochastic across simulations — M drawn from Uniform(lower, upper)
## once per simulation
nm <- NaturalMortality(Pars = list(M = c(0.1, 0.3)))

## Inter-annual random walk on M — log-normal with 10% CV
## MSD is removed from Pars after use
nm <- NaturalMortality(Pars = list(M   = c(0.1, 0.3),
                                   Msd = 0.1))

## Time-varying M with named change-point arrays
## Only the years where values change need to be supplied; Extend() fills
## all intermediate and future years by forward-filling automatically.
nSim <- 48

## M increases in 2010 (two change points: 1990 and 2010)
M_arr <- array(
  c(rep(0.2, nSim), rep(0.3, nSim)),
  dim      = c(nSim, 2),
  dimnames = list(Sim = seq_len(nSim), Year = c(1990, 2010))
)
nm <- NaturalMortality(Pars = list(M = M_arr))

## Combine stochastic (across sims) and time-varying (across years)
M_sim  <- runif(nSim, 0.1, 0.3)
M_arr2 <- array(
  c(M_sim, M_sim * 1.2),              # 20% increase from 2010 onward
  dim      = c(nSim, 2),
  dimnames = list(Sim = seq_len(nSim), Year = c(1990, 2010))
)
nm <- NaturalMortality(Pars = list(M = M_arr2))

# ---- Direct array specification ----

## Supply MeanAtAge directly (Pars left empty).
## A plain numeric vector of length nAge is accepted; treated as a single
## simulation, single year and replicated by Extend() as needed.
ages  <- 0:20
nm_aa <- NaturalMortality(
  MeanAtAge = seq(0.5, 0.1, length.out = length(ages))
)

## Named Sim x Age x Year array — age-varying M that shifts in 2010.
## Extend() replicates Sim = 1 to all nSim simulations automatically.
maa <- array(
  c(seq(0.5, 0.1, length.out = length(ages)),   # 1990 schedule
    seq(0.6, 0.15, length.out = length(ages))),  # 2010 schedule (M higher)
  dim      = c(1, length(ages), 2),
  dimnames = list(Sim = 1, Age = ages, Year = c(1990, 2010))
)
nm_arr <- NaturalMortality(MeanAtAge = maa)

## Supply MeanAtLength directly — converted to MeanAtAge via the ALK
## during Populate() when a Length object is provided.
lens  <- seq(5, 120, by = 5)
nm_al <- NaturalMortality(
  MeanAtLength = array(
    0.4 * exp(-0.02 * lens),          # M declining with length
    dim      = c(1, length(lens), 1),
    dimnames = list(Sim = 1, Length = lens, Year = 1990)
  )
)

# ---- Slot accessors ----

nm <- NaturalMortality(Pars = list(M = 0.2))

## Read slots
MeanAtAge(nm)     # NULL until Populate() is called
Units(nm)

## Replace slots
Units(nm)  <- "quarter"
Classes(nm) <- 0:20

# ---- Attaching to a Stock ----

stk <- Stock(Name = "Example stock", Ages = Ages(MaxAge = 20))
NaturalMortality(stk) <- NaturalMortality(Pars = list(M = 0.2))
NaturalMortality(stk)

# ---- Populate ----

## The final populated object (typically done internally).
## At-length models require a populated Length object passed to Populate().
pop_nm <- Populate(NaturalMortality(stk), Ages = Ages(MaxAge = 20))
pop_nm

MeanAtAge(pop_nm)

The naturalmortality S4 Class

Description

Defines the natural mortality schedule for a stock object. Mortality may be expressed as a function of age or length, and may vary across simulations and years. Objects are typically created via NaturalMortality(), which documents all parameters, validates inputs, and infers the mortality model automatically when possible.

Details

Direct construction via methods::new() is not recommended; use NaturalMortality() instead, which handles model inference and object validation.

Rates in MeanAtAge are instantaneous mortality values (M) expressed over the period defined by Units. For seasonal models, set Units to match the season length so that within-step rates are scaled correctly during Populate().

Slots

Pars

list. Named list of natural mortality parameters whose names correspond to those expected by Model. See NaturalMortalityModels() for parameter sets and Specifying Biological and Fleet Schedules for accepted input formats.

Model

function or character(1). Natural mortality model identifier, matched to one of NaturalMortalityModels(). Set automatically by FindModel() when Pars is supplied without an explicit model.

Units

character(1). Time unit in which mortality rates are expressed (e.g., "year" for instantaneous annual mortality). Must be accepted by ValidUnits() and match those used in Ages().

MeanAtAge

array. Mean instantaneous natural mortality at age with named dimensions Sim, Age, and Year. Populated automatically by Populate() when Pars and Model are set; may also be supplied directly when Pars is empty. When Pars contains a matched model, any existing values are overwritten. See Specifying Biological and Fleet Schedules.

MeanAtLength

array. Mean natural mortality at length with named dimensions Sim, Length, and Year. Populated automatically when an at-length mortality model is used, or may be supplied directly. Converted to MeanAtAge via the ALK during Populate() when MeanAtAge is not already populated. See Specifying Biological and Fleet Schedules.

Random

array. Reserved for future use. Intended to hold simulation- and year-specific multipliers that add stochastic variation around the average mortality schedule in MeanAtAge. Currently stored but not applied during Populate().

Classes

numeric. Age or length class midpoints corresponding to the ⁠MeanAt*⁠ array in use.

Misc

list. Used internally.

See Also

Other naturalmortality: NaturalMortality()


Natural Mortality Models

Description

Natural mortality models for age, length, and weight.

Usage

MortalityAtAge(Ages, M)

LorenzenMortalityLength(Length, Mref, Lref, c = -0.288)

LorenzenMortalityWeight(Weight, Mref, Wref, c = -0.288)

NaturalMortalityModels(full = TRUE, print = TRUE)

Arguments

Ages

numeric vector of age classes

M

natural mortality rate. Recycled if not length(Ages)

Length

numeric vector of length classes

Mref

reference mortality

Lref

reference length for Lorenzen M-at-length

c

exponent for Lorenzen models (default -0.288)

Weight

numeric vector of weight classes

Wref

reference weight for Lorenzen M-at-weight

full

logical; provide a complete table of models (TRUE) or just model names (FALSE)

print

logical; print results (TRUE) or return data frame invisibly (FALSE)

Details

at-length and at-weight schedules are converted internally to at-age using the age-length age-weight key respectively.

  • M-at-age:

    M(a)=MM(a) = M

  • Lorenzen M-at-length:

    M(L)=Mref(LLref)0.288M(L) = M_{ref} \cdot \left(\frac{L}{L_{ref}}\right)^{-0.288}

  • Lorenzen M-at-weight:

    M(W)=Mref(WWref)0.288M(W) = M_{ref} \cdot \left(\frac{W}{W_{ref}}\right)^{-0.288}

NaturalMortalityModels() prints a list of available models.

Value

Numeric vector of natural mortality at each age, length, or weight. NaturalMortalityModels() invisibly returns a data frame describing available models.

See Also

Ages(), Length(), Weight(), Stock()

Examples

Ages <- 0:15
Length <- seq(10, 100, 10)
Weight <- seq(1, 50, 5)

M_age <- MortalityAtAge(Ages, M = 0.2)

M_length_lor <- LorenzenMortalityLength(Length, Mref = 0.3, Lref = 50)

M_weight_lor <- LorenzenMortalityWeight(Weight, Mref = 0.3, Wref = 20)

# Plot M-at-age
plot(Ages, M_age, type = "l", lwd = 2, col = "blue", 
     xlab = "Age", ylab = "M", main = "Constant M-at-Age",
     ylim=c(0,0.25))

# Plot M-at-length
plot(Length, M_length_lor, type = "l", lwd = 2, col = "green", 
     xlab = "Length", ylab = "M", main = "Lorenzen M-at-Length",
     ylim=c(0, 0.5))

# Plot M-at-weight
plot(Weight, M_weight_lor, type = "l", lwd = 2, col = "purple", 
     xlab = "Weight", ylab = "M", main = "Lorenzen M-at-Weight", 
     ylim=c(0,0.8))

Item in list: get the list values from a list of lists

Description

Create of vector of values that correspond with a slot in a list of objects

Usage

NIL(listy, namey, lev1 = T)

Arguments

listy

A list of objects

namey

A character vector representing the list item's name

lev1

Logical, should NIL default to the first level of the list?

Author(s)

T. Carruthers


National Oceanographic and Atmospheric Administration default plot 1

Description

A preliminary plot for returning trade-offs plots and performance table for total yield, variability in yield, probability of overfishing and likelihood of biomass dropping below 50 per cent BMSY

Usage

NOAA_plot(MSEobj, nam = NA, type = NA, panel = T)

Arguments

MSEobj

An object of class MSE

nam

Title of plot

type

Plots full range of data if NA. Plots a subset that meet thresholds if not NA.

panel

Should a two panel plot be made or should plots be made in sequence.

Value

A table of performance metrics.

Author(s)

T. Carruthers


Extract Number-at-Age time series

Description

Returns the number of individuals (abundance) from a hist or mse object, either as a list of length nStock() or a data.frame.

Usage

Number(object, df = FALSE, byAge = FALSE, byArea = FALSE)

Arguments

object

A hist or mse object.

df

Logical. If FALSE (default) the raw array slot is returned. If TRUE a tidy data.frame is returned.

byAge

Logical. If TRUE the data frame retains the Age dimension rather than summing over ages. Ignored when df = FALSE.

byArea

Logical. If TRUE the data frame retains the Area dimension rather than summing over areas. Ignored when df = FALSE.

Value

  • df = FALSE — the raw Number array slot (list of arrays, one per stock).

  • df = TRUE — a data.frame (subclass "number.df") with columns Sim, Stock, Year, Period, MP (MSE only), and optionally Age / Area, plus Value, Variable, and Units.

See Also

Biomass(), SBiomass(), SProduction()

Examples

Hist <- Simulate(SingleStockOM)
Number(Hist, df = TRUE)
Number(Hist, df = TRUE, byAge = TRUE)
Number(Hist, df = TRUE, byAge = TRUE, byArea = TRUE)

Obs Constructor and Accessor

Description

Construct an obs object defining the observation error structure for each data type in the operating model, or extract the Obs slot from an enclosing object.

Usage

Obs(
  Name = NULL,
  LifeHistory = NULL,
  Exploitation = NULL,
  Effort = NULL,
  Landings = NULL,
  Discards = NULL,
  CPUE = NULL,
  Survey = NULL,
  LandingsAtAge = NULL,
  DiscardsAtAge = NULL,
  LandingsAtSize = NULL,
  DiscardsAtSize = NULL,
  Misc = list()
)

Obs(x) <- value

Arguments

Name

character(1) or an S4 object. Unique identifier for this observation model. Default NULL.

If Name is an om object, Obs() returns Name@Obs (the top-level observation model list) rather than constructing a new object. If Name is a hist or mse object, Obs() returns the Obs slot of the embedded OM (Name@OM@Obs). See Pass-Through Access in Details.

LifeHistory

A lifehistoryobs object, or NULL (default). When NULL, an empty lifehistoryobs is created via LifeHistoryObs(). Currently a placeholder; see LifeHistoryObs().

Exploitation

An exploitationobs object, or NULL (default). When NULL, an empty exploitationobs is created via ExploitationObs(). Currently a placeholder; see ExploitationObs().

Effort

An effortobs object, or NULL (default). When NULL, an empty effortobs is created via EffortObs().

Landings

A catchobs object, or NULL (default). When NULL, an empty catchobs is created via CatchObs(). Defines observation error for landed catch.

Discards

A catchobs object, or NULL (default). When NULL, an empty catchobs is created via CatchObs(). Defines observation error for discarded catch.

CPUE

An indicesobs object, or NULL (default). When NULL, an empty indicesobs is created via IndicesObs(). Defines observation error for CPUE indices.

Survey

An indicesobs object, or NULL (default). When NULL, an empty indicesobs is created via IndicesObs(). Defines observation error for fishery-independent survey indices.

LandingsAtAge

A compobs object, or NULL (default). When NULL, an empty compobs is created via CompObs(). Defines observation error for landed catch-at-age composition.

DiscardsAtAge

A compobs object, or NULL (default). When NULL, an empty compobs is created via CompObs(). Defines observation error for discarded catch-at-age composition.

LandingsAtSize

A compobs object, or NULL (default). When NULL, an empty compobs is created via CompObs(). Defines observation error for landed catch-at-length composition.

DiscardsAtSize

A compobs object, or NULL (default). When NULL, an empty compobs is created via CompObs(). Defines observation error for discarded catch-at-length composition.

Misc

list. Miscellaneous additional objects. Default list().

x

An om object.

value

A two-level named list of obs objects, or a single obs object, to assign to the Obs slot.

Details

Sub-Object Initialisation

All sub-object slots are initialised to empty objects of the appropriate class when not supplied. Empty sub-objects cause the model to skip observation error for that data type (e.g., an empty Landings slot means catch is reported without observation error). To activate observation error for a data type, supply a sub-object with at least CV specified.

Pass-Through Access

When Name is an om, hist, or mse object, Obs() extracts the Obs slot of the embedded OM rather than constructing a new object:

  • Obs(om)om@Obs

  • Obs(hist)hist@OM@Obs

  • Obs(mse)mse@OM@Obs

The result in all cases is the two-level named list ⁠[[stock_complex]][[fleet_name]]⁠ of obs objects stored in the OM.

Attaching to an OM

A single obs object can be assigned to a specific stock complex and fleet slot with:

Obs(om) <- MyObs           # replaces the full Obs list

Individual sub-objects are more commonly set directly on the obs object before it is inserted into the OM.

Value

  • Obs() returns an obs object. When Name is an om, hist, or mse object, returns the Obs slot of the embedded OM (a two-level named list of obs objects).

  • ⁠Obs<-⁠ returns x with the Obs slot replaced by value.

See Also

Other obs: CatchObs(), CompObs(), EffortObs(), ExploitationObs(), IndicesObs(), LifeHistoryObs(), catchobs-class, compobs-class, effortobs-class, exploitationobs-class, indicesobs-class, lifehistoryobs-class, obs-class

Examples

# Empty obs object
obs <- Obs()
obs

# Obs with catch observation error specified
obs <- Obs(
  Name     = "MyObs",
  Landings = CatchObs(CV = 0.2, Bias = 1.0),
  CPUE     = IndicesObs(CV = 0.3)
)

# Pass-through: extract Obs from an OM
# Obs(my_om)

The obs S4 Class

Description

Defines the observation error structure applied to each data type in the operating model. Each slot contains a sub-object specifying bias, CV, and sampling structure for one category of observed data. Objects are typically created via the Obs() constructor, which documents all parameters in detail.

Details

An obs object defines how each data type is observed, i.e., the error structure (CV, bias, selectivity). Observed values are held in data objects stored in OM@Data, Hist@Data, and MSE@PPD.

OM@Obs is a two-level named list indexed first by stock complex, then by fleet or index name:

OM@Obs[[stock_complex]][[fleet_name]]  →  obs-class object

Stock complexes aggregate stocks whose data are reported together (e.g., combined landings across species). This indexing mirrors OM@Data.

The slots Effort, Landings, Discards, CPUE, Survey, LandingsAtAge, DiscardsAtAge, LandingsAtSize, and DiscardsAtSize are populated with empty sub-objects by Obs() when not supplied. The LifeHistory and Exploitation slots are reserved for future use and are not currently populated during model runs; see LifeHistoryObs() and ExploitationObs().

Direct construction via methods::new() is not recommended; use Obs() instead, which initialises all sub-objects automatically.

Slots

Name

character or NULL. Unique identifier for this observation model. See Obs().

LifeHistory

A lifehistoryobs object. Observation error on life-history parameters (growth, maturity, natural mortality, etc.). See LifeHistoryObs().

Exploitation

An exploitationobs object. Observation error on exploitation processes (selectivity, retention, discard mortality). See ExploitationObs().

Effort

An effortobs object. Observation error on fishing effort. See EffortObs().

Landings

A catchobs object. Observation error on landed catch. See CatchObs().

Discards

A catchobs object. Observation error on discarded catch. See CatchObs().

CPUE

An indicesobs object. Observation error on catch-per-unit-effort indices. See IndicesObs().

Survey

An indicesobs object. Observation error on fishery-independent survey indices. See IndicesObs().

LandingsAtAge

A compobs object. Observation error on landed catch-at-age composition. See CompObs().

DiscardsAtAge

A compobs object. Observation error on discarded catch-at-age composition. See CompObs().

LandingsAtSize

A compobs object. Observation error on landed catch-at-length composition. See CompObs().

DiscardsAtSize

A compobs object. Observation error on discarded catch-at-length composition. See CompObs().

Misc

list. Miscellaneous additional objects.

See Also

Other obs: CatchObs(), CompObs(), EffortObs(), ExploitationObs(), IndicesObs(), LifeHistoryObs(), Obs(), catchobs-class, compobs-class, effortobs-class, exploitationobs-class, indicesobs-class, lifehistoryobs-class


Class 'Obs'

Description

An operating model component that controls the observation model

Slots

Name

The name of the observation model object. Single value. Character string.

Name

The name of the Observation error object. Single value. Character string.

Cobs

Observation error around the total catch. Observation error in the total catch is expressed as a coefficient of variation (CV). Cobs requires upper and lower bounds of a uniform distribution, and for each simulation a CV is sampled from this distribution. Each CV is used to specify a log-normal error distribution with a mean of 1 and a standard deviation equal to the sampled CV. The yearly observation error values for the catch data are then drawn from this distribution. For each time step the simulation model records the true catch, but the observed catch is generated by applying this yearly error term (plus any bias, if specified) to the true catch.

Cbiascv

Log-normally distributed coefficient of variation controlling the sampling bias in observed catch for each simulation. Bias occurs when catches are systematically skewed away from the true catch level (for example, due to underreporting of catch or undetected illegal catches). Cbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years.

CAA_nsamp

Number of catch-at-age observations collected per time step. For each time step a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. Positive integers.

CAA_ESS

Effective sample size of catch-at-age observations collected per time step. For each time step a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. CAA_ESS should not exceed CAA_nsamp. If greater than 1, then this is the multinomial distribution sample size. If less than 1, this is the coefficient of variation for the logistic normal distribution (see help doucmentation for simCAA for details).

CAL_nsamp

Number of catch-at-length observations collected per time step. For each time step a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. Positive integers.

CAL_ESS

Effective sample size. For each time step a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. CAL_ESS should not exceed CAL_nsamp. Positive integers.

Iobs

Observation error in the relative abundance index expressed as a coefficient of variation (CV). Iobs requires upper and lower bounds of a uniform distribution, and for each simulation a CV is sampled from this distribution. Each CV is used to specify a log-normal error distribution with a mean of 1 and a standard deviation equal to the sampled CV. The yearly observation error values for the index of abundance data are then drawn from this distribution. For each time step the simulation model records the true change in abundance, but the observed index is generated by applying this yearly error term (plus any bias, if specified) to the true relative change in abundance. Positive real numbers.

Btobs

Observation error in the absolute abundance expressed as a coefficient of variation (CV). Btobs requires upper and lower bounds of a uniform distribution, and for each simulation a CV is sampled from this distribution. Each CV is used to specify a log-normal error distribution with a mean of 1 and a standard deviation equal to the sampled CV. The yearly observation error values for the absolute abundance data are then drawn from this distribution. For each time step the simulation model records the true abundance, but the observed abundance is generated by applying this yearly error term (plus any bias, if specified) to the true abundance. Positive real numbers.

Btbiascv

Log-normally distributed coefficient (CV) controlling error in observations of the current stock biomass. Bias occurs when the observed index of abundance is is systematically higher or lower than the true relative abundance. Btbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

beta

A parameter controlling hyperstability/hyperdepletion in the measurement of abundance. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. Values below 1 lead to hyperstability (the observed index decreases more slowly than the true abundance) and values above 1 lead to hyperdepletion (the observed index decreases more rapidly than true abundance). Positive real numbers.

LenMbiascv

Log-normal coefficient of variation for sampling bias in observed length at 50 percent maturity. LenMbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

Mbiascv

Log-normal coefficient of variation for sampling bias in observed natural mortality rate. Mbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

Kbiascv

Log-normal coefficient of variation for sampling bias in observed growth parameter K. Kbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

t0biascv

Log-normal coefficient of variation for sampling bias in observed t0. t0biascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

Linfbiascv

Log-normal coefficient of variation for sampling bias in observed maximum length. Linfbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

LFCbiascv

Log-normal coefficient of variation for sampling bias in observed length at first capture. LFCbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

LFSbiascv

Log-normal coefficient of variation for sampling bias in length-at-full selection. LFSbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

FMSY_Mbiascv

Log-normal coefficient of variation for sampling bias in estimates of the ratio of the fishing mortality rate that gives the maximum sustainable yield relative to the assumed instantaneous natural mortality rate. FMSY/M. FMSY_Mbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

BMSY_B0biascv

Log-normal coefficient of variation for sampling bias in estimates of the BMSY relative to unfished biomass (BMSY/B0). BMSY_B0biascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

Irefbiascv

Log-normal coefficient of variation for sampling bias in the observed relative index of abundance (Iref). Irefbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

Brefbiascv

Log-normal coefficient of variation for sampling bias in the observed reference biomass (Bref). Brefbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

Crefbiascv

Log-normal coefficient of variation for sampling bias in the observed reference catch (Cref). Crefbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

Dbiascv

Log-normal coefficient of variation for sampling bias in the observed depletion level. Dbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

Dobs

Log-normal coefficient of variation controlling error in observations of stock depletion among years. Observation error in the depletion expressed as a coefficient of variation (CV). Dobs requires the upper and lower bounds of a uniform distribution, and for each simulation a CV is sampled from this distribution. Each CV is used to specify a log-normal error distribution with a mean of 1 and a standard deviation equal to the sampled CV. The yearly observation error values for the depletion data are then drawn from this distribution. For each time step the simulation model records the true depletion, but the observed depletion is generated by applying this yearly error term (plus any bias, if specified) to the true depletion.

hbiascv

Log-normal coefficient of variation for sampling persistent bias in steepness. hbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

Recbiascv

Log-normal coefficient of variation for sampling persistent bias in recent recruitment strength. Recbiascv requires the upper and lower bounds of a uniform distribution, and for each simulation a CV is sampled from this distribution. Each CV is used to specify a log-normal error distribution with a mean of 1 and a standard deviation equal to the sampled CV. The yearly bias values for the depletion data are then drawn from this distribution. Positive real numbers.

sigmaRbiascv

Log-normal coefficient of variation for sampling persistent bias in recruitment variability. sigmaRbiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years. Positive real numbers.

Eobs

Observation error around the total effort. Observation error in the total effort is expressed as a coefficient of variation (CV). Eobs requires upper and lower bounds of a uniform distribution, and for each simulation a CV is sampled from this distribution. Each CV is used to specify a log-normal error distribution with a mean of 1 and a standard deviation equal to the sampled CV. The yearly observation error values for the effort data are then drawn from this distribution. For each time step the simulation model records the true effort, but the observed effort is generated by applying this yearly error term (plus any bias, if specified) to the true effort.

Ebiascv

Log-normally distributed coefficient of variation controlling the sampling bias in observed effort for each simulation. Bias occurs when effort is systematically skewed away from the true effort level. Ebiascv is a single value specifying the standard deviation of a log-normal distribution with a mean of 1 and a standard deviation equal to the sampled CV. For each simulation a bias value is drawn from this distribution, and that bias is applied across all years.

Objects from the Class

Objects can be created by calls of the form new('Obs')

Note

Its questionable whether the hyperstability/hyperdepletion should be categorised as an observation model characteristic as it is most often driven by fleet dynamics (and therefore should be in the fleet object). Oh well its here and you might want to make it hyperstable beta < 1 or hyperdeplete beta > 1, only.

Author(s)

T. Carruthers and A. Hordyk

Examples

showClass('Obs')

ObsDescription

Description

A data.frame with description of slots for class Obs

Usage

ObsDescription

Format

An object of class data.frame with 30 rows and 2 columns.


OM Constructor and Accessor

Description

Construct an om object defining the complete specification of an operating model (OM) for use in Management Strategy Evaluation (MSE), or extract the OM slot from an enclosing object.

Usage

OM(
  Name = "A new OM object",
  Agency = "",
  Author = "",
  Email = "",
  Region = "",
  Latitude = NULL,
  Longitude = NULL,
  Sponsor = "",
  nSim = 48,
  nYear = 20,
  pYear = 30,
  CurrentYear = as.numeric(format(Sys.Date(), "%Y")),
  Seasons = 1,
  Stock = NULL,
  Fleet = NULL,
  Obs = NULL,
  Imp = NULL,
  Data = NULL,
  DataLag = 0,
  CatchFrac = NULL,
  Allocation = NULL,
  EFactor = NULL,
  Complexes = NULL,
  Herm = NULL,
  SharePar = NULL,
  Relations = NULL,
  StockTargeting = NULL,
  Interval = 1,
  nReps = 1,
  pStar = 0.5,
  maxF = 3,
  Seed = 101,
  Control = NULL,
  Misc = list(),
  Source = NULL
)

Arguments

Name

Character. Name of the operating model. Default "A new OM object".

If Name is an S4 object with an OM slot (e.g. a hist or mse object), OM() returns that slot directly rather than constructing a new object. See Pass-Through Access in Details.

Agency

Character. Name of the agency responsible for management. Supports Markdown. Default "".

Author

Character vector. Name(s) of the author(s) of the operating model. Default "".

Email

Character vector. Email address(es) corresponding to Author. Supports Markdown. Default "".

Region

Character. Name of the geographic region of the fishery. Default "".

Latitude

Numeric. Latitude (decimal degrees) of the centre of Region. Default NULL.

Longitude

Numeric. Longitude (decimal degrees) of the centre of Region. Default NULL.

Character. Organisation sponsoring development of the operating model. Supports Markdown. Default "".

nSim

Positive integer. Number of stochastic simulations. Default 48.

nYear

Numeric. Number of historical years. Default 20.

pYear

Numeric. Number of projection years. Default 30.

CurrentYear

Integer. Final historical calendar year of the operating model. Default is the current system year.

Seasons

Integer. Number of seasons per year. Default 1.

Stock

A stock object or named list of stock objects. Default NULL. See Stock() for construction and pass-through access.

Fleet

A hierarchical named list of fleet objects indexed by stock then fleet. Each stock must have the same number of fleets. Default NULL. See Fleet() for construction and pass-through access.

Obs

A hierarchical named list of obs objects indexed by stock and fleet. Default NULL. See Obs() for construction and pass-through access.

Imp

A hierarchical named list of imp objects indexed by stock and fleet. Default NULL. See Imp() for construction and pass-through access.

Data

A data object or list of data objects associated with the operating model. Default NULL. See Data() for construction and pass-through access.

DataLag

Integer. Number of time steps that data are lagged relative to management implementation. Default 0.

CatchFrac

List. Controls catch fraction allocation among fleets or stocks. Default NULL.

Allocation

List. Controls effort or catch allocation among fleets or stocks. Default NULL.

EFactor

List. Effort or exploitation modifiers applied during projection. Default NULL.

Complexes

List. Defines stock complexes for data aggregation and management. Default NULL.

Herm

List. Defines hermaphroditism or movement between stocks. Default NULL.

SharePar

Logical. Whether key parameters are shared among stocks. Default NULL.

Relations

List. Biological or ecological relationships among stocks (e.g. predator-prey). Default NULL. Currently not used.

StockTargeting

A stocktargeting object. Defines fleet-level stock targeting weights and deviations. Populated internally. See StockTargeting().

Interval

Numeric scalar or named numeric vector. Management update interval in years. Default 1.

nReps

Positive integer. Number of stochastic replicates used for generating management advice. Default 1.

pStar

Numeric in [0,1][0, 1]. Percentile applied to stochastic management advice. Default 0.5.

maxF

Numeric. Maximum allowable instantaneous fishing mortality. Applies to nominal fishing mortality for fish that interact with the fishing gear; actual effective F may be lower if some fish are discarded and survive. Default 3.

Seed

Integer. Random number generator seed for reproducibility. Default 101.

Control

Named list of operating model control settings. When NULL (default), ControlDefault is used.

Misc

List. Miscellaneous objects or developer-use components. Default list().

Source

Character. References to data sources or documentation. Supports Markdown. Default NULL.

Details

Pass-Through Access

When Name is an S4 object with an OM slot, OM() returns that slot directly rather than constructing a new object. This allows a consistent interface for both construction and retrieval:

om  <- OM(hist_obj)    # extract from hist or mse
OM(hist_obj)           # same

Derived Slots

The Years slot is not a constructor parameter. It is derived automatically from nYear, pYear, CurrentYear, and Seasons via CalcYears() and is read-only. Use Years() to extract it from a constructed object.

StockTargeting Initialisation

The StockTargeting slot is initialised automatically by StockTargeting() when Stock and Fleet are provided. It is not a user-facing parameter and should not be set directly in most workflows.

Sub-Object Slots

Stock, Fleet, Obs, Imp, and Data each have dedicated constructor functions that also act as pass-through accessors when called with an om argument. Replacement is handled by the corresponding replacement functions in each constructor file:

Stock(om)  <- Stock("MyStock", ...)
Fleet(om)  <- list(s1 = list(f1 = Fleet("MyFleet", ...)))
Obs(om)    <- Obs("MyObs", ...)
Imp(om)    <- Imp("MyImp", ...)
Data(om)   <- Data(...)

Accessing and Assigning Slots

All remaining slots in om objects can be accessed or assigned using functions matching the slot names. See OM-accessors for the full list:

Agency(om)
Agency(om) <- "DFO"

Value

  • OM() returns a new om object when Name is a character string or NULL.

  • OM() returns Name@OM (an om object) when Name is an S4 object with an OM slot.

See Also

Other om: ComplexOM, MultiStockOM, OM-accessors, SingleStockOM, TwoFleetOM, om-class

Examples

om <- OM()
Agency(om)
Agency(om) <- "DFO"

nSim(om)
nSim(om) <- 100

Years(om)

Access and Modify OM Slots

Description

Accessor and replacement functions for slots in om objects. Each function retrieves or replaces the value of the corresponding slot. All accessors also accept hist and mse objects, extracting the embedded OM slot transparently.

Usage

Agency(x)

Agency(x) <- value

Author(x)

Author(x) <- value

Email(x)

Email(x) <- value

Region(x)

Region(x) <- value

Latitude(x)

Latitude(x) <- value

Longitude(x)

Longitude(x) <- value

Sponsor(x)

Sponsor(x) <- value

Source(x)

Source(x) <- value

nYear(x)

nYear(x) <- value

pYear(x)

pYear(x) <- value

CurrentYear(x)

CurrentYear(x) <- value

Seasons(x)

Seasons(x) <- value

DataLag(x)

DataLag(x) <- value

CatchFrac(x)

CatchFrac(x) <- value

Allocation(x)

Allocation(x) <- value

EFactor(x)

EFactor(x) <- value

Complexes(x)

Complexes(x) <- value

Herm(x)

Herm(x) <- value

SharePar(x)

SharePar(x) <- value

Relations(x)

Relations(x) <- value

Interval(x)

Interval(x) <- value

nReps(x)

nReps(x) <- value

pStar(x)

pStar(x) <- value

maxF(x)

maxF(x) <- value

Seed(x)

Seed(x) <- value

Control(x)

Control(x) <- value

Arguments

x

An om, hist, or mse object.

value

Replacement value for the corresponding slot.

Details

Sub-Object Slots

The Stock, Fleet, Obs, Imp, and Data slots are accessed and replaced via their own constructor functions, which act as pass-through accessors when called with an om argument. They are not listed here. See Stock(), Fleet(), Obs(), Imp(), Data().

Read-Only Slots

Years is derived automatically from nYear, pYear, CurrentYear, and Seasons and is read-only. Use Years() to extract it.

Value

  • Accessor functions return the value of the named slot.

  • Replacement functions return x with the named slot updated.

See Also

Other om: ComplexOM, MultiStockOM, OM(), SingleStockOM, TwoFleetOM, om-class

Examples

om <- OM()

Agency(om)
Agency(om) <- "DFO"

nSim(om)
nSim(om) <- 100

maxF(om)
maxF(om) <- 5

The om S4 Class

Description

The om defines a complete operating model (OM) specification for use in Management Strategy Evaluation (MSE).

Details

Direct construction via methods::new() is not recommended; use OM() instead, which populates defaults, derives Years, and initialises StockTargeting automatically.

All slots can be accessed or replaced using functions matching the slot name. See OM-accessors for the full list. Slots belonging to sub-objects (Stock, Fleet, Obs, Imp, Data) are accessed via their own constructors, which also serve as pass-through accessors when called with an om argument.

Slots

Name

Character. Name of the operating model. See OM().

Agency

Character. Name of the agency responsible for management. Supports Markdown. See OM().

Author

Character vector. Name(s) of the author(s). See OM().

Email

Character vector. Email address(es) corresponding to Author. Supports Markdown. See OM().

Region

Character. Name of the geographic region of the fishery. See OM().

Latitude

Numeric. Latitude (decimal degrees) of the centre of Region. See OM().

Longitude

Numeric. Longitude (decimal degrees) of the centre of Region. See OM().

Sponsor

Character. Organisation sponsoring development of the operating model. Supports Markdown. See OM().

nSim

Positive integer. Number of stochastic simulations. See OM().

nYear

Numeric. Number of historical years. See OM().

pYear

Numeric. Number of projection years. See OM().

CurrentYear

Integer. Final historical calendar year. See OM().

Seasons

Integer. Number of seasons per year. See OM().

Years

Numeric vector. Model time steps (including seasonal resolution if applicable). Derived from nYear, pYear, CurrentYear, and Seasons via CalcYears(). Read-only; see Years().

Stock

A stock object or named list of stock objects. See Stock().

Fleet

A hierarchical named list of fleet objects indexed by stock then fleet. Each stock must have the same number of fleets. See Fleet().

Obs

A hierarchical named list of obs objects indexed by stock and fleet. See Obs().

Imp

A hierarchical named list of imp objects indexed by stock and fleet. See Imp().

Data

A data object or list of data objects associated with the operating model. See Data().

DataLag

Integer. Number of time steps that data are lagged relative to management implementation. See OM().

CatchFrac

List. Controls catch fraction allocation among fleets or stocks. See OM().

Allocation

List. Controls effort or catch allocation among fleets or stocks. See OM().

EFactor

List. Effort or exploitation modifiers applied during projection. See OM().

Complexes

List. Defines stock complexes for data aggregation and management. See OM().

Herm

List. Defines hermaphroditism or movement between stocks. See OM().

SharePar

Logical. Whether key parameters are shared among stocks. See OM().

Relations

List. Biological or ecological relationships among stocks. See OM().

StockTargeting

A stocktargeting object. Defines fleet-level stock targeting weights and deviations. Initialised automatically by OM() via StockTargeting().

Interval

Numeric scalar or named numeric vector. Management update interval in years. See OM().

nReps

Positive integer. Number of stochastic replicates for management advice. See OM().

pStar

Numeric. Percentile applied to stochastic management advice. See OM().

maxF

Numeric. Maximum allowable instantaneous fishing mortality. See OM().

Seed

Integer. Random number generator seed. See OM().

Control

Named list of operating model control settings. See OM().

Misc

List. Miscellaneous objects or developer-use components.

Log

List. Internal diagnostic and runtime information. See Log().

Source

Character. References to data sources or documentation. Supports Markdown. See OM().

See Also

Other om: ComplexOM, MultiStockOM, OM(), OM-accessors, SingleStockOM, TwoFleetOM


Class 'OM'

Description

An object containing all the parameters needed to control the MSE which can be build from component Stock, Fleet, Obs, and Imp objects.

Details

Almost all of these inputs are a vector of length 2 which describes the upper and lower bounds of a uniform distribution from which to sample the parameter.

Slots

Name

Name of the operating model

Agency

Name of the agency responsible for the management of the fishery. Character string

Region

Name of the general geographic region of the fishery. Character string

Sponsor

Name of the organization who sponsored the OM. Character string

Latitude

Latitude (decimal degrees). Negative values represent the South of the Equator. Numeric. Single value

Longitude

Longitude (decimal degrees). Negative values represent the West of the Prime Meridian. Numeric. Single value

nsim

The number of simulations

proyears

The number of projected years

interval

The assessment interval - how often would you like to update the management system?

pstar

The percentile of the sample of the management recommendation for each method

maxF

Maximum instantaneous fishing mortality rate that may be simulated for any given age class

reps

Number of samples of the management recommendation for each method. Note that when this is set to 1, the mean value of the data inputs is used.

cpars

A list of custom parameters. Time series are a matrix nsim rows by nyears columns. Single parameters are a vector nsim long. See validcpars()

seed

A random seed to ensure users can reproduce results exactly

Source

A reference to a website or article from which parameters were taken to define the operating model

Objects from the Class

Objects can be created by calls of the form new('OM', Stock, Fleet, Obs, Imp).

Author(s)

T. Carruthers and A. Hordyk


OMDescription

Description

A data.frame with description of slots for class OM

Usage

OMDescription

Format

An object of class data.frame with 15 rows and 2 columns.


Generate OM Documentation Report

Description

Generate OM Documentation Report

Usage

OMdoc(
  OM = NULL,
  rmd.source = NULL,
  overwrite = FALSE,
  out.file = NULL,
  inc.plot = TRUE,
  render = TRUE,
  output = "html_document",
  openFile = TRUE,
  quiet = FALSE,
  dir = NULL,
  ...
)

Arguments

OM

An object of class 'OM' or the name of an OM xlsx file

rmd.source

Optional. Name of the source.rmd file corresponding to the 'OM'. Default assumption is that the file is '[email protected]'

overwrite

Logical. Should existing files be overwritten?

out.file

Optional. Character. Name of the output file. Default is the same as the text file.

inc.plot

Logical. Should the plots be included?

render

Logical. Should the document be compiled? May be useful to turn off if there are problems with compiling the Rmd file.

output

Character. Output file type. Default is 'html_document'. 'pdf_document' is available but may require additional software and have some formatting issues.

openFile

Logical. Should the compiled file be opened in web browser?

quiet

TRUE to suppress printing of the pandoc command line.

dir

Optional file path to read the xlsx and rmd files. Default is getwd()

...

Optional additional named arguments provided to runMSE

Value

Creates a Rmarkdown file and compiles a HTML report file in the working directory.

Author(s)

A. Hordyk

Examples

## Not run: 
OMinit('myOM', Stock='Herring', Fleet='Generic_Fleet', Obs='Generic_Obs',
Imp='Perfect_Imp', overwrite=TRUE)
myOM <- XL2OM('myOM.xlsx')
OMdoc(myOM)

## End(Not run)

Copy example OM XL and OM Documentation

Description

Copy example OM XL and OM Documentation

Usage

OMexample(dir = getwd())

Arguments

dir

the file path to copy the files to.

Examples

## Not run: 
OMexample()

## End(Not run)

Initialize Operating Model

Description

Generates an Excel spreadsheet and a source.rmd file in the current working directory for specifying and documenting a MSEtool Operating Model.

Usage

OMinit(
  name = NULL,
  ...,
  files = c("xlsx", "rmd"),
  dir = NULL,
  overwrite = FALSE
)

Arguments

name

The name of the Excel and source.rmd file to be created in the working directory (character). Use 'example' for a populated example OM XL and documentation file.

...

Optional MSEtool objects to use as templates: OM, Stock, Fleet, Obs, or Imp objects

files

What files should be created: 'xlsx', 'rmd', or c('xlsx', 'rmd') (default: both) to use as templates for the Operating Model.

dir

Optional file path to create the xlsx and rmd files. Default is getwd()

overwrite

Logical. Should files be overwritten if they already exist?

Value

name.xlsx and name.rmd files are created in the working directory.

Author(s)

A. Hordyk

Examples

## Not run: 
# Create an Excel OM template and rmd file called 'myOM.xlsx' and 'myOM.rmd':
OMinit('myOM')

# Create an Excel OM template and text file called 'myOM.rmd' and 'myOM.rmd', using
# another OM as a template:
OMinit('myOM', myOM)

# Create an Excel OM template and text file called 'myOM.rmd' and 'myOM.rmd', using
# the Stock object 'Herring' as a template:
OMinit('myOM', Herring)

# Create an Excel OM template and text file called 'myOM.rmd' and 'myOM.rmd', using
# the Stock object 'Herring', and Obs object 'Generic_obs' as templates:
OMinit('myOM', Herring, Generic_obs)

## End(Not run)

Determine optimal number of cpus

Description

Determine optimal number of cpus

Usage

optCPU(nsim = 96, thresh = 5, plot = TRUE, msg = TRUE, maxn = NULL)

Arguments

nsim

Numeric. Number of simulations.

thresh

Recommended n cpus is what percent of the fastest time?

plot

Logical. Show the plot?

msg

Logical. Should messages be printed to console?

maxn

Optional. Maximum number of cpus. Used for demo purposes

Author(s)

A. Hordyk

See Also

setup

Examples

## Not run: 
optCPU()

## End(Not run)

Imp class objects

Description

Example objects of class Imp

Usage

Overages

Perfect_Imp

Format

An object of class Imp of length 1.

An object of class Imp of length 1.

Examples

avail("Imp")

Performance Metrics Methods

Description

Performance metric (PMs) methods for your management strategy evaluation.

Usage

P10(MSEobj = NULL, Ref = 0.1, Yrs = NULL)

P50(MSEobj = NULL, Ref = 0.5, Yrs = NULL)

P100(MSEobj = NULL, Ref = 1, Yrs = NULL)

PNOF(MSEobj = NULL, Ref = 1, Yrs = NULL)

LTY(MSEobj = NULL, Ref = 0.5, Yrs = -10)

STY(MSEobj = NULL, Ref = 0.5, Yrs = 10)

Yield(MSEobj = NULL, Ref = 1, Yrs = NULL)

PGK(MSEobj = NULL, Ref = 1, Yrs = NULL)

AAVY(MSEobj = NULL, Ref = 0.2, Yrs = NULL)

AAVE(MSEobj = NULL, Ref = 0.2, Yrs = NULL)

Arguments

MSEobj

An object of class MSE

Ref

Reference point for calculating the performance metric. See details.

Yrs

Numeric vector of length 2 with year indices to summarize performance. If NULL, the performance is summarized over all projection years.

Details

Performance Metric definitions:

P10 Probability B > 0.1 BMSY
P50 Probability B > 0.5 BMSY
P100 Probability B > BMSY
PNOF Probability F < FMSY
LTY Probability Long-Term Yield > 0.5 Relative Yield
STY Probability Short-Term Yield > 0.5 Relative Yield
AAVY Probability AAVY < 0.2 (Average Annual Variability in Yield)
AAVE Probability AAVE < 0.2 (Average Annual Variability in Effort)
Yield Average Yield (relative to Reference Yield)

Argument Ref provides the ratio relative to the reference point for calculating the performance metric. For biomass-based PMs (P10, P50, P100), this is the fraction of BMSY. For PNOF, the fraction of FMSY. For Yield (and LTY/STY), the fraction of the Reference Yield. For AAVY is it the maximum acceptable variability in yield (i.e, default for AAVY is Ref=0.2)

The Yrs argument defines the number of years to calculate the performance statistic over. A value of NULL, the default for AAVY, AAVE, P10, P50, P100, and PNOF, means that the performance metric is calculated over all projection years. A numeric vector of length two is used to specify the first and last year, e.g, if Yrs=c(1,10) the performance statistic is calculated over the first 10 projection years. A numeric vector of length one with positive or negative value respectively can be used to specify the first x or last x years, e.g, Yrs=10 is first 10 years, and Yrs=-10 is the last 10 years. See ChkYrs for more details.

By default Long-Term Yield (LTY) is the Yield in the last ten years of the projection period in the MSE, and Short-Term Yield (STY) is that in the first 10 years of the projection period.

Value

An object of class PMobj

Examples

## Not run: 
myMSE <- runMSE()
P10(myMSE)
P50(myMSE)
P100(myMSE)
PNOF(myMSE)
LTY(myMSE)
STY(myMSE)
AAVY(myMSE)
AAVE(myMSE)
Yield(myMSE)

## End(Not run)

The perrecruit S4 Class

Description

An S4 class storing per-recruit quantities evaluated across a vector of apical fishing mortality values. Produced internally by CalcPerRecruit() during reference point and equilibrium calculations.

Details

Spawning numbers-per-recruit

When SpawnTimeFrac > 0 for any stock, NPRF_SP differs from NPRF: survival to the spawn date is computed as

Nexp(ZSpawnTimeFrac)N \cdot \exp(-Z \cdot \texttt{SpawnTimeFrac})

so that SPR, SBiomass, and SProduction reflect abundance at the time of spawning rather than at the start of the year. When SpawnTimeFrac = 0 for all stocks, NPRF_SP is not populated.

SPFrom

When stocks share a spawning component (e.g. a complex), the SPFrom slot of each stock's SRR() determines which stock's SPRF is used when computing relative SPR. This is handled upstream in CalcPerRecruit() before the SPRF and SPR0 slots are populated.

Relationships between slots

SPR=SPRF/SPR0\texttt{SPR} = \texttt{SPRF} / \texttt{SPR0}

SBiomass=aNPRF_SPaWama\texttt{SBiomass} = \sum_a \texttt{NPRF\_SP}_a \cdot W_a \cdot m_a

SProduction=aNPRF_SPafa\texttt{SProduction} = \sum_a \texttt{NPRF\_SP}_a \cdot f_a

where WaW_a, mam_a, and faf_a are weight, maturity, and fecundity at age respectively.

Slots

apicalF

Numeric vector of apical fishing mortality values at which per-recruit quantities were evaluated. Length nF.

NPR0

Numbers-per-recruit at unfished conditions. Array (⁠Sim × Age × Year⁠) or a list by stock.

NPR0_SP

Spawning numbers-per-recruit at unfished conditions, accounting for SpawnTimeFrac. Array (⁠Sim × Age × Year⁠) or a list by stock. Equal to NPR0 when SpawnTimeFrac is zero for all stocks.

NPRF

Numbers-per-recruit at fishing mortality. Array (⁠Sim × Age × Year × F⁠) or a list by stock, where the F dimension has length nF.

NPRF_SP

Spawning numbers-per-recruit at fishing mortality, accounting for SpawnTimeFrac. Array (⁠Sim × Age × Year × F⁠) or a list by stock. Populated only when SpawnTimeFrac > 0 for any stock; otherwise NULL.

SPR0

Spawning-per-recruit at unfished conditions. Array (⁠Sim × Stock × Year⁠).

SPRF

Spawning-per-recruit at fishing mortality. Array (⁠Sim × Stock × Year × F⁠).

SPR

Spawning-per-recruit relative to unfished, i.e. SPRF / SPR0. Array (⁠Sim × Stock × Year × F⁠).

Biomass

Total biomass-per-recruit. Array (⁠Sim × Stock × Year × F⁠).

SBiomass

Spawning biomass-per-recruit. Array (⁠Sim × Stock × Year × F⁠).

SProduction

Spawning production-per-recruit, computed from fecundity-at-age rather than weight × maturity. Array (⁠Sim × Stock × Year × F⁠).

Removals

Total removals-per-recruit (landings + dead discards), summed over fleets. Array (⁠Sim × Stock × Year × F⁠).

Landings

Landings-per-recruit, summed over fleets. Array (⁠Sim × Stock × Year × F⁠).

Misc

List reserved for internal use.

See Also

CalcPerRecruit()


Plot Data object

Description

Creates plots of the Data object in the R console. Wrapper for summary(Data)

Usage

## S3 method for class 'Data'
plot(
  x,
  wait = TRUE,
  i = 1,
  plots = "all",
  rmd = FALSE,
  head = "##",
  tplot = 25,
  ...
)

Arguments

x

An object of class Data

wait

Logical. Wait for key press before next plot?

i

iteration number for the Data object.

plots

Character. What plots to show? all, TS, CAA, CAL, PD for all plots, time-series, catch-at-age, catch-at-length, and probability distributions respectively

rmd

Logical. Used in a rmd file?

head

Character. Heading for rmd file. Default is '##' (second level heading)

tplot

Integer. Number of plots per page. Default 25

...

Not used


Standard plot for an object of class MMSE (multi MSE)

Description

Plot the projected biomass, fishing, mortality rate and yield for all stocks and MPs

Usage

## S3 method for class 'MMSE'
plot(
  x = NULL,
  maxcol = 6,
  qcol = rgb(0.4, 0.8, 0.95),
  lcol = "dodgerblue4",
  quants = c(0.05, 0.25, 0.75, 0.95),
  curyr = 2018,
  addline = FALSE,
  ...
)

Arguments

x

Object of class MMSE. A Multi-OM object created by multiMSE(MOM, ...)

maxcol

Integer. The maximum number of columns (MPs) to be plotted in each plot

qcol

Character, color. The color of the inner percentile range

lcol

Character, color. The color of the outer percentile range.

quants

Numeric vector. The percentiles that are plotted (LB2,LB1,UB1,UB2). LB2 and UB2 are the outer percentiles, LB1 and UB1 are the inner percentiles.

curyr

Integer. The current year from which projections start.

addline

Logical. Should two individual simulations be added to the percentile plots?

...

Not used

Author(s)

T.Carruthers


Standard plot for an object of class MOM

Description

Plot the stocks, fleets, catch fractions and relationships in multi operating model object

Usage

## S4 method for signature 'MOM,missing'
plot(x, silent = TRUE, maxsims = 6)

Arguments

x

Object of class MOM. A Multi-OM object created by new('MOM', ...)

silent

Logical. Do you wish to see print outs / warnings?

maxsims

Integer. What are the maximum number of individual simulations you wish to plot?

Author(s)

T.Carruthers


Plot MSE object

Description

Plot MSE object

Usage

## S3 method for class 'MSE'
plot(x, ...)

Arguments

x

object of class MSE

...

other parameters passed to plot (currently ignored)


Plot Operating Model Object

Description

Generate HTML reports with plots of operating model components ("Stock", "Fleet", "Obs", and "Imp"), the historical simulations ("Hist"), or the complete OM ("OM").

The individual component plots of objects of class Stock and Fleet can also be generated by using the generic plot.pars function. See Examples below.

Usage

## S3 method for class 'pars'
plot(
  x,
  Object,
  Stock = NULL,
  nsamp = 3,
  nsim = 200,
  nyears = 50,
  proyears = 28,
  output_file = NULL,
  output_dir = getwd(),
  quiet = TRUE,
  tabs = TRUE,
  title = NULL,
  date = NULL,
  plotPars = NULL,
  html = FALSE,
  open = TRUE,
  dev = FALSE,
  ...
)

## S3 method for class 'Stock'
plot(
  x,
  nsamp = 3,
  nsim = 200,
  nyears = 50,
  proyears = 28,
  output_file = NULL,
  output_dir = getwd(),
  quiet = TRUE,
  tabs = TRUE,
  title = NULL,
  date = NULL,
  plotPars = NULL,
  open = TRUE,
  dev = FALSE,
  ...
)

## S3 method for class 'Fleet'
plot(
  x,
  Stock = NULL,
  nsamp = 3,
  nsim = 200,
  nyears = 50,
  proyears = 28,
  output_file = NULL,
  output_dir = getwd(),
  quiet = TRUE,
  tabs = TRUE,
  title = NULL,
  date = NULL,
  plotPars = NULL,
  open = TRUE,
  dev = FALSE,
  ...
)

## S3 method for class 'Obs'
plot(
  x,
  nsamp = 3,
  nsim = 200,
  nyears = 50,
  proyears = 28,
  output_file = NULL,
  output_dir = getwd(),
  quiet = TRUE,
  tabs = TRUE,
  title = NULL,
  date = NULL,
  plotPars = NULL,
  open = TRUE,
  dev = FALSE,
  ...
)

## S3 method for class 'Imp'
plot(
  x,
  nsamp = 3,
  nsim = 200,
  nyears = 50,
  proyears = 28,
  output_file = NULL,
  output_dir = getwd(),
  quiet = TRUE,
  tabs = TRUE,
  title = NULL,
  date = NULL,
  plotPars = NULL,
  open = TRUE,
  dev = FALSE,
  ...
)

## S3 method for class 'Hist'
plot(
  x,
  nsamp = 3,
  nsim = 200,
  nyears = 50,
  proyears = 28,
  output_file = NULL,
  output_dir = getwd(),
  quiet = TRUE,
  tabs = TRUE,
  title = NULL,
  date = NULL,
  plotPars = NULL,
  open = TRUE,
  dev = FALSE,
  ...
)

## S3 method for class 'OM'
plot(
  x,
  nsamp = 3,
  nsim = 200,
  nyears = 50,
  proyears = 28,
  output_file = NULL,
  output_dir = getwd(),
  quiet = TRUE,
  tabs = TRUE,
  title = NULL,
  date = NULL,
  plotPars = NULL,
  open = TRUE,
  dev = FALSE,
  ...
)

Arguments

x

An object of class Stock, Fleet, Obs, Imp, Hist, or OM, OR one of the following character strings for Object of class Stock: "M", "Growth", "Maturity", "Recruitment", "Spatial", or "Depletion" and for Object of class Fleet: "Effort", "Catchability", "MPA", and "Selectivity".

Object

An object of class Stock or Fleet

Stock

An object of class Stock required for Fleet parameters

nsamp

The number of random samples to show in the plot

nsim

The number of simulations (only used for objects not of class OM)

nyears

The number of historical years (only used for objects not of class OM)

proyears

The number of projection years (only used for objects not of class OM)

output_file

Name of the output html file (without file extension)

output_dir

Output directory. Defaults to getwd()

quiet

An option to suppress printing of the pandoc command line

tabs

Include tabs in the HTML file?

title

Optional title for the markdown report

date

Optional date for the markdown report

plotPars

A named list with options for plots:

  • breaks - numeric. Number of breaks in histograms.

  • col - character. Color of histograms.

  • axes - logical. Include axes in histogram?

  • cex.main - numeric. Size of main title in plots.

  • lwd - numeric. Line width for time-series plots.

html

Logical. Compile to a HTML report (TRUE) or print plots in R console (FALSE)

open

Logical. Open the html file?

dev

Logical. For development use only.

...

Not used

Examples

## Not run: 
# Plot Stock Object:
Stock <- MSEtool::Albacore
plot(Stock)

# Individual plots:
plot("M", Stock)
plot("Growth", Stock)
plot("Maturity", Stock)
plot("Recruitment", Stock)
plot("Spatial", Stock)
plot("Depletion", Stock)

# Plot Fleet Object
Fleet <- MSEtool::Generic_DecE
plot(Fleet, Stock)

# Individual plots:
plot("Effort", Fleet, Stock)
plot("Catchability", Fleet, Stock)
plot("MPA", Fleet, Stock)
plot("Selectivity", Fleet, Stock)


# Plot Obs Object
Obs <- MSEtool::Imprecise_Unbiased
plot(Obs)

# Plot Imp Object
Imp <- MSEtool::Overages
plot(Imp)


# Plot Hist Object
OM <- MSEtool::testOM
Hist <- Simulate(OM)
plot(Hist)

# Plot OM Object
plot(OM)

## End(Not run)

Print out plotting functions

Description

This function prints out the available plotting functions for objects of class MSE or Data

Usage

plotFun(class = c("MSE", "Data"), msg = TRUE)

Arguments

class

Character string. Prints out the plotting functions for objects of this class.

msg

Logical. Should the functions be printed to screen?

Note

Basically the function looks for any functions in the MSEtool that have the word plot in them. There is a chance that some plotting functions are missed. Let us know if you find any and we will add them.

Author(s)

A. Hordyk


A basic SSB plot for debugging runMSE output

Description

A basic SSB plot for debugging runMSE output

Usage

plotmulti(MSEmulti, maxsim = 8)

Arguments

MSEmulti

An object of class MMSE arising from a run of multiMSE(MOM, ...)

maxsim

Integer. The number of simulations to plot

Author(s)

T.Carruthers


A generic OFL plot for NOAA use

Description

As title.

Usage

plotOFL(Data, xlims = NA, perc = 0.5)

Arguments

Data

An object of class Data that has been run though TAC()

xlims

x axis limits

perc

The percentile of the OFL distribution to be plotted

Value

A table of performance metrics.

Author(s)

T. Carruthers


A fairly tidy time-series quantile plot

Description

A fairly tidy time-series quantile plot

Usage

plotquant(
  x,
  p = c(0.05, 0.25, 0.75, 0.95),
  yrs,
  qcol,
  lcol,
  addline = T,
  ablines = NA
)

Arguments

x

Matrix. A time series quantity ⁠[simulation, year]⁠

p

Numeric vector. The percentiles that are plotted (LB2,LB1,UB1,UB2). LB2 and UB2 are the outer percentiles, LB1 and UB1 are the inner percentiles.

yrs

Numeric vector. The years corresponding to the indexing of x

qcol

Character, color. The color of the inner percentile range

lcol

Character, color. The color of the outer percentile range.

addline

Logical. Should two individual simulations be added to the percentile plots?

ablines

Numeric vector. Horizontal lines to be added to the plot.

Author(s)

T.Carruthers


Plot a relationship between stocks

Description

Plot a relationship between stocks

Usage

plotRel(Stocks, Rel, Relno, Snams, leg = F, extras = 0)

Arguments

Stocks

A list of stock objects (MOM@Stocks)

Rel

A list of inter-stock MICE relationships (MOM@Rel)

Relno

Integer. The relationship you wish to plot

Snams

A vector of stock names

leg

Logical. Do you want to plot a legend?

extras

Integer. The number of blank plots to create at the end.

Author(s)

T.Carruthers


Create a table of Performance Limits and Performance Objectives

Description

Create a table of Performance Limits and Performance Objectives

Usage

PMLimit(
  MSE,
  ...,
  Prob = NULL,
  Labels = NULL,
  FeaseMPs = NULL,
  out.file = NULL,
  output_format = "html_document",
  openFile = TRUE,
  quiet = TRUE,
  dir = NULL,
  RMDfile = NULL,
  font_size = 14,
  auto_width = FALSE,
  enableSearch = TRUE,
  PMlist = NULL,
  build = TRUE
)

PMObj(
  MSE,
  ...,
  Labels = NULL,
  out.file = NULL,
  output_format = "html_document",
  openFile = TRUE,
  quiet = TRUE,
  dir = NULL,
  RMDfile = NULL,
  font_size = 14,
  use.colors = TRUE,
  cols = NULL,
  show.legend = TRUE,
  auto_width = FALSE,
  enableSearch = TRUE,
  PMlist = NULL,
  build = TRUE,
  cex.tex = 0.75,
  inc.title = TRUE,
  title = "Legend"
)

Arguments

MSE

An object of class 'MSE'

...

PM objects to be used as performance limits. Characters (i.e names of PM objects)

Prob

Minimum probability threshold

Labels

Optional named list specifying new labels for MPs. For example: Labels = list(AvC="Average Catch", CC1="Constant Catch")

FeaseMPs

Optional. Character vector of MP names that are considered feasible. e.g. the output from Fease()

out.file

Name of the output file. If none provided, output file will be named 'PerfLimTable'

output_format

Output file format. Currently only 'html_document' is supported

openFile

Logical. Should the file be opened in browser?

quiet

Logical. An option to suppress printing of the pandoc command line.

dir

Optional. Directory for output file. Default is working directory.

RMDfile

Optional. RMD template file

font_size

Numeric. Font size for text in the table

auto_width

Logical. Should table be width be automatic?

enableSearch

Currently disabled. Logical. Should search be enabled in the html table?

PMlist

Optional. List of PM names.

build

Logical. Build the html table?

use.colors

Logical. Color scale the probability text?

cols

Optional character vector of colors for probability text

show.legend

Logical. Show the legend??

cex.tex

Size of legend text

inc.title

Logical. Include title for legend?

title

Title for the legend

Value

PMLimit invisibly returns names of MPs that pass all performance limits

Functions

  • PMLimit(): Create a table of Performance Limits

  • PMObj(): Create a table of Performance Objectives.

Author(s)

A. Hordyk

Examples

## Not run: 
MSE <- runMSE()
PMLimit(MSE, "P50", "PNOF", Prob=0.9)
PMObj(MSE, "P100", "LTY")

## End(Not run)

An object for storing data for analysis using data-limited methods

Description

Used internally

Slots

Name

Name of the Performance Metric. Character

Caption

A caption to be used in plots. Character, call, or function.

Stat

Statistic of interest for the PM. Dimensions: nsim, nMP, yrs. Array

Ref

Reference value to calculate probability for statistic. Numeric.

Prob

Probability (mean over years) Dimensions: nsim by MP. Matrix, numeric or data.frame

Mean

Mean probability (mean over years and simulations). Numeric. Length nMPs

MPs

Name of MPs. Single value. Character string

Objects from the Class

Objects can be created by calls of the form new('PMobj')

Author(s)

A. Hordyk


popdynamics Class

Description

Stores population time-series for a single stock across simulations, ages, years, and areas.

Slots

Number

Number-at-age. List of length nStock, each element an array with dimensions Sim, Age, Year, Area.

Biomass

Total biomass. Array with dimensions Sim, Stock, Year.

SBiomass

Spawning biomass. Array with dimensions Sim, Stock, Year.

SProduction

Spawning production. Array with dimensions Sim, Stock, Year.

Misc

Miscellaneous list for additional outputs.


Populate Operating Model Components

Description

Generic dispatcher function to populate operating model objects and their components.

Usage

Populate(object, ...)

Arguments

object

An object to populate. The class of object determines which class-specific ⁠Populate*()⁠ function is called.

...

Named arguments passed to the appropriate ⁠Populate*()⁠ function. Only arguments relevant to the class of object are used.

Details

Generally, users will not need to use the ⁠Populate*⁠ functions as they are called internally.

Depending on the class of object, the function calls a class-specific ⁠Populate*()⁠ function that generates stochastic values, fills derived slots, and checks object structure and contents.

Populate() is a wrapper around class-specific population functions. The following methods may be called depending on the class of object:

Each ⁠Populate*()⁠ function has its own documentation detailing which named arguments it accepts. Users should consult the specific ⁠Populate*()⁠ help page for information about required slots, default behavior, and argument descriptions.

Value

The populated object, of the same class as object.

Examples

## Not run: 
# Populate a full operating model
OM <- Populate(OM)

# Populate a stock with specific arguments
Stock <- Populate(
  Stock,
  nYear = 40,
  pYear = 20,
  nSim = 100
)

# Populate a fleet using an already-populated stock
Fleet <- Populate(
  Fleet,
  Stock = Stock,
  nSim = 100
)

## End(Not run)

Populate a Catchability Object

Description

Populate a Catchability object by setting fleet/gear efficiency values for historical and projected years, and applying optional stochastic or increasing catchability parameters.

Usage

PopulateCatchability(
  Catchability,
  nSim = 5,
  HistYears = NULL,
  ProjYears = NULL,
  seed = NULL,
  silent = FALSE
)

Arguments

Catchability

A Catchability() object to populate.

nSim

Integer. Number of simulation replicates.

HistYears

Numeric vector of historical years.

ProjYears

Numeric vector of projected years.

seed

Integer. Random number seed used for stochastic generation.

silent

Logical; if TRUE, suppresses messages.

Details

PopulateCatchability() performs the following steps:

  • Initializes Efficiency to 1 if not provided.

  • Checks that Efficiency has correct dimensions (rows = 1 or nSim).

  • Adds dimension names if missing.

  • Applies qInc (annual increase in catchability) if provided.

  • Applies qCV (coefficient of variation) to introduce stochasticity.

Value

A populated Catchability() object.

Examples

## Not run: 
Catch <- Catchability()
Catch_pop <- PopulateCatchability(
  Catchability = Catch,
  nSim = 50,
  HistYears = 2000:2020,
  ProjYears = 2021:2025,
  seed = 123
)

## End(Not run)

Populate Catch Observation Error

Description

Populate a catchobs object by expanding CV, generating stochastic error arrays, applying multiplicative bias, and generating a stochastic reference level, all across simulation replicates and years.

Usage

PopulateCatchObs(Catch, nSim, HistYears, ProjYears)

Arguments

Catch

A catchobs object. Used for both landed catch (Obs@Landings) and discarded catch (Obs@Discards).

nSim

Integer. Number of simulation replicates.

HistYears

Integer vector. Calendar years of the historical period.

ProjYears

Integer vector. Calendar years of the projection period.

Details

If EmptyObject() returns TRUE for Catch, the object is returned unchanged and no population is performed.

Otherwise the following slots are populated in order:

  • CV: expanded to a named ⁠[nSim]⁠ array via PopulateObsCV().

  • Error: generated as a lognormal draw from CV across all historical and projection years, producing a named ⁠[nSim x nYear]⁠ array via PopulateObsError(). If Error is already a fully-formed array it is validated and dimension names are applied.

  • Bias: expanded to a named ⁠[nSim]⁠ multiplicative bias array via PopulateObsBias(). Defaults to 1 (no bias) if unspecified.

  • Ref: generated as a lognormal draw from a CV, producing a named ⁠[nSim]⁠ reference level error multiplier array via PopulateObsRef().

Value

A populated catchobs object.

See Also

PopulateObs(), catchobs, PopulateObsCV(), PopulateObsError(), PopulateObsBias(), PopulateObsRef()


Populate a Closure Object

Description

Populates a Closure array for a fleet, ensuring proper dimensions across simulations, years, and spatial areas.

Usage

PopulateClosure(Closure, nArea, nSim = 5, Years, silent = FALSE)

Arguments

Closure

An array representing fleet-specific area closures, or NULL.

nArea

Integer. Number of spatial areas.

nSim

Integer. Number of simulation replicates.

Years

Numeric vector of model years.

silent

Logical; if TRUE, suppresses informational messages.

Details

PopulateClosure() ensures the Closure array has dimensions: sim × year × area. If the array is empty, it defaults to 1 (open) for all areas.

Existing arrays are checked for compatibility with nArea. Dimension names for Sim, Year, and Area are automatically added if missing.

Value

An array representing fleet area closures with proper dimensions and dimnames.

Examples

## Not run: 
Closure <- NULL
Closure_pop <- PopulateClosure(Closure, nArea = 5, nSim = 3, Years = 2000:2025)

## End(Not run)

Populate Composition Observation Error

Description

Populate a compobs object by expanding SampleSize, ESS, Theta, and Shift across simulation replicates, years, and composition bins, and applying default values where slots are unspecified.

Usage

PopulateCompObs(
  Comp,
  nSim,
  HistYears,
  ProjYears,
  Bins = NULL,
  BinName = "Class"
)

Arguments

Comp

A compobs object. Used for landed catch-at-age (Obs@LandingsAtAge), discarded catch-at-age (Obs@DiscardsAtAge), landed catch-at-size (Obs@LandingsAtSize), and discarded catch-at-size (Obs@DiscardsAtSize).

nSim

Integer. Number of simulation replicates.

HistYears

Integer vector. Calendar years of the historical period.

ProjYears

Integer vector. Calendar years of the projection period.

Bins

Numeric vector. Age classes for age composition slots, or length class midpoints for size composition slots. Used to set the length of the Bin dimension and to name it in the populated Shift array. NULL is accepted only when EmptyObject() returns TRUE for Comp.

BinName

Character scalar. Name used for the bin dimension in populated arrays, typically "Age" or "Class".

Details

If EmptyObject() returns TRUE for Comp (i.e. SampleSize is NULL), the object is returned unchanged and no population is performed.

Otherwise the following slots are populated:

SampleSize: expanded to a named ⁠[nSim x nYear]⁠ array via PopulateObsScalar(), covering all historical and projection years. A length-2 input c(lower, upper) is interpreted as bounds of a Uniform distribution from which nSim values are drawn.

ESS: expanded in the same way as SampleSize. If NULL, defaults silently to the populated SampleSize array. Typically ESS <= SampleSize; values of ESS < SampleSize produce overdispersion relative to a pure multinomial with SampleSize draws.

Theta: expanded to a named ⁠[nSim x nYear]⁠ array of values in ⁠(0, 1]⁠. If NULL, defaults silently to 1 (standard multinomial, no additional overdispersion). A length-2 input is treated as Uniform bounds.

Shift: expanded to a named ⁠[nSim x nYear x nBin]⁠ array via Extend(), where nBin = length(Bins). Accepted input forms:

  • NULL (default): no shift applied; slot remains NULL.

  • Scalar: constant offset across all simulations, years, and bins.

  • Vector of length nBin: bin-specific offset, constant across simulations and years.

  • Named matrix with any subset of Sim, Year, and Bin dimensions with change-point years.

  • Full ⁠[nSim x nYear x nBin]⁠ array.

In conditioning mode, ESS, Theta, and Shift are populated internally by ConditionObs_Comp() and should not be set by the user.

Composition generation model

After population, the fully-expanded slots are used by the simulation engine to generate observed compositions as follows. Let q be the OM-predicted composition vector for a given simulation, year, and fleet:

  1. Base concentration: α=ESS×q\alpha = \mathrm{ESS} \times \mathbf{q}

  2. Apply shift (if non-NULL): αb=αb×exp(Shift[sim,year,b])\alpha_b' = \alpha_b \times \exp(\mathrm{Shift}[\mathrm{sim}, \mathrm{year}, b])

  3. Dirichlet draw: pDirichlet(α/Theta)\mathbf{p}^* \sim \mathrm{Dirichlet}(\alpha' / \mathrm{Theta})

  4. Multinomial draw: obsMultinomial(SampleSize,p)\mathrm{obs} \sim \mathrm{Multinomial}(\mathrm{SampleSize}, \mathbf{p}^*)

Value

A populated compobs object.

See Also

CompObs(), compobs, PopulateObs(), ConditionObs_Comp()


Populate a Depletion Object

Description

Populate a Depletion object by generating initial and final depletion values across simulation replicates, and validating the reference biomass.

Usage

PopulateDepletion(Depletion, nSim = 5, seed = NULL, silent = FALSE)

Arguments

Depletion

A Depletion() object to populate.

nSim

Integer. Number of simulation replicates.

seed

Integer. Random seed used for stochastic generation.

silent

Logical. If TRUE, suppress informational messages.

Details

PopulateDepletion() handles population of initial and final depletion values. Steps include:

  • Generating stochastic values if required for Initial and Final slots.

  • Validating that the Reference slot is one of the accepted types: "B0", "BMSY", "SB0", or "SBMSY".

  • Returning a fully populated Depletion object.

Value

A populated Depletion() object.

Examples

## Not run: 
# Assuming a Depletion object `D` exists
D_pop <- PopulateDepletion(D, nSim = 10, seed = 123)

## End(Not run)

Populate a DiscardMortality Object

Description

Populates a DiscardMortality object with mean-at-age and mean-at-length values.

Usage

PopulateDiscardMortality(
  DiscardMortality,
  Ages = NULL,
  Length = NULL,
  nSim = 5,
  Years = NULL,
  nArea = 1,
  CalcAtLength = TRUE,
  seed = NULL,
  silent = FALSE,
  force = FALSE,
  replace = FALSE,
  ASKOverride = NULL
)

Arguments

DiscardMortality

A DiscardMortality() object to populate.

Ages

An Ages() object defining age classes.

Length

A Length() object. Required if the model depends on length-at-age.

nSim

Integer. Number of simulation replicates.

Years

Numeric vector of model years.

nArea

Integer. Number of spatial areas.

CalcAtLength

Logical; if TRUE, calculates mean-at-length from age-based arrays.

seed

Integer. Random seed used for stochastic generation.

silent

Logical; if TRUE, suppresses informational messages.

force

Logical; if TRUE, forces re-population even if digest indicates object is current.

replace

Used internally.

ASKOverride

Used internally.

Details

PopulateDiscardMortality() handles population of discard mortality at age and optionally at length. Steps include:

  • Converting mean-at-length to mean-at-age if necessary

  • Calculating mean-at-length from age-based arrays if CalcAtLength = TRUE

  • Adding an 'Area' dimension and setting dimension names

  • Handling empty objects by setting discard mortality to zero

Value

A populated DiscardMortality() object.

Examples

## Not run: 
DM <- DiscardMortality()
DM_pop <- PopulateDiscardMortality(
  DM, Ages = Ages, Length = Length, Years = 2000:2025, nSim = 5
)

## End(Not run)

Populate an Effort Object

Description

Populate an Effort object by generating historical effort, and populating distribution and targeting across areas and simulation replicates.

Usage

PopulateEffort(Effort, HistYears, nArea = 1, nSim = 5, seed = NULL)

Arguments

Effort

An effort object to populate.

HistYears

Numeric vector of historical years to populate effort for.

nArea

Integer. Number of spatial areas.

nSim

Integer. Number of simulation replicates.

seed

Integer. Random number seed used for stochastic generation.

Details

PopulateEffort() performs the following steps:

  • Generates historical effort if the Effort slot is a data frame.

  • Ensures the effort matrix has correct dimensions and names.

  • Validates fleet effort distribution and targeting across areas.

Value

A populated Effort() object.

Examples

## Not run: 
Eff <- Effort()
Eff_pop <- PopulateEffort(
  Effort = Eff,
  HistYears = 2000:2025,
  nArea = 3,
  nSim = 50,
  seed = 123
)

## End(Not run)

Populate Effort Observation Error

Description

Populate an effortobs object by expanding CV, generating stochastic error arrays, and generating multiplicative bias across simulations.

Usage

PopulateEffortObs(Effort, nSim, HistYears, ProjYears)

Arguments

Effort

An effortobs object.

nSim

Integer. Number of simulation replicates.

HistYears

Integer vector. Calendar years of the historical period.

ProjYears

Integer vector. Calendar years of the projection period.

Details

If EmptyObject() returns TRUE for Effort, the object is returned unchanged and no population is performed.

Otherwise the following slots are populated in order:

  • CV: expanded to a named ⁠[nSim]⁠ array via PopulateObsCV().

  • Error: generated as a lognormal draw from CV across all historical and projection years, producing a named ⁠[nSim x nYear]⁠ array via PopulateObsError(). If Error is already a fully-formed array it is validated and dimension names are applied.

  • Bias: expanded to a named ⁠[nSim]⁠ multiplicative bias array via PopulateObsBias(). Defaults to 1 (no bias) if unspecified.

Value

A populated effortobs object.

See Also

PopulateObs(), effortobs, PopulateObsCV(), PopulateObsError(), PopulateObsBias()


Populate a Fecundity Object

Description

Populate a Fecundity object by generating mean-at-age values, adding stochastic deviations, and optionally calculating fecundity-at-length. Handles models that depend on age, length, or weight.

Usage

PopulateFecundity(
  Fecundity,
  Ages = NULL,
  Length = NULL,
  Weight = NULL,
  Maturity = NULL,
  Years = NULL,
  nSim = 5,
  seed = NULL,
  silent = FALSE,
  CalcAtLength = FALSE,
  force = FALSE
)

Arguments

Fecundity

A Fecundity() object to populate.

Ages

An Ages() object defining age classes.

Length

A Length() object. Required if the fecundity model depends on length-at-age.

Weight

A Weight() object. Required if the fecundity model depends on weight-at-age.

Maturity

A Maturity() object. Required to calculate fecundity as egg production of mature individuals.

Years

Numeric vector of model years.

nSim

Integer. Number of simulation replicates.

seed

Integer. Random seed used for stochastic generation.

silent

Logical. If TRUE, suppress informational messages.

CalcAtLength

Logical. If TRUE, calculate fecundity-at-length values from age-based arrays.

force

Logical. If TRUE, force re-population even if the object digest is unchanged.

Details

PopulateFecundity() handles population of mean fecundity-at-age for a stock. Steps include:

  • Structuring model parameters across nSim and Years

  • Resolving the fecundity model class

  • Generating mean fecundity at age, or at length if applicable

  • Converting between mean-at-length and mean-at-age

  • Multiplying by maturity to represent egg production of mature individuals

  • Adding stochastic variation via PopulateRandom()

Value

A populated Fecundity() object.

See Also

Populate(), PopulateStock(), PopulateLength(), PopulateWeight(), PopulateMaturity()

Examples

## Not run: 
# Assuming `Ages`, `Length`, `Weight`, and `Maturity` objects exist
F <- Fecundity()
F_pop <- PopulateFecundity(
  F,
  Ages = Ages,
  Length = Length,
  Weight = Weight,
  Maturity = Maturity,
  Years = 2000:2025,
  nSim = 5,
  seed = 123,
  CalcAtLength = TRUE
)

## End(Not run)

Populate a Fleet Object

Description

Populate a Fleet object by generating effort, catchability, selectivity, retention, discard mortality, and spatial closures for a fleet.

Usage

PopulateFleet(Fleet, Stock, seed = 103, silent = FALSE, force = FALSE)

Arguments

Fleet

A Fleet() object to populate.

Stock

A populated Stock() object.

seed

Integer. Random seed used for stochastic generation.

silent

Logical. If TRUE, suppress informational messages.

force

Logical. If TRUE, force re-population even if digest indicates the object is current.

Details

PopulateFleet() performs the following steps:

  • Populates fleet effort for historical years.

  • Populates fleet catchability for historical and projected years.

  • Populates selectivity and retention objects.

  • Populates discard mortality and spatial closures.

  • Initializes fleet-specific weight-at-age if not already defined.

Value

A populated Fleet() object.

See Also

Populate(), PopulateStock()

Examples

## Not run: 
F <- Fleet()
F_pop <- PopulateFleet(Fleet = F, Stock = Stock, seed = 123, nSim = 50)

## End(Not run)

Populate Index Observation Error

Description

Populate an indicesobs object by expanding CV, generating stochastic error arrays, applying lag-1 autocorrelation, applying multiplicative bias, and populating index years, across simulation replicates and years.

Usage

PopulateIndexObs(Index, nSim, HistYears, ProjYears)

Arguments

Index

An indicesobs object. Used for both CPUE indices (Obs@CPUE) and fishery-independent survey indices (Obs@Survey).

nSim

Integer. Number of simulation replicates.

HistYears

Integer vector. Calendar years of the historical period.

ProjYears

Integer vector. Calendar years of the projection period.

Details

If EmptyObject() returns TRUE for Index, the object is returned unchanged and no population is performed.

Otherwise the following slots are populated in order:

  • CV — expanded to a named ⁠[nSim]⁠ array via PopulateObsCV().

  • Error — generated as a lognormal draw from CV across all historical and projection years, producing a named ⁠[nSim x nYear]⁠ array via PopulateObsError(). If Error is already a fully-formed array it is validated and dimension names are applied. If AC is non-zero, the error series is subsequently transformed to an AR(1) process (see below).

  • AC — expanded to a named ⁠[nSim]⁠ array via PopulateObsAC(). Accepted inputs: scalar applied to all simulations, length-2 vector c(lower, upper) for a per-simulation Uniform draw, or a vector of length nSim used directly. Defaults to 0 (no autocorrelation).

  • Ref — generated as a lognormal draw from a CV, producing a named ⁠[nSim]⁠ reference level error array via PopulateObsRef().

  • Years — if empty, defaults to all historical years (HistYears).

The following slots are used internally during the simulation and are not populated here: Beta, Selectivity, Type, Efficiency.

Autocorrelated index error

When AC is non-zero, the independently-drawn lognormal error series is transformed into a variance-preserving AR(1) process on the log scale. Let εt=log(Errort)\varepsilon_t = \log(\mathrm{Error}_t) be the raw log-errors drawn from N(μ,σ2)N(\mu, \sigma^2) where μ\mu and σ\sigma are derived from CV. The AR(1) series is constructed as:

εt=ρεt1+1ρ2εt\varepsilon_t^* = \rho \, \varepsilon_{t-1}^* + \sqrt{1 - \rho^2} \, \varepsilon_t

where ρ\rho is the per-simulation lag-1 autocorrelation coefficient (AC). This formulation preserves the marginal variance Var(εt)=σ2\mathrm{Var}(\varepsilon_t^*) = \sigma^2 for all values of ρ\rho. The AR(1) series is then exponentiated to return to the natural scale: Errort=exp(εt)\mathrm{Error}_t^* = \exp(\varepsilon_t^*).

Value

A populated indicesobs object.

See Also

PopulateObs(), indicesobs, PopulateObsCV(), PopulateObsError(), PopulateObsAC(), PopulateObsRef()


Populate a Length Object

Description

Populate a Length object by generating stochastic length-at-age values, expanding parameters across simulation replicates and years, and optionally constructing age–length keys.

Usage

PopulateLength(
  Length,
  Ages = NULL,
  Years = NULL,
  nSim = 5,
  ALK = TRUE,
  seed = NULL,
  silent = FALSE,
  force = FALSE
)

Arguments

Length

A Length() object to populate.

Ages

An Ages() object defining age classes. If NULL, defaults ages 0:10 are used.

Years

Numeric vector of model years. If NULL, defaults years seq(1950, CurrentYear + 5) are used.

nSim

Integer. Number of simulation replicates.

ALK

Logical. If TRUE, populate age–length keys.

seed

Integer. Random seed used for stochastic generation.

silent

Logical. If TRUE, suppress informational messages.

force

Logical. If TRUE, force re-population even if the object digest is unchanged.

Details

PopulateLength() expands length-at-age parameters and generates stochastic realizations across simulations and years. Population involves:

  • Structuring model parameters across nSim and Years

  • Resolving the length-at-age model

  • Generating mean and random length-at-age values

  • Expanding coefficients of variation

  • Optionally constructing age–length keys

To avoid unnecessary recomputation, a digest of the length object and key arguments is checked before population. If the digest is unchanged and force = FALSE, the input object is returned unchanged.

Value

A populated Length() object.

See Also

Populate(), PopulateStock()

Examples

## Not run: 
Length <- PopulateLength(
  Length,
  Ages = Ages,
  Years = Years,
  nSim = 100,
  ALK = TRUE,
  seed = 123
)

## End(Not run)

Populate a Maturity Object

Description

Populate a Maturity object by generating maturity-at-age or maturity-at-weight values for a stock, expanding parameters across simulation replicates and years, and optionally calculating values at length.

Usage

PopulateMaturity(
  Maturity,
  Ages = NULL,
  Length = NULL,
  Weight = NULL,
  Years = NULL,
  nSim = 5,
  seed = NULL,
  silent = FALSE,
  CalcAtLength = FALSE,
  force = FALSE
)

Arguments

Maturity

A Maturity() object to populate.

Ages

An Ages() object defining age classes.

Length

A Length() object. Required if the maturity model depends on length-at-age.

Weight

A Weight() object. Required if the maturity model depends on weight-at-age.

Years

Numeric vector of model years.

nSim

Integer. Number of simulation replicates.

seed

Integer. Random seed used for stochastic generation.

silent

Logical. If TRUE, suppress informational messages.

CalcAtLength

Logical. If TRUE, calculate maturity-at-length values from age-based arrays.

force

Logical. If TRUE, force re-population even if the object digest is unchanged.

Details

PopulateMaturity() handles population of maturity-at-age or maturity-at-weight for a stock. Steps include:

  • Structuring model parameters across nSim and Years

  • Resolving the maturity model class

  • Generating mean maturity at age, at length, or at weight as appropriate

  • Converting between mean-at-length/weight and mean-at-age

  • Adding stochastic variation via PopulateRandom()

  • Setting semelparous array if applicable

Value

A populated Maturity() object.

See Also

Populate(), PopulateStock(), PopulateLength(), PopulateWeight()

Examples

## Not run: 
M <- PopulateMaturity(
  Maturity,
  Ages = Ages,
  Length = Length,
  Weight = Weight,
  Years = Years,
  nSim = 100,
  CalcAtLength = TRUE,
  seed = 123
)

## End(Not run)

Populate a Natural Mortality Object

Description

Populate a NaturalMortality object by generating stochastic natural mortality-at-age values, expanding parameters across simulation replicates and years, and optionally calculating values at length.

Usage

PopulateNaturalMortality(
  NaturalMortality,
  Ages = NULL,
  Length = NULL,
  Years = NULL,
  nSim = 5,
  CalcAtLength = FALSE,
  seed = NULL,
  silent = FALSE,
  force = FALSE
)

Arguments

NaturalMortality

A NaturalMortality() object to populate.

Ages

An Ages() object defining age classes.

Length

A Length() object. Required if the mortality model depends on length-at-age.

Years

Numeric vector of model years.

nSim

Integer. Number of simulation replicates.

CalcAtLength

Logical. If TRUE, calculate mortality-at-length values from age-based arrays.

seed

Integer. Random seed used for stochastic generation.

silent

Logical. If TRUE, suppress informational messages.

force

Logical. If TRUE, force re-population even if the object digest is unchanged.

Details

PopulateNaturalMortality() handles natural mortality-at-age population for a stock, including stochastic generation and propagation across simulations and years. Steps include:

  • Structuring model parameters across nSim and Years

  • Resolving the mortality model class

  • Generating mean natural mortality at age or at length

  • Converting between mean-at-length and mean-at-age if necessary

  • Adding stochastic variation via PopulateRandom()

Value

A populated NaturalMortality() object.

See Also

Populate(), PopulateStock(), PopulateLength()

Examples

## Not run: 
NM <- PopulateNaturalMortality(
  NaturalMortality,
  Ages = Ages,
  Length = Length,
  Years = Years,
  nSim = 100,
  CalcAtLength = TRUE,
  seed = 123
)

## End(Not run)

Populate an Obs Object

Description

Populate an obs object by expanding observation error parameters across simulation replicates and years, generating stochastic error arrays, and applying default values where slots are unspecified.

Usage

PopulateObs(Obs, HistYears, ProjYears, nSim, AgeBins = NULL, SizeBins = NULL)

Arguments

Obs

An obs object to populate.

HistYears

Integer vector. Calendar years of the historical period.

ProjYears

Integer vector. Calendar years of the projection period.

nSim

Integer. Number of simulation replicates.

AgeBins

Numeric vector. Age class values used to name the Bin dimension of populated age-composition arrays. Required when Obs@LandingsAtAge or Obs@DiscardsAtAge is non-empty.

SizeBins

Numeric vector. Length class midpoints, used to name the Bin dimension of populated size-composition arrays. Required when Obs@LandingsAtSize or Obs@DiscardsAtSize is non-empty.

Details

PopulateObs() coordinates population of all observation error components of an obs object, calling a dedicated sub-function for each slot:

Slots for LifeHistory and Exploitation observation error are reserved for future implementation and are not populated.

If a slot contains an empty object (as determined by EmptyObject()), it is returned unchanged. See the individual sub-function documentation for details on expansion rules, default values, and accepted input forms.

Value

A populated obs object.

See Also

Populate(), PopulateEffortObs(), PopulateCatchObs(), PopulateIndexObs(), PopulateCompObs()


Populate an Operating Model

Description

Populate a complete operating model (om object) by populating all component objects (stocks, fleets, observation models, and derived structures), performing internal consistency checks, and initializing simulation-specific values.

Usage

PopulateOM(OM, silent = FALSE, force = FALSE, standardize_effort = TRUE)

Arguments

OM

An OM() object to populate.

silent

Logical. If TRUE, suppress informational messages and warnings during population.

force

Logical. If TRUE, force re-population even if the internal object digest indicates no changes since the last call.

standardize_effort

Logical. Used internally. Apply StandardizeEffort()?

Details

This function is typically called internally, but may also be called directly.

PopulateOM() is the top-level population routine for operating models. It orchestrates population of all model components, including:

To avoid unnecessary recomputation, a digest of the operating model is checked before population. If the digest is unchanged and force = FALSE, the input object is returned unchanged.

Value

An OM() object populated with simulation- and time-specific values.

See Also

Populate(), PopulateStock(), PopulateFleet()

Examples

## Not run: 
OM <- PopulateOM(OM)


## End(Not run)

Populate a Retention Object

Description

Populates a Retention object with mean-at-age, mean-at-length, or mean-at-weight values.

Usage

PopulateRetention(
  Retention,
  Ages = NULL,
  Length = NULL,
  Weight = NULL,
  Maturity = NULL,
  nSim = 5,
  Years = NULL,
  nArea = 1,
  CalcAtLength = TRUE,
  seed = NULL,
  silent = FALSE,
  force = FALSE,
  replace = FALSE,
  ASKOverride = NULL
)

Arguments

Retention

A Retention() object to populate.

Ages

An Ages() object defining age classes.

Length

A Length() object. Required if the retention model depends on length-at-age.

Weight

A Weight() object. Required if the retention model depends on weight-at-age.

Maturity

A Maturity() object. Required if the retention model uses relative selectivity.

nSim

Integer. Number of simulation replicates.

Years

Numeric vector of model years.

nArea

Integer. Number of spatial areas.

CalcAtLength

Logical; if TRUE, calculates mean-at-length from age-based arrays.

seed

Integer. Random seed used for stochastic generation.

silent

Logical; if TRUE, suppresses informational messages.

force

Logical; if TRUE, forces re-population even if digest indicates object is current.

replace

Used internally.

ASKOverride

Used internally.

Details

PopulateRetention() handles population of retention-at-age, retention- at-length, or retention-at-weight. Steps include:

  • Resolving the retention model class

  • Generating mean retention at age, length, or weight as appropriate

  • Converting between mean-at-length/weight and mean-at-age

  • Adding stochastic variation via PopulateRandom()

  • Adding an 'Area' dimension and setting dimension names

Value

A populated Retention() object.

Examples

## Not run: 
Ret <- Retention()
Ret_pop <- PopulateRetention(
  Ret, Ages = Ages, Length = Length, Weight = Weight, 
  Maturity = Maturity, Years = 2000:2025, nSim = 5
)

## End(Not run)

Populate a Selectivity Object

Description

Populate a Selectivity object by generating selectivity-at-age, selectivity-at-length, or selectivity-at-weight values for a fleet.

Usage

PopulateSelectivity(
  Selectivity,
  Ages = NULL,
  Length = NULL,
  Weight = NULL,
  Maturity = NULL,
  nSim = 5,
  Years = NULL,
  nArea = 1,
  CalcAtLength = TRUE,
  seed = NULL,
  silent = FALSE,
  CheckMaxValue = TRUE,
  replace = FALSE,
  ASKOverride = NULL
)

Arguments

Selectivity

A Selectivity() object to populate.

Ages

An Ages() object defining age classes.

Length

A Length() object. Required if the selectivity model depends on length-at-age.

Weight

A Weight() object. Required if the selectivity model depends on weight-at-age.

Maturity

A Maturity() object. Required if isRel = TRUE to scale selectivity relative to maturity L50.

nSim

Integer. Number of simulation replicates.

Years

Numeric vector of model years.

nArea

Integer. Number of spatial areas.

CalcAtLength

Logical. If TRUE, calculate selectivity-at-length values from age-based arrays.

seed

Integer. Random seed used for stochastic generation.

silent

Logical. If TRUE, suppress informational messages.

CheckMaxValue

Logical. If TRUE, ensure selectivity has a maximum value of 1 across age classes.

replace

Used interally.

ASKOverride

Used internally.

Details

PopulateSelectivity() performs the following steps:

  • Structures selectivity parameters across simulation replicates, years, and areas.

  • Resolves the selectivity model class and applies relative scaling to maturity if isRel = TRUE.

  • Generates mean selectivity-at-age, selectivity-at-length, or selectivity-at-weight depending on the model.

  • Converts between mean-at-length/weight and mean-at-age.

  • Ensures maximum selectivity does not exceed 1 if CheckMaxValue = TRUE.

  • Adds an area dimension to all arrays and sets dimension names.

Value

A populated Selectivity() object.

Examples

## Not run: 
S <- Selectivity()
S_pop <- PopulateSelectivity(
  Selectivity = S,
  Ages = Ages,
  Length = Length,
  Weight = Weight,
  Maturity = Maturity,
  Years = 2000:2025,
  nSim = 50,
  nArea = 5
)

## End(Not run)

Populate a Spatial Object

Description

Populate a Spatial object by validating or generating spatial structure for a stock, including movement matrices, unfished distributions, and relative area size.

Usage

PopulateSpatial(
  Spatial,
  Ages = NULL,
  Years = NULL,
  nSim = 5,
  seed = NULL,
  silent = FALSE,
  force = FALSE
)

Arguments

Spatial

A Spatial() object to populate.

Ages

An Ages() object defining age classes.

Years

Numeric vector of model years.

nSim

Integer. Number of simulation replicates.

seed

Integer. Random seed used for stochastic generation.

silent

Logical. If TRUE, suppress informational messages.

force

Logical. If TRUE, force re-population even if the object digest is unchanged.

Details

PopulateSpatial() handles population of spatial structure for a stock. Steps include:

  • Creating a default non-spatial structure if the object is empty

  • Validating supplied movement matrices and their dimensions

  • Calculating unfished spatial distributions

  • Generating movement probabilities and movement matrices when required

  • Expanding spatial objects across simulations and years

If a movement matrix is supplied, it is used to calculate unfished distribution.

Value

A populated Spatial() object.

See Also

Populate(), PopulateStock(), PopulateFleet()

Examples

## Not run: 
Spatial <- PopulateSpatial(
  Spatial,
  Ages = Ages,
  Years = Years,
  nSim = 100,
  seed = 123
)

## End(Not run)

Populate an SRR Object

Description

Populate a SRR object by generating recruitment deviations, and structuring values across simulation replicates and years.

Usage

PopulateSRR(
  SRR,
  Ages = NULL,
  CurrentYear = NULL,
  Years = NULL,
  nSim = 5,
  seed = NULL,
  silent = FALSE,
  force = FALSE
)

Arguments

SRR

A SRR() object to populate.

Ages

An Ages() object defining age classes.

CurrentYear

Numeric. Last historical year of the operating model.

Years

Numeric vector of model years.

nSim

Integer. Number of simulation replicates.

seed

Integer. Random seed used for stochastic generation.

silent

Logical. If TRUE, suppress informational messages.

force

Logical. If TRUE, force re-population even if the object digest is unchanged.

Details

PopulateSRR() handles population of stock-recruitment parameters. Steps include:

  • Structuring model parameters across nSim and Years

  • Resolving the SRR model class and relative recruitment function

  • Initializing R0, SD, and AC parameters

  • Generating historical and projection recruitment deviations

Value

A populated SRR() object.

See Also

Populate(), PopulateStock()

Examples

## Not run: 
# Assuming `Ages` object exists
SRR_obj <- SRR()
SRR_pop <- PopulateSRR(
  SRR_obj,
  Ages = Ages,
  CurrentYear = 2025,
  Years = 2000:2030,
  nSim = 10,
  seed = 123
)

## End(Not run)

Populate a Stock Object

Description

Populate a Stock object by generating stochastic biological quantities, expanding values across simulation replicates and years, and filling derived age- and length-based components.

Usage

PopulateStock(
  Stock,
  nYear,
  pYear,
  CurrentYear = NULL,
  nSim = 5,
  Seasons = 1,
  ALK = TRUE,
  AWK = TRUE,
  seed = 102,
  silent = FALSE,
  force = FALSE,
  CalcAtLength = FALSE
)

Arguments

Stock

A Stock() object to populate.

nYear

Integer. Number of historical years.

pYear

Integer. Number of projection years.

CurrentYear

Numeric or character. Calendar year of the final historical year. Defaults to the current system year if NULL.

nSim

Integer. Number of simulation replicates.

Seasons

Integer. Number of seasons per year.

ALK

Logical. If TRUE, populate age–length keys.

AWK

Logical. If TRUE, populate age–weight keys.

seed

Integer. Random seed used for stochastic generation.

silent

Logical. If TRUE, suppress informational messages.

force

Logical. If TRUE, force re-population even if the object digest is unchanged.

CalcAtLength

Logical. If TRUE, calculate at-length quantities from at-age arrays where applicable

Details

PopulateStock() coordinates population of all biological components associated with a stock, including:

To avoid unnecessary recomputation, a digest of the stock object and key arguments is checked before population. If the digest is unchanged and force = FALSE, the input object is returned unchanged.

Value

A populated Stock() object.

See Also

Populate(), PopulateOM()

Examples

## Not run: 
Stock <- PopulateStock(
  Stock,
  nYear = 40,
  pYear = 20,
  nSim = 100,
  seed = 123
)


## End(Not run)

Populate a Weight-at-Age Object

Description

Populate a Weight object by generating stochastic weight-at-age values, expanding parameters across simulation replicates and years, and optionally constructing age–weight keys.

Usage

PopulateWeight(
  Weight,
  Ages = NULL,
  Length = NULL,
  Years = NULL,
  nSim = 5,
  AWK = FALSE,
  CalcAtLength = FALSE,
  seed = NULL,
  silent = FALSE,
  force = FALSE
)

Arguments

Weight

A Weight() object to populate.

Ages

An Ages() object defining age classes. If NULL, defaults are inferred from Weight.

Length

A Length() object. Required if the weight model depends on length-at-age.

Years

Numeric vector of model years. If NULL, defaults are inferred from Weight.

nSim

Integer. Number of simulation replicates.

AWK

Logical. If TRUE, populate age–weight keys.

CalcAtLength

Logical. If TRUE, calculate weight-at-length values from weight-at-age arrays.

seed

Integer. Random seed used for stochastic generation.

silent

Logical. If TRUE, suppress informational messages.

force

Logical. If TRUE, force re-population even if the object digest is unchanged.

Details

PopulateWeight() handles weight-at-age population for a stock, including stochastic generation and propagation across simulations and years. Steps include:

  • Structuring model parameters across nSim and Years

  • Resolving the weight model class

  • Generating mean weight-at-age or weight-at-length values

  • Converting between mean-at-length and mean-at-age as needed

  • Optionally constructing age–weight keys if AWK = TRUE

  • Generating random variation and coefficients of variation

Value

A populated Weight() object.

See Also

Populate(), PopulateStock(), PopulateLength()

Examples

## Not run: 
Weight <- PopulateWeight(
  Weight,
  Ages = Ages,
  Length = Length,
  Years = Years,
  nSim = 100,
  AWK = TRUE,
  CalcAtLength = TRUE,
  seed = 123
)

## End(Not run)

Specifying Biological and Fleet Schedules

Description

Several objects in this package — length, weight, maturity, naturalmortality, fecundity, and the fleet sub-objects selectivity, and retention — share a common structure for specifying schedules (growth, mortality, maturity, selectivity, etc.) across simulations and years. This page describes that structure and the rules that govern how Pars, Model, and ⁠MeanAt*⁠ arrays interact.

Two Ways to Specify a Schedule

Option 1 — Model-based (recommended)

Supply Pars, a named list whose element names correspond to the arguments of a built-in model function (see, e.g., LengthModels(), MaturityModels(), NaturalMortalityModels()). The model is then resolved automatically by FindModel(), which matches the parameter names in Pars to the formal arguments of candidate model functions. You may also set Model explicitly to a character string naming the model or to a custom R function — see Custom Models below.

When model-based, Pars are expanded to ⁠Sim × Year⁠ arrays by Populate(), the model function is called to produce MeanAtAge (or MeanAtLength/MeanAtWeight for size-based models), and any existing values in ⁠MeanAt*⁠ slots are overwritten.

Option 2 — Direct array

Leave Pars = list() (the default) and supply one of MeanAtAge, MeanAtLength, or MeanAtWeight directly as a numeric array. No model is inferred and no overwriting occurs.

These two options are mutually exclusive: if Pars contains valid, non-NA named values that match a model, it takes precedence and any values supplied in ⁠MeanAt*⁠ will be replaced.

Populating Pars — Input Formats

Each element of Pars may be supplied in any of the following forms. All are converted internally to ⁠Sim × Year⁠ (or ⁠Sim × Year × Area⁠) arrays before the model function is called.

Scalar — a single value applied to all simulations and years:

Pars = list(M = 0.2)

Length-2 bounds vector — values are sampled independently for each simulation from Uniform(lower, upper). When nSim = 1, the midpoint is used:

Pars = list(M = c(0.1, 0.3))   # U(0.1, 0.3) across simulations

Length-nSim vector — one value per simulation, constant across years:

Pars = list(M = c(0.15, 0.20, 0.25, ...))

⁠Sim × Year⁠ array with named dimensions — full stochastic, time-varying specification. Only the years where the value changes need to be included; Extend() fills intermediate and future years automatically by forward-filling from the most recent supplied year:

m_arr <- array(
  c(0.2, 0.4),              # two change points
  dim      = c(1, 2),
  dimnames = list(Sim = 1, Year = c(1990, 2010))
)
Pars = list(M = m_arr)

Temporal random walk — append a partner entry named ⁠<ParName>SD⁠ to Pars. A mean-preserving log-normal random walk is then applied to the base parameter across years, and the SD entry is removed from Pars after use:

Pars = list(M = 0.2, MSD = 0.1)   # M with log-normal inter-annual variation

⁠MeanAt*⁠ Array Formats and Dimension Conventions

All ⁠MeanAt*⁠ arrays use named dimensions. The expected dimension names depend on the array type:

Array Dimensions
MeanAtAge ⁠Sim × Age × Year⁠
MeanAtLength ⁠Sim × Class × Year⁠
MeanAtWeight ⁠Sim × Class × Year⁠

As with Pars, you only need to supply the years at which the schedule changes. Extend() forward-fills all other years automatically. Similarly, a single simulation (Sim dimension of length 1) is replicated to all nSim simulations.

A numeric vector of length nAge is also accepted for MeanAtAge and is promoted to a ⁠1 × nAge × 1⁠ array automatically.

How MeanAtLength and MeanAtWeight Relate to MeanAtAge

openMSE uses age-based accounting, so MeanAtAge is ultimately what is needed. MeanAtLength and MeanAtWeight serve two roles:

  1. Generating length- or weight- data (e.g., observed size distributions, length-based data).

  2. Conversion to MeanAtAge when a schedule is naturally expressed on a size axis (e.g., length-based maturity ogives, length-based selectivity).

The conversion from size to age uses the Age-Length Key (ALK) stored in the length object, or the Age-Weight Key (AWK) from the weight object:

  • If MeanAtLength is populated and MeanAtAge is not, Populate() converts MeanAtLengthMeanAtAge via the ALK.

  • If MeanAtWeight is populated and MeanAtAge is not, Populate() converts MeanAtWeightMeanAtAge via the AWK.

  • If MeanAtAge is already populated it is not overwritten by this conversion.

  • If both MeanAtLength and MeanAtAge are populated, MeanAtAge takes precedence and MeanAtLength is used only for size-indexed output.

For model-based specification, whether the model populates MeanAtAge directly or via MeanAtLength depends on the model's function signature: models that accept a Length argument produce MeanAtLength first and then convert to MeanAtAge via the ALK; age-based models populate MeanAtAge directly.

Model Resolution — Pars, Model, and FindModel()

When Pars is non-empty and Model is NULL, FindModel() is called automatically. It scans the candidate model functions for the object class (e.g., all functions with class "LengthModel") and finds the one whose formal argument names match the names in Pars exactly (excluding auxiliary arguments such as Ages, Length, Weight). SD-suffixed entries are ignored during matching.

If no unique match is found, an informative error is thrown directing the user to the relevant ⁠*Models()⁠ function.

You may bypass automatic inference by setting Model explicitly:

  • Character string: the name of a built-in model (must exist as an exported function of the appropriate class).

  • R function: a custom function whose formal arguments match the names in Pars. Auxiliary arguments (Ages, Length, Weight, etc.) may also be present.

If object@Model is already a function object, FindModel() returns it unchanged — no further matching is attempted.

Custom Models

Any R function can be used as a model by passing it to Model. The function must accept arguments whose names match the elements of Pars, plus any required auxiliary arguments (Ages, Length, Weight, etc. as appropriate). It must return a named ⁠Sim × Age × Year⁠ array (or ⁠Sim × Class × Year⁠ for size-based outputs):

my_M <- function(M, Ages) {
  # age-varying M: decline from M to M/2 over age classes
  m_vec <- seq(M, M / 2, length.out = length(Ages))
  array(m_vec, dim = c(1, length(Ages), 1),
        dimnames = list(Sim = 1, Age = Ages, Year = 1))
}

NaturalMortality(Pars = list(M = 0.3), Model = my_M)

See Also


Extract and Reconstruct Posterior Predicted Data (PPD)

Description

Extracts the projected data objects from an mse object.

Usage

PPD(MSE)

Arguments

MSE

An object of class mse.

Details

To avoid duplication, historical data are stored only for the first MP. PPD() extracts the historical data from the first MP, and then prepends those data to the other (projection only) data objects stored in MSE@PPD

Value

A named list of PPD (data objects) for each simulation, MP, and stock/complex.

See Also

JoinYear(), Years(), mse


A projection by projection plot of F/FMSY and B/BMSY

Description

A shorter version of the plot method for MSEs that just shows the projected trends in stock status and over exploitation

Usage

Pplot(MSEobj, nam = NA, maxMP = 10, MPs = NA, maxsims = 20)

Arguments

MSEobj

An object of class MSE

nam

Title of plot

maxMP

The maximum number of MPs to plot (defaults to the first 10)

MPs

A character vector of MPs to plot

maxsims

Integer, the maximum number of simulations to plot

Author(s)

T. Carruthers


A projection by projection plot of F/FMSY, B/BMSY, B/B0, and yield

Description

A projection by projection plot of F/FMSY, B/BMSY, B/B0, and yield

Usage

Pplot2(
  MSEobj,
  YVar = c("F_FMSY", "SSB_SSBMSY"),
  MPs = NA,
  sims = NULL,
  traj = c("all", "quant", "both"),
  quants = c(0.1, 0.9),
  incquant = TRUE,
  quantcol = "lightgray",
  RefYield = c("lto", "curr"),
  LastYr = TRUE,
  ref.lines = c(0.5, 1, 1.5),
  maxMP = 6,
  alpha = 60,
  cex.axis = 1,
  cex.lab = 1,
  YLab = NULL,
  incMP = TRUE,
  MPcex = 1,
  MPcol = "black",
  incLeg = TRUE,
  cex.leg = 1.5,
  legPos = "topleft",
  yline = NULL,
  xline = NULL,
  parOR = FALSE,
  xaxis = TRUE,
  yaxis = TRUE,
  oneIt = TRUE,
  ...
)

Arguments

MSEobj

An object of class MSE

YVar

What to plot on the y-axis? Options are: c('SSB_SSB0', 'SSB_SSBMSY', 'F_FMSY', 'Yield')

MPs

Optional subset by MP

sims

Optional subset by simulation

traj

Plot all projections (all), only quantiles (quant), or both projections and median (both)

quants

Numeric vector of length 2 specifying the quantiles (e.g., 10th and 90th. Median is always included)

incquant

Logical. Include the quantiles or only plot median?

quantcol

Colour of the quantile polygon

RefYield

Should yield be relative to long-term optimum (lto) or last historical year (curr)

LastYr

Logical. Include the last historical year in the yield projections?

ref.lines

Numeric vector of y-values for horizontal reference lines. Set to NULL to remove lines.

maxMP

Maximum number of MPs to plot

alpha

Alpha for transparency of lines

cex.axis

Size of axis text

cex.lab

Size of axis label

YLab

Optional label for y-axis

incMP

Logical. Include name of MP?

MPcex

Size of MP label

MPcol

Optional character vector of colors for MP labels

incLeg

Logical. Include a legend?

cex.leg

Size of legend text

legPos

Legend position

yline

Optional horizontal lines

xline

Optional vertical lines

parOR

Logical to over-ride the par parameters

xaxis

Logical. Should x-axis labels be displayed?

yaxis

Logical. Should y-axis labels be displayed?

oneIt

Logical. Should one iteration be plotted on the quantile plot?

...

Additional arguments to be passed to plotting functions

Author(s)

T. Carruthers & A.Hordyk


Print method for multiHist objects

Description

Print method for multiHist objects

Usage

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

Arguments

x

For print.multiHist, a multiHist class object

...

Additional arguments (not used)

Value

Prints a summary of object x to the console


Print a RepList object

Description

Print a summary of a RepList object, which is a list of outputs from r4ss::SS_output.

Usage

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

Arguments

x

A RepList object.

...

Additional arguments (currently ignored).

Value

Invisibly returns x.


Project an Operating Model Over the Projection Period

Description

Runs the MSE projection loop for one or more management procedures (MPs) and returns a completed MSE-legacy object. Dispatches to the appropriate internal projection engine based on the class of Hist: hist objects use the new om-based engine; Hist-legacy objects use the legacy engine.

Usage

Project(
  Hist,
  MPs = NULL,
  parallel = FALSE,
  silent = FALSE,
  nSim = NULL,
  Reduce = TRUE,
  extended = FALSE,
  checkMPs = FALSE
)

Arguments

Hist

A hist or Hist-legacy object containing the conditioned operating model and historical dynamics, as returned by Simulate().

MPs

Character vector of MP names to project. MPs must be functions available in the current environment. f NULL (default), projects c("CurrentEffort", "CurrentCatch").

parallel

Logical or named list controlling parallel execution of MPs. If TRUE, all MPs are run in parallel. If a named list, names correspond to individual MPs to run in parallel. Default FALSE.

silent

Logical. Suppress progress messages if TRUE. Default FALSE.

nSim

Integer. If provided, reduces the number of simulations to nSim before projecting. Only used for hist objects. If NULL (default), all simulations in Hist are used.

Reduce

Logical. Reserved for future use. Default TRUE.

extended

Logical. If TRUE, stores full age- and area-structured arrays for all years in MSE@Misc$extended. Only used for Hist-legacy objects. Substantially increases object size. Default FALSE.

checkMPs

Logical. Validate MP names and availability before projecting. Only used for Hist-legacy objects. Default FALSE.

Value

An mse or a MSE-legacy object containing projection results for all MPs.

See Also

Simulate(), runMSE()


Performance Whisker Plot

Description

A NAFO / ICCAT / SSB style MSE performance whisker plot

Usage

PWhisker(MSEobj)

Arguments

MSEobj

An object of class MSE

Value

A box plot of performance

Author(s)

T. Carruthers


A quantile plot

Description

Plots quantiles and simulations for a stochastic time-series variable

Usage

quantile_plot(
  datmat,
  xvals,
  p = c(0.05, 0.25, 0.5, 0.75, 0.95),
  tcol,
  ylim,
  sims = 1:3,
  refline = NA,
  dox = F,
  doy = F
)

Arguments

datmat

Matrix of real values with dimensions (simulation, year) (e.g. SB/SBMSY)

xvals

Vector of numerical values of length ncol(datmat). The xaxis labels for datmat.

p

Vector of quantiles five positions long. Defaults to c(0.05,0.25,0.5,0.75,0.95) so the 90% and 50% intervals with the median plotted in white.

tcol

Color of shaded regions (transparent)

ylim

Numerical vector of length 2, lower and upper limits for the yaxis

sims

Vector of positive integers, the individual simulations to plot

refline

Positive real number, a reference line to plot (on scale of y axis)

dox

Logical, should the x axis labels be plotted.

doy

Logical, should the y axis labels be plotted.

Author(s)

T. Carruthers


Dirichlet-Multinomial Sampler

Description

Draw a single composition sample from the Dirichlet-Multinomial distribution. The Dirichlet-Multinomial arises as a multinomial draw whose probability vector is itself drawn from a Dirichlet distribution, producing compositions that are overdispersed relative to a standard multinomial.

Usage

rDirichletMultinomial(n, alpha)

Arguments

n

Integer. Total count (sample size) for the multinomial draw.

alpha

Numeric vector of positive Dirichlet concentration parameters, length nBin. The relative magnitudes determine the expected composition.

Details

Model

Given concentration vector α\boldsymbol{\alpha} and total count nn:

pDirichlet(α)\mathbf{p} \sim \mathrm{Dirichlet}(\boldsymbol{\alpha})

yMultinomial(n,p)\mathbf{y} \sim \mathrm{Multinomial}(n,\, \mathbf{p})

The marginal distribution of y\mathbf{y} is Dirichlet-Multinomial with mean nα/αn \cdot \boldsymbol{\alpha} / \sum \boldsymbol{\alpha} and variance exceeding the multinomial by a factor of (n+α)/(1+α)(n + \sum \boldsymbol{\alpha}) / (1 + \sum \boldsymbol{\alpha}).

The Dirichlet draw is obtained via the standard gamma representation: independent Gamma(αb,1)\mathrm{Gamma}(\alpha_b, 1) draws normalised to sum to 1.

Relationship to ESS and Theta

In the composition observation model (see CompObs()), the concentration vector is constructed as:

αb=ESSΘqbexp(Shiftb)\alpha_b = \mathrm{ESS} \cdot \Theta \cdot q_b \cdot \exp(\mathrm{Shift}_b)

where q\mathbf{q} is the vector of OM-predicted proportions. Passing this as alpha and SampleSize as n recovers the full composition observation model.

  • Theta = 1, no Shift: recovers a near-multinomial draw (Dirichlet variance shrinks as ESS grows).

  • Theta < 1: shrinks alpha, increasing overdispersion.

  • Shift non-NULL: tilts the expected composition bin-by-bin on the log-concentration scale before drawing.

Value

Integer vector of length nBin summing to n.

See Also

CompObs(), GenHistData_AgeComp(), GenHistData_SizeComp()

Examples

# Near-multinomial draw (high ESS, Theta = 1, no shift)
q <- c(0.1, 0.3, 0.4, 0.2)
alpha <- 200 * 1 * q
rDirichletMultinomial(n = 500, alpha = alpha)

# Overdispersed draw (low Theta)
alpha_od <- 200 * 0.3 * q
rDirichletMultinomial(n = 500, alpha = alpha_od)

# With shift — tilts expected composition toward older ages
shift <- c(-0.5, -0.2, 0.2, 0.5)
alpha_shifted <- 200 * 1 * q * exp(shift)
rDirichletMultinomial(n = 500, alpha = alpha_shifted)

MP feasibility diagnostic using real data

Description

What MPs do not return NAs from the real data

Usage

RealFease(Data = NULL)

Arguments

Data

An object of class 'Data'. Optional. If Data object is included, the returned MPs are both feasible (in terms of management) and possible (sufficient data to run MP)

Value

a vector of MP names that calculate without errors for the specific data.

Author(s)

T. Carruthers


Class 'Rec'

Description

An object for storing the MP recommendations

Slots

TAC

A numeric value with the TAC recommendation

Effort

A numeric value with the effort recommendation as a fraction of current (nyear) fishing effort

Spatial

A boolean vector of length 'nareas' specifying if area is open (1) or closed (0) to fishing

Allocate

A boolean value describing if effort should be re-allocated from close to open areas

LR5

smallest length at 5 per cent retention - in absolute units - i.e same units as Linf and L50

LFR

smallest length at full retention - in absolute units - i.e same units as Linf and L50

HS

upper harvest slot (no retention above this) - in absolute units - i.e same units as Linf and L50

Rmaxlen

retention of the largest size class - fraction between 0 and 1

L5

smallest length at 5 per cent selection - in absolute units - i.e same units as Linf and L50

LFS

smallest length at full selection - in absolute units - i.e same units as Linf and L50

Vmaxlen

selection of the largest size class - fraction between 0 and 1

Fdisc

fraction of discarded fish that die - fraction between 0 and 1

DR

Discard rate - the fraction of caught fish that are discarded

Misc

An empty list that can be used to store information and pass on to MPs in future

Objects from the Class

Objects can be created by calls of the form new('Rec')

Author(s)

A. Hordyk


Reduce redundant Sim, Year, and Age dimensions in arrays

Description

Reduce the size of array-like objects by collapsing dimensions (Sim, Year, and/or Age) when their values are identical across that dimension. The function works recursively on S4 objects and lists, applying the reduction to all array-valued components.

Usage

ReduceDims(
  array,
  IncSim = TRUE,
  IncAge = FALSE,
  IncYear = FALSE,
  debug = FALSE
)

Arguments

array

An array, list, or S4 object. For non-array objects, the function is applied recursively to all components or slots.

IncSim

Logical; reduce the Sim dimension if present and all simulations are identical.

IncAge

Logical; reduce the Age dimension if present and all ages are identical.

IncYear

Logical; reduce the Yeardimension if present and all years are identical or by keeping only unique years.

debug

Logical. Print debug messages?

Details

Reduction is controlled independently for each supported dimension. If a dimension is excluded or not present, it is left unchanged.

For arrays, the function detects dimensions named Sim, Age, and Year. If enabled, dimensions are reduced as follows:

  • Sim: kept at length 1 when all simulations are identical.

  • Age: kept at length 1 when all ages are identical.

  • Year: kept at length 1 when all years are identical; otherwise, only unique years are retained.

Value

An object of the same class as array, with reduced dimensions where applicable.

See Also

ReduceNSim()


Reduce the number of simulations

Description

Subsets an OM() or Hist() object by reducing number of simulations to nSim

Usage

ReduceNSim(object, nSim = NULL)

Arguments

object

An OM() or Hist() object

nSim

Integer. The maximum number of simulations

Value

The OM() or Hist() with reduced nSim

See Also

Reduce()

Examples

OM <- Populate(SingleStockOM)
nSim(OM)
OM |> Stock(1) |> Length() |> MeanAtAge() |> dim()

OM_reduced <- ReduceNSim(OM, 2)
nSim(OM_reduced)
OM_reduced |> Stock(1) |> Length() |> MeanAtAge() |> dim()

Reference Points Object

Description

The reference class stores biological and management reference points derived from per-recruit, equilibrium, or dynamic population analyses. These reference points are typically used for management strategy evaluation, harvest control rules, and performance metrics.

Slots

SPR0

List or array of unfished spawning potential ratio (SPR0), by stock and simulation.

MSY

An object containing MSY-based reference points such as FMSY, BMSY, and MSY.

Landings

List or array of reference landings values.

Removals

List or array of reference removals values.

F01

List or array of fishing mortality corresponding to the 0.1 slope reference point.

FMax

List or array of fishing mortality at maximum yield-per-recruit.

FCrash

List or array of fishing mortality leading to population collapse.

SPRcrash

List or array of spawning potential ratio at collapse.

MGT

List or array of mean generation time reference points.

BLow

List or array defining the B-Low biomass reference points.

Misc

Miscellaneous list for additional reference quantities or diagnostics.


referencedata Class

Description

Stores biological and management reference points by extending refpointsMSY. Used in the Reference slot of a data object.

Usage

ReferenceData()

Details

This class inherits all slots from refpointsMSY (e.g., MSY, FMSY, BMSY) and appends a Misc slot for any additional reference point data not covered by the parent class.

Value

ReferenceData() returns a referencedata object.

Slots

Misc

A named list for any additional reference point metadata not covered by the inherited refpointsMSY slots.

ReferenceData() creates a new referencedata object.

See Also

data, Data(), refpointsMSY


The refpointsMSY S4 Class

Description

An S4 class storing MSY-based biological reference points. Produced internally during reference point calculations and not intended to be modified directly by users.

Details

Reference point calculations

MSY reference points are derived from the per-recruit quantities in a perrecruit object by identifying the apical fishing mortality that maximises total removals, accounting for the stock-recruitment relationship. All slots share the same ⁠Sim × Stock × Year⁠ dimensions, where the Year dimension reflects the year(s) for which biological and fishery parameters were evaluated.

Slots

FMSY

Fishing mortality rate at MSY (⁠Sim × Stock × Year⁠).

BMSY

Total biomass at MSY (⁠Sim × Stock × Year⁠).

SBMSY

Spawning biomass at MSY (⁠Sim × Stock × Year⁠).

SPMSY

Spawning production at MSY (⁠Sim × Stock × Year⁠).

SPRMSY

Spawning potential ratio at MSY (⁠Sim × Stock × Year⁠).

MSYLandings

Landed catch at MSY (⁠Sim × Stock × Year⁠).

MSYDiscards

Dead discards at MSY (⁠Sim × Stock × Year⁠).

Misc

List reserved for internal use.

See Also

perrecruit


Rename Stocks and Fleets in an OM

Description

Renames stocks and/or fleets throughout an operating model (OM) object, updating all names recursively across S4 slots, lists, and array dimension names.

Usage

Rename(object, Stocks = NULL, Fleets = NULL)

Arguments

object

An object of class om.

Stocks

Optional named character vector or named list mapping new stock names to current names (e.g. c('new_name' = 'old_name')). If NULL, stock names are unchanged.

Fleets

Optional named character vector or named list mapping new fleet names to current names. If NULL, fleet names are unchanged.

Value

The input OM object with stock and/or fleet names updated throughout.

Renaming is applied recursively: list element names, S4 slot names, and the Stock and Fleet dimensions of arrays are all updated wherever a match is found. Names not present in Stocks or Fleets are left unchanged, so partial lookups are safe.

The lookup arguments use the convention NewName = OldName, e.g.: Fleets = list(NewFleet = 'OldFleet').

See Also

Reorder()

Examples

OM <- SingleStockOM
StockNames(OM)
FleetNames(OM)

OM2 <- Rename(OM, 
              Stocks = list('New Stock Name' = 'Example Stock'),
              Fleets = list('New Fleet Name' = 'Example Fleet')
)

StockNames(OM2)
FleetNames(OM2)

Reorder Stocks and Fleets in an OM

Description

Reorders stocks and/or fleets throughout an operating model (OM) object, updating all list elements and array dimension orders recursively across S4 slots.

Usage

Reorder(object, Stocks = NULL, Fleets = NULL)

Arguments

object

An object of class om.

Stocks

Optional character vector of all stock names in the desired order. Must contain exactly the same names as currently in OM. If NULL, stock order is unchanged.

Fleets

Optional character vector of all fleet names in the desired order. Must contain exactly the same names as currently in OM. If NULL, fleet order is unchanged.

Details

Reordering is applied recursively: list element names, S4 slot names, and the Stock and Fleet dimensions of arrays are all reordered wherever a match is found. The full set of names must be provided — partial reordering is not supported.

Value

The input om object with stocks and/or fleets reordered throughout.

See Also

Rename()

Examples

OM <- AddFleet(SingleStockOM, 'DummyFleet')
FleetNames(OM)

OM2 <- Reorder(OM, Fleets = rev(FleetNames(OM)))
FleetNames(OM2)

Replace an existing Stock, Fleet, Obs, or Imp object

Description

A function that replaces a Stock, Fleet, Obs, or Imp object from an OM with one from another object.

Usage

Replace(
  OM,
  from,
  Sub = c("Stock", "Fleet", "Obs", "Imp"),
  Name = NULL,
  silent = FALSE
)

Arguments

OM

An operating model object (class OM) which will be updated with a sub-model from another OM

from

An object of class OM, Stock, Fleet, Obs, or Imp to be replace the values in OM

Sub

A character string specifying what object type to replace (only used if from is class OM) "Stock", "Fleet", "Obs", or "Imp" (default is all four which is probably not what you want to do)

Name

Character. Name for the new OM object (OM@Name)

silent

Should messages be printed?

Value

An object of class OM

Author(s)

A. Hordyk

Examples

# Replace Stock
OM <- MSEtool::testOM
OM2 <- Replace(OM, Blue_shark)

# Replace Fleet
OM <- MSEtool::testOM
OM2 <- Replace(OM, Generic_DecE)

# Replace Fleet from another OM
# OM1 <- new("OM", Albacore, Generic_DecE, Perfect_Info, Overages)
# OM2 <- new("OM", Blue_shark, Generic_IncE, Generic_Obs, Perfect_Imp)
# OM1a <- Replace(OM1, OM2, "Fleet")

Enlarge (replicate) a DLM data object to create an additional dimension for simulation / sensitivity testing

Description

Replicates position 1 data to multiple positions for sensitivity testing etc

Usage

replic8(Data, nrep)

Arguments

Data

A data-limited methods data object

nrep

The number of positions to expand the DLM object to

Author(s)

T. Carruthers


Generate a Data Report

Description

A HTML Data Report is generated and opened in a web browser

Usage

Report(
  Data = NULL,
  md = NULL,
  name = "Data-Report",
  title = "Data Documentation",
  author = "Author Name",
  date = Sys.Date(),
  output_format = c("html_document", "pdf_document"),
  open = TRUE,
  quiet = TRUE,
  dir = NULL,
  overwrite = FALSE
)

Arguments

Data

Either an object of class Data or the file path to a valid file to be imported with XL2Data

md

Full file path to a valid text file documenting the Data

name

Optional. Name of the output file

title

Title for the Report. Title in the markdown file will override this value

author

Author of the Report. Author in the markdown file will override this value

date

Date of the Report. Date in the markdown file will override this value

output_format

Output file format: html_document or pdf_document

open

Logical. Open the compiled report?

quiet

Logical.An option to suppress printing of the pandoc command line.

dir

Optional. Directory to save the file. Defaults to getwd()

overwrite

Logical. Overwrite an existing file with the same name?

Value

Nothing. A Data Report is generated and saved in dir

Author(s)

A. Hordyk

Examples

## Not run: 
DataInit('Example') # generate example Data Input and Documentation files
Report('Example', 'Example.md')

## End(Not run)

ReqData

Description

Dataframe with required data slots for built-in MPs

Usage

ReqData

Format

An object of class data.frame with 123 rows and 2 columns.


What management procedures need what data

Description

A function that finds all the MPs and searches the function text for slots in the Data object

Usage

Required(funcs = NA, noCV = FALSE)

Arguments

funcs

A character vector of management procedures

noCV

Logical. Should the CV slots be left out?

Value

A matrix of MPs and their required data in terms of slotnames('Data'), and broad Data classes for each MP

Author(s)

T. Carruthers

See Also

Can Cant Needed MPtype Data-legacy


Retention

Description

Construct and manipulate a retention object defining retention-at-age, retention-at-length, or retention-at-weight for a Fleet() object. Retention is optional; if not specified, all age and length classes are assumed fully retained.

Usage

Retention(
  Pars = list(),
  Model = NULL,
  MeanAtAge = NULL,
  MeanAtLength = NULL,
  MeanAtWeight = NULL,
  Classes = NULL,
  isRel = FALSE,
  Misc = list()
)

Retention(x) <- value

Arguments

Pars

Named list of retention parameters passed to the retention model function. Parameter names must match the arguments of the chosen model (see RetentionModels()). Each element may be a scalar, vector, or array; see Specifying Biological and Fleet Schedules for accepted formats. Default list() (empty).

If Pars and Model are both provided, MeanAtAge is computed from the model and any values already in MeanAtAge are overwritten. To preserve a user-specified MeanAtAge, leave Pars = list() (the default).

If Pars is a fleet object, the Retention slot of that fleet is returned.

Model

Character or function or NULL. Retention model identifier. If NULL (default), the model is inferred automatically from the names in Pars via FindModel(). May also be supplied as a custom R function with arguments matching those in Pars. See RetentionModels() for built-in options.

MeanAtAge

Numeric array or NULL. Mean retention-at-age with dimensions ⁠Sim x Age x Year⁠ (area dimension added during population). Used directly when Pars is empty and MeanAtLength is not supplied. See Specifying Biological and Fleet Schedules for accepted array formats. Note: if Pars and Model are both provided, any values supplied here will be overwritten during population.

MeanAtLength

Numeric array or NULL. Mean retention-at-length with dimensions ⁠Sim x Length x Year⁠. If provided and Pars is empty, takes precedence over MeanAtAge; MeanAtAge is derived from it via the age-length key.

MeanAtWeight

Numeric array or NULL. Mean retention-at-weight with dimensions ⁠Sim x Weight x Year⁠. Default NULL.

Classes

Numeric vector or NULL. Length or weight class midpoints corresponding to the second dimension of MeanAtLength or MeanAtWeight. Default NULL.

isRel

Logical. If TRUE, length-based parameters (e.g., LR5, LFR) are interpreted as multiples of the length-at-50%-maturity (L50) of the paired stock rather than absolute length values. A Maturity() object must be available to PopulateRetention() for scaling to occur. Default FALSE.

Misc

List. Miscellaneous additional inputs. Default list().

x

A retention object, or a fleet object for ⁠Retention<-⁠.

value

For ⁠Retention<-⁠: a retention object.

Details

Retention is optional for all fleet objects. It defines the probability that a selected fish is retained, on a scale from 0 to 1. Fish that are selected but not retained are treated as discards, and their fate is determined by DiscardMortality().

When no retention object is supplied, PopulateRetention() sets full retention (1) for all age and length classes.

Specifying Retention

There are two ways to specify retention:

Model-based (recommended): supply Pars as a named list whose element names match the arguments of a built-in or custom model function. The model is resolved automatically unless Model is specified explicitly. See RetentionModels() for available models and their required parameters, and Specifying Biological and Fleet Schedules for how parameter values are structured across simulations and years.

Available model families are: logistic (at-age, at-length, at-weight, with optional MaxRet asymptote), knife-edge (at-age, at-length), and double-normal (at-length, at-weight). At-length and at-weight schedules are converted to at-age internally using the age-length or age-weight key.

Direct array: leave Pars = list() and supply MeanAtAge, MeanAtLength, or MeanAtWeight directly. If MeanAtLength is provided, it takes precedence and MeanAtAge is derived from it. If only MeanAtAge is provided, MeanAtLength is calculated from it unless already populated.

These two approaches are mutually exclusive: if Pars is non-empty and Model can be resolved, any values in MeanAtAge will be overwritten.

Relative Parameters

When isRel = TRUE, length-based parameters (e.g., LR5, LFR) are scaled by the maturity L50 of the paired stock before the retention curve is computed.

Attaching to a Fleet

A retention object can be attached to a Fleet() with Retention(Fleet) <- MyRetention and retrieved with Retention(Fleet).

Individual slots may be accessed or modified using Pars(), Model(), MeanAtAge(), MeanAtLength(), MeanAtWeight(), and Classes().

Value

  • Retention() returns a retention object. If Pars is a fleet object, the Retention slot of that fleet is returned.

  • ⁠Retention<-⁠ returns x with the Retention slot replaced by value.

See Also

Other fleet: Bioeconomic(), Catchability(), DiscardMortality(), Effort(), Fleet(), Selectivity(), bioeconomic-class, catchability-class, discardmortality-class, effort-class, fleet-class, retention-class, selectivity-class

Examples

# See man-examples/class-Retention.R

The retention S4 Class

Description

Defines retention-at-age, retention-at-length, or retention-at-weight for use in a fleet object. Retention is optional; if not specified, all age and length classes are assumed fully retained. Objects are typically created via the Retention() constructor, which documents all parameters in detail.

Slots

Pars

list. Named list of retention parameters passed to Model. See Retention() and RetentionModels().

Model

function or character or NULL. Retention model identifier or function. See RetentionModels().

isRel

logical, numeric, or character. Whether length-based parameters are expressed relative to maturity L50. See Retention().

MeanAtAge

numeric array or NULL. Mean retention-at-age (⁠Sim x Age x Year x Area⁠). See Retention().

MeanAtLength

numeric array or NULL. Mean retention-at-length (⁠Sim x Length x Year x Area⁠). See Retention().

MeanAtWeight

numeric array or NULL. Mean retention-at-weight (⁠Sim x Weight x Year x Area⁠). See Retention().

Classes

numeric or NULL. Length or weight class midpoints corresponding to the second dimension of MeanAtLength or MeanAtWeight.

Misc

list. Miscellaneous additional inputs. For internal use.

See Also

Other fleet: Bioeconomic(), Catchability(), DiscardMortality(), Effort(), Fleet(), Retention(), Selectivity(), bioeconomic-class, catchability-class, discardmortality-class, effort-class, fleet-class, selectivity-class


Retention Models

Description

Logistic, knife-edge, and double-normal retention-at-age, retention-at-length, and retention-at-weight models for use in a Retention() object.

Usage

RetentionAtAge(Ages, RA50, RA50_95, MaxRet = 1)

RetentionKnifeEdgeAge(Ages, RA)

RetentionAtLength(Length, RL50, RL50_95, MaxRet = 1)

RetentionKnifeEdgeLength(Length, RL)

RetentionAtWeight(Weight, RW50, RW50_95, MaxRet = 1)

DoubleNormalRetention(Length, LR5, LFR, Rmaxlen)

DoubleNormalRetentionWeight(Weight, WR5, WFR, Rmaxweight)

RetentionModels(full = TRUE, print = TRUE)

RetentionModelsLength(full = TRUE, print = TRUE)

RetentionModelsAge(full = TRUE, print = TRUE)

RetentionModelsWeight(full = TRUE, print = TRUE)

Arguments

Ages

Numeric vector of age classes.

RA50

Numeric. Age at 50% retention (logistic-at-age).

RA50_95

Numeric. Interval between RA50 and age at 95% retention (logistic-at-age).

MaxRet

Numeric. Maximum (asymptotic) retention. Default 1 (full retention). Values less than 1 produce a dome-shaped or partially selective retention curve.

RA

Numeric. Knife-edge age threshold; fish at or above this age are fully retained.

Length

Numeric vector of length classes.

RL50

Numeric. Length at 50% retention (logistic-at-length).

RL50_95

Numeric. Interval between RL50 and length at 95% retention (logistic-at-length).

RL

Numeric. Knife-edge length threshold; fish at or above this length are fully retained.

Weight

Numeric vector of weight classes.

RW50

Numeric. Weight at 50% retention (logistic-at-weight).

RW50_95

Numeric. Interval between RW50 and weight at 95% retention (logistic-at-weight).

LR5

Numeric. Length at 5% retention (double-normal).

LFR

Numeric. Length at full retention (double-normal).

Rmaxlen

Numeric. Retention at max(Length) (double-normal). Values less than 1 produce a dome-shaped retention curve.

WR5

Numeric. Weight at 5% retention (double-normal).

WFR

Numeric. Weight at full retention (double-normal).

Rmaxweight

Numeric. Retention at max(Weight) (double-normal). Values less than 1 produce a dome-shaped retention curve.

full

Logical. If TRUE (default), returns a complete table of available models. If FALSE, returns model names only.

print

Logical. If TRUE (default), prints results to the console. If FALSE, returns the data frame invisibly without printing.

Details

Three families of retention model are available:

  • Logistic: a standard increasing retention curve parameterised by the 50% and 95% retention points, with asymptote MaxRet:

    R(x)=MaxRet1+exp(ln(19)xx50x95x50)R(x) = \frac{\texttt{MaxRet}}{1 + \exp\left(-\ln(19) \cdot \frac{x - x_{50}}{x_{95} - x_{50}}\right)}

  • Knife-edge: full retention at or above a threshold, zero below:

    R(x)={0x<xt1xxtR(x) = \begin{cases} 0 & x < x_t \\ 1 & x \geq x_t \end{cases}

  • Double-normal: a combination of ascending and descending half-normal curves, producing either asymptotic (Rmaxlen = 1) or dome-shaped (Rmaxlen < 1) retention.

At-length and at-weight schedules are converted internally to at-age using the age-length key and age-weight key respectively.

The available model functions are:

  • RetentionAtAge(): logistic retention-at-age.

  • RetentionKnifeEdgeAge(): knife-edge retention-at-age.

  • RetentionAtLength(): logistic retention-at-length.

  • RetentionKnifeEdgeLength(): knife-edge retention-at-length.

  • RetentionAtWeight(): logistic retention-at-weight.

  • DoubleNormalRetention(): double-normal retention-at-length.

  • DoubleNormalRetentionWeight(): double-normal retention-at-weight.

The ⁠RetentionModels*⁠ functions list available models:

  • RetentionModels(): all retention models.

  • RetentionModelsAge(): retention-at-age models only.

  • RetentionModelsLength(): retention-at-length models only.

  • RetentionModelsWeight(): retention-at-weight models only.

Value

  • RetentionAtAge(), RetentionKnifeEdgeAge(), RetentionAtLength(), RetentionKnifeEdgeLength(), RetentionAtWeight(), DoubleNormalRetention(), DoubleNormalRetentionWeight(): a numeric vector of retention values (0–1) at each age, length, or weight class respectively.

  • RetentionModels(), RetentionModelsAge(), RetentionModelsLength(), RetentionModelsWeight(): invisibly returns a data frame (if full = TRUE) or character vector (if full = FALSE) of available models. Prints to console if print = TRUE.

See Also

Retention(), Selectivity(), Ages(), Length(), Weight(), Fleet()

Examples

ages   <- 0:10
lengths <- seq(0, 100, by = 1)
weights <- seq(0.1, 10, by = 0.5)

# ---- Logistic Retention ----
ret_age_log   <- RetentionAtAge(ages, RA50 = 3, RA50_95 = 2)
ret_length_log <- RetentionAtLength(lengths, RL50 = 40, RL50_95 = 10)
ret_weight_log <- RetentionAtWeight(weights, RW50 = 5, RW50_95 = 2)

# ---- Knife-Edge Retention ----
ret_age_ke    <- RetentionKnifeEdgeAge(ages, RA = 4)
ret_length_ke <- RetentionKnifeEdgeLength(lengths, RL = 50)

# ---- Double-Normal Retention ----
ret_dn_length <- DoubleNormalRetention(lengths, LR5 = 20, LFR = 50, Rmaxlen = 0.8)
ret_dn_weight <- DoubleNormalRetentionWeight(weights, WR5 = 1, WFR = 5, Rmaxweight = 0.8)


# ---- Plots ----
# Age-based
plot(ages, ret_age_log, type='l', lwd=2, col='blue', ylim=c(0,1),
     main='Retention-at-Age', xlab='Age', ylab='Retention')
lines(ages, ret_age_ke, type='s', lwd=2, col='red')
legend("bottomright", legend=c("Logistic","Knife-Edge"), col=c("blue","red"), lwd=2)

# Length-based
plot(lengths, ret_length_log, type='l', lwd=2, col='blue', ylim=c(0,1),
     main='Retention-at-Length', xlab='Length', ylab='Retention')
lines(lengths, ret_length_ke, type='s', lwd=2, col='red')
lines(lengths, ret_dn_length, lwd=2, col='green')
legend("bottomright", legend=c("Logistic","Knife-Edge","Double-Normal"),
       col=c("blue","red","green"), lwd=2)

# Weight-based
plot(weights, ret_weight_log, type='l', lwd=2, col='blue', ylim=c(0,1),
     main='Retention-at-Weight', xlab='Weight', ylab='Retention')
lines(weights, ret_dn_weight, lwd=2, col='green')
legend("bottomright", legend=c("Logistic","Double-Normal"),
       col=c("blue","green"), lwd=2)

COSEWIC MSE run using the correct MPs and projected time horizon

Description

Dedicated functions for MSE run and reporting for COSEWIC (Committee on the Status of Endangered Wildlife in Canada). MSE projects for 6x maximum age using NFref, FMSYref and curE management procedures.

Usage

runCOSEWIC(OM, ...)

COSEWIC_Pplot(
  MSEobj,
  syear = 2017,
  qcol = "#FFCB62",
  quants = c(0.05, 0.25, 0.5, 0.75, 0.95)
)

COSEWIC_Dplot(
  MSEobj,
  syear = 2017,
  qcol = "#79F48D",
  quants = c(0.05, 0.25, 0.5, 0.75, 0.95),
  nGT = 3
)

COSEWIC_Blow(
  MSEobj,
  syear = 2017,
  qcol = rgb(0.4, 0.8, 0.95),
  quants = c(0.05, 0.25, 0.5, 0.75, 0.95),
  nGT = 3
)

COSEWIC_Hplot(
  MSEobj,
  syear = 2017,
  qcol = rgb(0.4, 0.8, 0.95),
  quants = c(0.05, 0.25, 0.5, 0.75, 0.95)
)

COSEWIC_report(
  MSEobj,
  output_file = NA,
  author = "Author not specified",
  title = NA
)

COSEWIC_tab(MSEobj, rnd = 0, GTs = c(3, 6), syear = 2017, nGT = 3)

COSEWIC_tab_formatted(
  Ptab1,
  thresh = c(20, 40, 40, 20, 40, 40, 40, 30, 5),
  ret_thresh = F
)

Arguments

OM

An operating model object of class OM

...

Other named arguments to pass to runMSE

MSEobj

An object of class MSE with MPs = c("NFref", "FMSYref", "curE")

syear

Current year, starting year for projections (e.g. 2017)

qcol

Color of shaded regions (bars, quantiles)

quants

Quantiles of the shaded regions (vector 5 long e.g. 0.1, 0.2, 0.5, 0.8, 0.9)

nGT

Number of generation times. For COSEWIC_tab, for moving window of SSB chance (metrics A1 and A2). For COSEWIC_Blow and COSEWIC_Dplot, used for projections (the number of projection years should be greater than MaxAge * nGT).

output_file

The directory and filename you wish to use for the report e.g. "C:/temp/myMSEreport.html"

author

The person who made this report

title

The title of the report

rnd

The number of significant figures for rounding.

GTs

A vector of mean generation times to evaluate performance metrics over

Ptab1

A COSEWIC performance table made by COSEWIC_tab

thresh

A vector of thresholds for each column Health, Yield and Reb are 'greater than threshold' conditions

ret_thresh

Logical: if true just the threshold levels are returned

Functions

  • runCOSEWIC(): Calls runMSE with number of projection years for 6x maximum age and uses NFref, FMSYref, and curE MPs.

  • COSEWIC_Pplot(): Projection plots of spawning stock biomass under three scenarios: no catch, FMSY fishing and status quo fishing effort.

  • COSEWIC_Dplot(): Depletion plots evaluate whether significant declines have occurred over three generation times in both historical and projection years.

  • COSEWIC_Blow(): Plots that evaluate the likelihood of declining below Blow, by default, biomass that takes 3 generation times to reach half BMSY with zero fishing

  • COSEWIC_Hplot(): Plots of historical spawning stock relative to unfished and MSY levels.

  • COSEWIC_report(): Create a standard DFO COSEWIC report (provides performance plots to inform COSEWIC processes in Canadian fish stocks).

  • COSEWIC_tab(): Creates a standard COSEWIC performance table:

    • P_Cr is the probability of being in the critical zone (less than 20% depletion)

    • P_Ct is the probability of being in the cautious zone (between 20% and 40% depletion)

    • P_H is the probability of being in the healthy zone (above 40% depletion)

    • P_Cr_MSY is the probability of being in the critical zone (less than 40% BMSY)

    • P_Ct_MSY is the probability of being in the cautious zone (between 40% and 80% BMSY)

    • P_H_MSY is the probability of being in the healthy zone (above 80% BMSY)

    • Caut is the probability of being in the cautious zone in the last 10 projected years

    • P_A1 is the probability of being designated threatened according to COSEWIC Indicator A1 (Spawning biomass less than 70% that three generation times previously)

    • P_A2 is the probability of being designated threatened according to COSEWIC Indicator A2 (Spawning biomass less than 50% that three generation times previously)

    • Blow is the probability that the stock is below the biomass for which it takes 3 generation times to reach 50% BMSY with zero fishing

  • COSEWIC_tab_formatted(): A formatted version of the standard COSEWIC performance plot, color coded by thresholds.

Author(s)

T. Carruthers

References

https://cosewic.ca/index.php/en/


Runs input control MPs on a Data object.

Description

Function runs a MP (or MPs) of class 'Input' and returns a list: input control recommendation(s) in element 1 and Data object in element 2.

Usage

runInMP(Data, MPs = NA, reps = 100)

Arguments

Data

A object of class Data

MPs

A vector of MPs of class 'Input'

reps

Number of stochastic repetitions - often not used in input control MPs.

Author(s)

A. Hordyk


Run a Management Procedure

Description

Run a Management Procedure

Usage

runMP(Data, MPs = NA, reps = 100, perc = 0.5, chkMPs = FALSE, silent = FALSE)

Arguments

Data

A MSEtool Data object

MPs

The name of the MP to run (or a vector or names)

reps

Number of repetitions

perc

Percentile to summarize reps (default is median)

chkMPs

Logical. Should the MPs be checked before attempting to run them?

silent

Logical. Should messages by suppressed?

Value

invisibly returns the Data object


Run a Management Strategy Evaluation

Description

The primary user-facing function for running a complete MSE. Simulates historical dynamics with Simulate(), then projects forward under one or more management procedures (MPs) with Project(), returning a completed MSE object.

Usage

runMSE(
  OM = NULL,
  MPs = NULL,
  Hist = FALSE,
  silent = FALSE,
  parallel = FALSE,
  extended = FALSE,
  checkMPs = FALSE,
  nSim = NULL,
  nsim = NULL,
  DoDynamicUnfished = TRUE,
  DoRefLandings = TRUE,
  DoRefRemovals = FALSE,
  DoConditionObs = TRUE,
  DoGenerateData = TRUE,
  DoMSYRefs = TRUE,
  Reduce = TRUE,
  ...
)

Arguments

OM

An om, OM-legacy, hist, or Hist-legacy object. If NULL (default), uses SingleStockOM.

MPs

Character vector of MP names to project. MPs must be functions available in the current environment. If NULL (default), projects c("CurrentEffort", "CurrentCatch").

Hist

Logical. If TRUE, returns the hist or Hist-legacy object from Simulate() without running forward projections. Useful for inspecting historical dynamics or saving the conditioned OM for later use with Project(). Default FALSE.

silent

Logical. Suppress progress messages if TRUE. Default FALSE.

parallel

Logical or named list controlling parallel execution of MPs. For legacy OM and Hist objects only:

  • if TRUE, all MPs are run in parallel.

  • if a named list, names correspond to individual MPs to run in parallel.

  • pass "sac" to use the SAC parallel backend (OM-legacy only). Default FALSE.

extended

Logical. If TRUE, stores full age- and area-structured arrays for all years in MSE@Misc$extended (legacy only). Substantially increases object size. Default FALSE.

checkMPs

Logical. Validate MP names and availability before projecting. Default FALSE. Legacy only.

nSim

Integer. Reduce the number of simulations to nSim. Passed to both Simulate() and Project(). If NULL (default), all simulations are used.

nsim

Integer. Alternative to nSim for OM-legacy objects. Sets OM@nsim before simulating. Default NULL.

DoDynamicUnfished

Logical. Calculate dynamic unfished reference points? Passed to Simulate(). Default TRUE. om and hist class only.

DoRefLandings

Logical. Calculate landings-based reference points? Passed to Simulate(). Default TRUE. om and hist class only.

DoRefRemovals

Logical. Calculate removals-based reference points? Passed to Simulate(). Default FALSE. om and hist class only.

DoConditionObs

Logical. Condition observation model on historical data? Passed to Simulate(). Default TRUE. om and hist class only.

DoGenerateData

Logical. Generate observed data for MPs? Passed to Simulate(). Default TRUE. om and hist class only.

DoMSYRefs

Logical. Calculate MSY-based reference points? Passed to Simulate(). Default TRUE. om and hist class only.

Reduce

Logical. Reserved for future use. Default TRUE. om and hist class only.

...

Additional arguments. Reserved for future use.

Details

Accepts either an operating model (om or OM-legacy) or a pre-conditioned historical object (hist or Hist-legacy).

When a historical object is provided, Simulate() is skipped and the existing historical dynamics are used directly, saving computation time when projecting new MPs.

If OM = NULL, uses SingleStockOM and projects example MPs CurrentEffort and CurrentCatch as a quick demonstration.

Value

If Hist = TRUE, a hist or Hist-legacy object containing the conditioned historical dynamics. Otherwise, a MSE-legacy object containing projection results for all MPs. If an error occurs during Project(), the historical simulations are returned with a warning.

See Also

Simulate(), Project()


Summarise S4 Object Memory Usage by Slot

Description

Recursively inspects all slots of an S4 object, including nested S4 objects and lists containing S4 objects, and reports their memory footprint. Useful for identifying which slots dominate memory usage in complex S4 objects.

Usage

S4SlotSizes(obj, n = 5, verbose = TRUE)

Arguments

obj

An S4 object.

n

Integer. Number of largest slots to display in the printed summary. Default is 5.

verbose

Logical. If TRUE (default), prints a summary table of the top n slots. If FALSE, returns the full results silently.

Details

Slot paths reflect the access pattern needed to reach each element. For example, a nested S4 slot would appear as obj@SlotA@SlotB, and a named list element inside a slot as obj@SlotA[["item"]].

Note that sizes are not additive — parent slots include the memory of their children, so a slot containing a large nested S4 object will itself appear large.

Value

A data.frame with columns:

  • path: Full slot path using @ notation for S4 slots and ⁠[["name"]]⁠ or ⁠[[i]]⁠ notation for list elements.

  • mb: Size of the slot or element in megabytes.

Returned invisibly, sorted descending by size.

Examples

## Not run: 
# Inspect top 10 slots of a complex S4 model object
S4SlotSizes(my_model, n = 10)

# Retrieve full results without printing
sizes <- S4SlotSizes(my_model, verbose = FALSE)
sizes[sizes$mb > 1, ]  # slots larger than 1 MB

## End(Not run)

Save an Object to Disk

Description

A wrapper for saveRDS() that automatically creates the required directory structure and prints a informational message to the console.

Usage

Save(object, path = NULL, overwrite = FALSE, ...)

Arguments

object

Any R object to save.

path

Character. File path including file name and extension (e.g., "results/my_om.rds"). If NULL (default), a temporary file path is generated via tempfile().

overwrite

Logical. If FALSE (default), an error is thrown if path already exists. Set to TRUE to overwrite an existing file.

...

Additional arguments passed to saveRDS().

Value

Invisibly returns the full file path of the saved object.

See Also

saveRDS()

Examples

x <- list(a = 1, b = 2)
path <- Save(x, path = tempfile(fileext = ".rds"))
path

Select DataList for an MP from MMSE@PPD

Description

Select DataList for an MP from MMSE@PPD

Usage

select_MP(PPD, MP = 1)

Arguments

PPD

PPD slot from an MMSE object

MP

Numeric value indicating the MP to return DataList

Value

A nested list Data objects (nstock by nfleet)


Selectivity

Description

Construct and manipulate a selectivity object defining selectivity-at-age, selectivity-at-length, or selectivity-at-weight for a Fleet() object. Selectivity is required for all fleets.

Usage

Selectivity(
  Pars = list(),
  Model = NULL,
  MeanAtAge = NULL,
  MeanAtLength = NULL,
  MeanAtWeight = NULL,
  Classes = NULL,
  isRel = FALSE,
  Misc = list()
)

isRel(x)

isRel(x) <- value

Selectivity(x) <- value

Arguments

Pars

Named list of selectivity parameters passed to the selectivity model function. Parameter names must match the arguments of the chosen model (see SelectivityModels()). Each element may be a scalar, vector, or array; see Specifying Biological and Fleet Schedules for accepted formats. Default list() (empty).

If Pars and Model are both provided, MeanAtAge is computed from the model and any values already in MeanAtAge are overwritten. To preserve a user-specified MeanAtAge, leave Pars = list() (the default).

If Pars is a fleet object, the Selectivity slot of that fleet is returned.

Model

Character or function or NULL. Selectivity model identifier. If NULL (default), the model is inferred automatically from the names in Pars via FindModel(). May also be supplied as a custom R function with arguments matching those in Pars. See SelectivityModels() for built-in options.

MeanAtAge

Numeric array or NULL. Mean selectivity-at-age with dimensions ⁠Sim x Age x Year⁠ (area dimension added during population). Used directly when Pars is empty and MeanAtLength is not supplied. See Specifying Biological and Fleet Schedules for accepted array formats. Note: if Pars and Model are both provided, any values supplied here will be overwritten during population.

MeanAtLength

Numeric array or NULL. Mean selectivity-at-length with dimensions ⁠Sim x Length x Year⁠. If provided and Pars is empty, takes precedence over MeanAtAge; MeanAtAge is derived from it via the age-length key.

MeanAtWeight

Numeric array or NULL. Mean selectivity-at-weight with dimensions ⁠Sim x Weight x Year⁠. Default NULL.

Classes

Numeric vector or NULL. Length or weight class midpoints corresponding to the second dimension of MeanAtLength or MeanAtWeight. Default NULL.

isRel

Logical. If TRUE, length-based parameters (e.g., L5, LFS) are interpreted as multiples of the length-at-50%-maturity (L50) of the paired stock rather than absolute length values. A Maturity() object must be available to PopulateSelectivity() for scaling to occur. Default FALSE.

Misc

List. Miscellaneous additional inputs. Default list().

x

A selectivity object, or a fleet object for ⁠Selectivity<-⁠.

value

For ⁠Selectivity<-⁠: a selectivity object. For ⁠isRel<-⁠: a logical value.

Details

Selectivity is required for all fleet objects. It defines the probability that a fish of a given age, length, or weight is caught by the gear, on a scale from 0 to 1.

Specifying Selectivity

There are two ways to specify selectivity:

Model-based (recommended): supply Pars as a named list whose element names match the arguments of a built-in or custom model function. The model is resolved automatically unless Model is specified explicitly. See SelectivityModels() for available models and their required parameters, and Specifying Biological and Fleet Schedules for how parameter values are structured across simulations and years.

Available model families are: logistic (at-age, at-length, at-weight), knife-edge (at-age, at-length), and double-normal (at-length, at-weight). At-length and at-weight schedules are converted to at-age internally using the age-length or age-weight key.

Direct array: leave Pars = list() and supply MeanAtAge, MeanAtLength, or MeanAtWeight directly. If MeanAtLength is provided, it takes precedence and MeanAtAge is derived from it. If only MeanAtAge is provided, MeanAtLength is calculated from it unless already populated.

These two approaches are mutually exclusive: if Pars is non-empty and Model can be resolved, any values in MeanAtAge will be overwritten.

Relative Parameters

When isRel = TRUE, length-based parameters (e.g., L5, LFS) are scaled by the maturity L50 of the paired stock before the selectivity curve is computed. This allows selectivity to be expressed as a fraction of the length at 50% maturity rather than an absolute length, which is useful when the same fleet configuration is applied across stocks with different growth characteristics.

Attaching to a Fleet

A selectivity object can be attached to a Fleet() with Selectivity(Fleet) <- MySelectivity and retrieved with Selectivity(Fleet).

Individual slots may be accessed or modified using Pars(), Model(), MeanAtAge(), MeanAtLength(), MeanAtWeight(), Classes(), and isRel().

Value

  • Selectivity() returns a selectivity object. If Pars is a fleet object, the Selectivity slot of that fleet is returned.

  • ⁠Selectivity<-⁠ returns x with the Selectivity slot replaced by value.

  • isRel() returns the isRel slot from x.

  • ⁠isRel<-⁠ returns x with the isRel slot updated.

See Also

Other fleet: Bioeconomic(), Catchability(), DiscardMortality(), Effort(), Fleet(), Retention(), bioeconomic-class, catchability-class, discardmortality-class, effort-class, fleet-class, retention-class, selectivity-class

Examples

# See man-examples/class-Selectivity.R

The selectivity S4 Class

Description

Defines selectivity-at-age, selectivity-at-length, or selectivity-at-weight for use in a fleet object. Selectivity is required for all fleets. Objects are typically created via the Selectivity() constructor, which documents all parameters in detail.

Slots

Pars

list. Named list of selectivity parameters passed to Model. See Selectivity() and SelectivityModels().

Model

function or character or NULL. Selectivity model identifier or function. See SelectivityModels().

isRel

logical, numeric, or character. Whether length-based parameters are expressed relative to maturity L50. See Selectivity().

MeanAtAge

numeric array or NULL. Mean selectivity-at-age (⁠Sim x Age x Year x Area⁠). See Selectivity().

MeanAtLength

numeric array or NULL. Mean selectivity-at-length (⁠Sim x Length x Year x Area⁠). See Selectivity().

MeanAtWeight

numeric array or NULL. Mean selectivity-at-weight (⁠Sim x Weight x Year x Area⁠). See Selectivity().

Classes

numeric or NULL. Length or weight class midpoints corresponding to the second dimension of MeanAtLength or MeanAtWeight.

Misc

list. Miscellaneous additional inputs. Used internally.

See Also

Other fleet: Bioeconomic(), Catchability(), DiscardMortality(), Effort(), Fleet(), Retention(), Selectivity(), bioeconomic-class, catchability-class, discardmortality-class, effort-class, fleet-class, retention-class


Selectivity Models

Description

Logistic, knife-edge, and double-normal selectivity-at-age, selectivity-at-length, and selectivity-at-weight models for use in a Selectivity() object.

Usage

SelectivityAtAge(Ages, SA50, SA50_95)

SelectivityKnifeEdgeAge(Ages, SA)

SelectivityAtLength(Length, SL50, SL50_95)

SelectivityKnifeEdgeLength(Length, SL)

SelectivityAtWeight(Weight, SW50, SW50_95)

DoubleNormal(Length, L5, LFS, Vmaxlen)

DoubleNormalWeight(Weight, W5, WFS, Vmaxweight)

SelectivityModels(full = TRUE, print = TRUE)

SelectivityModelsLength(full = TRUE, print = TRUE)

SelectivityModelsAge(full = TRUE, print = TRUE)

SelectivityModelsWeight(full = TRUE, print = TRUE)

Arguments

Ages

Numeric vector of age classes.

SA50

Numeric. Age at 50% selectivity (logistic-at-age).

SA50_95

Numeric. Interval between SA50 and age at 95% selectivity (logistic-at-age).

SA

Numeric. Knife-edge age threshold; fish at or above this age are fully selected.

Length

Numeric vector of length classes.

SL50

Numeric. Length at 50% selectivity (logistic-at-length).

SL50_95

Numeric. Interval between SL50 and length at 95% selectivity (logistic-at-length).

SL

Numeric. Knife-edge length threshold; fish at or above this length are fully selected.

Weight

Numeric vector of weight classes.

SW50

Numeric. Weight at 50% selectivity (logistic-at-weight).

SW50_95

Numeric. Interval between SW50 and weight at 95% selectivity (logistic-at-weight).

L5

Numeric. Length at 5% selectivity (double-normal).

LFS

Numeric. Length at full selectivity (double-normal).

Vmaxlen

Numeric. Selectivity at max(Length) (double-normal). Values less than 1 produce a dome-shaped selectivity curve.

W5

Numeric. Weight at 5% selectivity (double-normal).

WFS

Numeric. Weight at full selectivity (double-normal).

Vmaxweight

Numeric. Selectivity at max(Weight) (double-normal). Values less than 1 produce a dome-shaped selectivity curve.

full

Logical. If TRUE (default), returns a complete table of available models. If FALSE, returns model names only.

print

Logical. If TRUE (default), prints results to the console. If FALSE, returns the data frame invisibly without printing.

Details

Three families of selectivity model are available:

  • Logistic: a standard increasing selectivity curve parameterised by the 50% and 95% selectivity points:

    S(x)=11+exp(ln(19)xx50x95x50)S(x) = \frac{1}{1 + \exp\left(-\ln(19) \cdot \frac{x - x_{50}}{x_{95} - x_{50}}\right)}

  • Knife-edge: full selectivity at or above a threshold, zero below:

    S(x)={0x<xt1xxtS(x) = \begin{cases} 0 & x < x_t \\ 1 & x \geq x_t \end{cases}

  • Double-normal: a combination of ascending and descending half-normal curves, producing either asymptotic (Vmaxlen = 1) or dome-shaped (Vmaxlen < 1) selectivity.

At-length and at-weight schedules are converted internally to at-age using the age-length key and age-weight key respectively.

The available model functions are:

  • SelectivityAtAge(): logistic selectivity-at-age.

  • SelectivityKnifeEdgeAge(): knife-edge selectivity-at-age.

  • SelectivityAtLength(): logistic selectivity-at-length.

  • SelectivityKnifeEdgeLength(): knife-edge selectivity-at-length.

  • SelectivityAtWeight(): logistic selectivity-at-weight.

  • DoubleNormal(): double-normal selectivity-at-length.

  • DoubleNormalWeight(): double-normal selectivity-at-weight.

The ⁠SelectivityModels*⁠ functions list available models:

  • SelectivityModels(): all selectivity models.

  • SelectivityModelsAge(): selectivity-at-age models only.

  • SelectivityModelsLength(): selectivity-at-length models only.

  • SelectivityModelsWeight(): selectivity-at-weight models only.

Value

  • SelectivityAtAge(), SelectivityKnifeEdgeAge(), SelectivityAtLength(), SelectivityKnifeEdgeLength(), SelectivityAtWeight(), DoubleNormal(), DoubleNormalWeight(): a numeric vector of selectivity values (0–1) at each age, length, or weight class respectively.

  • SelectivityModels(), SelectivityModelsAge(), SelectivityModelsLength(), SelectivityModelsWeight(): invisibly returns a data frame (if full = TRUE) or character vector (if full = FALSE) of available models. Prints to console if print = TRUE.

See Also

Selectivity(), Retention(), Ages(), Length(), Weight(), Fleet()

Examples

ages   <- 0:10
lengths <- seq(0, 100, by = 1)
weights <- seq(0.1, 10, by = 0.5)

# ---- Logistic Selectivity ----
sel_age_log   <- SelectivityAtAge(ages, SA50 = 3, SA50_95 = 2)
sel_length_log <- SelectivityAtLength(lengths, SL50 = 40, SL50_95 = 10)
sel_weight_log <- SelectivityAtWeight(weights, SW50 = 5, SW50_95 = 2)

# ---- Knife-Edge Selectivity ----
sel_age_ke    <- SelectivityKnifeEdgeAge(ages, SA = 4)
sel_length_ke <- SelectivityKnifeEdgeLength(lengths, SL = 50)


# ---- Double-Normal Selectivity ----
sel_dn_length <- DoubleNormal(lengths, L5 = 20, LFS = 50, Vmaxlen = 0.8)
sel_dn_weight <- DoubleNormalWeight(weights, W5 = 1, WFS = 5, Vmaxweight = 0.8)


# ---- Plots ----
# Age-based
plot(ages, sel_age_log, type='l', lwd=2, col='blue', ylim=c(0,1),
     main='Selectivity-at-Age', xlab='Age', ylab='Selectivity')
lines(ages, sel_age_ke, type='s', lwd=2, col='red')
legend("bottomright", legend=c("Logistic","Knife-Edge"), col=c("blue","red"), lwd=2)

# Length-based
plot(lengths, sel_length_log, type='l', lwd=2, col='blue', ylim=c(0,1),
     main='Selectivity-at-Length', xlab='Length', ylab='Selectivity')
lines(lengths, sel_length_ke, type='s', lwd=2, col='red')
lines(lengths, sel_dn_length, lwd=2, col='green')
legend("bottomright", legend=c("Logistic","Knife-Edge","Double-Normal"),
       col=c("blue","red","green"), lwd=2)

# Weight-based
plot(weights, sel_weight_log, type='l', lwd=2, col='blue', ylim=c(0,1),
     main='Selectivity-at-Weight', xlab='Weight', ylab='Selectivity')
lines(weights, sel_dn_weight, lwd=2, col='green')
legend("bottomright", legend=c("Logistic","Double-Normal"),
       col=c("blue","green"), lwd=2)

Sensitivity analysis

Description

A function that determines the inputs for a given data-limited method of class Output and then analyses the sensitivity of TAC estimates to marginal differences in each input. The range used for sensitivity is based on the user-specified CV for that input (e.g. CV_Mort, Mort)

Usage

Sense(Data, MP, nsense = 6, reps = 100, perc = c(0.05, 0.5, 0.95), ploty = T)

Arguments

Data

A data-limited methods data object

MP

A character string representing an MP applied in calculating the TAC recommendations in the DLM object

nsense

The number of points over which to calculate the TAC (resolution)

reps

The number of samples of the quota taken for the calculation of the TAC

perc

The percentile of the sample TAC

ploty

A logical switch, (T/F, should a plot be drawn?)

Author(s)

T. Carruthers

Examples

## Not run: 
Data <- Sense(MSEtool::Cobia, "AvC")

## End(Not run)

Setup parallel processing

Description

Sets up parallel processing using the snowfall package

Usage

setup(cpus = NULL, logical = FALSE, ...)

Arguments

cpus

the number of CPUs to use for parallel processing. If left empty all physical cores will be used, unless logical=TRUE, in which case both physical and logical (virtual) cores will be used.

logical

Use the logical cores as well? Using the virtual cores may not lead to any significant decrease in run time. You can test the optimal number of cores using optCPU()

...

other arguments passed to 'snowfall::sfInit'

Examples

## Not run: 
setup() # set-up the physical processors
setup(6) # set-up 6 processors
setup(logical=TRUE) # set-up physical and logical cores

## End(Not run)

Set Up Parallel Processing for openMSE Workflows

Description

Configure the global parallel processing strategy used throughout the openMSE framework via the future backend.

Usage

SetupParallel(
  workers = future::availableCores(),
  backend = c("auto", "multisession", "multicore", "sequential"),
  max_workers = c("physical", "logical"),
  silent = FALSE
)

DisableParallel(silent = FALSE)

CheckParallel(parallel)

Arguments

workers

Integer. Number of parallel workers. Defaults to future::availableCores().

backend

Character. Parallel backend to use. One of "auto" (default), "multisession", "multicore", or "sequential". "auto" selects a safe backend based on the operating system.

max_workers

Character. Which CPU cores to count when determining the worker ceiling. "physical" (default) limits to physical cores; "logical" allows hyperthreads. Using "physical" is generally recommended.

silent

Logical. If FALSE (default), prints a message describing the active parallel plan.

parallel

Logical. Has parallel been requested?

Details

These functions are intended to be called at the beginning (and optionally the end) of a workflow:

  • SetupParallel() establishes a parallel execution plan

  • DisableParallel() restores sequential execution

  • CheckParallel() validates that a parallel plan is active

By default, SetupParallel() selects a safe, platform-appropriate backend:

  • Windows: multisession

  • macOS / Linux: multisession (default), with optional multicore support

Although future::multicore is often faster on Unix-like systems, multisession is used by default because it is more robust.

Global side effects

SetupParallel() modifies the global future plan for the current R session. All packages relying on future (including furrr) will inherit this plan until it is changed or reset with DisableParallel().

Backend options

  • "multisession" — background R sessions; safe and portable on all platforms

  • "multicore" — forked processes (macOS / Linux only); faster for large workloads but may be unsafe with certain compiled code or external pointers

  • "sequential" — disables parallel processing entirely

Recommended usage

SetupParallel()          # start of workflow
# ... analysis code ...
DisableParallel()        # restore sequential execution

Value

All three functions invisibly return a logical scalar:

  • SetupParallel() and DisableParallel() return TRUE

  • CheckParallel() returns the value of parallel if a valid plan is active, or FALSE if no parallel plan is detected

See Also

future::plan(), future::availableCores(), furrr::future_map()

Examples

## Not run: 
SetupParallel()                        # auto-select backend
SetupParallel(workers = 4)             # explicit worker count
SetupParallel(backend = "multicore")   # multicore on Linux/macOS
DisableParallel()                      # restore sequential execution

## End(Not run)

Show Methods

Description

Display a formatted summary of MSEtool S4 objects in the console.

Arguments

object

An S4 object of the relevant class.


Show MSEtool S4 objects

Description

Briefly prints a couple of lines from str to avoid swamping the console with the contents of very large objects.

Usage

## S4 method for signature 'Data'
show(object)

## S4 method for signature 'OM'
show(object)

## S4 method for signature 'Hist'
show(object)

## S4 method for signature 'MSE'
show(object)

## S4 method for signature 'MOM'
show(object)

## S4 method for signature 'MMSE'
show(object)

Arguments

object

S4 object from MSEtool


Show the output of a PM

Description

Show the output of a PM

Usage

## S4 method for signature 'PMobj'
show(object)

Arguments

object

object of class MSE


Show the output of a single MP recommendation

Description

Show the output of a single MP recommendation

Usage

## S4 method for signature 'Rec'
show(object)

Arguments

object

object of class Rec


Slot in list: get the slot values from a list of objects

Description

Create of vector of values that correspond with a slot in a list of objects

Usage

SIL(listy, sloty)

Arguments

listy

A list of objects

sloty

A character vector representing the slot name

Author(s)

T. Carruthers


Simulate Catch-at-Age Data

Description

CAA generated with either a multinomial or logistic normal observation model from retained catch-at-age array

Usage

simCAA(nsim, yrs, n_age, Cret, CAA_ESS, CAA_nsamp)

Arguments

nsim

Number of simulations

yrs

Number of years

n_age

Number of age classes

Cret

Retained Catch at age in numbers - array(sim, years, maxage+1)

CAA_ESS

CAA effective sample size. If greater than 1, then this is the multinomial distribution sample size. If less than 1, this is the coefficient of variation for the logistic normal distribution (see details).

CAA_nsamp

CAA sample size

Details

The logistic normal generates the catch-at-age sample by first sampling once from a multivariate normal distribution with the mean vector equal to the logarithm of the proportions-at-age and the diagonal of the covariance matrix is the square of the product of the CV and the log proportions (all off-diagonals are zero). The sampled vector is then converted to proportions with the softmax function and expanded to numbers (CAA_nsamp). This method allows for simulating fractional values in the catch-at-age matrix.

Value

CAA array


Simulate Catch-at-Length Data

Description

Simulate CAL and calculate length-at-first capture (LFC), mean length (ML), modal length (Lc), and mean length over modal length (Lbar)

Usage

simCAL(
  nsim,
  nyears,
  maxage,
  CAL_ESS,
  CAL_nsamp,
  nCALbins,
  CAL_binsmid,
  CAL_bins,
  vn,
  retL,
  Linfarray,
  Karray,
  t0array,
  LenCV
)

Arguments

nsim

Number of simulations

nyears

Number of years

maxage

Maximum age

CAL_ESS

CAA effective sample size

CAL_nsamp

CAA sample size

nCALbins

number of CAL bins

CAL_binsmid

mid-points of CAL bins

CAL_bins

Boundary of CAL bins

vn

Vulnerable numbers-at-age

retL

Retention at length curve

Linfarray

Array of Linf values by simulation and year

Karray

Array of K values by simulation and year

t0array

Array of t0 values by simulation and year

LenCV

CV of length-at-age#'

Value

named list with CAL array and LFC, ML, & Lc vectors


Calculates movement matrices from user inputs

Description

A wrapper function for makemov used to generate movement matrices for the operating model. Calculates a movement matrix from user-specified unfished stock biomass fraction in each area and probability of staying in the area in each time step.

Usage

simmov(
  OM,
  dist = c(0.1, 0.2, 0.3, 0.4),
  prob = 0.5,
  distE = 0.1,
  probE = 0.1,
  prob2 = NA,
  figure = TRUE
)

plot_mov(mov, age = 1, type = c("matrix", "all"), year = 1, qval = 0.9)

Arguments

OM

Operating model, an object of class OM.

dist

A vector of fractions of unfished stock in each area. The length of this vector will determine the number of areas (nareas) in the OM.

prob

Mean probability of staying across all areas (single value) or a vector of the probability of individuals staying in each area (same length as dist).

distE

Logit (normal) St.Dev error for sampling stock fractions from the fracs vector

probE

Logit (normal) St.Dev error for sampling desired probability of staying either by area (prob is same length as dist) or the mean probability of staying (prob is a single number).

prob2

Optional vector as long as prob and dist. Upper bounds on uniform sampling of probability of staying, lower bound is prob.

figure

Logical to indicate if the movement matrix will be plotted (mean values and range across OM@nsim simulations.)

mov

A four-dimensional array of dimension c(nsim, maxage, nareas, nareas) or a five-dimensional array of dimension c(nsim, maxage, nareas, nareas, nyears + proyears) specifying movement in the operating model.

age

An age from 0 to maxage for the movement-at-age matrix figure when type = "matrix".

type

Whether to plot a movement matrix for a single age ("matrix") or the full movement versus age figure ("all")

year

If mov is a 5-dimensional array, the year (from 1 to nyears + proyears) for which to plot movement.

qval

The quantile to plot or report the range of values among simulations.

Value

The operating model OM with movement parameters in slot cpars. The mov array is of dimension nsim, maxage, nareas, nareas.

Functions

  • simmov(): Estimation function for creating movement matrix.

  • plot_mov(): Plotting function.

Note

Array mov is age-specific, but currently the movement generated by simmov is independent of age.

Author(s)

T. Carruthers and Q. Huynh

Examples

## Not run: 
movOM_5areas <- simmov(testOM, dist = c(0.01,0.1,0.2,0.3,0.39), prob = c(0.1,0.6,0.6,0.7,0.9))
movOM_5areas@cpars$mov[1, 1, , ] # sim 1, age 1, movement from areas in column i to areas in row j
plot_mov(movOM_5areas@cpars$mov)
plot_mov(movOM_5areas@cpars$mov, type = "all")


## End(Not run)

Calculates movement matrices from user specified distribution among other areas

Description

A wrapper function for makemov2 used to generate movement matrices for the operating model. Calculates a movement matrix from user-specified relative movement to other areas and probability of staying in the area in each time step.

Usage

simmov2(
  OM,
  dist = c(0.05, 0.6, 0.35),
  distE = 0.01,
  frac_other = matrix(c(NA, 2, 1, 3, NA, 1, 1, 4, NA), nrow = 3, byrow = T),
  frac_otherE = 0.01,
  prob = 0.8,
  probE = 1,
  figure = TRUE
)

Arguments

OM

Operating model, an object of class OM.

dist

A vector of fractions of unfished stock in each area. The length of this vector will determine the number of areas (nareas) in the OM.

distE

Logit (normal) St.Dev error for sampling desired fraction in each area

frac_other

A matrix (nareas rows from, nareas columns to) of relative fractions moving to other areas (the positive diagonal (staying) is unspecified).

frac_otherE

Logit (normal) St.Dev error for sampling desired fraction moving to other areas.

prob

the mean probability of staying in the same area among all areas

probE

Logit (normal) St.Dev error for sampling desired probability of staying in each area

figure

Logical to indicate if the movement matrix will be plotted (mean values and range across OM@nsim simulations.)

Value

The operating model OM with movement parameters in slot cpars. The mov array is of dimension nsim, maxage, nareas, nareas.

Functions

  • simmov2(): Estimation function for creating movement matrix.

Note

Array mov is age-specific, but currently the movement generated by simmov is independent of age.

Author(s)

T. Carruthers and Q. Huynh

Examples

## Not run: 
movOM_3areas <- simmov2(testOM, frac_other = matrix(c(NA,2,1, 2,NA,1, 1,2,NA),
nrow=3, byrow=T), frac_otherE = 0.01, prob = 0.8, probE = 0.3)
# sim 1, age 1, movement from areas in column i to areas in row j
movOM_3areas@cpars$mov[1, 1, , ] 
plot_mov(movOM_3areas@cpars$mov)
plot_mov(movOM_3areas@cpars$mov, type = "all")


## End(Not run)

Simulate Operating Model Dynamics

Description

Simulate historical fishery dynamics and calculate reference points for an om or OM-legacy object. Returns a populated hist or Hist-class object containing historical population dynamics, fishery data, and reference points.

Usage

Simulate(
  OM = NULL,
  parallel = FALSE,
  silent = FALSE,
  nSim = NULL,
  nsim = NULL,
  DoDynamicUnfished = TRUE,
  DoRefLandings = TRUE,
  DoRefRemovals = FALSE,
  DoConditionObs = TRUE,
  DoGenerateData = TRUE,
  DoMSYRefs = TRUE,
  Reduce = TRUE,
  ...
)

Arguments

OM

An om or OM-legacy object. If NULL (default), MSEtool::SingleStockOM is used.

parallel

Logical. Use parallel processing? Default FALSE.

silent

Logical. Suppress progress messages if TRUE. Default FALSE.

nSim

Integer. Number of simulation replicates. If NULL (default), the value in OM is used. Only used for om objects; use nsim for OM-legacy objects.

nsim

Integer. Synonym for nSim for OM-legacy objects. If NULL (default), nSim is used if provided.

DoDynamicUnfished

Logical. Calculate the dynamic unfished population dynamics? Default TRUE. Only used for om objects.

DoRefLandings

Logical. Calculate reference yield based on landings? Default TRUE. Only used for om objects.

DoRefRemovals

Logical. Calculate reference yield based on total removals (landings + discards)? Default FALSE. Only used for om objects.

DoConditionObs

Logical. Condition observation model on historical fishery data? Default TRUE. Only used for om objects.

DoGenerateData

Logical. Generate historical fishery data from the observation model? Default TRUE. Only used for om objects.

DoMSYRefs

Logical. Calculate MSY-based reference points? Passed to Simulate(). Default TRUE. om and hist class only.

Reduce

Logical. Reduce object size after simulation for memory efficiency? Default TRUE. Only used for om objects.

...

Additional arguments passed to sub-functions. Not currently used

Details

Simulate() is a dispatcher that calls internal functions Simulate_om() (for om objects) or SimulateOM() (for legacy OM-legacy objects) depending on the class of OM.

Value

See Also

OM(), runMSE()

Examples

## Not run: 
# Simulate using the default example OM
hist <- Simulate()

# Simulate with specific options
hist <- Simulate(
  OM             = MyOM,
  DoRefLandings  = TRUE,
  DoRefRemovals  = FALSE,
  DoGenerateData = FALSE,
  silent         = TRUE
)

## End(Not run)

SimulatedData Data

Description

An object of class Data

Usage

SimulatedData

Format

An object of class Data of length 1.


Run a multi-fleet multi-stock Management Strategy Evaluation

Description

Functions for running a multi-stock and/or multi-fleet Management Strategy Evaluation (closed-loop simulation) for a specified operating model

Usage

SimulateMOM(MOM = MSEtool::Albacore_TwoFleet, parallel = TRUE, silent = FALSE)

ProjectMOM(
  multiHist = NULL,
  MPs = NA,
  parallel = FALSE,
  silent = FALSE,
  checkMPs = FALSE,
  dropHist = FALSE,
  extended = FALSE
)

multiMSE(
  MOM = MSEtool::Albacore_TwoFleet,
  MPs = list(list(c("AvC", "DCAC"), c("FMSYref", "curE"))),
  Hist = FALSE,
  silent = FALSE,
  parallel = TRUE,
  checkMPs = FALSE,
  dropHist = TRUE,
  extended = FALSE
)

Arguments

MOM

A multi-fleet multi-stock operating model (class MOM)

parallel

Logical or a named list. Should MPs be run using parallel processing? See Details for more information.

silent

Should messages be printed out to the console?

multiHist

An Historical Simulation object (class multiHist)

MPs

A matrix of methods (nstock x nfleet) (character string) of class MP

checkMPs

Logical. Check if the specified MPs exist and can be run on SimulatedData?

dropHist

Logical. Drop the (very large) multiHist object from the returned MMSE object? The multiHist object can be (re-)created using SimulateMOM or kept in MMSE@multiHist if dropHist=FALSE

extended

Logical. Return extended projection results? if TRUE, MMSE@Misc$extended is a named list with extended data: FM for overall F across fleets ⁠[nsim, nstock, n_age, nMP, proyears, nareas]⁠. Misc slot in MMSE@PPD will also contain StockPars, FleetPars, and ReferencePoints

Hist

Should model stop after historical simulations? Returns a list containing all historical data

Details

Running MPs in parallel

For most MPs, running in parallel can actually lead to an increase in computation time, due to the overhead in sending the information over to the cores. Consequently, by default the MPs will not be run in parallel if parallel=TRUE (although other internal code will be run in parallel mode).

To run MPs in parallel, specify a named list with the name of the MP(s) assigned as TRUE. For example,⁠parallel=list(AvC=TRUE⁠) will run the AvC MP in parallel mode.

Value

Functions return objects of class MMSE and multiHist #'

  • SimulateMOM - An object of class multiHist

  • ProjectMOM - An object of class MMSE

  • multiMSE - An object of class MMSE

Functions

  • SimulateMOM(): Simulate historical dynamics for multi-OM

  • ProjectMOM(): Run Forward Projections for a MOM object

  • multiMSE(): Run a multi-stock, multi-fleet MSE

Author(s)

T. Carruthers and A. Hordyk


Single Stock Example Operating Model

Description

An example om object representing the simplest operating model structure: one stock and one fleet. Intended to illustrate basic OM construction and use in MSEtool. Pairings of stocks, fleets, and observation models are for illustration only and should not be taken as ecologically meaningful. See also TwoFleetOM, ComplexOM, and MultiStockOM for more complex structural examples.

Usage

SingleStockOM

Format

An om object with the following slots populated:

  • Name: "Single Stock - Single Fleet".

  • nSim: 8. Number of stochastic simulations.

  • nYear: 20. Number of historical years.

  • pYear: 30. Number of projection years.

  • Stock: AlbacoreExStock. A single stock object.

  • Fleet: a length-1 list containing a length-1 list of AsympExFleet. Structure is ⁠[[stock]][[fleet]]⁠.

  • Obs: a length-1 list containing a length-1 list of AgeStructuredObs. Structure is ⁠[[stock]][[fleet]]⁠.

  • Imp: NULL. Implementation error is not specified; the Imp slot retains its class default. See Imp() for details.

Details

Stock

AlbacoreExStock represents a long-lived, slow-growing pelagic species with low natural mortality. See AlbacoreExStock for full parameter details.

Fleet

AsympExFleet represents a fleet with asymptotic length-based selectivity and effort that stabilises early in the historical period. See AsympExFleet for full parameter details.

Observation Model

AgeStructuredObs provides landings, a spawning-biomass survey, and annual age-composition samples from both landed and discarded fish — a data-moderate scenario typical of stocks assessed with a statistical catch-at-age model. See AgeStructuredObs for full parameter details.

Implementation Error

The Imp slot is NULL. The imp is currently a placeholder and implementation error is not applied during simulation. See Imp() for details.

See Also

TwoFleetOM, ComplexOM, MultiStockOM for structural variants. AlbacoreExStock, AsympExFleet, AgeStructuredObs for the component objects. OM(), om, runMSE(), PopulateOM(), ExampleMPs()

Other om: ComplexOM, MultiStockOM, OM(), OM-accessors, TwoFleetOM, om-class

Examples

SingleStockOM
Stock(SingleStockOM)
Fleet(SingleStockOM)

## Not run: 
Hist <- runMSE(SingleStockOM, MPs = ExampleMPs())

## End(Not run)

Manually map the historical relative fishing effort trajectory.

Description

Internal function for interactive plot which allows users to specify the relative trajectory and variability in the historical fishing effort.

Usage

SketchFun(nyears, Years=NULL)

Arguments

nyears

Number of years

Years

An optional vector of years. Should be nyears long.

Author(s)

A. Hordyk


General purpose polynomial smoother

Description

Polynomial smoother (no gradient prediction) applied to a vector that can include NA values. Intended to be rapid for use in management procedures

Usage

smoothy(xx, plot = F, enp_mult, plotname = "", xlab = "x", ylab = "y", x = NA)

Arguments

xx

Vector of real numbers, data to be smoothed.

plot

Logical, should the 'fit' of the smoother be plotted?

enp_mult

Fraction, effective number of parameters multiplier. The smoother parameter number is length(xx) x enp_mult. So higher values of enp_mult means less smoothing (more parameters).

plotname

Character, in case you want to put a label on the plot (plot = T).

xlab

Character, in case you want an xaxis label on the plot (plot = T)

ylab

Character, in case you want a yaxis label on the plot (plot = T)

x

Numeric vector same length as xx, in case you want to have a custom xaxis (e.g. years)

Author(s)

T. Carruthers


Spatial Constructor and Accessors

Description

Construct a spatial object defining the spatial structure and movement dynamics for a stock, or access and replace the Spatial slot of a stock and its individual slots. Spatial is optional — leave it empty for non-spatial (single-area) models.

Usage

Spatial(
  UnfishedDist = NULL,
  ProbStaying = NULL,
  RelativeSize = NULL,
  Movement = NULL,
  FracOther = NULL,
  Arrangement = NULL,
  CVDist = 0.1,
  CVStay = 1,
  Misc = list()
)

UnfishedDist(x)

UnfishedDist(x) <- value

ProbStaying(x)

ProbStaying(x) <- value

RelativeSize(x)

RelativeSize(x) <- value

Movement(x)

Movement(x) <- value

FracOther(x)

FracOther(x) <- value

Arrangement(x)

Arrangement(x) <- value

CVDist(x)

CVDist(x) <- value

CVStay(x)

CVStay(x) <- value

Spatial(x) <- value

Arguments

UnfishedDist

numeric, array, or NULL. Relative unfished biomass distribution across areas. For two-area models, a single value giving the fraction in Area 1 (Area 2 is derived as 1 - UnfishedDist). For multi-area models, must sum to 1 across areas. Accepted formats:

  • Scalar: constant across all simulations, ages, and years.

  • Length-2 bounds vector: sampled from Uniform(lower, upper) once per simulation (two-area models only).

  • Named array ⁠Sim × Area × Age⁠ or ⁠Sim × Area × Age × Year⁠: full age- and time-varying specification. When UnfishedDist is a stock object, Spatial() acts as a pass-through accessor and returns x@Spatial. Default NULL.

ProbStaying

numeric or array. Probability of remaining in an area between time steps. For two-area models, specifies Area 1 only; the Area 2 value is solved internally. Accepts the same formats as UnfishedDist. Default NULL.

RelativeSize

numeric, array, character(1), or NULL. Relative size of each area, used for biomass density calculations. For two-area models, a single value gives the fraction of Area 1 (Area 2 = 1 - RelativeSize). For multi-area models, a vector of length nArea summing to 1, or a ⁠Sim × Area⁠ array. The special value "EqualDensity" sets RelativeSize equal to the mean UnfishedDist across ages and years, producing constant density across areas regardless of their relative size. When NULL (default), all areas are assumed equal in size.

Movement

array or NULL. Movement probability matrix with dimensions ⁠Sim × FromArea × ToArea⁠, optionally extended to ⁠Sim × FromArea × ToArea × Age × Year⁠. Row ⁠[i, ]⁠ gives the probabilities of moving from area i to each area; rows must sum to 1. When supplied, the asymptotic unfished distribution is derived from Movement and assigned to UnfishedDist, overwriting any existing values. When NULL (default), the movement matrix is fitted during Populate() from UnfishedDist, ProbStaying, and FracOther.

FracOther

array or NULL. Required for models with more than two areas. Array with dimensions ⁠Sim × Area × Area⁠, optionally extended to include Age and Year dimensions. Diagonal elements must be NA (staying probabilities are taken from ProbStaying). Off-diagonal element ⁠[i, j]⁠ gives the relative probability of moving from area i to area j; values need not sum to 1 as they are normalised internally. Default NULL.

Arrangement

array or NULL. Spatial layout of areas for plotting purposes. Reserved for future use; currently stored but not applied. Default NULL.

CVDist

numeric(1). Standard deviation of the log-scale penalty on the difference between the optimised asymptotic distribution and the target UnfishedDist during multi-area movement optimisation. Larger values allow the fitted movement matrix to deviate further from the target distribution. Has no effect for two-area models. Default 0.1.

CVStay

numeric(1). Standard deviation of the logit-scale penalty on the difference between the optimised diagonal (staying probability) and the target ProbStaying during multi-area movement optimisation. Larger values allow more deviation from the target staying probability. Has no effect for two-area models. Default 1.

Misc

list. Used internally. Default list().

x

A spatial object for slot accessors, or a stock object for ⁠Spatial<-⁠.

value

For ⁠Spatial<-⁠: a spatial object. For slot replacement functions: the replacement value for the corresponding slot.

Details

Default Behaviour for Non-Spatial Models

Spatial is optional. When the Spatial slot of a stock is empty, Populate() creates a default single-area structure automatically — no Spatial object needs to be specified for non-spatial models.

Two-Area Models

Specify UnfishedDist as the unfished fraction in Area 1 and ProbStaying as the probability of remaining in Area 1. Populate() solves for the Area 2 movement probabilities numerically so that the asymptotic distribution matches UnfishedDist and the Area 1 staying probability matches ProbStaying:

# Fixed parameters across all simulations
sp <- Spatial(UnfishedDist = 0.3,   # 30% of unfished biomass in Area 1
              ProbStaying  = 0.6,   # 60% probability of staying in Area 1
              RelativeSize = 0.4)   # Area 1 is 40% of total area

# Stochastic across simulations
sp <- Spatial(UnfishedDist = c(0.2, 0.4),
              ProbStaying  = c(0.5, 0.8),
              RelativeSize = c(0.3, 0.5))

Age-Varying Movement (Two-Area)

Supply UnfishedDist as a named ⁠Sim × Area × Age⁠ array. Age-specific movement is fitted independently for each age class:

nSim <- 1
ages <- Ages(MaxAge = 5)
nage <- nAge(ages)

# Fish progressively move to Area 2 with age
frac2 <- seq(0.1, 0.9, length.out = nage)
ud <- array(
  c(1 - frac2, frac2),
  dim      = c(nSim, 2, nage),
  dimnames = list(Sim = 1, Area = 1:2, Age = ages@Classes)
)
sp <- Spatial(UnfishedDist = ud, ProbStaying = 0.95)

Multi-Area Models (Three or More Areas)

UnfishedDist must be a ⁠Sim × Area⁠ (or higher-dimensional) array summing to 1 across areas. FracOther is required and specifies the relative probability of movement between each pair of areas. CVDist and CVStay control the penalty weights in the movement optimisation:

nArea <- 3

ud <- matrix(c(0.5, 0.2, 0.3), nrow = 1, ncol = nArea)

# Off-diagonal [i, j] = relative probability of moving from i to j
# Diagonal must be NA (staying probability comes from ProbStaying)
fo <- array(NA, dim = c(1, nArea, nArea))
fo[1, 1, ] <- c(NA, 1,   0.1)
fo[1, 2, ] <- c(1,  NA,  1  )
fo[1, 3, ] <- c(0.1, 1,  NA )

sp <- Spatial(UnfishedDist = ud,
              ProbStaying  = c(0.9, 0.2, 0.9),
              FracOther    = fo,
              RelativeSize = c(0.1, 0.4, 0.5))

Supplying a Movement Matrix Directly

When Movement is supplied, the asymptotic unfished distribution is derived from it and assigned to UnfishedDist, overwriting any existing values. The matrix must have dimensions ⁠Sim × FromArea × ToArea⁠, with rows summing to 1:

mov <- array(
  c(0.7, 0.3,
    0.2, 0.8),
  dim      = c(1, 2, 2),
  dimnames = list(Sim = 1, FromArea = 1:2, ToArea = 1:2)
)
sp <- Spatial(Movement = mov)

Equal Density Across Areas

Setting RelativeSize = "EqualDensity" assigns RelativeSize equal to the mean UnfishedDist across ages and years, so that biomass density is constant across areas regardless of their relative size. Useful when areas are defined by biomass share rather than physical extent:

sp <- Spatial(UnfishedDist = 0.3,
              ProbStaying  = 0.7,
              RelativeSize = "EqualDensity")

Pass-Through Access from a Stock

When UnfishedDist is a stock object, Spatial() returns the Spatial slot directly:

Spatial(my_stock)             # returns my_stock@Spatial
Spatial(my_stock) <- my_sp   # replaces my_stock@Spatial

Slot Accessors

Individual slots can be read or replaced using generic functions matching their names. All replacement functions re-validate the object:

UnfishedDist(sp)  <- 0.4
ProbStaying(sp)   <- 0.7
RelativeSize(sp)  <- 0.5
Movement(sp)      <- my_mov
FracOther(sp)     <- my_fo
CVDist(sp)        <- 0.05
CVStay(sp)        <- 0.5

Value

  • Spatial() returns a spatial object. If UnfishedDist is a stock, returns x@Spatial.

  • ⁠Spatial<-⁠ returns the stock x with the Spatial slot replaced and the object re-validated.

  • UnfishedDist(), ProbStaying(), RelativeSize(), Movement(), FracOther(), Arrangement(), CVDist(), CVStay() return the value of the corresponding slot from x.

  • All replacement variants return x with the named slot updated and the object re-validated.

See Also

  • spatial for the class definition and slot-level documentation.

  • FitMovement() for fitting movement matrix.

  • Populate() for array population.

  • Stock() for the enclosing stock constructor.

Other spatial: spatial-class

Examples

# ---- Default behaviour (non-spatial models) ----

## For single-area models, leave Spatial empty.
## Populate() creates a default single-area structure automatically.
stk <- Stock(Name = "Example stock", Ages = Ages(MaxAge = 5))
Spatial(stk)   # empty spatial-class object

# ---- Two-area model — fixed parameters ----

## UnfishedDist: fraction of unfished biomass in Area 1
## ProbStaying:  probability of remaining in Area 1
## RelativeSize: fraction of total area that is Area 1
## Area 2 values are derived automatically.
sp <- Spatial(UnfishedDist = 0.3,
              ProbStaying  = 0.6,
              RelativeSize = 0.4)
sp <- Populate(sp, Ages = Ages(MaxAge = 5), nSim = 1)
UnfishedDist(sp)   # asymptotic distribution: Sim x Area x Age x Year
ProbStaying(sp)
Movement(sp)       # fitted movement matrix: Sim x FromArea x ToArea x Age x Year
RelativeSize(sp)

# ---- Two-area model — stochastic across simulations ----

## Length-2 vectors are sampled from Uniform(lower, upper) once per simulation.
nSim <- 48
sp_stoch <- Spatial(UnfishedDist = c(0.2, 0.4),
                    ProbStaying  = c(0.5, 0.8),
                    RelativeSize = c(0.3, 0.5))
sp_stoch <- Populate(sp_stoch, Ages = Ages(MaxAge = 5), nSim = nSim)
UnfishedDist(sp_stoch)   # nSim x 2 x Age x Year
Movement(sp_stoch)

# ---- Two-area model — age-varying movement ----

## Supply a named Sim x Area x Age array for UnfishedDist.
## Movement is fitted independently for each age class.
ages <- Ages(MaxAge = 5)
nage <- nAge(ages)

## Fish progressively move to Area 2 with age — ud must sum to 1 across areas
frac2 <- seq(0.1, 0.9, length.out = nage)
ud <- array(NA, dim = c(1, 2, nage),
            dimnames = list(Sim = 1, Area = 1:2, Age = ages@Classes))
ud[, 1, ] <- 1 - frac2   # Area 1 fraction by age
ud[, 2, ] <- frac2        # Area 2 fraction by age
sp_age <- Spatial(UnfishedDist = ud, ProbStaying = 0.95)
sp_age <- Populate(sp_age, Ages = ages, nSim = 1)

## Asymptotic distribution by age
UnfishedDist(sp_age)[1, , , 1]

## Movement matrix for youngest and oldest age class
Movement(sp_age)[1, , , 1, 1]   # youngest
Movement(sp_age)[1, , , nage, 1] # oldest

# ---- Three-area model — fixed parameters ----

## FracOther is required for 3+ areas.
## Diagonal elements must be NA; off-diagonal [i,j] is the relative
## probability of moving from area i to area j (normalised internally).
nArea <- 3

ud <- matrix(c(0.5, 0.2, 0.3), nrow = 1, ncol = nArea)

fo <- array(NA, dim = c(1, nArea, nArea))
fo[1, 1, ] <- c(NA,  1,   0.1)   # from Area 1: 10x more likely to go to Area 2 than 3
fo[1, 2, ] <- c(1,   NA,  1  )   # from Area 2: equal probability to Area 1 and 3
fo[1, 3, ] <- c(0.1, 1,   NA )   # from Area 3: 10x more likely to go to Area 2 than 1

sp3 <- Spatial(UnfishedDist = ud,
               ProbStaying  = c(0.9, 0.2, 0.9),
               FracOther    = fo,
               RelativeSize = c(0.1, 0.4, 0.5))
sp3 <- Populate(sp3, Ages = Ages(MaxAge = 5), nSim = 1)
UnfishedDist(sp3)[1, , , 1]
Movement(sp3)[1, , , 1, 1]
RelativeSize(sp3)

# ---- Three-area model — age-varying movement ----

## UnfishedDist as a Sim x Area x Age array.
nage <- nAge(Ages(MaxAge = 5))

ud3 <- array(NA, dim = c(1, nArea, nage))
ud3[, , 1] <- c(0.95, 0.045, 0.005)
ud3[, , 2] <- c(0.75, 0.20,  0.05 )
ud3[, , 3] <- c(0.50, 0.40,  0.10 )
ud3[, , 4] <- c(0.30, 0.50,  0.20 )
ud3[, , 5] <- c(0.10, 0.50,  0.40 )
ud3[, , 6] <- c(0.01, 0.20,  0.79 )

sp3_age <- Spatial(UnfishedDist = ud3,
                   ProbStaying  = 0.05,
                   FracOther    = fo)
sp3_age <- Populate(sp3_age, Ages = Ages(MaxAge = 5), nSim = 1)

## Asymptotic distribution and movement at youngest and oldest age class
UnfishedDist(sp3_age)[1, , , 1]
Movement(sp3_age)[1, , , 1,    1]   # youngest
Movement(sp3_age)[1, , , nage, 1]   # oldest

# ---- Supplying a movement matrix directly ----

## When Movement is supplied, UnfishedDist is derived from it.
## Each row (FromArea) must sum to 1 across ToAreas.
mov <- array(NA, dim = c(1, 2, 2),
             dimnames = list(Sim = 1, FromArea = 1:2, ToArea = 1:2))
mov[1, 1, ] <- c(0.7, 0.3)   # from Area 1: 70% stay, 30% move to Area 2
mov[1, 2, ] <- c(0.2, 0.8)   # from Area 2: 20% move to Area 1, 80% stay
sp_mov <- Spatial(Movement = mov)
sp_mov <- Populate(sp_mov, Ages = Ages(MaxAge = 5), nSim = 1)
UnfishedDist(sp_mov)   # derived from supplied Movement matrix

# ---- Equal density across areas ----

## RelativeSize = "EqualDensity" sets RelativeSize equal to mean
## UnfishedDist, producing constant density across areas.
sp_ed <- Spatial(UnfishedDist = 0.3,
                 ProbStaying  = 0.7,
                 RelativeSize = "EqualDensity")
sp_ed <- Populate(sp_ed, Ages = Ages(MaxAge = 5), nSim = 1)
RelativeSize(sp_ed)   # equals mean UnfishedDist

# ---- Slot accessors ----

sp <- Spatial(UnfishedDist = 0.3, ProbStaying = 0.6, RelativeSize = 0.4)

## Read slots
UnfishedDist(sp)
ProbStaying(sp)
RelativeSize(sp)
CVDist(sp)
CVStay(sp)

## Replace slots
UnfishedDist(sp) <- 0.4
ProbStaying(sp)  <- 0.7
CVDist(sp)       <- 0.05

# ---- Attaching to a Stock ----

Spatial(stk) <- Spatial(UnfishedDist = 0.3,
                        ProbStaying  = 0.6,
                        RelativeSize = 0.4)
Spatial(stk)

The spatial S4 Class

Description

Defines the spatial structure and movement dynamics for a stock object. Objects are typically created via Spatial(), which documents all parameters and validates inputs. This object is optional — leave it empty for non-spatial (single-area) models; see Default Behaviour in Spatial().

Details

Direct construction via methods::new() is not recommended; use Spatial() instead, which validates inputs and handles dimension expansion.

For non-spatial (single-area) models, leave the Spatial slot of stock empty. Populate() creates a default single-area structure automatically.

The movement matrix is fitted by numerical optimisation to simultaneously reproduce the target UnfishedDist and ProbStaying. For multi-area models, CVDist and CVStay control the relative weight given to each target in the objective function.

Slots

UnfishedDist

numeric, array, or NULL. Relative unfished biomass distribution across areas. After Populate(), a named array with dimensions ⁠Sim × Area × Age × Year⁠. For two-area models, specifies the fraction in Area 1; the Area 2 fraction is derived as 1 - UnfishedDist. For multi-area models, values must sum to 1 across areas. See Spatial() for accepted input formats.

ProbStaying

numeric or array. Probability of remaining in an area between time steps. After Populate(), a named array with dimensions ⁠Sim × Area × Age × Year⁠. For two-area models, specifies Area 1 only; the Area 2 value is solved internally. See Spatial() for accepted input formats.

RelativeSize

numeric, array, or character(1). Relative size of each area, used to compute biomass density. After Populate(), a named ⁠Sim × Area⁠ array. The special value "EqualDensity" sets RelativeSize equal to the mean UnfishedDist across ages and years, producing constant density across areas. When NULL, all areas are assumed equal in size (1/nArea each).

Movement

array or NULL. Movement probability matrix with named dimensions ⁠Sim × FromArea × ToArea × Age × Year⁠. Row ⁠[i, ]⁠ gives the probabilities of moving from area i to each other area; rows sum to 1. Populated automatically during Populate() from UnfishedDist, ProbStaying, and optionally FracOther. May also be supplied directly, in which case the asymptotic unfished distribution is derived from Movement and assigned to UnfishedDist.

FracOther

array or NULL. Required for models with more than two areas. Named array with dimensions ⁠Sim × FromArea × ToArea × Age × Year⁠. Diagonal elements must be NA (probability of staying is taken from ProbStaying). Off-diagonal element ⁠[i, j]⁠ gives the relative probability of moving from area i to area j. Used as a penalty-weight matrix during movement optimisation.

Arrangement

array or NULL. Spatial layout of areas for plotting purposes. Reserved for future use; currently stored but not applied.

CVDist

numeric(1). Standard deviation of the log-scale penalty on the difference between the optimised asymptotic distribution and the target UnfishedDist during multi-area movement optimisation. Larger values allow the fitted movement matrix to deviate more from the target distribution. Has no effect for two-area models. Default 0.1.

CVStay

numeric(1). Standard deviation of the logit-scale penalty on the difference between the optimised diagonal (staying probability) and the target ProbStaying during multi-area movement optimisation. Larger values allow more deviation from the target staying probability. Has no effect for two-area models. Default 1.

Misc

list. Used internally.

See Also

  • Spatial() for the constructor and accessor functions.

  • Populate() for array population and movement matrix fitting.

  • Stock() for the enclosing stock constructor.

Other spatial: Spatial()


Standard MSE projection plot

Description

Plots projections of F/FMSY, SB/SBMSY and Yield

Usage

Splot(MSEobj, MPs = 5, p = c(0.05, 0.25, 0.5, 0.75, 0.95))

Arguments

MSEobj

Object of class 'MSE' from runMSE() or Project()

MPs

Either a positive integer (the first MPs number of MPs to plot), a character vector (the names of the MPs to plot), or an integer vector (the index of the MPs to plot)

p

Vector of quantiles five positions long. Defaults to c(0.05,0.25,0.5,0.75,0.95) so the 90% and 50% intervals with the median plotted in white.

Author(s)

T. Carruthers


SRR Constructor and Accessors

Description

Construct a srr object defining the stock-recruitment relationship and recruitment variability for a stock, or access and replace the SRR slot of a stock and its individual slots. An SRR object is required for all stock objects.

Usage

SRR(
  Pars = list(h = NA),
  Model = "BevertonHolt",
  R0 = NULL,
  SD = NULL,
  AC = NULL,
  SPFrom = NULL,
  TruncSD = 2,
  RecDevInit = NULL,
  RecDevHist = NULL,
  RecDevProj = NULL,
  SpawnTimeFrac = 0,
  RelRecFun = NULL,
  Units = 1,
  Misc = list()
)

R0(x)

R0(x) <- value

SPFrom(x)

SPFrom(x) <- value

RecDevInit(x)

RecDevInit(x) <- value

RecDevHist(x)

RecDevHist(x) <- value

RecDevProj(x)

RecDevProj(x) <- value

SpawnTimeFrac(x)

SpawnTimeFrac(x) <- value

RelRecFun(x)

RelRecFun(x) <- value

SRR(x) <- value

Arguments

Pars

list. Named list containing the steepness parameter for the chosen SRR model. R0 is never placed in Pars — it has its own dedicated slot. The required name depends on Model:

  • BevertonHolt: list(h = ...) where ⁠0.2 < h < 1⁠.

  • Ricker: list(hR = ...).

  • HockeyStick: list(Shinge = ...) where ⁠0 < Shinge <= 1⁠. When Pars is a non-list S4 object with an SRR slot (e.g., a stock), SRR() acts as a pass-through accessor and returns that slot. See Specifying Biological and Fleet Schedules for accepted input formats (scalar, bounds vector, nSim-length vector). Default list(h = NA).

Model

character(1) or function. SRR model identifier. Must match one of the models listed in SRRModels(), or be a custom R function. Default "BevertonHolt".

R0

numeric or NULL. Unfished equilibrium recruitment. May be:

  • A scalar: same value for all simulations.

  • A length-2 bounds vector: sampled from Uniform(lower, upper) once per simulation.

  • A length-nSim vector: one value per simulation. Interpreted in units of Units. Default NULL.

SD

numeric or NULL. Log-space standard deviation of recruitment deviations. Follows the same length conventions as R0. Currently fixed across years (time-varying SD is not yet supported). When NULL, recruitment is deterministic (no process error). Default NULL.

AC

numeric or NULL. Lag-1 autocorrelation of log-space recruitment deviations. Follows the same length conventions as R0. Currently fixed across years. Defaults to 0 (no autocorrelation) when NULL. Default NULL.

SPFrom

character(1) or numeric(1). Stock whose spawning production drives this stock's recruitment. Specify by stock name (character) or 1-based integer index (numeric). Defaults to self (the stock recruits from its own spawning production). Relevant only in multi-stock operating models. Default NULL.

TruncSD

numeric(1). Number of standard deviations at which the log-normal recruitment deviation distribution is truncated. Default 2.

RecDevInit

matrix or NULL. Pre-specified recruitment deviations (⁠Sim × Age⁠) for initialising the historical age structure, covering all age classes except the minimum age (whose deviation is the first column of RecDevHist). If NULL (default), generated internally from SD and AC during Populate().

RecDevHist

matrix or NULL. Pre-specified recruitment deviations (⁠Sim × nHistTS⁠) for historical time steps. The first column corresponds to the minimum age class in the initial year. If NULL (default), generated internally from SD and AC.

RecDevProj

matrix or NULL. Pre-specified recruitment deviations (⁠Sim × nProjTS⁠) for projection time steps. If NULL (default), generated internally from SD and AC.

SpawnTimeFrac

numeric(1). Fraction of the time step elapsed before spawning occurs. Determines how much mortality (⁠exp(-Z × SpawnTimeFrac)⁠) is applied to the population before spawning numbers are counted:

  • 0 (default): spawning at the start of the step; no mortality applied before spawning.

  • 0.5: spawning mid-step; half of annual Z applied before spawning.

  • 1: spawning at the end of the step; full within-step Z applied before spawning. Default 0.

RelRecFun

function, character(1), or NULL. Relative recruitment function giving equilibrium recruitment relative to R0 as a function of spawning-per-recruit (SPR). For built-in models, set automatically during Populate() (e.g., "BevertonHolt_RelRec" when Model = "BevertonHolt"). For custom SRR models, must be supplied with signature ⁠function(Pars, SPR)⁠. Default NULL.

Units

numeric(1). Scaling factor for recruitment. 1 (default) means R0 is in absolute numbers of fish; 1000 means R0 is in thousands of fish. Does not affect internal calculations — used only to set the interpretation of numbers in hist output. Default 1.

Misc

list. Used internally. Default list().

x

A srr object for slot accessors, or a stock object for ⁠SRR<-⁠.

value

For ⁠SRR<-⁠: a srr object. For slot replacement functions: the replacement value for the corresponding slot.

Details

Specifying the SRR

The SRR is defined by three components:

  1. The deterministic curve: Model and Pars (steepness only; R0 goes in its own slot). See SRRModels() for available models:

# Beverton-Holt with fixed steepness
srr <- SRR(Pars = list(h = 0.7), R0 = 1000)

# Beverton-Holt with stochastic steepness across simulations
srr <- SRR(Pars = list(h = c(0.6, 0.9)), R0 = 1000)

# Ricker
srr <- SRR(Pars = list(hR = 0.7), Model = "Ricker", R0 = 1000)

# Hockey-stick
srr <- SRR(Pars = list(Shinge = 0.3), Model = "HockeyStick", R0 = 1000)
  1. Process error: SD and AC control the magnitude and autocorrelation of log-space recruitment deviations. Both are currently fixed across years:

# Stochastic recruitment: SD = 0.4, no autocorrelation
srr <- SRR(Pars = list(h = 0.7), R0 = 1000, SD = 0.4)

# Stochastic recruitment: SD drawn from Uniform(0.3, 0.6), AC = 0.4
srr <- SRR(Pars = list(h = 0.7), R0 = 1000,
           SD = c(0.3, 0.6), AC = 0.4)
  1. Recruitment deviations (RecDevInit, RecDevHist, RecDevProj): generated automatically from SD and AC during Populate() when NULL. Supply directly to condition the operating model on observed recruitment indices or to reproduce a specific stochastic trajectory.

Custom SRR Models

A custom SRR function may be passed to Model. It must accept S, S0, R0, and any named parameters in Pars as arguments. A matching RelRecFun with signature ⁠function(Pars, SPR)⁠ must also be supplied:

my_srr <- function(S, S0, R0, h) {
  # custom Beverton-Holt variant
  4 * h * R0 * S / (S0 * (1 - h) + S * (5 * h - 1))
}
my_rrf <- function(Pars, SPR) {
  h <- Pars$h
  CR <- 4 * h / (1 - h)
  pmax((CR * SPR - 1) / ((CR - 1) * SPR), 0)
}
srr <- SRR(Pars = list(h = 0.7), Model = my_srr,
           R0 = 1000, RelRecFun = my_rrf)

Spawning Production Source (SPFrom)

In multi-stock models, one stock's recruitment may be driven by another stock's spawning production. Specify by stock name or 1-based index:

# Stock 2 recruits based on stock 1's spawning production
srr2 <- SRR(Pars = list(h = 0.7), R0 = 500, SPFrom = 1)
# equivalently by name:
srr2 <- SRR(Pars = list(h = 0.7), R0 = 500, SPFrom = "Stock1")

Pass-Through Access from a Stock

When Pars is a non-list S4 object with an SRR slot, SRR() returns that slot directly:

SRR(my_stock)           # returns my_stock@SRR
SRR(my_stock) <- my_srr # replaces my_stock@SRR

Slot Accessors

Individual slots can be read or replaced using generic functions matching their names. All replacement functions re-validate the object:

Pars(srr)          <- list(h = 0.8)
Model(srr)         <- "Ricker"
R0(srr)            <- 5000
SD(srr)            <- 0.4
AC(srr)            <- 0.3
TruncSD(srr)       <- 2
SpawnTimeFrac(srr) <- 0.5
SPFrom(srr)        <- 1
RelRecFun(srr)     <- "Ricker_RelRec"
RecDevHist(srr)    <- my_hist_matrix
RecDevProj(srr)    <- my_proj_matrix
RecDevInit(srr)    <- my_init_matrix

Value

  • SRR() returns a srr object. If Pars is a non-list S4 object with an SRR slot, returns that slot.

  • ⁠SRR<-⁠ returns the stock x with the SRR slot replaced and the object re-validated.

  • R0(), SPFrom(), RecDevInit(), RecDevHist(), RecDevProj(), SpawnTimeFrac(), RelRecFun() return the value of the corresponding slot from x.

  • All replacement variants return x with the named slot updated and the object re-validated.

See Also

Other srr: srr-class

Examples

# See SRRModels() for all available stock-recruitment models and their
# required parameters. Note: R0 always goes in its own slot, not in Pars.
SRRModels()

# ---- Beverton-Holt (default) ----

## Fixed steepness, deterministic recruitment
srr <- SRR(Pars = list(h = 0.7), R0 = 1000)

## Stochastic steepness — h drawn from Uniform(0.6, 0.9) once per simulation
srr <- SRR(Pars = list(h = c(0.6, 0.9)), R0 = 1000)

## Stochastic R0 across simulations
srr <- SRR(Pars = list(h = 0.7), R0 = c(500, 2000))

## Add recruitment process error: SD = 0.4, no autocorrelation
srr <- SRR(Pars = list(h = 0.7), R0 = 1000, SD = 0.4)

## SD drawn from Uniform(0.3, 0.6), with lag-1 autocorrelation
srr <- SRR(Pars = list(h = 0.7), R0 = 1000,
           SD = c(0.3, 0.6), AC = 0.4)

## R0 in thousands of fish (Units = 1000)
## Does not affect calculations — sets interpretation of numbers in output
srr <- SRR(Pars = list(h = 0.7), R0 = 5, Units = 1000)

# ---- Ricker ----

srr_r <- SRR(Pars  = list(hR = 0.7),
             Model = "Ricker",
             R0    = 1000,
             SD    = 0.4)

# ---- Hockey-stick ----

## Shinge is the hinge point relative to S0 (0 < Shinge <= 1)
srr_hs <- SRR(Pars  = list(Shinge = 0.3),
              Model = "HockeyStick",
              R0    = 1000,
              SD    = 0.4)

# ---- Spawning timing ----

## SpawnTimeFrac = 0 (default): spawning at start of step, no pre-spawn Z
## SpawnTimeFrac = 0.5:         mid-step spawning, exp(-0.5 * Z) applied first
## SpawnTimeFrac = 1:           end-of-step spawning, full exp(-Z) applied first
srr_mid <- SRR(Pars = list(h = 0.7), R0 = 1000, SpawnTimeFrac = 0.5)

# ---- Pre-specified recruitment deviations ----

## Supply RecDevHist directly to condition on observed recruitment.
## Dimensions: nSim x nHistTS. Values are multiplicative deviations
## in log-space (mean-zero lognormal deviates).
nSim    <- 48
nHistTS <- 50
hist_devs <- matrix(rnorm(nSim * nHistTS, 0, 0.4),
                    nrow = nSim, ncol = nHistTS)
dimnames(hist_devs) <- list(
  Sim  = seq_len(nSim),
  Year = seq(1970, by = 1, length.out = nHistTS)  
)
srr_cond <- SRR(Pars       = list(h = 0.7),
                R0         = 1000,
                SD         = 0.4,
                RecDevHist = hist_devs)

# ---- Multi-stock: SPFrom ----

## Stock 2 recruits based on stock 1's spawning production.
## Specify by 1-based index or by stock name.
srr_s2 <- SRR(Pars   = list(h = 0.7),
              R0     = 500,
              SPFrom = 1)          

# ---- Custom SRR model ----

## A custom model must accept S, S0, R0, and any named Pars.
## A matching RelRecFun with signature function(Pars, SPR) must also be given.
my_srr <- function(S, S0, R0, h) {
  4 * h * R0 * S / (S0 * (1 - h) + S * (5 * h - 1))
}
my_rrf <- function(Pars, SPR) {
  h  <- Pars$h
  CR <- 4 * h / (1 - h)
  pmax((CR * SPR - 1) / ((CR - 1) * SPR), 0)
}
srr_custom <- SRR(Pars       = list(h = 0.7),
                  Model      = my_srr,
                  R0         = 1000,
                  SD         = 0.4,
                  RelRecFun  = my_rrf)

# ---- Slot accessors ----

srr <- SRR(Pars = list(h = 0.7), R0 = 1000, SD = 0.4, AC = 0.3)

## Read slots
Pars(srr)
R0(srr)
SD(srr)
AC(srr)
SpawnTimeFrac(srr)
RelRecFun(srr)      # NULL until Populate() is called for built-in models

## Replace slots
R0(srr)            <- 2000
SD(srr)            <- 0.5
SpawnTimeFrac(srr) <- 0.5

# ---- Attaching to a Stock ----

stk <- Stock(Name = "Example stock", Ages = Ages(MaxAge = 20))
SRR(stk) <- SRR(Pars = list(h = 0.7), R0 = 1000, SD = 0.4)
SRR(stk)

# ---- Populate ----

## The final populated object (typically done internally).
## RecDevHist, RecDevProj, and RecDevInit are generated from SD and AC.
pop_srr <- Populate(SRR(stk), Ages = Ages(MaxAge = 20))
pop_srr

The srr S4 Class

Description

Defines the stock-recruitment relationship (SRR) and recruitment variability for a stock object. Objects are typically created via SRR(), which documents all parameters and validates inputs. An srr object is required for all stock objects.

Details

Direct construction via methods::new() is not recommended; use SRR() instead, which validates inputs and sets sensible defaults.

Recruitment deviations are generated in log-space with standard deviation SD and lag-1 autocorrelation AC, truncated at TruncSD standard deviations. SD and AC are currently fixed across years; time-varying process variance is not yet supported.

RecDevInit, RecDevHist, and RecDevProj may be supplied directly to override the internally generated deviations — for example, to condition the operating model on observed recruitment indices.

Slots

Pars

list. Named list containing the steepness parameter for the chosen SRR model. For BevertonHolt: list(h = ...). For Ricker: list(hR = ...). For HockeyStick: list(Shinge = ...). R0 is never placed in Pars; it has its own dedicated slot. See SRRModels() and Specifying Biological and Fleet Schedules for accepted input formats.

Model

function or character(1). SRR model identifier. Defaults to "BevertonHolt". See SRRModels() for available models.

R0

array or numeric. Unfished equilibrium recruitment. May be a scalar (same across all simulations), a length-2 bounds vector (sampled from Uniform(lower, upper) once per simulation), or a length-nSim vector. Interpreted in units of Units (e.g., Units = 1000 means R0 is in thousands of fish). Does not affect internal calculations — used only to set the scale of numbers in hist output.

SD

array or numeric. Log-space standard deviation of recruitment deviations. May be a scalar, length-2 bounds vector, or length-nSim vector. Fixed across years (currently not time-varying). When NULL, recruitment is deterministic.

AC

array or numeric. Lag-1 autocorrelation of log-space recruitment deviations. Follows the same length conventions as SD. Fixed across years (currently not time-varying). Defaults to 0 (no autocorrelation) when NULL.

SPFrom

character(1) or numeric(1). Identifies which stock's spawning production drives this stock's recruitment. Defaults to self (stock recruits from its own spawning production). For multi-stock models, may be a stock name (character) or 1-based integer index (numeric).

TruncSD

numeric(1). Number of standard deviations at which the log-normal recruitment deviation distribution is truncated. Default 2.

RecDevInit

matrix. Recruitment deviations (⁠Sim × Age⁠) used to initialise the historical age structure. Covers all age classes except the minimum age, whose deviation appears as the first entry of RecDevHist. Generated automatically during Populate() from SD and AC if NULL.

RecDevHist

matrix. Recruitment deviations (⁠Sim × nHistTS⁠) for historical time steps. The first column corresponds to the minimum age class in the initial year. Generated automatically if NULL.

RecDevProj

matrix. Recruitment deviations (⁠Sim × nProjTS⁠) for projection time steps. Generated automatically if NULL.

SpawnTimeFrac

numeric(1). Fraction of the time step elapsed before spawning occurs. Controls how much mortality is applied to the population before spawning numbers are counted: numbers at spawning are ⁠N × exp(-Z × SpawnTimeFrac)⁠. 0 = spawning at the start of the step (no mortality applied first); 1 = spawning at the end of the step (full within-step Z applied first). Default 0.

RelRecFun

function or character(1). Relative recruitment function giving equilibrium recruitment relative to R0 as a function of spawning-per-recruit (SPR). For built-in models, set automatically to paste0(Model, "_RelRec") (e.g., "BevertonHolt_RelRec") during Populate(). For custom SRR models, must be supplied by the user with signature ⁠function(Pars, SPR)⁠.

Units

numeric(1). Scaling factor for recruitment. Units = 1 (default) means R0 is in absolute numbers of fish. Units = 1000 means R0 is in thousands of fish. Does not affect internal calculations — used only to set the interpretation of numbers in hist output.

Misc

list. Used internally.

See Also

Other srr: SRR()


Stock–Recruitment Relationships (SRR)

Description

Deterministic stock–recruitment and relative-recruitment models evaluated for a single simulation and a single year.

Usage

BevertonHolt(S, S0, R0, h)

BevertonHolt_RelRec(Pars, SPR)

Ricker(S, S0, R0, hR)

Ricker_RelRec(Pars, SPR)

HockeyStick(S, S0, R0, Shinge)

HockeyStick_RelRec(Pars, SPR)

SRRModels(full = TRUE, print = TRUE)

Arguments

S

Spawning production (biomass or eggs). Numeric length >= 1

S0

Unfished equilibrium spawning production. Numeric scalar.

R0

Unfished equilibrium recruitment. Numeric scalar.

h

Beverton–Holt steepness. A named argument in Pars. 0.2 < h < 1

Pars

Named list of parameters required by a specific SRR model.

SPR

Spawning-per-recruit multiplier. Numeric scalar.

hR

Ricker steepness. A named argument in Pars.

Shinge

Hockey-stick hinge point relative to S0. A named argument in Pars.0 < Shinge <= 1

full

Logical. Provide a complete table (TRUE) or just the model names (FALSE)?

print

Logical. Print out the results (TRUE) or just return the data.frame (FALSE)?

Details

This family of functions provides:

  • Stock–recruitment functions that return expected recruitment given spawning production.

  • Relative-recruitment functions that return equilibrium recruitment relative to R0 as a function of spawning-per-recruit (SPR).

Model listing

SRRModels() prints or returns the set of stock–recruitment models available in the package.

Beverton–Holt

  • BevertonHolt() evaluates expected recruitment:

    R=αS1+βSR = \frac{\alpha S}{1 + \beta S}

  • BevertonHolt_RelRec() evaluates equilibrium recruitment relative to unfished recruitment as a function of SPR.

Ricker

  • Ricker() evaluates expected recruitment:

    R=αSeβSR = \alpha S e^{-\beta S}

  • Ricker_RelRec() evaluates equilibrium relative recruitment as a function of SPR.

Hockey Stick

  • HockeyStick() evaluates recruitment assuming linear increase up to a hinge point followed by saturation at R0:

    R={R0ShingeS,S<ShingeR0,SShingeR = \begin{cases} \frac{R0}{Shinge} S, & S < Shinge \\ R0, & S \ge Shinge \end{cases}

  • HockeyStick_RelRec() evaluates relative equilibrium recruitment as a function of SPR.

Value

For stock–recruitment functions (BevertonHolt(), Ricker(), HockeyStick()): A numeric scalar giving expected recruitment for the specified spawning production.

For relative-recruitment functions (⁠*_RelRec()⁠): A numeric scalar giving equilibrium recruitment relative to unfished recruitment (R / R0) as a function of spawning-per-recruit (SPR).

For SRRModels(): If print = TRUE, prints the available stock–recruitment models to the console and invisibly returns the result. If print = FALSE, returns a character vector or data frame describing the available models.

See Also

SRR()

Examples

## Compare stock–recruitment relationships

R0 <- 1000
S0 <- 1000
h <- 0.8
Shinge <- 0.2
S <- seq(0, S0, length.out = 200)

R_bh <- BevertonHolt(S, S0, R0, h)
R_rk <- Ricker(S, S0, R0, hR = h)
R_hs <- HockeyStick(S, S0, R0, Shinge)

plot(S, R_bh, type = "l", lwd = 2,
     ylim = c(0, 1200), xlab = "Spawning biomass (S)",
     ylab = "Recruitment")
lines(S, R_rk, lwd = 2, lty = 2)
lines(S, R_hs, lwd = 2, lty = 3)
abline(h=h*R0, lty=3)
abline(v=0.2*S0, lty=3)
legend("bottomright",
       legend = c("Beverton–Holt", "Ricker", "Hockey Stick"),
       lty = c(1, 2, 3), lwd = 2, bty = "n")


## Compare relative equilibrium recruitment vs SPR
SPR <- seq(0, 1, length.out = 200)

Pars_bh <- list(h = h)
Pars_rk <- list(hR = h)
Pars_hs <- list(Shinge = Shinge)

RR_bh <- sapply(SPR, BevertonHolt_RelRec, Pars = Pars_bh)
RR_rk <- sapply(SPR, Ricker_RelRec, Pars = Pars_rk)
RR_hs <- sapply(SPR, HockeyStick_RelRec, Pars = Pars_hs)

plot(SPR, RR_bh, type = "l", lwd = 2,
     ylim = c(0, 1.05), xlab = "SPR",
     ylab = "Relative recruitment (R / R0)")
lines(SPR, RR_rk, lwd = 2, lty = 2)
lines(SPR, RR_hs, lwd = 2, lty = 3)
legend("bottomright",
       legend = c("Beverton–Holt", "Ricker", "Hockey Stick"),
       lty = c(1, 2, 3), lwd = 2, bty = "n")

Reads data Stock Synthesis file structure into a Data object using package r4ss

Description

A function that uses the file location of a fitted SS3 model including input files to population the various slots of an Data object.

Usage

SS2Data(
  SSdir,
  Name = "Imported by SS2Data",
  Common_Name = "",
  Species = "",
  Region = "",
  min_age_M = 1,
  gender = 1,
  comp_fleet = "all",
  comp_season = "sum",
  comp_partition = "all",
  comp_gender = "all",
  index_season = "mean",
  silent = FALSE,
  ...
)

Arguments

SSdir

A folder with Stock Synthesis input and output files in it

Name

The name for the Data object

Common_Name

Character string for the common name of the stock.

Species

Scientific name of the species

Region

Geographic region of the stock or fishery.

min_age_M

Currently, the Data object supports a single value of M for all ages. The argument selects the minimum age for calculating the mean of age-dependent M from the SS assessment.

gender

An integer index for the sex for importing biological parameters (1 = female, 2 = male).

comp_fleet

A vector of indices corresponding to fleets in the assessment over which to aggregate the composition (catch-at-length and catch-at-age) data. By default, character string "all" will aggregate across all fleets.

comp_season

Integer, for seasonal models, the season for which the value of the index will be used. By default, "mean" will take the average across seasons.

comp_partition

Integer vector for selecting length/age observations that are retained (2), discarded (1), or both (0). By default, "all" sums over all available partitions.

comp_gender

Integer vector for selecting length/age observations that are female (1), male (2), or both (0), or both scaled to sum to one (3). By default, "all" sums over all gender codes.

index_season

Integer, for seasonal models, the season for which the value of the index will be used. By default, "mean" will take the average across seasons.

silent

Logical. Suppress all messages?

...

Arguments to pass to SS_output

Value

An object of class Data.

Note

Currently supports the version of r4ss on CRAN (v.1.24) and Github (v.1.34-40). Function may be incompatible with other versions of r4ss.

Author(s)

T. Carruthers and Q. Huynh

See Also

SS2OM


Reads data Stock Synthesis file structure into a nested Data object analogous with multiMSE

Description

A function that uses the file location of a fitted SS3 model including input files to population the various slots of an Data object.

Usage

SS2DataMOM(SSdir, age_M = NULL, comp_partition = 2, silent = FALSE, ...)

Arguments

SSdir

A folder with Stock Synthesis input and output files in it. Alternatively,

age_M

A vector of ages to average across to calculate a single value of natural mortality. Currently, the Data object supports a single value of M for all ages. By default, NULL averages over all ages.

comp_partition

Integer vector for selecting length/age observations that are retained (2), discarded (1), or both (0). By default, only retained comps are used. If multiple codes are used, then comp matrix is the sum over all codes.

silent

Logical. Suppress messages?

...

Arguments to pass to SS_output

Value

A nested list of Data objects, with the first index by stock/sex and the second index by fleet.

Note

Currently tested on r4ss version 1.38.1-41 and SS 3.30.14.

Catches in Data@Cat are the predicted sex-specific catch calculated from the SS output.

Author(s)

Q. Huynh

See Also

SS2MOM


Import Stock Synthesis to MOM (2-sex multi-fleet) or OM (single-sex, single-fleet)

Description

Functions that uses the file location or the r4ss output list of a fitted SS3 model including input files to populate the various slots of an MOM or OM object. SS2MOM and SS2OM mainly populates the Stock and Fleet components components of the operating model. SS2MOM creates a 2-sex model and multiple fleets with discarding behavior. SS2OM returns a single sex (either male, female, or averaged biological parameters) and single fleet (aggregate selectivity and mortality, no explicit discarding modeled). For either, the user still needs to parameterize most of the observation and implementation portions. SSMOM2OM is the internal function that simplifies the MOM object to an OM object. plot_SS2OM generates a markdown report to compare the OM and SS output.

Usage

SS2MOM(
  SSdir,
  nsim = 48,
  proyears = 50,
  reps = 1,
  maxF = 3,
  seed = 1,
  interval = 1,
  pstar = 0.5,
  Obs = MSEtool::Generic_Obs,
  Imp = MSEtool::Perfect_Imp,
  silent = FALSE,
  Name = "MOM generated by SS2MOM",
  Source = "No Source provided",
  ...
)

plot_SS2MOM(
  x,
  SSdir,
  gender = 1:2,
  filename = "SS2MOM",
  dir = tempdir(),
  open_file = TRUE,
  silent = FALSE,
  ...
)

SS2OM(
  SSdir,
  nsim = 48,
  proyears = 50,
  reps = 1,
  maxF = 3,
  seed = 1,
  interval = 1,
  pstar = 0.5,
  Obs = MSEtool::Generic_Obs,
  Imp = MSEtool::Perfect_Imp,
  import_mov = TRUE,
  gender = 1:2,
  seasons_to_years = TRUE,
  model_discards = TRUE,
  silent = FALSE,
  Name = "OM generated by SS2OM function",
  Source = "No source provided",
  Author = "No author provided",
  report = FALSE,
  filename = "SS2OM",
  dir = tempdir(),
  open_file = TRUE,
  ...
)

SSMOM2OM(
  MOM,
  SSdir,
  gender = 1:2,
  import_mov = TRUE,
  seed = 1,
  silent = FALSE,
  model_discards = TRUE
)

plot_SS2OM(
  x,
  SSdir,
  gender = 1:2,
  filename = "SS2OM",
  dir = tempdir(),
  open_file = TRUE,
  silent = FALSE,
  ...
)

MOM_agg_fleets(MOM)

Arguments

SSdir

A folder with Stock Synthesis input and output files in it.

nsim

The number of simulations to take for parameters with uncertainty (for OM@cpars custom parameters).

proyears

The number of projection years for MSE

reps

The number of stochastic replicates within each simulation in the operating model.

maxF

The maximum allowable F in the operating model.

seed

The random seed for the operating model.

interval

The interval at which management procedures will update the management advice in multiMSE, e.g., 1 = annual updates.

pstar

The percentile of the sample of the management recommendation for the MP/MMP.

Obs

The observation model (class Obs). These functions do not update implementation parameters.

Imp

The implementation model (class Imp). These functions do not update implementation parameters.

silent

Whether to silence messages to the console.

Name

The name of the operating model

Source

Reference to assessment documentation e.g. a url

...

Arguments to pass to SS_output.

x

For plot_SS2OM, an object of either class OM or Hist. For plot_SS2MOM, an object of either class MOM or multiHist.

gender

An integer that indexes the sex for importing life history parameters (1 = usually female, 2 = usually male, 1:2 = mean across both sexes). Only used for SS2OM only in a 2-sex model.

filename

If report = TRUE, character string for the name of the markdown and HTML files.

dir

If report = TRUE, the directory in which the markdown and HTML files will be saved.

open_file

If report = TRUE, whether the HTML document is opened after it is rendered.

import_mov

Logical. Import movement matrix?

seasons_to_years

Logical, when season is the time step, whether to convert OM from a seasonal model to annual model.

model_discards

Logical, how to simplify a multi-fleet SS model to an OM object. If TRUE, OM will still model discards using the mean retention across fleets (weighted by fleet F). Otherwise, no discards are modeled and all fishing removals are calculated in the OM from the SS F-at-age matrix.

Author

Who did the assessment

report

Logical, if TRUE, the function will run runMSE to generate the Hist object from the operating model to compare against SS output. A markdown report will be generated.

MOM

MOM object

Value

SS2MOM returns an object of class MOM. SS2OM returns an object of class OM.

Functions

  • MOM_agg_fleets(): Aggregate all fleets in an MOM object.

Note

Currently tested on r4ss version 1.38.1-40.0 and SS 3.30.14.

Author(s)

Q. Huynh

See Also

SS2Data SS2DataMOM


Plot Spawning stock biomass and reference points for both historical and projected period

Description

Plot Spawning stock biomass and reference points for both historical and projected period

Usage

SSBrefplot(MSE, simno = 1, ystart = 1, log = F, leg = T)

Arguments

MSE

An object of class 'MSE' produced by from runMSE()

simno

Positive integer, the simulation number you wish to plot

ystart

Positive integer, the calendar year corresponding with the first historical year

log

Boolean, whether log SSB and reference points should be plotted

leg

Boolean, should a legend be included in the plot?

Author(s)

T. Carruthers


Standardize fishing effort across stocks for each fleet

Description

For a multi-stock operating model, effort for a given fleet must be identical across stocks. When stocks have been specified with differing effort trajectories (e.g. derived from stock-specific estimated Fs), this function standardizes effort to the geometric mean across active stocks (those with positive effort) at each time step, and back-calculates stock-fleet targeting weights that preserve effective fishing mortality.

Usage

StandardizeEffort(
  OM,
  populate = TRUE,
  fit_stock_targeting = TRUE,
  generate_stock_targeting = TRUE
)

Arguments

OM

An operating model object (om).

populate

logical(1). Populate OM at beginning of call? Used internally. Default TRUE.

fit_stock_targeting

logical(1). Run FitStockTargeting() after standardizing? Default TRUE.

generate_stock_targeting

logical(1). Run GenerateStockTargeting() after fitting? Default TRUE. Ignored (with a warning) if fit_stock_targeting = FALSE, since GenerateStockTargeting() requires fitted targeting parameters.

Details

For each fleet fl, year t, and simulation i, the standardized effort is the geometric mean of stock-specific effort over stocks with positive effort at that time step:

Ef,t=exp ⁣(1Af,tsAf,tlogEs,f,t)E_{f,t} = \exp\!\left( \frac{1}{|\mathcal{A}_{f,t}|} \sum_{s \in \mathcal{A}_{f,t}} \log E_{s,f,t} \right)

where Af,t={s:Es,f,t>0}\mathcal{A}_{f,t} = \{s : E_{s,f,t} > 0\} is the set of active stocks for fleet ff at time tt.

The targeting weight for each stock is then:

δs,f,t=Es,f,tEf,t\delta_{s,f,t} = \frac{E_{s,f,t}}{E_{f,t}}

so that effective fishing mortality is conserved:

Ef,t×δs,f,t×qs,f=Es,f,t×qs,f=Fs,f,tE_{f,t} \times \delta_{s,f,t} \times q_{s,f} = E_{s,f,t} \times q_{s,f} = F_{s,f,t}

By construction, the targeting weights have geometric mean 1 over active stocks at each time step — equivalently, the log-targeting deviations sum to zero:

sAf,tlogδs,f,t=0\sum_{s \in \mathcal{A}_{f,t}} \log \delta_{s,f,t} = 0

Inactive stocks (Es,f,t=0E_{s,f,t} = 0) receive targeting weight δs,f,t=0\delta_{s,f,t} = 0.

These targeting weights are stored in OM@StockTargeting@Targeting and are subsequently used by FitStockTargeting() to estimate the historical covariance of log-targeting deviations.

If populated, the effort Distribution array must be identical across stocks for each fleet. The function returns OM unchanged if nStock == 1 (any pre-existing StockTargeting data is also cleared in this case, as it is not meaningful for single-stock models).

Value

The input OM object with:

  • Fleet[[st]][[fl]]@Effort@Effort set to the geometric mean effort over active stocks for all stocks in each fleet where effort differed across any stock.

  • OM@StockTargeting@Targeting populated with back-calculated targeting weights δs,f,t\delta_{s,f,t}. Over active stocks at each time step, the weights have geometric mean 1 (equivalently, their logs sum to zero). Inactive stocks receive weight 0.

See Also

FitStockTargeting(), GenerateStockTargeting()

Examples

## Not run: 
OM_standardized <- StandardizeEffort(OM)
# Inspect back-calculated targeting
OM_standardized@StockTargeting@Targeting

## End(Not run)

Stock Constructor and Accessors

Description

Construct a stock object defining the biological and population-dynamics properties of a stock, or access and replace the Stock slot of an enclosing S4 object (e.g., an om object).

Usage

Stock(
  Name = "New Stock Object",
  CommonName = NULL,
  Species = NULL,
  Ages = NULL,
  Length = NULL,
  Weight = NULL,
  NaturalMortality = NULL,
  Maturity = NULL,
  Fecundity = NULL,
  SRR = NULL,
  Spatial = NULL,
  Depletion = NULL,
  Seasons = 1,
  Misc = list()
)

Stock(x) <- value

CommonName(x)

CommonName(x) <- value

Species(x)

Species(x) <- value

Arguments

Name

character(1). Unique stock identifier used throughout model output. Alternatively, an S4 object that contains a Stock slot (e.g., an om object), in which case Stock() acts as a pass-through accessor — see Pass-Through Access. Default "New Stock Object".

CommonName

character(1). Common name of the species (e.g., "Atlantic cod"). When Name is an S4 object and CommonName is numeric, it is treated as a list index for multi-stock Stock slots — see Pass-Through Access. Default NULL.

Species

character(1). Scientific (Latin) name of the species (e.g., "Gadus morhua"). Default NULL.

Ages

An ages object defining the age structure and plus-group age. If NULL (default), an empty ages is created via Ages().

Length

A length object specifying the length-at-age growth schedule. If NULL (default), created via Length().

Weight

A weight object specifying the weight-at-age and weight-at-length schedules. If NULL (default), created via Weight().

NaturalMortality

A naturalmortality object specifying natural mortality rate(s), optionally age- or length-varying. If NULL (default), created via NaturalMortality().

Maturity

A maturity object specifying the maturity schedule as a function of age, length, or weight. If NULL (default), created via Maturity().

Fecundity

A fecundity object specifying egg production as a function of age or length. Optional. When NULL (default), spawning production (SProduction) equals spawning biomass (SBiomass, i.e. mature weight-at-age). When populated, SProduction is in the units of the Fecundity object (e.g. eggs). If NULL (default), created via Fecundity().

SRR

A srr object specifying the stock-recruitment relationship and recruitment variability. Created via SRR()

Spatial

A spatial object specifying spatial structure and movement dynamics. Optional — leave empty for single-area (non-spatial) models. If NULL (default), created via Spatial().

Depletion

A depletion object specifying depletion assumptions at the start (Initial) and/or end (Final) of the historical period, relative to a reference biomass (default "B0"). When Final is specified, Efficiency in Catchability() is optimised to achieve the target terminal depletion, overwriting any existing values. If NULL (default), created via Depletion().

Seasons

integer(1). Number of seasons per calendar year. Use values greater than 1 for within-year dynamics (e.g., 4 for quarterly seasons). Default 1. Must match the time units set in Ages().

Misc

list. Used internally. Default list().

x

A stock object, or an S4 object with a Stock slot, for use with accessor and replacement functions.

value

For ⁠Stock<-⁠: a stock object, or a list of stock objects for multi-stock operating models. For ⁠CommonName<-⁠ and ⁠Species<-⁠: a character(1) string.

Details

Object Structure

A stock object aggregates all biological components needed to simulate stock dynamics:

Required vs Optional Components

Ages(), Length(), Weight(), NaturalMortality(), Maturity(), and SRR() are required. If any are omitted, empty objects with default slots are created automatically, but the model will not run until the required parameters within each sub-object are populated.

Fecundity() and Spatial() are optional. Omitting Fecundity() causes SProduction to equal SBiomass. Omitting Spatial() implies a single well-mixed area.

Depletion() is also optional. Omitting it (or leaving both Initial and Final as NULL) means the stock starts unfished and terminal depletion is determined by the Fleet() and Catchability() parameters.

Pass-Through Access from an Enclosing Object

When Name is an S4 object with a Stock slot (e.g., an om), Stock() returns the slot rather than constructing a new object:

  • Stock(om) returns om@Stock.

  • Stock(om, i) returns om@Stock[[i]] when om@Stock is a list (multi-stock model), or om@Stock when it is a single stock.

The index i is passed via the CommonName argument.

Bookkeeping Slots

The slots nYear, pYear, nSim, CurrentYear, and Years are initialised to working defaults (20, 30, 48, the current calendar year, and the corresponding year vector). These are overwritten automatically when the stock is attached to an OM(), so they need not be set manually.

Value

  • Stock() returns a stock object. If Name is an S4 object with a Stock slot, returns that slot (or an indexed element for list-valued slots).

  • ⁠Stock<-⁠ returns x with the Stock slot replaced by value.

  • CommonName() and Species() return a character(1) string from the corresponding slot of x.

  • ⁠CommonName<-⁠ and ⁠Species<-⁠ return x with the named slot updated.

See Also

Other stock: stock-class

Examples

# ---- Minimal stock (required sub-objects only) ----

## Sub-objects with empty Pars are created automatically.
## The model will not run until each sub-object is fully specified.
## Nominally Gadus morhua but with made-up paramater values!!
stk <- Stock(Name = "Atlantic cod", CommonName = "Atlantic cod",
             Species = "Gadus morhua")
stk

# ---- Fully specified stock ----

stk <- Stock(
  Name             = "Atlantic cod",
  CommonName       = "Atlantic cod",
  Species          = "Gadus morhua",
  Ages             = Ages(MaxAge = 20),
  Length           = Length(Pars = list(Linf = 120, K = 0.2, t0 = -0.1)),
  Weight           = Weight(Pars = list(a = 0.008, b = 3.0)),
  NaturalMortality = NaturalMortality(Pars = list(M = 0.2)),
  Maturity         = Maturity(Pars = list(L50 = 50, L50_95 = 10)),
  SRR              = SRR(Pars = list(h = 0.7), R0 = 1000, SD = 0.4),
  Depletion        = Depletion(Final = 0.4)
)
stk

# ---- Accessing sub-objects ----

Ages(stk)
Length(stk)
NaturalMortality(stk)
SRR(stk)
Depletion(stk)

# ---- Replacing sub-objects ----

Length(stk) <- Length(Pars = list(Linf = c(100, 140), K = 0.2, t0 = -0.1))
Maturity(stk) <- Maturity(Pars = list(A50 = 4, A50_95 = 2))

# ---- Species name accessors ----

CommonName(stk)
Species(stk)
CommonName(stk) <- "Cod"
Species(stk)    <- "Gadus morhua"

# ---- Seasonal model ----

## Seasons = 4 creates quarterly time steps within each calendar year.
stk_seasonal <- Stock(
  Name    = "Seasonal stock",
  Ages    = Ages(MaxAge = 40, Units = "quarter"),
  Seasons = 4
)

Years(stk_seasonal, 'H')

# ---- Multi-stock pass-through access ----

## When Name is an OM or other S4 object with a Stock slot, Stock() is an
## accessor. For a list-valued Stock slot, pass an integer via CommonName.
## om <- OM(Stock = list(stk1, stk2))
## Stock(om)      # returns om@Stock (the list)
## Stock(om, 1)   # returns om@Stock[[1]]

# ---- Attaching to an OM ----

## om <- OM()
## Stock(om) <- stk
## Stock(om)

The stock S4 Class

Description

Defines the biological and population-dynamics properties of a stock for use in an operating model. Objects are typically created via Stock(), which documents all parameters in detail and initialises sub-objects automatically.

Details

This class is the central biological object in the operating model framework. The bookkeeping slots nYear, pYear, nSim, CurrentYear, and Years are populated with working defaults by Stock() and overridden automatically when the stock is attached to an OM(); they need not be set manually.

Direct construction via methods::new() is not recommended; use Stock() instead, which validates inputs and initialises all sub-objects.

Slots

Name

character. Unique stock identifier.

CommonName

character. Common name of the species.

Species

character. Scientific (Latin) name of the species.

Ages

An ages object defining the age structure. See Ages().

Length

A length object defining the length-at-age schedule. See Length().

Weight

A weight object defining the weight-at-age and weight-at-length schedules. See Weight().

NaturalMortality

A naturalmortality object defining the natural mortality schedule. See NaturalMortality().

Maturity

A maturity object defining the maturity schedule. See Maturity().

Fecundity

A fecundity object defining egg production as a function of age or length. Optional — when empty, spawning production (SProduction) equals spawning biomass (SBiomass). See Fecundity().

SRR

A srr object defining the stock-recruitment relationship and recruitment variability. See SRR() and SRRModels().

Spatial

A spatial object defining spatial structure and movement dynamics. Optional — when empty, a single well-mixed area is assumed. See Spatial().

Depletion

A depletion object defining depletion assumptions at the start (Initial) and/or end (Final) of the historical period. Optional — when empty, the stock starts unfished and terminal depletion is determined by the Fleet() and Catchability() parameters. See Depletion().

nYear

numeric(1). Number of historical years. Initialised to 20 by Stock() and overridden when attached to an OM().

pYear

numeric(1). Number of projection years. Initialised to 30 by Stock() and overridden when attached to an OM().

nSim

numeric(1). Number of stochastic simulations. Initialised to 48 by Stock() and overridden when attached to an OM().

CurrentYear

numeric(1). Final calendar year of the historical period. Initialised to the current system year by Stock() and overridden when attached to an OM().

Years

numeric. Vector of all model years (historical + projection), derived from nYear, pYear, CurrentYear, and Seasons. Overridden when attached to an OM().

Seasons

numeric(1). Number of seasons per calendar year.

Misc

list. Used internally.

Log

list. Internal log. Not intended for direct user access.

See Also

Other stock: Stock()


Class 'Stock'

Description

An operating model component that specifies the parameters of the population dynamics model

Slots

Name

An identifying name for the Stock object. Single value. Character string.

Common_Name

Common name of the species. Character string.

Species

Scientific name of the species. Genus and species name. Character string.

maxage

The maximum age of individuals that is simulated. There are maxage+1 (recruitment to age-0) age classes in the storage matrices. maxage is the 'plus group' where all age-classes > maxage are grouped, unless option switched off with OM@cpars$plusgroup=0. Single value. Positive integer.

R0

Initial number of unfished recruits to age-0. This number is used to scale the size of the population to match catch or data, but does not affect any of the population dynamics unless the OM has been conditioned with data. As a result, for a data-limited fishery any number can be used for R0. In data-rich stocks R0 may be estimated as part of a stock assessment, but for data limited stocks users can choose either an arbitrary number (say, 1000) or choose a number that produces simulated catches in recent historical years that are similar to real world catch data. Single value. Positive real number.

M

The instantaneous rate of natural mortality. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. Uniform distribution lower and upper bounds. Non-negative real numbers.

Msd

Inter-annual variation in M expressed as a coefficient of variation of a log-normal distribution. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. If this parameter is positive, yearly M is drawn from a log-normal distribution with a mean specified by log(M) drawn for that simulation and a standard deviation in log space specified by the value of Msd drawn for that simulation. Uniform distribution lower and upper bounds. Non-negative real numbers

h

Steepness of the stock recruit relationship. Steepness governs the proportion of unfished recruits produced when the stock is at 20% of the unfished population size. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This value is the same in all years of a given simulation. Uniform distribution lower and upper bounds. Values from 1/5 to 1.

SRrel

Type of stock-recruit relationship. Use 1 to select a Beverton Holt relationship, 2 to select a Ricker relationship. Single value. Integer

Perr

Recruitment process error, which is defined as the standard deviation of the recruitment deviations in log space. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. Uniform distribution lower and upper bounds. Non-negative real numbers.

AC

Autocorrelation in the recruitment deviations in log space. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided, and used to add lag-1 auto-correlation to the log recruitment deviations. Uniform distribution lower and upper bounds. Non-negative real numbers.

Linf

The von Bertalanffy growth parameter Linf, which specifies the average maximum size that would reached by adult fish if they lived indefinitely. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This value is the same in all years unless Linfsd is a positive number. Uniform distribution lower and upper bounds. Positive real numbers.

Linfsd

Inter-annual variation in Linf. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. If this parameter has a positive value, yearly Linf is drawn from a log-normal distribution with a mean specified by the value of Linf drawn for that simulation and a standard deviation (in log space) specified by the value of Linfsd drawn for that simulation. Uniform distribution lower and upper bounds. Non-negative real numbers.

K

The von Bertalanffy growth parameter k, which specifies the average rate of growth. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This value is the same in all years unless Ksd is a positive number. Uniform distribution lower and upper bounds. Positive real numbers.

Ksd

Inter-annual variation in K. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. If this parameter has a positive value, yearly K is drawn from a log-normal distribution with a mean specified by the value of K drawn for that simulation and a standard deviation (in log space) specified by the value of Ksd drawn for that simulation. Uniform distribution lower and upper bounds. Non-negative real numbers.

t0

The von Bertalanffy growth parameter t0, which specifies the theoretical age at a size 0. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. Uniform distribution lower and upper bounds. Non-positive real numbers.

LenCV

The coefficient of variation (defined as the standard deviation divided by mean) of the length-at-age. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided to specify the distribution of observed length-at-age, and the CV of this distribution is constant for all age classes (i.e, standard deviation increases proportionally with the mean). Uniform distribution lower and upper bounds. Positive real numbers.

L50

Length at 50% maturity. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. The L50 and L50_95 parameters are converted to ages using the growth parameters provided and used to construct a logistic curve to determine the proportion of the population that is mature in each age class. Uniform distribution lower and upper bounds. Positive real numbers.

L50_95

Difference in lengths between 50% and 95% maturity. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. The value drawn is then added to the length at 50% maturity to determine the length at 95% maturity. This parameterization is used instead of specifying the size at 95 percent maturity to avoid situations where the value drawn for the size at 95% maturity is smaller than that at 50% maturity. The L50 and L50_95 parameters are converted to ages using the growth parameters provided and used to construct a logistic curve to determine the proportion of the population that is mature in each age class. Uniform distribution lower and upper bounds. Positive real numbers.

D

Estimated current level of stock depletion, which is defined as the current spawning stock biomass divided by the unfished spawning stock biomass. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. This parameter is used during model initialization to select a series of yearly historical recruitment values and fishing mortality rates that, based on the information provided, could have resulted in the specified depletion level in the simulated last historical year. Uniform distribution lower and upper bounds. Positive real numbers (typically < 1)

a

The alpha parameter in allometric length-weight relationship. Single value. Weight parameters are used to determine catch-at-age and population-at-age from the number of individuals in each age class and the length of each individual, which is drawn from a normal distribution determined by the Linf, K, t0, and LenCV parameters. As a result, they function as a way to scale between numbers at age and biomass, and are not stochastic parameters. Single value. Positive real number.

b

The beta parameter in allometric length-weight relationship. Single value. Weight parameters are used to determine catch-at-age and population-at-age from the number of individuals in each age class and the length of each individual, which is drawn from a normal distribution determine by the Linf, K, t0, and LenCV parameters. As a result, they function as a way to scale between numbers at age and biomass, and are not stochastic parameters. Single value. Positive real number.

Size_area_1

The size of area 1 relative to area 2. The fraction of the unfished biomass in area 1. Please specify numbers between 0 and 1. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. For example, if Size_area_1 is 0.2, then 20% of the total area is allocated to area 1. Fishing can occur in both areas, or can be turned off in one area to simulate the effects of a no take marine reserve. Uniform distribution lower and upper bounds. Positive real numbers.

Frac_area_1

The fraction of the unfished biomass in area 1. Please specify numbers between 0 and 1. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. For example, if Frac_area_1 is 0.5, then 50% of the unfished biomass is allocated to area 1, regardless of the size of area 1 (i.e, size and fraction in each area determine the density of fish, which may impact fishing spatial targeting). In each time step recruits are allocated to each area based on the proportion specified in Frac_area_1. Uniform distribution lower and upper bounds. Positive real numbers.

Prob_staying

The probability of individuals in area 1 remaining in area 1 over the course of one year. Please specify numbers between 0 and 1. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. For example, in an area with a Prob_staying value of 0.95 each fish has a 95% probability of staying in that area in each time step, and a 5% probability of moving to the other area. Uniform distribution lower and upper bounds. Positive fraction.

Fdisc

The instantaneous discard mortality rate the stock experiences when fished using the gear type specified in the corresponding fleet object and discarded. For each simulation a single value is drawn from a uniform distribution specified by the upper and lower bounds provided. Uniform distribution lower and upper bounds. Non-negative real numbers.

Source

A reference to a website or article from which parameters were taken to define the stock object. Single value. Character string.

Objects from the Class

Objects can be created by calls of the form new('Stock')

Author(s)

T. Carruthers and A. Hordyk


StockDescription

Description

A data.frame with description of slots for class Stock

Usage

StockDescription

Format

An object of class data.frame with 27 rows and 2 columns.


Stock Targeting Constructor

Description

Initialises a stocktargeting object with NA-filled arrays sized to the supplied operating model. All arrays are dimensioned and named but left unpopulated.

Usage

StockTargeting(OM)

Arguments

OM

An om object. Must have at least one stock and one fleet.

Value

A stocktargeting object with:

  • Mean: NA array of dimension ⁠[nSim, nStock, nFleet]⁠

  • Covariance: NA array of dimension ⁠[nSim, nStock, nStock, nFleet]⁠

  • AC: NA array of dimension ⁠[nSim, nStock, nFleet]⁠

  • Targeting: NA array of dimension ⁠[nSim, nStock, nFleet, nHistYear]⁠

  • Misc: empty list

If nFleet < 1 or nStock < 1 an empty (default) stocktargeting object is returned with a warning.

See Also

stocktargeting


The stocktargeting S4 Class

Description

The stocktargeting object defines the properties of a fleet's ability to selectively target individual stocks in a mixed-stock fishery. Targeting weights scale the effective fishing effort of each fleet toward or away from each stock relative to the fleet mean.

Slots

Mean

array[sim, stock, fleet]. Mean targeting weight for each simulation, stock, and fleet. Values of 1 indicate neutral (equal) targeting across stocks.

Covariance

array[sim, stock_i, stock_j, fleet]. Log-space residual covariance matrix of targeting weights for each fleet and simulation. Diagonal entries represent per-stock variance; off-diagonal entries represent co-variation in targeting between pairs of stocks.

AC

array[sim, stock, fleet]. Lag-1 autocorrelation of log targeting deviations for each simulation, stock, and fleet. Currently not used but retained for future implementation.

Targeting

array[sim, stock, fleet, year]. Realised targeting deviations in normal space. For each fleet and year, values represent each stock's share of effective fishing effort relative to the fleet mean. Values greater than 1 indicate preferential targeting; values less than 1 indicate avoidance.

Misc

list. Reserved for additional information or user-defined extensions. Not used internally.


Subset MSE object by management procedure (MP) or simulation.

Description

Subset the MSE object by particular MPs (either MP number or name), or particular simulations, or a subset of the projection years (e.g., 1: < projection years).

Usage

Sub(MSEobj, MPs = NULL, sims = NULL, years = NULL)

Arguments

MSEobj

A MSE object.

MPs

A vector MPs names or MP numbers to subset the MSE object. Defaults to all MPs.

sims

A vector of simulation numbers to subset the MSE object. Can also be a logical vector. Defaults to all simulations.

years

A numeric vector of projection years. Should start at 1 and increase by one to some value equal or less than the total number of projection years.

Author(s)

A. Hordyk

See Also

SubOM for OM components and SubCpars for subsetting by simulation and projection years.

Examples

## Not run: 
MSE <- runMSE()
MSE_1 <- Sub(MSE, MPs=1:2)
MSE_1@MPs
MSE_2 <- Sub(MSE, sims=1:10)
MSE_2@nsim

## End(Not run)

Subset the cpars slot in an operating model

Description

Subset the custom parameters of an operating model by simulation and projection years

Usage

SubCpars(x, ...)

## S4 method for signature 'OM'
SubCpars(x, sims = 1:x@nsim, proyears = x@proyears, silent = FALSE)

## S4 method for signature 'MOM'
SubCpars(x, sims = 1:x@nsim, proyears = x@proyears, silent = FALSE)

Arguments

x

An object of class OM or MOM

...

Arguments for method.

sims

A logical vector of length x@nsim to either retain (TRUE) or remove (FALSE). Alternatively, a numeric vector indicating which simulations (from 1 to nsim) to keep.

proyears

If provided, a numeric to reduce the number of projection years (must be less than x@proyears).

silent

Logical to indicate if messages will be reported to console.

Details

Useful function for running multiMSE in batches if running into memory constraints.

Value

An object of class OM or MOM (same class as x).

Author(s)

T. Carruthers, Q. Huynh

See Also

Sub for MSE objects, SubOM for OM components.


Subset a Stock, Fleet, Obs, or Imp object from an OM object

Description

A function that strips out a Stock, Fleet, Obs, or Imp object from a complete OM object. Mainly used for internal functions.

Usage

SubOM(OM, Sub = c("Stock", "Fleet", "Obs", "Imp"))

Arguments

OM

An operating model object (class OM)

Sub

A character string specifying what object type to strip out "Stock", "Fleet", "Obs", or "Imp"

Value

An object of class Stock, Fleet, Obs, or Imp

Author(s)

A. Hordyk

See Also

Sub for subsetting MSE output and SubCpars for subsetting by simulation and projection years.

Examples

Stock <- SubOM(testOM, "Stock")
class(Stock)

Subset an object by simulation, year, age, MP, and/or fleet

Description

Recursively subsets an object along the Sim, Year, Age, MP, and/or Fleet & Stock dimensions. The function operates on arbitrarily nested structures including S4 objects, lists, arrays, and named numeric vectors.

Usage

Subset(
  object,
  Sims = NULL,
  Years = NULL,
  Ages = NULL,
  MPs = NULL,
  Fleets = NULL,
  Stocks = NULL,
  Impute = TRUE
)

Arguments

object

An object to be subset. Supported types include:

  • S4 objects (all slots are recursively subset)

  • Lists (including StockList, FleetList, etc.)

  • Arrays with a Sim, Year, Age, MP, and/or Fleet dimension

  • Named numeric vectors (for Sim and Age dimensions)

Sims

Numeric vector of simulation indices to retain. NULL skips.

Years

Numeric vector of calendar years to retain. NULL skips.

Ages

Numeric vector of age classes to retain. NULL skips.

MPs

Integer or character vector of MPs to retain. NULL skips.

Fleets

Character vector of fleets to retain. NULL skips.

Stocks

Character vector of stocks to retain. NULL skips.

Impute

Logical; only relevant when subsetting by Years. If TRUE (default), years not present in the object are imputed from the nearest available past year. If FALSE, years earlier than the earliest available year are dropped rather than imputed.

Subsetting is applied sequentially when multiple dimensions are supplied, allowing consistent extraction across simulations, years, and age classes in a single call.

Value

An object of the same class as object, subset according to the supplied dimension arguments.

Examples

nSim(SingleStockOM) <- 10
OM <- Populate(SingleStockOM)

# Subset Sims and Years
RecDevs <- OM |>
  Stock(1) |>
  SRR() |>
  RecDevHist()

Subset(RecDevs, Sims=1:2, Years = 1997:2000)


# Subset Ages
MeanLength <- OM |>
  Stock(1) |>
  Length() |>
  MeanAtAge()

Subset(MeanLength, Sim=1:2, Ages=0:3)

Summary of Data object

Description

Summary of Data object

Usage

## S4 method for signature 'Data'
summary(
  object,
  wait = TRUE,
  x = 1,
  plots = "all",
  rmd = FALSE,
  head = "##",
  tplot = 25
)

Arguments

object

An object of class Data

wait

Logical. Wait for key press before next plot?

x

iteration number for the Data object.

plots

Character. What plots to show? all, TS, CAA, CAL, PD for all plots, time-series, catch-at-age, catch-at-length, and probability distributions respectively

rmd

Logical. Used in a rmd file?

head

Character. Heading for rmd file. Default is '##' (second level heading)

tplot

Integer. Number of plots per page. Default 25


Summary of MMSE object

Description

Summary of MMSE object

Usage

## S4 method for signature 'MMSE'
summary(object, ..., silent = FALSE, Refs = NULL)

Arguments

object

object of class MMSE

...

a list of names of PM methods

silent

Should summary be printed to console? Logical.

Refs

An optional named list (matching the PM names) with numeric values to override the default Ref values. See examples.


Summary of MSE object

Description

Summary of MSE object

Usage

## S4 method for signature 'MSE'
summary(object, ..., silent = FALSE, Refs = NULL)

Arguments

object

object of class MSE

...

a list of names of PM methods

silent

Should summary be printed to console? Logical.

Refs

An optional named list (matching the PM names) with numeric values to override the default Ref values. See examples.


Sum over named array dimensions

Description

Convenience wrappers for summing an array over a specific named dimension. These functions provide fast, explicit alternatives to apply() when working with multi-dimensional arrays that use named dimensions.

Usage

SumOverAge(x)

SumOverArea(x)

SumOverClass(x)

SumOverFleet(x)

SumOverStock(x)

SumOverYear(x)

Arguments

x

An array. If the requested dimension is named, it will be summed out; otherwise the last dimension is used as a fallback.

Details

If the requested dimension name is present in names(dimnames(x)), that dimension is summed out. If the dimension is not named (or x has no dimension names), the last dimension of the array is summed by default.

Exported functions

  • SumOverAge() – sum over the "Age" dimension

  • SumOverArea() – sum over the "Area" dimension

  • SumOverClass() – sum over the "Class" dimension

  • SumOverFleet() – sum over the "Fleet" dimension

  • SumOverStock() – sum over the "Stock" dimension

  • SumOverYear() – sum over the "Year" dimension

Value

An array with the specified dimension removed. Dimension names are preserved where possible.


Calculate TAC recommendations for more than one MP

Description

A function that returns the stochastic TAC recommendations from a vector of output control MPs given a data object Data

Usage

TAC(Data, MPs = NA, reps = 100, timelimit = 1, checkMP = TRUE, silent = FALSE)

Arguments

Data

A data-limited methods data object

MPs

optional vector of MP names

reps

Number of repetitions

timelimit

The maximum time (seconds) taken to complete 10 reps

checkMP

Logical. Check if the MP can be run first?

silent

Logical. Suppress messages?

Author(s)

T. Carruthers

Examples

## Not run: 
library(MSEtool)
Data <- TAC(MSEtool::Cobia)
plot(Data)

## End(Not run)

TAC Filter

Description

Filters vector of TAC recommendations by replacing negatives with NA and and values beyond five standard deviations from the mean as NA

Usage

TACfilter(TAC)

Arguments

TAC

A numeric vector of TAC recommendations

Author(s)

T. Carruthers


Extract TAC Recommendations from an MSE Object

Description

Extracts the total allowable catch (TAC) recommendations issued by each management procedure (MP) in each simulation, year, and stock from the PPD slot of an mse object. Returns a tidy data frame suitable for plotting and performance indicator calculations.

Usage

TACs(MSE)

Arguments

MSE

An mse object.

Value

A data frame with columns:

  • Sim: simulation index.

  • Stock: stock name.

  • MP: management procedure name.

  • Year: calendar year (or decimal date for sub-annual time steps).

  • Period: "Historical" or "Projection".

  • Value: TAC recommendation in the units of the operating model.

  • Variable: always "TAC".

See Also

mse, Advice()


Taxa_Table

Description

Database from rfishbase

Usage

Taxa_Table

Format

An object of class tbl_df (inherits from tbl, data.frame) with 34721 rows and 8 columns.

Source

doi:10.1111/j.1095-8649.2012.03464.x

References

Carl Boettiger and Duncan Temple Lang and Peter Wainwright 2012. Journal of Fish Biology


Tom's expand grid

Description

Create an indexing grid from just a vector of maximum dimension sizes

Usage

TEG(vec)

Arguments

vec

A vector of maximum array sizes

Author(s)

T. Carruthers


OM class objects

Description

Example objects of class OM

Usage

testOM

Format

An object of class OM of length 1.

Examples

avail("OM")

Current default thresholds for DFO satisficing

Description

Crit_S is the probability of being in the critical zone in the first 10 projected years Caut_S is the probability of being in the cautious zone in the first 10 projected years Health_S is the probability of being in the healthy zone in the first 10 projected years OvFish_S is the probability of overfishing in the first 10 projected years Yield_S is the mean yield relative to FMSY management over the first 10 projected years Crit is the probability of being in the critical zone in the last 10 projected years Caut is the probability of being in the cautious zone in the last 10 projected years Health is the probability of being in the healthy zone in the last 10 projected years OvFish is the probability of overfishing in the last 10 projected years Yield is the mean yield relative to FMSY management over the last 10 projected years AAVY is the average annual variability in yield over the whole projection phrased as a CV percentage Reb is the probability the stock has rebuilt to over BMSY in 2 mean generation times

Usage

Thresh_tab(Ptab1)

Arguments

Ptab1

A DFO performance table made by DFO_tab()

Author(s)

T. Carruthers


Timeseries Class

Description

Stores detailed simulated time-series outputs including population, catch, effort, and fishing mortality components.

Slots

Number

List of number-at-age arrays Stock: Sim × Age × Year × Area (x MP for MSE objects).

Biomass

Total biomass array(Sim × Stock × Year (x MP for MSE objects).

SBiomass

Spawning biomass array Sim × Stock × Year (x MP for MSE objects).

SProduction

Spawning production array Sim × Stock × Year (x MP for MSE objects).

Interactions

Total interaction by Stock and Fleet (biomass). Array: Sim x Stock x Year x Fleet (x MP for MSE objects).

Landings

Total landings by Stock and Fleet (biomass). Array: Sim x Stock x Year x Fleet (x MP for MSE objects).

Discards

Total discards by Stock and Fleet (biomass). Array: Sim x Stock x Year x Fleet (x MP for MSE objects).

InteractAtAge

List of interactions-at-age (numbers) arrays. Stock: Sim × Age × Year × Fleet × Area (x MP for MSE objects).

LandingsAtAge

List of landings-at-age (numbers) arrays. Stock: Sim × Age × Year × Fleet × Area (x MP for MSE objects).

DiscardsAtAge

List of discards-at-age (numbers) arrays. Stock: Sim × Age × Year × Fleet × Area (x MP for MSE objects).

LandingsAtSize

Nested list of landings-at-size (numbers) arrays Stock, Fleet: Sim × Class × Year × Area (x MP for MSE objects).

DiscardsAtSize

Nested list of discards-at-size (numbers) arrays Stock, Fleet: Sim × Class × Year × Area (x MP for MSE objects).

Effort

Effort array Sim × Year × Fleet (x MP for MSE objects).

Distribution

Fleet effort distribution by area: Sim × Year × Fleet × Area (x MP for MSE objects).

FInteract

Apical fishing mortality for fish that interact with the fishing gear. Array: Sim x Stock x Year x Fleet (x MP for MSE objects).'

FDead

Apical fishing mortality for fish that are killed by fishing gear. Array: Sim x Stock x Year x Fleet (x MP for MSE objects).

FRetain

Apical fishing mortality for fish that are retained by fishers. Array: Sim x Stock x Year x Fleet (x MP for MSE objects).

FInteractArea

Area-specific fishing mortality-at-age for fish that interact with the fishing gear (list by stock). Stock: Sim x Age x Year x Fleet x Area (x MP for MSE objects).

FDeadArea

Area-specific fishing mortality-at-age of fish killed by fishing gear (list by stock). Stock: Sim x Age x Year x Fleet x Area (x MP for MSE objects).

FRetainArea

Area-specific fishing mortality-at-age of retained fish (list by stock). Stock: Sim x Age x Year x Fleet x Area (x MP for MSE objects).

Misc

Miscellaneous list.


Remove observation, implementation, and process error

Description

Takes an existing OM object and converts it to one without any observation error, implementation error, very little process error, and/or gradients in life history parameters and catchability.

Usage

tinyErr(x, ...)

## S4 method for signature 'OM'
tinyErr(x, obs = TRUE, imp = TRUE, proc = TRUE, grad = TRUE, silent = FALSE)

Arguments

x

An object of class OM

...

Arguments to generic function

obs

Logical. Remove observation error? Obs is replaced with Perfect_Info

imp

Logical. Remove implementation error? Imp is replaced with Perfect_Imp

proc

Logical. Remove process error? All sd and cv slots in Stock and Fleet object are set to 0.

grad

Logical. Remove gradients? All grad slots in Stock and qinc in Fleet are set to 0.

silent

Logical. Display messages?

Details

Useful for debugging and testing that MPs perform as expected under perfect conditions.

Value

An updated object of class OM

Examples

OM_noErr <- tinyErr(MSEtool::testOM)

Generic Trade-Plot Function

Description

Generic Trade-Plot Function

Usage

TradePlot(
  MSEobj,
  ...,
  Lims = c(0.2, 0.2, 0.8, 0.8),
  Title = NULL,
  Labels = NULL,
  Satisficed = FALSE,
  Show = "both",
  point.size = 2,
  lab.size = 4,
  axis.title.size = 12,
  axis.text.size = 10,
  legend = TRUE,
  legend.title.size = 12,
  position = c("right", "bottom"),
  cols = NULL,
  fill = "gray80",
  alpha = 0.4,
  PMlist = NULL,
  Refs = NULL,
  Yrs = NULL
)

Tplot(MSEobj, Lims = c(0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5), ...)

Tplot2(MSEobj, Lims = c(0.2, 0.2, 0.8, 0.8), ...)

Tplot3(MSEobj, Lims = c(0.5, 0.5, 0.8, 0.5), ...)

NOAA_plot2(MSEobj)

Arguments

MSEobj

An object of class MSE

...

Names of Performance Metrics (PMs), or other arguments to TradePlot. First PM is recycled if number of PMs is not even

Lims

A numeric vector of acceptable risk/minimum probability thresholds. Recycled if not equal to number of PMs.

Title

Optional title for each plot. Character vector of length(PMs)/2. Recycled.

Labels

Optional named list specifying new labels for MPs. For example: Labels = list(AvC="Average Catch", CC1="Constant Catch")

Satisficed

Logical. Show only the MPs that meet minimum acceptable thresholds (specified in Lims)

Show

Character. Show the plots ('plots'), results table ('table'), 'both' (default), or invisibly return objects only ('none')

point.size

Numeric. Size of the MP points

lab.size

Numeric. Size of MP label. Set to NULL to remove MP labels.

axis.title.size

Numeric. Size of axis titles

axis.text.size

Numeric. Size of axis text

legend

Logical. Include legend?

legend.title.size

Numeric. Size of legend title text

position

Character. Position of legend - 'right' or 'bottom'

cols

Optional character vector of colors for the legend (MP Types) or if cols is a character vector of length MSEobj@nMPs, then the MP labels are colored (no color legend).

fill

Character. Color of the fill

alpha

Numeric. Transparency of fill

PMlist

Optional list of PM names. Overrides any supplied in ... above

Refs

An optional named list (matching the PM names) with numeric values to override the default Ref values. See examples.

Yrs

An optional named list (matching the PM names) with numeric values to override the default Yrs values. See examples.

Value

Invisibly returns a list with summary table of MP performance and the ggplot objects for the plots

Functions

  • Tplot(): A trade-off plot showing probabilities that:

    • not overfishing (PNOF) against long-term yield is > 50\

    • spawning biomass is below BMSY (P100) against LTY

    • spawning biomass is below 0.5BMSY (P50) against LTY

    • spawning biomass is below 0.1BMSY (P10) against LTY

  • Tplot2(): A trade-off plot showing probabilities that:

    • short-term yield is > 50\

    • spawning biomass is below 0.1BMSY (P10) against average annual variability in yield is < 20\

  • Tplot3(): A trade-off plot showing probabilities that:

    • not overfishing (PNOF) against long-term yield is > 50\

    • spawning biomass is below 0.1BMSY (P10) against average annual variability in yield is < 20\

  • NOAA_plot2(): A trade-off plot developed for NOAA showing probabilities that:

    • not overfishing (PNOF) against long-term yield is > 50\

    • spawning biomass is below 0.5BMSY (P50) against average annual variability in yield is < 15\

Author(s)

A. Hordyk


Tune MP

Description

A generic function that uses optimize to tune a single MP parameter to minimize a user-specified function (e.g. squared distance from a mean yield, PGK = 60%, etc.)

Usage

tune_MP(Hist_list, MP, MP_parname, interval, minfunc, tol = 0.01, parallel = F)

Arguments

Hist_list

A list of objects of class Hist - created by runMSE(..., Hist=T)

MP

A character string that is the name of the MP to be tuned

MP_parname

A character string that is the argument (parameter) of the MP to be tuned

interval

A numeric vector two positions long that is the c(lower.bound, upper.bound) for the parameter to be tuned (MP_parname)

minfunc

A function to be minimized (e.g. the squared difference between mean yield obtained by the MP and a desired yield) that takes a list of MSE objects as its first argument.

tol

A positive numerical value that is the tolerance for the optimize procedure (default is 1E-2)

parallel

Logical: should the MSE projections (over the Hist objects in Hist_list) be calculated in parallel?

Value

A function of class MP with argument MP_parname tuned by optim to minimize minfunc

Author(s)

T. Carruthers

Examples

## Not run: 
testOM@cpars$Data = new('Data')
testOM@cpars$Data@MPrec=2000
Hist_1 = runMSE(testOM,Hist=T)
testOM2 = testOM
testOM2@D = testOM@D / 2
Hist_2 = runMSE(testOM2,Hist=T)

myMP = function(x, Data, reps=1, rate = 1){
  CpI = mean(Data@Cat[x,46:50]) / mean(Data@Ind[x,46:50],na.rm=T)
  I = Data@Ind[x,]
  recI = mean(I[length(I)-((5-1):0)])
  Rec=new('Rec')
  Rec@TAC = recI * CpI * rate
  Rec
}
class(myMP) = "MP"

C1000 = function(MSE_list){
  mucat = mean(sapply(MSE_list,function(X){mean(X@Catch)}))
  cat(paste0("mean catch = ",round(mucat,3),"\n"))
  (mucat - 1000)^2 # try to match 1,250t mean yield
}

myMP_t = tune_MP(list(Hist_1,Hist_2), MP = "myMP", MP_parname = "rate", 
                 interval = c(1,1.5), minfunc = C1000, tol=1E-3, parallel =F)

formals(myMP_t)$rate

## End(Not run)

Turing Test

Description

Plots the available data in the Data object together with 5 samples of historical data from the Operating Model (OM) in a random order. The test is used to determine if the data generated by the OM is similar to the fishery data in the Data object. In a well specified OM the user should not be able to visually identify which of the 6 plots is the real fishery data and which are generated by the OM.'

Usage

Turing(OM, Data, wait = TRUE)

TuringMOM(multiHist, Data, wait = TRUE)

Arguments

OM

An object of class OM or class multiHist

Data

An object of class Data or a nested list of Data objects for each stock and fleet

wait

Logical. Wait for key press before next plot?

multiHist

An object of class multiHist. The output of SimulateMOM

Details

In its current form the Turing function does not interpolate missing data in the Data object. Therefore if there are years with missing data, say in the catch time-series, it will be obvious which are the real data and which have been generated by the model. Future versions of the function may include methods to impute missing data for plotting purposes.

The question to ask when examining the plots produced by Turing: do the plots of the 6 data samples look like they are all samples from the same underlying distribution?

Functions

  • TuringMOM(): Turing function for multi-stock, multi-fleet MOMs

Note

The Turing function was suggested by Andre Punt in his review of one of our recent projects. It is named after the Turing test, developed by Alan Turing in 1950, which is designed to see if a human can detect the difference between human and machine generated information.

Examples

## Not run: 
Turing(MSEtool::testOM, MSEtool::SimulatedData, wait=FALSE)

## End(Not run)

Two-Fleet Example Operating Model

Description

An example om object representing a single stock exploited by two fleets with contrasting selectivity patterns and monitoring intensities. Intended to illustrate multi-fleet OM construction in MSEtool. Pairings of stocks, fleets, and observation models are for illustration only and should not be taken as ecologically meaningful. See also SingleStockOM, ComplexOM, and MultiStockOM for structural variants.

Usage

TwoFleetOM

Format

An om object with the following slots populated:

  • Name: "Single Stock - Two Fleets".

  • nSim: 8. Number of stochastic simulations.

  • nYear: 20. Number of historical years.

  • pYear: 30. Number of projection years.

  • Stock: AlbacoreExStock. A single stock object.

  • Fleet: a length-1 list containing a length-2 list of ⁠[[AsympExFleet, DomeExFleet]]⁠. Structure is ⁠[[stock]][[fleet]]⁠.

  • Obs: a length-1 list containing a length-2 list of ⁠[[AgeStructuredObs, CatchAndSurveyObs]]⁠. Structure is ⁠[[stock]][[fleet]]⁠. Fleet 1 has a data-moderate age-structured monitoring programme; Fleet 2 has catch and a survey only.

  • Imp: NULL. Implementation error is not specified; the Imp slot retains its class default. See Imp() for details.

Details

Stock

AlbacoreExStock represents a long-lived, slow-growing large pelagic species with low natural mortality. See AlbacoreExStock for full parameter details.

Fleets

Two contrasting fleets are included:

  • AsympExFleet: asymptotic length-based selectivity; effort stabilises early in the historical period.

  • DomeExFleet: dome-shaped selectivity; effort increases gradually across the historical period.

See AsympExFleet and DomeExFleet for full parameter details.

Observation Models

Each fleet has its own observation model, illustrating a contrast between a well-monitored commercial fleet and a less-monitored one:

  • Fleet 1 (AsympExFleet) uses AgeStructuredObs: landings, a spawning-biomass survey, and annual age-composition samples from landed and discarded fish.

  • Fleet 2 (DomeExFleet) uses CatchAndSurveyObs: reported landings and a biomass-proportional survey index only, with no composition data.

Implementation Error

The Imp slot is NULL. The imp is currently a placeholder and implementation error is not applied during simulation. See Imp() for details.

See Also

SingleStockOM, ComplexOM, MultiStockOM for structural variants. AlbacoreExStock, AsympExFleet, DomeExFleet, AgeStructuredObs, CatchAndSurveyObs for the component objects. OM(), om, runMSE(), PopulateOM(), ExampleMPs()

Other om: ComplexOM, MultiStockOM, OM(), OM-accessors, SingleStockOM, om-class

Examples

TwoFleetOM
nFleet(TwoFleetOM)

## Not run: 
Hist <- runMSE(TwoFleetOM, MPs = ExampleMPs())

## End(Not run)

unfished Class

Description

Stores unfished equilibrium and dynamic population states, used as the baseline reference for calculating biological reference points.

Usage

Unfished(object)

Equilibrium(unfished)

Dynamic(unfished)

Arguments

object

A hist or mse object.

unfished

An unfished object.

Details

Three accessor functions are provided:

  • Unfished() extracts the unfished object from a hist or mse object

  • Equilibrium() extracts the equilibrium population dynamics

  • Dynamic() extracts the dynamic population dynamics

Value

  • Unfished() returns an unfished object

  • Equilibrium() returns a popdynamics object

  • Dynamic() returns a popdynamics object

Slots

Equilibrium

Unfished equilibrium population dynamics. A popdynamics object.

Dynamic

Unfished dynamic population dynamics. A popdynamics object.

Misc

Miscellaneous list for additional outputs.

See Also

popdynamics

Examples

## Not run: 
unf  <- Unfished(Hist)
eq   <- Equilibrium(unf)
dyn  <- Dynamic(unf)

## End(Not run)

Unit Conversion Functions

Description

A family of simple unit conversion functions for weight and length measurements commonly used in fisheries stock assessments.

Usage

lb2kg(x)

lb2mt(x)

kg2lb(x)

kg2mt(x)

kg2_1000lb(x)

inch2mm(x)

mm2inch(x)

Arguments

x

Numeric vector of values to convert.

Details

Weight:

  • lb2kg(x): pounds → kilograms

  • lb2mt(x): pounds → metric tonnes

  • kg2lb(x): kilograms → pounds

  • kg2mt(x): kilograms → metric tonnes

  • kg2_1000lb(x): kilograms → thousands of pounds

Length:

  • inch2mm(x): inches → millimetres

  • mm2inch(x): millimetres → inches

Value

Numeric vector of the same length as x in the target units.


Update an S4 Object and Its Slots

Description

Recursively updates an openMSE S4 object to ensure all slots are valid, and optionally replaces specified slots with new values. UpdateSlots() is called first to reset any inaccessible or corrupted slots to their class defaults, recursing into nested S4 objects. Named arguments in ... are then used to replace slots by name.

Usage

UpdateObject(object, ...)

UpdateSlots(object)

Arguments

object

An S4 object.

...

Named objects used to replace existing slots. Names must match slot names in object. Unrecognised names emit a warning and are ignored.

Value

The updated S4 object with all slots valid and any supplied replacements applied.

Examples

## Not run: 
obj <- UpdateObject(obj, Fleet=newFleet)

## End(Not run)

Find the Management Procedures that use a particular data slot

Description

Find the Management Procedures that use a particular data slot

Usage

Uses(slot, silent = FALSE)

Arguments

slot

A slot from an object of class Data. Character string.

silent

Logical. Should messages be printed?

Value

A character string of MPs that use the slot.

Author(s)

A. Hordyk

Examples

Uses("Mort")

Valid custom parameters (cpars)

Description

Valid custom parameters (cpars)

Usage

validcpars(
  type = c("all", "Stock", "Fleet", "Obs", "Imp", "internal"),
  valid = TRUE,
  show = TRUE
)

Arguments

type

What cpars to show? 'all', 'Stock', 'Fleet', 'Obs', 'Imp', or 'internal'

valid

Logical. Show valid cpars?

show

Logical. Display the table in the Viewer?

Value

a HTML datatable with variable name, description and type of valid cpars

Control list

A named list for control, for example, OM@cpars$control <- list(TAC = "removals", CAL = "removals"), can be specified to override default settings in the MSE simulation. Possible names in the control list are:

  • TAC Character, set to "removals" so that the TAC is applied to the sum of retained + discarded catch. Default only applies the TAC to the retained catch.

  • CAL Character, set to "removals" to sample the catch-at-length from retained + discarded catch. Default only samples from retained catch.

  • D Character, set to "VB" so that historical depletion OM@D corresponds to vulnerable biomass depletion (only used when OM@cpars$qs = NULL).

  • optVB Logical, set to TRUE so that historical depletion OM@D corresponds to vulnerable biomass depletion. Default sets depletion according to spawning biomasss when OM@cpars$qs = NULL.

  • optSBMSY Logical, set to TRUE such that OM@D corresponds to the ratio of spawning biomass to MSY. Default uses according to spawning biomass depletion (biomass relative to unfished levels).

  • Depletion Character, set to "end" such that historical depletion OM@D corresponds to the biomass at the end of the last projection year. Default corresponds to the value at the beginning of the last projection year.

  • ntrials Integer, set the number of iterations to sample the operating model to match the depletion to OM@D. Default is 50.

  • fracD Numeric, the maximum allowable proportion of simulations allowed to hit the bounds of the depletion parameter (simulation returns an error if exceeded). Default is 0.05.

  • checks Logical. If TRUE, plots depletion and SB/SBMSY figures and prints values to the R console to diagnose issues with operating model configuration with regards to depletion.

  • unfished Logical. If TRUE, returns historical simulations with F = 0.

  • progress Logical. If TRUE, updates progress bar through shiny::incProgress. Used in conjunction with Shiny apps.

  • maxiterF Integer, the number of iterations to solve for F in the projections from the specified TAC. Default is 300.

  • tolF Numeric, the tolerance for the catch relative to the TAC when solving for F in the projections. Default is 1e-4.

  • HZN Integer, the number of generations to solve for B_low. Default is 2. See getBlow().

  • Bfrac Numeric, proportion of SBMSY to solve for B_low. Default is 0.5. See getBlow().

  • skipdata Logical. If TRUE, skips conditioning on data in MOM@cpars[[p]][[f]]$Data. Only used in multiMSE().

  • HermEq Logical, whether the equilibrium population age structures in the multi-OM is generated from the hermaphroditism vector (intended for use in salmonMSE). Default is TRUE. Only used in multiMSE().

  • HistRel Logical, whether to perform the historical reconstruction with inter-stock relationships in MOM@Rel. Default is TRUE. Only used in multiMSE().

Examples

## Not run: 
validcpars() # all valid cpars

validcpars("Obs", FALSE) # invalid Obs cpars

## End(Not run)

Return Valid Units

Description

Returns the valid units for Ages(), Length(), and Weight() objects.

Usage

ValidUnits(x = "ages")

Arguments

x

An ages, length, or weight object, or a character string specifying the class: one of "ages", "length", or "weight" (case-insensitive). If NULL, returns a named list of valid units for all three classes. Default "ages".

Value

  • If x is NULL: a named list with elements Age, Length, and Weight, each containing a character vector of valid unit strings.

  • If x is an ages object or "ages": a character vector of valid age units: "year", "half-year", "quarter", "month", "week".

  • If x is a length object or "length": a character vector of valid length units: "mm", "cm", "inch".

  • If x is a weight object or "weight": a character vector of valid weight units: "g", "kg", "lb".

  • If no match is found: the string "No units found".

See Also

Ages(), Length(), Weight()

Examples

ValidUnits()           # age units (default)
ValidUnits("length")   # length units
ValidUnits("weight")   # weight units
ValidUnits(NULL)       # all units as a named list
ValidUnits(Ages())     # age units from an ages-class object

Calculate Value Of Information

Description

A function that relates operating model parameters and parameters of the observation model to yield (by default). A user can also specific their own utility values (Ut) which is arranged in a matrix of nsim rows and nMP columns.

Usage

VOI(
  MSEobj,
  ncomp = 6,
  nbins = 8,
  maxrow = 8,
  Ut = NA,
  Utnam = "Utility",
  plot = TRUE
)

Arguments

MSEobj

An object of class MSE

ncomp

Maximum number of variables to examine per MP

nbins

Number of percentile bins for sampled parameters of the operating model or observation model, which is used for calculating variability in utility across the sampled range of each parameter

maxrow

maximum number of MPs per plot

Ut

A matrix of user-specified utility values of nsim rows and nMPs columns

Utnam

The name of the utility measure for plotting

plot

Logical. Show the plot?

Author(s)

T. Carruthers


Calculate Value Of Information 2

Description

A function that relates operating model parameters and parameters of the observation model to relative yield (yield over last 5 years of projection relative to a 'best F' scenario that maximizes yield).

Usage

VOI2(MSEobj, ncomp = 6, nbins = 4, Ut = NA, Utnam = "yield", lay = F)

Arguments

MSEobj

An object of class MSE

ncomp

Maximum number of observation variables to examine per MP

nbins

Number of bins for sampled observation variables used for calculating variability in utility across the sampled range of each parameter

Ut

A matrix of user-specified utility values of nsim rows and nMPs columns

Utnam

The name of the utility measure for plotting

lay

Controls whether labels are in lay terms or not

Note

VOI2 assumes that relative cost for each type of improvement in data is linearly related to the number of samples (e.g. nCAAobs) or square function of improved precision and bias e.g.: relative cost= 1/(newCV/oldCV)^2

Author(s)

T. Carruthers


Yet another Value of Information Plot

Description

A function that relates parameters of the observation model and the operating model parameters to yield.

Usage

VOIplot(
  MSEobj,
  MPs = NA,
  nvars = 5,
  nMP = 4,
  Par = c("Obs", "OM"),
  YVar = c("Y", "B"),
  doPlot = TRUE,
  incStat = FALSE,
  availMP = NULL,
  acceptMP = NULL,
  incNames = TRUE,
  labcex = 0.8,
  quants = c(0.05, 0.95)
)

Arguments

MSEobj

An object of class MSE

MPs

The MPs to plot. If NA it will plot the first nMP from MSEobj

nvars

The number of observation or operating model parameters to plot (number of columns)

nMP

The maximum number of MPs to plot (number of rows)

Par

Plot Operating Model (OM) or Observation (Obs) parameters?

YVar

Variable for Y-Axis: Yield (Y) or Biomass (B) (relative to BMSY)

doPlot

Output the plot?

incStat

Include a print out of statistic describing the curviness of the line?

availMP

Optional character string of MPs that are available. These names are colored black

acceptMP

Optional character string of MPs that are acceptable. These names are colored green if they are also in availMP

incNames

Include the names?

labcex

Character size of the label

quants

Quantiles to calculate

Value

A list of all the information included in the plot

Author(s)

A. Hordyk


Weight Constructor and Accessors

Description

Construct a weight object defining the weight-at-age and weight-at-length schedules for a stock, or access and replace the Weight slot of a stock and its individual slots. A Weight object is required for all stock objects.

Usage

Weight(
  Pars = list(),
  Model = NULL,
  Units = "g",
  MeanAtAge = NULL,
  MeanAtLength = NULL,
  CVatAge = NULL,
  Dist = "lognormal",
  TruncSD = 2,
  Timing = 0,
  Random = NULL,
  AWK = NULL,
  Classes = NULL,
  Misc = list()
)

AWK(x)

AWK(x) <- value

Weight(x) <- value

Arguments

Pars

list. Named list of allometric parameters. Element names must match the arguments of a built-in weight model (see WeightModels()). When Pars is non-empty and Model is NULL, the model is inferred automatically by FindModel(). When Pars is a stock object, Weight() acts as a pass-through accessor and returns x@Weight. See Specifying Weight-at-Age and Specifying Biological and Fleet Schedules for the full set of accepted input formats. Default list().

Model

character(1) or function. Weight model identifier. When NULL (default), the model is inferred from Pars via FindModel(). May be set to a character string naming a built-in model or to a custom R function — see Specifying Biological and Fleet Schedules.

Units

character(1). Physical unit of weight measurements. Must be one of the strings returned by ValidUnits() (e.g., "g", "kg"). Default "g".

MeanAtAge

array or NULL. Mean weight at age with named dimensions ⁠Sim × Age × Year⁠. Supply directly when bypassing the model-based approach (Pars = list()). Only the years at which values change need to be included; Extend() fills the remainder. When Pars contains a matched model, any values here are overwritten during Populate(). A numeric vector of length nAge is also accepted and is promoted to a ⁠1 × nAge × 1⁠ array automatically. Default NULL.

MeanAtLength

array or NULL. Mean weight at length with named dimensions ⁠Sim × Length × Year⁠. Populated automatically during Populate() when an at-length weight model is used (see At-Length Models); may also be supplied directly. When MeanAtLength is populated and MeanAtAge is not, Populate() converts it to MeanAtAge via the age-length key (ALK) from a length object. Default NULL.

CVatAge

numeric(1), length-2 bounds vector, array, or NULL. Coefficient of variation of weight-at-age, used to parameterise the within-age-class weight distribution and to build the age-weight key (AWK). A length-2 vector is treated as Uniform(lower, upper) bounds sampled once per simulation. When NULL (default), no AWK is constructed; for most models weight variability is propagated through the ALK and a length-weight relationship rather than through CVatAge directly.

Dist

character(1). Parametric distribution for weight-at-age variability. Options are "lognormal" (default) and "normal".

TruncSD

numeric(1). Number of standard deviations at which the weight distribution is truncated. Default 2.

Timing

numeric(1). Fractional position within the time step at which weight is measured: 0 = start of step, 1 = end of step. Default 0.

Random

array or NULL. Simulation- and year-specific random multipliers applied to weight parameters. Currently stored but not applied. Default NULL.

AWK

array or NULL. Age-weight key giving the probability that an individual of a given age belongs to each weight class (⁠Sim × Age × Class × Year⁠). Only populated during Populate() when CVatAge is non-NULL; supply directly only when overriding the computed key. Default NULL.

Classes

numeric or NULL. Weight class midpoints in units of Units. Populated automatically during Populate() when CVatAge is non-NULL and Classes is NULL. Default NULL.

Misc

list. Used internally. Default list().

x

A weight object for slot accessors, or a stock object for ⁠Weight<-⁠.

value

For ⁠Weight<-⁠: a weight object. For ⁠AWK<-⁠: a replacement age-weight key array.

Details

Specifying Weight-at-Age

There are two ways to define the weight schedule:

Model-based (recommended): supply Pars with named parameters matching a built-in model (see WeightModels()). If Model = NULL and the parameter names uniquely match a model, FindModel() resolves the model automatically. MeanAtAge is then populated by Populate() when the stock is added to an OM():

# Power-law length-weight — model inferred from Pars names
wt <- Weight(Pars = list(a = 0.01, b = 3.0))

# Stochastic a across simulations
wt <- Weight(Pars = list(a = c(0.008, 0.012), b = 3.0))

# Time-varying a (increases in 2010; Extend() fills the rest)
a_arr <- array(c(0.01, 0.012), dim = c(1, 2),
               dimnames = list(Sim = 1, Year = c(1990, 2010)))
wt <- Weight(Pars = list(a = a_arr, b = 3.0))

# Inter-annual random walk on a (log-normal, SD = 0.1)
wt <- Weight(Pars = list(a = 0.01, aSD = 0.1, b = 3.0))

Direct array: supply MeanAtAge (or MeanAtLength) with Pars = list(). Values are preserved during Populate():

ages  <- 0:20
wt_aa <- Weight(MeanAtAge = 0.01 * (100 * (1 - exp(-0.2 * ages)))^3)

See Specifying Biological and Fleet Schedules for full details on input formats and the rules that govern how Pars, Model, and ⁠MeanAt*⁠ arrays interact.

At-Length Weight Models

Some built-in weight models (those whose class contains "at-Length") take a length object as input and produce MeanAtLength rather than MeanAtAge directly. In this case a populated Length() object must be passed to Populate(). The resulting MeanAtLength is then converted to MeanAtAge automatically via the age-length key (ALK). The same conversion applies when MeanAtLength is supplied directly by the user.

The Age-Weight Key

The AWK is only constructed when CVatAge is non-NULL. For most operating models weight variability is captured through the ALK and a length-weight relationship, so CVatAge is typically left at its default of NULL.

Pass-Through Access from a Stock

When Pars is a stock object, Weight() returns the Weight slot directly:

Weight(my_stock)           # returns my_stock@Weight
Weight(my_stock) <- my_wt  # replaces my_stock@Weight

Slot Accessors

Individual slots can be read or replaced using generic functions matching their names. All replacement functions re-validate the object:

Pars(wt)          <- list(a = 0.01, b = 3.0)
Model(wt)         <- "LengthWeight"
Units(wt)         <- "kg"
MeanAtAge(wt)     <- my_array
MeanAtLength(wt)  <- my_length_array
CVatAge(wt)       <- 0.1
Dist(wt)          <- "lognormal"
TruncSD(wt)       <- 3
Timing(wt)        <- 0
AWK(wt)           <- my_awk
Classes(wt)       <- seq(0, 5, by = 0.5)

Value

  • Weight() returns a weight object. If Pars is a stock, returns x@Weight.

  • ⁠Weight<-⁠ returns the stock x with the Weight slot replaced and the object re-validated.

  • AWK() returns the age-weight key array from x.

  • ⁠AWK<-⁠ returns x with the AWK slot updated and the object re-validated.

See Also

  • weight for the class definition and slot-level documentation.

  • WeightModels() for available weight models and required parameter sets.

  • ValidUnits() for accepted unit strings.

  • FindModel() for automatic model inference.

  • Populate() for array population.

  • Stock() for the enclosing stock constructor.

  • Length() for the companion length schedule, required when using at-length weight models.

Other weight: weight-class

Examples

# See WeightModels() for all available built-in weight models and the
# parameter names required for each.
WeightModels()

# ---- Model-based specification ----

## Constant parameters (scalar) — same value for every simulation and year
wt <- Weight(Pars = list(a = 0.01, b = 3.0))

## Stochastic across simulations — a drawn from Uniform(lower, upper)
## once per simulation; b fixed in all simulations
wt <- Weight(Pars = list(a = c(0.008, 0.012), b = 3.0))

## Inter-annual random walk on a — log-normal with 10% CV
## aSD is removed from Pars after use
wt <- Weight(Pars = list(a    = c(0.008, 0.012),
                         aSD  = 0.1,
                         b    = 3.0))

## Time-varying parameters with named change-point arrays
## Only the years where values change need to be supplied; Extend() fills
## all intermediate and future years by forward-filling automatically.
nSim <- 48

## a increases in 2010 (two change points: 1990 and 2010)
a_arr <- array(
  c(rep(0.01, nSim), rep(0.012, nSim)),
  dim      = c(nSim, 2),
  dimnames = list(Sim = seq_len(nSim), Year = c(1990, 2010))
)
wt <- Weight(Pars = list(a = a_arr, b = 3.0))

## Combine stochastic (across sims) and time-varying (across years):
## a is drawn per simulation AND increases in 2010
a_sim  <- runif(nSim, 0.008, 0.012)
a_arr2 <- array(
  c(a_sim, a_sim * 1.2),              # 20% increase from 2010 onward
  dim      = c(nSim, 2),
  dimnames = list(Sim = seq_len(nSim), Year = c(1990, 2010))
)
wt <- Weight(Pars = list(a = a_arr2, b = 3.0))

# ---- Direct array specification ----

## Supply MeanAtAge directly (Pars left empty).
## A plain numeric vector of length nAge is accepted; it is treated as a
## single simulation, single year and replicated by Extend() as needed.
ages  <- 0:20
Linf  <- 100; K <- 0.2; t0 <- -0.1; a <- 0.01; b <- 3
wt_aa <- Weight(MeanAtAge = a * (Linf * (1 - exp(-K * (ages - t0))))^b)

## Named Sim x Age x Year array — two change-point years, single simulation.
## Extend() replicates Sim = 1 to all nSim simulations automatically.
maa <- array(
  c(a * (Linf       * (1 - exp(-K * (ages - t0))))^b,   # 1990 schedule
    a * (Linf * 1.1 * (1 - exp(-K * (ages - t0))))^b),  # 2010 (Linf up 10%)
  dim      = c(1, length(ages), 2),
  dimnames = list(Sim = 1, Age = ages, Year = c(1990, 2010))
)
wt_arr <- Weight(MeanAtAge = maa)

## Supply MeanAtLength directly — converted to MeanAtAge via the ALK
## during Populate() when a Length object is provided.
lens      <- seq(5, 120, by = 5)
wt_al <- Weight(
  MeanAtLength = array(
    a * lens^b,
    dim      = c(1, length(lens), 1),
    dimnames = list(Sim = 1, Length = lens, Year = 1990)
  )
)

# ---- Slot accessors ----

wt <- Weight(Pars = list(a = 0.01, b = 3.0))

## Read slots
MeanAtAge(wt)     # NULL until Populate() is called
MeanAtLength(wt)  # NULL until Populate() is called (at-length models only)
CVatAge(wt)       # NULL by default; AWK is only built when non-NULL
Units(wt)

## Replace slots
Units(wt)   <- "kg"
TruncSD(wt) <- 3

# ---- Attaching to a Stock ----

stk <- Stock(Name = "Example stock", Ages = Ages(MaxAge = 20))
Weight(stk) <- Weight(Pars = list(a = 0.01, b = 3.0))
Weight(stk)

# ---- Populate ----

## The final populated object (typically done internally).
## An at-length model requires a populated Length object.
pop_wt <- Populate(Weight(stk), Ages = Ages(MaxAge = 20))
pop_wt

The weight S4 Class

Description

Defines the weight-at-age and weight-at-length schedules for a stock object. Objects are typically created via Weight(), which documents all parameters, validates inputs, and infers the model automatically when possible.

Details

Direct construction via methods::new() is not recommended; use Weight() instead, which handles model inference and object validation.

The AWK slot is only populated during Populate() when CVatAge is non-NULL. For most applications weight variability is propagated through the age-length key (ALK, see Length()) and a length-weight relationship rather than directly through an age-weight distribution.

Slots

Pars

list. Named list of parameters whose names correspond to those expected by Model. See WeightModels() for parameter sets and Specifying Biological and Fleet Schedules for accepted input formats.

Model

function or character(1). Weight model identifier, matched to one of WeightModels(). Set automatically by FindModel() when Pars is supplied without an explicit model.

Units

character(1). Physical unit of the weight measurements (e.g., "g", "kg"). Must be accepted by ValidUnits().

MeanAtAge

array. Mean weight at age with named dimensions Sim, Age, and Year. Populated automatically by Populate() when Pars and Model are set; may also be supplied directly when Pars is empty. When Pars contains a matched model, any existing values are overwritten. See Specifying Biological and Fleet Schedules.

MeanAtLength

array. Mean weight at length with named dimensions Sim, Length, and Year. Populated automatically when an at-length weight model is used, or may be supplied directly. Converted to MeanAtAge via the ALK during Populate() when MeanAtAge is not already populated. See Specifying Biological and Fleet Schedules.

CVatAge

array or numeric. Coefficient of variation of weight-at-age, used to generate the within-age-class weight distribution and to build the age-weight key (AWK). NULL by default; the AWK is only constructed when this slot is populated.

Dist

character(1). Parametric distribution used for weight-at-age variability (e.g., "lognormal").

TruncSD

array or numeric. Number of standard deviations at which the weight distribution is truncated.

Timing

array or numeric. Fractional position within the time step at which weight is measured (0 = start, 1 = end).

Random

array. Random effects on weight parameters across simulations or years.

AWK

array. Age-weight key: the probability of belonging to each weight class given age, derived from MeanAtAge, CVatAge, Dist, and TruncSD. Only populated when CVatAge is non-NULL; use AWK() to retrieve.

Classes

numeric. Weight class midpoints in units of Units.

Misc

list. Used internally.

See Also

Other weight: Weight()


Weight-at-Age and Weight-at-Length Models

Description

Allometric weight models used to compute weight at age or at length.

Usage

WeightatAge(Ages, a, b)

WeightatLength(Length, Alpha, Beta)

WeightatMeanLength(Length, alpha, beta)

WeightModels(full = TRUE, print = TRUE)

Arguments

Ages

numeric vector of age classes (for Weight-at-Age)

a

scaling parameter for Weight-at-Age in units of Weight().

b

exponent for Weight-at-Age. Typically around 3.

Length

numeric vector of length classes for WeightatLength or a mean length-at-age schedule for WeightatMeanLength

Alpha

scaling parameter for Weight-at-Length in units of Weight().

Beta

exponent for Weight-at-Length. Typically around 3.

alpha

scaling parameter for Weight-at-Mean-Length in units of Weight().

beta

exponent for Weight-at-Mean-Length. Typically around 3.

full

logical; provide a complete table of models (TRUE) or just model names (FALSE)

print

logical; print results (TRUE) or return data frame invisibly (FALSE)

WeightModels() prints the list of available weight models.

Details

Models are identified internally by matching the names in Pars. WeightatMeanLength returns weight-at-age corresponding to the mean length at each age, while WeightatLength returns weight-at-length for the supplied length classes.

  • Weight-at-Age:

    W(a)=aAgebW(a) = a \cdot Age^b

  • Weight-at-Length:

    W(L)=αLβW(L) = \alpha \cdot L^\beta

  • Weight-at-Mean-Length:

    W(Lmean)=αmeanLmeanβmeanW(L_{mean}) = \alpha_{mean} \cdot L_{mean}^{\beta_{mean}}

    , returning weight-at-age

at-length schedules (except from WeightatMeanLength) are converted internally to at-age using the age-length key respectively.

Value

Each function returns a numeric vector of expected weights for each age or length. WeightModels() invisibly returns a data frame describing available models.

See Also

Ages(), Length(), Stock(), Weight()

Examples

Ages <- 0:10
MeanLength <- vonBert(Ages, 100, 0.2)
Length <- seq(10, 100, 10)

W_age <- WeightatAge(Ages, a = 59.56, b = 2)
W_mean <- WeightatMeanLength(MeanLength, alpha = 0.01, beta = 3)
W_length <- WeightatLength(Length, Alpha = 0.0001, Beta = 3)

df <- data.frame(
  Age = Ages,
  W_age = W_age,
  W_mean = W_mean
)

# Plot Weight-at-Age and Weight-at-Mean-Length
matplot(df$Age, df[,-1], type = "l", lty = 1, lwd = 2,
        col = c("blue", "purple"), xlab = "Age (years)", ylab = "Weight",
        main = "Weight-at-Age Models")
legend("topleft", legend = colnames(df)[-1], col = c("blue", "purple"), lty = 1, lwd = 2)

# Plot Weight-at-Length
plot(Length, W_length, type = "l", lwd = 2, col = "red",
     xlab = "Length", ylab = "Weight", main = "Weight-at-Length Model")

Takes a fitted SAM model and samples historical population and fishing dynamics from the MLE fit and variance-covariance matrix.

Description

Takes a fitted SAM model and samples historical population and fishing dynamics from the MLE fit and variance-covariance matrix. Maturity-at-age-year, Mortality-at-age-year and weight-at-age-year are identical among simulations and are a direct copy of the matrices in the WHAM fitting object.

Usage

WHAM2OM(
  obj,
  nsim = 3,
  proyears = 30,
  interval = 2,
  Name = NULL,
  WLa = 1,
  WLb = 3,
  WAAind = 1,
  Obs = MSEtool::Imprecise_Unbiased,
  Imp = MSEtool::Perfect_Imp,
  nyr_par_mu = 3,
  LowerTri = 2,
  plusgroup = T,
  altinit = 0,
  fixq1 = T,
  report = FALSE,
  silent = FALSE,
  ...
)

Arguments

obj

a SAM output object

nsim

Positive integer. The number of simulations.

proyears

Positive integer. The number of projection years for MSE.

interval

Positive integer. The interval at which management procedures will update the management advice in runMSE, e.g., 1 = annual updates.

Name

Character string. The name of the operating model.

WLa

positive real number or array ⁠[sim, ages, year]⁠. The default weight-length parameter a (W=aL^b)

WLb

positive real number or array ⁠[sim, ages, year]⁠. The default weight-length parameter b (W=aL^b)

WAAind

positive integer. The index of the WHAM weight-at-age array input$data$waa to be assumed as the weight-at-age for the operating model

Obs

The observation model (class Obs). This function only updates the catch and index observation error.

Imp

The implementation model (class Imp). This function does not update implementation parameters.

nyr_par_mu

Positive integer. The number of recent years that natural mortality, age vulnerability, weight, length and maturity parameters are averaged over for defining future projection conditions.

LowerTri

Integer. The number of recent years for which model estimates of recruitment are ignored (not reliably estimated by the assessment)

plusgroup

Logical. Does the assessment assume that the oldest age class is a plusgroup?

altinit

Integer. Various assumptions for how to set up the initial numbers. 0: standard, 1: no plus group, 2: temporary fix for MSEtool plus group initialization

fixq1

Logical. Should q be fixed (ie assume the F-at-age array faa is accurate?

report

Logical, if TRUE, a diagnostic will be reported showing the matching of the OM reconstructed numbers at age vs the assessment.

silent

Whether to silence messages to the console.

...

Additional arguments, including R0 (unfished recruitment), phi0 (unfished spawners per recruit associated with R0 and h for calculating stock recruit parameters),

Details

Use a seed for the random number generator to sample future recruitment.

Value

An object of class OM.

Author(s)

T. Carruthers

See Also

Assess2OM


Biomass wormplot

Description

A worm plot for plotting the likelihood of meeting biomass targets in future years.

Usage

wormplot(MSEobj, Bref = 0.5, LB = 0.25, UB = 0.75)

Arguments

MSEobj

Object of class MSE, output of the runMSE function

Bref

The reference fraction of BMSY (to evaluate the probability of exceeding this level)

LB

The lower bound probability that separates red (bad) and yellow (O.K.) colored segments

UB

The upper bound probability that separates yellow (O.K.) and green (good) colored segments

Details

Returns a matrix of nMPs rows and proyears columns which is the fraction of simulations for which biomass was above Bref.

Author(s)

T. Carruthers


Wrapped Normal Distribution

Description

Evaluates a wrapped normal distribution over a circular seasonal domain, suitable for specifying seasonal recruitment patterns in models with Seasons > 1.

Usage

WrappedNormal(n_seasons, mu, sigma, n_wraps = 5)

Arguments

n_seasons

Integer. Number of seasons per year (e.g. 12 for monthly, 4 for quarterly).

mu

Numeric. Peak season (need not be an integer; e.g. 3.5 for a peak between seasons 3 and 4).

sigma

Numeric. Standard deviation in units of seasons. Smaller values concentrate recruitment around the peak; larger values spread it across the year.

n_wraps

Integer. Number of periods summed on each side to approximate wrapping. Default 5 is sufficient for any reasonable sigma.

Value

A numeric vector of unnormalised density values of length n_seasons. Normalise with ⁠/ sum(...)⁠ to obtain season proportions.

Examples

# Monthly model: peak recruitment March/April, moderate spread
pi_raw <- WrappedNormal(n_seasons = 12, mu = 3.5, sigma = 1.5)
pi_m   <- pi_raw / sum(pi_raw)
names(pi_m) <- month.abb

# Narrow spread — recruitment concentrated in 1-2 seasons
pi_raw <- WrappedNormal(n_seasons = 12, mu = 3.5, sigma = 0.5)

# Wide spread — recruitment across most of the year
pi_raw <- WrappedNormal(n_seasons = 12, mu = 3.5, sigma = 3)

# Quarterly model: peak in Q1
pi_raw <- WrappedNormal(n_seasons = 4, mu = 1.5, sigma = 0.8)

Internal function to write CSVs for objects

Description

Used internally in the DLMtool package to write CSV files from an existing DLMtool object

Usage

writeCSV(
  inobj,
  tmpfile = NULL,
  objtype = c("Stock", "Fleet", "Obs", "Imp", "Data", "OM")
)

Arguments

inobj

A object of class Stock, Fleet, Obs, Imp, Data, or OM

tmpfile

The full file path and name for the saved CSV file

objtype

The class corresonding to the inobj

Author(s)

A. Hordyk


Import a Data object from Excel file

Description

Import a Data object from Excel file

Usage

XL2Data(name, dec = c(".", ","), sheet = 1, silent = FALSE)

Arguments

name

Name of the data file, with or without file extension. Include full file path if not in working directory

dec

the character used in the file for decimal points.

sheet

Sheet number if importing Data from XL file

silent

Logical. Hide messages?

Value

An object of class 'Data'

Author(s)

A. Hordyk

Examples

## Not run: 
MyData <- XL2Data("MyData.xlsx")

## End(Not run)

Import Fleet Object from Excel file

Description

Imports a Fleet Object from a correctly formatted Excel file.

Usage

XL2Fleet(name = NULL, cpars = NULL, msg = TRUE)

Arguments

name

Name of the OM Excel file. Provide full file path if not in current directory.

cpars

An optional list of custom parameters (single parameters are a vector nsim long, time series are a matrix nsim rows by nyears columns)

msg

Should messages be printed?

Details

An error message will alert if any slots are missing values, or if the Excel file is missing the required tabs.

Value

An object of class Fleet

Author(s)

A. Hordyk


Load OM from Excel file

Description

Imports an OM from a correctly formatted Excel file. Create the Excel spreadsheet template using OMinit and document each slot in the corresponding text file.

Usage

XL2OM(name = NULL, cpars = NULL, msg = TRUE)

Arguments

name

Name of the OM Excel file. Provide full file path if not in current directory.

cpars

An optional list of custom parameters (single parameters are a vector nsim long, time series are a matrix nsim rows by nyears columns)

msg

Should messages be printed?

Details

An error message will alert if any slots are missing values, or if the Excel file is missing the required tabs.

Value

An object of class OM

Author(s)

A. Hordyk

Examples

## Not run: 
OMinit('myOM', templates=list(Stock='Herring', Fleet='Generic_Fleet', Obs='Generic_Obs',
Imp='Perfect_Imp'), overwrite=TRUE)
myOM <- XL2OM('myOM.xlsx')


## End(Not run)

Import Stock Object from Excel file

Description

Imports a Stock Object from a correctly formatted Excel file.

Usage

XL2Stock(name = NULL, cpars = NULL, msg = TRUE)

Arguments

name

Name of the OM Excel file. Provide full file path if not in current directory.

cpars

An optional list of custom parameters (single parameters are a vector nsim long, time series are a matrix nsim rows by nyears columns)

msg

Should messages be printed?

Details

An error message will alert if any slots are missing values, or if the Excel file is missing the required tabs.

Value

An object of class Stock

Author(s)

A. Hordyk


Calculate or Extract Time Step Values

Description

Two related functions for working with historical and projection time steps:

Usage

CalcYears(nYear, pYear, CurrentYear, Seasons = 1, Period = NULL)

Years(x, Period = NULL)

Arguments

nYear

Integer. Number of historical time steps.

pYear

Integer. Number of projection time steps.

CurrentYear

Integer. Final historical year (or index if CurrentYear < 1900).

Seasons

Integer. Number of seasons per year. Default 1 (annual).

Period

Character or NULL. Controls which time steps are returned. See Details.

x

An om, hist, or mse object, or a list of such objects. (Years() only.)

Details

  • CalcYears() generates a numeric vector of time step values from explicit parameters.

  • Years() extracts time step values from an om, hist, or mse object, or a list of such objects, by delegating to CalcYears().

The historical period spans nYear time steps ending at CurrentYear. The projection period spans pYear time steps beginning after CurrentYear. If pYear = 0 or Period = "H", only historical values are returned.

For sub-annual seasons (Seasons > 1), time steps are expressed as decimal dates (e.g. 2020.5 for mid-2020) using lubridate::decimal_date(). Supported resolutions are half-year, quarter, month, week, and day, as determined by CalcTSUnits().

When CurrentYear < 1900, a non-calendar index is used and years are counted backwards from CurrentYear rather than mapped to real calendar years.

Period accepts partial matches to "Historical" or "Projection" (e.g. "H", "Hist", "Proj"). Matching is case-insensitive. NULL (default) returns all time steps.

Value

A numeric vector of time step values, or for Years() applied to a list, a list of such vectors.

See Also

CalcTSUnits(), om

Examples

# Annual time steps
CalcYears(nYear=20, pYear=10, CurrentYear=2026)

# Semi-annual time steps
CalcYears(nYear=20, pYear=10, CurrentYear=2026, Seasons=2)

# Historical period only
CalcYears(nYear=20, pYear=10, CurrentYear=2026, Period="H")