| 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 |
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.
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) <- valueAC(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
x |
An S4 object with the corresponding slot. |
value |
The value to assign to the slot |
st |
Integer. Stock index used when |
Accessor functions return the value stored in the named slot of x.
Replacement functions return x with the named slot updated to value.
MyLength <- Length() MeanAtAge(MyLength)MyLength <- Length() MeanAtAge(MyLength)
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.
AddAutoCorrelation(values, ac, last_value)AddAutoCorrelation(values, ac, last_value)
values |
|
ac |
|
last_value |
The AR(1) recursion applied is:
where |
A numeric vector of the same length as values with AR(1)
auto-correlation applied.
Adds a new fleet to an om object, appending a fleet, an obs, and an imp object for every stock in the OM.
AddFleet(OM, FleetName, Fleet = NULL, Obs = NULL, Imp = NULL)AddFleet(OM, FleetName, Fleet = NULL, Obs = NULL, Imp = NULL)
OM |
An object of class |
FleetName |
A length-1 character string giving the name of the new
fleet. Must not already exist in |
Fleet |
Optional. An object of class |
Obs |
Optional. An obs object. If |
Imp |
Optional. An imp object. If |
The om object with the new fleet appended to OM@Fleet and
OM@Obs for every stock.
OM <- SingleStockOM FleetNames(OM) OM2 <- AddFleet(OM, 'DummyFleet') FleetNames(OM2)OM <- SingleStockOM FleetNames(OM) OM2 <- AddFleet(OM, 'DummyFleet') FleetNames(OM2)
addMMPs() adds additional management procedures to a MMSE object by combining
multiple MMSE objects that have identical historical OM values, and population/ fleet structures.
addMMPs(MMSEobjs)addMMPs(MMSEobjs)
MMSEobjs |
A list |
An object of class MMSE
Q. Huynh
Construct an advice object defining management advice returned by a management procedure.
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() )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() )
TAC |
Numeric vector or matrix specifying total allowable catch.
See |
TACType |
Character. Does the TAC refer to |
TACUnit |
Character. Units in which the TAC is expressed: |
Effort |
Numeric vector or matrix specifying relative or absolute
fishing effort. See |
EffType |
Character. Effort interpretation: |
Closure |
Numeric vector or array specifying spatial closures. See |
Selectivity |
A |
Retention |
A |
DiscardMortality |
A |
ApicalF |
Numeric array specifying target apical fishing mortality. Not currently used |
BagLimit |
Numeric vector or
The bag limit regulation persists across time steps until a new
|
SpeciesLimit |
Numeric matrix or
|
LimitType |
Character or
|
ClosureMode |
Character or
|
Misc |
Miscellaneous list. Will be passed to |
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.
There are several options for populating the slots in an Advice object:
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.
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.
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.
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.
Same as described for Selectivity, but for Retention() objects.
Same as described for Selectivity, but for DiscardMortality() objects.
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.
Not currently used.
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.
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.
An advice object.
advice for the class definition and slot-level documentation.
Selectivity(), Retention(), DiscardMortality() for gear regulation
sub-objects.
TripsScalar(), AnglerPerTrip() for the effort-to-trips and
angler-scaling parameters consumed by the bag limit model.
Theta() for the within-trip catch overdispersion parameter.
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" )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" )
advice S4 ClassThe 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.
TACNumeric vector length 1 or numeric length nFleet specifying
total allowable catch in units of TACUnit.
TACTypeCharacter. Does the TAC refer to "Removals" (default) or
"Landings". Either length 1 (applied to all fleets) or a character
vector of length nFleet.
TACUnitCharacter. Units of the TAC: "Biomass" (default) or
"Number". Either length 1 (applied to all fleets) or a character
vector of length nFleet.
EffortNumeric 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.
EffTypeCharacter. 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".
ClosureNumeric vector length nArea or array with dimensions nFleet
x nArea specifyin an area open (1; default) or closed (0) to fishing.
SelectivityA Selectivity() object or an nFleet long list
of Selectivity() objects defining gear selectivity prescribed by the MP
RetentionA Retention() object or an nFleet long list
of Retention() objects defining retention prescribed by the MP
DiscardMortalityA DiscardMortality() object or an nFleet long
list of DiscardMortality() objects defining discard mortality set in the MP
ApicalFNumeric array specifying target apical fishing mortality. Not currently used
BagLimitNumeric 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().
SpeciesLimitNumeric matrix or NULL. Species-specific bag limits
(fish per angler or vessel per trip) within a complex, with dimensions
nFleet x nStock. See Advice().
LimitTypeCharacter 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().
ClosureModeCharacter 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().
MiscMiscellaneous list. Will be passed to Data@Misc in following time steps.
LogList used internally to store diagnostics
Advice(), Selectivity(), Retention(), DiscardMortality()
advicedata S4 ClassStores 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.
AdviceData()AdviceData()
AdviceData() returns a advicedata object.
TACA numeric vector, array, or list of Total Allowable Catch (TAC) values. When a vector, elements correspond to successive advice years.
EffortA numeric vector, array, or list of advised fishing effort
values. Structured analogously to TAC.
MiscA named list for any additional advice-level metadata (e.g., harvest control rule outputs, reference point comparisons).
AdviceData() creates a new advicedata object.
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.
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) <- valueAges(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
MaxAge |
|
MinAge |
|
Units |
|
PlusGroup |
|
x |
An ages object for slot accessors ( |
value |
For |
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).
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.
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.
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`
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
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.
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
# 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)# 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)
ages S4 ClassDefines the discrete age structure of a stock object. Objects are
typically created via Ages(), which documents all parameters and validates
inputs.
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.
MaxAgenumeric(1). Maximum age in units of Units. When
PlusGroup = TRUE, fish older than this age are pooled into the plus
group.
MinAgenumeric(1). Minimum (youngest) age class in units of
Units. Must be non-negative and less than or equal to MaxAge.
Unitscharacter(1). Time unit for MinAge and MaxAge. Must be
one of the values returned by ValidUnits() (e.g., "year").
PlusGrouplogical(1). If TRUE, MaxAge is treated as an
open-ended plus group that accumulates all fish at or beyond that age.
Classesnumeric. 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.
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()
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.
AgeStructuredObsAgeStructuredObs
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.
obs, Obs(), CatchObs(), IndicesObs(), CompObs(),
CatchAndSurveyObs, CommercialFleetObs, LengthStructuredObs,
DataRichObs
Other obs-examples:
CatchAndSurveyObs,
CommercialFleetObs,
DataRichObs,
LengthStructuredObs
AgeStructuredObs LandingsAtAge(AgeStructuredObs) DiscardsAtAge(AgeStructuredObs)AgeStructuredObs LandingsAtAge(AgeStructuredObs) DiscardsAtAge(AgeStructuredObs)
Example objects of class Stock
Albacore Blue_shark Bluefin_tuna Bluefin_tuna_WAtl Butterfish Herring Mackerel Porgy Rockfish Snapper Sole ToothfishAlbacore Blue_shark Bluefin_tuna Bluefin_tuna_WAtl Butterfish Herring Mackerel Porgy Rockfish Snapper Sole Toothfish
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.
avail("Stock")avail("Stock")
Example objects of class MOM
Albacore_TwoFleetAlbacore_TwoFleet
An object of class MOM of length 1.
avail("MOM")avail("MOM")
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.
AlbacoreExStockAlbacoreExStock
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.
CalcAgeClasses() generates the integer age vector Ages@Classes
(0:20), which is used as the age dimension in all subsequent arrays.
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().
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().
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().
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().
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().
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.
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().
PopulateDepletion() samples current biomass depletion relative to B0
for each simulation from the uniform prior, setting the initial conditions
of the operating model.
ButterfishExStock, Stock(), PopulateStock(), Populate(),
stock
AlbacoreExStock ## Not run: PopulatedStock <- PopulateStock( AlbacoreExStock, nYear = 50, pYear = 30, nSim = 48, seed = 42 ) ## End(Not run)AlbacoreExStock ## Not run: PopulatedStock <- PopulateStock( AlbacoreExStock, nYear = 50, pYear = 30, nSim = 48, seed = 42 ) ## End(Not run)
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.
ApplyAC(LogResid, AC, LastError)ApplyAC(LogResid, AC, LastError)
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. |
Numeric matrix of same dimensions as LogResid with autocorrelated residuals.
GenResiduals(), CalcResidualStats()
Apply multi Management Procedures (class MMP) to a hierarchical list of Data class objects
applyMMP( DataList, MP = NA, reps = 1, nsims = NA, silent = FALSE, parallel = snowfall::sfIsRunning() )applyMMP( DataList, MP = NA, reps = 1, nsims = NA, silent = FALSE, parallel = snowfall::sfIsRunning() )
DataList |
A hierarchical list of |
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 |
A hierarchical list of management recommendations (object class Rec), Fleets nested in Stocks
Apply Management Procedures to an object of class Data
applyMP( Data, MPs = NA, reps = 100, nsims = NA, silent = FALSE, parallel = snowfall::sfIsRunning() )applyMP( Data, MPs = NA, reps = 100, nsims = NA, silent = FALSE, parallel = snowfall::sfIsRunning() )
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) |
A list with the first element a list of management recommendations, and the second the updated Data object
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.
Array2DF(array) DF2Array(DF)Array2DF(array) DF2Array(DF)
array |
A |
DF |
A |
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.
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.
# 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)# 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)
Multiply, divide, subtract, or add two arrays together.
ArraySum(array1, array2) ArrayDivide(array1, array2) ArrayMultiply(array1, array2) ArraySubtract(array1, array2) ArrayExtend(array1, array2) ArrayFill(object) <- valueArraySum(array1, array2) ArrayDivide(array1, array2) ArrayMultiply(array1, array2) ArraySubtract(array1, array2) ArrayExtend(array1, array2) ArrayFill(object) <- value
array1 |
An array with named dimensions. |
array2 |
An array with the same named dimensions as |
object |
An array with named dimensions |
value |
An array with the same dimension names as |
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
The resulting array
# 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# 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
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.
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")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")
asap |
A list returned by ASAP, e.g., |
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? |
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.
An operating model OM class.
Q. Huynh
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.
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, ... )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, ... )
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 |
Imp |
Either a single implementation model to be used for all sexes and populations (class |
naa |
Numbers-at-age by sex |
faa |
Fishing mortality rate-at-age by sex and fleet |
waa |
Weight-at-age |
Mataa |
Maturity (spawning fraction)-at-age |
Maa |
Natural mortality rate-at-age |
laa |
Length-at-age |
fecaa |
Fecundity 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):
|
Use a seed for the random number generator to sample future recruitment.
An object of class MOM
Q. Huynh
Assess2OM
is identical to VPA2OM.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.
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, ... )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, ... )
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 |
faa |
Numeric array |
waa |
Numeric array |
Mataa |
Numeric array |
Maa |
Numeric array |
laa |
Numeric array |
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):
|
Use a seed for the random number generator to sample future recruitment.
An object of class OM.
T. Carruthers
SS2OM iSCAM2OM WHAM2OM ASAP2OM
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.
AsympExFleetAsympExFleet
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.
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.
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.
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.
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.
Because the Retention slot is empty, PopulateRetention() sets full
retention (1.0) across all ages, lengths, simulations, and years.
Because the DiscardMortality slot is empty, PopulateDiscardMortality()
applies default discard mortality values. All discarded fish are assumed
to survive (discard mortality = 0) unless overridden.
Because Closure is NULL, PopulateClosure() applies no spatial or
temporal closures; all areas are open to fishing in all years.
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.
DomeExFleet, AlbacoreExStock, ButterfishExStock, Fleet(),
PopulateFleet(), Populate(), fleet
AsympExFleet ## Not run: PopulatedStock <- PopulateStock(AlbacoreExStock, nYear = 50, pYear = 30, nSim = 48) PopulatedFleet <- PopulateFleet(AsympExFleet, Stock = PopulatedStock, seed = 42) ## End(Not run)AsympExFleet ## Not run: PopulatedStock <- PopulateStock(AlbacoreExStock, nYear = 50, pYear = 30, nSim = 48) PopulatedFleet <- PopulateFleet(AsympExFleet, Stock = PopulatedStock, seed = 42) ## End(Not run)
Example objects of class Data
Atlantic_mackerel China_rockfish Cobia Example_datafile Gulf_blue_tilefish ourReefFish Red_snapper Simulation_1Atlantic_mackerel China_rockfish Cobia Example_datafile Gulf_blue_tilefish ourReefFish Red_snapper Simulation_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.
An object of class Data of length 1.
avail("Data")avail("Data")
Generic class finder
avail(classy, package = NULL, msg = TRUE, abc = FALSE)avail(classy, package = NULL, msg = TRUE, abc = FALSE)
classy |
A class of object (character string, e.g. 'Fleet') |
package |
Optional. Names(s) of the package to search for object of class |
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 |
Finds objects of the specified class in the global environment or the openMSE packages.
T. Carruthers
avail("OM", msg=FALSE) Stocks <- avail("Stock") Fleets <- avail("Fleet") MPs <- avail("MP")avail("OM", msg=FALSE) Stocks <- avail("Stock") Fleets <- avail("Fleet") MPs <- avail("MP")
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).
Awatea2OM( AwateaDir, nsim = 48, proyears = 50, Name = "OM made by Awatea2OM", Source = "No source provided", Author = "No author provided", verbose = TRUE )Awatea2OM( AwateaDir, nsim = 48, proyears = 50, Name = "OM made by Awatea2OM", Source = "No source provided", Author = "No author provided", verbose = TRUE )
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? |
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.
Q. Huynh and T. Carruthers
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
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, ...)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, ...)
rdat |
A list object from the |
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 |
An object of class MOM
BAM2OM(): Create a single stock/fleet OM from a BAM object
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.
GetBAMFleetNames(Stock) FixFleetNames(FleetNames)GetBAMFleetNames(Stock) FixFleetNames(FleetNames)
Stock |
A character string matching a stock name available in
|
FleetNames |
A character vector of raw fleet name strings as extracted from BAM output. |
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.
## Not run: GetBAMFleetNames('Red Snapper') ## End(Not run) FixFleetNames(c('L.cHL', 'D.rHB', 'cPT'))## Not run: GetBAMFleetNames('Red Snapper') ## End(Not run) FixFleetNames(c('L.cHL', 'D.rHB', 'cPT'))
Biomass(), SBiomass(), and SProduction() extract total biomass,
spawning biomass, and spawning production, respectively, from a
hist or mse object.
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 )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 )
object |
|
df |
Logical. If |
byAge |
Logical. If |
byArea |
Logical. If |
Reduce |
Logical. If |
IncYear |
Logical. Passed to |
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".
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.
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)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)
Construct and manipulate a bioeconomic object storing revenue, cost, and investment dynamics for fleet-level or stock-level bioeconomic analyses.
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) <- valueBioeconomic( 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
Revenue |
Numeric array or |
Cost |
Numeric or |
Investment |
Numeric or |
Disinvestment |
Numeric or |
Depreciation |
Numeric or |
Discount |
Numeric or |
Misc |
List. Miscellaneous additional inputs. Default |
x |
A bioeconomic object, or a fleet object for
|
value |
For |
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.
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().
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.
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
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))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))
bioeconomic S4 ClassStores 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.
Note: The bioeconomic is not currently used by the MSE framework. It is included for future development.
Revenuenumeric array or NULL. Revenue by simulation, fleet, and
year. See Bioeconomic().
Costnumeric or NULL. Operating cost per unit of effort. See
Bioeconomic().
Investmentnumeric or NULL. Cost of adding a unit of effort. See
Bioeconomic().
Disinvestmentnumeric or NULL. Cost of removing a unit of effort.
See Bioeconomic().
Depreciationnumeric or NULL. Depreciation rate of effort units.
See Bioeconomic().
Discountnumeric or NULL. Discount factor applied to future
values. See Bioeconomic().
Misclist. Miscellaneous additional inputs.
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
## S3 method for class 'Data' boxplot(x, upq = 0.9, lwq = 0.1, ylim = NULL, outline = FALSE, col = NULL, ...)## S3 method for class 'Data' boxplot(x, upq = 0.9, lwq = 0.1, ylim = NULL, outline = FALSE, col = NULL, ...)
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 |
... |
Optional additional arguments passed to |
Returns a data frame containing the information shown in the plot
A. Hordyk
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.
ButterfishExStockButterfishExStock
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.
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.
CalcAgeClasses() generates the age vector Ages@Classes
(0:8), which is used as the age dimension in all subsequent arrays.
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.
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.
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.
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.
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.
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.
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.
PopulateDepletion() samples current biomass depletion relative to B0
for each simulation from the uniform prior, setting the initial conditions
of the operating model.
AlbacoreExStock, Stock(), PopulateStock(), Populate(),
stock
ButterfishExStock ## Not run: PopulatedStock <- PopulateStock( ButterfishExStock, nYear = 50, pYear = 30, nSim = 48, seed = 42 ) ## End(Not run)ButterfishExStock ## Not run: PopulatedStock <- PopulateStock( ButterfishExStock, nYear = 50, pYear = 30, nSim = 48, seed = 42 ) ## End(Not run)
Computes the numeric vector of age classes (in years) from an Ages()
object, respecting sub-annual time steps.
CalcAgeClasses(Ages)CalcAgeClasses(Ages)
Ages |
An |
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.
A numeric vector of age classes in years, or NULL if any of
Ages@Units, Ages@MinAge, or Ages@MaxAge are empty.
# 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# 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
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.
CalcAgeSizeKey( MeanAtAge, CVatAge, Classes, TruncSD = 2, Dist = c("normal", "lognormal"), silent = FALSE, type = "Length" )CalcAgeSizeKey( MeanAtAge, CVatAge, Classes, TruncSD = 2, Dist = c("normal", "lognormal"), silent = FALSE, type = "Length" )
MeanAtAge |
Numeric vector, matrix, or 3D array of mean size-at-age, or
a |
CVatAge |
Numeric vector, matrix, or 3D array of coefficient of variation (CV)
at age. Same structure as |
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 |
silent |
Logical; if |
type |
Character; currently only |
A 4D array with dimensions Sim, Age, Class, and Year.
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]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]
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.
CalcAsymDist(Movement, method = c("la", "mc"), tol = 1e-10, maxiter = 10000)CalcAsymDist(Movement, method = c("la", "mc"), tol = 1e-10, maxiter = 10000)
Movement |
A square row-stochastic matrix of dimensions |
method |
Character. Solution method for matrices larger than 2 × 2.
One of |
tol |
Numeric. Convergence tolerance. Used to check row sums, detect
reducible 2-area chains, clamp near-zero negative probabilities, and
assess convergence of the |
maxiter |
Integer. Maximum number of iterations for the |
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])
A numeric vector of length nArea giving the stationary
probability of occupying each area. Values sum to 1.
# 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")# 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")
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.
CalcEquilibrium(OM, apicalF = NULL, Years = NULL, Complex = NULL)CalcEquilibrium(OM, apicalF = NULL, Years = NULL, Complex = NULL)
OM |
An om or hist object. If a hist
object is supplied, |
apicalF |
Numeric vector of apical fishing mortality values at which
equilibrium quantities are evaluated. If |
Years |
Numeric years for which equilibrium quantities are
evaluated. Biological and fishery parameters are subset to this year.
Must match years in |
Complex |
Character vector of complex names to evaluate. If |
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).
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.
Unlike CalcPerRecruit(), this function accepts only a single Year
value. For multi-year equilibrium curves, call the function separately
for each year.
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.
CalcPerRecruit(), CalcMSY(), equilibrium
Computes the innovation covariance matrix () for a
multivariate AR(1) process given the stationary covariance matrix
() and lag-1 autocorrelation coefficients ().
CalcInnovationCov(Sigma_Z, phi)CalcInnovationCov(Sigma_Z, phi)
Sigma_Z |
Numeric covariance matrix ( |
phi |
Numeric vector of length |
The relationship used is:
where 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 to prevent
Matrix::nearPD() from inflating innovation variance beyond what is
consistent with the stationary distribution.
A numeric covariance matrix (nStock x nStock) representing the
innovation covariance (). Rows and columns
corresponding to inactive stocks (zero diagonal in Sigma_Z) are set
to zero.
GenerateStockTargeting(), FitStockTargeting()
Sigma_Z <- matrix(c(1, 0.5, 0.5, 1), 2, 2) phi <- c(0.7, 0.6) CalcInnovationCov(Sigma_Z, phi)Sigma_Z <- matrix(c(1, 0.5, 0.5, 1), 2, 2) phi <- c(0.7, 0.6) CalcInnovationCov(Sigma_Z, phi)
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.
CalcMSY(Hist, Years = NULL, type = c("Removals", "Landings"), silent = FALSE)CalcMSY(Hist, Years = NULL, type = c("Removals", "Landings"), silent = FALSE)
Hist |
A hist or om object. If an |
Years |
Integer vector of years for which reference points are
evaluated. Biological and fishery parameters are subset to these years.
If |
type |
Character. Whether MSY is defined in terms of total removals
(landings plus dead discards) or landings only. One of |
silent |
Logical. If |
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.
An a refpointsMSY object.
CalcPerRecruit(), CalcSPR0(), refpointsMSY,
Extracts biological and fishery parameters from a hist or om object and evaluates per-recruit quantities at a given apical fishing mortality.
CalcPerRecruit(OM, apicalF = 0.1, Years = NULL, Complex = NULL)CalcPerRecruit(OM, apicalF = 0.1, Years = NULL, Complex = NULL)
OM |
A om or hist object. If an |
apicalF |
Numeric vector of apical fishing mortality values at which
per-recruit quantities are evaluated. Default |
Years |
Integer vector of years for which per-recruit quantities are
evaluated. Biological and fishery parameters are subset to these years
If |
Complex |
Character vector of complex names to evaluate. If |
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.
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.
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.
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.
Calculate Reference Yield
calcRefYield(x, StockPars, FleetPars, pyears, Ncurr, nyears, proyears)calcRefYield(x, StockPars, FleetPars, pyears, Ncurr, nyears, proyears)
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 |
A. Hordyk
Computes standard deviation and lag-1 autocorrelation of log residuals
for a simulated index (sim x year).
CalcResidualStats(LogResiduals, nSeasons = 1)CalcResidualStats(LogResiduals, nSeasons = 1)
LogResiduals |
A numeric matrix or array with dimensions |
nSeasons |
Number of seasons in the array (default 1). |
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.
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
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().
CalcSPR0(OM, silent = FALSE)CalcSPR0(OM, silent = FALSE)
OM |
Either a om or hist object. If an om
object is provided, the historical dynamics are populated internally via
|
silent |
Logical. If |
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().
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:
CalcSurvival( NaturalMortality, FishingMortality = NULL, PlusGroup = TRUE, SpawnTimeFrac = 0, Semelparous = FALSE )CalcSurvival( NaturalMortality, FishingMortality = NULL, PlusGroup = TRUE, SpawnTimeFrac = 0, Semelparous = FALSE )
NaturalMortality |
Numeric array of natural mortality-at-age. Either
a 2D array ( |
FishingMortality |
Optional numeric array of fishing mortality-at-age,
matching the dimensions of |
PlusGroup |
Logical. If |
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 |
Semelparous |
Either |
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])).
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.
Two complementary functions for converting between the integer number of seasons per year and the corresponding time unit label used throughout the package:
CalcTSUnits(Seasons) CalcSeasons(Units)CalcTSUnits(Seasons) CalcSeasons(Units)
Seasons |
Integer. Number of seasons per year. Must be one of
|
Units |
Character. Time unit label. Case-insensitive. Must be one of
|
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"
|
CalcTSUnits(): a character string time unit label.
CalcSeasons(): an integer season count.
CalcTSUnits(1) # "year" CalcTSUnits(4) # "quarter" CalcTSUnits(NULL) # "year" CalcSeasons("year") # 1 CalcSeasons("Quarter") # 4CalcTSUnits(1) # "year" CalcTSUnits(4) # "quarter" CalcTSUnits(NULL) # "year" CalcSeasons("year") # 1 CalcSeasons("Quarter") # 4
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.
CalcUnfished_Dynamic(Hist, IdenticalHist = NULL, silent = FALSE)CalcUnfished_Dynamic(Hist, IdenticalHist = NULL, silent = FALSE)
Hist |
A |
IdenticalHist |
Logical; if |
silent |
Logical; if |
A popdynamics object containing dynamic unfished
Number, Biomass, SBiomass, and SProduction arrays with dimensions
Sim × Stock × Year.
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.
CalcUnfished_Equilibrium(OM, silent = FALSE)CalcUnfished_Equilibrium(OM, silent = FALSE)
OM |
|
silent |
Logical; if |
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.
A popdynamics object containing equilibrium unfished
Number, Biomass, SBiomass, and SProduction arrays with
dimensions Sim × Stock × Year.
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.
CalcUnfishedDist(Spatial, Ages = NULL, Years = NULL)CalcUnfishedDist(Spatial, Ages = NULL, Years = NULL)
Spatial |
A |
Ages |
An ages object supplying age class labels. If |
Years |
Numeric vector of year labels. If |
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().
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.
Calculates the equilibrium unfished number-at-age
CalcUnfishedNumber(OM, SP = FALSE)CalcUnfishedNumber(OM, SP = FALSE)
OM |
An |
SP |
Logical. Account for |
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.
A named list of length nStock() with each element an array with dimensions
Sim, Age, and Year
Calculate Unfished Survival
CalcUnfishedSurvival( OM, SP = FALSE, Years = NULL, silent = FALSE, Extend = TRUE )CalcUnfishedSurvival( OM, SP = FALSE, Years = NULL, silent = FALSE, Extend = TRUE )
OM |
An |
SP |
Logical. Account for |
Years |
Numeric vector of years to calculate |
silent |
Logical. Print messages? |
Extend |
Logical. Extend the array to include all Sims and Years? |
A list of length nStock() with an array with the unfished survival for each Stocks
## Not run: CalcUnfishedSurvival(OM) ## End(Not run)## Not run: CalcUnfishedSurvival(OM) ## End(Not run)
A function that condenses the number of catch-at-length bins in a data object
CALsimp(Data, nbins = 10, simno = 1)CALsimp(Data, nbins = 10, simno = 1)
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 |
T. Carruthers
Diagnostic tools that look up the slot requirements of each MP and compares to the data available in the Data object.
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)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)
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) |
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
CanMPs <- Can(MSEtool::Cobia) CantMPs <- Cant(MSEtool::Cobia) Needs <- Needed(MSEtool::Cobia)CanMPs <- Can(MSEtool::Cobia) CantMPs <- Cant(MSEtool::Cobia) Needs <- Needed(MSEtool::Cobia)
Interactions(), Landings(), Discards(), and Removals() extract
total interactions (encounters), retained landings, discards, and removals
(landings + discards) respectively.
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 )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 )
object |
|
df |
Logical. Applies to hist and mse objects only.
If |
byAge |
Logical. If |
byArea |
Logical. If |
byFleet |
Logical. If |
Reduce |
Logical. If |
IncYear |
Logical. Passed to |
bySize |
Logical. If |
x |
|
value |
A catchobs object (when |
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".
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.
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()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()
Construct and manipulate a catchability object defining fishing
gear or vessel efficiency for a Fleet() object.
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) <- valueCatchability(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
Efficiency |
Numeric, array, or
If |
qCV |
Numeric or |
qInc |
Numeric or |
Misc |
List. Miscellaneous additional inputs. Default |
x |
A catchability object for accessor and replacement functions. |
value |
The replacement value for the corresponding slot. |
Theta |
Numeric, array, or
|
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.
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.
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.
Theta
Theta () parameterises the negative binomial distribution
used by bag-limit management procedures to model within-trip catch counts:
where is the mean catch per trip at time ,
computed internally by the OM from the unfished equilibrium catch and
current depletion (assuming ; see Note). The variance of
within-trip catch is:
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.
A catchability object can be attached to a Fleet() with
Catchability(Fleet) <- MyCatchability and retrieved with
Catchability(Fleet).
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.
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
# See man-examples/class-Catchability.R# See man-examples/class-Catchability.R
catchability S4 ClassDefines gear or vessel efficiency for use in a fleet object.
Objects are typically created via the Catchability() constructor, which
documents all parameters in detail.
Efficiencynumeric, array, or NULL. Gear efficiency (q).
See Catchability().
qCVnumeric or NULL. Coefficient of variation for stochastic
variation in catchability during projected years. See Catchability().
qIncnumeric or NULL. Annual percentage increase in catchability
during projected years. See Catchability().
Thetanumeric, array, or NULL. Overdispersion parameter
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().
Misclist. Miscellaneous additional inputs. Used internally.
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
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.
CatchAndSurveyObsCatchAndSurveyObs
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.
obs, Obs(), CatchObs(), IndicesObs(),
CommercialFleetObs, AgeStructuredObs, LengthStructuredObs,
DataRichObs
Other obs-examples:
AgeStructuredObs,
CommercialFleetObs,
DataRichObs,
LengthStructuredObs
CatchAndSurveyObs Landings(CatchAndSurveyObs) Survey(CatchAndSurveyObs)CatchAndSurveyObs Landings(CatchAndSurveyObs) Survey(CatchAndSurveyObs)
Construct a catchdata object storing observed landed or discarded catch and associated uncertainty.
CatchData( Name = NULL, Value = NULL, CV = NULL, Units = NULL, Ref = NULL, RefCV = NULL )CatchData( Name = NULL, Value = NULL, CV = NULL, Units = NULL, Ref = NULL, RefCV = NULL )
Name |
|
Value |
|
CV |
|
Units |
|
Ref |
|
RefCV |
|
All arguments are optional; an empty object is valid and slots are
populated later (e.g., by GenHistData_Catch()).
Landings(data) <- CatchData(Value = myArray, CV = myCVArray) Discards(data) <- CatchData(Value = myArray, CV = myCVArray)
A catchdata object.
catchdata for the class definition.
CatchObs() for the observation error structure that generates
catchdata objects during simulation.
Other data:
CompData(),
EffortData(),
catchdata-class,
compdata-class,
effortdata-class
# 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"))# 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"))
catchdata S4 ClassStores 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.
Namecharacter or NULL. Fleet names, length nFleet.
Valuearray or NULL. Observed catch values with dimensions
[nYear x nFleet]. See CatchData().
CVarray or NULL. Coefficients of variation matching the
dimensions of Value. See CatchData().
Unitscharacter or NULL. Units of catch measurement per fleet
(e.g., "t" for tonnes, "numbers"). See CatchData().
Refarray or NULL. Reference catch values (e.g., a historical
baseline), matching the dimensions of Value. See CatchData().
RefCVarray or NULL. Coefficients of variation for the reference
values, matching the dimensions of Ref. See CatchData().
CatchData() for the constructor and full parameter documentation.
data for the enclosing data object.
Other data:
CatchData(),
CompData(),
EffortData(),
compdata-class,
effortdata-class
Construct a catchobs object defining observation error for landed or discarded catch, or access and replace individual slots.
CatchObs( CV = NULL, Bias = NULL, Error = NULL, Years = NULL, Units = NULL, Ref = NULL, Misc = list() )CatchObs( CV = NULL, Bias = NULL, Error = NULL, Years = NULL, Units = NULL, Ref = NULL, Misc = list() )
CV |
When conditioning on real data via |
Bias |
When conditioning on real data via |
Error |
|
Years |
|
Units |
|
Ref |
|
Misc |
|
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:
User-supplied Error: stored directly; CV is not used.
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])).
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.
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.
Landings(obs) <- CatchObs(CV = 0.2) Discards(obs) <- CatchObs(CV = 0.3, Bias = 1.1)
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.
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
# 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)# 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)
catchobs S4 ClassDefines 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.
CVnumeric or NULL. Coefficient of variation of catch observation
error. See CatchObs().
Errornumeric array or NULL. Realised lognormal observation error
multipliers (nSim x nYear). Populated internally during conditioning or
simulation; see CatchObs().
Biasnumeric or NULL. Multiplicative observation bias. See
CatchObs().
Yearsnumeric or NULL. Calendar years over which the observation
error is conditioned. See CatchObs().
Unitscharacter or NULL. Units of catch ("Biomass" or
"Number"). See CatchObs().
Refnumeric array or NULL. Reference catch values, one per
simulation. See CatchObs().
Misclist. Miscellaneous additional objects.
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
Warns if a catch slot (Landings or Discards) contains no data, or if
any catch values are not in units of biomass
CheckCatch(Data, incUnits = TRUE, slot_names = c("Landings", "Discards"))CheckCatch(Data, incUnits = TRUE, slot_names = c("Landings", "Discards"))
Data |
A data object. |
incUnits |
Logical. If |
slot_names |
Slots to check. Defaults are |
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.
NULL invisibly, called for its side-effect warnings.
Custom MPs cannot have the same names of MPs in MSEtool and related packages
CheckDuplicate(MPs)CheckDuplicate(MPs)
MPs |
Character vector of MP names |
An error if duplicated MP names, otherwise nothing
Check that specified MPs are valid and will run on MSEtool::SimulatedData
CheckMPs(MPs = NA, silent = FALSE)CheckMPs(MPs = NA, silent = FALSE)
MPs |
Character vector of MP names |
silent |
Logical. Report messages? |
MP names
Utility functions for MSE objects
checkMSE(MSEobj) addMPs(MSEobjs) joinMSE(MSEobjs = NULL) joinHist(Hist_List) updateMSE(MSEobj, save.name = NULL)checkMSE(MSEobj) addMPs(MSEobjs) joinMSE(MSEobjs = NULL) joinHist(Hist_List) updateMSE(MSEobj, save.name = NULL)
MSEobj |
A |
MSEobjs |
A list of MSE objects |
Hist_List |
A list of objects of class |
save.name |
Character string. Optional file name to save the updated MSE object to disk. |
An object of class MSE
A new object of class Hist
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)
A. Hordyk
Check OM object is complete
CheckOM(OM, msg = TRUE, stop_if_missing = TRUE)CheckOM(OM, msg = TRUE, stop_if_missing = TRUE)
OM |
An object of class |
msg |
Logical. Display messages? |
stop_if_missing |
Logical. Stop with error is values are missing and there is no default? |
The OM object with default values (if needed)
SingleStockOM <- CheckOM(SingleStockOM)SingleStockOM <- CheckOM(SingleStockOM)
Checks if a required package and (if applicable) package version are installed and if not, provides an error with installation instructions
CheckPackage(pkg, version = NULL, pkg.path = NULL)CheckPackage(pkg, version = NULL, pkg.path = NULL)
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 |
# 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)# 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)
Interactive plots to specify trends and variability in fishing effort, fleet selectivity, and natural mortality for the operating model.
ChooseEffort(Fleet, Years = NULL) ChooseM(OM, type = c("age", "length"), x = NULL, y = NULL) ChooseSelect(Fleet, Stock, FstYr = NULL, SelYears = NULL)ChooseEffort(Fleet, Years = NULL) ChooseM(OM, type = c("age", "length"), x = NULL, y = NULL) ChooseSelect(Fleet, Stock, FstYr = NULL, SelYears = NULL)
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). |
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). |
ChooseEffort and ChooseSelect return a Fleet object while
ChooseM returns an OM object.
A. Hordyk
Combines several fleets into a new aggregated fleet within an Operating Model, preserving the overall fishery dynamics that would result from the disaggregated fleets.
CombineFleets(OM, FleetList, silent = FALSE)CombineFleets(OM, FleetList, silent = FALSE)
OM |
An |
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 |
|
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
Let be the apical fishing mortality for fleet ,
and , , be selectivity, retention,
and discard mortality at age .
Apical F and effort
Effort is recovered as , where is
taken from the first fleet.
F-at-age (interaction)
Selectivity
Retention
Discard mortality (age-specific F-weighted average on the instantaneous-rate scale)
WeightFleet (age-specific F-weighted average)
Create a blank MP recommendations object (class Rec) of the right dimensions
CombineMMP(temp, nareas)CombineMMP(temp, nareas)
temp |
A list of nsim simulations. |
nareas |
The number of areas. |
T. Carruthers
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.
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 )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 )
OM_List |
Named list of |
Name |
|
FillEffort |
List controlling effort forward-filling. See |
FillEfficiency |
List controlling efficiency forward-filling. See |
StandardizeEffort |
|
silent |
|
Validate that all OMs share nSim, Seasons, and fleet names.
Standardize each OM via PopulateOM().
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.
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.
Concatenate stocks and fleets.
Generate correlated recruitment deviations for the projection period
via GenMultiStockRecDevs().
Optionally standardize effort across stocks via StandardizeEffort(),
which populates @StockTargeting
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.
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.
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]].
GenMultiStockRecDevs(), StandardizeEffort()
## 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)## 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)
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.
CommercialFleetObsCommercialFleetObs
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.
obs, Obs(), CatchObs(), EffortObs(), IndicesObs(),
CatchAndSurveyObs, AgeStructuredObs, LengthStructuredObs,
DataRichObs
Other obs-examples:
AgeStructuredObs,
CatchAndSurveyObs,
DataRichObs,
LengthStructuredObs
CommercialFleetObs Effort(CommercialFleetObs) CPUE(CommercialFleetObs)CommercialFleetObs Effort(CommercialFleetObs) CPUE(CommercialFleetObs)
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.
CompareBAM(Stock, OM = NULL, plot = FALSE, thresh = 1)CompareBAM(Stock, OM = NULL, plot = FALSE, thresh = 1)
Stock |
Character string matching a stock in |
OM |
Optional OM or |
plot |
Logical. Plot the timeseries for the |
thresh |
Numeric. MARE threshold (as a percentage) above which a
comparison is flagged, printed, and plotted. Default |
Series with MARE exceeding thresh are plotted automatically.
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).
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.
CompareSS(SSDir, Hist, sim = 1, silent = FALSE, ...) CompareSS_Number(SSDir, Hist, sim = 1, silent = FALSE, ...) CompareSS_Biomass(SSDir, Hist, sim = 1, silent = FALSE, ...)CompareSS(SSDir, Hist, sim = 1, silent = FALSE, ...) CompareSS_Number(SSDir, Hist, sim = 1, silent = FALSE, ...) CompareSS_Biomass(SSDir, Hist, sim = 1, silent = FALSE, ...)
SSDir |
Character string giving the path to a directory containing SS3
output files, or a list returned by |
Hist |
A |
sim |
Integer. Simulation index used to select both the SS3 report
element and the OM simulation row. Default |
silent |
Logical. Passed to |
... |
Additional arguments forwarded to |
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.
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.
ImportSSReport(), Simulate(), Number(), Biomass()
Construct a compdata object storing age or size composition observations of catch samples.
CompData( Name = NULL, Value = NULL, Classes = NULL, Units = NULL, Log = list(), Misc = list() )CompData( Name = NULL, Value = NULL, Classes = NULL, Units = NULL, Log = list(), Misc = list() )
Name |
|
Value |
|
Classes |
|
Units |
|
Log |
|
Misc |
|
All arguments are optional; an empty object is valid and slots are
populated later (e.g., by GenHistData_AgeComp() or
GenHistData_SizeComp().
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().
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)
A compdata object.
compdata for the class definition.
CompObs() for the observation error structure that generates
compdata objects during simulation.
Other data:
CatchData(),
EffortData(),
catchdata-class,
compdata-class,
effortdata-class
# 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")# 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")
compdata S4 ClassStores 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.
Namecharacter or NULL. Fleet names, length nFleet.
Valuearray or NULL. Composition counts with dimensions
[nYear x nFleet x nClass]. See CompData().
Classesnumeric or NULL. Class midpoints — ages in years for
age compositions, or bin midpoints in the appropriate length unit for
size compositions. See CompData().
Unitscharacter or NULL. Units of the class variable
(e.g., "years", "cm", "mm"). See CompData().
Loglist. Named list used for diagnostic and audit logging.
Misclist. Named list for additional composition-level metadata.
CompData() for the constructor and full parameter documentation.
data for the enclosing data object.
Other data:
CatchData(),
CompData(),
EffortData(),
catchdata-class,
effortdata-class
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.
ComplexOMComplexOM
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.
Two biologically contrasting stocks are included:
AlbacoreExStock: long-lived, slow-growing, low natural mortality.
ButterfishExStock: short-lived, fast-growing, high natural mortality.
See AlbacoreExStock and ButterfishExStock for full parameter details.
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.
AsympExFleet is applied to both stocks, representing a single fleet type with asymptotic length-based selectivity. See AsympExFleet for full parameter details.
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.
The Imp slot is NULL. The imp is currently a placeholder and
implementation error is not applied during simulation. See Imp() for
details.
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
ComplexOM ComplexOM@Complexes nStock(ComplexOM) ## Not run: Hist <- runMSE(ComplexOM, MPs = ExampleMPs()) ## End(Not run)ComplexOM ComplexOM@Complexes nStock(ComplexOM) ## Not run: Hist <- runMSE(ComplexOM, MPs = ExampleMPs()) ## End(Not run)
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.
CompObs( SampleSize = NULL, ESS = NULL, Theta = NULL, Years = NULL, Shift = NULL, Misc = list() )CompObs( SampleSize = NULL, ESS = NULL, Theta = NULL, Years = NULL, Shift = NULL, Misc = list() )
SampleSize |
|
ESS |
|
Theta |
|
Years |
|
Shift |
|
Misc |
|
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
Step 2 — Apply log-concentration offset (if Shift non-NULL)
When Shift is NULL, .
Step 3 — Dirichlet draw
where Theta controls overdispersion. Theta = 1
recovers the standard Dirichlet with concentration .
Smaller values of Theta shrink the total concentration and increase
variance.
Step 4 — Multinomial draw
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.
obs <- Obs() LandingsAtAge(obs) <- CompObs(SampleSize = 200, ESS = 50) LandingsAtSize(obs) <- CompObs(SampleSize = 150, ESS = 40, Theta = 0.5)
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.
compobs for the class definition and slot descriptions.
PopulateCompObs() for the population function.
ConditionObs_Comp() for the conditioning function.
Obs() for the enclosing observation model constructor.
Other obs:
CatchObs(),
EffortObs(),
ExploitationObs(),
IndicesObs(),
LifeHistoryObs(),
Obs(),
catchobs-class,
compobs-class,
effortobs-class,
exploitationobs-class,
indicesobs-class,
lifehistoryobs-class,
obs-class
# 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) )# 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) )
compobs S4 ClassDefines 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.
During simulation, PopulateCompObs() applies the following steps:
Shift non-NULL: user-specified (or conditioned) per-bin
log-concentration offsets are exponentiated and applied to the
OM-predicted concentration vector:
Shift NULL (default): pure Dirichlet-Multinomial draw from the
OM-predicted composition with concentration scaled by ESS and
dispersion Theta:
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.
SampleSizenumeric 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.
ESSnumeric 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.
Thetanumeric 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.
Yearsnumeric 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.
Shiftnumeric 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.
Misclist. Reserved for internal use.
CompObs() for the constructor and full parameter documentation.
PopulateCompObs() for the population function.
ConditionObs_Comp() for the conditioning function.
obs for the enclosing observation model object.
Other obs:
CatchObs(),
CompObs(),
EffortObs(),
ExploitationObs(),
IndicesObs(),
LifeHistoryObs(),
Obs(),
catchobs-class,
effortobs-class,
exploitationobs-class,
indicesobs-class,
lifehistoryobs-class,
obs-class
A named list of default control options for Control(OM).
ControlDefaultControlDefault
An object of class list of length 2.
Can be modified if you know what you're doing!
Have I undertaken enough simulations (nsim)? Has my MSE converged on stable (reliable) performance metrics?
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 )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 )
MSEobj |
An MSE object of class |
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 |
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? |
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:
Is the order of the MPs stable over the last ref.it iterations?
Is the average difference in performance statistic over the last ref.it iterations < thresh?
By default three commonly used performance metrics are used:
Average Yield Relative to Reference Yield
Probability Spawning Biomass is above 0.1BMSY
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.
A table of convergence results for each MP
A. Hordyk
## Not run: MSE <- runMSE() Converge(MSE) ## End(Not run)## Not run: MSE <- runMSE() Converge(MSE) ## End(Not run)
Converts legacy openMSE S4 objects to their equivalent new S4 class
representations. Dispatches to the appropriate conversion function based on
the class of x.
Convert(x, ...)Convert(x, ...)
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 ( |
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.
A new S4 object of the corresponding updated class:
MOM-legacy → om
ConvertOM(), ConvertMOM(), ConvertStock(), ConvertFleet(),
ConvertObs(), ConvertImp(), ConvertData()
# 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)# 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)
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.
ConvertData(Data, Seasons = 1, sim = 1, silent = FALSE)ConvertData(Data, Seasons = 1, sim = 1, silent = FALSE)
Data |
A Data-legacy object to convert. |
Seasons |
Integer. Number of seasons per year. Default |
sim |
Integer. Simulation index to extract from the legacy object.
Default |
silent |
Logical. If |
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
A data object populated from simulation sim of Data.
Convert(), ConvertOM(), ConvertMOM()
## Not run: Datalegacy <- readRDS("MyLegacyData.rds") data_new <- ConvertData(Datalegacy, sim = 1) ## End(Not run)## Not run: Datalegacy <- readRDS("MyLegacyData.rds") data_new <- ConvertData(Datalegacy, sim = 1) ## End(Not run)
fleet ClassConverts a legacy Fleet-legacy object to the current fleet by mapping each component to its corresponding new S4 sub-object.
ConvertFleet(Fleet, silent = FALSE)ConvertFleet(Fleet, silent = FALSE)
Fleet |
A Fleet-legacy object to convert. An OM-legacy
object with a legacy |
silent |
Logical. If |
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
|
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.
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.
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.
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.
A fleet object.
Convert(), ConvertOM(), ConvertMOM(), ConvertStock(),
ConvertObs(), ConvertImp(), Effort(), Catchability(),
Selectivity(), Retention(), SelectivityModels(),
RetentionModels()
## Not run: fleet_legacy <- readRDS("MyLegacyFleet.rds") fleet_new <- ConvertFleet(fleet_legacy) ## End(Not run)## Not run: fleet_legacy <- readRDS("MyLegacyFleet.rds") fleet_new <- ConvertFleet(fleet_legacy) ## End(Not run)
Converts a legacy Imp-legacy object to the current imp by mapping implementation error parameters to their corresponding new S4 slots.
ConvertImp(Imp, silent = FALSE)ConvertImp(Imp, silent = FALSE)
Imp |
An Imp-legacy object to convert. |
silent |
Logical. If |
An imp object with TAC, Effort, and Size
implementation error slots populated.
Convert(), ConvertOM(), ConvertMOM(), ConvertObs()
## Not run: Implegacy <- readRDS("MyLegacyImp.rds") imp_new <- ConvertImp(Implegacy) ## End(Not run)## Not run: Implegacy <- readRDS("MyLegacyImp.rds") imp_new <- ConvertImp(Implegacy) ## End(Not run)
Converts a legacy MOM-legacy object to the current om, copying
attributes, updating year vectors, and optionally populating the object
via PopulateOM().
ConvertMOM( MOM, Author = "", CurrentYear = NULL, Seasons = 1, Populate = TRUE, silent = FALSE )ConvertMOM( MOM, Author = "", CurrentYear = NULL, Seasons = 1, Populate = TRUE, silent = FALSE )
MOM |
A MOM-legacy object to convert. |
Author |
Character. Author of the OM. Default |
CurrentYear |
Numeric. Last historical calendar year. If |
Seasons |
Integer. Number of seasons per year. Default |
Populate |
Logical. If |
silent |
Logical. If |
An om object.
Convert(), ConvertOM(), ConvertStock(), ConvertFleet(),
ConvertObs(), ConvertImp(), PopulateOM()
## Not run: MOMlegacy <- readRDS("MyLegacyMOM.rds") om_new <- ConvertMOM(MOMlegacy) ## End(Not run)## Not run: MOMlegacy <- readRDS("MyLegacyMOM.rds") om_new <- ConvertMOM(MOMlegacy) ## End(Not run)
obs ClassConverts a legacy Obs-legacy object to the current obs by mapping observation error parameters to their corresponding sub-object slots.
ConvertObs(Obs, silent = FALSE)ConvertObs(Obs, silent = FALSE)
Obs |
An Obs-legacy object to convert. An om object
with a legacy |
silent |
Logical. If |
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.
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)
An obs object.
Convert(), ConvertOM(), ConvertMOM(), ConvertImp() for
related legacy conversion functions.
## Not run: obs_legacy <- readRDS("MyLegacyObs.rds") obs_new <- ConvertObs(obs_legacy) ## End(Not run)## Not run: obs_legacy <- readRDS("MyLegacyObs.rds") obs_new <- ConvertObs(obs_legacy) ## End(Not run)
Converts a legacy OM-legacy object to the current om,
copying attributes, updating year vectors, and optionally populating the
object via PopulateOM().
ConvertOM( OM, Author = "", CurrentYear = NULL, Seasons = 1, Populate = TRUE, silent = FALSE )ConvertOM( OM, Author = "", CurrentYear = NULL, Seasons = 1, Populate = TRUE, silent = FALSE )
OM |
An OM-legacy object to convert. |
Author |
Character. Author of the OM. Default |
CurrentYear |
Numeric. Last historical calendar year. If |
Seasons |
Integer. Number of seasons per year. Default |
Populate |
Logical. If |
silent |
Logical. If |
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.
An om object.
Convert(), ConvertMOM(), ConvertStock(), ConvertFleet(),
ConvertObs(), ConvertImp(), PopulateOM()
## Not run: OMlegacy <- readRDS("MyLegacyOM.rds") om_new <- ConvertOM(OMlegacy) ## End(Not run)## Not run: OMlegacy <- readRDS("MyLegacyOM.rds") om_new <- ConvertOM(OMlegacy) ## End(Not run)
stock ClassConverts a legacy Stock-legacy object to the current stock by mapping each component to its corresponding new S4 sub-object.
ConvertStock(Stock, Seasons = 1, silent = FALSE)ConvertStock(Stock, Seasons = 1, silent = FALSE)
Stock |
A Stock-legacy object to convert. An OM-legacy
object with a legacy |
Seasons |
Numeric. Number of seasons in a year. Default |
silent |
Logical. If |
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
|
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.
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.
A stock object.
Convert(), ConvertOM(), ConvertMOM(), ConvertFleet(),
ConvertObs(), ConvertImp()
## Not run: stock_legacy <- readRDS("MyLegacyStock.rds") stock_new <- ConvertStock(stock_legacy) ## End(Not run)## Not run: stock_legacy <- readRDS("MyLegacyStock.rds") stock_new <- ConvertStock(stock_legacy) ## End(Not run)
Current default thresholds for COSEWIC satisficing
Cos_thresh_tab(Ptab1)Cos_thresh_tab(Ptab1)
Ptab1 |
A COSEWIC performance table made by COSEWIC_tab() |
T. Carruthers
OM@cpars is formatted correctlyInternal function for checking that the OM@cpars is formatted correctly
cparscheck(cpars)cparscheck(cpars)
cpars |
a list of model parameters to be sampled (single parameters are
a vector |
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
T. Carruthers
Compare median biomass and yield in first year and last 5 years of projection
Cplot( MSEobj, MPs = NA, lastYrs = 5, point.size = 2, lab.size = 4, axis.title.size = 12, axis.text.size = 10, legend.title.size = 12 )Cplot( MSEobj, MPs = NA, lastYrs = 5, point.size = 2, lab.size = 4, axis.title.size = 12, axis.text.size = 10, legend.title.size = 12 )
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 |
## Not run: MSE <- runMSE() Cplot(MSE) ## End(Not run)## Not run: MSE <- runMSE() Cplot(MSE) ## End(Not run)
Convert between the Beverton-Holt stock-recruitment steepness (h) and compensation ratio (CR) parameterizations.
CR2h(CR) h2CR(h)CR2h(CR) h2CR(h)
CR |
Numeric. Compensation ratio (see Details). |
h |
Numeric. Steepness value (see Details). Must be in the range (0.2, 1), exclusive. |
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:
Numeric. CR2h() returns steepness (h) bounded between 0.2 and 1;
h2CR() returns the compensation ratio (CR).
CR2h(5) h2CR(0.7)CR2h(5) h2CR(0.7)
Data
Creates a new data object, or extracts the Data or PPD slot from
an existing om, hist, or mse class object.
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() )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() )
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 |
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 |
Seasons |
A positive integer giving the number of seasons per year.
Defaults to |
nArea |
A positive integer giving the number of spatial areas.
Defaults to |
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
|
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:
LifeHistory → lifehistorydata
Exploitation → exploitationdata
Reference → referencedata
Effort → effortdata
Landings, Discards → catchdata
CPUE, Survey → indicesdata
LandingsAtAge, DiscardsAtAge, LandingsAtSize, DiscardsAtSize → compdata
Advice → advicedata
A data object, or when Name is an mse object, a list
of data objects from the @PPD slot.
data, LastTAC(), LastHistYearInd(), ProjectionYear()
A function to read in Data object from an Excel spreadsheet with tabs named following specific convention.
Data_xl(fname, stkname, fpath = "", saveCSV = FALSE)Data_xl(fname, stkname, fpath = "", saveCSV = FALSE)
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? |
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'.
A object of class Data
A. Hordyk
## Not run: OM <- OM_xl(fname='OMTables.xlsx', stkname='myFish') ## End(Not run)## Not run: OM <- OM_xl(fname='OMTables.xlsx', stkname='myFish') ## End(Not run)
data S4 ClassThe 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.
Objects should be created with the Data() constructor, which initialises
all sub-object slots to empty objects of the appropriate class when not
supplied.
NameOptional character string. Name of the data object.
CommonNameOptional character string. Common name of the stock.
SpeciesOptional character string. Scientific name of the species.
AgencyOptional character string. Name of the managing agency.
AuthorOptional character string. Name(s) of the data author(s).
EmailOptional character string. Contact email(s) for the author(s).
RegionOptional character string. Geographic region of the stock.
LatitudeOptional numeric. Latitude of the stock in decimal degrees.
LongitudeOptional numeric. Longitude of the stock in decimal degrees.
YearsNumeric vector of calendar years covered by the data.
YearLHNumeric. The last historical year, separating the historical
period from the projection period. Defaults to max(Years) when not
supplied to Data().
SeasonsPositive integer. Number of seasons per year. Defaults to 1.
nAreaPositive integer. Number of spatial areas. Defaults to 1.
LifeHistoryAn object of class lifehistorydata containing biological parameters such as growth, maturity, and natural mortality.
ExploitationAn object of class exploitationdata containing selectivity, retention, and discard mortality parameters.
ReferenceAn object of class referencedata containing biological reference points such as unfished biomass and MSY-based quantities.
EffortAn object of class effortdata containing fishing effort time series.
LandingsAn object of class catchdata containing landed catch time series.
DiscardsAn object of class catchdata containing discarded catch time series.
CPUEAn object of class indicesdata containing catch-per-unit-effort indices.
SurveyAn object of class indicesdata containing fishery-independent survey indices.
LandingsAtAgeAn object of class compdata containing age composition of landed catch.
DiscardsAtAgeAn object of class compdata containing age composition of discarded catch.
LandingsAtSizeAn object of class compdata containing size composition of landed catch.
DiscardsAtSizeAn object of class compdata containing size composition of discarded catch.
AdviceAn object of class advicedata containing TAC recommendations and related management advice.
MiscA named list for any additional user-defined data. Defaults to
list().
LogInternal named list used for diagnostic and audit logging.
'Data'
An object for storing fishery data for analysis
NameThe name of the Data object. Single value. Character string
Common_NameCommon name of the species. Character string
SpeciesScientific name of the species. Genus and species name. Character string
RegionName of the general geographic region of the fishery. Character string
LHYearThe last historical year of the simulation (before projection). Single value. Positive integer
MPrecThe previous recommendation of a management procedure. Vector of length nsim. Positive real numbers
UnitsUnits of the catch/absolute abundance estimates. Single value. Character string
MPeffThe current level of effort. Vector of length nsim. Positive real numbers
nareasNumber of fishing areas. Vector of length nsim. Non-negative integer
MaxAgeMaximum age. Vector nsim long. Positive integer
MortNatural mortality rate. Vector nsim long. Positive real numbers
CV_MortCoefficient of variation in natural mortality rate. Vector nsim long. Positive real numbers
vbLinfMaximum length. Vector nsim long. Positive real numbers
CV_vbLinfCoefficient of variation in maximum length. Vector nsim long. Positive real numbers
vbKThe von Bertalanffy growth coefficient K. Vector nsim long. Positive real numbers
CV_vbKCoefficient of variation in the von Bertalanffy K parameter. Vector nsim long. Positive real numbers
vbt0Theoretical age at length zero. Vector nsim long. Non-positive real numbers
CV_vbt0Coefficient of variation in age at length zero. Vector nsim long. Positive real numbers
wlaWeight-Length parameter alpha. Vector nsim long. Positive real numbers
CV_wlaCoefficient of variation in weight-length parameter a. Vector nsim long. Positive real numbers
wlbWeight-Length parameter beta. Vector nsim long. Positive real numbers
CV_wlbCoefficient of variation in weight-length parameter b. Vector nsim long. Positive real numbers
steepSteepness of stock-recruitment relationship. Vector nsim long. Value in the range of one-fifth to 1
CV_steepCoefficient of variation in steepness. Vector nsim long. Positive real numbers
sigmaRRecruitment variability. Vector nsim long. Positive real numbers
CV_sigmaRCoefficient of variation in recruitment variability. Vector nsim long. Positive real numbers
L50Length at 50 percent maturity. Vector nsim long. Positive real numbers
CV_L50Coefficient of variation in length at 50 per cent maturity. Vector nsim long. Positive real numbers
L95Length at 95 percent maturity. Vector nsim long. Positive real numbers
LenCVCoefficient of variation of length-at-age (assumed constant for all age classes). Vector nsim long. Positive real numbers
LFCLength at first capture. Vector nsim long. Positive real numbers
CV_LFCCoefficient of variation in length at first capture. Vector nsim long. Positive real numbers
LFSShortest length at full selection. Vector nsim long. Positive real numbers
CV_LFSCoefficient of variation in length at full selection. Vector nsim long. Positive real numbers
VmaxlenVulnerability of individuals at asymptotic length. Vector nsim long. Real number between 0 and 1.
YearYears that corresponding to catch and relative abundance data. Vector nyears long. Positive integer
CatTotal annual catches. Matrix of nsim rows and nyears columns. Non-negative real numbers
CV_CatCoefficient 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.
EffortAnnual fishing effort. Matrix of nsim rows and nyears columns. Non-negative real numbers
CV_EffortCoefficient 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.
IndRelative total abundance index. Matrix of nsim rows and nyears columns. Non-negative real numbers
CV_IndCoefficient 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
SpIndRelative spawning abundance index. Matrix of nsim rows and nyears columns. Non-negative real numbers
CV_SpIndCoefficient of variation in the relative spawning abundance index. Matrix nsim rows and either 1 or nyear columns. Positive real numbers.
VIndRelative vulnerable abundance index. Matrix of nsim rows and nyears columns. Non-negative real numbers
CV_VIndCoefficient of variation in the relative vulnerable abundance index. Matrix nsim rows and either 1 or nyear columns. Positive real numbers.
AddIndOptional additional indices. Array of dimensions nsim, n additional indices, and nyears (length Year).
CV_AddIndCoefficient of variation for additional indices. Array of same dimensions as AddInd
AddIndVVulnerability-at-age schedules for the additional indices. Array with dimensions: nsim, n additional indices, MaxAge+1.
AddIunitsUnits for the additional indices - biomass (1; default) or numbers (0). Numeric vector length n.ind.
AddIndTypeIndex calculated from total stock (1, default), spawning stock (2), or vulnerable stock (3). Numeric vector of length n.ind
RecRecent recruitment strength. Matrix of nsim rows and nyears columns. Non-negative real numbers
CV_RecLog-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.
MLMean length time series. Matrix of nsim rows and nyears columns. Non-negative real numbers
LcModal length of catches. Matrix of nsim rows and nyears columns. Positive real numbers
LbarMean length of catches over Lc. Matrix of nsim rows and nyears columns. Positive real numbers
Vuln_CAAOptional 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.
CAACatch at Age data (numbers). Array of dimensions nsim x nyears x MaxAge+1. Non-negative integers
Vuln_CALOptional 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_binsThe values delimiting the length bins for the catch-at-length data. Vector. Non-negative real numbers
CAL_midsThe values of the mid-points of the length bins. Optional, calculated from CAL_bins if not entered. Vector. Non-negative real numbers.
CALCatch-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).
DepStock depletion SSB(current)/SSB(unfished). Vector nsim long. Fraction.
CV_DepCoefficient of variation in current stock depletion. Vector nsim long. Positive real numbers
AbunAn estimate of absolute current vulnerable abundance. Vector nsim long. Positive real numbers
CV_AbunCoefficient of variation in estimate of absolute current stock size. Vector nsim long. Positive real numbers
SpAbunAn estimate of absolute current spawning stock abundance. Vector nsim long. Positive real numbers
CV_SpAbunCoefficient of variation in estimate of absolute spawning current stock size. Vector nsim long. Positive real numbers
FMSY_MAn assumed ratio of FMSY to M. Vector nsim long. Positive real numbers
CV_FMSY_MCoefficient of variation in the ratio in FMSY/M. Vector nsim long. Positive real numbers
BMSY_B0The most productive stock size relative to unfished. Vector nsim long. Fraction
CV_BMSY_B0Coefficient of variation in the position of the most productive stock size relative to unfished. Vector nsim long. Positive real numbers
CrefReference or target catch level (eg MSY). Vector of length nsim. Positive real numbers
CV_CrefLog-normal CV for reference or target catch level. Vector of length nsim. Positive real numbers
BrefReference or target biomass level (eg BMSY). Vector of length nsim. Positive real numbers
CV_BrefLog-normal CV for reference or target biomass level. Vector of length nsim. Positive real numbers
IrefReference or target relative abundance index level (eg BMSY / B0). Vector of length nsim. Positive real numbers
CV_IrefLog-normalCV for reference or target relative abundance index level. Vector of length nsim. Positive real numbers
tThe number of years corresponding to AvC and Dt. Single value. Positive integer
AvCAverage catch over time t. Vector nsim long. Positive real numbers
CV_AvCCoefficient of variation in average catches over time t. Vector nsim long. Positive real numbers
DtDepletion over time t SSB(now)/SSB(now-t+1). Vector nsim long. Fraction
CV_DtCoefficient of variation in depletion over time t. Vector nsim long. Positive real numbers
RefA reference management level (eg a catch limit). Single value. Positive real number
Ref_typeType of reference management level (eg 2009 catch limit). Single value. Character string
LogA record of events. Single value. Character string
paramsA place to store estimated parameters. An object. R list
PosMPsThe methods that can be applied to these data. Vector. Character strings
TACThe calculated catch limits (function TAC). An array with dimensions PosMPs x replicate TAC samples x nsim. Positive real numbers
SenseThe results of the sensitivity analysis (function Sense). An array with dimensions PosMPs x sensitivity increments. Positive real numbers
MPsThe methods that were applied to these data. Vector. Character strings
OMA table of operating model conditions. R table object of nsim rows. Real numbers
ObsA table of observation model conditions. R table object of nsim rows. Real numbers
MiscOther information for MPs. An object. R list
Objects can be created by calls of the form
new('Data', stock)
T. Carruthers and A. Hordyk
newdata<-new('Data')newdata<-new('Data')
A function that writes a correctly formatted .csv file from a MSEtool Data object
Data2csv(Data, file = NULL, simno = 1, overwrite = F, keepNAs = T)Data2csv(Data, file = NULL, simno = 1, overwrite = F, keepNAs = T)
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. |
T. Carruthers
A data.frame with description of slots for class Data
DataDescriptionDataDescription
An object of class data.frame with 94 rows and 2 columns.
A way of locating where the package was installed so you can find example data files and code etc.
DataDir(stock = NA)DataDir(stock = NA)
stock |
Character string representing the name of a .csv file e.g. 'Snapper', 'Rockfish' |
The file path to the object
T. Carruthers
## Not run: tilefish_location <- DataDir("Gulf_blue_tilefish") tilefish_Data <- new("Data", tilefish_location) ## End(Not run)## Not run: tilefish_location <- DataDir("Gulf_blue_tilefish") tilefish_Data <- new("Data", tilefish_location) ## End(Not run)
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.
LastTAC(Data) LastHistYearInd(Data) ProjectionYear(Data)LastTAC(Data) LastHistYearInd(Data) ProjectionYear(Data)
Data |
An object of class data. |
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.
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
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
DataInit(name = "Data", ext = c("xlsx", "csv"), overwrite = FALSE, dir = NULL)DataInit(name = "Data", ext = c("xlsx", "csv"), overwrite = FALSE, dir = NULL)
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()“ |
Nothing. Creates template data files in the working directory.
A. Hordyk
## Not run: DataInit("Example") # populated example DataInit("myData") # empty template ## End(Not run)## Not run: DataInit("Example") # populated example DataInit("myData") # empty template ## End(Not run)
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.
DataRichObsDataRichObs
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].
obs, Obs(), CatchObs(), EffortObs(), IndicesObs(),
CompObs(), CatchAndSurveyObs, CommercialFleetObs,
AgeStructuredObs, LengthStructuredObs
Other obs-examples:
AgeStructuredObs,
CatchAndSurveyObs,
CommercialFleetObs,
LengthStructuredObs
DataRichObs Survey(DataRichObs) LandingsAtAge(DataRichObs) DiscardsAtSize(DataRichObs)DataRichObs Survey(DataRichObs) LandingsAtAge(DataRichObs) DiscardsAtSize(DataRichObs)
Dataframe with details of slots in Dat object
DataSlotsDataSlots
An object of class tbl_df (inherits from tbl, data.frame) with 101 rows and 4 columns.
Truncate a Data object so that all time-dependent arrays are trimmed
to the specified final year.
DataTrim(Data, Year)DataTrim(Data, Year)
Data |
A |
Year |
A single numeric value specifying the final year to retain. Arrays that are not indexed by
|
A Data object where all year-dependent slots include only years less than
or equal to Year.
SubsetYear() for year-based subsetting
Years() for extracting available years
Example objects of class Fleet
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_FishDecE_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
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.
avail("Fleet")avail("Fleet")
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.
DefaultAges(Ages = NULL) DefaultYears(Years = NULL)DefaultAges(Ages = NULL) DefaultYears(Years = NULL)
Ages |
An ages object, or |
Years |
Numeric vector of years, or |
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.
DefaultAges(): an ages object.
DefaultYears(): a numeric vector of integer years.
DefaultAges() DefaultYears()DefaultAges() DefaultYears()
Delete the Log Directory
DeleteLogs(Dir = file.path(getwd(), "Log"))DeleteLogs(Dir = file.path(getwd(), "Log"))
Dir |
Directory where the logs are kept. |
Nothing
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.
Depletion(Initial = NULL, Final = NULL, Reference = "B0") Initial(x) Initial(x) <- value Final(x) Final(x) <- value Depletion(x) <- valueDepletion(Initial = NULL, Final = NULL, Reference = "B0") Initial(x) Initial(x) <- value Final(x) Final(x) <- value Depletion(x) <- value
Initial |
|
Final |
|
Reference |
|
x |
A depletion object for slot accessors, or a stock
object for |
value |
For |
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.
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))
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")
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
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
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.
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
# ---- 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# ---- 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
depletion S4 ClassDefines 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.
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.
Initialarray 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.
Finalarray 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.
Referencecharacter(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.
Misclist. Used internally.
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()
A plot of biomass relative to BMSY over projected years
DFO_bar(MSEobj, yres = 10)DFO_bar(MSEobj, yres = 10)
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 |
T. Carruthers
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
DFO_hist(OM, panel = T, nsim = 48)DFO_hist(OM, panel = T, nsim = 48)
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) |
T. Carruthers
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
DFO_plot(MSEobj, zero_origin = T)DFO_plot(MSEobj, zero_origin = T)
MSEobj |
An MSE object of class MSE produced by MSEtool function runMSE |
zero_origin |
Logical: should plots have a zero-zero origin? |
T. Carruthers
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
DFO_plot2(MSEobj, nam = NA, panel = T, Bcut = 50, Ycut = 50)DFO_plot2(MSEobj, nam = NA, panel = T, Bcut = 50, Ycut = 50)
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) |
A table of performance metrics.
T. Carruthers
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
DFO_proj(MSEobj, maxplot = 6)DFO_proj(MSEobj, maxplot = 6)
MSEobj |
An operating model object of class MSE |
maxplot |
The maximum number of MPs to be plotted per figure |
T. Carruthers
A plot of biomass relative to BMSY quantiles over projected years
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 )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 )
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. |
T. Carruthers
Provides performance plots typical in the assessment of Canadian fish stocks.
DFO_report( MSEobj, output_file = NA, author = "Author not specified", title = NA, maxMPs = 15 )DFO_report( MSEobj, output_file = NA, author = "Author not specified", title = NA, maxMPs = 15 )
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 |
T. Carruthers
DFO performance spider plot (top three MPs)
DFO_spider(MSEobj)DFO_spider(MSEobj)
MSEobj |
An object of class MSE produced by MSEtool::runMSE() |
T. Carruthers
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
DFO_tab(MSEobj, maxMPs = 15, rnd = 0)DFO_tab(MSEobj, maxMPs = 15, rnd = 0)
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. |
T. Carruthers
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
DFO_tab_formatted( Ptab1, thresh = c(30, 50, 40, 60, 50, 20, 40, 50, 60, 50, 30, 50), ret_thresh = F )DFO_tab_formatted( Ptab1, thresh = c(30, 50, 40, 60, 50, 20, 40, 50, 60, 50, 30, 50), ret_thresh = F )
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 |
T. Carruthers
Retrieve or set the dimension of an object.
dim(x)dim(x)
x |
an R object, for example a matrix, array or data frame. This is a wrapper for |
MyArray <- array(1:6, dim = c(6, 2), dimnames = list( Age = 1:6, Year = c(2025, 2026) ) ) dim(MyArray)MyArray <- array(1:6, dim = c(6, 2), dimnames = list( Age = 1:6, Year = c(2025, 2026) ) ) dim(MyArray)
Utilities to add or drop named dimensions from arrays.
AddDimension(array, name, val = 1, pos = NULL) DropDimension(array, name, warn = TRUE)AddDimension(array, name, val = 1, pos = NULL) DropDimension(array, name, warn = TRUE)
array |
An array with named dimensions. |
name |
A single character string naming the dimension to add
( |
val |
Value(s) to assign as the dimname of the new dimension in
|
pos |
Integer giving the position at which to insert the new dimension
in |
warn |
Logical; if |
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.
An array with modified dimensions and updated dimnames.
# ---- 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)# ---- 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)
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.
DiscardMortality( MeanAtAge = NULL, MeanAtLength = NULL, Classes = NULL, Misc = list() ) DiscardMortality(x) <- valueDiscardMortality( MeanAtAge = NULL, MeanAtLength = NULL, Classes = NULL, Misc = list() ) DiscardMortality(x) <- value
MeanAtAge |
Numeric, numeric vector, or array, or
If Unlike |
MeanAtLength |
Numeric array or |
Classes |
Numeric vector or |
Misc |
List. Miscellaneous additional inputs. Default |
x |
A discardmortality object, or a fleet object for
|
value |
For |
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.
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.
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().
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.
discardmortality for the class definition and slot-level documentation.
Fleet() for the enclosing fleet constructor.
Selectivity(), Retention() for related fleet components.
PopulateDiscardMortality() for population details.
Other fleet:
Bioeconomic(),
Catchability(),
Effort(),
Fleet(),
Retention(),
Selectivity(),
bioeconomic-class,
catchability-class,
discardmortality-class,
effort-class,
fleet-class,
retention-class,
selectivity-class
# See man-examples/class-DiscardMortality.R# See man-examples/class-DiscardMortality.R
discardmortality S4 ClassDefines 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.
MeanAtAgenumeric 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().
MeanAtLengthnumeric array or NULL. Mean discard
mortality-at-length (Sim x Length x Year x Area). See
DiscardMortality().
Classesnumeric or NULL. Length class midpoints corresponding to
the second dimension of MeanAtLength.
Misclist. Miscellaneous additional inputs. Used internally.
DiscardMortality() for the constructor and full parameter
documentation.
fleet for the enclosing fleet object.
Selectivity(), Retention() for related fleet components.
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
DLMDataDir(stock = NA)DLMDataDir(stock = NA)
stock |
Character string representing the name of a .csv file e.g. 'Snapper', 'Rockfish' |
The file path to the object
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)
doHCR(trial_TAC, est, ref, CP = c(0, 1), CPy = c(0, 1))doHCR(trial_TAC, est, ref, CP = c(0, 1), CPy = c(0, 1))
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). |
A real number (TAC advice but theoretically could be used for effort, size limits etc).
T. Carruthers
Given an index (historical period and projected period) this function creates sparsity in the projected index to simulate varying frequency (intensity) of data collection.
doIfreq(I_hist, I_freq, LHYr, CurYr, Year)doIfreq(I_hist, I_freq, LHYr, CurYr, Year)
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. |
A thinned ector I_hist long of index observations.
T. Carruthers
MPs that perform worse than comparable MPs across all performance metrics are considered 'dominated' as other options are always preferable.
Dom(MSEobj, ..., PMlist = NULL, Refs = NULL, Yrs = NULL)Dom(MSEobj, ..., PMlist = NULL, Refs = NULL, Yrs = NULL)
MSEobj |
An object of class |
... |
Names of Performance Metrics (PMs), or other arguments to |
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 |
Yrs |
An optional named list (matching the PM names) with numeric values to override the default |
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)
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
A. Hordyk
## 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)## 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)
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.
DomeExFleetDomeExFleet
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.
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.
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.
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.
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.
Because the Retention slot is empty, PopulateRetention() sets full
retention (1.0) across all ages, lengths, simulations, and years.
Because the DiscardMortality slot is empty, PopulateDiscardMortality()
applies default discard mortality values. All discarded fish are assumed
to survive (discard mortality = 0) unless overridden.
Because Closure is NULL, PopulateClosure() applies no spatial or
temporal closures; all areas are open to fishing in all years.
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.
AlbacoreExStock, ButterfishExStock, Fleet(),
PopulateFleet(), Populate(), fleet
DomeExFleet ## Not run: PopulatedStock <- PopulateStock(AlbacoreExStock, nYear = 50, pYear = 30, nSim = 48) PopulatedFleet <- PopulateFleet(DomeExFleet, Stock = PopulatedStock, seed = 42) ## End(Not run)DomeExFleet ## Not run: PopulatedStock <- PopulateStock(AlbacoreExStock, nYear = 50, pYear = 30, nSim = 48) PopulatedFleet <- PopulateFleet(DomeExFleet, Stock = PopulatedStock, seed = 42) ## End(Not run)
Creates a TAC management recommendation given constraints on how much that can change from previous TAC and contraints on minimum and maximum TAC
doRec(MPrec, mod, delta_down, delta_up, TACrng)doRec(MPrec, mod, delta_down, delta_up, TACrng)
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). |
n object of class Rec.
T. Carruthers
Construct and manipulate an effort object defining historical
fishing effort and spatial structure for a Fleet() object.
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) <- valueEffort( 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
Effort |
Numeric array, data frame, or
If |
Units |
Character or |
Distribution |
Numeric array or |
Targeting |
Numeric array or |
Maximum |
Numeric array or |
Mode |
Character or |
TripsScalar |
Numeric array or |
AnglerPerTrip |
Numeric array or |
Misc |
List. Miscellaneous additional inputs. Default |
df |
Logical. Only used when |
x |
An effort object for accessor and replacement functions. |
value |
The replacement value for the corresponding slot. |
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.
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.
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.
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 (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 2–3
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.
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 , such that the
fleet-level retention cap is:
where 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.
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.
An effort object can be attached to a Fleet() with
Effort(Fleet) <- MyEffort and retrieved with Effort(Fleet).
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.
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
## ---- 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)## ---- 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)
effort S4 ClassDefines 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.
Effortnumeric array, data frame, or NULL. Historical fishing
effort. See Effort() for accepted formats.
Unitscharacter 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().
Distributionnumeric array or NULL. Fraction of total effort
allocated to each spatial area (Sim x Year x Area). See Effort().
Targetingnumeric array or NULL. Fleet targeting concentration
parameter (Sim x Year). See Effort().
Maximumnumeric array or NULL. Maximum allowable effort. See
Effort().
Modecharacter or NULL. Spatial utility calculation mode:
"Density" (default) or "Biomass". See Effort().
TripsScalarnumeric array or NULL. Time-varying scalar
converting the effort index to absolute angler trip
counts via (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().
AnglerPerTripnumeric 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
, where
is the bag limit (fish per angler per trip) and
is the number of trips. See Effort().
Misclist. Miscellaneous additional inputs.
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
Construct an effortdata object storing observed fishing effort and uncertainty, or access and replace individual slots.
EffortData(Name = NULL, Value = NULL, CV = NULL, Units = NULL)EffortData(Name = NULL, Value = NULL, CV = NULL, Units = NULL)
Name |
|
Value |
|
CV |
|
Units |
|
EffortData() is the standard constructor. All arguments are optional;
an empty object is valid and slots are populated later (e.g., by
GenHistData_Effort()).
Effort(data) <- EffortData(Value = myArray, CV = myCVArray)
EffortData() returns an effortdata object.
Effort() returns the Effort slot from a data object x.
Effort<- returns x with the Effort slot replaced.
effortdata for the class definition.
EffortObs() for the observation error structure that generates
effortdata objects during simulation.
GenHistData_Effort() for how Value, CV, and Units are populated
from the operating model history.
Other data:
CatchData(),
CompData(),
catchdata-class,
compdata-class,
effortdata-class
# 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"))# 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"))
effortdata S4 ClassStores 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.
Namecharacter or NULL. Names of the fleets
Valuearray or NULL. Observed effort values with dimensions
[nYear x nFleet]. See EffortData().
CVarray or NULL. Coefficients of variation matching the
dimensions of Value. See EffortData().
Unitscharacter or NULL. Units of effort measurement per fleet
(e.g., "days", "trips", "unitless"). See EffortData().
EffortData() for the constructor and full parameter documentation.
data for the enclosing data object.
Other data:
CatchData(),
CompData(),
EffortData(),
catchdata-class,
compdata-class
Construct an effortobs object defining observation error for fishing effort data, or access and replace individual slots.
EffortObs( CV = NULL, Bias = NULL, Error = NULL, Years = NULL, Units = NULL, Ref = NULL, Misc = list() )EffortObs( CV = NULL, Bias = NULL, Error = NULL, Years = NULL, Units = NULL, Ref = NULL, Misc = list() )
CV |
|
Bias |
|
Error |
|
Years |
|
Units |
|
Ref |
|
Misc |
|
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:
User-supplied Error: stored directly; CV is not used.
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.
Effort(obs) <- EffortObs(CV = 0.15)
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.
Other obs:
CatchObs(),
CompObs(),
ExploitationObs(),
IndicesObs(),
LifeHistoryObs(),
Obs(),
catchobs-class,
compobs-class,
effortobs-class,
exploitationobs-class,
indicesobs-class,
lifehistoryobs-class,
obs-class
# 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))# 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))
effortobs S4 ClassDefines 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.
CVnumeric or NULL. Coefficient of variation of effort observation
error. See EffortObs().
Errornumeric array or NULL. Realised lognormal observation error
multipliers (nSim x nYear). Populated internally during simulation;
see EffortObs().
Biasnumeric or NULL. Multiplicative observation bias. See
EffortObs().
Yearsnumeric or NULL. Calendar years over which the observation
error applies. See EffortObs().
Unitscharacter or NULL. Units of fishing effort
(e.g., "hours", "trips"). See EffortObs().
Refnumeric array or NULL. Reference effort values, one per
simulation. See EffortObs().
Misclist. Miscellaneous additional objects.
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
An all-purpose empirical MP that runs of Indices of relative abundance
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 )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 )
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, )) |
An object of class MP.
T. Carruthers
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.
EmptyObject(object)EmptyObject(object)
object |
An S4 object, or any R object. For S4 objects, Otherwise it inspects every slot recursively:
For non-S4 objects,
|
A length-1 logical.
# 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))# 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))
equilibrium S4 ClassAn 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().
All F-dependent slots are obtained by multiplying the corresponding per-recruit quantity from a perrecruit object by equilibrium recruitment:
where is the relative recruitment function from the stock's
SRR() and is unfished recruitment. Values of
RelRecruits below zero are floored at zero before scaling.
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.
apicalFNumeric vector of apical fishing mortality values at
which equilibrium quantities were evaluated. Length nF.
SPR0Spawning-per-recruit at unfished conditions.
Array (Sim × Stock × Year).
SPRSpawning-per-recruit relative to unfished, i.e.
SPRF / SPR0. Array (Sim × Stock × Year × F).
RelRecruitsRelative recruitment from the stock-recruitment
relationship, evaluated at each SPR value.
Array (Sim × Stock × Year × F).
RecruitsAbsolute equilibrium recruitment (R0 × RelRecruits).
Array (Sim × Stock × Year × F).
NumberAbsolute equilibrium numbers-at-age
(NPRF × Recruits), summed over the age dimension.
Array (Sim × Stock × Year × F).
BiomassAbsolute equilibrium total biomass.
Array (Sim × Stock × Year × F).
SBiomassAbsolute equilibrium spawning biomass.
Array (Sim × Stock × Year × F).
SProductionAbsolute equilibrium spawning production, computed from
fecundity-at-age rather than weight × maturity.
Array (Sim × Stock × Year × F).
RemovalsAbsolute equilibrium total removals (landings + dead
discards), summed over fleets. Array (Sim × Stock × Year × F).
LandingsAbsolute equilibrium landings, summed over fleets.
Array (Sim × Stock × Year × F).
MiscList reserved for internal use.
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.
CurrentEffort(Data) CurrentCatch(Data) CurrentLandings(Data) AverageCatch(Data) ExampleMPs()CurrentEffort(Data) CurrentCatch(Data) CurrentLandings(Data) AverageCatch(Data) ExampleMPs()
Data |
A data object containing historical observations. |
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.
CurrentEffort, CurrentCatch, AverageCatch — an advice
object; see Advice() for constructor details.
ExampleMPs — a character vector of the example MP names.
Advice(), CheckCatch(), data, advice
## Not run: MSE <- runMSE(SingleStockOM, MPs=ExampleMPs()) ## End(Not run)## Not run: MSE <- runMSE(SingleStockOM, MPs=ExampleMPs()) ## End(Not run)
exploitationdata ClassGroups 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.
ExploitationData()ExploitationData()
ExploitationData() returns a exploitationdata object.
SelectivityAn object of class selectivity defining the age- or length-based selectivity pattern for each fleet.
RetentionAn object of class retention defining the probability of retaining a fish of a given age or length once caught.
DiscardMortalityAn object of class discardmortality defining the mortality rate of discarded fish by age or length.
MiscA named list for any additional exploitation-level metadata.
ExploitationData() creates a new exploitationdata object.
Construct an exploitationobs object defining observation error for exploitation process parameters.
ExploitationObs( Selectivity = list(), Retention = list(), DiscardMortality = list(), Misc = list() )ExploitationObs( Selectivity = list(), Retention = list(), DiscardMortality = list(), Misc = list() )
Selectivity |
|
Retention |
|
DiscardMortality |
|
Misc |
|
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.
An exploitationobs object.
exploitationobs for the class definition.
Obs() for the enclosing observation model constructor.
exploitationdata for the complementary observed-values class.
Other obs:
CatchObs(),
CompObs(),
EffortObs(),
IndicesObs(),
LifeHistoryObs(),
Obs(),
catchobs-class,
compobs-class,
effortobs-class,
exploitationobs-class,
indicesobs-class,
lifehistoryobs-class,
obs-class
eo <- ExploitationObs()eo <- ExploitationObs()
exploitationobs S4 ClassDefines 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().
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.
Selectivitylist. Observation error specification for selectivity.
See ExploitationObs().
Retentionlist. Observation error specification for retention.
See ExploitationObs().
DiscardMortalitylist. Observation error specification for discard
mortality. See ExploitationObs().
Misclist. Miscellaneous additional objects.
ExploitationObs() for the constructor.
obs for the enclosing object.
exploitationdata for the complementary observed-values class.
Other obs:
CatchObs(),
CompObs(),
EffortObs(),
ExploitationObs(),
IndicesObs(),
LifeHistoryObs(),
Obs(),
catchobs-class,
compobs-class,
effortobs-class,
indicesobs-class,
lifehistoryobs-class,
obs-class
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.
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)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)
array |
An |
nSim |
Integer. Total number of simulations, or |
AgeClasses |
Numeric vector of age classes, or |
Classes |
Numeric vector of size classes (length or weight bins), or
|
Years |
Numeric vector of |
Areas |
Numeric vector of area indices ( |
default |
Default fill value for forward-filled years. If |
backfill |
Logical. If |
maintain_seasonal_pattern |
Logical. Seasonal models only.
If |
skip_data |
|
debug |
Logical. If |
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.
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.
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.
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().
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.
The input object with dimensions extended as specified. The return type matches the input type (array, S4, or list).
ExtendSims(), ExtendAges(), ExtendClasses(),
ExtendYears(), ExtendAreas()
# 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)# 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)
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).
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)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)
Hist |
A hist object; the output of |
type |
Character. One of
|
Reduce |
Logical. If |
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.
ReduceDims() for details on dimension collapsing.
What MPs may be run (best case scenario) for various data-availability scenarios and management constraints?
Fease( Data = NULL, TAC = TRUE, TAE = TRUE, SL = TRUE, Spatial = TRUE, names.only = TRUE, msg = TRUE, include.ref = FALSE )Fease( Data = NULL, TAC = TRUE, TAE = TRUE, SL = TRUE, Spatial = TRUE, names.only = TRUE, msg = TRUE, include.ref = FALSE )
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 |
Either a vector of MP names that are feasible for the fishery (default) or a 3 column data frame (names.only=FALSE).
T. Carruthers & A. Hordyk
## Not run: Fease(TAC=FALSE) Fease(SL=FALSE, Spatial=FALSE) Fease(Atlantic_mackerel, TAE=FALSE, names.only=FALSE) ## End(Not run)## Not run: Fease(TAC=FALSE) Fease(SL=FALSE, Spatial=FALSE) Fease(Atlantic_mackerel, TAE=FALSE, names.only=FALSE) ## End(Not run)
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.
Fecundity( Pars = list(), Model = NULL, Units = "eggs", MeanAtAge = NULL, MeanAtLength = NULL, Classes = NULL, Timing = NULL, Misc = list() ) Fecundity(x) <- valueFecundity( Pars = list(), Model = NULL, Units = "eggs", MeanAtAge = NULL, MeanAtLength = NULL, Classes = NULL, Timing = NULL, Misc = list() ) Fecundity(x) <- value
Pars |
|
Model |
|
Units |
|
MeanAtAge |
|
MeanAtLength |
|
Classes |
|
Timing |
|
Misc |
|
x |
A fecundity object for slot accessors, or a stock
object for |
value |
For |
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.
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)
)
)
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().
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
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
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.
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
# 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)# 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)
fecundity S4 ClassDefines 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.
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.
Parslist. 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.
Modelfunction or character(1). Fecundity model identifier,
matched to one of FecundityModels(). Set automatically by FindModel()
when Pars is supplied without an explicit model.
Unitscharacter(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.
MeanAtAgearray. 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.
MeanAtLengtharray. 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.
Classesnumeric. Age or length class midpoints corresponding to the
MeanAt* array in use.
Timingarray 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().
Misclist. Used internally.
Fecundity() for the constructor and accessor functions.
FecundityModels() for available models and their required parameters.
ValidUnits() for accepted unit strings.
Populate() for array population.
FindModel() for automatic model inference.
Length() and Weight() for the companion schedules used in the
default spawning biomass calculation and at-length fecundity models.
Maturity() for the maturity schedule multiplied through fecundity
during population.
SRR() for spawning timing within the time step.
Specifying Biological and Fleet Schedules for the
full description of how Pars, Model, and MeanAt* arrays interact.
Other fecundity:
Fecundity()
Logistic fecundity-at-age, fecundity-at-length, and fecundity-at-weight
models for use in a Fecundity() object.
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)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)
Ages |
numeric vector of age classes (for age-based models) |
A50 |
age at 50% maximum fecundity (Logistic-at-Age) |
A50_95 |
interval between |
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 |
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)? |
All fecundity models use a logistic 50/95 parameterisation:
where .
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.
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
Fecundity(), Maturity(), Ages(), Length(), Weight(),
Stock()
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")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")
FInteract(), FDead(), and FRetain() extract fishing mortality for
interactions (encounters), killed, and retained fish
respectively, from a hist or mse object.
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 )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 )
object |
|
df |
Logical. If |
byAge |
Logical. If |
byArea |
Logical. If |
byFleet |
Logical. If |
Reduce |
Logical. If |
IncYear |
Logical. Passed to |
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".
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.
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)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)
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.
FitMovement(Spatial, sim = 1, age = 1, year = 1)FitMovement(Spatial, sim = 1, age = 1, year = 1)
Spatial |
A populated spatial object whose |
sim |
|
age |
|
year |
|
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.
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.
Spatial() for the constructor and full spatial specification.
FitMovement_2_Area() for the two-area optimisation.
FitMovement_Multi_Area() for the multi-area optimisation.
Populate() which calls this function internally.
Estimates the covariance of log-targeting deviations from historical
targeting weights stored in OM@StockTargeting@Targeting, as produced
by StandardizeEffort().
FitStockTargeting(OM, tol = 1e-06, active_thresh = 0.1)FitStockTargeting(OM, tol = 1e-06, active_thresh = 0.1)
OM |
An operating model object (om) with a populated
|
tol |
|
active_thresh |
|
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):
Stock targeting deviations are the multiplicative departures from this fleet mean:
The stationary covariance is estimated from
across historical years for stocks that are
consistently active (positive targeting in strictly more than
active_thresh proportion of years). Element
captures the co-variation in log-targeting deviations between stocks
and for fleet .
The function returns OM unchanged if @Mean and @Covariance are
already fully populated, or if nStock == 1.
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.
StandardizeEffort(), GenerateStockTargeting()
Construct and manipulate a fleet object defining the exploitation characteristics of a fleet for a stock in an operating model.
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) <- valueFleet( 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
Name |
Character or |
Effort |
An effort object defining historical fishing effort,
spatial distribution, and targeting. See |
Catchability |
A catchability object defining gear efficiency
and optional projected-year stochasticity or trends. See |
Selectivity |
A selectivity object defining
selectivity-at-age, -at-length, or -at-weight. Required for all fleets.
See |
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 |
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
|
Closure |
Numeric array or |
WeightFleet |
Numeric array or |
Bioeconomic |
A bioeconomic object. Not currently used. Default is an empty bioeconomic. |
Dynamics |
List. Reserved for future use for fleet dynamics model
parameters. Default |
Misc |
List. Miscellaneous additional inputs. Default |
x |
|
value |
A fleet object or named list of fleet objects
for |
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.
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.
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.
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.
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 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().
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.
fleet for the class definition and slot-level documentation.
OM() for the operating model constructor.
Effort(), Catchability(), Selectivity(), Retention(),
DiscardMortality() for sub-object constructors.
PopulateFleet() for how fleet components are expanded across
simulations and years.
Other fleet:
Bioeconomic(),
Catchability(),
DiscardMortality(),
Effort(),
Retention(),
Selectivity(),
bioeconomic-class,
catchability-class,
discardmortality-class,
effort-class,
fleet-class,
retention-class,
selectivity-class
# See man-examples/class-Fleet.R# See man-examples/class-Fleet.R
fleet S4 ClassDefines 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.
Namecharacter or NULL. Unique fleet identifier.
EffortAn effort object defining historical fishing effort,
spatial distribution, and targeting behaviour. See Effort().
CatchabilityA catchability object defining gear efficiency
and optional projected-year trends or stochasticity. See Catchability().
SelectivityA selectivity object defining selectivity-at-age,
-at-length, or -at-weight. Required for all fleets. See Selectivity().
RetentionA retention object defining retention-at-age,
-at-length, or -at-weight. Optional; defaults to full retention if not
supplied. See Retention().
DiscardMortalityA discardmortality object defining the
proportion of discarded catch that dies. Optional; defaults to 0 (all
discards survive) if not supplied. See DiscardMortality().
Closurenumeric 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().
WeightFleetnumeric 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().
BioeconomicA bioeconomic object. Not currently used.
DynamicsList. Reserved for future use for fleet dynamics model
parameters. Default list(). Not currently used.#'
nYearnumeric or NULL. Number of years. Inherited from the paired
stock during PopulateFleet().
pYearnumeric or NULL. Number of projection years. Inherited from
the paired stock during PopulateFleet().
nSimnumeric or NULL. Number of simulation replicates. Inherited
from the paired stock during PopulateFleet().
CurrentYearnumeric or NULL. Current calendar year. Inherited
from the paired stock during PopulateFleet().
Yearsnumeric or NULL. Full year vector (historical and
projected). Inherited from the paired stock during
PopulateFleet().
Seasonsnumeric or NULL. Number of seasons. Inherited from the paired
stock during PopulateFleet().
Misclist. Miscellaneous additional inputs.
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
'Fleet'
The component of the operating model that controls fishing dynamics
NameIdentifying name for the fleet. Usually includes location and gear type.
nyearsThe 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.
CurrentYrThe 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.
EffYearsVector 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).
EffLowerLower 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).
EffUpperUpper 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).
EsdAdditional 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.
qincMean 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.
qcvInter-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.
L5Shortest 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.
LFSShortest 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.
VmaxlenProportion 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.
isRelSpecify whether selection and retention parameters use absolute lengths or relative to the size of maturity. Single logical value (TRUE or FALSE).
LR5Shortest 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.
LFRShortest 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.
RmaxlenProportion 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.
DRDiscard 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_targDistribution 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.
MPALogical argument (TRUE or FALSE). Creates an MPA in Area 1 for all years if true is selected. Defaults to FALSE.
MiscMiscellaneous list for bio-economic parameters
Objects can be created by calls of the form new('Fleet')
T. Carruthers and A. Hordyk
showClass('Fleet')showClass('Fleet')
A data.frame with description of slots for class Fleet
FleetDescriptionFleetDescription
An object of class data.frame with 20 rows and 2 columns.
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.
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)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)
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? |
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!
An object of class Rec with the TAC slot populated with a numeric vector of length reps
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
See Data-legacy for information on the Data object
T. Carruthers, A. Hordyk
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)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)
Simulates stochastic stock-specific targeting multipliers for each fleet using independent multivariate lognormal draws at each time step.
GenerateStockTargeting( OM, Period = c("Historical", "Projection"), TruncSD = 2, n_recent = 5, seed = 101 )GenerateStockTargeting( OM, Period = c("Historical", "Projection"), TruncSD = 2, n_recent = 5, seed = 101 )
OM |
An operating model object (om) containing a populated
|
Period |
Character string specifying which period to simulate:
|
TruncSD |
|
n_recent |
|
seed |
|
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:
where:
is the targeting multiplier for stock at
time
is the log-space deviation for stock
at time , drawn from the multivariate normal with mean zero and
covariance
is the stationary covariance matrix of
log-targeting deviations estimated by FitStockTargeting()
is the
lognormal bias correction for stock , where is the fitted log-scale mean from
FitStockTargeting() and is
the marginal variance. This ensures , preserving the historical mean targeting level for
each stock on the natural scale.
Deviations are truncated to
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
throughout.
FitStockTargeting(), StandardizeEffort()
## Not run: OM <- GenerateStockTargeting(OM, Period = "Projection") OM <- GenerateStockTargeting(OM, Period = "Projection", TruncSD = 2, n_recent = 5) ## End(Not run)## Not run: OM <- GenerateStockTargeting(OM, Period = "Projection") OM <- GenerateStockTargeting(OM, Period = "Projection", TruncSD = 2, n_recent = 5) ## End(Not run)
Example objects of class Obs
Generic_Obs Imprecise_Biased Imprecise_Unbiased Perfect_Info Precise_Biased Precise_UnbiasedGeneric_Obs Imprecise_Biased Imprecise_Unbiased Perfect_Info Precise_Biased Precise_Unbiased
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.
avail("Obs")avail("Obs")
Generates stochastic historical fishing effort trajectories from an
data.frame containing effort control points.
GenHistEffort(Effort, nSim = 5, Years = NULL)GenHistEffort(Effort, nSim = 5, Years = NULL)
Effort |
A
|
nSim |
Integer. Number of stochastic effort simulations to generate. |
Years |
Optional integer vector of calendar years defining the full
effort time series. Required if |
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:
Effort at each control year is drawn independently from a
uniform distribution between Lower and Upper.
Effort is linearly interpolated to annual resolution across
Years.
If CV is non-NULL, multiplicative lognormal
process error is applied with mean 1.
The resulting effort trajectory is normalised so that effort in the final year equals 1.
An nSim x nYear numeric array used in an Effort() object
These functions generate simulated "mean at" arrays using a model and parameters.
GenMeanAtAge(Model, Pars, Ages) GenMeanAtLength(Model, Pars, Length) GenMeanAtWeight(Model, Pars, Weight)GenMeanAtAge(Model, Pars, Ages) GenMeanAtLength(Model, Pars, Length) GenMeanAtWeight(Model, Pars, Weight)
Model |
A character string naming a built-in model or a valid R function. |
Pars |
A named |
Ages |
Numeric vector of age classes (for |
Length |
Numeric vector of length classes (for |
Weight |
Numeric vector of weight classes (for |
A numeric array with dimensions: Sim, Age/Class, Year, and
sometimes Area.
LengthModels(), WeightModels(), NaturalMortalityModels(),
MaturityModels, FecundityModels(), SelectivityModels(),
RetentionModels()
# 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)# 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)
Generates stochastic recruitment deviations for multiple stocks using a multivariate lognormal AR(1) process, preserving both cross-stock covariance and temporal autocorrelation.
GenMultiStockRecDevs(OM, TruncSD = 2, silent = FALSE)GenMultiStockRecDevs(OM, TruncSD = 2, silent = FALSE)
OM |
An operating model object of class om. |
TruncSD |
Numeric scalar. Number of standard deviations at which to
truncate the innovation distribution. Defaults to |
silent |
|
Deviations are simulated in log-space:
where:
is a bias-corrected mean
is a diagonal matrix of lag-1 autocorrelation coefficients
The innovation covariance matrix is derived from the
stationary covariance using CalcInnovationCov().
The function proceeds as follows for each simulation:
Extract stock-specific parameters (sd, ac, mu)
Impute missing historical deviations using univariate AR(1)
Estimate stationary covariance from historical log deviations
Compute innovation covariance via CalcInnovationCov()
Simulate projection deviations using a multivariate AR(1) process
Truncation is applied to the innovation term , not the
deviations themselves.
The input OM object with RecDevProj populated for all stocks
and simulations.
CalcInnovationCov(), AddAutoCorrelation()
Generate recruitment deviations for initial ages, historical years, and projected years, with optional auto-correlation and truncation.
GenRecDevs( SD = 0.2, AC = 0, TruncSD = 2, Ages = NULL, HistYears = NULL, ProjYears = NULL, nSim = 48, RecDevInit = NULL, RecDevHist = NULL, RecDevProj = NULL )GenRecDevs( SD = 0.2, AC = 0, TruncSD = 2, Ages = NULL, HistYears = NULL, ProjYears = NULL, nSim = 48, RecDevInit = NULL, RecDevHist = NULL, RecDevProj = NULL )
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 |
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.
If |
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.
## 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)## 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 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().
GenResiduals( SD, AC, Years, nSim = NULL, TruncSD = 2, nSeasons = 1, NA_Season = list() )GenResiduals( SD, AC, Years, nSim = NULL, TruncSD = 2, nSeasons = 1, NA_Season = list() )
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 |
Numeric array of dimensions nSim x nYear containing truncated log-normal residuals.
ApplyAC(), CalcResidualStats()
Internal function for determining if object is of classy
getclass(x, classy)getclass(x, classy)
x |
Character string object name |
classy |
A class of object (character string, e.g. 'Fleet') |
TRUE or FALSE
T. Carruthers with nasty hacks from A. Hordyk
Get part of an MP specific data-list
getDataList(MSElist, mm)getDataList(MSElist, mm)
MSElist |
A hierarchical list [Stock][Fleet][MP] |
mm |
integer the MP number |
a sublist of MSElist for a specific MP
Extract the first dimension of a hierarchical list of recommendation objects
getfirstlev(x, name, pp, ff)getfirstlev(x, name, pp, ff)
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) |
T. Carruthers
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
GetMetaData(OM, Period = c("Historical", "Projection", "All"), Years = NULL)GetMetaData(OM, Period = c("Historical", "Projection", "All"), Years = NULL)
OM |
An operating model object. |
Period |
Character string specifying the model period. Must be one
of |
Years |
Optional vector of years to subset the OM. If |
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)
## Not run: meta <- GetMetaData(MyOM, Period = "Historical") meta$nSim meta$AgeClasses ## End(Not run)## Not run: meta <- GetMetaData(MyOM, Period = "Historical") meta$nSim meta$AgeClasses ## End(Not run)
The user specifies the probability of staying in the same area and spatial heterogeneity (both in the unfished state).
getmov2(x, Prob_staying, Frac_area_1)getmov2(x, Prob_staying, Frac_area_1)
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) |
This is paired with movfit to find the correct movement model.
A markov movement matrix
T. Carruthers
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?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?
Calls dynGet(), then get() in order to find the MP definition in the R session.
getMP(MP)getMP(MP)
MP |
Character of MP name |
The function definition or an error message from try() if unsuccessful
Q. Huynh
Count independent variables for a MICE relationship at position x in a Rel list
getnIVs(x, Rel)getnIVs(x, Rel)
x |
Position of a MICE relationship in the list Rel (MOM@Rel) |
Rel |
The list of MICE relationships (MOM@Rel) |
T.Carruthers
Calculate selectivity curve
getsel(x, lens, lfs, sls, srs)getsel(x, lens, lfs, sls, srs)
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) |
Reads biological reference points from one or more Stock Synthesis (SS3)
model outputs and returns the requested quantities from the
derived_quants table.
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") )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") )
SSDir |
One of:
|
Labels |
Character vector of
|
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.
Convert stock recruit parameters from steepness parameterization to alpha/beta (and vice versa)
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)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)
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 |
beta |
Beta parameter |
h |
Steepness parameter |
R0 |
Unfished recruitment parameter |
The Type 1 Beverton-Holt equation is
The Type 2 Beverton-Holt equation is
The Ricker equation is
A numeric.
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
Q. Huynh
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.
expandHerm(Herm, maxage, np, nsim) checkHerm(Herm, maxage, nsim, nyears, proyears) subsetHerm(Herm, y)expandHerm(Herm, maxage, np, nsim) checkHerm(Herm, maxage, nsim, nyears, proyears) subsetHerm(Herm, y)
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 |
T. Carruthers
Q. Huynh
hist Class and AccessorThe 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.
Hist(MSE = NULL)Hist(MSE = NULL)
MSE |
An mse object. If |
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.
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.
hist, mse, timeseries, Simulate()
hist ClassThe 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.
OMThe om object used to generate the historical time-series.
UnfishedAn 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.
ReferenceA reference object containing biological and management reference points.
DataA nested named list of data objects containing historical observations generated during the spool-up phase. The list has two levels:
LogInternal named list storing diagnostics, warnings, and bookkeeping information generated during the historical simulation. Not intended for direct user access.
MiscNamed list for carrying arbitrary additional objects alongside the historical results. Useful for attaching model-specific diagnostics or intermediate outputs.
NumberList of numbers-at-age arrays, one element per stock.
Each array has dimensions Sim × Age × Year × Area.
BiomassTotal biomass array with dimensions Sim × Stock × Year.
SBiomassSpawning biomass array with dimensions Sim × Stock × Year.
SProductionSpawning production array with dimensions
Sim × Stock × Year.
InteractionsTotal biomass interacting with fishing gear, by stock and
fleet. Array with dimensions Sim × Stock × Year × Fleet.
LandingsTotal landed biomass by stock and fleet. Array with
dimensions Sim × Stock × Year × Fleet.
DiscardsTotal discarded biomass by stock and fleet. Array with
dimensions Sim × Stock × Year × Fleet.
InteractAtAgeList of interactions-at-age arrays (numbers), one
element per stock. Each array has dimensions
Sim × Age × Year × Fleet × Area.
LandingsAtAgeList of landings-at-age arrays (numbers), one element
per stock. Each array has dimensions Sim × Age × Year × Fleet × Area.
DiscardsAtAgeList of discards-at-age arrays (numbers), one element
per stock. Each array has dimensions Sim × Age × Year × Fleet × Area.
LandingsAtSizeNested list of landings-at-size arrays (numbers),
indexed by stock then fleet. Each array has dimensions
Sim × Class × Year × Area.
DiscardsAtSizeNested list of discards-at-size arrays (numbers),
indexed by stock then fleet. Each array has dimensions
Sim × Class × Year × Area.
EffortFishing effort array with dimensions Sim × Year × Fleet.
DistributionFleet effort distribution across areas. Array with
dimensions Sim × Year × Fleet × Area.
FInteractApical fishing mortality for fish that interact with the
fishing gear. Array with dimensions Sim × Stock × Year × Fleet
(array.null).
FDeadApical fishing mortality for fish killed by the fishing gear.
Array with dimensions Sim × Stock × Year × Fleet (array.null).
FRetainApical fishing mortality for fish retained by fishers. Array
with dimensions Sim × Stock × Year × Fleet (array.null).
FInteractAreaArea- 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).
FDeadAreaArea- 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).
FRetainAreaArea- 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).
om, unfished, reference, timeseries, data, popdynamics
'Hist'
An object for storing information generated by the end of the historical simulations
DataThe Data object at the end of the historical period
OMParsA numeric data.frame with nsim rows with sampled Stock, Fleet, Obs, and Imp parameters.
AtAgeA 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
TSdataA 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
RefA 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
SampParsA named list with all sampled Stock, Fleet, Obs, and Imp parameters
OMThe OM object (without cpars)
MiscA list for additional information
A. Hordyk
Produces a blank plot if all values in x are equal
hist2(x, col, axes = FALSE, main = "", breaks = 10, cex.main = 1)hist2(x, col, axes = FALSE, main = "", breaks = 10, cex.main = 1)
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 |
A data.frame with description of slots for class Hist
HistDescriptionHistDescription
An object of class data.frame with 76 rows and 2 columns.
Construct an imp object defining implementation error for TAC,
effort, and size-based management controls, or extract the Imp slot from
an enclosing object.
Imp(Name = NULL, TAC = NULL, Effort = NULL, Size = NULL, Misc = list())Imp(Name = NULL, TAC = NULL, Effort = NULL, Size = NULL, Misc = list())
Name |
If |
TAC |
An impslot object, or |
Effort |
An impslot object, or |
Size |
An impslot object, or |
Misc |
List. Miscellaneous additional objects. Default |
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
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.
The imp is currently a placeholder. The class interface is subject to change.
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.
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
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.
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.
NameCharacter. Name of the implementation error model.
See Imp().
TACAn impslot object. Implementation error for total
allowable catch recommendations. See Imp().
EffortAn impslot object. Implementation error for
effort-based controls. See Imp().
SizeAn impslot object. Implementation error for size-based
regulations. See Imp().
MiscList. Miscellaneous additional objects.
The imp is currently a placeholder. The class interface is subject to change.
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
'Imp'
An operating model component that specifies the degree of adherence to management recommendations (Implementation error)
NameThe name of the Implementation error object. Single value. Character string.
NameThe name of the Implementation error object. Single value. Character string.
TACFracMean 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.
TACSDLog-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.
TAEFracMean 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.
TAESDLog-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.
SizeLimFracMean 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.
SizeLimSDLog-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 can be created by calls of the form
new('Imp')#'
T. Carruthers and A. Hordyk
showClass('Imp')showClass('Imp')
A data.frame with description of slots for class Imp
ImpDescriptionImpDescription
An object of class data.frame with 7 rows and 2 columns.
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.
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"))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"))
Stock |
Character string matching a stock name available in |
nSim |
Integer. Number of simulations. Default |
pYear |
Integer. Number of projection years. Default |
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 |
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 |
SurveyNames |
A character vector of user-facing names for survey
indices detected in |
UnitsLandings |
A character vector of length equal to the number of landings fleets detected. Each element must be one of:
|
UnitsDiscards |
A character vector of length equal to the number of
discard fleets detected. Accepts the same values as |
populate |
Logical. If |
silent |
Logical. If |
type |
Character. Format of BAM output to retrieve: |
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 name matching the retain fleet names in the OM.
Discard mortality rate (0–1).
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.
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.
ImportBAMData( OM, BAMdata, SurveyNames = NULL, UnitsLandings = NULL, UnitsDiscards = NULL, DiscFleets = NULL )ImportBAMData( OM, BAMdata, SurveyNames = NULL, UnitsLandings = NULL, UnitsDiscards = NULL, DiscFleets = NULL )
OM |
An om object. |
BAMdata |
A named list returned by |
SurveyNames |
A character vector of user-facing names for survey
indices detected in |
UnitsLandings |
A named character vector or list mapping fleet names to
unit strings. Names must be a subset of
|
UnitsDiscards |
A named character vector or list following the same
convention as |
DiscFleets |
A character vector of BAM discard column name stubs used
to rename discard fleets after import. Names are expected in the form
|
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.
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.
Composition data are not yet imported. Planned sources are
BAMdata$comp.mats$*age* (age composition) and
BAMdata$comp.mats$lcomp.*.ob (length composition).
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.
GetBAMOutput(), Data(), CatchData(), Obs()
## 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)## 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 3 (SS3) model and convert it
into an OM() object.
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, ... )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, ... )
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 |
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 |
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). |
Sponsor |
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 |
Interval |
Integer specifying the number of years between management actions. |
DataLag |
Integer specifying the observation lag in years. |
silent |
Logical; if |
Populate |
Logical; if |
... |
Additional arguments passed to SS3 import functions. |
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.
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.
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.
https://nmfs-ost.github.io/ss3-website/ (Stock Synthesis 3)
## 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)## 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)
Reads a parsed SS3 report and populates a data object with catch, index, and composition data.
ImportSSData( SSDir, Name = "Imported by ImportSSData", CommonName = "", Species = "", silent = FALSE, ... )ImportSSData( SSDir, Name = "Imported by ImportSSData", CommonName = "", Species = "", silent = FALSE, ... )
SSDir |
Character vector of SS3 report directories, or a pre-parsed
|
Name |
Character; name for the |
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 |
A populated Data() object
Import SS3 Report directories with optional parallel processing
ImportSSReport(SSDir, parallel = FALSE, silent = FALSE, ...)ImportSSReport(SSDir, parallel = FALSE, silent = FALSE, ...)
SSDir |
Character vector of SS3 report directories, or a pre-parsed
|
parallel |
Logical; whether to use parallel processing (default FALSE) |
silent |
Logical; suppress progress messages (default FALSE) |
... |
Additional arguments passed to |
A named RepList object: a list of parsed r4ss::SS_output lists,
one per SS3 directory, with integer-character names ("1", "2", ...)
ImportSS(), SetupParallel(), DisableParallel()
Construct an impslot object representing implementation uncertainty for a single management control, or access and replace individual slots.
ImpSlot(Mean = NULL, SD = NULL, Compliance = NULL, Error = NULL, Misc = list())ImpSlot(Mean = NULL, SD = NULL, Compliance = NULL, Error = NULL, Misc = list())
Mean |
Numeric array or list of arrays, or |
SD |
Numeric array or list of arrays, or |
Compliance |
Numeric array or list of arrays, or |
Error |
Numeric array or list of arrays, or |
Misc |
List. Miscellaneous additional objects. Default |
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.
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.
The impslot and its enclosing imp are currently placeholders. Dimensional requirements and validation rules will be formalised in a future release.
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.
impslot for the class definition.
Imp() for the enclosing constructor and accessor.
TAC(), Effort(), Size() for slot-level accessors on
imp objects.
Other imp:
Imp(),
imp-class,
impslot-class
# 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)))# 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)))
indicesdata S4 ClassStores 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.
IndicesData() returns a indicesdata object.
NameOptional character string. Name of the index.
ValueNumeric array of observed index values, with dimensions
[nYear, nIndex], where nYear represents the total number of time steps.
CVNumeric array of coefficients of variation (CVs) for the index
observations, matching the dimensions of Value.
UnitsOptional character string. Units of the index
(e.g., "kg/trip", "numbers/tow").
RefNumeric vector of length nIndex giving a reference value for
each index (e.g., a historical mean or target level).
RefCVNumeric array of CVs for the reference values, matching the
dimensions of Ref.
TimingNumeric vector of length nIndex giving the within-year
timing of each observation as a fraction of the year (0–1).
SelectivityAn array or character specification mapping each index to a fleet selectivity or defining an independent selectivity curve.
MiscA named list for any additional index-level metadata.
IndicesData() creates a new indicesdata object.
Construct an indicesobs object defining observation error for a CPUE or survey abundance index, or access and replace individual slots.
IndicesObs( CV = NULL, Error = NULL, Areas = NULL, Units = NULL, Selectivity = NULL, TruncSD = 2, Ref = NULL, Beta = NULL, AC = NULL, Misc = list() )IndicesObs( CV = NULL, Error = NULL, Areas = NULL, Units = NULL, Selectivity = NULL, TruncSD = 2, Ref = NULL, Beta = NULL, AC = NULL, Misc = list() )
CV |
When conditioning on real data via |
Error |
|
Areas |
|
Units |
|
Selectivity |
Selectivity specification for this index. Accepted forms:
|
TruncSD |
|
Ref |
|
Beta |
|
AC |
|
Misc |
|
The Error array (nSim x nYear) is obtained in one of three ways, in
order of precedence:
User-supplied Error: stored directly; CV is not used.
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.
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.
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.
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.
CPUE(obs) <- IndicesObs(CV = 0.3) Survey(obs) <- IndicesObs(CV = 0.2, Selectivity = "SBiomass")
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.
indicesobs for the class definition and slot-level documentation.
Obs() for the enclosing observation model constructor.
CalcResidualStats() for residual statistic computation.
GenResiduals(), ApplyAC() for projection error generation.
ConditionObs() for how slots are estimated from real data.
Other obs:
CatchObs(),
CompObs(),
EffortObs(),
ExploitationObs(),
LifeHistoryObs(),
Obs(),
catchobs-class,
compobs-class,
effortobs-class,
exploitationobs-class,
indicesobs-class,
lifehistoryobs-class,
obs-class
# 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"))# 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"))
indicesobs S4 ClassDefines 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.
CVnumeric or NULL. Coefficient of variation of index observation
error. See IndicesObs().
Errornumeric 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().
Betanumeric array or NULL. Hyperstability/hyperdepletion
parameter. Reserved for future use; currently not implemented. See
IndicesObs().
ACnumeric 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().
Yearsnumeric or NULL. Calendar years over which the observation
error is conditioned. See IndicesObs().
Areasnumeric or NULL. Integer indices of the spatial areas
contributing to this index. See IndicesObs().
Unitscharacter or NULL. Units of the index ("Biomass",
"Number", or "Recruitment"). See IndicesObs().
Selectivityarray, character, numeric, or list. Selectivity
specification for this index. See IndicesObs().
Typecharacter. Index type identifier. See IndicesObs().
Refnumeric array or NULL. Reference index value, one per
simulation. See IndicesObs().
Efficiencynumeric 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.
TruncSDnumeric(1) or NULL. Number of standard deviations at
which to truncate the lognormal residual distribution when generating
projection errors. Default 2. See IndicesObs().
Statsdata.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.
Misclist. Miscellaneous additional objects.
IndicesObs() for the constructor and full parameter
documentation.
obs for the enclosing observation model object.
CalcResidualStats() for how Stats is computed.
Other obs:
CatchObs(),
CompObs(),
EffortObs(),
ExploitationObs(),
IndicesObs(),
LifeHistoryObs(),
Obs(),
catchobs-class,
compobs-class,
effortobs-class,
exploitationobs-class,
lifehistoryobs-class,
obs-class
initialize ~~~~ Methods for Function initialize ~~
%% ~~describe this method here~~
%% ~~describe this method here~~
%% ~~describe this method here~~
%% ~~describe this method here~~
%% ~~describe this method here~~
%% ~~describe this method here~~
%% ~~describe this method here~~
%% ~~describe this method here~~
Runs a set of input control methods are returns the output in a single table
Input(Data, MPs = NA, reps = 100, timelimit = 10, CheckMPs = TRUE, msg = TRUE)Input(Data, MPs = NA, reps = 100, timelimit = 10, CheckMPs = TRUE, msg = TRUE)
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? |
A. Hordyk
## Not run: library(MSEtool) Input(MSEtool::Cobia) ## End(Not run)## Not run: library(MSEtool) Input(MSEtool::Cobia) ## End(Not run)
Internal functions for reading iSCAM input and output files into R
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)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)
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 |
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
Chris Grandin (DFO PBS)
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).
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" )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" )
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? |
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
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.
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
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.
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.
T. Carruthers, Q. Huynh
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).
iSCAMcomps(replist, Year)iSCAMcomps(replist, Year)
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 |
T. Carruthers
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).
iSCAMinds(idata, Year, fleeteffect = T)iSCAMinds(idata, Year, fleeteffect = T)
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? |
T. Carruthers
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().
isNewObject(object)isNewObject(object)
object |
An S4 object.
The default instance is obtained as follows:
|
A length-1 logical. Returns FALSE for non-S4 objects.
Plot several plots with a shared legend
join_plots( plots, ncol = length(plots), nrow = 1, position = c("right", "bottom"), legend = TRUE )join_plots( plots, ncol = length(plots), nrow = 1, position = c("right", "bottom"), legend = TRUE )
plots |
list of plot objects of class |
ncol |
Optional number of columns |
nrow |
Optional number of rows |
position |
position of the legend ("bottom" or "right") |
legend |
Logical. Use a legend? |
modified from https://github.com/tidyverse/ggplot2/wiki/share-a-legend-between-two-ggplot2-graphs
A function that combined a list of data objects into a single data object (same dimensions but can have different numbers of simulations)
joinData(DataList)joinData(DataList)
DataList |
A list of data objects of identical dimension (except for simulation) |
T. Carruthers
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).
JoinYear(object1, object2)JoinYear(object1, object2)
object1 |
The earlier object. Must have years that precede those in
|
object2 |
The later object with the same structure as |
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.
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.
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.
A standard KOBE plot by each method that also shows the percentage of methods that ended up in each quadrant.
Kplot( MSEobj, maxsim = 60, MPs = NA, sims = NULL, maxMP = 9, nam = NA, cex.leg = 1.5 )Kplot( MSEobj, maxsim = 60, MPs = NA, sims = NULL, maxMP = 9, nam = NA, cex.leg = 1.5 )
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 |
Apologies for the nauseating shading.
T. Carruthers with some additions from A. Hordyk
Data object by a specified number of time-stepsLag the time-series slots in a Data object by a specified number of time-steps
Lag_Data(Data, Data_Lag = 0, msg = FALSE)Lag_Data(Data, Data_Lag = 0, msg = FALSE)
Data |
An object of class |
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? |
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.
An object of class Data with time-series slots lagged.
# 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,])# 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
ldim(x)ldim(x)
x |
A list |
T. Carruthers
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.
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) <- valueLength( 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
Pars |
|
Model |
|
Units |
|
MeanAtAge |
|
CVatAge |
|
Dist |
|
TruncSD |
|
Timing |
|
Random |
|
ALK |
|
Classes |
|
Misc |
|
x |
A length object for slot accessors, or a stock
object for |
value |
For |
There are two ways to define the length schedule:
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().
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.
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).
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
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)
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.
length for the class definition and slot-level documentation.
LengthModels() for available growth 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.
Other length:
length-class
# 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)# 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 (LAA) growth models
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)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)
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)? |
LengthModels() prints the list of models and parameters to the console
von Bertalanffy:
Brody:
Gompertz:
Schnute: flexible formula depending on parameters a and b
LengthModels() invisibly returns a data frame
containing the models
Growth models: Numeric vector of expected lengths at age.
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)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)
length S4 ClassDefines 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.
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.
Parslist. 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.
Modelfunction or character(1). Growth model identifier, matched
to one of LengthModels(). Set automatically by FindModel() when Pars
is supplied without an explicit model.
Unitscharacter(1). Physical unit of the length measurements (e.g.,
"mm", "cm"). Must be accepted by ValidUnits().
MeanAtAgearray. 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.
CVatAgearray or numeric. Coefficient of variation of
length-at-age, used to generate the within-age-class length distribution.
Distcharacter(1). Parametric distribution used for length-at-age
variability (e.g., "normal").
TruncSDarray or numeric. Number of standard deviations at which
the length distribution is truncated.
Timingarray or numeric. Fractional position within the time step
at which length is measured (0 = start, 1 = end).
Randomarray. Random effects on growth parameters across simulations
or years.
ALKarray. 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.
Classesnumeric. Length class midpoints in units of Units.
Misclist. Used internally.
Length() for the constructor and accessor functions.
LengthModels() for available growth models and their required #' parameters.
ValidUnits() for accepted unit strings.
Populate() for array population.
FindModel() for automatic model inference.
ALK() to retrieve the age-length key.
Specifying Biological and Fleet Schedules for the
full description of how Pars, Model, and MeanAtAge interact.
Other length:
Length()
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.
LengthStructuredObsLengthStructuredObs
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.
obs, Obs(), CatchObs(), IndicesObs(), CompObs(),
CatchAndSurveyObs, CommercialFleetObs, AgeStructuredObs,
DataRichObs
Other obs-examples:
AgeStructuredObs,
CatchAndSurveyObs,
CommercialFleetObs,
DataRichObs
LengthStructuredObs LandingsAtSize(LengthStructuredObs) DiscardsAtSize(LengthStructuredObs)LengthStructuredObs LandingsAtSize(LengthStructuredObs) DiscardsAtSize(LengthStructuredObs)
Predict missing life-history based on taxonomic information and hierarchical model fitted to FishBase life-history parameters
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 )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 )
OM |
An object of class 'OM' |
dist |
Character. Should parameters be sampled from a uniform ( |
filterMK |
Logical or numeric specifying percentiles. See Details.
e.g. |
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 |
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.
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.
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
A. Hordyk
https://github.com/James-Thorson-NOAA/FishLife
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
Database from the FishLife package with predicted life-history parameters for all species on FishBase
LHdatabaseLHdatabase
An object of class list of length 3.
https://github.com/James-Thorson-NOAA/FishLife/
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 ClassGroups 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.
LifeHistoryData()LifeHistoryData()
LifeHistoryData() returns a lifehistorydata object.
AgesAn object of class ages defining the age structure of the population (minimum age, maximum age, plus-group).
LengthAn object of class length defining the growth model (e.g., von Bertalanffy) and length-at-age parameters.
WeightAn object of class weight defining the weight-at-age or length–weight relationship.
NaturalMortalityAn object of class naturalmortality defining natural mortality rates, which may be age-, size-, or time-varying.
MaturityAn object of class maturity defining maturity-at-age or maturity-at-length schedules.
FecundityAn object of class fecundity defining fecundity-at-age or fecundity-at-length relationships.
SRRAn object of class srr defining the stock–recruitment relationship (e.g., Beverton–Holt, Ricker) and associated parameters.
SpatialAn object of class spatial defining the spatial structure of the population, including movement and area allocation.
DepletionAn object of class depletion specifying the initial depletion level relative to unfished biomass.
MiscA named list for any additional life-history metadata.
LifeHistoryData() creates a new lifehistorydata object.
Construct a lifehistoryobs object defining observation error for life-history parameters.
LifeHistoryObs( Ages = list(), Length = list(), Weight = list(), NaturalMortality = list(), Maturity = list(), Fecundity = list(), SRR = list(), Spatial = list(), Depletion = list(), Misc = list() )LifeHistoryObs( Ages = list(), Length = list(), Weight = list(), NaturalMortality = list(), Maturity = list(), Fecundity = list(), SRR = list(), Spatial = list(), Depletion = list(), Misc = list() )
Ages |
|
Length |
|
Weight |
|
NaturalMortality |
|
Maturity |
|
Fecundity |
|
SRR |
|
Spatial |
|
Depletion |
|
Misc |
|
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.
A lifehistoryobs object.
lifehistoryobs for the class definition.
Obs() for the enclosing observation model constructor.
lifehistorydata for the complementary observed-values class.
Other obs:
CatchObs(),
CompObs(),
EffortObs(),
ExploitationObs(),
IndicesObs(),
Obs(),
catchobs-class,
compobs-class,
effortobs-class,
exploitationobs-class,
indicesobs-class,
lifehistoryobs-class,
obs-class
lho <- LifeHistoryObs()lho <- LifeHistoryObs()
lifehistoryobs S4 ClassDefines 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().
Ageslist. Observation error specification for age structure
parameters. See LifeHistoryObs().
Lengthlist. Observation error specification for growth parameters.
See LifeHistoryObs().
Weightlist. Observation error specification for weight-at-age or
length-weight parameters. See LifeHistoryObs().
NaturalMortalitylist. Observation error specification for natural
mortality. See LifeHistoryObs().
Maturitylist. Observation error specification for maturity
schedules. See LifeHistoryObs().
Fecunditylist. Observation error specification for fecundity
parameters. See LifeHistoryObs().
SRRlist. Observation error specification for stock-recruitment
parameters. See LifeHistoryObs().
Spatiallist. Observation error specification for spatial
parameters. See LifeHistoryObs().
Depletionlist. Observation error specification for initial
depletion. See LifeHistoryObs().
Misclist. 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.
LifeHistoryObs() for the constructor.
obs for the enclosing object.
lifehistorydata for the complementary observed-values class.
Other obs:
CatchObs(),
CompObs(),
EffortObs(),
ExploitationObs(),
IndicesObs(),
LifeHistoryObs(),
Obs(),
catchobs-class,
compobs-class,
effortobs-class,
exploitationobs-class,
indicesobs-class,
obs-class
Convert between lists of arrays and higher-dimensional arrays in a predictable and efficient way.
List2Array(x, name = "Fleet", dim1 = "Sim", pos = NULL) Array2List(x, pos = 2, index = NULL)List2Array(x, name = "Fleet", dim1 = "Sim", pos = NULL) Array2List(x, pos = 2, index = NULL)
x |
A list (for |
name |
Character string giving the name of the new dimension created by
|
dim1 |
Character string giving the name of the first dimension when
combining a list of vectors. Defaults to |
pos |
Integer or character specifying the position or name of the
dimension to add ( |
index |
Optional integer vector specifying which slices to extract in
|
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.
List2Array(): an array with one additional dimension
Array2List(): a named list of arrays
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 xx <- 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
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.
LoadArgs(fun = "Simulate", envir = .GlobalEnv, debug = FALSE)LoadArgs(fun = "Simulate", envir = .GlobalEnv, debug = FALSE)
fun |
Character string naming a function, or a function object.
Default |
envir |
Environment to assign default values into. Default
|
debug |
Logical. If |
NULL invisibly. Called for its side effect of populating envir.
# 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)# 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)
Prints any warnings stored in the Log slot of an S4 object to the console
using cli formatting.
Log(object)Log(object)
object |
An S4 object with a |
Invisibly returns NULL. Called for its side effect of printing
warnings to the console.
## Not run: Log(my_object) ## End(Not run)## Not run: Log(my_object) ## End(Not run)
logit() transforms a probability to the log-odds scale. ilogit() is its
inverse — the sigmoid function — mapping any real number back to [0, 1].
logit(p) ilogit(x)logit(p) ilogit(x)
p |
A numeric vector of probabilities. Values must be in the open
interval (0, 1); |
x |
A numeric vector of real-valued log-odds. |
The two functions are mutual inverses:
so that ilogit(logit(p)) == p and logit(ilogit(x)) == x (up to
floating-point precision).
logit(p) returns a numeric vector of log-odds in (-Inf, Inf).
ilogit(x) returns a numeric vector of probabilities in (0, 1).
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))) # TRUElogit(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
Converts an OM to a single stock, single fleet MOM.
makeMOM(..., silent = FALSE)makeMOM(..., silent = FALSE)
... |
An |
silent |
Should messages be printed out to the console? |
A class MOM object.
Q. Huynh
MOM <- makeMOM(testOM)MOM <- makeMOM(testOM)
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.
makemov(fracs = c(0.1, 0.2, 0.3, 0.4), prob = c(0.5, 0.8, 0.9, 0.95))makemov(fracs = c(0.1, 0.2, 0.3, 0.4), prob = c(0.5, 0.8, 0.9, 0.95))
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 |
T. Carruthers
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.
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 )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 )
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? |
T. Carruthers
Generate a MICE Rel object, with predict and simulate methods, for multiMSE.
Currently implements intra-stock dynamics via density-dependent processes.
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, ...)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, ...)
type |
String to indicate the type of stock interaction. |
stock |
The index position of the stock in the MOM. |
CV |
Coefficient of variation of the predicted value for |
... |
Additional arguments depending on |
x |
For |
object |
A |
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. |
A class "Rel" object to pass to MOM@Rel.
Natural mortality (M) is a linear function of stock depletion in terms to total biomass (B) in year y (Forrest et al. 2018):
with a constraint that if
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]
Q. Huynh
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
# 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)# 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
makeTransparent(someColor, alpha = 100)makeTransparent(someColor, alpha = 100)
someColor |
Character string describing color |
alpha |
transparency |
T. Carruthers
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.
Maturity( Pars = list(), Model = NULL, MeanAtAge = NULL, MeanAtLength = NULL, MeanAtWeight = NULL, Classes = NULL, Semelparous = FALSE, Misc = list() ) Semelparous(x) Semelparous(x) <- value Maturity(x) <- valueMaturity( Pars = list(), Model = NULL, MeanAtAge = NULL, MeanAtLength = NULL, MeanAtWeight = NULL, Classes = NULL, Semelparous = FALSE, Misc = list() ) Semelparous(x) Semelparous(x) <- value Maturity(x) <- value
Pars |
|
Model |
|
MeanAtAge |
|
MeanAtLength |
|
MeanAtWeight |
|
Classes |
|
Semelparous |
|
Misc |
|
x |
A maturity object for slot accessors, or a stock
object for |
value |
For |
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)
)
)
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.
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.
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
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)
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.
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
# 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# 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
maturity S4 ClassDefines 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.
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.
Parslist. 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.
Modelfunction or character(1). Maturity model identifier,
matched to one of MaturityModels(). Set automatically by FindModel()
when Pars is supplied without an explicit model.
MeanAtAgearray. 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.
MeanAtLengtharray. 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.
MeanAtWeightarray. 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.
Classesnumeric. Age, length, or weight class midpoints
corresponding to the MeanAt* array in use.
Semelparouslogical 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.
Misclist. Used internally.
Maturity() for the constructor and accessor functions.
MaturityModels() for available maturity models and their required
parameters.
Populate() for array population.
FindModel() for automatic model inference.
Semelparous() to retrieve or set the post-spawn mortality array.
Length() and Weight() for the companion schedules required by at-length and at-weight maturity models.
Specifying Biological and Fleet Schedules for the
full description of how Pars, Model, and MeanAt* arrays interact.
Other maturity:
Maturity()
Logistic maturity models
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)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)
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 |
Length |
numeric vector of length classes (for length-based models) |
L50 |
length at 50% maturity (Logistic-at-Length) |
L50_95 |
interval between |
Weight |
numeric vector of weight classes (for weight-based models) |
W50 |
weight at 50% maturity (Logistic-at-Weight) |
W50_95 |
interval between |
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:
at-length and at-weight schedules are converted internally to at-age using the age-length age-weight key respectively.
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
Ages(), Length(), Maturity(), Weight(), Stock()
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")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")
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.
ML2D(OM, ML, nsim = 100, ploty = T, Dlim = c(0.05, 0.6))ML2D(OM, ML, nsim = 100, ploty = T, Dlim = c(0.05, 0.6))
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. |
An object of class 'OM' with 'D' slot populated
T. Carruthers
'MMSE'
A Multi Management Strategy Evaluation object that contains information about simulation conditions and performance of MPs for a multi-stock, multi-fleet operating model.
NameName of the MMSE object. Single value. Character string
nyearsThe number of years for the historical simulation. Single value. Positive integer
proyearsThe number of years for the projections - closed loop simulations. Single value. Positive integer
nMPsNumber of management procedures simulation tested. Single value. Positive integer.
MPsThe names of the MPs that were tested. Vector of length nMPs. Character strings.
MPcondThe MP condition. Character ('bystock': an MP per stock, 'byfleet' and MP per stock and fleet, 'MMP' an MP for all stocks and fleets)
MPrefsThe names of the MPs applied for each stock (row) and fleet (column). An array.
nsimNumber of simulations. Single value. Positive integer
nstocksNumber of stocks. Single value. Positive integer
nfleetsNumber of fleets. Single value. Positive integer
SnamesNames of the stocks
FnamesNames of the fleets (matrix nstocks x nfleets)
StocksThe stock operating model objects. List of Stocks
FleetsThe fleet operating model objects. Hierarchical list, fleets nested in stocks.
ObssThe fleet specific observation error operating model objects. Hierarchical list, fleets nested in stocks.
ImpsThe fleet specific implementation error operating model objects. Hierarchical list, fleets nested in stocks.
OMA table of sampled parameters of the operating model. Data frame of nsim rows.
ObsA table of sampled parameters of the observation model. Data frame of nsim rows.
SB_SBMSYSimulated spawning biomass relative to SBMSY over the projection. An array with dimensions: nsim, nStocks, nMPs, proyears. Non-negative real numbers
F_FMSYSimulated fishing mortality rate relative to FMSY over the projection. An array with dimensions: nsim, nStocks, nFleets, nMPs, proyears. Non-negative real numbers
NSimulated stock numbers over the projection. An array with dimensions: nsim, nStocks, maxage+1, nMPs, proyears, nareas. Non-negative real numbers
BSimulated stock biomass over the projection. An array with dimensions: nsim, nStocks, nMPs, proyears. Non-negative real numbers
SSBSimulated spawning stock biomass over the projection. An array with dimensions: nsim, nStocks, nMPs, proyears. Non-negative real numbers
VBSimulated vulnerable biomass over the projection. An array with dimensions: nsim, nStocks, nMPs, proyears. Non-negative real numbers
FMSimulated fishing mortality rate over the projection. An array with dimensions: nsim, nStocks, nFleets, nMPs, proyears. Non-negative real numbers
SPRA list of SPR values. Currently not used.
CatchSimulated catches (landings) over the projection. An array with dimensions: nsim, nStocks, nFleets, nMPs, proyears. Non-negative real numbers
RemovalsSimulated removals (landings+discards) over the projection. An array with dimensions: nsim, nStocks, nFleets, nMPs, proyears. Non-negative real numbers
EffortSimulated relative fishing effort in the projection years. An array with dimensions: nsim, nStocks, nFleets, nMPs, proyears. Non-negative real numbers
TACSimulated 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
TAESimulated 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
BioEcoA named list of bio-economic output. Not currently used.
RefPointNamed 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
multiHistThe object of class multiHist containing information from the spool-up period.
PPDPosterior predictive data. List of Data objects at the end of
the projection period (length nMPs)
MiscMiscellaneous output such as posterior predictive data
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)
T. Carruthers
Low-level curve functions used internally by
FecundityModels(), MaturityModels(), RetentionModels(),
SelectivityModels(), and WeightModels().
allometric(x, scale, exponent) dnormal(lens, lfs, sl, sr) double_normal(x, x5, xF, xMax) logistic_50_95(x, x50, x50_95, asymp = 1)allometric(x, scale, exponent) dnormal(lens, lfs, sl, sr) double_normal(x, x5, xF, xMax) logistic_50_95(x, x50, x50_95, asymp = 1)
x |
Numeric vector of values (ages, lengths, or weights) at which to evaluate the curve. |
scale |
Multiplicative scale parameter ( |
exponent |
Power exponent ( |
lens |
Numeric vector of lengths ( |
lfs |
Length at full selection, the peak of the |
sl |
Standard deviation of the ascending limb of |
sr |
Standard deviation of the descending limb of |
x5 |
Value of |
xF |
Value of |
xMax |
Maximum value on the descending limb of |
x50 |
Value of |
x50_95 |
Interval between the 50% and 95% points ( |
asymp |
Asymptote of the logistic curve. Defaults to |
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.
where if and 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:
where is asymp.
Each function returns a numeric vector of the same length as the primary
input (x or lens).
FecundityModels(), MaturityModels(), RetentionModels(),
SelectivityModels(), WeightModels()
'MOM'
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.
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.
NameName of the operating model
AgencyName of the agency responsible for the management of the fishery. Character string
RegionName of the general geographic region of the fishery. Character string
SponsorName of the organization who sponsored the OM. Character string
LatitudeLatitude (decimal degrees). Negative values represent the South of the Equator. Numeric. Single value
LongitudeLongitude (decimal degrees). Negative values represent the West of the Prime Meridian. Numeric. Single value
nsimThe number of simulations
proyearsThe number of projected years
intervalThe assessment interval - how often would you like to update the management system?
pstarThe percentile of the sample of the management recommendation for each method
maxFMaximum instantaneous fishing mortality rate that may be simulated for any given age class
repsNumber 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.
cparsA 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()
seedA random seed to ensure users can reproduce results exactly
SourceA reference to a website or article from which parameters were taken to define the operating model
StocksList of stock objects
FleetsList of Fleet objects
ObsHierarchical List of Observation model objects Level 1 is stock, level 2 is fleet
ImpsHierarchical List of Implementation model objects Level 1 is stock, level 2 is fleet
CatchFracA 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)
AllocationA 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).
EfactorA list nstock long, of current effort factors by fleet (default is 1 - same as current effort)
ComplexesA 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
SexParsA 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.
RelA 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 can be created by calls of the form
new('MOM', Stock_list, Fleet_list, Obs_list, Imp_list).
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.
T. Carruthers and A. Hordyk
Article on MOM and multiMSE: https://openmse.com/features-multimse/
Apply the movement model to the stock for one time-step
movestockCPP(nareas, maxage, mov, Number)movestockCPP(nareas, maxage, mov, Number)
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 |
A. Hordyk
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.
movfit_Rcpp(par, prb, frac)movfit_Rcpp(par, prb, frac)
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) |
This is paired with getmov to find the correct movement model.
T. Carruthers with an amateur attempt at converting to Rcpp by A. Hordyk (but it works!)
Fill any NAs arising from MPCalcs (hermaphroditism mode)
MPCalcsNAs(MPCalcs)MPCalcsNAs(MPCalcs)
MPCalcs |
A list of arrays arising fromt the DLMtool function CalcMPDynamics() |
T. Carruthers
Management Procedure Type
MPtype(MPs = NA)MPtype(MPs = NA)
MPs |
A vector of MP names. If none are provided function is run on all available MPs |
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)
## Not run: library(openMSE) MPtype(c("AvC", "curE", "matlenlim", "MRreal", "FMSYref")) ## End(Not run)## Not run: library(openMSE) MPtype(c("AvC", "curE", "matlenlim", "MRreal", "FMSYref")) ## End(Not run)
mse ClassThe 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.
OMThe om object used as the operating model.
MPsNamed list of management procedures evaluated in the MSE. Each element corresponds to one MP applied across all simulations.
UnfishedAn unfished object containing unfished equilibrium and dynamic reference trajectories. See unfished for details.
ReferenceA reference object containing biological and management reference points derived from the historical period. See reference for details.
HistA 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.
PPDList containing posterior predictive distribution outputs and diagnostics generated during the MSE.
LogInternal list storing MSE diagnostics and execution metadata. Not intended for direct user access.
MiscNamed 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.
hist, timeseries, om, unfished,
reference, Hist(), Advice()
'MSE'
A Management Strategy Evaluation object that contains information about simulation conditions and performance of data-limited methods
NameName of the MSE object. Single value. Character string
nyearsThe number of years for the historical simulation. Single value. Positive integer
proyearsThe number of years for the projections - closed loop simulations. Single value. Positive integer
nMPsNumber of management procedures simulation tested. Single value. Positive integer.
MPsThe names of the MPs that were tested. Vector of length nMPs. Character strings.
nsimNumber of simulations. Single value. Positive integer
OMOperating model parameters (last historical year used for
time-varying parameters). Data.frame with nsim rows
ObsObservation parameters (last historical year used for time-varying
parameters). Data.frame with nsim rows
SB_SBMSYSimulated spawning biomass relative to spawning BMSY over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers
F_FMSYSimulated fishing mortality rate relative to FMSY over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers
NSimulated total numbers over the projection. An array with dimensions: nsim, maxage+1, nMPs, proyears, nareas. Non-negative real numbers.
BSimulated stock biomass over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers
SSBSimulated spawning stock biomass over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers
VBSimulated vulnerable biomass over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers
FMSimulated fishing mortality rate over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers
SPRNamed list with equilibrium and dynamic SPR. Each element is an array with dimensions: nsim, nMPs, proyears. Non-negative real numbers.
CatchSimulated catches (landings) over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers
RemovalsSimulated removals (catch + discards) over the projection. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers
EffortSimulated relative fishing effort in the projection years. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers
TACSimulated Total Allowable Catch prescribed by MPs. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers
TAESimulated Total Allowable Effort prescribed by MPs. An array with dimensions: nsim, nMPs, proyears. Non-negative real numbers
BioEcoNamed list with bio-economic output Only used if bio-economic parameters are included in OM
RefPointNamed 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_histSimulated catches (landings) from the spool-up period. An array with dimensions: nsim, nyears. Non-negative real numbers
FM_histSimulated fishing mortality rate from the spool-up period. An array with dimensions: nsim, nyears Non-negative real numbers
SSB_histSimulated spawning stock biomass from the spool-up period. An array with dimensions: nsim, nyears. Non-negative real numbers
HistInformation from the historical spool-up period. Object of class
Hist. Only contains slots AtAge and TSdata unless extended=TRUE in runMSE
PPDPosterior predictive data. List of Data objects at the end of
the projection period (length nMPs)
MiscMiscellaneous output
T. Carruthers and A. Hordyk
mse Object to a Slick ObjectConverts an mse object (or a list of mse objects) into a
Slick::Slick() data object for interactive visualization in the
Slick App.
MSE2Slick(MSE)MSE2Slick(MSE)
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. |
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.
A Slick::Slick() object ready for use with Slick::App().
Slick::Slick(), Slick::App(), mse
## 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)## 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)
A data.frame with description of slots for class MSE
MSEDescriptionMSEDescription
An object of class data.frame with 29 rows and 2 columns.
Downloads the MSEextra package from GitHub
MSEextra(silent = FALSE)MSEextra(silent = FALSE)
silent |
Logical. Should messages to printed? |
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.
MSYRefs(Hist) FMSY(Hist) BMSY(Hist) SBMSY(Hist) SPMSY(Hist) SPRMSY(Hist) MSYLandings(Hist) MSYDiscards(Hist)MSYRefs(Hist) FMSY(Hist) BMSY(Hist) SBMSY(Hist) SPMSY(Hist) SPRMSY(Hist) MSYLandings(Hist) MSYDiscards(Hist)
Hist |
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.
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).
Internal function to calculate MSY Reference Points
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 )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 )
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 |
SRRpars |
Optional. A named list of arguments for |
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. |
See opt
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)
multiData(MSElist, StockPars, p, mm, nf)multiData(MSElist, StockPars, p, mm, nf)
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 |
T. Carruthers
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
multiDataS(MSElist, Real.Data.Map, np, mm, nf, realVB)multiDataS(MSElist, Real.Data.Map, np, mm, nf, realVB)
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 |
T. Carruthers
A basic comparison of runMSE output (MSE) and multiMSE (MMSE)
multidebug(MSEsingle, MSEmulti, p = 1, f = 1, MPno = 1, maxsims = 4)multidebug(MSEsingle, MSEmulti, p = 1, f = 1, MPno = 1, maxsims = 4)
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. |
T.Carruthers
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.
MultiStockOMMultiStockOM
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]]:
AlbacoreExStock: [[AgeStructuredObs, CommercialFleetObs]]
ButterfishExStock: [[CatchAndSurveyObs, LengthStructuredObs]]
Complexes: NULL. Stocks are managed independently.
Imp: NULL. Implementation error is not specified; the Imp
slot retains its class default. See Imp() for details.
Two biologically contrasting stocks are included:
AlbacoreExStock: long-lived, slow-growing, low natural mortality.
ButterfishExStock: short-lived, fast-growing, high natural mortality.
See AlbacoreExStock and ButterfishExStock for full parameter details.
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 vary by stock and fleet, illustrating a range of monitoring intensities across the two stocks:
AlbacoreExStock, Fleet 1 (AsympExFleet): AgeStructuredObs — landings, a spawning-biomass survey, and age-composition samples from landed and discarded fish.
AlbacoreExStock, Fleet 2 (DomeExFleet): CommercialFleetObs — landings, discards, effort, and a commercial CPUE index; no survey or composition data.
ButterfishExStock, Fleet 1 (AsympExFleet): CatchAndSurveyObs — reported landings and a biomass-proportional survey index only.
ButterfishExStock, Fleet 2 (DomeExFleet): LengthStructuredObs — landings, a survey, and annual length-composition samples from landed and discarded fish.
The Imp slot is NULL. The imp is currently a placeholder and
implementation error is not applied during simulation. See Imp() for
details.
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
MultiStockOM nStock(MultiStockOM) nFleet(MultiStockOM) ## Not run: Hist <- runMSE(MultiStockOM, MPs = ExampleMPs()) ## End(Not run)MultiStockOM nStock(MultiStockOM) nFleet(MultiStockOM) ## Not run: Hist <- runMSE(MultiStockOM, MPs = ExampleMPs()) ## End(Not run)
Access Stock or Fleet Names
StockNames(object) FleetNames(object, IncSurvey = FALSE)StockNames(object) FleetNames(object, IncSurvey = FALSE)
object |
|
IncSurvey |
Logical. Include names of survey (non-fishing) fleets? Default: FALSE |
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.
StockNames(): a character vector of stock names
FleetNames(): a character vector of fleet names (always taken from the first stock)
StockNames(SingleStockOM) FleetNames(SingleStockOM)StockNames(SingleStockOM) FleetNames(SingleStockOM)
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.
NaturalMortality( Pars = list(), Model = NULL, Units = "year", MeanAtAge = NULL, MeanAtLength = NULL, Random = NULL, Classes = NULL, Misc = list() ) NaturalMortality(x) <- valueNaturalMortality( Pars = list(), Model = NULL, Units = "year", MeanAtAge = NULL, MeanAtLength = NULL, Random = NULL, Classes = NULL, Misc = list() ) NaturalMortality(x) <- value
Pars |
|
Model |
|
Units |
|
MeanAtAge |
|
MeanAtLength |
|
Random |
|
Classes |
|
Misc |
|
x |
A naturalmortality object for slot accessors, or a
stock object for |
value |
For |
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)
)
)
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.
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.
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
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
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.
naturalmortality for the class definition and slot-level documentation.
NaturalMortalityModels() 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 mortality models.
Other naturalmortality:
naturalmortality-class
# 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)# 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)
naturalmortality S4 ClassDefines 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.
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().
Parslist. 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.
Modelfunction or character(1). Natural mortality model
identifier, matched to one of NaturalMortalityModels(). Set
automatically by FindModel() when Pars is supplied without an
explicit model.
Unitscharacter(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().
MeanAtAgearray. 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.
MeanAtLengtharray. 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.
Randomarray. 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().
Classesnumeric. Age or length class midpoints corresponding to the
MeanAt* array in use.
Misclist. Used internally.
NaturalMortality() for the constructor and accessor functions.
NaturalMortalityModels() for available models and their required
parameters.
ValidUnits() for accepted unit strings.
Populate() for array population.
FindModel() for automatic model inference.
Length() for the companion length schedule, required when using
at-length mortality models.
Specifying Biological and Fleet Schedules for the
full description of how Pars, Model, and MeanAt* arrays interact.
Other naturalmortality:
NaturalMortality()
Natural mortality models for age, length, and weight.
MortalityAtAge(Ages, M) LorenzenMortalityLength(Length, Mref, Lref, c = -0.288) LorenzenMortalityWeight(Weight, Mref, Wref, c = -0.288) NaturalMortalityModels(full = TRUE, print = TRUE)MortalityAtAge(Ages, M) LorenzenMortalityLength(Length, Mref, Lref, c = -0.288) LorenzenMortalityWeight(Weight, Mref, Wref, c = -0.288) NaturalMortalityModels(full = TRUE, print = TRUE)
Ages |
numeric vector of age classes |
M |
natural mortality rate. Recycled if not |
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) |
at-length and at-weight schedules are converted internally to at-age using the age-length age-weight key respectively.
M-at-age:
Lorenzen M-at-length:
Lorenzen M-at-weight:
NaturalMortalityModels() prints a list of available models.
Numeric vector of natural mortality at each age, length, or weight.
NaturalMortalityModels() invisibly returns a data frame describing available models.
Ages(), Length(), Weight(), Stock()
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))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))
Create of vector of values that correspond with a slot in a list of objects
NIL(listy, namey, lev1 = T)NIL(listy, namey, lev1 = T)
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? |
T. Carruthers
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
NOAA_plot(MSEobj, nam = NA, type = NA, panel = T)NOAA_plot(MSEobj, nam = NA, type = NA, panel = T)
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. |
A table of performance metrics.
T. Carruthers
Returns the number of individuals (abundance) from a hist or
mse object, either as a list of length nStock() or
a data.frame.
Number(object, df = FALSE, byAge = FALSE, byArea = FALSE)Number(object, df = FALSE, byAge = FALSE, byArea = FALSE)
object |
|
df |
Logical. If |
byAge |
Logical. If |
byArea |
Logical. If |
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.
Biomass(), SBiomass(), SProduction()
Hist <- Simulate(SingleStockOM) Number(Hist, df = TRUE) Number(Hist, df = TRUE, byAge = TRUE) Number(Hist, df = TRUE, byAge = TRUE, byArea = TRUE)Hist <- Simulate(SingleStockOM) Number(Hist, df = TRUE) Number(Hist, df = TRUE, byAge = TRUE) Number(Hist, df = TRUE, byAge = TRUE, byArea = TRUE)
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.
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) <- valueObs( 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
Name |
If |
LifeHistory |
A lifehistoryobs object, or |
Exploitation |
An exploitationobs object, or |
Effort |
An effortobs object, or |
Landings |
A catchobs object, or |
Discards |
A catchobs object, or |
CPUE |
An indicesobs object, or |
Survey |
An indicesobs object, or |
LandingsAtAge |
A compobs object, or |
DiscardsAtAge |
A compobs object, or |
LandingsAtSize |
A compobs object, or |
DiscardsAtSize |
A compobs object, or |
Misc |
|
x |
An om object. |
value |
A two-level named list of obs objects, or a single
obs object, to assign to the |
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.
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.
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.
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.
obs for the class definition and slot-level documentation.
CatchObs(), EffortObs(), IndicesObs(), CompObs() for
sub-object constructors.
LifeHistoryObs(), ExploitationObs() for placeholder sub-objects.
data and Data() for the complementary observed-values object.
OM() for the operating model constructor.
ConvertObs() for converting legacy Obs-legacy objects.
Other obs:
CatchObs(),
CompObs(),
EffortObs(),
ExploitationObs(),
IndicesObs(),
LifeHistoryObs(),
catchobs-class,
compobs-class,
effortobs-class,
exploitationobs-class,
indicesobs-class,
lifehistoryobs-class,
obs-class
# 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)# 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)
obs S4 ClassDefines 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.
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.
Namecharacter or NULL. Unique identifier for this observation
model. See Obs().
LifeHistoryA lifehistoryobs object. Observation error on
life-history parameters (growth, maturity, natural mortality, etc.).
See LifeHistoryObs().
ExploitationAn exploitationobs object. Observation error on
exploitation processes (selectivity, retention, discard mortality).
See ExploitationObs().
EffortAn effortobs object. Observation error on fishing
effort. See EffortObs().
LandingsA catchobs object. Observation error on landed
catch. See CatchObs().
DiscardsA catchobs object. Observation error on discarded
catch. See CatchObs().
CPUEAn indicesobs object. Observation error on
catch-per-unit-effort indices. See IndicesObs().
SurveyAn indicesobs object. Observation error on
fishery-independent survey indices. See IndicesObs().
LandingsAtAgeA compobs object. Observation error on
landed catch-at-age composition. See CompObs().
DiscardsAtAgeA compobs object. Observation error on
discarded catch-at-age composition. See CompObs().
LandingsAtSizeA compobs object. Observation error on
landed catch-at-length composition. See CompObs().
DiscardsAtSizeA compobs object. Observation error on
discarded catch-at-length composition. See CompObs().
Misclist. Miscellaneous additional objects.
Obs() for the constructor and accessor.
CatchObs(), EffortObs(), IndicesObs(), CompObs() for
sub-object constructors.
LifeHistoryObs(), ExploitationObs() for placeholder sub-objects.
data and Data() for the complementary observed-values object.
OM() for the operating model constructor.
ConvertObs() for converting legacy Obs-legacy objects.
Other obs:
CatchObs(),
CompObs(),
EffortObs(),
ExploitationObs(),
IndicesObs(),
LifeHistoryObs(),
Obs(),
catchobs-class,
compobs-class,
effortobs-class,
exploitationobs-class,
indicesobs-class,
lifehistoryobs-class
'Obs'
An operating model component that controls the observation model
NameThe name of the observation model object. Single value. Character string.
NameThe name of the Observation error object. Single value. Character string.
CobsObservation 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.
CbiascvLog-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_nsampNumber 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_ESSEffective 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_nsampNumber 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_ESSEffective 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.
IobsObservation 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.
BtobsObservation 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.
BtbiascvLog-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.
betaA 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.
LenMbiascvLog-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.
MbiascvLog-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.
KbiascvLog-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.
t0biascvLog-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.
LinfbiascvLog-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.
LFCbiascvLog-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.
LFSbiascvLog-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_MbiascvLog-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_B0biascvLog-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.
IrefbiascvLog-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.
BrefbiascvLog-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.
CrefbiascvLog-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.
DbiascvLog-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.
DobsLog-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.
hbiascvLog-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.
RecbiascvLog-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.
sigmaRbiascvLog-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.
EobsObservation 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.
EbiascvLog-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 can be created by calls of the form
new('Obs')
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.
T. Carruthers and A. Hordyk
showClass('Obs')showClass('Obs')
A data.frame with description of slots for class Obs
ObsDescriptionObsDescription
An object of class data.frame with 30 rows and 2 columns.
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.
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 )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 )
Name |
Character. Name of the operating model. Default
If |
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 |
Region |
Character. Name of the geographic region of the fishery.
Default |
Latitude |
Numeric. Latitude (decimal degrees) of the centre of
|
Longitude |
Numeric. Longitude (decimal degrees) of the centre of
|
Sponsor |
Character. Organisation sponsoring development of the
operating model. Supports Markdown. Default |
nSim |
Positive integer. Number of stochastic simulations. Default
|
nYear |
Numeric. Number of historical years. Default |
pYear |
Numeric. Number of projection years. Default |
CurrentYear |
Integer. Final historical calendar year of the operating model. Default is the current system year. |
Seasons |
Integer. Number of seasons per year. Default |
Stock |
A stock object or named list of stock objects.
Default |
Fleet |
A hierarchical named list of fleet objects indexed by
stock then fleet. Each stock must have the same number of fleets. Default
|
Obs |
A hierarchical named list of obs objects indexed by
stock and fleet. Default |
Imp |
A hierarchical named list of imp objects indexed by
stock and fleet. Default |
Data |
A data object or list of data objects
associated with the operating model. Default |
DataLag |
Integer. Number of time steps that data are lagged relative
to management implementation. Default |
CatchFrac |
List. Controls catch fraction allocation among fleets or
stocks. Default |
Allocation |
List. Controls effort or catch allocation among fleets or
stocks. Default |
EFactor |
List. Effort or exploitation modifiers applied during
projection. Default |
Complexes |
List. Defines stock complexes for data aggregation and
management. Default |
Herm |
List. Defines hermaphroditism or movement between stocks.
Default |
SharePar |
Logical. Whether key parameters are shared among stocks.
Default |
Relations |
List. Biological or ecological relationships among stocks
(e.g. predator-prey). Default |
StockTargeting |
A stocktargeting object. Defines fleet-level
stock targeting weights and deviations. Populated internally.
See |
Interval |
Numeric scalar or named numeric vector. Management update
interval in years. Default |
nReps |
Positive integer. Number of stochastic replicates used for
generating management advice. Default |
pStar |
Numeric in |
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 |
Seed |
Integer. Random number generator seed for reproducibility.
Default |
Control |
Named list of operating model control settings. When |
Misc |
List. Miscellaneous objects or developer-use components.
Default |
Source |
Character. References to data sources or documentation.
Supports Markdown. Default |
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
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.
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.
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(...)
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"
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.
om for the class definition.
OM-accessors for slot accessor and replacement functions.
Stock(), Fleet(), Obs(), Imp(), Data() for sub-object
constructors and their pass-through accessors.
Years(), CalcYears() for the derived time-step vector.
StockTargeting() for the stock targeting sub-object.
Log() for accessing runtime diagnostics.
PopulateOM(), runMSE() for downstream use of the operating model.
ConvertOM(), ConvertMOM() for converting legacy objects.
Other om:
ComplexOM,
MultiStockOM,
OM-accessors,
SingleStockOM,
TwoFleetOM,
om-class
om <- OM() Agency(om) Agency(om) <- "DFO" nSim(om) nSim(om) <- 100 Years(om)om <- OM() Agency(om) Agency(om) <- "DFO" nSim(om) nSim(om) <- 100 Years(om)
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.
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) <- valueAgency(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
x |
|
value |
Replacement value for the corresponding slot. |
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().
Years is derived automatically from nYear, pYear, CurrentYear, and
Seasons and is read-only. Use Years() to extract it.
Accessor functions return the value of the named slot.
Replacement functions return x with the named slot updated.
OM() for the constructor.
om for the class definition.
Stock(), Fleet(), Obs(), Imp(), Data() for sub-object
pass-through accessors.
Years() for the read-only time-step vector.
Log() for runtime diagnostics.
Other om:
ComplexOM,
MultiStockOM,
OM(),
SingleStockOM,
TwoFleetOM,
om-class
om <- OM() Agency(om) Agency(om) <- "DFO" nSim(om) nSim(om) <- 100 maxF(om) maxF(om) <- 5om <- OM() Agency(om) Agency(om) <- "DFO" nSim(om) nSim(om) <- 100 maxF(om) maxF(om) <- 5
om S4 ClassThe om defines a complete operating model (OM) specification for use in Management Strategy Evaluation (MSE).
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.
NameCharacter. Name of the operating model. See OM().
AgencyCharacter. Name of the agency responsible for management.
Supports Markdown. See OM().
AuthorCharacter vector. Name(s) of the author(s). See OM().
EmailCharacter vector. Email address(es) corresponding to Author.
Supports Markdown. See OM().
RegionCharacter. Name of the geographic region of the fishery.
See OM().
LatitudeNumeric. Latitude (decimal degrees) of the centre of
Region. See OM().
LongitudeNumeric. Longitude (decimal degrees) of the centre of
Region. See OM().
SponsorCharacter. Organisation sponsoring development of the
operating model. Supports Markdown. See OM().
nSimPositive integer. Number of stochastic simulations. See OM().
nYearNumeric. Number of historical years. See OM().
pYearNumeric. Number of projection years. See OM().
CurrentYearInteger. Final historical calendar year. See OM().
SeasonsInteger. Number of seasons per year. See OM().
YearsNumeric vector. Model time steps (including seasonal resolution
if applicable). Derived from nYear, pYear, CurrentYear, and
Seasons via CalcYears(). Read-only; see Years().
StockFleetA hierarchical named list of fleet objects indexed by
stock then fleet. Each stock must have the same number of fleets.
See Fleet().
ObsA hierarchical named list of obs objects indexed by stock
and fleet. See Obs().
ImpA hierarchical named list of imp objects indexed by stock
and fleet. See Imp().
DataA data object or list of data objects associated
with the operating model. See Data().
DataLagInteger. Number of time steps that data are lagged relative
to management implementation. See OM().
CatchFracList. Controls catch fraction allocation among fleets or
stocks. See OM().
AllocationList. Controls effort or catch allocation among fleets or
stocks. See OM().
EFactorList. Effort or exploitation modifiers applied during
projection. See OM().
ComplexesList. Defines stock complexes for data aggregation and
management. See OM().
HermList. Defines hermaphroditism or movement between stocks.
See OM().
ShareParLogical. Whether key parameters are shared among stocks.
See OM().
RelationsList. Biological or ecological relationships among stocks.
See OM().
StockTargetingA stocktargeting object. Defines fleet-level
stock targeting weights and deviations. Initialised automatically by
OM() via StockTargeting().
IntervalNumeric scalar or named numeric vector. Management update
interval in years. See OM().
nRepsPositive integer. Number of stochastic replicates for
management advice. See OM().
pStarNumeric. Percentile applied to stochastic management advice.
See OM().
maxFNumeric. Maximum allowable instantaneous fishing mortality.
See OM().
SeedInteger. Random number generator seed. See OM().
ControlNamed list of operating model control settings. See OM().
MiscList. Miscellaneous objects or developer-use components.
LogList. Internal diagnostic and runtime information. See Log().
SourceCharacter. References to data sources or documentation.
Supports Markdown. See OM().
OM() for the constructor and OM-accessors for slot accessors.
Stock(), Fleet(), Obs(), Imp(), Data() for sub-object
constructors and their pass-through accessors.
Years(), CalcYears() for the derived time-step vector.
StockTargeting() for the stock targeting sub-object.
Log() for accessing runtime diagnostics.
runMSE(), PopulateOM() for downstream use of the operating model.
Other om:
ComplexOM,
MultiStockOM,
OM(),
OM-accessors,
SingleStockOM,
TwoFleetOM
'OM'
An object containing all the parameters needed to control the MSE which can be build from component Stock, Fleet, Obs, and Imp objects.
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.
NameName of the operating model
AgencyName of the agency responsible for the management of the fishery. Character string
RegionName of the general geographic region of the fishery. Character string
SponsorName of the organization who sponsored the OM. Character string
LatitudeLatitude (decimal degrees). Negative values represent the South of the Equator. Numeric. Single value
LongitudeLongitude (decimal degrees). Negative values represent the West of the Prime Meridian. Numeric. Single value
nsimThe number of simulations
proyearsThe number of projected years
intervalThe assessment interval - how often would you like to update the management system?
pstarThe percentile of the sample of the management recommendation for each method
maxFMaximum instantaneous fishing mortality rate that may be simulated for any given age class
repsNumber 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.
cparsA list of custom parameters. Time series are a matrix nsim rows by nyears columns. Single parameters are a vector nsim long. See validcpars()
seedA random seed to ensure users can reproduce results exactly
SourceA reference to a website or article from which parameters were taken to define the operating model
Objects can be created by calls of the form
new('OM', Stock, Fleet, Obs, Imp).
T. Carruthers and A. Hordyk
A data.frame with description of slots for class OM
OMDescriptionOMDescription
An object of class data.frame with 15 rows and 2 columns.
Generate OM Documentation Report
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, ... )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, ... )
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 |
... |
Optional additional named arguments provided to |
Creates a Rmarkdown file and compiles a HTML report file in the working directory.
A. Hordyk
## 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)## 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
OMexample(dir = getwd())OMexample(dir = getwd())
dir |
the file path to copy the files to. |
## Not run: OMexample() ## End(Not run)## Not run: OMexample() ## End(Not run)
Generates an Excel spreadsheet and a source.rmd file in the current working directory for specifying and documenting a MSEtool Operating Model.
OMinit( name = NULL, ..., files = c("xlsx", "rmd"), dir = NULL, overwrite = FALSE )OMinit( name = NULL, ..., files = c("xlsx", "rmd"), dir = NULL, overwrite = FALSE )
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 |
overwrite |
Logical. Should files be overwritten if they already exist? |
name.xlsx and name.rmd files are created in the working directory.
A. Hordyk
## 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)## 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
optCPU(nsim = 96, thresh = 5, plot = TRUE, msg = TRUE, maxn = NULL)optCPU(nsim = 96, thresh = 5, plot = TRUE, msg = TRUE, maxn = NULL)
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 |
A. Hordyk
## Not run: optCPU() ## End(Not run)## Not run: optCPU() ## End(Not run)
Example objects of class Imp
Overages Perfect_ImpOverages Perfect_Imp
An object of class Imp of length 1.
An object of class Imp of length 1.
avail("Imp")avail("Imp")
Performance metric (PMs) methods for your management strategy evaluation.
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)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)
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. |
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.
An object of class PMobj
## 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)## 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)
perrecruit S4 ClassAn 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.
When SpawnTimeFrac > 0 for any stock, NPRF_SP differs from NPRF:
survival to the spawn date is computed as
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.
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.
where , , and are weight, maturity, and
fecundity at age respectively.
apicalFNumeric vector of apical fishing mortality values at
which per-recruit quantities were evaluated. Length nF.
NPR0Numbers-per-recruit at unfished conditions.
Array (Sim × Age × Year) or a list by stock.
NPR0_SPSpawning 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.
NPRFNumbers-per-recruit at fishing mortality.
Array (Sim × Age × Year × F) or a list by stock,
where the F dimension has length nF.
NPRF_SPSpawning 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.
SPR0Spawning-per-recruit at unfished conditions.
Array (Sim × Stock × Year).
SPRFSpawning-per-recruit at fishing mortality.
Array (Sim × Stock × Year × F).
SPRSpawning-per-recruit relative to unfished, i.e.
SPRF / SPR0. Array (Sim × Stock × Year × F).
BiomassTotal biomass-per-recruit.
Array (Sim × Stock × Year × F).
SBiomassSpawning biomass-per-recruit.
Array (Sim × Stock × Year × F).
SProductionSpawning production-per-recruit, computed from
fecundity-at-age rather than weight × maturity.
Array (Sim × Stock × Year × F).
RemovalsTotal removals-per-recruit (landings + dead discards),
summed over fleets. Array (Sim × Stock × Year × F).
LandingsLandings-per-recruit, summed over fleets.
Array (Sim × Stock × Year × F).
MiscList reserved for internal use.
Creates plots of the Data object in the R console. Wrapper for summary(Data)
## S3 method for class 'Data' plot( x, wait = TRUE, i = 1, plots = "all", rmd = FALSE, head = "##", tplot = 25, ... )## S3 method for class 'Data' plot( x, wait = TRUE, i = 1, plots = "all", rmd = FALSE, head = "##", tplot = 25, ... )
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? |
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 |
Plot the projected biomass, fishing, mortality rate and yield for all stocks and MPs
## 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, ... )## 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, ... )
x |
Object of class |
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 |
T.Carruthers
Plot the stocks, fleets, catch fractions and relationships in multi operating model object
## S4 method for signature 'MOM,missing' plot(x, silent = TRUE, maxsims = 6)## S4 method for signature 'MOM,missing' plot(x, silent = TRUE, maxsims = 6)
x |
Object of class |
silent |
Logical. Do you wish to see print outs / warnings? |
maxsims |
Integer. What are the maximum number of individual simulations you wish to plot? |
T.Carruthers
Plot MSE object
## S3 method for class 'MSE' plot(x, ...)## S3 method for class 'MSE' plot(x, ...)
x |
object of class MSE |
... |
other parameters passed to plot (currently ignored) |
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.
## 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, ... )## 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, ... )
x |
An object of class |
Object |
An object of class |
Stock |
An object of class |
nsamp |
The number of random samples to show in the plot |
nsim |
The number of simulations (only used for objects not of class |
nyears |
The number of historical years (only used for objects not of class |
proyears |
The number of projection years (only used for objects not of class |
output_file |
Name of the output html file (without file extension) |
output_dir |
Output directory. Defaults to |
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:
|
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 |
## 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)## 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)
This function prints out the available plotting functions for objects of class MSE or Data
plotFun(class = c("MSE", "Data"), msg = TRUE)plotFun(class = c("MSE", "Data"), msg = TRUE)
class |
Character string. Prints out the plotting functions for objects of this class. |
msg |
Logical. Should the functions be printed to screen? |
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.
A. Hordyk
A basic SSB plot for debugging runMSE output
plotmulti(MSEmulti, maxsim = 8)plotmulti(MSEmulti, maxsim = 8)
MSEmulti |
An object of class MMSE arising from a run of multiMSE(MOM, ...) |
maxsim |
Integer. The number of simulations to plot |
T.Carruthers
As title.
plotOFL(Data, xlims = NA, perc = 0.5)plotOFL(Data, xlims = NA, perc = 0.5)
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 |
A table of performance metrics.
T. Carruthers
A fairly tidy time-series quantile plot
plotquant( x, p = c(0.05, 0.25, 0.75, 0.95), yrs, qcol, lcol, addline = T, ablines = NA )plotquant( x, p = c(0.05, 0.25, 0.75, 0.95), yrs, qcol, lcol, addline = T, ablines = NA )
x |
Matrix. A time series quantity |
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. |
T.Carruthers
Plot a relationship between stocks
plotRel(Stocks, Rel, Relno, Snams, leg = F, extras = 0)plotRel(Stocks, Rel, Relno, Snams, leg = F, extras = 0)
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. |
T.Carruthers
Create a table of Performance Limits and Performance Objectives
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" )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" )
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: |
FeaseMPs |
Optional. Character vector of MP names that are considered feasible. e.g. the output from |
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 |
PMLimit invisibly returns names of MPs that pass all performance limits
PMLimit(): Create a table of Performance Limits
PMObj(): Create a table of Performance Objectives.
A. Hordyk
## Not run: MSE <- runMSE() PMLimit(MSE, "P50", "PNOF", Prob=0.9) PMObj(MSE, "P100", "LTY") ## End(Not run)## Not run: MSE <- runMSE() PMLimit(MSE, "P50", "PNOF", Prob=0.9) PMObj(MSE, "P100", "LTY") ## End(Not run)
Used internally
NameName of the Performance Metric. Character
CaptionA caption to be used in plots. Character, call, or function.
StatStatistic of interest for the PM. Dimensions: nsim, nMP, yrs. Array
RefReference value to calculate probability for statistic. Numeric.
ProbProbability (mean over years) Dimensions: nsim by MP. Matrix, numeric or data.frame
MeanMean probability (mean over years and simulations). Numeric. Length nMPs
MPsName of MPs. Single value. Character string
Objects can be created by calls of the form
new('PMobj')
A. Hordyk
popdynamics ClassStores population time-series for a single stock across simulations, ages, years, and areas.
NumberNumber-at-age. List of length nStock, each element an array
with dimensions Sim, Age, Year, Area.
BiomassTotal biomass. Array with dimensions Sim, Stock, Year.
SBiomassSpawning biomass. Array with dimensions Sim, Stock, Year.
SProductionSpawning production. Array with dimensions Sim, Stock, Year.
MiscMiscellaneous list for additional outputs.
Generic dispatcher function to populate operating model objects and their components.
Populate(object, ...)Populate(object, ...)
object |
An object to populate. The class of |
... |
Named arguments passed to the appropriate |
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.
The populated object, of the same class as object.
## 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)## 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 by setting fleet/gear efficiency values for
historical and projected years, and applying optional stochastic or
increasing catchability parameters.
PopulateCatchability( Catchability, nSim = 5, HistYears = NULL, ProjYears = NULL, seed = NULL, silent = FALSE )PopulateCatchability( Catchability, nSim = 5, HistYears = NULL, ProjYears = NULL, seed = NULL, silent = FALSE )
Catchability |
A |
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 |
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.
A populated Catchability() object.
## Not run: Catch <- Catchability() Catch_pop <- PopulateCatchability( Catchability = Catch, nSim = 50, HistYears = 2000:2020, ProjYears = 2021:2025, seed = 123 ) ## End(Not run)## Not run: Catch <- Catchability() Catch_pop <- PopulateCatchability( Catchability = Catch, nSim = 50, HistYears = 2000:2020, ProjYears = 2021:2025, seed = 123 ) ## End(Not run)
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.
PopulateCatchObs(Catch, nSim, HistYears, ProjYears)PopulateCatchObs(Catch, nSim, HistYears, ProjYears)
Catch |
A catchobs object. Used for both landed catch
( |
nSim |
Integer. Number of simulation replicates. |
HistYears |
Integer vector. Calendar years of the historical period. |
ProjYears |
Integer vector. Calendar years of the projection period. |
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().
A populated catchobs object.
PopulateObs(), catchobs, PopulateObsCV(),
PopulateObsError(), PopulateObsBias(), PopulateObsRef()
Populates a Closure array for a fleet, ensuring proper dimensions across
simulations, years, and spatial areas.
PopulateClosure(Closure, nArea, nSim = 5, Years, silent = FALSE)PopulateClosure(Closure, nArea, nSim = 5, Years, silent = FALSE)
Closure |
An array representing fleet-specific area closures, or |
nArea |
Integer. Number of spatial areas. |
nSim |
Integer. Number of simulation replicates. |
Years |
Numeric vector of model years. |
silent |
Logical; if |
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.
An array representing fleet area closures with proper dimensions and dimnames.
## Not run: Closure <- NULL Closure_pop <- PopulateClosure(Closure, nArea = 5, nSim = 3, Years = 2000:2025) ## End(Not run)## Not run: Closure <- NULL Closure_pop <- PopulateClosure(Closure, nArea = 5, nSim = 3, Years = 2000:2025) ## End(Not run)
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.
PopulateCompObs( Comp, nSim, HistYears, ProjYears, Bins = NULL, BinName = "Class" )PopulateCompObs( Comp, nSim, HistYears, ProjYears, Bins = NULL, BinName = "Class" )
Comp |
A compobs object. Used for landed catch-at-age
( |
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 |
BinName |
Character scalar. Name used for the bin dimension in
populated arrays, typically |
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.
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:
Base concentration:
Apply shift (if non-NULL):
Dirichlet draw:
Multinomial draw:
A populated compobs object.
CompObs(), compobs, PopulateObs(), ConditionObs_Comp()
Populate a Depletion object by generating initial and final depletion
values across simulation replicates, and validating the reference biomass.
PopulateDepletion(Depletion, nSim = 5, seed = NULL, silent = FALSE)PopulateDepletion(Depletion, nSim = 5, seed = NULL, silent = FALSE)
Depletion |
A |
nSim |
Integer. Number of simulation replicates. |
seed |
Integer. Random seed used for stochastic generation. |
silent |
Logical. If |
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.
A populated Depletion() object.
## Not run: # Assuming a Depletion object `D` exists D_pop <- PopulateDepletion(D, nSim = 10, seed = 123) ## End(Not run)## Not run: # Assuming a Depletion object `D` exists D_pop <- PopulateDepletion(D, nSim = 10, seed = 123) ## End(Not run)
Populates a DiscardMortality object with mean-at-age and mean-at-length
values.
PopulateDiscardMortality( DiscardMortality, Ages = NULL, Length = NULL, nSim = 5, Years = NULL, nArea = 1, CalcAtLength = TRUE, seed = NULL, silent = FALSE, force = FALSE, replace = FALSE, ASKOverride = NULL )PopulateDiscardMortality( DiscardMortality, Ages = NULL, Length = NULL, nSim = 5, Years = NULL, nArea = 1, CalcAtLength = TRUE, seed = NULL, silent = FALSE, force = FALSE, replace = FALSE, ASKOverride = NULL )
DiscardMortality |
A |
Ages |
An |
Length |
A |
nSim |
Integer. Number of simulation replicates. |
Years |
Numeric vector of model years. |
nArea |
Integer. Number of spatial areas. |
CalcAtLength |
Logical; if |
seed |
Integer. Random seed used for stochastic generation. |
silent |
Logical; if |
force |
Logical; if |
replace |
Used internally. |
ASKOverride |
Used internally. |
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
A populated DiscardMortality() object.
## Not run: DM <- DiscardMortality() DM_pop <- PopulateDiscardMortality( DM, Ages = Ages, Length = Length, Years = 2000:2025, nSim = 5 ) ## End(Not run)## Not run: DM <- DiscardMortality() DM_pop <- PopulateDiscardMortality( DM, Ages = Ages, Length = Length, Years = 2000:2025, nSim = 5 ) ## End(Not run)
Populate an Effort object by generating historical effort,
and populating distribution and targeting across areas and simulation replicates.
PopulateEffort(Effort, HistYears, nArea = 1, nSim = 5, seed = NULL)PopulateEffort(Effort, HistYears, nArea = 1, nSim = 5, seed = NULL)
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. |
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.
A populated Effort() object.
## Not run: Eff <- Effort() Eff_pop <- PopulateEffort( Effort = Eff, HistYears = 2000:2025, nArea = 3, nSim = 50, seed = 123 ) ## End(Not run)## Not run: Eff <- Effort() Eff_pop <- PopulateEffort( Effort = Eff, HistYears = 2000:2025, nArea = 3, nSim = 50, seed = 123 ) ## End(Not run)
Populate an effortobs object by expanding CV, generating stochastic error arrays, and generating multiplicative bias across simulations.
PopulateEffortObs(Effort, nSim, HistYears, ProjYears)PopulateEffortObs(Effort, nSim, HistYears, ProjYears)
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. |
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.
A populated effortobs object.
PopulateObs(), effortobs, PopulateObsCV(),
PopulateObsError(), PopulateObsBias()
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.
PopulateFecundity( Fecundity, Ages = NULL, Length = NULL, Weight = NULL, Maturity = NULL, Years = NULL, nSim = 5, seed = NULL, silent = FALSE, CalcAtLength = FALSE, force = FALSE )PopulateFecundity( Fecundity, Ages = NULL, Length = NULL, Weight = NULL, Maturity = NULL, Years = NULL, nSim = 5, seed = NULL, silent = FALSE, CalcAtLength = FALSE, force = FALSE )
Fecundity |
A |
Ages |
An |
Length |
A |
Weight |
A |
Maturity |
A |
Years |
Numeric vector of model years. |
nSim |
Integer. Number of simulation replicates. |
seed |
Integer. Random seed used for stochastic generation. |
silent |
Logical. If |
CalcAtLength |
Logical. If |
force |
Logical. If |
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()
A populated Fecundity() object.
Populate(), PopulateStock(), PopulateLength(), PopulateWeight(),
PopulateMaturity()
## 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)## 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 by generating effort, catchability, selectivity,
retention, discard mortality, and spatial closures for a fleet.
PopulateFleet(Fleet, Stock, seed = 103, silent = FALSE, force = FALSE)PopulateFleet(Fleet, Stock, seed = 103, silent = FALSE, force = FALSE)
Fleet |
A |
Stock |
A populated |
seed |
Integer. Random seed used for stochastic generation. |
silent |
Logical. If |
force |
Logical. If |
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.
A populated Fleet() object.
## Not run: F <- Fleet() F_pop <- PopulateFleet(Fleet = F, Stock = Stock, seed = 123, nSim = 50) ## End(Not run)## Not run: F <- Fleet() F_pop <- PopulateFleet(Fleet = F, Stock = Stock, seed = 123, nSim = 50) ## End(Not run)
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.
PopulateIndexObs(Index, nSim, HistYears, ProjYears)PopulateIndexObs(Index, nSim, HistYears, ProjYears)
Index |
An indicesobs object. Used for both CPUE indices
( |
nSim |
Integer. Number of simulation replicates. |
HistYears |
Integer vector. Calendar years of the historical period. |
ProjYears |
Integer vector. Calendar years of the projection period. |
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.
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 be the raw log-errors
drawn from where and are
derived from CV. The AR(1) series is constructed as:
where is the per-simulation lag-1 autocorrelation coefficient
(AC). This formulation preserves the marginal variance
for all values of
. The AR(1) series is then exponentiated to return to the
natural scale: .
A populated indicesobs object.
PopulateObs(), indicesobs, PopulateObsCV(),
PopulateObsError(), PopulateObsAC(),
PopulateObsRef()
Populate a Length object by generating stochastic length-at-age values,
expanding parameters across simulation replicates and years, and optionally
constructing age–length keys.
PopulateLength( Length, Ages = NULL, Years = NULL, nSim = 5, ALK = TRUE, seed = NULL, silent = FALSE, force = FALSE )PopulateLength( Length, Ages = NULL, Years = NULL, nSim = 5, ALK = TRUE, seed = NULL, silent = FALSE, force = FALSE )
Length |
A |
Ages |
An |
Years |
Numeric vector of model years. If |
nSim |
Integer. Number of simulation replicates. |
ALK |
Logical. If |
seed |
Integer. Random seed used for stochastic generation. |
silent |
Logical. If |
force |
Logical. If |
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.
A populated Length() object.
## Not run: Length <- PopulateLength( Length, Ages = Ages, Years = Years, nSim = 100, ALK = TRUE, seed = 123 ) ## End(Not run)## Not run: Length <- PopulateLength( Length, Ages = Ages, Years = Years, nSim = 100, ALK = TRUE, seed = 123 ) ## End(Not run)
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.
PopulateMaturity( Maturity, Ages = NULL, Length = NULL, Weight = NULL, Years = NULL, nSim = 5, seed = NULL, silent = FALSE, CalcAtLength = FALSE, force = FALSE )PopulateMaturity( Maturity, Ages = NULL, Length = NULL, Weight = NULL, Years = NULL, nSim = 5, seed = NULL, silent = FALSE, CalcAtLength = FALSE, force = FALSE )
Maturity |
A |
Ages |
An |
Length |
A |
Weight |
A |
Years |
Numeric vector of model years. |
nSim |
Integer. Number of simulation replicates. |
seed |
Integer. Random seed used for stochastic generation. |
silent |
Logical. If |
CalcAtLength |
Logical. If |
force |
Logical. If |
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
A populated Maturity() object.
Populate(), PopulateStock(), PopulateLength(), PopulateWeight()
## Not run: M <- PopulateMaturity( Maturity, Ages = Ages, Length = Length, Weight = Weight, Years = Years, nSim = 100, CalcAtLength = TRUE, seed = 123 ) ## End(Not run)## Not run: M <- PopulateMaturity( Maturity, Ages = Ages, Length = Length, Weight = Weight, Years = Years, nSim = 100, CalcAtLength = TRUE, seed = 123 ) ## End(Not run)
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.
PopulateNaturalMortality( NaturalMortality, Ages = NULL, Length = NULL, Years = NULL, nSim = 5, CalcAtLength = FALSE, seed = NULL, silent = FALSE, force = FALSE )PopulateNaturalMortality( NaturalMortality, Ages = NULL, Length = NULL, Years = NULL, nSim = 5, CalcAtLength = FALSE, seed = NULL, silent = FALSE, force = FALSE )
NaturalMortality |
A |
Ages |
An |
Length |
A |
Years |
Numeric vector of model years. |
nSim |
Integer. Number of simulation replicates. |
CalcAtLength |
Logical. If |
seed |
Integer. Random seed used for stochastic generation. |
silent |
Logical. If |
force |
Logical. If |
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()
A populated NaturalMortality() object.
Populate(), PopulateStock(), PopulateLength()
## Not run: NM <- PopulateNaturalMortality( NaturalMortality, Ages = Ages, Length = Length, Years = Years, nSim = 100, CalcAtLength = TRUE, seed = 123 ) ## End(Not run)## Not run: NM <- PopulateNaturalMortality( NaturalMortality, Ages = Ages, Length = Length, Years = Years, nSim = 100, CalcAtLength = TRUE, seed = 123 ) ## End(Not run)
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.
PopulateObs(Obs, HistYears, ProjYears, nSim, AgeBins = NULL, SizeBins = NULL)PopulateObs(Obs, HistYears, ProjYears, nSim, AgeBins = NULL, SizeBins = NULL)
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 |
SizeBins |
Numeric vector. Length class midpoints, used to name the
|
PopulateObs() coordinates population of all observation error components
of an obs object, calling a dedicated sub-function for each slot:
Effort observation error via PopulateEffortObs()
Landed catch observation error via PopulateCatchObs()
Discarded catch observation error via PopulateCatchObs()
CPUE index observation error via PopulateIndexObs()
Survey index observation error via PopulateIndexObs()
Landed catch-at-age composition error via PopulateCompObs()
Discarded catch-at-age composition error via PopulateCompObs()
Landed catch-at-size composition error via PopulateCompObs()
Discarded catch-at-size composition error via PopulateCompObs()
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.
A populated obs object.
Populate(), PopulateEffortObs(), PopulateCatchObs(),
PopulateIndexObs(), PopulateCompObs()
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.
PopulateOM(OM, silent = FALSE, force = FALSE, standardize_effort = TRUE)PopulateOM(OM, silent = FALSE, force = FALSE, standardize_effort = TRUE)
OM |
An |
silent |
Logical. If |
force |
Logical. If |
standardize_effort |
Logical. Used internally. Apply |
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:
Stocks via PopulateStock()
Fleets via PopulateFleet()
Implementation models (imp)
Observation models (obs)
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.
An OM() object populated with simulation- and time-specific values.
Populate(), PopulateStock(), PopulateFleet()
## Not run: OM <- PopulateOM(OM) ## End(Not run)## Not run: OM <- PopulateOM(OM) ## End(Not run)
Populates a Retention object with mean-at-age, mean-at-length, or
mean-at-weight values.
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 )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 )
Retention |
A |
Ages |
An |
Length |
A |
Weight |
A |
Maturity |
A |
nSim |
Integer. Number of simulation replicates. |
Years |
Numeric vector of model years. |
nArea |
Integer. Number of spatial areas. |
CalcAtLength |
Logical; if |
seed |
Integer. Random seed used for stochastic generation. |
silent |
Logical; if |
force |
Logical; if |
replace |
Used internally. |
ASKOverride |
Used internally. |
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
A populated Retention() object.
## Not run: Ret <- Retention() Ret_pop <- PopulateRetention( Ret, Ages = Ages, Length = Length, Weight = Weight, Maturity = Maturity, Years = 2000:2025, nSim = 5 ) ## End(Not run)## 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 by generating selectivity-at-age,
selectivity-at-length, or selectivity-at-weight values for a fleet.
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 )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 )
Selectivity |
A |
Ages |
An |
Length |
A |
Weight |
A |
Maturity |
A |
nSim |
Integer. Number of simulation replicates. |
Years |
Numeric vector of model years. |
nArea |
Integer. Number of spatial areas. |
CalcAtLength |
Logical. If |
seed |
Integer. Random seed used for stochastic generation. |
silent |
Logical. If |
CheckMaxValue |
Logical. If |
replace |
Used interally. |
ASKOverride |
Used internally. |
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.
A populated Selectivity() object.
## 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)## 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 by validating or generating spatial structure
for a stock, including movement matrices, unfished distributions, and
relative area size.
PopulateSpatial( Spatial, Ages = NULL, Years = NULL, nSim = 5, seed = NULL, silent = FALSE, force = FALSE )PopulateSpatial( Spatial, Ages = NULL, Years = NULL, nSim = 5, seed = NULL, silent = FALSE, force = FALSE )
Spatial |
A |
Ages |
An |
Years |
Numeric vector of model years. |
nSim |
Integer. Number of simulation replicates. |
seed |
Integer. Random seed used for stochastic generation. |
silent |
Logical. If |
force |
Logical. If |
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.
A populated Spatial() object.
Populate(), PopulateStock(), PopulateFleet()
## Not run: Spatial <- PopulateSpatial( Spatial, Ages = Ages, Years = Years, nSim = 100, seed = 123 ) ## End(Not run)## Not run: Spatial <- PopulateSpatial( Spatial, Ages = Ages, Years = Years, nSim = 100, seed = 123 ) ## End(Not run)
Populate a SRR object by generating recruitment deviations,
and structuring values across simulation replicates and years.
PopulateSRR( SRR, Ages = NULL, CurrentYear = NULL, Years = NULL, nSim = 5, seed = NULL, silent = FALSE, force = FALSE )PopulateSRR( SRR, Ages = NULL, CurrentYear = NULL, Years = NULL, nSim = 5, seed = NULL, silent = FALSE, force = FALSE )
SRR |
A |
Ages |
An |
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 |
force |
Logical. If |
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
A populated SRR() object.
## 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)## 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 by generating stochastic biological quantities,
expanding values across simulation replicates and years, and filling
derived age- and length-based components.
PopulateStock( Stock, nYear, pYear, CurrentYear = NULL, nSim = 5, Seasons = 1, ALK = TRUE, AWK = TRUE, seed = 102, silent = FALSE, force = FALSE, CalcAtLength = FALSE )PopulateStock( Stock, nYear, pYear, CurrentYear = NULL, nSim = 5, Seasons = 1, ALK = TRUE, AWK = TRUE, seed = 102, silent = FALSE, force = FALSE, CalcAtLength = FALSE )
Stock |
A |
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 |
nSim |
Integer. Number of simulation replicates. |
Seasons |
Integer. Number of seasons per year. |
ALK |
Logical. If |
AWK |
Logical. If |
seed |
Integer. Random seed used for stochastic generation. |
silent |
Logical. If |
force |
Logical. If |
CalcAtLength |
Logical. If |
PopulateStock() coordinates population of all biological components
associated with a stock, including:
Length-at-age via PopulateLength()
Weight-at-age via PopulateWeight()
Natural mortality via PopulateNaturalMortality()
Maturity via PopulateMaturity()
Fecundity via PopulateFecundity()
Stock–recruitment via PopulateSRR()
Spatial structure via PopulateSpatial()
Initial depletion via PopulateDepletion()
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.
A populated Stock() object.
## Not run: Stock <- PopulateStock( Stock, nYear = 40, pYear = 20, nSim = 100, seed = 123 ) ## End(Not run)## Not run: Stock <- PopulateStock( Stock, nYear = 40, pYear = 20, nSim = 100, seed = 123 ) ## End(Not run)
Populate a Weight object by generating stochastic weight-at-age values,
expanding parameters across simulation replicates and years, and optionally
constructing age–weight keys.
PopulateWeight( Weight, Ages = NULL, Length = NULL, Years = NULL, nSim = 5, AWK = FALSE, CalcAtLength = FALSE, seed = NULL, silent = FALSE, force = FALSE )PopulateWeight( Weight, Ages = NULL, Length = NULL, Years = NULL, nSim = 5, AWK = FALSE, CalcAtLength = FALSE, seed = NULL, silent = FALSE, force = FALSE )
Weight |
A |
Ages |
An |
Length |
A |
Years |
Numeric vector of model years. If |
nSim |
Integer. Number of simulation replicates. |
AWK |
Logical. If |
CalcAtLength |
Logical. If |
seed |
Integer. Random seed used for stochastic generation. |
silent |
Logical. If |
force |
Logical. If |
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
A populated Weight() object.
Populate(), PopulateStock(), PopulateLength()
## Not run: Weight <- PopulateWeight( Weight, Ages = Ages, Length = Length, Years = Years, nSim = 100, AWK = TRUE, CalcAtLength = TRUE, seed = 123 ) ## End(Not run)## Not run: Weight <- PopulateWeight( Weight, Ages = Ages, Length = Length, Years = Years, nSim = 100, AWK = TRUE, CalcAtLength = TRUE, seed = 123 ) ## End(Not run)
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.
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.
Pars — Input FormatsEach 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 ConventionsAll 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.
MeanAtLength and MeanAtWeight Relate to MeanAtAge
openMSE uses age-based accounting, so MeanAtAge
is ultimately what is needed. MeanAtLength and MeanAtWeight serve two
roles:
Generating length- or weight- data (e.g., observed size distributions, length-based data).
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 MeanAtLength → MeanAtAge via the ALK.
If MeanAtWeight is populated and MeanAtAge is not, Populate()
converts MeanAtWeight → MeanAtAge 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.
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.
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)
Length(), Weight(), Maturity(), NaturalMortality(), Fecundity()
for the stock sub-object constructors that follow this pattern.
Selectivity(), Retention() for the fleet
sub-object constructors that follow this pattern.
LengthModels(), WeightModels(), MaturityModels(),
NaturalMortalityModels(), SelectivityModels(), RetentionModels(),
for the available built-in models and their
required parameter sets.
Extend() for the array extension rules.
Populate() for the top-level population dispatch function.
Extracts the projected data objects from an mse object.
PPD(MSE)PPD(MSE)
MSE |
An object of class mse. |
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
A named list of PPD (data objects) for each simulation, MP, and stock/complex.
A shorter version of the plot method for MSEs that just shows the projected trends in stock status and over exploitation
Pplot(MSEobj, nam = NA, maxMP = 10, MPs = NA, maxsims = 20)Pplot(MSEobj, nam = NA, maxMP = 10, MPs = NA, maxsims = 20)
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 |
T. Carruthers
A projection by projection plot of F/FMSY, B/BMSY, B/B0, and yield
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, ... )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, ... )
MSEobj |
An object of class MSE |
YVar |
What to plot on the y-axis? Options are: |
MPs |
Optional subset by MP |
sims |
Optional subset by simulation |
traj |
Plot all projections ( |
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 ( |
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 |
T. Carruthers & A.Hordyk
multiHist objectsPrint method for multiHist objects
## S3 method for class 'multiHist' print(x, ...)## S3 method for class 'multiHist' print(x, ...)
x |
For |
... |
Additional arguments (not used) |
Prints a summary of object x to the console
RepList objectPrint a summary of a RepList object, which is a list of outputs
from r4ss::SS_output.
## S3 method for class 'RepList' print(x, ...)## S3 method for class 'RepList' print(x, ...)
x |
A |
... |
Additional arguments (currently ignored). |
Invisibly returns x.
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.
Project( Hist, MPs = NULL, parallel = FALSE, silent = FALSE, nSim = NULL, Reduce = TRUE, extended = FALSE, checkMPs = FALSE )Project( Hist, MPs = NULL, parallel = FALSE, silent = FALSE, nSim = NULL, Reduce = TRUE, extended = FALSE, checkMPs = FALSE )
Hist |
A hist or Hist-legacy object containing the
conditioned operating model and historical dynamics, as returned by
|
MPs |
Character vector of MP names to project. MPs must be functions
available in the current environment. f |
parallel |
Logical or named list controlling parallel execution of
MPs. If |
silent |
Logical. Suppress progress messages if |
nSim |
Integer. If provided, reduces the number of simulations to
|
Reduce |
Logical. Reserved for future use. Default |
extended |
Logical. If |
checkMPs |
Logical. Validate MP names and availability before
projecting. Only used for Hist-legacy objects. Default |
An mse or a MSE-legacy object containing projection results for all MPs.
A NAFO / ICCAT / SSB style MSE performance whisker plot
PWhisker(MSEobj)PWhisker(MSEobj)
MSEobj |
An object of class MSE |
A box plot of performance
T. Carruthers
Plots quantiles and simulations for a stochastic time-series variable
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 )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 )
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. |
T. Carruthers
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.
rDirichletMultinomial(n, alpha)rDirichletMultinomial(n, alpha)
n |
Integer. Total count (sample size) for the multinomial draw. |
alpha |
Numeric vector of positive Dirichlet concentration parameters,
length |
Given concentration vector and total count
:
The marginal distribution of is Dirichlet-Multinomial
with mean and
variance exceeding the multinomial by a factor of
.
The Dirichlet draw is obtained via the standard gamma representation:
independent draws normalised to sum
to 1.
ESS and Theta
In the composition observation model (see CompObs()), the concentration
vector is constructed as:
where 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.
Integer vector of length nBin summing to n.
CompObs(), GenHistData_AgeComp(), GenHistData_SizeComp()
# 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)# 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)
What MPs do not return NAs from the real data
RealFease(Data = NULL)RealFease(Data = NULL)
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) |
a vector of MP names that calculate without errors for the specific data.
T. Carruthers
'Rec'
An object for storing the MP recommendations
TACA numeric value with the TAC recommendation
EffortA numeric value with the effort recommendation as a fraction of current (nyear) fishing effort
SpatialA boolean vector of length 'nareas' specifying if area is open (1) or closed (0) to fishing
AllocateA boolean value describing if effort should be re-allocated from close to open areas
LR5smallest length at 5 per cent retention - in absolute units - i.e same units as Linf and L50
LFRsmallest length at full retention - in absolute units - i.e same units as Linf and L50
HSupper harvest slot (no retention above this) - in absolute units - i.e same units as Linf and L50
Rmaxlenretention of the largest size class - fraction between 0 and 1
L5smallest length at 5 per cent selection - in absolute units - i.e same units as Linf and L50
LFSsmallest length at full selection - in absolute units - i.e same units as Linf and L50
Vmaxlenselection of the largest size class - fraction between 0 and 1
Fdiscfraction of discarded fish that die - fraction between 0 and 1
DRDiscard rate - the fraction of caught fish that are discarded
MiscAn empty list that can be used to store information and pass on to MPs in future
Objects can be created by calls of the form
new('Rec')
A. Hordyk
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.
ReduceDims( array, IncSim = TRUE, IncAge = FALSE, IncYear = FALSE, debug = FALSE )ReduceDims( array, IncSim = TRUE, IncAge = FALSE, IncYear = FALSE, debug = FALSE )
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 |
IncAge |
Logical; reduce the |
IncYear |
Logical; reduce the |
debug |
Logical. Print debug messages? |
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.
An object of the same class as array, with reduced dimensions
where applicable.
Subsets an OM() or Hist() object by reducing number
of simulations to nSim
ReduceNSim(object, nSim = NULL)ReduceNSim(object, nSim = NULL)
object |
|
nSim |
Integer. The maximum number of simulations |
The OM() or Hist() with reduced nSim
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()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()
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.
SPR0List or array of unfished spawning potential ratio (SPR0), by stock and simulation.
MSYAn object containing MSY-based reference points such as FMSY, BMSY, and MSY.
LandingsList or array of reference landings values.
RemovalsList or array of reference removals values.
F01List or array of fishing mortality corresponding to the 0.1 slope reference point.
FMaxList or array of fishing mortality at maximum yield-per-recruit.
FCrashList or array of fishing mortality leading to population collapse.
SPRcrashList or array of spawning potential ratio at collapse.
MGTList or array of mean generation time reference points.
BLowList or array defining the B-Low biomass reference points.
MiscMiscellaneous list for additional reference quantities or diagnostics.
referencedata ClassStores biological and management reference points by extending
refpointsMSY. Used in the Reference slot of a data object.
ReferenceData()ReferenceData()
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.
ReferenceData() returns a referencedata object.
MiscA named list for any additional reference point metadata not covered by the inherited refpointsMSY slots.
ReferenceData() creates a new referencedata object.
refpointsMSY S4 ClassAn S4 class storing MSY-based biological reference points. Produced internally during reference point calculations and not intended to be modified directly by users.
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.
FMSYFishing mortality rate at MSY (Sim × Stock × Year).
BMSYTotal biomass at MSY (Sim × Stock × Year).
SBMSYSpawning biomass at MSY (Sim × Stock × Year).
SPMSYSpawning production at MSY (Sim × Stock × Year).
SPRMSYSpawning potential ratio at MSY (Sim × Stock × Year).
MSYLandingsLanded catch at MSY (Sim × Stock × Year).
MSYDiscardsDead discards at MSY (Sim × Stock × Year).
MiscList reserved for internal use.
Renames stocks and/or fleets throughout an operating model (OM) object, updating all names recursively across S4 slots, lists, and array dimension names.
Rename(object, Stocks = NULL, Fleets = NULL)Rename(object, Stocks = NULL, Fleets = NULL)
object |
An object of class |
Stocks |
Optional named character vector or named list mapping new
stock names to current names (e.g. |
Fleets |
Optional named character vector or named list mapping new
fleet names to current names. If |
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').
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)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)
Reorders stocks and/or fleets throughout an operating model (OM) object, updating all list elements and array dimension orders recursively across S4 slots.
Reorder(object, Stocks = NULL, Fleets = NULL)Reorder(object, Stocks = NULL, Fleets = NULL)
object |
An object of class |
Stocks |
Optional character vector of all stock names in the desired
order. Must contain exactly the same names as currently in |
Fleets |
Optional character vector of all fleet names in the desired
order. Must contain exactly the same names as currently in |
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.
The input om object with stocks and/or fleets reordered
throughout.
OM <- AddFleet(SingleStockOM, 'DummyFleet') FleetNames(OM) OM2 <- Reorder(OM, Fleets = rev(FleetNames(OM))) FleetNames(OM2)OM <- AddFleet(SingleStockOM, 'DummyFleet') FleetNames(OM) OM2 <- Reorder(OM, Fleets = rev(FleetNames(OM))) FleetNames(OM2)
A function that replaces a Stock, Fleet, Obs, or Imp object from an OM with one from another object.
Replace( OM, from, Sub = c("Stock", "Fleet", "Obs", "Imp"), Name = NULL, silent = FALSE )Replace( OM, from, Sub = c("Stock", "Fleet", "Obs", "Imp"), Name = NULL, silent = FALSE )
OM |
An operating model object (class OM) which will be updated with a sub-model from another OM |
from |
An object of class |
Sub |
A character string specifying what object type to replace (only used if |
Name |
Character. Name for the new OM object ( |
silent |
Should messages be printed? |
An object of class OM
A. Hordyk
# 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")# 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")
Replicates position 1 data to multiple positions for sensitivity testing etc
replic8(Data, nrep)replic8(Data, nrep)
Data |
A data-limited methods data object |
nrep |
The number of positions to expand the DLM object to |
T. Carruthers
A HTML Data Report is generated and opened in a web browser
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 )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 )
Data |
Either an object of class |
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: |
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 |
overwrite |
Logical. Overwrite an existing file with the same name? |
Nothing. A Data Report is generated and saved in dir
A. Hordyk
## Not run: DataInit('Example') # generate example Data Input and Documentation files Report('Example', 'Example.md') ## End(Not run)## Not run: DataInit('Example') # generate example Data Input and Documentation files Report('Example', 'Example.md') ## End(Not run)
Dataframe with required data slots for built-in MPs
ReqDataReqData
An object of class data.frame with 123 rows and 2 columns.
A function that finds all the MPs and searches the function text for slots in the Data object
Required(funcs = NA, noCV = FALSE)Required(funcs = NA, noCV = FALSE)
funcs |
A character vector of management procedures |
noCV |
Logical. Should the CV slots be left out? |
A matrix of MPs and their required data in terms of slotnames('Data'),
and broad Data classes for each MP
T. Carruthers
Can Cant Needed MPtype Data-legacy
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.
Retention( Pars = list(), Model = NULL, MeanAtAge = NULL, MeanAtLength = NULL, MeanAtWeight = NULL, Classes = NULL, isRel = FALSE, Misc = list() ) Retention(x) <- valueRetention( Pars = list(), Model = NULL, MeanAtAge = NULL, MeanAtLength = NULL, MeanAtWeight = NULL, Classes = NULL, isRel = FALSE, Misc = list() ) Retention(x) <- value
Pars |
Named list of retention parameters passed to the retention
model function. Parameter names must match the arguments of the chosen
model (see If If |
Model |
Character or function or |
MeanAtAge |
Numeric array or |
MeanAtLength |
Numeric array or |
MeanAtWeight |
Numeric array or |
Classes |
Numeric vector or |
isRel |
Logical. If |
Misc |
List. Miscellaneous additional inputs. Default |
x |
|
value |
For |
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.
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.
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.
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().
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.
retention for the class definition and slot-level documentation.
RetentionModels() for available model functions and their parameters.
Fleet() for the enclosing fleet constructor.
Selectivity(), DiscardMortality() for related fleet components.
Specifying Biological and Fleet Schedules for how
Pars, Model, and MeanAt* arrays are structured.
PopulateRetention() for population details.
Other fleet:
Bioeconomic(),
Catchability(),
DiscardMortality(),
Effort(),
Fleet(),
Selectivity(),
bioeconomic-class,
catchability-class,
discardmortality-class,
effort-class,
fleet-class,
retention-class,
selectivity-class
# See man-examples/class-Retention.R# See man-examples/class-Retention.R
retention S4 ClassDefines 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.
Parslist. Named list of retention parameters passed to Model.
See Retention() and RetentionModels().
Modelfunction or character or NULL. Retention model identifier
or function. See RetentionModels().
isRellogical, numeric, or character. Whether length-based
parameters are expressed relative to maturity L50. See Retention().
MeanAtAgenumeric array or NULL. Mean retention-at-age
(Sim x Age x Year x Area). See Retention().
MeanAtLengthnumeric array or NULL. Mean retention-at-length
(Sim x Length x Year x Area). See Retention().
MeanAtWeightnumeric array or NULL. Mean retention-at-weight
(Sim x Weight x Year x Area). See Retention().
Classesnumeric or NULL. Length or weight class midpoints
corresponding to the second dimension of MeanAtLength or
MeanAtWeight.
Misclist. Miscellaneous additional inputs. For internal use.
Retention() for the constructor and full parameter
documentation.
RetentionModels() for available model functions.
fleet for the enclosing fleet object.
Other fleet:
Bioeconomic(),
Catchability(),
DiscardMortality(),
Effort(),
Fleet(),
Retention(),
Selectivity(),
bioeconomic-class,
catchability-class,
discardmortality-class,
effort-class,
fleet-class,
selectivity-class
Logistic, knife-edge, and double-normal retention-at-age,
retention-at-length, and retention-at-weight models for use in a
Retention() object.
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)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)
Ages |
Numeric vector of age classes. |
RA50 |
Numeric. Age at 50% retention (logistic-at-age). |
RA50_95 |
Numeric. Interval between |
MaxRet |
Numeric. Maximum (asymptotic) retention. Default |
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 |
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 |
LR5 |
Numeric. Length at 5% retention (double-normal). |
LFR |
Numeric. Length at full retention (double-normal). |
Rmaxlen |
Numeric. Retention at |
WR5 |
Numeric. Weight at 5% retention (double-normal). |
WFR |
Numeric. Weight at full retention (double-normal). |
Rmaxweight |
Numeric. Retention at |
full |
Logical. If |
print |
Logical. If |
Three families of retention model are available:
Logistic: a standard increasing retention curve parameterised by the
50% and 95% retention points, with asymptote MaxRet:
Knife-edge: full retention at or above a threshold, zero below:
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.
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.
Retention(), Selectivity(), Ages(), Length(), Weight(),
Fleet()
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)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)
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.
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 )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 )
OM |
An operating model object of class OM |
... |
Other named arguments to pass to |
MSEobj |
An object of class MSE with |
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 |
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 |
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 |
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.
T. Carruthers
https://cosewic.ca/index.php/en/
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.
runInMP(Data, MPs = NA, reps = 100)runInMP(Data, MPs = NA, reps = 100)
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. |
A. Hordyk
Run a Management Procedure
runMP(Data, MPs = NA, reps = 100, perc = 0.5, chkMPs = FALSE, silent = FALSE)runMP(Data, MPs = NA, reps = 100, perc = 0.5, chkMPs = FALSE, silent = FALSE)
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? |
invisibly returns the Data object
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.
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, ... )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, ... )
OM |
An om, OM-legacy, hist, or Hist-legacy object.
If |
MPs |
Character vector of MP names to project. MPs must be functions
available in the current environment. If |
Hist |
Logical. If |
silent |
Logical. Suppress progress messages if |
parallel |
Logical or named list controlling parallel execution of
MPs. For legacy
|
extended |
Logical. If |
checkMPs |
Logical. Validate MP names and availability before
projecting. Default |
nSim |
Integer. Reduce the number of simulations to |
nsim |
Integer. Alternative to |
DoDynamicUnfished |
Logical. Calculate dynamic unfished reference
points? Passed to |
DoRefLandings |
Logical. Calculate landings-based reference points?
Passed to |
DoRefRemovals |
Logical. Calculate removals-based reference points?
Passed to |
DoConditionObs |
Logical. Condition observation model on historical
data? Passed to |
DoGenerateData |
Logical. Generate observed data for MPs? Passed to
|
DoMSYRefs |
Logical. Calculate MSY-based reference points? Passed to
|
Reduce |
Logical. Reserved for future use. Default |
... |
Additional arguments. Reserved for future use. |
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.
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.
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.
S4SlotSizes(obj, n = 5, verbose = TRUE)S4SlotSizes(obj, n = 5, verbose = TRUE)
obj |
An S4 object. |
n |
Integer. Number of largest slots to display in the printed summary.
Default is |
verbose |
Logical. If |
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.
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.
## 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)## 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)
A wrapper for saveRDS() that automatically creates the required directory
structure and prints a informational message to the console.
Save(object, path = NULL, overwrite = FALSE, ...)Save(object, path = NULL, overwrite = FALSE, ...)
object |
Any R object to save. |
path |
Character. File path including file name and extension (e.g.,
|
overwrite |
Logical. If |
... |
Additional arguments passed to |
Invisibly returns the full file path of the saved object.
x <- list(a = 1, b = 2) path <- Save(x, path = tempfile(fileext = ".rds")) pathx <- list(a = 1, b = 2) path <- Save(x, path = tempfile(fileext = ".rds")) path
MMSE@PPD
Select DataList for an MP from MMSE@PPD
select_MP(PPD, MP = 1)select_MP(PPD, MP = 1)
PPD |
|
MP |
Numeric value indicating the MP to return DataList |
A nested list Data objects (nstock by nfleet)
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.
Selectivity( Pars = list(), Model = NULL, MeanAtAge = NULL, MeanAtLength = NULL, MeanAtWeight = NULL, Classes = NULL, isRel = FALSE, Misc = list() ) isRel(x) isRel(x) <- value Selectivity(x) <- valueSelectivity( Pars = list(), Model = NULL, MeanAtAge = NULL, MeanAtLength = NULL, MeanAtWeight = NULL, Classes = NULL, isRel = FALSE, Misc = list() ) isRel(x) isRel(x) <- value Selectivity(x) <- value
Pars |
Named list of selectivity parameters passed to the selectivity
model function. Parameter names must match the arguments of the chosen
model (see If If |
Model |
Character or function or |
MeanAtAge |
Numeric array or |
MeanAtLength |
Numeric array or |
MeanAtWeight |
Numeric array or |
Classes |
Numeric vector or |
isRel |
Logical. If |
Misc |
List. Miscellaneous additional inputs. Default |
x |
A selectivity object, or a fleet object for
|
value |
For |
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.
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.
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.
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().
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.
selectivity for the class definition and slot-level documentation.
SelectivityModels() for available model functions and their parameters.
Fleet() for the enclosing fleet constructor.
Retention(), DiscardMortality() for related fleet components.
Specifying Biological and Fleet Schedules for how
Pars, Model, and MeanAt* arrays are structured.
PopulateSelectivity() for population details.
Other fleet:
Bioeconomic(),
Catchability(),
DiscardMortality(),
Effort(),
Fleet(),
Retention(),
bioeconomic-class,
catchability-class,
discardmortality-class,
effort-class,
fleet-class,
retention-class,
selectivity-class
# See man-examples/class-Selectivity.R# See man-examples/class-Selectivity.R
selectivity S4 ClassDefines 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.
Parslist. Named list of selectivity parameters passed to Model.
See Selectivity() and SelectivityModels().
Modelfunction or character or NULL. Selectivity model
identifier or function. See SelectivityModels().
isRellogical, numeric, or character. Whether length-based
parameters are expressed relative to maturity L50. See Selectivity().
MeanAtAgenumeric array or NULL. Mean selectivity-at-age
(Sim x Age x Year x Area). See Selectivity().
MeanAtLengthnumeric array or NULL. Mean selectivity-at-length
(Sim x Length x Year x Area). See Selectivity().
MeanAtWeightnumeric array or NULL. Mean selectivity-at-weight
(Sim x Weight x Year x Area). See Selectivity().
Classesnumeric or NULL. Length or weight class midpoints
corresponding to the second dimension of MeanAtLength or
MeanAtWeight.
Misclist. Miscellaneous additional inputs. Used internally.
Selectivity() for the constructor and full parameter
documentation.
SelectivityModels() for available model functions.
fleet for the enclosing fleet object.
Other fleet:
Bioeconomic(),
Catchability(),
DiscardMortality(),
Effort(),
Fleet(),
Retention(),
Selectivity(),
bioeconomic-class,
catchability-class,
discardmortality-class,
effort-class,
fleet-class,
retention-class
Logistic, knife-edge, and double-normal selectivity-at-age,
selectivity-at-length, and selectivity-at-weight models for use in a
Selectivity() object.
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)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)
Ages |
Numeric vector of age classes. |
SA50 |
Numeric. Age at 50% selectivity (logistic-at-age). |
SA50_95 |
Numeric. Interval between |
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 |
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 |
L5 |
Numeric. Length at 5% selectivity (double-normal). |
LFS |
Numeric. Length at full selectivity (double-normal). |
Vmaxlen |
Numeric. Selectivity at |
W5 |
Numeric. Weight at 5% selectivity (double-normal). |
WFS |
Numeric. Weight at full selectivity (double-normal). |
Vmaxweight |
Numeric. Selectivity at |
full |
Logical. If |
print |
Logical. If |
Three families of selectivity model are available:
Logistic: a standard increasing selectivity curve parameterised by the 50% and 95% selectivity points:
Knife-edge: full selectivity at or above a threshold, zero below:
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.
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.
Selectivity(), Retention(), Ages(), Length(), Weight(),
Fleet()
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)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)
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)
Sense(Data, MP, nsense = 6, reps = 100, perc = c(0.05, 0.5, 0.95), ploty = T)Sense(Data, MP, nsense = 6, reps = 100, perc = c(0.05, 0.5, 0.95), ploty = T)
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?) |
T. Carruthers
## Not run: Data <- Sense(MSEtool::Cobia, "AvC") ## End(Not run)## Not run: Data <- Sense(MSEtool::Cobia, "AvC") ## End(Not run)
Sets up parallel processing using the snowfall package
setup(cpus = NULL, logical = FALSE, ...)setup(cpus = NULL, logical = FALSE, ...)
cpus |
the number of CPUs to use for parallel processing. If left empty
all physical cores will be used, unless |
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 |
... |
other arguments passed to 'snowfall::sfInit' |
## 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)## 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)
Configure the global parallel processing strategy used throughout the
openMSE framework via the future backend.
SetupParallel( workers = future::availableCores(), backend = c("auto", "multisession", "multicore", "sequential"), max_workers = c("physical", "logical"), silent = FALSE ) DisableParallel(silent = FALSE) CheckParallel(parallel)SetupParallel( workers = future::availableCores(), backend = c("auto", "multisession", "multicore", "sequential"), max_workers = c("physical", "logical"), silent = FALSE ) DisableParallel(silent = FALSE) CheckParallel(parallel)
workers |
Integer. Number of parallel workers. Defaults to
|
backend |
Character. Parallel backend to use. One of |
max_workers |
Character. Which CPU cores to count when determining the
worker ceiling. |
silent |
Logical. If |
parallel |
Logical. Has |
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.
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().
"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
SetupParallel() # start of workflow # ... analysis code ... DisableParallel() # restore sequential execution
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
future::plan(), future::availableCores(), furrr::future_map()
## 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)## 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)
Display a formatted summary of MSEtool S4 objects in the console.
object |
An S4 object of the relevant class. |
Briefly prints a couple of lines from str to avoid swamping the console with the contents of very large objects.
## 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)## 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)
object |
S4 object from MSEtool |
Show the output of a PM
## S4 method for signature 'PMobj' show(object)## S4 method for signature 'PMobj' show(object)
object |
object of class MSE |
Show the output of a single MP recommendation
## S4 method for signature 'Rec' show(object)## S4 method for signature 'Rec' show(object)
object |
object of class Rec |
Create of vector of values that correspond with a slot in a list of objects
SIL(listy, sloty)SIL(listy, sloty)
listy |
A list of objects |
sloty |
A character vector representing the slot name |
T. Carruthers
CAA generated with either a multinomial or logistic normal observation model from retained catch-at-age array
simCAA(nsim, yrs, n_age, Cret, CAA_ESS, CAA_nsamp)simCAA(nsim, yrs, n_age, Cret, CAA_ESS, CAA_nsamp)
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 |
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.
CAA array
Simulate CAL and calculate length-at-first capture (LFC), mean length (ML), modal length (Lc), and mean length over modal length (Lbar)
simCAL( nsim, nyears, maxage, CAL_ESS, CAL_nsamp, nCALbins, CAL_binsmid, CAL_bins, vn, retL, Linfarray, Karray, t0array, LenCV )simCAL( nsim, nyears, maxage, CAL_ESS, CAL_nsamp, nCALbins, CAL_binsmid, CAL_bins, vn, retL, Linfarray, Karray, t0array, LenCV )
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#' |
named list with CAL array and LFC, ML, & Lc vectors
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.
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)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)
OM |
Operating model, an object of class |
dist |
A vector of fractions of unfished stock in each area. The length of this vector will determine the
number of areas ( |
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 |
mov |
A four-dimensional array of dimension |
age |
An age from 0 to maxage for the movement-at-age matrix figure when |
type |
Whether to plot a movement matrix for a single age ( |
year |
If |
qval |
The quantile to plot or report the range of values among simulations. |
The operating model OM with movement parameters in slot cpars.
The mov array is of dimension nsim, maxage, nareas, nareas.
simmov(): Estimation function for creating movement matrix.
plot_mov(): Plotting function.
Array mov is age-specific, but currently the movement generated by simmov is
independent of age.
T. Carruthers and Q. Huynh
## 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)## 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)
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.
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 )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 )
OM |
Operating model, an object of class |
dist |
A vector of fractions of unfished stock in each area. The length of this vector will determine the
number of areas ( |
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 |
The operating model OM with movement parameters in slot cpars.
The mov array is of dimension nsim, maxage, nareas, nareas.
simmov2(): Estimation function for creating movement matrix.
Array mov is age-specific, but currently the movement generated by simmov is
independent of age.
T. Carruthers and Q. Huynh
## 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)## 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 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.
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, ... )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, ... )
OM |
An om or OM-legacy object. If |
parallel |
Logical. Use parallel processing? Default |
silent |
Logical. Suppress progress messages if |
nSim |
Integer. Number of simulation replicates. If |
nsim |
Integer. Synonym for |
DoDynamicUnfished |
Logical. Calculate the dynamic unfished population
dynamics? Default |
DoRefLandings |
Logical. Calculate reference yield based on landings?
Default |
DoRefRemovals |
Logical. Calculate reference yield based on total
removals (landings + discards)? Default |
DoConditionObs |
Logical. Condition observation model on historical
fishery data? Default |
DoGenerateData |
Logical. Generate historical fishery data from the
observation model? Default |
DoMSYRefs |
Logical. Calculate MSY-based reference points? Passed to
|
Reduce |
Logical. Reduce object size after simulation for memory
efficiency? Default |
... |
Additional arguments passed to sub-functions. Not currently used |
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.
If OM is an OM-legacy object: a Hist-legacy object.
## 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)## 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)
An object of class Data
SimulatedDataSimulatedData
An object of class Data of length 1.
Functions for running a multi-stock and/or multi-fleet Management Strategy Evaluation (closed-loop simulation) for a specified operating model
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 )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 )
MOM |
A multi-fleet multi-stock operating model (class |
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 |
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 |
dropHist |
Logical. Drop the (very large) |
extended |
Logical. Return extended projection results?
if TRUE, |
Hist |
Should model stop after historical simulations? Returns a list containing all historical data |
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.
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
SimulateMOM(): Simulate historical dynamics for multi-OM
ProjectMOM(): Run Forward Projections for a MOM object
multiMSE(): Run a multi-stock, multi-fleet MSE
T. Carruthers and A. Hordyk
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.
SingleStockOMSingleStockOM
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.
AlbacoreExStock represents a long-lived, slow-growing pelagic species with low natural mortality. See AlbacoreExStock for full parameter details.
AsympExFleet represents a fleet with asymptotic length-based selectivity and effort that stabilises early in the historical period. See AsympExFleet for full parameter details.
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.
The Imp slot is NULL. The imp is currently a placeholder and
implementation error is not applied during simulation. See Imp() for
details.
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
SingleStockOM Stock(SingleStockOM) Fleet(SingleStockOM) ## Not run: Hist <- runMSE(SingleStockOM, MPs = ExampleMPs()) ## End(Not run)SingleStockOM Stock(SingleStockOM) Fleet(SingleStockOM) ## Not run: Hist <- runMSE(SingleStockOM, MPs = ExampleMPs()) ## End(Not run)
Internal function for interactive plot which allows users to specify the relative trajectory and variability in the historical fishing effort.
SketchFun(nyears, Years=NULL)SketchFun(nyears, Years=NULL)
nyears |
Number of years |
Years |
An optional vector of years. Should be nyears long. |
A. Hordyk
Polynomial smoother (no gradient prediction) applied to a vector that can include NA values. Intended to be rapid for use in management procedures
smoothy(xx, plot = F, enp_mult, plotname = "", xlab = "x", ylab = "y", x = NA)smoothy(xx, plot = F, enp_mult, plotname = "", xlab = "x", ylab = "y", x = NA)
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) |
T. Carruthers
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.
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) <- valueSpatial( 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
UnfishedDist |
|
ProbStaying |
|
RelativeSize |
|
Movement |
|
FracOther |
|
Arrangement |
|
CVDist |
|
CVStay |
|
Misc |
|
x |
A spatial object for slot accessors, or a stock
object for |
value |
For |
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.
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))
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)
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))
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)
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")
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
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
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.
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
# ---- 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)# ---- 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)
spatial S4 ClassDefines 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().
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.
UnfishedDistnumeric, 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.
ProbStayingnumeric 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.
RelativeSizenumeric, 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).
Movementarray 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.
FracOtherarray 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.
Arrangementarray or NULL. Spatial layout of areas for plotting
purposes. Reserved for future use; currently stored but not applied.
CVDistnumeric(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.
CVStaynumeric(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.
Misclist. Used internally.
Spatial() for the constructor and accessor functions.
Populate() for array population and movement matrix fitting.
Stock() for the enclosing stock constructor.
Other spatial:
Spatial()
Plots projections of F/FMSY, SB/SBMSY and Yield
Splot(MSEobj, MPs = 5, p = c(0.05, 0.25, 0.5, 0.75, 0.95))Splot(MSEobj, MPs = 5, p = c(0.05, 0.25, 0.5, 0.75, 0.95))
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. |
T. Carruthers
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.
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) <- valueSRR( 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
Pars |
|
Model |
|
R0 |
|
SD |
|
AC |
|
SPFrom |
|
TruncSD |
|
RecDevInit |
|
RecDevHist |
|
RecDevProj |
|
SpawnTimeFrac |
|
RelRecFun |
|
Units |
|
Misc |
|
x |
A srr object for slot accessors, or a stock object
for |
value |
For |
The SRR is defined by three components:
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)
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)
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.
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)
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")
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
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
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.
srr for the class definition and slot-level documentation.
SRRModels() for available stock-recruitment models and their required
parameters.
Populate() for array population.
Stock() for the enclosing stock constructor.
Fecundity() for the spawning production used as input to the SRR.
Specifying Biological and Fleet Schedules for
accepted Pars, R0, SD, and AC input formats.
Other srr:
srr-class
# 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# 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
srr S4 ClassDefines 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.
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.
Parslist. 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.
Modelfunction or character(1). SRR model identifier. Defaults
to "BevertonHolt". See SRRModels() for available models.
R0array 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.
SDarray 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.
ACarray 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.
SPFromcharacter(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).
TruncSDnumeric(1). Number of standard deviations at which the
log-normal recruitment deviation distribution is truncated. Default 2.
RecDevInitmatrix. 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.
RecDevHistmatrix. 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.
RecDevProjmatrix. Recruitment deviations (Sim × nProjTS) for
projection time steps. Generated automatically if NULL.
SpawnTimeFracnumeric(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.
RelRecFunfunction 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).
Unitsnumeric(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.
Misclist. Used internally.
SRR() for the constructor and accessor functions.
SRRModels() for available stock-recruitment models and their required
parameters.
Populate() for array population.
Stock() for the enclosing stock constructor.
Fecundity() for the spawning production used as input to the SRR.
Specifying Biological and Fleet Schedules for
accepted Pars input formats.
Other srr:
SRR()
Deterministic stock–recruitment and relative-recruitment models evaluated for a single simulation and a single year.
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)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)
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 |
Named list of parameters required by a specific SRR model. |
SPR |
Spawning-per-recruit multiplier. Numeric scalar. |
hR |
Ricker steepness. A named argument in |
Shinge |
Hockey-stick hinge point relative to |
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)? |
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).
SRRModels() prints or returns the set of stock–recruitment models
available in the package.
BevertonHolt() evaluates expected recruitment:
BevertonHolt_RelRec() evaluates equilibrium recruitment relative to unfished
recruitment as a function of SPR.
Ricker() evaluates expected recruitment:
Ricker_RelRec() evaluates equilibrium relative recruitment as a function
of SPR.
HockeyStick() evaluates recruitment assuming linear increase up to a hinge
point followed by saturation at R0:
HockeyStick_RelRec() evaluates relative equilibrium recruitment as a
function of SPR.
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.
## 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")## 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")
A function that uses the file location of a fitted SS3 model including input files to population the various slots of an Data object.
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, ... )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, ... )
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 |
comp_season |
Integer, for seasonal models, the season for which the value of the index will be used. By default, |
comp_partition |
Integer vector for selecting length/age observations that are retained (2), discarded (1), or both (0). By default, |
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, |
index_season |
Integer, for seasonal models, the season for which the value of the index will be used. By default, |
silent |
Logical. Suppress all messages? |
... |
Arguments to pass to SS_output |
An object of class Data.
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.
T. Carruthers and Q. Huynh
A function that uses the file location of a fitted SS3 model including input files to population the various slots of an Data object.
SS2DataMOM(SSdir, age_M = NULL, comp_partition = 2, silent = FALSE, ...)SS2DataMOM(SSdir, age_M = NULL, comp_partition = 2, silent = FALSE, ...)
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, |
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 |
A nested list of Data objects, with the first index by stock/sex and the second index by fleet.
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.
Q. Huynh
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.
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)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)
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 |
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 |
filename |
If |
dir |
If |
open_file |
If |
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 |
SS2MOM returns an object of class MOM. SS2OM returns an object of class OM.
MOM_agg_fleets(): Aggregate all fleets in an MOM object.
Currently tested on r4ss version 1.38.1-40.0 and SS 3.30.14.
Q. Huynh
Plot Spawning stock biomass and reference points for both historical and projected period
SSBrefplot(MSE, simno = 1, ystart = 1, log = F, leg = T)SSBrefplot(MSE, simno = 1, ystart = 1, log = F, leg = T)
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? |
T. Carruthers
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.
StandardizeEffort( OM, populate = TRUE, fit_stock_targeting = TRUE, generate_stock_targeting = TRUE )StandardizeEffort( OM, populate = TRUE, fit_stock_targeting = TRUE, generate_stock_targeting = TRUE )
OM |
An operating model object (om). |
populate |
|
fit_stock_targeting |
|
generate_stock_targeting |
|
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:
where is the set of
active stocks for fleet at time .
The targeting weight for each stock is then:
so that effective fishing mortality is conserved:
By construction, the targeting weights have geometric mean 1 over active stocks at each time step — equivalently, the log-targeting deviations sum to zero:
Inactive stocks () receive targeting weight
.
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).
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 . Over active stocks at each time step, the
weights have geometric mean 1 (equivalently, their logs sum to zero).
Inactive stocks receive weight 0.
FitStockTargeting(), GenerateStockTargeting()
## Not run: OM_standardized <- StandardizeEffort(OM) # Inspect back-calculated targeting OM_standardized@StockTargeting@Targeting ## End(Not run)## Not run: OM_standardized <- StandardizeEffort(OM) # Inspect back-calculated targeting OM_standardized@StockTargeting@Targeting ## End(Not run)
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).
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) <- valueStock( 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
Name |
|
CommonName |
|
Species |
|
Ages |
An ages object defining the age structure and plus-group
age. If |
Length |
A length object specifying the length-at-age growth
schedule. If |
Weight |
A weight object specifying the weight-at-age and
weight-at-length schedules. If |
NaturalMortality |
A naturalmortality object specifying natural
mortality rate(s), optionally age- or length-varying. If |
Maturity |
A maturity object specifying the maturity schedule
as a function of age, length, or weight. If |
Fecundity |
A fecundity object specifying egg production as a
function of age or length. Optional. When |
SRR |
A srr object specifying the stock-recruitment
relationship and recruitment variability. Created via |
Spatial |
A spatial object specifying spatial structure and
movement dynamics. Optional — leave empty for single-area (non-spatial)
models. If |
Depletion |
A depletion object specifying depletion assumptions
at the start ( |
Seasons |
|
Misc |
|
x |
A stock object, or an S4 object with a |
value |
For |
A stock object aggregates all biological components needed to simulate stock dynamics:
age structure (Ages());
survival (NaturalMortality());
reproduction (Maturity(), Fecundity(), SRR());
initial conditions (Depletion());
and optional spatial structure (Spatial()).
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.
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.
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.
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.
stock for the class definition and slot-level documentation.
OM() for the operating model constructor.
Ages(), Length(), Weight(), NaturalMortality(), Maturity(),
Fecundity(), SRR(), Spatial(), Depletion() for the sub-object
constructors.
Specifying Biological and Fleet Schedules for how
Pars, Model, and MeanAt* arrays are specified across sub-objects.
Other stock:
stock-class
# ---- 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)# ---- 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)
stock S4 ClassDefines 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.
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.
Namecharacter. Unique stock identifier.
CommonNamecharacter. Common name of the species.
Speciescharacter. Scientific (Latin) name of the species.
AgesLengthA length object defining the length-at-age schedule.
See Length().
WeightA weight object defining the weight-at-age and
weight-at-length schedules. See Weight().
NaturalMortalityA naturalmortality object defining the
natural mortality schedule. See NaturalMortality().
MaturityA maturity object defining the maturity schedule.
See Maturity().
FecundityA fecundity object defining egg production as a
function of age or length. Optional — when empty, spawning production
(SProduction) equals spawning biomass (SBiomass). See Fecundity().
SRRA srr object defining the stock-recruitment relationship
and recruitment variability. See SRR() and SRRModels().
SpatialA spatial object defining spatial structure and
movement dynamics. Optional — when empty, a single well-mixed area is
assumed. See Spatial().
DepletionA 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().
nYearnumeric(1). Number of historical years. Initialised to 20
by Stock() and overridden when attached to an OM().
pYearnumeric(1). Number of projection years. Initialised to 30
by Stock() and overridden when attached to an OM().
nSimnumeric(1). Number of stochastic simulations. Initialised to
48 by Stock() and overridden when attached to an OM().
CurrentYearnumeric(1). Final calendar year of the historical
period. Initialised to the current system year by Stock() and
overridden when attached to an OM().
Yearsnumeric. Vector of all model years (historical + projection),
derived from nYear, pYear, CurrentYear, and Seasons. Overridden
when attached to an OM().
Seasonsnumeric(1). Number of seasons per calendar year.
Misclist. Used internally.
Loglist. Internal log. Not intended for direct user access.
Stock() for the constructor and accessor functions.
Ages(), Length(), Weight(), NaturalMortality(), Maturity(),
Fecundity(), SRR(), Spatial(), Depletion() for the sub-object
constructors.
OM() for the operating model constructor.
Specifying Biological and Fleet Schedules for how
Pars, Model, and MeanAt* arrays are specified across sub-objects.
Other stock:
Stock()
'Stock'
An operating model component that specifies the parameters of the population dynamics model
NameAn identifying name for the Stock object. Single value. Character string.
Common_NameCommon name of the species. Character string.
SpeciesScientific name of the species. Genus and species name. Character string.
maxageThe 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.
R0Initial 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.
MThe 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.
MsdInter-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
hSteepness 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.
SRrelType of stock-recruit relationship. Use 1 to select a Beverton Holt relationship, 2 to select a Ricker relationship. Single value. Integer
PerrRecruitment 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.
ACAutocorrelation 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.
LinfThe 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.
LinfsdInter-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.
KThe 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.
KsdInter-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.
t0The 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.
LenCVThe 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.
L50Length 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_95Difference 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.
DEstimated 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)
aThe 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.
bThe 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_1The 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_1The 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_stayingThe 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.
FdiscThe 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.
SourceA reference to a website or article from which parameters were taken to define the stock object. Single value. Character string.
Objects can be created by calls of the form
new('Stock')
T. Carruthers and A. Hordyk
A data.frame with description of slots for class Stock
StockDescriptionStockDescription
An object of class data.frame with 27 rows and 2 columns.
Initialises a stocktargeting object with NA-filled arrays sized to the
supplied operating model. All arrays are dimensioned and named but left
unpopulated.
StockTargeting(OM)StockTargeting(OM)
OM |
An om object. Must have at least one stock and one fleet. |
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.
stocktargeting S4 ClassThe 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.
Meanarray[sim, stock, fleet]. Mean targeting weight for each
simulation, stock, and fleet. Values of 1 indicate neutral (equal)
targeting across stocks.
Covariancearray[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.
ACarray[sim, stock, fleet]. Lag-1 autocorrelation of log targeting
deviations for each simulation, stock, and fleet. Currently not used
but retained for future implementation.
Targetingarray[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.
Misclist. Reserved for additional information or user-defined
extensions. Not used internally.
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).
Sub(MSEobj, MPs = NULL, sims = NULL, years = NULL)Sub(MSEobj, MPs = NULL, sims = NULL, years = NULL)
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. |
A. Hordyk
SubOM for OM components and SubCpars for subsetting by simulation and projection years.
## 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)## 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 custom parameters of an operating model by simulation and projection years
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)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)
x |
An object of class |
... |
Arguments for method. |
sims |
A logical vector of length |
proyears |
If provided, a numeric to reduce the number of projection years (must be less than |
silent |
Logical to indicate if messages will be reported to console. |
Useful function for running multiMSE in batches if running into memory constraints.
An object of class OM or MOM (same class as x).
T. Carruthers, Q. Huynh
Sub for MSE objects, SubOM for OM components.
A function that strips out a Stock, Fleet, Obs, or Imp object from a complete OM object. Mainly used for internal functions.
SubOM(OM, Sub = c("Stock", "Fleet", "Obs", "Imp"))SubOM(OM, Sub = c("Stock", "Fleet", "Obs", "Imp"))
OM |
An operating model object (class OM) |
Sub |
A character string specifying what object type to strip out "Stock", "Fleet", "Obs", or "Imp" |
An object of class Stock, Fleet, Obs, or Imp
A. Hordyk
Sub for subsetting MSE output and SubCpars for subsetting by simulation and projection years.
Stock <- SubOM(testOM, "Stock") class(Stock)Stock <- SubOM(testOM, "Stock") class(Stock)
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.
Subset( object, Sims = NULL, Years = NULL, Ages = NULL, MPs = NULL, Fleets = NULL, Stocks = NULL, Impute = TRUE )Subset( object, Sims = NULL, Years = NULL, Ages = NULL, MPs = NULL, Fleets = NULL, Stocks = NULL, Impute = TRUE )
object |
An object to be subset. Supported types include:
|
Sims |
Numeric vector of simulation indices to retain. |
Years |
Numeric vector of calendar years to retain. |
Ages |
Numeric vector of age classes to retain. |
MPs |
Integer or character vector of MPs to retain. |
Fleets |
Character vector of fleets to retain. |
Stocks |
Character vector of stocks to retain. |
Impute |
Logical; only relevant when subsetting by Subsetting is applied sequentially when multiple dimensions are supplied, allowing consistent extraction across simulations, years, and age classes in a single call. |
An object of the same class as object, subset according to the
supplied dimension arguments.
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)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
## S4 method for signature 'Data' summary( object, wait = TRUE, x = 1, plots = "all", rmd = FALSE, head = "##", tplot = 25 )## S4 method for signature 'Data' summary( object, wait = TRUE, x = 1, plots = "all", rmd = FALSE, head = "##", tplot = 25 )
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? |
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
## S4 method for signature 'MMSE' summary(object, ..., silent = FALSE, Refs = NULL)## S4 method for signature 'MMSE' summary(object, ..., silent = FALSE, Refs = NULL)
object |
object of class |
... |
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 |
Summary of MSE object
## S4 method for signature 'MSE' summary(object, ..., silent = FALSE, Refs = NULL)## S4 method for signature 'MSE' summary(object, ..., silent = FALSE, Refs = NULL)
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 |
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.
SumOverAge(x) SumOverArea(x) SumOverClass(x) SumOverFleet(x) SumOverStock(x) SumOverYear(x)SumOverAge(x) SumOverArea(x) SumOverClass(x) SumOverFleet(x) SumOverStock(x) SumOverYear(x)
x |
An array. If the requested dimension is named, it will be summed out; otherwise the last dimension is used as a fallback. |
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.
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
An array with the specified dimension removed. Dimension names are preserved where possible.
A function that returns the stochastic TAC recommendations from a vector of output control MPs given a data object Data
TAC(Data, MPs = NA, reps = 100, timelimit = 1, checkMP = TRUE, silent = FALSE)TAC(Data, MPs = NA, reps = 100, timelimit = 1, checkMP = TRUE, silent = FALSE)
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? |
T. Carruthers
## Not run: library(MSEtool) Data <- TAC(MSEtool::Cobia) plot(Data) ## End(Not run)## Not run: library(MSEtool) Data <- TAC(MSEtool::Cobia) plot(Data) ## End(Not run)
Filters vector of TAC recommendations by replacing negatives with NA and and values beyond five standard deviations from the mean as NA
TACfilter(TAC)TACfilter(TAC)
TAC |
A numeric vector of TAC recommendations |
T. Carruthers
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.
TACs(MSE)TACs(MSE)
MSE |
An mse object. |
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".
Database from rfishbase
Taxa_TableTaxa_Table
An object of class tbl_df (inherits from tbl, data.frame) with 34721 rows and 8 columns.
doi:10.1111/j.1095-8649.2012.03464.x
Carl Boettiger and Duncan Temple Lang and Peter Wainwright 2012. Journal of Fish Biology
Create an indexing grid from just a vector of maximum dimension sizes
TEG(vec)TEG(vec)
vec |
A vector of maximum array sizes |
T. Carruthers
Example objects of class OM
testOMtestOM
An object of class OM of length 1.
avail("OM")avail("OM")
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
Thresh_tab(Ptab1)Thresh_tab(Ptab1)
Ptab1 |
A DFO performance table made by DFO_tab() |
T. Carruthers
Timeseries ClassStores detailed simulated time-series outputs including population, catch, effort, and fishing mortality components.
NumberList of number-at-age arrays Stock: Sim × Age × Year × Area (x MP for MSE objects).
BiomassTotal biomass array(Sim × Stock × Year (x MP for MSE objects).
SBiomassSpawning biomass array Sim × Stock × Year (x MP for MSE objects).
SProductionSpawning production array Sim × Stock × Year (x MP for MSE objects).
InteractionsTotal interaction by Stock and Fleet (biomass). Array: Sim x Stock x Year x Fleet (x MP for MSE objects).
LandingsTotal landings by Stock and Fleet (biomass). Array: Sim x Stock x Year x Fleet (x MP for MSE objects).
DiscardsTotal discards by Stock and Fleet (biomass). Array: Sim x Stock x Year x Fleet (x MP for MSE objects).
InteractAtAgeList of interactions-at-age (numbers) arrays. Stock: Sim × Age × Year × Fleet × Area (x MP for MSE objects).
LandingsAtAgeList of landings-at-age (numbers) arrays. Stock: Sim × Age × Year × Fleet × Area (x MP for MSE objects).
DiscardsAtAgeList of discards-at-age (numbers) arrays. Stock: Sim × Age × Year × Fleet × Area (x MP for MSE objects).
LandingsAtSizeNested list of landings-at-size (numbers) arrays Stock, Fleet: Sim × Class × Year × Area (x MP for MSE objects).
DiscardsAtSizeNested list of discards-at-size (numbers) arrays Stock, Fleet: Sim × Class × Year × Area (x MP for MSE objects).
EffortEffort array Sim × Year × Fleet (x MP for MSE objects).
DistributionFleet effort distribution by area: Sim × Year × Fleet × Area (x MP for MSE objects).
FInteractApical fishing mortality for fish that interact with the fishing gear. Array: Sim x Stock x Year x Fleet (x MP for MSE objects).'
FDeadApical fishing mortality for fish that are killed by fishing gear. Array: Sim x Stock x Year x Fleet (x MP for MSE objects).
FRetainApical fishing mortality for fish that are retained by fishers. Array: Sim x Stock x Year x Fleet (x MP for MSE objects).
FInteractAreaArea-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).
FDeadAreaArea-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).
FRetainAreaArea-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).
MiscMiscellaneous list.
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.
tinyErr(x, ...) ## S4 method for signature 'OM' tinyErr(x, obs = TRUE, imp = TRUE, proc = TRUE, grad = TRUE, silent = FALSE)tinyErr(x, ...) ## S4 method for signature 'OM' tinyErr(x, obs = TRUE, imp = TRUE, proc = TRUE, grad = TRUE, silent = FALSE)
x |
An object of class |
... |
Arguments to generic function |
obs |
Logical. Remove observation error? |
imp |
Logical. Remove implementation error? |
proc |
Logical. Remove process error? All |
grad |
Logical. Remove gradients? All |
silent |
Logical. Display messages? |
Useful for debugging and testing that MPs perform as expected under perfect conditions.
An updated object of class OM
OM_noErr <- tinyErr(MSEtool::testOM)OM_noErr <- tinyErr(MSEtool::testOM)
Generic Trade-Plot Function
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)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)
MSEobj |
An object of class |
... |
Names of Performance Metrics (PMs), or other arguments to |
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 |
Labels |
Optional named list specifying new labels for MPs. For example: |
Satisficed |
Logical. Show only the MPs that meet minimum acceptable thresholds (specified in |
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 |
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 |
Yrs |
An optional named list (matching the PM names) with numeric values to override the default |
Invisibly returns a list with summary table of MP performance and the ggplot objects for the plots
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\
A. Hordyk
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.)
tune_MP(Hist_list, MP, MP_parname, interval, minfunc, tol = 0.01, parallel = F)tune_MP(Hist_list, MP, MP_parname, interval, minfunc, tol = 0.01, parallel = F)
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? |
A function of class MP with argument MP_parname tuned by optim to minimize minfunc
T. Carruthers
## 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)## 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)
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.'
Turing(OM, Data, wait = TRUE) TuringMOM(multiHist, Data, wait = TRUE)Turing(OM, Data, wait = TRUE) TuringMOM(multiHist, Data, wait = TRUE)
OM |
An object of class |
Data |
An object of class |
wait |
Logical. Wait for key press before next plot? |
multiHist |
An object of class |
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?
TuringMOM(): Turing function for multi-stock, multi-fleet MOMs
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.
## Not run: Turing(MSEtool::testOM, MSEtool::SimulatedData, wait=FALSE) ## End(Not run)## Not run: Turing(MSEtool::testOM, MSEtool::SimulatedData, wait=FALSE) ## End(Not run)
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.
TwoFleetOMTwoFleetOM
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.
AlbacoreExStock represents a long-lived, slow-growing large pelagic species with low natural mortality. See AlbacoreExStock for full parameter details.
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.
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.
The Imp slot is NULL. The imp is currently a placeholder and
implementation error is not applied during simulation. See Imp() for
details.
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
TwoFleetOM nFleet(TwoFleetOM) ## Not run: Hist <- runMSE(TwoFleetOM, MPs = ExampleMPs()) ## End(Not run)TwoFleetOM nFleet(TwoFleetOM) ## Not run: Hist <- runMSE(TwoFleetOM, MPs = ExampleMPs()) ## End(Not run)
unfished ClassStores unfished equilibrium and dynamic population states, used as the baseline reference for calculating biological reference points.
Unfished(object) Equilibrium(unfished) Dynamic(unfished)Unfished(object) Equilibrium(unfished) Dynamic(unfished)
object |
A |
unfished |
An |
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
Unfished() returns an unfished object
Equilibrium() returns a popdynamics object
Dynamic() returns a popdynamics object
EquilibriumUnfished equilibrium population dynamics. A popdynamics object.
DynamicUnfished dynamic population dynamics. A popdynamics object.
MiscMiscellaneous list for additional outputs.
## Not run: unf <- Unfished(Hist) eq <- Equilibrium(unf) dyn <- Dynamic(unf) ## End(Not run)## Not run: unf <- Unfished(Hist) eq <- Equilibrium(unf) dyn <- Dynamic(unf) ## End(Not run)
A family of simple unit conversion functions for weight and length measurements commonly used in fisheries stock assessments.
lb2kg(x) lb2mt(x) kg2lb(x) kg2mt(x) kg2_1000lb(x) inch2mm(x) mm2inch(x)lb2kg(x) lb2mt(x) kg2lb(x) kg2mt(x) kg2_1000lb(x) inch2mm(x) mm2inch(x)
x |
Numeric vector of values to convert. |
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
Numeric vector of the same length as x in the target units.
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.
UpdateObject(object, ...) UpdateSlots(object)UpdateObject(object, ...) UpdateSlots(object)
object |
An S4 object. |
... |
Named objects used to replace existing slots. Names must match
slot names in |
The updated S4 object with all slots valid and any supplied replacements applied.
## Not run: obj <- UpdateObject(obj, Fleet=newFleet) ## End(Not run)## Not run: obj <- UpdateObject(obj, Fleet=newFleet) ## End(Not run)
Find the Management Procedures that use a particular data slot
Uses(slot, silent = FALSE)Uses(slot, silent = FALSE)
slot |
A slot from an object of class |
silent |
Logical. Should messages be printed? |
A character string of MPs that use the slot.
A. Hordyk
Uses("Mort")Uses("Mort")
Valid custom parameters (cpars)
validcpars( type = c("all", "Stock", "Fleet", "Obs", "Imp", "internal"), valid = TRUE, show = TRUE )validcpars( type = c("all", "Stock", "Fleet", "Obs", "Imp", "internal"), valid = TRUE, show = TRUE )
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? |
a HTML datatable with variable name, description and type of valid cpars
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().
## Not run: validcpars() # all valid cpars validcpars("Obs", FALSE) # invalid Obs cpars ## End(Not run)## Not run: validcpars() # all valid cpars validcpars("Obs", FALSE) # invalid Obs cpars ## End(Not run)
Returns the valid units for Ages(), Length(), and Weight() objects.
ValidUnits(x = "ages")ValidUnits(x = "ages")
x |
An ages, length, or weight object, or a
character string specifying the class: one of |
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".
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 objectValidUnits() # 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
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.
VOI( MSEobj, ncomp = 6, nbins = 8, maxrow = 8, Ut = NA, Utnam = "Utility", plot = TRUE )VOI( MSEobj, ncomp = 6, nbins = 8, maxrow = 8, Ut = NA, Utnam = "Utility", plot = TRUE )
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? |
T. Carruthers
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).
VOI2(MSEobj, ncomp = 6, nbins = 4, Ut = NA, Utnam = "yield", lay = F)VOI2(MSEobj, ncomp = 6, nbins = 4, Ut = NA, Utnam = "yield", lay = F)
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 |
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
T. Carruthers
A function that relates parameters of the observation model and the operating model parameters to yield.
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) )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) )
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 |
A list of all the information included in the plot
A. Hordyk
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.
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) <- valueWeight( 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
Pars |
|
Model |
|
Units |
|
MeanAtAge |
|
MeanAtLength |
|
CVatAge |
|
Dist |
|
TruncSD |
|
Timing |
|
Random |
|
AWK |
|
Classes |
|
Misc |
|
x |
A weight object for slot accessors, or a stock
object for |
value |
For |
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.
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 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.
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
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)
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.
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
# 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# 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
weight S4 ClassDefines 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.
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.
Parslist. 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.
Modelfunction or character(1). Weight model identifier, matched
to one of WeightModels(). Set automatically by FindModel() when Pars
is supplied without an explicit model.
Unitscharacter(1). Physical unit of the weight measurements (e.g.,
"g", "kg"). Must be accepted by ValidUnits().
MeanAtAgearray. 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.
MeanAtLengtharray. 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.
CVatAgearray 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.
Distcharacter(1). Parametric distribution used for weight-at-age
variability (e.g., "lognormal").
TruncSDarray or numeric. Number of standard deviations at which
the weight distribution is truncated.
Timingarray or numeric. Fractional position within the time step
at which weight is measured (0 = start, 1 = end).
Randomarray. Random effects on weight parameters across simulations
or years.
AWKarray. 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.
Classesnumeric. Weight class midpoints in units of Units.
Misclist. Used internally.
Weight() for the constructor and accessor functions.
WeightModels() for available models and their required parameters.
ValidUnits() for accepted unit strings.
Populate() for array population.
FindModel() for automatic model inference.
AWK() to retrieve the age-weight key.
Length() for the companion length schedule, required when using at-length weight models.
Specifying Biological and Fleet Schedules for the
full description of how Pars, Model, and MeanAt* arrays interact.
Other weight:
Weight()
Allometric weight models used to compute weight at age or at length.
WeightatAge(Ages, a, b) WeightatLength(Length, Alpha, Beta) WeightatMeanLength(Length, alpha, beta) WeightModels(full = TRUE, print = TRUE)WeightatAge(Ages, a, b) WeightatLength(Length, Alpha, Beta) WeightatMeanLength(Length, alpha, beta) WeightModels(full = TRUE, print = TRUE)
Ages |
numeric vector of age classes (for Weight-at-Age) |
a |
scaling parameter for Weight-at-Age in units of |
b |
exponent for Weight-at-Age. Typically around 3. |
Length |
numeric vector of length classes for |
Alpha |
scaling parameter for Weight-at-Length in units of |
Beta |
exponent for Weight-at-Length. Typically around 3. |
alpha |
scaling parameter for Weight-at-Mean-Length in units of |
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)
|
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:
Weight-at-Length:
Weight-at-Mean-Length:
, returning weight-at-age
at-length schedules (except from WeightatMeanLength) are converted internally
to at-age using the age-length key respectively.
Each function returns a numeric vector of expected weights for each age or length.
WeightModels() invisibly returns a data frame describing available models.
Ages(), Length(), Stock(), Weight()
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")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. 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.
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, ... )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, ... )
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 |
WLb |
positive real number or array |
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), |
Use a seed for the random number generator to sample future recruitment.
An object of class OM.
T. Carruthers
A worm plot for plotting the likelihood of meeting biomass targets in future years.
wormplot(MSEobj, Bref = 0.5, LB = 0.25, UB = 0.75)wormplot(MSEobj, Bref = 0.5, LB = 0.25, UB = 0.75)
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 |
Returns a matrix of nMPs rows and proyears columns which is the fraction of simulations for which biomass was above Bref.
T. Carruthers
Evaluates a wrapped normal distribution over a circular seasonal domain,
suitable for specifying seasonal recruitment patterns in models with
Seasons > 1.
WrappedNormal(n_seasons, mu, sigma, n_wraps = 5)WrappedNormal(n_seasons, mu, sigma, n_wraps = 5)
n_seasons |
Integer. Number of seasons per year (e.g. |
mu |
Numeric. Peak season (need not be an integer; e.g. |
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 |
A numeric vector of unnormalised density values of length
n_seasons. Normalise with / sum(...) to obtain season proportions.
# 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)# 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)
Used internally in the DLMtool package to write CSV files from an existing DLMtool object
writeCSV( inobj, tmpfile = NULL, objtype = c("Stock", "Fleet", "Obs", "Imp", "Data", "OM") )writeCSV( inobj, tmpfile = NULL, objtype = c("Stock", "Fleet", "Obs", "Imp", "Data", "OM") )
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 |
A. Hordyk
Import a Data object from Excel file
XL2Data(name, dec = c(".", ","), sheet = 1, silent = FALSE)XL2Data(name, dec = c(".", ","), sheet = 1, silent = FALSE)
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? |
An object of class 'Data'
A. Hordyk
## Not run: MyData <- XL2Data("MyData.xlsx") ## End(Not run)## Not run: MyData <- XL2Data("MyData.xlsx") ## End(Not run)
Imports a Fleet Object from a correctly formatted Excel file.
XL2Fleet(name = NULL, cpars = NULL, msg = TRUE)XL2Fleet(name = NULL, cpars = NULL, msg = TRUE)
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? |
An error message will alert if any slots are missing values, or if the Excel file is missing the required tabs.
An object of class Fleet
A. Hordyk
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.
XL2OM(name = NULL, cpars = NULL, msg = TRUE)XL2OM(name = NULL, cpars = NULL, msg = TRUE)
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? |
An error message will alert if any slots are missing values, or if the Excel file is missing the required tabs.
An object of class OM
A. Hordyk
## 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)## 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)
Imports a Stock Object from a correctly formatted Excel file.
XL2Stock(name = NULL, cpars = NULL, msg = TRUE)XL2Stock(name = NULL, cpars = NULL, msg = TRUE)
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? |
An error message will alert if any slots are missing values, or if the Excel file is missing the required tabs.
An object of class Stock
A. Hordyk
Two related functions for working with historical and projection time steps:
CalcYears(nYear, pYear, CurrentYear, Seasons = 1, Period = NULL) Years(x, Period = NULL)CalcYears(nYear, pYear, CurrentYear, Seasons = 1, Period = NULL) Years(x, Period = NULL)
nYear |
Integer. Number of historical time steps. |
pYear |
Integer. Number of projection time steps. |
CurrentYear |
Integer. Final historical year (or index if
|
Seasons |
Integer. Number of seasons per year. Default |
Period |
Character or |
x |
An om, hist, or mse object, or a list of
such objects. ( |
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.
A numeric vector of time step values, or for Years() applied to
a list, a list of such vectors.
# 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")# 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")