Nothing
# Class specification and constructors for the simulation class
# Copyright 2012 Finlay Scott and Julia Blanchard.
# Copyright 2018 Gustav Delius and Richard Southwell.
# Distributed under the GPL 3 or later
# Maintainer: Gustav Delius, University of York, <gustav.delius@york.ac.uk>
# Validity check
valid_MizerSim <- function(object) {
errors <- character()
validObject(object@params)
# array dimensions
if (length(dim(object@n)) != 3) {
msg <- "n slot must have three dimensions"
errors <- c(errors, msg)
}
if (length(dim(object@effort)) != 2) {
msg <- "effort slot must have two dimensions"
errors <- c(errors, msg)
}
if (length(dim(object@n_pp)) != 2) {
msg <- "n_pp slot must have two dimensions"
errors <- c(errors, msg)
}
# Check time dimension is good - size, dim name, and names
if (!all(c(dim(object@n)[[1]],
dim(object@n_pp)[[1]],
dim(object@n_other)[[1]]) == dim(object@effort)[[1]])) {
msg <- "First dimension of effort, n, n_pp and n_other slots must be the same length."
errors <- c(errors, msg)
}
if (!all(c(names(dimnames(object@n))[[1]],
names(dimnames(object@n_pp))[[1]],
names(dimnames(object@n_other))[[1]],
names(dimnames(object@effort))[[1]]) == "time")) {
msg <- "First dimension of effort, n, n_pp and n_other slots must be called 'time'."
errors <- c(errors, msg)
}
# species dimension of n
if (dim(object@n)[[2]] != dim(object@params@psi)[[1]]) {
msg <- "Second dimension of n slot must have same length as the species names in the params slot"
errors <- c(errors, msg)
}
if (names(dimnames(object@n))[[2]] != "sp") {
msg <- "Second dimension of n slot must be called 'sp'"
errors <- c(errors, msg)
}
if (!all(names(dimnames(object@n))[[2]] ==
names(dimnames(object@params@psi))[[1]])) {
msg <- "Second dimension of n slot must have same species names as in the params slot"
errors <- c(errors, msg)
}
# w dimension of n
if (dim(object@n)[[3]] != length(object@params@w)) {
msg <- "Third dimension of n slot must have same length as w in the params slot"
errors <- c(errors, msg)
}
if (names(dimnames(object@n))[[3]] != "w") {
msg <- "Third dimension of n slot must be called 'w'"
errors <- c(errors, msg)
}
if (!all(names(dimnames(object@n))[[3]] ==
names(dimnames(object@params@psi))[[2]])) {
msg <- "Third dimension of n slot must have same size names as in the params slot"
errors <- c(errors, msg)
}
# w dimension of n_pp
if (dim(object@n_pp)[[2]] != length(object@params@w_full)) {
msg <- "Second dimension of n_pp slot must have same length as w_full in the params slot"
errors <- c(errors, msg)
}
if (names(dimnames(object@n_pp))[[2]] != "w") {
msg <- "Second dimension of n_pp slot must be called 'w'"
errors <- c(errors, msg)
}
if (!all(dimnames(object@n_pp)$w == names(object@params@rr_pp))) {
msg <- "Second dimension of n_pp slot must have same size names as rr_pp in the params slot"
errors <- c(errors, msg)
}
# component dimension of n_other
if (dim(object@n_other)[[2]] != length(object@params@other_dynamics)) {
msg <- "Second dimension of n_other slot must have same length as other_dynamics in the params slot"
errors <- c(errors, msg)
}
if (names(dimnames(object@n_other))[[2]] != "component") {
msg <- "Second dimension of n_other slot must be called 'component'"
errors <- c(errors, msg)
}
if (!all(dimnames(object@n_other)$component == names(object@params@other_dynamics))) {
msg <- "Second dimension of n_other slot must have same component names as other_dynamics in the params slot"
errors <- c(errors, msg)
}
# gear dimension of effort
if (dim(object@effort)[[2]] != dim(object@params@catchability)[[1]]) {
msg <- "Second dimension of effort slot must have same number of gears as in the params slot"
errors <- c(errors, msg)
}
if (names(dimnames(object@effort))[[2]] != "gear") {
msg <- "Second dimension of effort slot must be called 'gear'"
errors <- c(errors, msg)
}
if (!all(names(dimnames(object@effort))[[2]] ==
names(dimnames(object@params@catchability)[[1]]))) {
msg <- "Second dimension of effort slot must have same gear names as in the params slot."
errors <- c(errors, msg)
}
if (length(errors) == 0) TRUE else errors
}
# Soundtrack: Yob - Quantum Mystic
#### Class definition ####
#' A class to hold the results of a simulation
#'
#' A class that holds the results of projecting a \linkS4class{MizerParams}
#' object through time using [project()].
#'
#' A new `MizerSim` object can be created with the [MizerSim()]
#' constructor, but you will never have to do that because the object is
#' created automatically by [project()] when needed.
#'
#' As a user you should never have to access the slots of a MizerSim object
#' directly. Instead there are a range of functions to extract the information.
#' [N()] and [NResource()] return arrays with the saved abundances of
#' the species and the resource population at size respectively. [getEffort()]
#' returns the fishing effort of each gear through time.
#' [getTimes()] returns the vector of times at which simulation results
#' were stored and [idxFinalT()] returns the index with which to access
#' specifically the value at the final time in the arrays returned by the other
#' functions. [getParams()] extracts the ecosystem state as a `MizerParams`
#' object with initial abundances set to values from the simulation; [finalParams()]
#' and [initialParams()] are convenient shorthands for the final and initial
#' time steps. There are also several
#' [summary_functions] and [plotting_functions]
#' available to explore the contents of a `MizerSim` object.
#'
#' The arrays all have named dimensions. The names of the `time` dimension
#' denote the time in years. The names of the `w` dimension are weights in grams
#' rounded to three significant figures. The names of the `sp` dimension are the
#' same as the species name in the order specified in the species_params data
#' frame. The names of the `gear` dimension are the names of the gears, in the
#' same order as specified when setting up the `MizerParams` object.
#'
#' Extensions of mizer can use the `n_other` slot to store the abundances of
#' other ecosystem components and these extensions should provide their own
#' functions for accessing that information.
#'
#' The `MizerSim` class has changed since previous versions of mizer. To use
#' a `MizerSim` object created by a previous version, you need to upgrade it
#' with [validSim()].
#'
#' @slot params An object of type \linkS4class{MizerParams}.
#' If this params object uses extensions, the `MizerSim` object uses the same
#' extension chain, which can be inspected with
#' `getMetadata(params)$extensions`; `MizerSim` has no separate extension
#' record.
#' @slot n Three-dimensional array (time x species x size) that stores the
#' projected community number densities.
#' @slot n_pp An array (time x size) that stores the projected resource number
#' densities.
#' @slot n_other A list array (time x component) that stores the projected
#' values for other ecosystem components.
#' @slot effort An array (time x gear) that stores the fishing effort by time
#' and gear.
#' @slot sim_params A named list of the parameters passed to [project()] or
#' [projectUntilSettled()] to produce this simulation, such as `method` and `dt`.
#'
#' @name MizerSim-class
#' @rdname MizerSim-class
NULL
#' @export
`@.MizerSim` <- function(object, name) {
name_str <- as.character(substitute(name))
if (isS4(object)) {
object <- upgrade_s4_to_s3(object)
}
object[[name_str]]
}
#' @export
`@<-.MizerSim` <- function(object, name, value) {
name_str <- as.character(substitute(name))
if (isS4(object)) {
object <- upgrade_s4_to_s3(object)
}
object[[name_str]] <- value
object
}
#' Constructor for the `MizerSim` class
#'
#' A constructor for the `MizerSim` class. This is used by
#' [project()] to create `MizerSim` objects of the right
#' dimensions. It is not necessary for users to use this constructor.
#'
#' @param params a \linkS4class{MizerParams} object
#' @param t_dimnames Numeric vector that is used for the time dimensions of the
#' slots. Default = NA.
#' @param t_max The maximum time step of the simulation. Only used if t_dimnames
#' = NA. Default value = 100.
#' @param t_save How often should the results of the simulation be stored. Only
#' used if t_dimnames = NA. Default value = 1.
#'
#' @return An object of type \linkS4class{MizerSim}
#' @export
MizerSim <- function(params, t_dimnames = NA, t_max = 100, t_save = 1) {
# If the dimnames for the time dimension not passed in, calculate them
# from t_max and t_save
if (any(is.na(t_dimnames))) {
t_dimnames <- seq(from = 0, to = t_max, by = t_save)
}
if (!is.numeric(t_dimnames)) {
stop("The t_dimnames argument must be numeric.")
}
if (is.unsorted(t_dimnames)) {
stop("The t_dimnames argument should be increasing.")
}
no_sp <- nrow(params@species_params)
species_names <- dimnames(params@psi)$sp
no_w <- length(params@w)
w_names <- dimnames(params@psi)$w
no_t <- length(t_dimnames)
array_n <- array(NA, dim = c(no_t, no_sp, no_w),
dimnames = list(time = t_dimnames,
sp = species_names, w = w_names))
no_gears <- dim(params@selectivity)[1]
gear_names <- dimnames(params@selectivity)$gear
array_effort <- array(NA, dim = c(no_t, no_gears),
dimnames = list(time = t_dimnames,
gear = gear_names))
no_w_full <- length(params@w_full)
w_full_names <- names(params@rr_pp)
array_n_pp <- array(NA, dim = c(no_t, no_w_full),
dimnames = list(time = t_dimnames,
w = w_full_names))
component_names <- names(params@other_dynamics)
no_components <- length(component_names)
list_n_other <- rep(list(NA), no_t * no_components)
dim(list_n_other) <- c(no_t, no_components)
dimnames(list_n_other) <- list(time = t_dimnames,
component = component_names)
sim <- structure(
list(
params = params,
n = array_n,
n_pp = array_n_pp,
n_other = list_n_other,
effort = array_effort,
sim_params = list()
),
class = "MizerSim"
)
coerceToExtensionClass(sim)
}
#' A MizerSim holding only the state stored in a MizerParams
#'
#' Wraps the single state in a `MizerParams` object into a `MizerSim` with one
#' time step, so that a function written against a `MizerSim` can be applied to
#' it without projecting.
#'
#' This exists for analyses such as [scanModel()] that measure a quantity with a
#' user-supplied function of a `MizerSim`. When the model has settled on a fixed
#' point there is nothing to project: the state does not change, so a snapshot
#' of it carries all the information a longer run would. Every slot that a
#' summary function might read has to be filled, because [MizerSim()] initialises
#' them all to `NA` and, for example, `getYield()` reads `sim@effort` and would
#' otherwise return `NA` without complaint.
#'
#' Note that the result has a single time step, so a function that needs more
#' than one — anything taking a difference through time — cannot be applied to
#' it.
#'
#' @param params A MizerParams object.
#' @param t The time to label the single time step with.
#' @return A MizerSim object with one time step holding the initial state of
#' `params`.
#' @keywords internal
params_as_sim <- function(params, t = 0) {
sim <- MizerSim(params, t_dimnames = t)
sim@n[1, , ] <- params@initial_n
sim@n_pp[1, ] <- params@initial_n_pp
if (length(params@initial_n_other) > 0) {
sim@n_other[1, ] <- params@initial_n_other
}
sim@effort[1, ] <- params@initial_effort
sim
}
#' Validate MizerSim object and upgrade if necessary
#'
#' Checks that the given MizerSim object is valid and upgrades it if necessary.
#' It also validates the embedded [MizerParams-class()] object with
#' [validParams()]. If any entries of the consumer abundance array `sim@n` are
#' non-finite, a warning is issued and the simulation is truncated at the last
#' time step where `sim@n` is still finite.
#'
#' Occasionally, during the development of new features for mizer, the
#' \linkS4class{MizerSim} class or the \linkS4class{MizerParams} class gains
#' extra slots. MizerSim objects created in older versions of mizer are then no
#' longer valid in the new version because of the missing slots. You need to
#' upgrade them with this function.
#'
#' This function adds the missing slots and fills them with default values. It
#' also calls [validParams()] to upgrade the MizerParams object inside the
#' MizerSim object. Any object from version 0.4 onwards can be upgraded.
#'
#' @inheritSection validParams Backwards compatibility
#'
#' @param sim The MizerSim object to validate
#' @return A valid MizerSim object
#' @export
validSim <- function(sim) {
if (isS4(sim)) {
sim <- upgrade_s4_to_s3(sim)
if (isS4(sim$params)) {
sim$params <- upgrade_s4_to_s3(sim$params)
}
}
UseMethod("validSim")
}
#' @export
validSim.MizerSim <- function(sim) {
if (isS4(sim)) {
sim <- upgrade_s4_to_s3(sim)
if (isS4(sim$params)) {
sim$params <- upgrade_s4_to_s3(sim$params)
}
}
assert_that(inherits(sim, "MizerSim"))
if (needs_upgrading(sim)) {
sim <- suppressWarnings(upgradeSim(sim))
warning("Your MizerSim object was created with an earlier version of mizer. You can upgrade it with `sim <- validSim(sim)` where you should replace `sim` by the name of the variable that holds your MizerSim object.")
} else {
# Always validate the params object, even if no upgrading was required.
sim@params <- validParams(sim@params)
}
if (!all(is.finite(sim@n))) {
inf_idx <- which(!is.finite(sim@n), arr.ind = TRUE)
max_t_idx <- min(inf_idx[, 1]) - 1
max_t <- as.numeric(dimnames(sim@n)$time[max_t_idx])
warning("The simulation failed to work beyond time = ", max_t)
slice <- get_sim_rate_slice(sim, max_t_idx)
rates <- getRates(sim@params,
n = slice$n,
n_pp = slice$n_pp,
n_other = slice$n_other,
effort = slice$effort,
t = slice$t)
inf_rates <- sapply(rates, function(x) any(!is.finite(x)))
if (any(inf_rates)) {
warning("The following rates failed to be finite: ",
paste(names(rates)[inf_rates], collapse = ", "), ".")
}
sim <- truncateSim(sim, end_time = max_t)
}
sim <- coerceToExtensionClass(sim)
validObject(sim)
sim
}
truncateSim <- function(sim, end_time) {
assert_that(is(sim, "MizerSim"))
times <- dimnames(sim@n)$time
if (!(end_time %in% times)) {
stop("end_time = ", end_time, " is not a valid time contained in the simulation.")
}
t_idx <- match(end_time, times)
sim@n <- sim@n[1:t_idx, , , drop = FALSE]
sim@n_pp <- sim@n_pp[1:t_idx, , drop = FALSE]
sim@n_other <- sim@n_other[1:t_idx, , drop = FALSE]
sim@effort <- sim@effort[1:t_idx, , drop = FALSE]
sim
}
#' Time series of size spectra
#'
#' Fetch the simulation results for the size spectra over time.
#'
#' @param sim A MizerSim object
#' @return For `N()`: An `ArrayTimeBySpeciesBySize` object (time x species x
#' size) with the number density of consumers.
#' @export
#' @examples
#' str(N(NS_sim))
N <- function(sim) {
UseMethod("N")
}
#' @export
N.MizerSim <- function(sim) {
assert_that(is(sim, "MizerSim"))
ArrayTimeBySpeciesBySize(sim@n, value_name = "Number density",
units = "1/g", type = "density",
params = sim@params)
}
#' @rdname N
#' @return For `NResource()`: An array (time x size) with the number density of resource
#' @export
#' @examples
#' str(NResource(NS_sim))
NResource <- function(sim) {
UseMethod("NResource")
}
#' @export
NResource.MizerSim <- function(sim) {
assert_that(is(sim, "MizerSim"))
ArrayTimeByResourceBySize(sim@n_pp, value_name = "Number density",
units = "1/g", type = "density",
params = sim@params)
}
#' Size spectra at end of simulation
#'
#' @param sim A MizerSim object
#' @return For `finalN()`: An `ArraySpeciesBySize` object (species x size)
#' holding the consumer number densities at the end of the simulation
#' @export
#' @examples
#' str(finalN(NS_sim))
#'
#' # This could also be obtained using `N()` and `idxFinalT()`
#' identical(N(NS_sim)[idxFinalT(NS_sim), , ], finalN(NS_sim))
finalN <- function(sim) {
UseMethod("finalN")
}
#' @export
finalN.MizerSim <- function(sim) {
assert_that(is(sim, "MizerSim"))
n <- sim@params@initial_n # Needed to get the right dimnames
n[] <- sim@n[dim(sim@n)[[1]], , ]
ArraySpeciesBySize(n, value_name = "Number density",
type = "density", params = sim@params)
}
#' @rdname finalN
#' @return For `finalNResource()`: A vector holding the resource number
#' densities at the end of the simulation for all size classes
#' @export
#' @examples
#' str(finalNResource(NS_sim))
finalNResource <- function(sim) {
UseMethod("finalNResource")
}
#' @export
finalNResource.MizerSim <- function(sim) {
assert_that(is(sim, "MizerSim"))
ArrayResourceBySize(sim@n_pp[dim(sim@n_pp)[[1]], ],
value_name = "Number density", units = "1/g",
type = "density", params = sim@params)
}
#' @rdname finalN
#' @return For `idxFinalT()`: An integer giving the index for extracting the
#' results for the final time step
#' @export
#' @examples
#' idx <- idxFinalT(NS_sim)
#' idx
#' # This coincides with
#' length(getTimes(NS_sim))
#' # and corresponds to the final time
#' getTimes(NS_sim)[idx]
#' # We can use this index to extract the result at the final time
#' identical(N(NS_sim)[idx, , ], finalN(NS_sim))
#' identical(NResource(NS_sim)[idx, ], finalNResource(NS_sim))
idxFinalT <- function(sim) {
UseMethod("idxFinalT")
}
#' @export
idxFinalT.MizerSim <- function(sim) {
assert_that(is(sim, "MizerSim"))
dim(sim@n_pp)[[1]]
}
#' Times for which simulation results are available
#'
#' @param sim A MizerSim object
#' @return A numeric vector of the times (in years) at which simulation results
#' have been stored in the MizerSim object.
#' @export
#' @examples
#' getTimes(NS_sim)
getTimes <- function(sim) {
UseMethod("getTimes")
}
#' @export
getTimes.MizerSim <- function(sim) {
assert_that(is(sim, "MizerSim"))
as.numeric(dimnames(sim@n)$time)
}
#' Fishing effort used in simulation
#'
#' Note that the array returned may not be exactly the same as the `effort`
#' argument that was passed in to `project()`. This is because only the saved
#' effort is stored (the frequency of saving is determined by the argument
#' `t_save`).
#'
#' @param sim A MizerSim object
#' @return An array (time x gear) that contains the fishing effort by time and
#' gear.
#' @export
#' @examples
#' str(getEffort(NS_sim))
getEffort <- function(sim) {
UseMethod("getEffort")
}
#' @export
getEffort.MizerSim <- function(sim) {
assert_that(is(sim, "MizerSim"))
sim@effort
}
#' Extract the model state from a simulation
#'
#' A `MizerParams` object describes the state of the ecosystem: its species
#' parameters, size grid, rate functions, *and* the current abundances stored in
#' the `initial_n`, `initial_n_pp`, `initial_n_other`, and `initial_effort`
#' slots. These functions extract that state from a `MizerSim` object.
#'
#' `getParams()` returns the state averaged over a chosen `time_range`, or at a
#' single time point. When no `time_range` is given, the state at the final time
#' step is returned.
#'
#' `initialParams()` returns the state at the initial time of the simulation,
#' i.e., the `MizerParams` object that the simulation started from.
#'
#' `finalParams()` returns the state at the *last* saved time step. It is a
#' convenience wrapper around `getParams()` with no `time_range` argument.
#'
#' The abundances set by `getParams()` are averages over the selected time
#' range. By default this is an arithmetic mean; set `geometric_mean = TRUE` to
#' use a geometric mean instead (this does not affect the effort or other
#' components, which are always averaged arithmetically).
#'
#' @param sim A `MizerSim` object.
#' @param time_range The time range to average the abundances over. Can be a
#' vector of values, a vector of min and max time, or a single value. Only the
#' range of times is relevant, i.e., all times between the smallest and
#' largest will be selected. Default is the final time step.
#' @param geometric_mean `r lifecycle::badge("experimental")`
#' If `TRUE`, the average of the abundances over the time range is a geometric
#' mean instead of the default arithmetic mean. This does not affect the
#' average of the effort or of other components, which is always arithmetic.
#' @return A `MizerParams` object with `initial_n`, `initial_n_pp`,
#' `initial_n_other`, and `initial_effort` set to the values from the selected
#' time of the simulation.
#' @export
#' @examples
#' sim <- project(NS_params, t_max = 20, effort = 0.5)
#' # State at a specific time
#' params_10 <- getParams(sim, time_range = 10)
#' # State averaged over the last 10 years
#' params_avg <- getParams(sim, time_range = c(10, 20))
#' # State at the start and at the end of the simulation
#' params_start <- initialParams(sim)
#' params_end <- finalParams(sim)
getParams <- function(sim, time_range, geometric_mean = FALSE) {
UseMethod("getParams")
}
#' @export
getParams.MizerSim <- function(sim, time_range, geometric_mean = FALSE) {
assert_that(is(sim, "MizerSim"),
is.flag(geometric_mean))
params <- sim@params
if (missing(time_range)) {
time_range <- max(as.numeric(dimnames(sim@n)$time))
}
time_elements <- get_time_elements(sim, time_range)
mean_fn <- mean
if (geometric_mean) {
mean_fn <- function(x) exp(mean(log(x)))
}
params@initial_n[] <-
apply(sim@n[time_elements, , , drop = FALSE], c(2, 3), mean_fn)
params@initial_n_pp[] <-
apply(sim@n_pp[time_elements, , drop = FALSE], 2, mean_fn)
mizer_add <- function(l1, l2) {
ifelse(is.list(l1), Map("+", l1, l2), l1 + l2)
}
params@initial_n_other[] <-
apply(sim@n_other[time_elements, , drop = FALSE], 2,
function(l) Reduce(mizer_add, l) / length(l),
simplify = FALSE)
params@initial_effort[] <-
apply(sim@effort[time_elements, , drop = FALSE], 2, mean)
params@time_modified <- lubridate::now()
params
}
#' @rdname getParams
#' @export
initialParams <- function(sim) {
sim <- validSim(sim)
sim@params
}
#' @rdname getParams
#' @export
finalParams <- function(sim) {
UseMethod("finalParams")
}
#' @export
finalParams.MizerSim <- function(sim) {
getParams(sim)
}
#' Extract the projection parameters used to produce a simulation
#'
#' Returns the named list of arguments passed to [project()] or
#' [projectUntilSettled()] when producing this `MizerSim` object, such as
#' `method` and `dt`. Returns an empty list for simulations produced by
#' older versions of mizer.
#'
#' @param sim A MizerSim object
#' @return A named list of projection parameters.
#' @export
#' @examples
#' sim <- project(NS_params, t_max = 0.1, dt = 0.05, method = "predictor-corrector")
#' getSimParams(sim)
getSimParams <- function(sim) {
UseMethod("getSimParams")
}
#' @export
getSimParams.MizerSim <- function(sim) {
assert_that(is(sim, "MizerSim"))
sim@sim_params
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.