| Title: | Modules and Functions for the mse Package |
|---|---|
| Description: | A number of additional modules and auxiliary functions for the 'mse' package are provided here. |
| Authors: | Iago Mosqueira [aut, cre] (ORCID: <https://orcid.org/0000-0002-3252-0591>) |
| Maintainer: | Iago Mosqueira <[email protected]> |
| License: | EUPL-1.2 |
| Version: | 0.2.2 |
| Built: | 2026-05-24 16:32:52 UTC |
| Source: | https://github.com/flr/msemodules |
Adjusts a TAC recommendation from an HCR by banking a proportion of any increase or borrowing against a future quota when a decrease is large, smoothing inter-annual TAC variability while respecting stock health conditions.
bank_borrow.is( stk, ctrl, args, split = NULL, rate = NULL, diff = 0.15, healthy = 1, tracking )bank_borrow.is( stk, ctrl, args, split = NULL, rate = NULL, diff = 0.15, healthy = 1, tracking )
stk |
An FLCore::FLStock object representing the stock. |
ctrl |
An FLasher::fwdControl object carrying the TAC recommendation to be adjusted. |
args |
A list of management-cycle dimensionality arguments supplied
automatically by |
split |
Optional split-control input. Currently unused; reserved for
future support of multiple mse::mseCtrl objects within a single
|
rate |
Numeric in |
diff |
Numeric. Minimum relative change in TAC (compared to the
previous HCR decision |
healthy |
Numeric. Minimum value of the |
tracking |
An FLCore::FLQuant used to record intermediate
values and decisions during MP evaluation, passed through and updated by
|
In the initial year (ay == iy) the tracking metrics borrowing.isys and
banking.isys are initialized to zero and the reference TAC (pre) is set
to the realized catch in the year preceding the management lag.
In subsequent years pre is taken from the hcr tracking metric for the
current year, and the TAC carried in ctrl is first corrected for any
amount borrowed or banked in the previous cycle before new banking/borrowing
is evaluated.
Banking and borrowing are triggered as follows:
Borrowing: if the (corrected) TAC falls more than diff below
pre and the stock is healthy, rate * tac is added to the
current TAC and recorded in borrowing.isys.
Banking: if the (corrected) TAC rises more than diff above
pre and the stock is healthy, rate * tac is subtracted from
the current TAC and recorded in banking.isys.
Only annual management cycles (frq == 1) are currently supported; a
non-annual frq raises an error.
A list with two elements:
ctrlThe input FLasher::fwdControl object with the
adjusted TAC stored in ctrl$value.
trackingThe updated tracking object, with borrowing.isys and
banking.isys metrics written for the assessment year ay.
Iago MOSQUEIRA [email protected]
mse::mp(), mse::mpCtrl(), mse::mseCtrl()
## Not run: data(sol274) # mpCtrl combining a hockey-stick HCR with 10% banking/borrowing ctrl <- mpCtrl( est = mseCtrl(method = perfect.sa), hcr = mseCtrl(method = hockeystick.hcr, args = list(metric = "ssb", trigger = 42000, output = "catch", target = 11000)), isys = mseCtrl(method = bank_borrow.is, args = list(rate = 0.10, healthy = 2, diff = 0.05))) run <- mp(om, control = ctrl, args = list(iy = 2021, fy = 2035)) plot(om, list(BaB = run)) # Inspect the TAC-setting steps from the tracking object items <- c("year", "hcr", "banking.isys", "borrowing.isys", "isys", "fwd") dcast( tracking(run)[metric %in% items[-1], .(data = mean(data)), by = .(year, metric)], year ~ metric, value.var = "data")[, ..items] ## End(Not run)## Not run: data(sol274) # mpCtrl combining a hockey-stick HCR with 10% banking/borrowing ctrl <- mpCtrl( est = mseCtrl(method = perfect.sa), hcr = mseCtrl(method = hockeystick.hcr, args = list(metric = "ssb", trigger = 42000, output = "catch", target = 11000)), isys = mseCtrl(method = bank_borrow.is, args = list(rate = 0.10, healthy = 2, diff = 0.05))) run <- mp(om, control = ctrl, args = list(iy = 2021, fy = 2035)) plot(om, list(BaB = run)) # Inspect the TAC-setting steps from the tracking object items <- c("year", "hcr", "banking.isys", "borrowing.isys", "isys", "fwd") dcast( tracking(run)[metric %in% items[-1], .(data = mean(data)), by = .(year, metric)], year ~ metric, value.var = "data")[, ..items] ## End(Not run)
Implements a buffer harvest control rule (HCR) that adjusts management output according to the recent value of a stock or index metric relative to a set of threshold reference points.
Tools for visualizing a buffer-based harvest control rule (HCR), including the HCR curve itself and optional shaded management-tier bands.
buffer.hcr( stk, ind, metric = "wmean", target = 1, width = 0.5, lim = max(target * 0.1, target - 2 * width), bufflow = max(lim * 1.5, target - width), buffupp = target + width, sloperatio = 0.15, initial, nyears = 4, dupp = NULL, dlow = NULL, all = TRUE, scale = FALSE, ..., args, tracking ) plot_buffer.hcr( args, obs = "missing", alpha = 0.3, labels = c(lim = "Limit", bufflow = "Lower~buffer", buffupp = "Upper~buffer", metric = metric, output = output), metric = args$metric, output = "multiplier", xlim = buffupp * 1.5, ylim = scale * 1.5 ) buffer_bands(x)buffer.hcr( stk, ind, metric = "wmean", target = 1, width = 0.5, lim = max(target * 0.1, target - 2 * width), bufflow = max(lim * 1.5, target - width), buffupp = target + width, sloperatio = 0.15, initial, nyears = 4, dupp = NULL, dlow = NULL, all = TRUE, scale = FALSE, ..., args, tracking ) plot_buffer.hcr( args, obs = "missing", alpha = 0.3, labels = c(lim = "Limit", bufflow = "Lower~buffer", buffupp = "Upper~buffer", metric = metric, output = output), metric = args$metric, output = "multiplier", xlim = buffupp * 1.5, ylim = scale * 1.5 ) buffer_bands(x)
stk |
A stock object, typically an |
ind |
An index object used when computing the selected metric. |
metric |
Character string giving the metric used for the x-axis and,
when |
target |
Numeric. Target value of the metric. |
width |
Numeric. Half-width of the buffer around |
lim |
Numeric. Lower limit reference point for the metric. |
bufflow |
Numeric. Lower bound of the buffer zone. |
buffupp |
Numeric. Upper bound of the buffer zone. |
sloperatio |
Numeric. Controls the slope of output increases above
|
initial |
Initial output value used when no previous output is available. |
nyears |
Number of recent years over which the metric is averaged. |
dupp |
Optional upper bound on proportional increase in output. |
dlow |
Optional lower bound on proportional decrease in output. |
all |
Logical. If |
scale |
Logical. If |
... |
Additional arguments passed to |
args |
A list of arguments defining the buffer HCR. Typically includes
values such as |
tracking |
A tracking object updated with metric, decision, tier, and output values. |
obs |
Optional observed values to overlay on the HCR plot. Can be:
|
alpha |
Numeric. Alpha transparency used for observed points and paths. |
labels |
Labels for plot annotations. A named vector or list with names
among |
output |
Character string giving the output used for the y-axis and,
when |
xlim |
Numeric. Maximum x-axis value for the HCR plot. By default set to
|
ylim |
Numeric. Maximum y-axis value for the HCR plot. |
x |
An object for which |
buffer.hcr() computes a piecewise decision multiplier from the selected
metric and applies it to the previous output value.
buffer_bands() creates shaded ggplot2 rectangles marking the critical,
recovery, buffer, and above-target zones implied by the same thresholds.
plot_buffer.hcr() draws the HCR curve implied by the buffer rule and can
optionally overlay observed values.
buffer_bands() returns ggplot2 layers that shade the management tiers
defined by the HCR thresholds.
The buffer harvest control rule is defined by threshold values that partition the x-axis metric into zones:
below lim: critical zone;
between lim and bufflow: recovery zone;
between bufflow and buffupp: buffer zone;
above buffupp: above-target zone.
plot_buffer.hcr() evaluates the implied HCR multiplier across a sequence of
metric values and draws the resulting curve, including annotations for the
key thresholds.
buffer_bands() constructs semi-transparent shaded rectangles spanning these
threshold intervals to support interpretation of HCR plots.
For buffer.hcr(), a list with components ctrl and tracking.
For buffer_bands(), a list of ggplot2 layers for shading HCR zones.
For plot_buffer.hcr(), a ggplot2 object.
For buffer_bands(), a list of ggplot2 components:
a ggplot2::geom_rect() layer that draws shaded tier bands;
a ggplot2::scale_fill_manual() layer that assigns colours to tiers.
plot_buffer.hcr() computes the HCR response curve from the supplied buffer
rule parameters and returns a ggplot object. The plot includes:
the HCR line;
vertical reference markers for lim, bufflow, and buffupp;
labels for the threshold points;
optional observed points or trajectories.
If obs is an FLStock object, the function extracts the chosen metric
and output values using FLCore::metrics() and overlays them on the HCR curve. If
there is a single iteration, both points and a path are added, and first/last
years are labelled.
If obs is numeric, a single red point is placed at the corresponding
location on the HCR curve.
buffer_bands() extracts lim, bufflow, and buffupp from args(x) and
defines four contiguous x-axis intervals. A fourth threshold,
target = 1.5 * buffupp, is used as the upper bound for the final tier.
The returned rectangles extend from y = 0 to y = Inf, so they occupy the
full vertical plotting range.
Thresholds are assumed to satisfy
0 <= lim <= bufflow <= buffupp.
buffer_bands() adds a fill scale and may therefore override an
existing fill scale in a ggplot object.
In plot_buffer.hcr(), default values such as xlim and ylim
depend on objects created after argument expansion and may rely on the
surrounding evaluation framework.
plot_buffer.hcr() currently uses internal helper functions such as
FLCore::spread(), args(), and FLCore::metrics(), and assumes these are available.
Iago Mosqueira, WMR; Richard Hillary, CSIRO
args(), FLCore::metrics(), ggplot2::geom_line(),
ggplot2::geom_rect(), ggplot2::scale_fill_manual()
## Not run: args <- list(lim = 0.4, bufflow = 1, buffupp = 2, sloperatio = 0.2) # Plot the HCR curve plot_buffer.hcr(args, labels = list(metric = "CPUE", output = "C~mult")) # Add buffer bands to a custom ggplot layers <- buffer_bands(hcr) p <- ggplot(dat, aes(x = biomass, y = harvest)) + geom_line() for (ly in layers) p <- p + ly p ## End(Not run)## Not run: args <- list(lim = 0.4, bufflow = 1, buffupp = 2, sloperatio = 0.2) # Plot the HCR curve plot_buffer.hcr(args, labels = list(metric = "CPUE", output = "C~mult")) # Add buffer bands to a custom ggplot layers <- buffer_bands(hcr) p <- ggplot(dat, aes(x = biomass, y = harvest)) + geom_line() for (ly in layers) p <- p + ly p ## End(Not run)
Implements a depletion-based harvest control rule (HCR) in which management output is scaled according to stock status relative to carrying capacity.
depletion.hcr( stk, ind, metric = "ssb", mult = 1, hrmsy, K, trigger = 0.4, lim = 0.1, min = 1e-05, initial, dupp = NULL, dlow = NULL, all = TRUE, ..., args, tracking )depletion.hcr( stk, ind, metric = "ssb", mult = 1, hrmsy, K, trigger = 0.4, lim = 0.1, min = 1e-05, initial, dupp = NULL, dlow = NULL, all = TRUE, ..., args, tracking )
stk |
A stock object, typically an |
ind |
An FLQuant object containing metrics to be used by the HCR. |
metric |
Character string specifying the metric to use in the HCR.
Passed to |
mult |
Numeric multiplier applied to the harvest rate after scaling by
the decision rule. Defaults to |
hrmsy |
Numeric target harvest rate associated with MSY conditions. |
K |
Numeric carrying capacity or proxy scaling constant used to convert the metric into a depletion ratio. |
trigger |
Numeric depletion threshold above which the HCR applies the
full harvest rate. Defaults to |
lim |
Numeric depletion limit reference point below which the HCR
applies the minimum multiplier. Defaults to |
min |
Numeric minimum multiplier applied when depletion falls below
|
initial |
Optional numeric initial output value used when interannual change constraints are applied in the first management year. |
dupp |
Optional numeric upper bound on proportional increase in output.
If not |
dlow |
Optional numeric lower bound on proportional decrease in output.
If not |
all |
Logical. If |
... |
Additional arguments intended for downstream metric calculation. |
args |
A list of auxiliary framework arguments unpacked by |
tracking |
A tracking object updated throughout the |
The rule uses the ratio of a selected stock metric to K as a depletion
indicator and adjusts the harvest rate relative to hrmsy depending on
whether the stock is above a trigger level, between a limit and trigger, or
below the limit.
The function first computes the selected metric from stk and ind using
mse::selectMetric(), restricted to the terminal data year dy. This metric is
tracked under "metric.hcr".
Stock status is then expressed as the depletion ratio:
The decision multiplier is calculated as a piecewise function:
if met / K >= trigger, the multiplier is 1;
if lim <= met / K < trigger, the multiplier increases linearly from
0 at lim to 1 at trigger;
if met / K < lim, the multiplier is set to min.
This multiplier is recorded in tracking under "decision.hcr".
The rule also classifies stock status into three tiers based on depletion:
Tier 1: below lim;
Tier 2: between lim and trigger;
Tier 3: at or above trigger.
Tier membership is stored under "tier.hcr".
A harvest-rate target is then computed as:
and management output is set as:
This provisional output is stored under "output.hcr" before optional upper
and lower change constraints are applied.
If dupp and/or dlow are supplied, the previous output value is recovered
either from initial in the first management year or from the tracking
object in later years. The provisional output is then capped and/or floored
according to the specified proportional limits.
Finally, missing values are replaced with zero and the result is converted to
an FLasher::fwdControl() object with one catch target per management year.
A named list with components:
ctrl: an fwdControl object specifying the catch target for the
management years in mys;
tracking: the updated tracking object containing recorded metric,
decision, tier, and output values.
If dupp is supplied, increases in output can be capped. If dlow is
supplied, decreases can be limited. When all = TRUE, these constraints are
always applied. When all = FALSE, they are only applied when the metric is
below the trigger, allowing unconstrained changes when stock status is at
or above the trigger level.
The function assumes spread(args[...]) creates ay, iy, dy,
mys, and it in scope.
Although ... is declared, it is not currently passed on in the call
to mse::selectMetric() in the implementation shown.
The previous output retrieval uses
tracking[metric == 'hcr' & year == ay, data], which assumes a specific
internal structure for tracking.
track(tracking, "decision.hcr", mys) stores the decision for all
management years, whereas track(tracking, "tier.hcr", ay) stores tier
at assessment year resolution.
Missing outputs are silently converted to zero.
Iago Mosqueira, WMR
buffer.hcr(), mse::selectMetric(), FLasher::fwdControl(),
Converts a fishing-mortality target set by an HCR into a relative effort
multiplier by scaling against a reference fishing mortality computed from
recent years. Passing a relative effort target to FLasher::fwd() rather
than an absolute F smooths the response to inter-annual variability in
fleet dynamics.
effort.is( stk, ctrl, nyears = args$nsqy, Fref = yearMeans(fbar(stk)[, ac(seq(dy - nyears + 1, dy))]), args, tracking )effort.is( stk, ctrl, nyears = args$nsqy, Fref = yearMeans(fbar(stk)[, ac(seq(dy - nyears + 1, dy))]), args, tracking )
stk |
An FLCore::FLStock object containing stock and fishery information. |
ctrl |
An FLasher::fwdControl object whose |
nyears |
Integer. Number of years over which the mean reference fishing
mortality is calculated. Defaults to |
Fref |
Numeric or FLCore::FLQuant. Reference fishing mortality
used as the denominator when computing the multiplier. Defaults to the
mean of |
args |
A list of management-cycle dimensionality arguments supplied
automatically by |
tracking |
An FLCore::FLQuant used to record intermediate values and decisions during MP evaluation, passed through unchanged by this method. |
The effort multiplier is defined as
where is the value in ctrl$value as set by the
HCR and is the mean FLCore::fbar() over the most
recent nyears years of data.
Setting ctrl$relYear tells FLasher::fwd() to express the effort target
relative to the effort observed in that reference year, effectively turning
the absolute F recommendation into a proportional change instruction.
An error is raised immediately if ctrl$quant is not one of "f",
"fbar", or "effort".
A list with two elements:
ctrlThe input FLasher::fwdControl object with value
replaced by the dimensionless effort multiplier and relYear set to
ctrl$year - data_lag so that FLasher::fwd() interprets the target
relative to the correct historical year.
trackingThe tracking object, returned unchanged.
Iago MOSQUEIRA [email protected]
mse::mp(), mse::split.is(), mse::mpCtrl(), mse::mseCtrl(),
FLCore::fbar()
## Not run: data(plesim) # mpCtrl combining a hockey-stick HCR (F target) with effort.is ctrl <- mpCtrl( est = mseCtrl(method = perfect.sa), hcr = mseCtrl(method = hockeystick.hcr, args = list(metric = "ssb", trigger = 45000, output = "fbar", target = 0.27)), isys = mseCtrl(method = effort.is, args = list(nyears = 3))) run <- mp(om, control = ctrl, args = list(iy = 2021, fy = 2035)) run_nois <- mp(om, control = ctrl[-3], args = list(iy = 2021, fy = 2035)) # Compare with and without the effort.is buffer effect plot(om, effort.is = run, no_is = run_nois) ## End(Not run)## Not run: data(plesim) # mpCtrl combining a hockey-stick HCR (F target) with effort.is ctrl <- mpCtrl( est = mseCtrl(method = perfect.sa), hcr = mseCtrl(method = hockeystick.hcr, args = list(metric = "ssb", trigger = 45000, output = "fbar", target = 0.27)), isys = mseCtrl(method = effort.is, args = list(nyears = 3))) run <- mp(om, control = ctrl, args = list(iy = 2021, fy = 2035)) run_nois <- mp(om, control = ctrl[-3], args = list(iy = 2021, fy = 2035)) # Compare with and without the effort.is buffer effect plot(om, effort.is = run, no_is = run_nois) ## End(Not run)
The inspect function turns the long tracking table into a year a metric summary
on which to track the inoputs and outputs of all steps inside a call to the mp
function.
inspect(tab, metrics = NULL, summary = medmad)inspect(tab, metrics = NULL, summary = medmad)
tab |
An |
metrics |
A character vector specifying the metrics to include in the output. If a single character value is given and it does not match excatly any of the contained metrics, it is used to subset using the datatable::%ilike% function. The special value |
summary |
A function (such as |
The function processes the table on the tracking slot by:
Arranging metrics based on the order in which they are produced inside mp().
Subsets metrics based on user input or predefined criteria like "decisions".
Aggregates the data column using the summary function provided.
Reshapes the processed data.table into a year-by-metrics format for easy reading.
The predefined metric order is that of the various steps inside mp(): "om", "obs", "est", "ind", "phcr", "hcr", "isys", "tm", "iem", "fb", "fwd". Extra tracks produced inside any module are placed before the one named after
the module that produced it.
A data.table where rows correspond to years and columns to selected metrics, with the tracking data aggregated using the specified summary function.
# Load example MP run data(mserun) # Inspect all metrics inspect(run) # Inspect with different summary function inspect(tracking(run), summary=mean) # Inspect metrics with "SB" or "sb" in their names inspect(tracking(run), metrics="SB") # Inspect specific metrics inspect(tracking(run), metrics=c("C.om", "C.obs", "C.est")) # Inspect only decision-related metrics from 'hcr' inspect(tracking(run), metrics="decisions")# Load example MP run data(mserun) # Inspect all metrics inspect(run) # Inspect with different summary function inspect(tracking(run), summary=mean) # Inspect metrics with "SB" or "sb" in their names inspect(tracking(run), metrics="SB") # Inspect specific metrics inspect(tracking(run), metrics=c("C.om", "C.obs", "C.est")) # Inspect only decision-related metrics from 'hcr' inspect(tracking(run), metrics="decisions")
Transforms a performance statistics data.table, or an FLmse/FLmses
object, into one or more FLCore::FLQuant objects organized by
management procedure, with statistics in the first (quant) dimension and
iterations preserved in the iter dimension.
performanceFLQuant(x) performanceFLQuants(x)performanceFLQuant(x) performanceFLQuants(x)
x |
An object of class mse::FLmse, mse::FLmses, or a
|
performanceFLQuants() always returns a named list (one FLQuant per MP).
performanceFLQuant() is a convenience wrapper that unwraps the list when
only one MP is present.
Conversion from data.table to FLQuant is delegated to
FLCore::as.FLQuant(), which expects the columns to map unambiguously onto
the standard FLQuant dimensions. The statistic column populates the
quant dimension and must therefore contain values meaningful as dimension
names.
When a biol column is present, data.table::setnames() renames it to
unit before passing to FLCore::as.FLQuant(), leaving the original table
unmodified.
An informative error is raised if x is a data.table that does not
contain all required columns (statistic, year, iter, data, mp).
performanceFLQuants()A named list of FLCore::FLQuant
objects, one per unique mp value. The first (quant) dimension is
named by statistic; year and iter dimensions correspond to
simulation years and iterations. When a biol column is present its
values populate the unit dimension.
performanceFLQuant()If the list contains exactly one element, that FLCore::FLQuant is returned directly; otherwise the full named list is returned.
performanceFLQuants(): Convenience wrapper returning a single
FLCore::FLQuant directly when only one management procedure is
present, or the full named list otherwise.
Iago MOSQUEIRA [email protected]
mse::performance(), mse::FLmse, mse::FLmses,
FLCore::FLQuant, FLCore::as.FLQuant(), readPerformance(),
writePerformance()
## Not run: # From an FLmse object flqs <- performanceFLQuants(mse_run) # From a pre-read data.table (multiple MPs) dat <- readPerformance() flqs <- performanceFLQuants(dat) flqs[["MP1"]]["SSB", , , , ,] # Convenience wrapper — returns FLQuant directly for a single MP flq <- performanceFLQuant(dat) ## End(Not run)## Not run: # From an FLmse object flqs <- performanceFLQuants(mse_run) # From a pre-read data.table (multiple MPs) dat <- readPerformance() flqs <- performanceFLQuants(dat) flqs[["MP1"]]["SSB", , , , ,] # Convenience wrapper — returns FLQuant directly for a single MP flq <- performanceFLQuant(dat) ## End(Not run)
Implements a Proportional-Integral-Derivative (PID) based harvest control rule for adjusting Total Allowable Catch (TAC) based on divergence from a reference point using PID control signals.
pid.hcr( stk, ind, ref, metric = ssb, initial, kp = 0, ki = 0, kd = 0, nyears = 5, dlow = NA, dupp = NA, args, tracking, ... )pid.hcr( stk, ind, ref, metric = ssb, initial, kp = 0, ki = 0, kd = 0, nyears = 5, dlow = NA, dupp = NA, args, tracking, ... )
stk |
|
ind |
|
ref |
Numeric. The reference value for the metric to determine divergence. |
metric |
Character or function. The metric applied to measure stock status. Default is |
Creates stochastic multiplicative deviation series for use in shortcut stock assessments, typically representing uncertainty or observation error applied to fishing mortality and spawning stock biomass metrics.
shortcut_devs( om, Fcv = 0.212, Fphi = 0.423, SSBcv = 0, SSBphi = 0, bias.correct = FALSE )shortcut_devs( om, Fcv = 0.212, Fphi = 0.423, SSBcv = 0, SSBphi = 0, bias.correct = FALSE )
om |
An operating model object used only to define dimensions for the
generated deviation series. The function uses |
Fcv |
Numeric. Standard deviation on the log scale for the fishing
mortality deviation process. Defaults to |
Fphi |
Numeric. Autocorrelation parameter for the fishing mortality
deviation process. Defaults to |
SSBcv |
Numeric. Standard deviation on the log scale for the spawning
stock biomass deviation process. Defaults to |
SSBphi |
Numeric. Autocorrelation parameter for the spawning stock
biomass deviation process. Currently not used in the implementation, which
fixes the |
bias.correct |
Logical. If |
The deviations are generated as lognormal autoregressive series and returned
as an FLQuants object with components for F and SSB.
The function generates deviations using FLCore::rlnormar1(), with:
n = dims(om)$iter iterations;
years = dimnames(om)$year;
meanlog = 0, so the process is centered on multiplicative value 1
on the log scale before optional bias correction;
separate variance and autocorrelation settings for F and SSB.
The returned object is suitable for direct use in shortcut.sa(), where the
deviations can be applied to derived stock metrics.
An FLQuants object with two elements:
F: a lognormal AR(1) deviation series for fishing mortality;
SSB: a lognormal deviation series for spawning stock biomass.
Although SSBphi is provided as an argument, the function currently hardcodes
rho=0 for the SSB process. This means the SSB deviations are independent
through time regardless of the value supplied to SSBphi.
Iago Mosqueira, WMR; Ernesto Jardim, IPMA
shortcut.sa(), FLCore::rlnormar1(), FLCore::FLQuants()
## Not run: # Generate default shortcut deviations devs <- shortcut_devs(om) # More variable and autocorrelated F deviations devs <- shortcut_devs(om, Fcv = 0.3, Fphi = 0.6) # With bias correction devs <- shortcut_devs(om, bias.correct = TRUE) ## End(Not run)## Not run: # Generate default shortcut deviations devs <- shortcut_devs(om) # More variable and autocorrelated F deviations devs <- shortcut_devs(om, Fcv = 0.3, Fphi = 0.6) # With bias correction devs <- shortcut_devs(om, bias.correct = TRUE) ## End(Not run)
Performs a simplified or "shortcut" stock assessment by truncating an operating model stock object to the current data year, computing a selected stock metric, applying stochastic deviations, and returning the resulting indicator together with the truncated stock and updated tracking object.
shortcut.sa( stk, idx, metric = "ssb", SSBdevs = met %=% 1, devs = SSBdevs, args, tracking, ... )shortcut.sa( stk, idx, metric = "ssb", SSBdevs = met %=% 1, devs = SSBdevs, args, tracking, ... )
stk |
An |
idx |
An index object. Currently included for interface compatibility with other assessment functions, but not used directly inside this function. |
metric |
A character string naming the function used to compute the
assessment metric from |
SSBdevs |
An object containing deviations to apply to the computed
metric. Defaults to |
devs |
Deprecated alias or shorthand for |
args |
A list-like object containing dimensions and assessment settings
needed by |
tracking |
A tracking object updated in-place through to record convergence of the shortcut assessment. |
... |
Additional arguments passed to the metric function named in
|
This function is intended for use inside management procedure workflows where a full assessment model is not run, but an index or assessment quantity is approximated from the operating model using a direct transformation of stock state and observation-error-like deviations.
The function proceeds as follows:
values in args are unpacked using FLCore::spread();
the stock object is truncated to end=dy using window();
the requested metric is computed by calling the function named in
metric on stk;
the result is collapsed across units using FLCore::unitSums();
stochastic deviations are applied over the period from y0 to dy;
the resulting quantity is wrapped in an FLCore::FLQuants() object and named
with the selected metric;
convergence is recorded in tracking by setting
"conv.est" to 1 for year ay and biological unit stock.
A named list with components:
stk: the stock object truncated to the terminal data year dy;
ind: an FLQuants object containing the derived indicator series,
named according to metric;
tracking: the updated tracking object with convergence information
recorded.
the function named in metric exists and accepts stk as its first
argument;
devs or SSBdevs are dimensionally compatible with the metric
computed from stk;
idx is currently unused but may be retained for consistency with
other assessment-method signatures.
devs is currently used to build the indicator, even though
SSBdevs is the more explicit argument name.
Iago Mosqueira, WMR; Ernesto Jardim, IPMA
shortcut_devs(), FLCore::ssb()
## Not run: # dataset contains both OM (FLom) and OEM (FLoem) data(plesim) # Create shortcut deviances for F and SSB devs <- shortcut_devs(om, Fcv = 0.3, Fphi = 0.6) # Set control: sa and hcr control <- mpCtrl(list( est = mseCtrl(method=shortcut.sa, args=list(devs=devs$SSB)), hcr = mseCtrl(method=hockeystick.hcr, args=list(lim=0, trigger=14000, target=0.18)))) # Runs mp tes <- mp(om, ctrl=control, args=list(iy=2021, fy=2026)) ## End(Not run)## Not run: # dataset contains both OM (FLom) and OEM (FLoem) data(plesim) # Create shortcut deviances for F and SSB devs <- shortcut_devs(om, Fcv = 0.3, Fphi = 0.6) # Set control: sa and hcr control <- mpCtrl(list( est = mseCtrl(method=shortcut.sa, args=list(devs=devs$SSB)), hcr = mseCtrl(method=hockeystick.hcr, args=list(lim=0, trigger=14000, target=0.18)))) # Runs mp tes <- mp(om, ctrl=control, args=list(iy=2021, fy=2026)) ## End(Not run)
Transforms performance metrics from FLmse or FLmsea objects, stored as a
data.table into an FLQuant pr FLQuants object.
trackingFLQuant(x) trackingFLQuants(x)trackingFLQuant(x) trackingFLQuants(x)
x |
An object of class |
If x is of class FLmse or FLmses, the performance slot is extracted
automatically. The data.table must contain columns: statistic, year, iter,
data, and mp. Optionally, a biol column can be present, as in the
performance table obtained from callin mp() on an FLombf OM. Values for each
biol will be separated using the 'unit' dimension.
The first (quant) dimension of the FLQuant or FLQuants contain the
statistics, named as in the statistic column of the performance table.
When results from multiple management procedures are present, the output is an
FLQuants list of FLQuant objects, one per mp.
If a single management procedure (mp) is present, returns a single FLQuant
object. If multiple management procedures are present, returns a list of
FLQuant objects, one per mp. When biol column is present, it is renamed
to unit in the resulting FLQuant or FLQuants.
mse::performance(), mse::FLmse, FLmses
## Not run: # Using a data.table directly perf_dt <- data.table( statistic = rep("SSB", 4), year = rep(2025:2026, 2), iter = rep(1:2, each = 2), data = runif(4, 1000, 3000), mp = "MP1" ) quant <- trackingFLQuant(perf_dt) quants <- trackingFLQuants(perf_dt) ## End(Not run)## Not run: # Using a data.table directly perf_dt <- data.table( statistic = rep("SSB", 4), year = rep(2025:2026, 2), iter = rep(1:2, each = 2), data = runif(4, 1000, 3000), mp = "MP1" ) quant <- trackingFLQuant(perf_dt) quants <- trackingFLQuants(perf_dt) ## End(Not run)
A family of utilities for persisting, retrieving, labelling, summarizing,
and reshaping performance statistics tables produced by
mse::performance().
writePerformance(dat, file = "model/performance.dat.gz", overwrite = FALSE) readPerformance(file = "model/performance.dat.gz") summaryPerformance(file = "model/performance.dat.gz") labelPerformance(dat, labels = NULL) setLabelPerformance(file = "model/performance.dat.gz", labels) periodsPerformance(x, periods) extractPerformance(dat, mp) getOMPerformance(path, pattern = "*.rds", fy, ...) getMSEPerformance(path, pattern = "*.rds")writePerformance(dat, file = "model/performance.dat.gz", overwrite = FALSE) readPerformance(file = "model/performance.dat.gz") summaryPerformance(file = "model/performance.dat.gz") labelPerformance(dat, labels = NULL) setLabelPerformance(file = "model/performance.dat.gz", labels) periodsPerformance(x, periods) extractPerformance(dat, mp) getOMPerformance(path, pattern = "*.rds", fy, ...) getMSEPerformance(path, pattern = "*.rds")
dat |
A |
file |
A character string giving the path to the performance table
file. Defaults to |
overwrite |
Logical. If |
labels |
The labelling specification used by
|
x |
A |
periods |
A vector or list whose elements define the years belonging to
each period (used by |
mp |
A character string used by |
path |
A character string giving the directory containing serialized
files, used by |
pattern |
A character string passed to |
fy |
The final year to which each operating model is trimmed with
|
... |
Additional arguments forwarded to |
writePerformance()Serializes a table to disk, merging with any existing file.
readPerformance()Reads a stored table and restores column classes, key, and factor levels.
summaryPerformance()Prints a compact console summary.
labelPerformance()Adds or replaces the label column.
setLabelPerformance()Reads, re-labels, and overwrites a stored table.
periodsPerformance()Aggregates annual statistics into user-defined periods.
extractPerformance()Subsets to selected MPs together with their OM baseline rows.
getOMPerformance()Batch-reads OM files and returns a combined performance table.
getMSEPerformance()Batch-reads MSE result files and returns a combined performance table.
writePerformance
Before writing, all columns are coerced to character and then year and
data are restored to numeric to ensure a consistent serialization format.
Optional columns are normalized: if neither type nor run is present,
empty character columns for type, run, and mp are added; if mp is
absent but type and run are present, mp is constructed by pasting
om, type, and run with "_"; if label is absent it is set to mp
when an MP is present, otherwise to om. Column order is standardized to
om, type, run, mp, biol, statistic, name, desc, year,
iter, data before writing.
readPerformance
Reading is performed with data.table::fread() with explicit colClasses
to avoid ambiguous type inference (e.g. when iter contains non-numeric
labels or mp is an empty string). The key set by data.table::setkey()
enables efficient subsetting and is assumed by several downstream functions.
The label column is optional; when absent it is not created — use
labelPerformance() to add it after reading.
periodsPerformance
periods is coerced to a list internally. The compact year label uses only
the last two digits of the final year (2026:2035 → "2026-35"). Missing
values in data are silently ignored (na.rm = TRUE). When x contains a
label column the grouping includes it; otherwise grouping is by type,
mp, statistic, name, desc, and iter.
extractPerformance
Operating model baseline rows are identified by an empty string in mp.
Because matching uses %like%, use anchored patterns (e.g. "^HCR1$")
when MP names share substrings. Explicit support for a vector of distinct
MP names is planned.
getOMPerformance
Each .rds file is expected to contain a list-like object with an $om
component compatible with FLCore::window() and mse::performance().
Warnings from mse::performance() are suppressed with
base::suppressWarnings(); re-run individual files interactively if
unexpected results appear.
getMSEPerformance
If a file's deserialized object already inherits from data.table it is
returned directly, allowing pre-computed performance summaries to be mixed
with raw MSE objects. fill = TRUE in data.table::rbindlist() tolerates
minor column-structure differences across files.
writePerformance(), setLabelPerformance()
Invisibly TRUE.
readPerformance()A data.table keyed by om, type, run,
biol, mp, statistic, and year, with grouping columns as
factors and column order fixed as om, type, run, mp, biol,
statistic, name, desc, year, iter, data.
summaryPerformance()Invisibly TRUE (called for its printed
side-effect).
labelPerformance()A copy of dat with a label factor column
added or replaced; OM-only rows appear first in the factor levels.
periodsPerformance()A data.table with one row per grouping
combination and period, containing period, year (compact range
string), data (period mean), and the inherited grouping columns.
extractPerformance()A subset of dat containing the matched MP
rows and their corresponding OM baseline rows (mp == "").
getOMPerformance(), getMSEPerformance()
A data.table produced
by row-binding the performance results from all matching files.
readPerformance(): Read a performance statistics table from disk,
restoring column classes, data.table key, column order, and factor levels.
summaryPerformance(): Print a compact console summary of the number
of operating models, MP types, and management procedures, together with
per-group year ranges and iteration counts.
labelPerformance(): Add or replace the label factor column
in a performance statistics table; OM-only rows appear first in the factor
levels.
setLabelPerformance(): Convenience wrapper that reads a stored
performance table, updates its label column via
labelPerformance(), and writes the result back, replacing the previous
contents.
periodsPerformance(): Collapse annual performance statistics into
broader user-defined periods by computing the mean of data over
the years belonging to each period.
extractPerformance(): Subset a performance table to the rows
belonging to management procedures matching a pattern, together with their
corresponding OM baseline rows (mp == "").
getOMPerformance(): Batch-read serialized OM files, trim each to
fy with FLCore::window(), compute mse::performance(), and
row-bind the results into a single table.
getMSEPerformance(): Batch-read serialized MSE result files or
pre-computed performance data.table files and row-bind them into a
single table.
Iago MOSQUEIRA [email protected]
mse::performance(), mse::FLmse, mse::FLmses,
FLCore::window(), performanceFLQuants()
## Not run: ## writePerformance / readPerformance writePerformance(perf_dat) dat <- readPerformance() dat <- readPerformance("results/performance.dat.gz") ## summaryPerformance summaryPerformance() summaryPerformance(dat) ## labelPerformance dat <- labelPerformance(dat) dat <- labelPerformance(dat, labels = "numeric") dat <- labelPerformance(dat, labels = list( hcr01 = "Conservative HCR", hcr02 = "Moderate HCR")) ## setLabelPerformance setLabelPerformance(labels = "numeric") setLabelPerformance("results/performance.dat.gz", labels = list(hcr01 = "Low F", hcr02 = "High F")) ## periodsPerformance res <- periodsPerformance(dat, periods = list( short = 2021:2025, medium = 2026:2035, long = 2036:2050)) ## extractPerformance sub <- extractPerformance(dat, "HCR1") sub <- extractPerformance(dat, "^HCR1$") ## getOMPerformance dat <- getOMPerformance("om", fy = 2025) dat <- getOMPerformance("om", fy = 2025, probs = c(0.1, 0.5, 0.9)) ## getMSEPerformance dat <- getMSEPerformance("mse") dat <- getMSEPerformance("mse", pattern = "scenario_.*\\.rds$") ## End(Not run)## Not run: ## writePerformance / readPerformance writePerformance(perf_dat) dat <- readPerformance() dat <- readPerformance("results/performance.dat.gz") ## summaryPerformance summaryPerformance() summaryPerformance(dat) ## labelPerformance dat <- labelPerformance(dat) dat <- labelPerformance(dat, labels = "numeric") dat <- labelPerformance(dat, labels = list( hcr01 = "Conservative HCR", hcr02 = "Moderate HCR")) ## setLabelPerformance setLabelPerformance(labels = "numeric") setLabelPerformance("results/performance.dat.gz", labels = list(hcr01 = "Low F", hcr02 = "High F")) ## periodsPerformance res <- periodsPerformance(dat, periods = list( short = 2021:2025, medium = 2026:2035, long = 2036:2050)) ## extractPerformance sub <- extractPerformance(dat, "HCR1") sub <- extractPerformance(dat, "^HCR1$") ## getOMPerformance dat <- getOMPerformance("om", fy = 2025) dat <- getOMPerformance("om", fy = 2025, probs = c(0.1, 0.5, 0.9)) ## getMSEPerformance dat <- getMSEPerformance("mse") dat <- getMSEPerformance("mse", pattern = "scenario_.*\\.rds$") ## End(Not run)