| Title: | Multi-Stock Assessment |
| Version: | 0.1.0 |
| Date: | 2026-01-16 |
| Maintainer: | Quang Huynh <quang@bluematterscience.com> |
| Description: | Implementation of a next-generation, multi-stock age-structured fisheries assessment model. 'multiSA' is intended for use in mixed fisheries where stock composition can not be readily identified in fishery data alone, e.g., from catch and age/length composition. Models can be fitted to genetic data, e.g., stock composition of catches and close-kin pairs, with seasonal stock availability and movement. |
| License: | GPL (≥ 3) |
| Depends: | R (≥ 3.5.0) |
| Imports: | dplyr, gplots, graphics, methods, pbapply, reshape2, rmarkdown, snowfall, stats, tinyplot, RTMB (≥ 1.7), TMB, utils |
| Suggests: | numDeriv, RTMBdist, usethis |
| LazyLoad: | yes |
| Encoding: | UTF-8 |
| RoxygenNote: | 7.3.3 |
| URL: | https://blue-matter.github.io/multiSA/, https://github.com/Blue-Matter/multiSA |
| BugReports: | https://github.com/Blue-Matter/multiSA/issues |
| NeedsCompilation: | no |
| Packaged: | 2026-01-29 23:31:49 UTC; quang |
| Author: | Quang Huynh |
| Repository: | CRAN |
| Date/Publication: | 2026-02-03 12:40:13 UTC |
multiSA: Multi-Stock Assessment
Description
Implementation of a next-generation, multi-stock age-structured fisheries assessment model. 'multiSA' is intended for use in mixed fisheries where stock composition can not be readily identified in fishery data alone, e.g., from catch and age/length composition. Models can be fitted to genetic data, e.g., stock composition of catches and close-kin pairs, with seasonal stock availability and movement.
Author(s)
Maintainer: Quang Huynh quang@bluematterscience.com (ORCID)
See Also
Useful links:
Report bugs at https://github.com/Blue-Matter/multiSA/issues
Additional methods for AD types
Description
Methods for RTMB AD class
Usage
## S4 method for signature 'ad,matrix'
x %*% y
Arguments
x |
AD object |
y |
Non-AD matrix |
Functions
-
x %*% y: Matrix product function implemented for mixed AD and non-AD objects withcolSums(x * y). See ADmatrix.
If statements compatible with RTMB
Description
Convenience functions that allow taping of gradients in RTMB with if expressions,
following the corresponding CppAD functions.
Usage
CondExpLt(left, right, if_true, if_false)
CondExpLe(left, right, if_true, if_false)
CondExpGt(left, right, if_true, if_false)
CondExpGe(left, right, if_true, if_false)
CondExpEq(left, right, if_true, if_false)
Arguments
left |
Numeric on left hand side of the evaluation |
right |
Numeric on right hand side of the evaluation |
if_true |
Numeric if expression is true |
if_false |
Numeric if expression is false |
Details
Functions should be vectorized.
CondExpLt evaluates whether left < right
CondExpLe evaluates whether left <= right
CondExpGt evaluates whether left > right
CondExpGe evaluates whether left >= right
CondExpEq evaluates whether left == right
Value
Numeric
Examples
library(RTMB)
TapeConfig(comparison = "tape")
f <- function(x) CondExpLt(x, 3, 0, x^2)
g <- MakeTape(f, numeric(1))
x <- seq(0, 5)
# Does not work!
f2 <- function(x) if (x < 3) 0 else x^2
g2 <- MakeTape(f2, numeric(1))
# Compare the real answer (deriv) with various values returned by RTMB
data.frame(
x = x,
deriv = ifelse(x < 3, 0, 2 * x),
deriv_f = sapply(x, g$jacobian),
deriv_f2 = sapply(x, g2$jacobian)
)
DCKMR S4 object
Description
Store lists of data frames for parent offspring pairs and half-sibling pairs
Slots inherited from DCKMR
POP_sA list by stock of data frames for parent-offspring pairs. Each row in the data frame corresponds to a "sampling unit" defined by the columns:
aCapture year of parent tAge at capture of parent yBirth year of offspring nNumber of pairwise comparisons mNumber of POPs HSP_sA list by stock of data frames for half-sibling pairs. Each row in the data frame corresponds to a "sampling unit" defined by the columns:
yiBirth year of older sibling yjBirth year of younger sibling nNumber of pairwise comparisons mNumber of HSPs CKMR_likeCharacter, likelihood for the POP and HSP sampling units. See
typeargument inlike_CKMR()for options.
Dfishery S4 object
Description
S4 class that organizes the various data inputs for the MSA model. MSAdata simply inherits the slots from 6 component classes:
Dmodel, Dstock, Dfishery, Dsurvey DCKMR, and Dtag, where the D- prefix denotes an object for data inputs (or model configuration).
Details
For convenience, most arrays and matrices have the associated dimensions in the variable name. For example, Cobs_ymfr represents
observed catch with the dimension following the underscore, following this template:
y | Year |
m | Season |
a | Age |
r | Region |
f | Fishery |
i | Index |
s | Stock |
Slots inherited from Dfishery
nfInteger, number of fleets
Cobs_ymfrTotal fishery catch
Csd_ymfrLognormal standard deviation of the fishery catch. Only used if
Dmodel@condition = "F". Default of 0.01.fwt_ymafsFishery weight at age. Set to 1 when fleet catch is in units of abundance. Set to stock weight at age by default (values at beginning of time step).
CAAobs_ymafrFishery catch at age composition
CALobs_ymlfrFishery catch at length composition
fcomp_likeCharacter, likelihood for the fishery composition data. See
typeargument oflike_comp()for optionsCAAN_ymfrSample size of the catch at age vector by season if using the multinomial or Dirichlet-multinomial likelihoods
CALN_ymfrSample size of the catch at length vector by season if using the multinomial or Dirichlet-multinomial likelihoods
CAAtheta_fCatch at age dispersion parameter if using the Dirichlet-multinomial likelihood. Default set to 1.
CALtheta_fCatch at length dispersion parameter if using the Dirichlet-multinomial likelihood. Default set to 1.
sel_block_yfIndex of dummy fleets to model time blocks of selectivity
sel_fCharacter vector of the functional form for selectivity. Choose between:
"logistic_length", "dome_length", "logistic_age", "dome_age", "SB", "B"Cinit_mfrEquilibrium seasonal catch prior to the first year. One way to initialize the abundance at the start of the first year in the model. Default of zero.
SC_ymafrsStock composition data.
SC_aaBoolean matrix that aggregates age classes for the stock composition data. See example.
SC_ffBoolean matrix that aggregates fleets for the stock composition data. See example.
SC_likeCharacter, likelihood for the stock composition data. See
typeargument oflike_comp()for optionsSCN_ymafrSample size of the stock composition vector if using the multinomial or Dirichlet-multinomial likelihoods
SCtheta_fStock composition dispersion parameter if using the Dirichlet-multinomial likelihood. Default set to 1.
SCstdev_ymafrsStock composition standard deviation if using the lognormal likelihood. Default set to 0.1.
See Also
MSAdata-class check_data() Dmodel-class Dstock-class Dfishery-class Dsurvey-class DCKMR-class Dtag-class
Examples
# Aggregate stock composition for ages 1-4 and 5-10 across all fleets
na <- 10
na_SC <- 2
SC_aa <- matrix(0, na_SC, na) # Assumes dim(SC_ymafrs)[3] = na_SC
SC_aa[1, 1:4] <- SC_aa[2, 5:10] <- 1
nf <- 3
nf_SC <- 1
SC_ff <- matrix(1, nf_SC, nf) # Assumes dim(SC_ymafrs)[4] <- nf_SC
Dlabel S4 object
Description
Vectors for labeling plots.
Slots inherited from Dlabel
yearVector of years. Length
Dmodel@nyseasonVector of season names. Length
Dmodel@nmageVector of ages. Length
Dmodel@naregionVector of region names. Length
Dmodel@nrstockVector of stock names. Length
Dmodel@nsfleetVector of fleet names. Length
Dfishery@nfindexVector of index of abundance names. Length
Dsurvey@ni
Dmodel S4 object
Description
S4 class that organizes the various data inputs for the MSA model. MSAdata simply inherits the slots from 6 component classes:
Dmodel, Dstock, Dfishery, Dsurvey DCKMR, and Dtag, where the D- prefix denotes an object for data inputs (or model configuration).
Details
For convenience, most arrays and matrices have the associated dimensions in the variable name. For example, Cobs_ymfr represents
observed catch with the dimension following the underscore, following this template:
y | Year |
m | Season |
a | Age |
r | Region |
f | Fishery |
i | Index |
s | Stock |
Slots inherited from Dmodel
nyInteger, number of years
nmInteger, number of seasons
naInteger, number of ages. The first age class is zero and the last age class (plus group is age
na - 1).nlInteger, number of length bins. Set to zero if lengths are not modeled.
nrInteger, number of spatial regions
nsInteger, number of stocks
lbinVector of lower boundary of length bins. Length
nl + 1lmidVector of midpoint of length bins. Length
nlFmaxNumeric, maximum allowable instantaneous fishing mortality rate (units of per season). Defaults to 3.
y_phiInteger, the year from which to obtain values of natural mortality and fecundity for the unfished stock-recruit replacement line (
phi). Relevant if natural mortality or fecundity are time-varying. Defaults to 1.scale_sVector, length
ns. Multiplicative scaling factor that informs relative stock size to aid parameter estimation. Larger values implies larger stocks. Default set to 1. Seemake_parameters().nyinitInteger, number of years of spool-up to calculate equilibrium unfished and starting conditions for the population model to account for seasonal and spatial dynamics. The numerical spool-up is not needed when both
nm = 1andnr = 1, i.e.,nyinit = 1. Otherwise, set to2 * naby default.conditionCharacter, either to specify the model estimates fishing mortality as a parameter (
"F", default) or equal to the catch ("catch").nitFInteger, number of iterations to solve Baranov catch equation from observed catch if
condition = "catch". Defaults to 5.y_Fmult_fInteger vector by fleet, the year in which to directly estimate F. Choose a year/season/region combination when the catch is average relative to the time series. Only used if
condition = "F".m_Fmult_fInteger vector by fleet, the season in which to directly estimate F. Choose a year/season/region combination when the catch is average relative to the time series. Only used if
condition = "F".r_Fmult_fInteger vector by fleet, the region in which to directly estimate F. Choose a year/season/region combination when the catch is average relative to the time series. Only used if
condition = "F".pbc_rdev_ysNumeric matrix, for the fraction of lognormal bias correction (
-0.5 * sd_r^2) applied to the recruitment estimates in the model. Typically between 0-1, with default of 1.pbc_initrdev_asNumeric matrix, for the fraction of lognormal bias correction (
-0.5 * sd_r^2) applied to the initial abundance vector in the model. Typically between 0-1, with default of 1.priorCharacter vector to be evaluated in the model to return the log prior for a parameter. See example in documentation for prior.
nyretInteger, number of recent years of data to remove from the likelihood for retrospective analysis (positive numbers). Default is zero.
See Also
MSAdata-class check_data() Dmodel-class Dstock-class Dfishery-class Dsurvey-class DCKMR-class Dtag-class
Dstock S4 object
Description
S4 class that organizes the various data inputs for the MSA model. MSAdata simply inherits the slots from 6 component classes:
Dmodel, Dstock, Dfishery, Dsurvey DCKMR, and Dtag, where the D- prefix denotes an object for data inputs (or model configuration).
Details
For convenience, most arrays and matrices have the associated dimensions in the variable name. For example, Cobs_ymfr represents
observed catch with the dimension following the underscore, following this template:
y | Year |
m | Season |
a | Age |
r | Region |
f | Fishery |
i | Index |
s | Stock |
Slots inherited from Dstock
m_spawnInteger, season of spawning. Defaults to 1. The progeny will enter the age structure in the same season.
m_advanceageInteger, season in which to advance age classes (corresponding to calendar year) to the next age class. Defaults to 1.
len_ymasLength-at-age. Only needed if
Dmodel@nl > 0to fit length composition (you may want to calculate the growth at the middle of the time step).calc_growth()may be a helpful function.sdlen_ymasStandard deviation in length-at-age
LAK_ymalsLength-at-age probability array. If empty, values will be calculated by
check_data()withcalc_LAK().mat_yasProportion mature by age class. Ignored if maturity ogive is estimated, e.g., when fitting to close-kin genetic data.
swt_ymasStock weight-at-age (at beginning of time step). See
calc_growth()example.fec_yasFecundity, i.e., spawning output, of mature animals. Default uses stock weight at age.
M_yasNatural mortality. Instantaneous units per year. Ignored if M is estimated.
SRR_sCharacter vector of stock-recruit relationship by stock. See
SRRargument incalc_recruitment()for options.delta_sFraction of season that elapses when spawning occurs, e.g., midseason spawning occurs when
delta_s = 0.5. Default is zero.presence_rsLogical matrix indicating presence/absence of stock
sin regionr. Used to constrain movement matrix. Default is TRUE for all stocks and regions.natal_rsThe fraction of the mature stock
sin regionrthat spawns at time of spawning. See example. Default is 1 for all stocks and regions.
See Also
MSAdata-class check_data() Dmodel-class Dstock-class Dfishery-class Dsurvey-class DCKMR-class Dtag-class
Examples
# Set natal_rs matrix so that the spawning output of stock 1 is
# calculated from mature animals present in regions 1, 2.
# Similarly for stock 2, spawning output from areas 2 and 3.
nr <- 4
ns <- 2
natal_rs <- matrix(0, nr, ns)
natal_rs[1:2, 1] <- natal_rs[2:3, 2] <- 1
Dsurvey S4 object
Description
S4 class that organizes the various data inputs for the MSA model. MSAdata simply inherits the slots from 6 component classes:
Dmodel, Dstock, Dfishery, Dsurvey DCKMR, and Dtag, where the D- prefix denotes an object for data inputs (or model configuration).
Details
For convenience, most arrays and matrices have the associated dimensions in the variable name. For example, Cobs_ymfr represents
observed catch with the dimension following the underscore, following this template:
y | Year |
m | Season |
a | Age |
r | Region |
f | Fishery |
i | Index |
s | Stock |
Slots inherited from Dsurvey
niInteger, number of indices of abundance. Zero is possible.
Iobs_ymiObserved indices
Isd_ymiLognormal standard deviation of the observed indices
unit_iCharacter vector, units of the index. Set to
"B"to use stock weight at age (default) or"N"for abundance (numbers).IAAobs_ymaiArray, survey age composition
IALobs_ymliArray, survey length composition
icomp_likeCharacter, likelihood for the composition data. See
like_comp()for optionsIAAN_ymiArray, sample size of the index age composition by season if using the multinomial or Dirichlet-multinomial likelihoods
IALN_ymiArray, sample size of the index length composition by season if using the multinomial or Dirichlet-multinomial likelihoods
IAAtheta_iNumeric vector, survey age composition dispersion parameter if using the Dirichlet-multinomial likelihood
IALtheta_iNumeric vector, index length composition dispersion parameter if using the Dirichlet-multinomial likelihood
samp_irsBoolean array that specifies the regions and stocks sampled by the index.
samp[i, r, s]indicates whether indexioperates in regionrand catches stocks.sel_iCharacter vector, functional forms for selectivity. See
"type"argument inconv_selpar()for options.delta_iNumeric vector, The elapsed fraction of time in the seasonal time step (between 0 - 1) when the index samples the population. Set to a negative number (-1) to sample over the duration of the timestep, i.e.,
(1 - exp(-Z))/Z.
See Also
MSAdata-class check_data() Dmodel-class Dstock-class Dfishery-class Dsurvey-class DCKMR-class Dtag-class
Dtag S4 object
Description
S4 class that organizes the various data inputs for the MSA model. MSAdata simply inherits the slots from 6 component classes:
Dmodel, Dstock, Dfishery, Dsurvey DCKMR, and Dtag, where the D- prefix denotes an object for data inputs (or model configuration).
Details
For convenience, most arrays and matrices have the associated dimensions in the variable name. For example, Cobs_ymfr represents
observed catch with the dimension following the underscore, following this template:
y | Year |
m | Season |
a | Age |
r | Region |
f | Fishery |
i | Index |
s | Stock |
Slots inherited from Dtag
tag_ymarrsArray. Number of tags that move between regions. Informs movement matrices of stocks between time steps.
tag_ymarsArray. Number of tags distributed among regions. Informs stock distribution (within time step).
tag_yyBoolean matrix that aggregates years for the tag data. Only used for the tag movement array
tag_ymarrs.tag_aaBoolean matrix that aggregates ages for the tag data.
tag_likeCharacter. Likelihood for the tagging data, either the vector of proportions by region of origin for
tag_ymarrs, or by region of stock distribution fortag_ymars. Seetypeargument oflike_comp()for optionstagN_ymarsArray. Sample size of the tag movement vectors if using the multinomial or Dirichlet-multinomial likelihoods.
tagN_ymasArray. Sample size of the tag distribution vectors if using the multinomial or Dirichlet-multinomial likelihoods.
tagtheta_sArray. Tag dispersion parameter (by stock) if using the Dirichlet-multinomial likelihoods. Default set to 1.
tagstdev_sArray. Tag standard deviation (by stock) if using the lognormal likelihood. Default set to 0.1.
See Also
MSAdata-class check_data() Dmodel-class Dstock-class Dfishery-class Dsurvey-class DCKMR-class Dtag-class
MSAassess S4 object
Description
S4 object that returns output from MSA model
Slots
objRTMB object returned by
RTMB::MakeADFun()optList returned by
stats::nlminb()SDList returned by
RTMB::sdreport()reportList of model output at the parameter estimates, returned by
obj$report(obj$env$last.par.best)MiscList, miscellaneous items
MSAdata S4 object
Description
S4 class that organizes the various data inputs for the MSA model. MSAdata simply inherits the slots from 6 component classes:
Dmodel, Dstock, Dfishery, Dsurvey DCKMR, and Dtag, where the D- prefix denotes an object for data inputs (or model configuration).
Details
For convenience, most arrays and matrices have the associated dimensions in the variable name. For example, Cobs_ymfr represents
observed catch with the dimension following the underscore, following this template:
y | Year |
m | Season |
a | Age |
r | Region |
f | Fishery |
i | Index |
s | Stock |
Slots
DmodelClass Dmodel containing parameters for model structure (number of years, ages, etc.)
DstockClass Dstock containing stock parameters (growth, natural mortality, etc.)
DfisheryClass Dfishery containing fishery data (catch, size and stock composition, etc.)
DsurveyClass Dsurvey containing survey data (indices of abundance)
DCKMRClass DCKMR containing genetic close-kin data
DtagClass Dtag containing tagging data
DlabelClass Dlabel containing names for various dimensions. Used for plotting.
MiscList for miscellaneous inputs as needed
Slots inherited from Dmodel
nyInteger, number of years
nmInteger, number of seasons
naInteger, number of ages. The first age class is zero and the last age class (plus group is age
na - 1).nlInteger, number of length bins. Set to zero if lengths are not modeled.
nrInteger, number of spatial regions
nsInteger, number of stocks
lbinVector of lower boundary of length bins. Length
nl + 1lmidVector of midpoint of length bins. Length
nlFmaxNumeric, maximum allowable instantaneous fishing mortality rate (units of per season). Defaults to 3.
y_phiInteger, the year from which to obtain values of natural mortality and fecundity for the unfished stock-recruit replacement line (
phi). Relevant if natural mortality or fecundity are time-varying. Defaults to 1.scale_sVector, length
ns. Multiplicative scaling factor that informs relative stock size to aid parameter estimation. Larger values implies larger stocks. Default set to 1. Seemake_parameters().nyinitInteger, number of years of spool-up to calculate equilibrium unfished and starting conditions for the population model to account for seasonal and spatial dynamics. The numerical spool-up is not needed when both
nm = 1andnr = 1, i.e.,nyinit = 1. Otherwise, set to2 * naby default.conditionCharacter, either to specify the model estimates fishing mortality as a parameter (
"F", default) or equal to the catch ("catch").nitFInteger, number of iterations to solve Baranov catch equation from observed catch if
condition = "catch". Defaults to 5.y_Fmult_fInteger vector by fleet, the year in which to directly estimate F. Choose a year/season/region combination when the catch is average relative to the time series. Only used if
condition = "F".m_Fmult_fInteger vector by fleet, the season in which to directly estimate F. Choose a year/season/region combination when the catch is average relative to the time series. Only used if
condition = "F".r_Fmult_fInteger vector by fleet, the region in which to directly estimate F. Choose a year/season/region combination when the catch is average relative to the time series. Only used if
condition = "F".pbc_rdev_ysNumeric matrix, for the fraction of lognormal bias correction (
-0.5 * sd_r^2) applied to the recruitment estimates in the model. Typically between 0-1, with default of 1.pbc_initrdev_asNumeric matrix, for the fraction of lognormal bias correction (
-0.5 * sd_r^2) applied to the initial abundance vector in the model. Typically between 0-1, with default of 1.priorCharacter vector to be evaluated in the model to return the log prior for a parameter. See example in documentation for prior.
nyretInteger, number of recent years of data to remove from the likelihood for retrospective analysis (positive numbers). Default is zero.
Slots inherited from Dstock
m_spawnInteger, season of spawning. Defaults to 1. The progeny will enter the age structure in the same season.
m_advanceageInteger, season in which to advance age classes (corresponding to calendar year) to the next age class. Defaults to 1.
len_ymasLength-at-age. Only needed if
Dmodel@nl > 0to fit length composition (you may want to calculate the growth at the middle of the time step).calc_growth()may be a helpful function.sdlen_ymasStandard deviation in length-at-age
LAK_ymalsLength-at-age probability array. If empty, values will be calculated by
check_data()withcalc_LAK().mat_yasProportion mature by age class. Ignored if maturity ogive is estimated, e.g., when fitting to close-kin genetic data.
swt_ymasStock weight-at-age (at beginning of time step). See
calc_growth()example.fec_yasFecundity, i.e., spawning output, of mature animals. Default uses stock weight at age.
M_yasNatural mortality. Instantaneous units per year. Ignored if M is estimated.
SRR_sCharacter vector of stock-recruit relationship by stock. See
SRRargument incalc_recruitment()for options.delta_sFraction of season that elapses when spawning occurs, e.g., midseason spawning occurs when
delta_s = 0.5. Default is zero.presence_rsLogical matrix indicating presence/absence of stock
sin regionr. Used to constrain movement matrix. Default is TRUE for all stocks and regions.natal_rsThe fraction of the mature stock
sin regionrthat spawns at time of spawning. See example. Default is 1 for all stocks and regions.
Slots inherited from Dfishery
nfInteger, number of fleets
Cobs_ymfrTotal fishery catch
Csd_ymfrLognormal standard deviation of the fishery catch. Only used if
Dmodel@condition = "F". Default of 0.01.fwt_ymafsFishery weight at age. Set to 1 when fleet catch is in units of abundance. Set to stock weight at age by default (values at beginning of time step).
CAAobs_ymafrFishery catch at age composition
CALobs_ymlfrFishery catch at length composition
fcomp_likeCharacter, likelihood for the fishery composition data. See
typeargument oflike_comp()for optionsCAAN_ymfrSample size of the catch at age vector by season if using the multinomial or Dirichlet-multinomial likelihoods
CALN_ymfrSample size of the catch at length vector by season if using the multinomial or Dirichlet-multinomial likelihoods
CAAtheta_fCatch at age dispersion parameter if using the Dirichlet-multinomial likelihood. Default set to 1.
CALtheta_fCatch at length dispersion parameter if using the Dirichlet-multinomial likelihood. Default set to 1.
sel_block_yfIndex of dummy fleets to model time blocks of selectivity
sel_fCharacter vector of the functional form for selectivity. Choose between:
"logistic_length", "dome_length", "logistic_age", "dome_age", "SB", "B"Cinit_mfrEquilibrium seasonal catch prior to the first year. One way to initialize the abundance at the start of the first year in the model. Default of zero.
SC_ymafrsStock composition data.
SC_aaBoolean matrix that aggregates age classes for the stock composition data. See example.
SC_ffBoolean matrix that aggregates fleets for the stock composition data. See example.
SC_likeCharacter, likelihood for the stock composition data. See
typeargument oflike_comp()for optionsSCN_ymafrSample size of the stock composition vector if using the multinomial or Dirichlet-multinomial likelihoods
SCtheta_fStock composition dispersion parameter if using the Dirichlet-multinomial likelihood. Default set to 1.
SCstdev_ymafrsStock composition standard deviation if using the lognormal likelihood. Default set to 0.1.
Slots inherited from Dsurvey
niInteger, number of indices of abundance. Zero is possible.
Iobs_ymiObserved indices
Isd_ymiLognormal standard deviation of the observed indices
unit_iCharacter vector, units of the index. Set to
"B"to use stock weight at age (default) or"N"for abundance (numbers).IAAobs_ymaiArray, survey age composition
IALobs_ymliArray, survey length composition
icomp_likeCharacter, likelihood for the composition data. See
like_comp()for optionsIAAN_ymiArray, sample size of the index age composition by season if using the multinomial or Dirichlet-multinomial likelihoods
IALN_ymiArray, sample size of the index length composition by season if using the multinomial or Dirichlet-multinomial likelihoods
IAAtheta_iNumeric vector, survey age composition dispersion parameter if using the Dirichlet-multinomial likelihood
IALtheta_iNumeric vector, index length composition dispersion parameter if using the Dirichlet-multinomial likelihood
samp_irsBoolean array that specifies the regions and stocks sampled by the index.
samp[i, r, s]indicates whether indexioperates in regionrand catches stocks.sel_iCharacter vector, functional forms for selectivity. See
"type"argument inconv_selpar()for options.delta_iNumeric vector, The elapsed fraction of time in the seasonal time step (between 0 - 1) when the index samples the population. Set to a negative number (-1) to sample over the duration of the timestep, i.e.,
(1 - exp(-Z))/Z.
Slots inherited from DCKMR
POP_sA list by stock of data frames for parent-offspring pairs. Each row in the data frame corresponds to a "sampling unit" defined by the columns:
aCapture year of parent tAge at capture of parent yBirth year of offspring nNumber of pairwise comparisons mNumber of POPs HSP_sA list by stock of data frames for half-sibling pairs. Each row in the data frame corresponds to a "sampling unit" defined by the columns:
yiBirth year of older sibling yjBirth year of younger sibling nNumber of pairwise comparisons mNumber of HSPs CKMR_likeCharacter, likelihood for the POP and HSP sampling units. See
typeargument inlike_CKMR()for options.
Slots inherited from Dtag
tag_ymarrsArray. Number of tags that move between regions. Informs movement matrices of stocks between time steps.
tag_ymarsArray. Number of tags distributed among regions. Informs stock distribution (within time step).
tag_yyBoolean matrix that aggregates years for the tag data. Only used for the tag movement array
tag_ymarrs.tag_aaBoolean matrix that aggregates ages for the tag data.
tag_likeCharacter. Likelihood for the tagging data, either the vector of proportions by region of origin for
tag_ymarrs, or by region of stock distribution fortag_ymars. Seetypeargument oflike_comp()for optionstagN_ymarsArray. Sample size of the tag movement vectors if using the multinomial or Dirichlet-multinomial likelihoods.
tagN_ymasArray. Sample size of the tag distribution vectors if using the multinomial or Dirichlet-multinomial likelihoods.
tagtheta_sArray. Tag dispersion parameter (by stock) if using the Dirichlet-multinomial likelihoods. Default set to 1.
tagstdev_sArray. Tag standard deviation (by stock) if using the lognormal likelihood. Default set to 0.1.
Slots inherited from Dlabel
yearVector of years. Length
Dmodel@nyseasonVector of season names. Length
Dmodel@nmageVector of ages. Length
Dmodel@naregionVector of region names. Length
Dmodel@nrstockVector of stock names. Length
Dmodel@nsfleetVector of fleet names. Length
Dfishery@nfindexVector of index of abundance names. Length
Dsurvey@ni
See Also
MSAdata-class check_data() Dmodel-class Dstock-class Dfishery-class Dsurvey-class DCKMR-class Dtag-class
Examples
# Set natal_rs matrix so that the spawning output of stock 1 is
# calculated from mature animals present in regions 1, 2.
# Similarly for stock 2, spawning output from areas 2 and 3.
nr <- 4
ns <- 2
natal_rs <- matrix(0, nr, ns)
natal_rs[1:2, 1] <- natal_rs[2:3, 2] <- 1
# Aggregate stock composition for ages 1-4 and 5-10 across all fleets
na <- 10
na_SC <- 2
SC_aa <- matrix(0, na_SC, na) # Assumes dim(SC_ymafrs)[3] = na_SC
SC_aa[1, 1:4] <- SC_aa[2, 5:10] <- 1
nf <- 3
nf_SC <- 1
SC_ff <- matrix(1, nf_SC, nf) # Assumes dim(SC_ymafrs)[4] <- nf_SC
Newton-Raphson search for fishing mortality
Description
Performs a root finding routine to find the index of F that minimizes the difference between observed catch and the value predicted by the Baranov equation.
Usage
calc_F(
Cobs,
N,
sel,
wt,
M,
q_fs,
delta = 1,
na = dim(N)[1],
nr = dim(N)[2],
ns = dim(N)[3],
nf = length(Cobs),
Fmax = 2,
nitF = 5L,
trans = c("log", "logit")
)
Arguments
Cobs |
Observed catch. Matrix |
N |
Stock abundance at the beginning of the time step. Array |
sel |
Selectivity. Array |
wt |
Fishery weight at age. Array |
M |
Instantaneous natural mortality. Units of per year |
q_fs |
Relative catchability of stock |
delta |
Numeric, the duration of time in years corresponding to the observed catch, e.g., 0.25 is a quarterly time step. |
na |
Integer, number of age classes |
nr |
Integer, number of regions |
ns |
Integer, number of stocks |
nf |
Integer, number of fleets |
Fmax |
Numeric, the maximum Findex value |
nitF |
Integer, number of iterations for the Newton-Raphson routine |
trans |
Whether to perform the search in log or logit space |
Details
The predicted catch for fleet f in region r is
C^{\textrm{pred}}_{f,r} = \sum_s \sum_a v_{a,f,s} q_{f,s} F_{f,r} \dfrac{1 - \exp(-Z_{a,r,s})}{Z_{a,r,s}} N_{a,r,s} w_{a,f,s}
The Newton-Raphson routine minimizes f(x_{f,r}) = C_{f,r}^{\textrm{pred}} - C_{f,r}^{\textrm{obs}}.
If trans = "log", F_{f,r} = \exp(x_{f,r}).
If trans = "logit", F_{f,r} = F_{\textrm{max}}/(1 + \exp(x_{f,r})).
The gradient with respect to \vec{x} is
f'(x_{f,r}) = \sum_s \sum_a v_{a,f,s} q_{f,s} N_{a,r,s} w_{a,f,s} \left(\dfrac{\alpha\gamma}{\beta}\right)'
\left(\dfrac{\alpha\gamma}{\beta}\right)' = \dfrac{(\alpha\gamma' + \alpha'\gamma)\beta - \alpha\gamma\beta'}{\beta^2}
where
\alpha_{f,r} = F_{f,r} |
\beta_{a,r,s} = Z_{a,r,s} = M_{a,s} + \sum_f v_{a,f,s} q_{f,s} F_{f,r} |
\gamma_{a,r,s} = 1 - \exp(-Z_{a,r,s}) |
\beta'_{a,f,r,s} = v_{a,f} q_{f,s} \alpha'_{f,r} |
\gamma'_{a,f,r,s} = \exp(-Z_{a,r,s})\beta'_{a,f,r,s}
|
If trans = "log", \alpha'_{f,r} = \alpha_{f,r}.
If trans = "logit", \alpha'_{f,r} = F_{\textrm{max}}\exp(-x_{f,r})/(1 + \exp(-x_{f,r}))^2.
This function solves for \vec{x} by iterating until f(\vec{x}) approaches zero, where the vector arrow
indexes over fleet and region. In iteration i+1:
\vec{x}_{i+1} = \vec{x}_i - \dfrac{f(\vec{x}_i)}{f'(\vec{x}_i)}
.
Value
A list containing:
-
F_afrsFishing mortality array -
F_arsFishing mortality array (summed across fleets) -
Z_arsTotal mortality array -
F_indexIndex of fishing mortality. Matrix[f, r] -
CB_frsCatch (biomass) array -
CN_afrsCatch (abundance) array -
VB_afrsVulnerable biomass at the beginning of the time step. Array -
penaltyPenalty term returned byposfun()whenF_indexexceedsFmax -
fnDifference between predicted and observed catch at the last iteration. Matrix[f, r] -
grGradient offnwith respect toF_indexin either log or logit space at the last iteration. Vector by[f, r]
Author(s)
Q. Huynh
Length-at-age key
Description
Calculates the probability distribution of length-at-age using the normal probability density function
Usage
calc_LAK(len_a, sd_la, lbin, nl = length(lbin))
Arguments
len_a |
Vector of length-at-age |
sd_la |
Vector of standard deviation in length-at-age |
lbin |
Vector of the lower boundary of the length bins |
nl |
Integer, number of length bins (default is |
Value
Matrix by age (rows) and length (columns)
Predict the probability of CKMR kinship pairs
Description
Calculate the probability of observing a parent-offspring pair (calc_POP) and
half-sibling pair (calc_HSP) for closed-kin mark recapture (CKMR) for an age-structured
model.
Usage
calc_POP(t, a, y, N, fec)
calc_HSP(yi, yj, N, fec, Z)
Arguments
t |
Vector, capture year of parent |
a |
Vector, age at capture of parent |
y |
Vector, birth year of offspring |
N |
Abundance of mature spawners. Matrix by |
fec |
Fecundity schedule of mature spawners. Matrix by |
yi |
Vector, birth year of sibling |
yj |
Vector, birth year of sibling |
Z |
Instantaneous total mortality rate. Matrix by |
Value
Numeric, vector of probabilities
Parent-offspring pairs
The parent-offspring probability is calculated from Bravington et al. 2016, eq 3.4:
p_{\textrm{POP}} = 2 \times \dfrac{f(y_j,y_j - (t_i - a_i))}{\sum_a f(y_j,a) N(y_j,a)}
where y_j - (t_i - a_i) is the parental age in year y_j. Scalar 2 accounts for the fact
that the parent could be either a mother or a father.
calc_POP is vectorized with respect to t, a, and y.
Half-sibling pairs
The half-sibling probability is calculated from Bravington et al. 2016, eq 3.10, and expanded by Hillary et al. 2018, Supplement S2.8.1 for age-specific survival and fecundity of the parent:
p_{\textrm{HSP}} = 4 \times
\sum_a\left(
\dfrac{N(y_i, a)f(y_i, a)}{\sum_{a'} N(y_i, a')f(y_i,a')}\times
\exp(-\sum_{t = 0}^{y_j - y_i - 1} Z(y_i + t,a + t))\times
\dfrac{f(y_j,a+y_j-y_i)}{\sum_{a'} N(y_j,a')f(y_j,a')}
\right)
The first ratio is the probability that a fish at age
ain yeary_iis the parent ofi.The exponential term is that fish's survival from year
y_itoy_j.The second ratio is the probability that the parent of
i, agea+y_j-y_iin yeary_j, is the parent ofj.
The parent is not observed in the HSP, so we sum the probabilities over all potential ages in year y_i.
calc_HSP is vectorized with respect to yi and yj.
Author(s)
Q. Huynh with contribution from Y. Tsukahara (Fisheries Research Institute, Japan)
References
Bravington, M.V. et al. 2016. Close-Kin Mark-Recapture. Stat. Sci. 31: 259-274. doi:10.1214/16-STS552
Hillary, R.M. et al. 2018. Genetic relatedness reveals total population size of white sharks in eastern Australia and New Zealand. Sci. Rep. 8: 2661. doi:10.1038/s41598-018-20593-w
See Also
Equilibrium distribution from movement matrix
Description
Applies the seasonal movement matrices several times in order to obtain the equilibrium spatial distribution over the course of a year. Not used in the model but useful for reporting.
Usage
calc_eqdist(
x,
nm = dim(x)[1],
nr = dim(x)[2],
start = rep(1/nr, nr),
m_start = 1L,
nit = 20
)
Arguments
x |
Movement array |
nm |
Number of seasons |
nr |
Number of regions |
start |
The initial distribution. Vector of length |
m_start |
Integer, the season in which to apply the initial distribution and start the projection |
nit |
Integer, the number of times the movement matrix will be applied |
Value
Matrix by season and region [m, r]
Calculate von Bertalanffy length-at-age
Description
Returns an array of length-at-age with seasonal dimension. Useful for MSAdata inputs.
Usage
calc_growth(
Linf_s,
K_s,
t0_s,
ns = length(Linf_s),
nm = 4,
ny = 20,
a = seq(1, 10) - 1
)
Arguments
Linf_s |
Vector by stock |
K_s |
Vector by stock |
t0_s |
Vector by |
ns |
Integer, number of stocks |
nm |
Integer, number of seasons |
ny |
Integer, number of years |
a |
Integer vector of ages |
Value
Array [y, m, a, s]
Examples
len_ymas <- calc_growth(c(30, 40), c(0.4, 0.2), c(-1, -1))
# Calculate stock weight at age
a_s <- rep(1e-6, 2)
b_s <- c(3, 3.1)
ns <- length(a_s)
swt_ymas <- sapply(1:ns, function(s) {
a_s[s]*len_ymas[, , , s]^b_s[s]
}, simplify = "array")
Calculate index at age
Description
For indices of abundance, the function calculates the numbers vulnerable to the survey.
Usage
calc_index(
N,
Z,
sel,
na = dim(N)[1],
nr = dim(N)[2],
ns = dim(N)[3],
ni = dim(sel)[2],
samp = array(1, c(ni, nr, ns)),
delta = rep(0, ni)
)
Arguments
N |
Stock abundance at the beginning of the time step. Array |
Z |
Instantaneous total mortality. Array |
sel |
Index selectivity. Array |
na |
Integer, number of age classes |
nr |
Integer, number of regions |
ns |
Integer, number of stocks |
ni |
Integer, number of indices |
samp |
Boolean indicates which regions and stocks are sampled by the index. Array |
delta |
Fraction of time step when the index samples the population. Vector by |
Details
The index is calculated as
I_{a,i,s} = v_{a,i,s} \sum_r N_{a,r,s} d_{a,r,s} \times \mathbb{1}(r \in R_i) \mathbb{1}(s \in S_i)
If the survey samples at a moment in time, then
d_{a,r,s} = \exp(-\delta_i Z_{a,r,s})
Otherwise, if the index samples the population over the duration of the time step, then
d_{a,r,s} = (1 - \exp(-Z_{a,r,s}))/Z_{a,r,s}
where R_i and S_i denote the regions and stocks, respectively, sampled by index i. For example,
R_2 = 1 denotes that the second index of abundance only samples region 1. These are informed by array samp where
samp[i, r, s] = 1 indicates that stock s in region r is sampled by index i.
Value
Index at age. Array [a, i, s]
Project stock abundance to the next time step
Description
This function applies survival of the current abundance, advances age classes, re-distributes the stock using the movement matrix.
Usage
calc_nextN(
N,
surv,
na = dim(N)[1],
nr = dim(N)[2],
ns = dim(N)[3],
advance_age = TRUE,
mov = array(1/nr, c(na, nr, nr, ns)),
plusgroup = TRUE
)
Arguments
N |
Abundance at current time step. Array |
surv |
Survival during the current time step. Array |
na |
Integer, number of age classes |
nr |
Integer, number of regions |
ns |
Integer, number of stocks |
advance_age |
Logical, whether the animals advance to their next age class |
mov |
Movement array in the next time step. Array |
plusgroup |
Logical, whether the last age class is an accumulator plus group. |
Value
Abundance at the next time step. Array [a, r, s]
Equilibrium spawners per recruit by projection
Description
Project a population forward in time using calc_population() with constant recruitment and
seasonal dynamics (growth, movement-by-season) to obtain per recruit parameters. Note that the fishing
mortality among fleets and stocks remain linked by matrix q_fs.
Usage
calc_phi_project(
ny,
nm,
na,
nf = 1,
nr,
ns = 1,
F_mfr = array(0, c(nm, nf, nr)),
sel_mafs = array(1, c(nm, na, nf, ns)),
fwt_mafs = array(1, c(nm, na, nf, ns)),
q_fs = matrix(1, nf, ns),
M_as,
mov_marrs,
mat_as,
fec_as,
m_spawn = 1,
m_advanceage = 1,
delta_s = rep(0, ns),
natal_rs = matrix(1, nr, ns),
recdist_rs = matrix(1/nr, nr, ns)
)
Arguments
ny |
Integer, number of years for the projection |
nm |
Integer, number of seasons |
na |
Integer, number of age classes |
nf |
Integer, number of fleets |
nr |
Integer, number of regions |
ns |
Integer, number of stocks |
F_mfr |
Equilibrium fishing mortality (per season). Matrix |
sel_mafs |
Selectivity by season, age, fleet, stock. Array |
fwt_mafs |
Fishery weight array by season, age, fleet, stock. Array |
q_fs |
Relative catchability of stock |
M_as |
Natural mortality. Matrix |
mov_marrs |
Movement array |
mat_as |
Maturity at age. Matrix |
fec_as |
Fecundity at age. Matrix |
m_spawn |
Integer, season of spawning |
m_advanceage |
Integer, season at which to advance integer year age classes |
delta_s |
Numeric vector by |
natal_rs |
Matrix |
recdist_rs |
Matrix |
Details
The initial population vector will be the survival at age evenly divided by the number of regions nr.
Value
A named list returned by calc_population().
See Also
Simple spawners per recruit calculation
Description
Calculate spawners per recruit by individual stock. Appropriate for a population model with a single spatial area and an annual time steps, i.e. single season.
Usage
calc_phi_simple(Z, fec_a, mat_a, delta = 0)
calc_NPR(Z, na = length(Z), plusgroup = TRUE)
Arguments
Z |
Total mortality at age |
fec_a |
Fecundity at age. Vector |
mat_a |
Maturity at age. Vector |
delta |
Fraction of season that elapses when spawning occurs, e.g., midseason spawning when |
na |
Integer, number of age classes |
plusgroup |
Logical, whether the largest age class is a plusgroup accumulator age |
Value
calc_phi_simple() returns a numeric for the spawning biomass per recruit.
calc_NPR() returns a numeric, numbers per recruit at age
See Also
Multi-fleet, multi-area, multi-stock population dynamics model
Description
Project age-structured populations forward in time. Also used by [calc_phi_project()] to calculate
equilibrium abundance and biomass for which there is no analytic solution
due to seasonal movement.
Usage
calc_population(
ny = 10,
nm = 4,
na = 20,
nf = 1,
nr = 4,
ns = 2,
initN_ars = array(1, c(na, nr, ns)),
mov_ymarrs,
M_yas = array(0.3, c(ny, na, ns)),
SRR_s = rep("BH", ns),
sralpha_s = rep(1e+16, ns),
srbeta_s = rep(1e+16, ns),
mat_yas = array(1, c(ny, na, ns)),
fec_yas = array(1, c(ny, na, ns)),
Rdev_ys = matrix(1, ny, ns),
m_spawn = 1,
m_advanceage = 1,
delta_s = rep(0, ns),
natal_rs = matrix(1, nr, ns),
recdist_rs = matrix(1/nr, nr, ns),
fwt_ymafs = array(1, c(ny, nm, na, nf, ns)),
q_fs = matrix(1, nf, ns),
sel_ymafs = array(1, c(ny, nm, na, nf, ns)),
condition = c("F", "catch"),
F_ymfr = array(0, c(ny, nm, nf, nr)),
Cobs_ymfr = array(1e-08, c(ny, nm, nf, nr)),
Fmax = 2,
nitF = 5L
)
Arguments
ny |
Integer, number of years for the projection |
nm |
Integer, number of seasons |
na |
Integer, number of age classes |
nf |
Integer, number of fleets |
nr |
Integer, number of regions |
ns |
Integer, number of stocks |
initN_ars |
Abundance in the first year, first season. Array |
mov_ymarrs |
Movement array |
M_yas |
Natural mortality (per year). Array |
SRR_s |
Character vector by |
sralpha_s |
Numeric vector by |
srbeta_s |
Numeric vector by |
mat_yas |
Maturity ogive. Array |
fec_yas |
Fecundity schedule (spawning output of mature individuals). Array |
Rdev_ys |
Recruitment deviations. Matrix |
m_spawn |
Integer, season of spawning |
m_advanceage |
Integer, season at which to advance integer year age classes |
delta_s |
Numeric vector by |
natal_rs |
Matrix |
recdist_rs |
Matrix |
fwt_ymafs |
Fishery weight at age. Array |
q_fs |
Relative catchability of stock |
sel_ymafs |
Fishery selectivity. Array |
condition |
Whether the fishing mortality is conditioned on the catch or specified F argument. |
F_ymfr |
Fishing mortality (per season). Array |
Cobs_ymfr |
Fishery catch (weight). Array |
Fmax |
Numeric, the maximum Findex value |
nitF |
Integer, number of iterations for the Newton-Raphson routine |
Value
A named list containing:
-
N_ymarsStock abundance -
F_ymarsFishing mortality (summed across fleets) -
F_ymfrFishing mortality (by fleet and region) -
Z_ymarsTotal mortality -
F_ymafrsFishing mortality (disaggregated by fleet) -
CN_ymafrsCatch at age (abundance) -
CB_ymfrsFishery catch (weight) -
VB_ymfrsVulnerable biomass available to the fishing fleets -
Nsp_yarsSpawning abundance (in the spawning season) -
Npsp_yarsPotentail spawners, mature animals in the spawning season that do not spawn if outside natal regions -
S_yrsSpawning output -
R_ysRecruitment -
penaltyNumeric quadratic penalty if apical fishing mortality (by fleet) exceedsFmax. Seecalc_F().
Examples
unfished_pop <- calc_population()
Calculate recruitment from stock-recruit function
Description
Calculate recruitment from stock-recruit function
Usage
calc_recruitment(x, SRR = c("BH", "Ricker"), eq = FALSE, ...)
Arguments
x |
Numeric, either the spawning output or the equilibrium spawners per recruit, from which
the recruitment will be calculated. See argument |
SRR |
Character to indicate the functional form of the stock recruit function |
eq |
Logical, indicates whether |
... |
Parameters of the SRR function. Provide one of two sets of variables:
|
Value
Numeric of length x
Examples
calc_recruitment(10, SRR = "Ricker", a = 2, b = 0.5)
calc_recruitment(10, SRR = "Ricker", h = 0.9, R0 = 1, phi0 = 1)
Check dimensions and inputs in MSAdata object
Description
Ensures that data inputs are of proper dimension. Whenever possible, default values are added to missing items.
Usage
check_data(MSAdata, silent = FALSE)
Arguments
MSAdata |
S4 object containing data inputs. See MSAdata |
silent |
Logical, whether or not to report default values to the console |
Value
An updated MSAdata object.
See Also
Calculate covariance matrix
Description
Uses Cholesky factorization to generate a covariance matrix (or any symmetric positive definite matrix).
Usage
conv_Sigma(sigma, lower_diag)
Arguments
sigma |
Numeric vector of marginal standard deviations (all greater than zeros) |
lower_diag |
Numeric vector to populate the lower triangle of the correlation matrix. All real numbers.
Length |
Value
Numeric
Examples
set.seed(23)
n <- 5
sigma <- runif(n, 0, 2)
lower_diag <- runif(sum(1:(n-1)), -10, 10)
Sigma <- conv_Sigma(sigma, lower_diag)
Sigma/t(Sigma) # Is symmetric matrix? All ones
cov2cor(Sigma)
Calculate movement matrix for all age classes
Description
Movement matrices are calculated for all age classes from a base matrix and a gravity model formulation (Carruthers et al. 2016).
Usage
conv_mov(x, g, v, na = dim(x)[1], nr = dim(x)[2], aref = ceiling(0.5 * na))
Arguments
x |
Base log-movement parameters. See details. Array |
g |
Gravity model attractivity term. Tendency to move to region |
v |
Gravity model viscosity term. Tendency to stay in same region. Vector by |
na |
Integer, number of ages |
nr |
Integer, number of regions |
aref |
Integer, reference age class |
Details
Rows index region of origin and columns denote region of destination.
In log space, the movement matrix m_a for age class a from region r to r' is the sum of base matrix x and
gravity matrix G:
m_{a,r,r'} = x_{a,r,r'} + G_{a,r,r'}
To essentially exclude movement from r to r', set x_{a,r,r'} = -1000.
Gravity matrix G includes an attractivity term g and viscosity term v:
G_{a,r,r'} =
\begin{cases}
g'_{a,r'} + v_a \quad & r = r'\\
g'_{a,r'} \quad & \textrm{otherwise}
\end{cases}
Vector g' are offset terms relative to the value for the reference age class:
g'_{a,r'} =
\begin{cases}
g_{a,r} \quad & a = a_{ref}\\
g_{a,r} + g_{a=aref,r} \quad & \textrm{otherwise}
\end{cases}
The movement matrix in normal space is obtained by the softmax transformation:
M_{a,r,r'} = \dfrac{\exp(m_{a,r,r'})}{\sum_{r'}\exp(m_{a,r,r'})}
If x and v are zero, then the movement matrix simply distributes the total stock
abundance into the various regions as specified in g'.
Value
Movement array [a, r, r]
References
Carruthers, T.R., et al. 2015. Modelling age-dependent movement: an application to red and gag groupers in the Gulf of Mexico. CJFAS 72: 1159-1176. doi:10.1139/cjfas-2014-0471
Selectivity at age and length
Description
Calculate selectivity at age and length from a matrix of parameters.
-
conv_selpar()converts parameters from log or logit space to real units. -
calc_sel_len()calculates selectivity at length. -
calc_fsel_age()calculates selectivity at age for fisheries, and coordinates dummy fleets. -
calc_isel_age()calculates selectivity at age for indices, and can map selectivity from fisheries or population parameters (e.g, mature or total biomass).
Usage
conv_selpar(x, type, maxage, maxL)
calc_sel_len(sel_par, lmid, type)
calc_fsel_age(
sel_len,
LAK,
type,
sel_par,
sel_block = seq(1, length(type)),
mat,
a = seq(1, nrow(LAK)) - 1
)
calc_isel_age(
sel_len,
LAK,
type,
sel_par,
fsel_age,
maxage,
mat,
a = seq(1, nrow(LAK)) - 1
)
Arguments
x |
Estimated parameters. Matrix |
type |
Character string to indicate the functional form of selectivity. Options include:
|
maxage |
Maximum value of the age of full selectivity |
maxL |
Maximum value of the length of full selectivity |
sel_par |
Matrix of parameters returned by |
lmid |
Midpoints of length bins for calculating selectivity at length |
sel_len |
Selectivity at length matrix returned by |
LAK |
Length-at-age probability matrix. Matrix |
sel_block |
Integer vector. Length |
mat |
Maturity at age vector |
a |
Integer vector of ages corresponding to the rows of |
fsel_age |
Matrix returned by |
Value
conv_selpar() returns a matrix of the same dimensions as x.
calc_sel_len() returns a matrix [l, f], i.e., [length(lmid), length(type)].
calc_fsel_age() returns a matrix [a, f], i.e., [a, length(sel_block)]
calc_isel_age() returns a matrix [a, i], i.e., [a, length(type)]
Converting selectivity parameters (conv_selpar)
The first row of x corresponds to the length or age of full selectivity: \mu_f = L_{max}/(1 + \exp(-x_{1,f}))
The second row of x corresponds to the width of the ascending limb for selectivity:
\sigma_f^{asc} = \exp(x_{2,f})
The third row of x corresponds to the width of the descending limb for selectivity (if dome-shaped):
\sigma_f^{des} = \exp(x_{3,f})
Length selectivity (calc_sel_len)
The selectivity at length is
s_{\ell} =
\begin{cases}
\exp(\alpha) & L_{\ell} < \mu_f\\
\exp(\beta) & L_{\ell} \ge \mu_f\\
\end{cases}
where
\alpha = -0.5(L_\ell - \mu_f)^2/(\sigma_f^{asc})^2
and
\beta = -0.5(L_\ell - \mu_f)^2/(\sigma_f^{des})^2
Age selectivity (calc_fsel_age)
The equivalent selectivity at age is converted from the length values (sel_len) as
s_a = \sum_\ell s_\ell \times \textrm{Prob}(L_{\ell}|a)
If selectivity is explicitly in age units, then the values are directly calculated
from parameters in sel_par.
Vector sel_block assigns the output selectivity from a different column of the input matrix
and facilitates time-varying selectivity in time blocks. For example, sel_block[1] <- 2 means
that selectivity values in the first column of the output is based on the second column of the
input matrices (sel_len[, 2] or sel_par[, 2]).
Fit MSA model
Description
Wrapper function that calls RTMB to create the model and perform the numerical optimization
Usage
fit_MSA(
MSAdata,
parameters,
map = list(),
random = NULL,
run_model = TRUE,
do_sd = TRUE,
report = TRUE,
silent = FALSE,
control = list(iter.max = 2e+05, eval.max = 4e+05),
...
)
Arguments
MSAdata |
Data object. Class MSAdata, validated by |
parameters |
List of parameters, e.g., returned by |
map |
List of parameters indicated whether they are fixed and how they are shared, e.g., returned by |
random |
Character vector indicating the parameters that are random effects, e.g., returned by |
run_model |
Logical, whether to fit the model through |
do_sd |
Logical, whether to calculate the standard errors with |
report |
Logical, whether to return the report list with |
silent |
Logical, whether to report progress to console. Not passed to |
control |
Passed to |
... |
Other arguments to |
Value
A MSAassess object.
See Also
Retrieve data object used to fit model
Description
A convenient function to retrieve the data object used to fit the model. The object is embedded in an environment within the RTMB object.
Usage
get_MSAdata(MSAassess)
Arguments
MSAassess |
MSAassess object returned by |
Value
MSAdata object
Calculate standard errors
Description
A wrapper function to return standard errors. Various numerical techniques are employed to obtain a positive-definite covariance matrix.
Usage
get_sdreport(obj, getReportCovariance = FALSE, silent = FALSE, ...)
Arguments
obj |
The list returned by |
getReportCovariance |
Logical, passed to |
silent |
Logical, whether to report progress to console. See details. |
... |
Other arguments to |
Details
In marginal cases where the determinant of the Hessian matrix is less than 0.1, several steps are utilized to obtain a positive-definite covariance matrix, in the following order:
Invert hessian returned by
h <- obj@he(obj$env.last.par.best)(skipped in models with random effects)Invert hessian returned by
h <- stats::optimHess(obj$env.last.par.best, obj$fn, obj$gr)Invert hessian returned by
h <- numDeriv::jacobian(obj$gr, obj$env.last.par.best)Calculate covariance matrix from
chol2inv(chol(h))
Value
Object returned by RTMB::sdreport(). A correlation matrix is generated and stored in: get_sdreport(obj)$env$corr.fixed
Likelihood for CKMR
Description
Returns the log-likelihood for a set of pairwise comparisons. For a parent-offspring pair, a comparison is defined by the capture year of parent, capture age of parent, and birth year of offspring. For a half-sibling pair, a comparison is defined by the cohort year of each sibling. Binomial and Poisson distributions are supported (Conn et al. 2020).
Usage
like_CKMR(n, m, p, type = c("binomial", "poisson"))
Arguments
n |
The number of pairwise comparisons |
m |
The number of kinship matches |
p |
The probability of kinship match |
type |
The statistical distribution for the likelihood calculation |
Value
Numeric representing the log-likelihood.
References
Conn, P.B. et al. 2020. Robustness of close-kin mark-recapture estimators to dispersal limitation and spatially varying sampling probabilities. Ecol. Evol. 10: 5558-5569. doi:10.1002/ece3.6296
See Also
Likelihood for composition vectors
Description
Returns the log-likelihood for composition data, e.g., length, age, or stock composition, with various statistical distributions supported.
Usage
like_comp(
obs,
pred,
type = c("multinomial", "dirmult1", "dirmult2", "lognormal"),
N = sum(obs),
theta,
stdev
)
Arguments
obs |
A vector of observed values. Internally converted to proportions. |
pred |
A vector of predicted values. Same length as |
type |
Character for the desired distribution |
N |
Numeric, the sample size corresponding to |
theta |
Numeric, the linear ( |
stdev |
Numeric or vectorized for |
Details
Observed and predicted vectors are internally converted to proportions.
For type = "lognormal", zero observations are removed from the likelihood calculation.
Value
Numeric representing the log-likelihood.
References
Thorson et al. 2017. Model-based estimates of effective sample size in stock assessment models using the Dirichlet-multinomial distribution. Fish. Res. 192:84-93. doi:10.1016/j.fishres.2016.06.005
Examples
M <- 0.1
age <- seq(1:10)
pred <- exp(-M * age)
obs <- pred * rlnorm(10, sd = 0.05)
like_comp(obs, pred, N = 10, type = "multinomial")
like_comp(obs, pred, N = 100, type = "multinomial")
like_comp(obs, pred, N = 10, type = "dirmult1", theta = 1)
like_comp(obs, pred, N = 10, type = "dirmult1", theta = 20)
Make list of parameters for RTMB
Description
Sets up the list of parameters, map of parameters (see map argument in TMB::MakeADFun()), and identifies some random effects parameters
based on the input data and some user choices on model configuration.
These functions provide a template for the parameter and map setup that can be adjusted for alternative configurations. check_parameters()
checks whether custom made parameter lists are of the correct dimension.
Usage
make_parameters(
MSAdata,
start = list(),
map = list(),
est_mov = c("none", "dist_random", "gravity_fixed"),
silent = FALSE,
...
)
make_map(
p,
MSAdata,
map = list(),
est_M = FALSE,
est_h = FALSE,
est_mat = FALSE,
est_sdr = FALSE,
est_mov = c("none", "dist_random", "gravity_fixed"),
est_qfs = FALSE,
silent = FALSE
)
check_parameters(p = list(), map, MSAdata, silent = FALSE)
Arguments
MSAdata |
S4 data object |
start |
An optional list of parameters. Named list of parameters with the associated dimensions and transformations below.
Overrides default values created by |
map |
List of mapped parameters. Used by |
est_mov |
Character describing structure of stock movement parameters. Only used if map arguments for the movement parameters is NULL. See details below. |
silent |
Logical, whether |
... |
Various arguments for |
p |
List of parameters, e.g., returned by |
est_M |
Logical, estimate natural mortality? Only used if |
est_h |
Logical, estimate steepness? Only used if |
est_mat |
Logical, estimate maturity? Only used if |
est_sdr |
Logical, estimate standard deviation of recruitment deviates? Only used if |
est_qfs |
Logical, estimate relative catchability of stocks by each fleet? Fix |
Value
make_parameters() returns a list of parameters ("p") concatenated with the output of make_map().
make_map() returns a named list containing parameter mappings ("map") and a character vector of random effects ("random").
check_parameters() invisibly returns the parameter list if no problems are encountered.
Parameters
Generally parameter names will have up to three components, separated by underscores.
For example, log_M_s represents the natural logarithm of natural mortality, and is a vector by stock s.
The first component describes the transformation from the estimated parameter space to the normal parameter space,
frequently, log or logit. Prefix t indicates some other custom transformation that is described below.
Second is the parameter name, e.g., M for natural mortality, rdev for recruitment deviates, etc.
Third is the dimension of the parameter variable and the indexing for the vectors, matrices, and arrays, e.g., y for year, s for stock.
See MSAdata. Here, an additional index p represents some other number of parameters that is described below.
t_R0_sVector by
s. Unfished recruitment, i.e., intersection of unfished replacement line and average stock recruit function, is represented as:R0_s <- exp(t_R0_s) * MSAdata@Dmodel@scale_s. By default,t_R0_s = 3t_h_sVector by
s. Steepness of the stock-recruit function. Logit space for Beverton-Holt and log space for Ricker functions. Default steepness value of 0.8mat_psMatrix
[2, s]. Maturity parameters (can be estimated or specified in data object). Logistic functional form. The parameter in the first row is the age of 50 percent maturity in logit space:a50_s <- plogis(mat_ps[1, ] * na). In the second row is the age of 95 percent maturity as a logarithmic offset:a95_s <- a50_s + exp(mat_ps[2, ]). Defaulta50_s <- 0.5 * naanda95_s <- a50_s + 1log_M_sVector by
s. Natural logarithm of natural mortality (can be estimated or specified in data object). Default parameter value for all stocks:M <- -log(0.05)/MSAdata@Dmodel@nalog_rdev_ysMatrix
[y, s]. Log recruitment deviations. By default, all start values are at zero.log_sdr_sVector by
s. log-Standard deviation of the log recruitment deviations. Default SD = 0.4log_q_fsMatrix
[f, s]. The natural logarithm ofq_fs, the relative fishing efficiency offfor stocks. Equal values imply equal catchability of all stocks. See equations incalc_F(). Default sets all values to zero.log_Fdev_ymfrArray
[y, m, f, r]. Fishing mortality parameters. For each fleet, the log of F is estimated directly for the reference year, season, region. For other strata, F is an offset from this value:F_{y,m,f,r} = \begin{cases} \exp(x^{\textrm{Fmult}}_f) \quad & y = y_{\textrm{ref}}, m = m_{\textrm{ref}}, r = r_{\textrm{ref}}\\ \exp(x^{\textrm{Fmult}}_f + x^{\textrm{Fdev}}_{y,m,r}) \quad & \textrm{otherwise} \end{cases}sel_pfMatrix
[3, f]. Fishery selectivity parameters in logit or log space. See equationsconv_selpar(), wheresel_pfis thexmatrix.sel_piMatrix
[3, i]. Index selectivity parameters in logit or log space. See equationsconv_selpar(), wheresel_piis thexmatrix.mov_x_marrsArray
[m, a, r, r, s]. Base movement matrix. Set to -1000 to effectively exclude movements from region pairs. See equations inconv_mov()mov_g_ymarsArray
[y, m, a, r, s]. Attractivity term in gravity model for movement. Ifxandvare zero, this matrix specifies the distribution of total stock abundance into the various regions. See equations inconv_mov()mov_v_ymasArray
[y, m, a, s]. Viscosity term in gravity model for movement. See equations inconv_mov()log_sdg_rsArray
[r, s]. Marginal log standard deviation in the stock distribution (mov_g_ymars) among regions for stocks. Only used whenest_mov = "dist_random". Default SD of 0.1.t_corg_psArray
[sum(1:(nr - 1)), s]. Lower triangle of the correlation matrix formov_g_ymars, to be obtained with the Cholesky factorization. Only used whenest_mov = dist_random. Default values of zero.log_initF_mfrArray
[m, f, r]. Initial F corresponding to the equilibrium catch.log_initrdev_asArray
[na - 1, s]. Recruitment deviations for the initial abundance-at-age vector.
Start list
Users can provide R0_s and h_s in the start list. make_parameters() will make the appropriate transformation for the starting values
of t_R0_s and t_h_s, respectively.
Movement setup for make_map()
If a single region model or est_mov = "none": no movement parameters are estimated.
If est_mov = "dist_random": fix all values for mov_x_marrs and mov_v_ymas. Fix mov_g_ymars for the first region for each year,
season, age, and stock. mov_g_ymars are random effects.
If est_mov = "gravity_fixed": fix all values for mov_x_marrs. Fix mov_g_ymars for the first region for each year,
season, age, and stock. Estimate all mov_v_ymas. Both mov_g_ymars and mov_v_ymas are fixed effects.
By default p$mov_x_marrs is zero. Set to -1000 for areas for which there is no abundance of a particular stock.
See Also
Optimize RTMB model
Description
A convenient function that fits a RTMB model and calculates standard errors.
Usage
optimize_RTMB(
obj,
hessian = FALSE,
restart = 0,
do_sd = TRUE,
control = list(iter.max = 2e+05, eval.max = 4e+05),
lower = -Inf,
upper = Inf,
silent = FALSE
)
Arguments
obj |
The list returned by |
hessian |
Logical, whether to pass the Hessian function |
restart |
Integer, the maximum number of additional attempts to fit the model. See details. |
do_sd |
Logical, whether to calculate standard errors through |
control |
List of options passed to |
lower |
Lower bounds of parameters passed to |
upper |
Upper bounds of parameters passed to |
silent |
Logical, whether to report progress to console |
Details
Argument restart allows for recursive model fitting to obtain convergence, through the following procedure:
Optimize model with
stats::nlminb().Determine convergence, defined by
RTMB::sdreport()by whether the Cholesky decomposition of the covariance matrix is possible.If convergence is not achieved, jitter parameter estimates with multiplicative factor
rlnorm(mean = 0, sd = 1e-3)and return to step 1.
Value
A named list: "opt" is the output of stats::nlminb() and "SD" is the output of get_sdreport()
See Also
Plotting functions for data in MSA model
Description
A set of functions to plot data variables and predicted values (catch, age composition, etc.)
Usage
plot_catch(fit, f = 1, by = c("region", "stock"), prop = FALSE, annual = FALSE)
plot_index(fit, i = 1, zoom = FALSE)
plot_CAA(fit, f = 1, r = 1, do_mean = FALSE)
plot_CAL(fit, f = 1, r = 1, do_mean = FALSE)
plot_IAA(fit, i = 1, do_mean = FALSE)
plot_IAL(fit, i = 1, do_mean = FALSE)
plot_SC(fit, ff = 1, aa = 1, r = 1, prop = FALSE)
plot_tagmov(fit, s = 1, yy = 1, aa = 1)
Arguments
fit |
|
f |
Integer, indexes the fleet |
by |
Character to indicate dimension for multivariate plots |
prop |
Logical, whether to plot proportions (TRUE) or absolute numbers |
annual |
Logical, whether to plot annual values (summed over seasons) |
i |
Integer, indexes the survey |
zoom |
Logical, for |
r |
Integer, indexes the region |
do_mean |
Logical, whether to plot full compositions or time series of mean length or mean age |
ff |
Integer, indexes the aggregate fleet (for stock composition data) |
aa |
Integer, indexes the aggregate age class (for stock composition and tag data) |
s |
Integer, indexes the stock |
yy |
Integer, indexes the aggregate years (for the tag data) |
Details
-
plot_catchplots the fishery catch by stock or region (either whole numbers or proportions)
-
plot_indexplots indices of abundance
-
plot_CAAplots the fishery catch at age
-
plot_CALplots the catch at length
-
plot_IAAplots the index age composition
-
plot_IALplots the index length composition
-
plot_SCplots the stock composition
-
plot_tagmovplots the tag movements
Value
Various base graphics plots
Plotting functions for fitted MSA model
Description
A set of functions to plot state variables (biomass, recruitment time series, etc.)
Usage
plot_S(fit, by = c("stock", "region"), r, s, prop = FALSE, facet_free = FALSE)
plot_B(fit, by = c("stock", "region"), r, s, prop = FALSE, facet_free = FALSE)
plot_R(fit, s)
plot_SRR(fit, s = 1, phi = TRUE)
plot_Rdev(fit, s = 1, log = TRUE)
plot_Fstock(fit, s, by = c("annual", "season"))
plot_self(fit, f = 1, type = c("length", "age"))
plot_seli(fit, i = 1)
plot_selstock(
fit,
s = 1,
by = c("annual", "season"),
plot2d = c("contour", "filled.contour"),
...
)
plot_N(fit, m = 1, r, s = 1, plot2d = c("contour", "filled.contour"), ...)
plot_V(fit, f = 1, by = c("stock", "region"), prop = FALSE, facet_free = FALSE)
plot_Ffleet(fit, f = 1)
plot_mov(fit, s = 1, y, a, palette = "Peach")
plot_recdist(fit, palette = "Peach")
Arguments
fit |
|
by |
Character to indicate whether to calculate selectivity from F per year or per season |
r |
Integer for the corresponding region |
s |
Integer for the corresponding stock |
prop |
Logical, whether to plot proportions (TRUE) or absolute numbers |
facet_free |
Logical, whether to allow the y-axis limits to vary by panel in facetted plots |
phi |
Logical, whether to plot unfished replacement line |
log |
Logical, whether to plot the natural logarithm of the response variable |
f |
Integer for the corresponding fleet |
type |
For |
i |
Integer for the corresponding survey |
plot2d |
Character, plotting function for either a |
... |
Other argument to the base graphics function |
m |
Integer for the corresponding season |
y |
Integer, year for plotting the movement matrix (last model year is the default) |
a |
Integer, corresponding age for plotting the movement matrix (age 1 is the default) |
palette |
Character, palette name to pass to |
Details
-
plot_Splots spawning output by stock or region (either whole numbers or proportions for the latter)
-
plot_Bplots total biomass by stock or region (either whole numbers or proportions for the latter)
-
plot_Rplots recruitment by stock
-
plot_SRRplots the stock-recruitment relationship and history (realized recruitment) by stock
-
plot_Rdevplots recruitment deviations by stock
-
plot_Fstockplots apical instantaneous fishing mortality (per year or per season) by stock
-
plot_selfplots fishery selectivity
-
plot_seliplots index selectivity
-
plot_selstockplots the realized selectivity from total catch and total abundance at age
-
plot_Nreports total abundance at age
-
plot_Vplots vulnerable biomass, availability to the fishery
-
plot_Ffleetplots apical instantaneous fishing mortality (per season) by fleet
-
plot_movplots movement matrices and the corresponding equilibrium distribution in multi-area models
-
plot_recdistplots the distribution of recruitment for each stock
Value
Various base graphics plots
Quadratic penalty function
Description
Taped penalty function if x < eps
Usage
posfun(x, eps)
Arguments
x |
Numeric, the parameter |
eps |
Numeric, the threshold below which a penalty will be applied |
Value
The penalty value is
\textrm{penalty} =
\begin{cases}
0.1 (x - \varepsilon)^2 & x \le \varepsilon\\
0 & x > \varepsilon
\end{cases}
Numeric
Priors for MSA model
Description
Priors in MSA are set by providing character strings which are then parsed into an expression and evaluated in the model environment
(see example). This provides flexibility to set a prior for any desired model parameter or variable. See list of parameters in the
documentation for [check_parameters()] for options (note that priors for log_rdev_ys and log_initrdev_as are not needed as they're hard-coded into the model).
Several functions below generate the character string for the prior for important dynamics parameters, such as natural mortality and steepness.
Usage
prior_h(MSAdata, s = 1, m, stdev)
prior_M(MSAdata, s = 1, meanlog, sdlog)
prior_q(MSAdata, i = 1, meanlog, sdlog)
Arguments
MSAdata |
Data object. Class MSAdata |
s |
Integer for stock |
m |
Mean in un-transformed space |
stdev |
Standard deviation in un-transformed space |
meanlog |
Mean of the lognormal distribution on the log scale |
sdlog |
Standard of the lognormal distribution on the log scale |
i |
Integer for the corresponding index |
Details
-
prior_hreturns the log prior for stock-recruit steepness. Beta distribution for the Beverton-Holt function and normal distribution for Ricker function.
-
prior_Mreturns the log prior for natural mortality. Lognormal distribution.
-
prior_qreturns the log prior for index catchability. Lognormal distribution.
Value
Character.
Examples
# Add M and steepness prior to model
dat <- new("MSAdata")
dat@Dmodel@ns <- 1
dat@Dstock@SRR_s <- "BH"
pr_M <- prior_M(dat, s = 1, log(0.25), 0.3)
pr_h <- prior_h(dat, s = 1, 0.8, 0.15)
dat@Dmodel@prior <- c(pr_M, pr_h)
Profile parameters of MSA model
Description
Evaluate change in objective function and likelihood components for up to 2 parameters.
Usage
## S3 method for class 'MSAassess'
profile(fitted, p1, v1, p2, v2, cores = 1, ...)
## S3 method for class 'MSAprof'
plot(
x,
component = "objective",
rel = TRUE,
xlab,
ylab,
main,
plot2d = c("contour", "filled.contour"),
...
)
Arguments
fitted |
|
p1 |
Character string that represents the first parameter to be profiled,
including the parameter name and index of the vector/array. See "Parameters" section of |
v1 |
Vector of values corresponding to |
p2 |
Character string that represents the optional second parameter to be profiled |
v2 |
Vector of values corresponding to |
cores |
Integer for the number of cores to use for parallel processing (snowfall package) |
... |
Other argument to the base graphics function, i.e., either plot() or contour() |
x |
Output from |
component |
Character for the column in |
rel |
Logical, whether the relative change in |
xlab |
Optional character for the x-axis label |
ylab |
Optional character for the y-axis label |
main |
Optional character for the plot title |
plot2d |
Character, plotting function for two-dimensional profiling (either a |
Value
The profile generic returns a data frame of the likelihood values that correspond to
fixed values of p1 and p2.
Likelihood
loglikerefers to maximizing the probability of the observed data (higher values for better fit)Prior
logpriorrefers to maximizing the probability of a parameter to their prior distribution (higher values are closer to the prior mode)Penalty
penaltyare values added to the objective function when parameters exceed model bounds (lower values are better)-
fnis the objective function returned by RTMB (lower values are better) -
objectiveis the objective function returned by the optimizer (lower values are better)
The accompanying plot function returns a line plot for a 1-dimensional profile or a contour plot for a two dimensional profile. Will plot the negative log likelihood or negative log prior (better fit with lower values).
Relative values are obtained by subtracting from the fitted value. See attr(x, "fitted")
Generate markdown reports
Description
Generate a markdown report of model fits and estimates.
Usage
report(object, ...)
## S3 method for class 'MSAassess'
report(
object,
name,
filename = "MSA",
dir = tempdir(),
open_file = TRUE,
render_args = list(),
...
)
Arguments
object |
An object from MSA. |
... |
Additional arguments to render reports. |
name |
Optional character string for the model name to include in the report, e.g., model run number. Default
uses |
filename |
Character string for the name of the markdown and HTML files. |
dir |
The directory in which the markdown and HTML files will be saved. |
open_file |
Logical, whether the HTML document is opened after it is rendered. |
render_args |
List of arguments to pass to |
Value
report.MSAassess invisibly returns the output of rmarkdown::render(): character of the path of the rendered HTML markdown report.
Calculate model residuals
Description
Extract residuals from fitted model
Usage
## S3 method for class 'MSAassess'
residuals(object, vars, type = c("response", "pearson"), ...)
Arguments
object |
MSAassess object returned by |
vars |
Character vector to indicate which residuals will be calculated. Available choices from MSAdata object are: "Cinit_mfr", "Cobs_ymfr", "CAAobs_ymafr", "CALobs_ymlfr", "Iobs_ymi", "IAAobs_ymai", "IALobs_ymli", "SC_ymafrs" |
type |
Character, 'response' for the |
... |
Not used |
Value
A named list based on vars argument.
Retrospective analysis
Description
Perform a retrospective analysis, successive removals of most recent years of data to evaluate consistency in model estimates of biomass, recruitment, etc.
The summary method returns Mohn's rho and the plot method generates a markdown report.
Usage
retrospective(MSAassess, yret = 0:5, cores = 1)
## S3 method for class 'MSAretro'
plot(
x,
var = c("S_yst", "R_yst", "F_yst", "log_rdev_yst", "VB_ymft"),
s = 1,
f = 1,
...
)
## S3 method for class 'MSAretro'
summary(object, by = c("stock", "fleet"), ...)
## S3 method for class 'MSAretro'
report(
object,
filename = "retro",
dir = tempdir(),
open_file = TRUE,
render_args = list(),
...
)
Arguments
MSAassess |
MSAassess object |
yret |
Vector specifying the years (positive integers and include zero) to remove for the retrospective analysis |
cores |
Integer for the number of cores to use for parallel processing (snowfall package) |
x, object |
Output of |
var |
Character to indicate the metric, the item in the |
s |
Integer for the stock index to plot |
f |
Integer for the fleet index to plot |
... |
Not used |
by |
Character indicating whether to calculate to Mohn's rho on stock or fleet-based time series |
filename |
Character string for the name of the markdown and HTML files. |
dir |
The directory in which the markdown and HTML files will be saved. |
open_file |
Logical, whether the HTML document is opened after it is rendered. |
render_args |
List of arguments to pass to |
Value
A MSAretro object containing a named lists of arrays generated by the retrospective analysis:
-
S_ystSpawning output array[y, s, t]wheretindexes the retrospective peel -
R_ystRecruitment array[y, s, t] -
F_ystApical fishing mortality[y, s, t] -
VB_ymftVulnerable biomass available to each fishery[y, m, f, t]
plot.MSAretro returns individual figures using base graphics.
summary.MSAretro returns a matrix of Mohn's rho.
report.MSAretro invisibly returns the output of rmarkdown::render(): character of the path of the rendered HTML markdown report.
sapply2 function
Description
An alternate sapply function with argument simplify = "array" for convenience.
Usage
sapply2(X, FUN, ..., USE.NAMES = TRUE)
Arguments
X, FUN, ..., USE.NAMES |
Same arguments as |
Value
Output of simplify2array(), typically an array
Simulate data
Description
Simulate data observations from fitted MSA model.
Usage
## S3 method for class 'MSAassess'
simulate(object, nsim = 1, seed = NULL, ...)
Arguments
object |
|
nsim |
Integer, number of simulations |
seed |
Random number generator seed |
... |
Not used |
Value
A list of nsim length with data observations
Softmax function
Description
Takes a vector of real numbers and returns the corresponding vector of probabilities
Usage
softmax(eta, log = FALSE)
Arguments
eta |
Vector |
log |
Logical, whether to return the value of the logarithm |
Details
Uses multiSA:::logspace.add for numerical stability
Value
Numeric, vector length of eta: \exp(\eta)/\sum\exp(\eta)