| Title: | Dynamic Multi-Species Size Spectrum Modelling |
| Date: | 2025-11-16 |
| Type: | Package |
| Description: | A set of classes and methods to set up and run multi-species, trait based and community size spectrum ecological models, focused on the marine environment. |
| Maintainer: | Gustav Delius <gustav.delius@york.ac.uk> |
| Version: | 2.5.4 |
| License: | GPL-3 |
| Imports: | assertthat, deSolve, dplyr, ggplot2 (≥ 3.4.0), ggrepel, grid,lubridate, methods, plotly, plyr, progress, Rcpp, reshape2,rlang, lifecycle |
| LinkingTo: | Rcpp |
| Depends: | R (≥ 3.1) |
| Suggests: | testthat (≥ 3.0.0), vdiffr, diffviewer, roxygen2, knitr,rmarkdown, pkgdown, covr, spelling |
| Collate: | 'age_mat.R' 'helpers.R' 'MizerParams-class.R''MizerSim-class.R' 'reproduction.R' 'saveParams.R''species_params.R' 'setColours.R' 'setInteraction.R''setPredKernel.R' 'setSearchVolume.R' 'setMaxIntakeRate.R''setMetabolicRate.R' 'setMetadata.R' 'setExtMort.R''setExtEncounter.R' 'setReproduction.R' 'setResource.R''setFishing.R' 'setInitialValues.R' 'setBevertonHolt.R''upgrade.R' 'selectivity_funcs.R' 'pred_kernel_funcs.R''resource_dynamics.R' 'resource_semichemostat.R''resource_logistic.R' 'project.R' 'mizer-package.R''project_methods.R' 'rate_functions.R' 'summary_methods.R''plots.R' 'plotBiomassObservedVsModel.R''plotYieldObservedVsModel.R' 'animateSpectra.R''newMultispeciesParams.R' 'wrapper_functions.R''newSingleSpeciesParams.R' 'steady.R' 'extension.R' 'data.R''RcppExports.R' 'deprecated.R' 'get_initial_n.R''compareParams.R' 'customFunction.R' 'manipulate_species.R''calibrate.R' 'match.R' 'matchGrowth.R' 'steadySingleSpecies.R''defaults_edition.R' 'validSpeciesParams.R' |
| RoxygenNote: | 7.3.3 |
| Encoding: | UTF-8 |
| LazyData: | true |
| URL: | https://sizespectrum.org/mizer/,https://github.com/sizespectrum/mizer |
| BugReports: | https://github.com/sizespectrum/mizer/issues |
| Language: | en-GB |
| RdMacros: | lifecycle |
| VignetteBuilder: | knitr |
| Config/testthat/edition: | 3 |
| NeedsCompilation: | yes |
| Packaged: | 2025-11-16 21:31:14 UTC; gustav |
| Author: | Gustav Delius |
| Repository: | CRAN |
| Date/Publication: | 2025-11-16 21:50:02 UTC |
mizer: Multi-species size-based modelling in R
Description
The mizer package implements multi-species size-based modelling in R. It hasbeen designed for modelling marine ecosystems.
Details
Usingmizer is relatively simple. There are three main stages:
Setting the model parameters. This is done by creating an object ofclassMizerParams. This includes model parameters such as thelife history parameters of each species, and the range of the size spectrum.There are several setup functions that help to create a MizerParams objectsfor particular types of models:
Running a simulation. This is done by calling the
project()function with the model parameters. This produces anobject ofMizerSim that contains the results of the simulation.Exploring results. After a simulation has been run, the results can beexplored using a range ofplotting_functions,summary_functions andindicator_functions.
See themizer website for full details ofthe principles behind mizer and how the package can be used to performsize-based modelling.
Author(s)
Maintainer: Gustav Deliusgustav.delius@york.ac.uk (ORCID) [copyright holder]
Authors:
Finlay Scottdrfinlayscott@gmail.com [copyright holder]
Julia Blanchardjulia.blanchard@utas.edu.au (ORCID) [copyright holder]
Ken Andersenkha@aqua.dtu.dk (ORCID) [copyright holder]
Other contributors:
Richard Southwellrichard.southwell@york.ac.uk [contributor, copyright holder]
See Also
Useful links:
Report bugs athttps://github.com/sizespectrum/mizer/issues
Beverton Holt function to calculate density-dependent reproduction rate
Description
Takes the density-independent ratesR_{di} of egg production (ascalculated bygetRDI()) and returnsreduced, density-dependent reproduction ratesR_{dd} given as
R_{dd} = R_{di}\frac{R_{max}}{R_{di} + R_{max}}
whereR_{max} are the maximum possible reproduction rates that must bespecified in a column in the species parameter dataframe.(All quantities in the above equation are species-specific but we droppedthe species index for simplicity.)
Usage
BevertonHoltRDD(rdi, species_params, ...)Arguments
rdi | Vector of density-independent reproduction rates |
species_params | A species parameter dataframe. Must contain a column |
... | Unused |
Details
This is only one example of a density-dependence. You can write your ownfunction based on this example, returning different density-dependentreproduction rates. Three other examples provided areRickerRDD(),SheperdRDD(),noRDD() andconstantRDD(). For more explanation seesetReproduction().
Value
Vector of density-dependent reproduction rates.
See Also
Other functions calculating density-dependent reproduction rate:RickerRDD(),SheperdRDD(),constantEggRDI(),constantRDD(),noRDD()
Alias forset_multispecies_model()
Description
An alias provided for backward compatibility with mizer version <= 1.0
Usage
MizerParams( species_params, interaction = matrix(1, nrow = nrow(species_params), ncol = nrow(species_params)), min_w_pp = 1e-10, min_w = 0.001, max_w = NULL, no_w = 100, n = 2/3, q = 0.8, f0 = 0.6, kappa = 1e+11, lambda = 2 + q - n, r_pp = 10, ...)Arguments
species_params | A data frame of species-specific parameter values. |
interaction | Optional interaction matrix of the species (predatorspecies x prey species). By default all entries are 1. See "Settinginteraction matrix" section below. |
min_w_pp | The smallest size of the resource spectrum. By default thisis set to the smallest value at which any of the consumers can feed. |
min_w | Sets the size of the eggs of all species for which this is notgiven in the |
max_w | The largest size of the consumer spectrum. By default this isset to the largest |
no_w | The number of size bins in the consumer spectrum. |
n | The allometric growth exponent. This can be overruled for individualspecies by including a |
q | Allometric exponent of search volume |
f0 | Expected average feeding level. Used to set |
kappa | The coefficient of the initial resource abundance power-law. |
lambda | Used to set power-law exponent for resource capacity if the |
r_pp | |
... | Unused |
Value
A MizerParams object
A class to hold the parameters for a size based model.
Description
Although it is possible to build aMizerParams object by hand it isnot recommended and several constructors are available. Dynamic simulationsare performed usingproject() function on objects of this class. As auser you should never need to access the slots inside aMizerParams objectdirectly.
Details
TheMizerParams class is fairly complex with a large number ofslots, many of which are multidimensional arrays. The dimensions of thesearrays is strictly enforced so thatMizerParams objects are consistentin terms of number of species and number of size classes.
TheMizerParams class does not hold any dynamic information, e.g.abundances or harvest effort through time. These are held inMizerSim objects.
Slots
metadataA list with metadata information. See
setMetadata().mizer_versionThe package version of mizer (as returned by
packageVersion("mizer")) that created or upgraded the model.extensionsA named vector of strings where each name is the name ofand extension package needed to run the model and each value is a stringgiving the information that the remotes package needs to install thecorrect version of the extension package, see https://remotes.r-lib.org/.
time_createdA POSIXct date-time object with the creation time.
time_modifiedA POSIXct date-time object with the last modified time.
wThe size grid for the fish part of the spectrum. An increasingvector of weights (in grams) running from the smallest egg size to thelargest maximum size.
dwThe widths (in grams) of the size bins
w_fullThe size grid for the full size range including the resourcespectrum. An increasing vector of weights (in grams) running from thesmallest resource size to the largest maximum size of fish. Thelast entries of the vector have to be equal to the content of the w slot.
dw_fullThe width of the size bins for the full spectrum. The lastentries have to be equal to the content of the dw slot.
w_min_idxA vector holding the index of the weight of the egg sizeof each species
maturityAn array (species x size) that holds the proportion ofindividuals of each species at size that are mature. This enters in thecalculation of the spawning stock biomass with
getSSB(). SetwithsetReproduction().psiAn array (species x size) that holds the allocation to reproductionfor each species at size,
\psi_i(w). Changed withsetReproduction().intake_maxAn array (species x size) that holds the maximum intake foreach species at size. Changed with
setMaxIntakeRate().search_volAn array (species x size) that holds the search volume foreach species at size. Changed with
setSearchVolume().metabAn array (species x size) that holds the metabolismfor each species at size. Changed with
setMetabolicRate().mu_bAn array (species x size) that holds the external mortality rate
\mu_{ext.i}(w). Changed withsetExtMort().ext_encounterAn array (species x size) that holds the external encounter rate
E_{ext.i}(w). Changed withsetExtEncounter().pred_kernelAn array (species x predator size x prey size) that holdsthe predation coefficient of each predator at size on each prey size. Ifthis is NA then the following two slots will be used. Changed with
setPredKernel().ft_pred_kernel_eAn array (species x log of predator/prey size ratio)that holds the Fourier transform of the feeding kernel in a formappropriate for evaluating the encounter rate integral. If this is NAthen the
pred_kernelwill be used to calculate the availableenergy integral. Changed withsetPredKernel().ft_pred_kernel_pAn array (species x log of predator/prey size ratio)that holds the Fourier transform of the feeding kernel in a formappropriate for evaluating the predation mortality integral. If this is NAthen the
pred_kernelwill be used to calculate the integral.Changed withsetPredKernel().rr_ppA vector the same length as the w_full slot. The size specificgrowth rate of the resource spectrum.
cc_ppA vector the same length as the w_full slot. The size specificcarrying capacity of the resource spectrum.
resource_dynamicsName of the function for projecting the resourceabundance density by one timestep.
other_dynamicsA named list of functions for projecting thevalues of other dynamical components of the ecosystem that may be modelledby a mizer extensions you have installed. The names of the list entriesare the names of those components.
other_encounterA named list of functions for calculating thecontribution to the encounter rate from each other dynamical component.
other_mortA named list of functions for calculating thecontribution to the mortality rate from each other dynamical components.
other_paramsA list containing the parameters needed by any mizerextensions you may have installed to model other dynamical components ofthe ecosystem.
rates_funcsA named list with the names of the functions that should beused to calculate the rates needed by
project(). By default this will beset to the names of the built-in rate functions.scspecies_paramsA data.frame to hold the species specific parameters.See
species_params()for details.given_species_paramsA data.frame to hold the species parameters thatwere given explicitly rather than obtained by default calculations.
gear_paramsData frame with parameters for gear selectivity. See
setFishing()for details.interactionThe species specific interaction matrix,
\theta_{ij}.Changed withsetInteraction().selectivityAn array (gear x species x w) that holds the selectivity ofeach gear for species and size,
S_{g,i,w}. Changed withsetFishing().catchabilityAn array (gear x species) that holds the catchability ofeach species by each gear,
Q_{g,i}. Changed withsetFishing().initial_effortA vector containing the initial fishing effort for eachgear. Changed with
setFishing().initial_nAn array (species x size) that holds the initial abundance ofeach species at each weight.
initial_n_ppA vector the same length as the w_full slot that describesthe initial resource abundance at each weight.
initial_n_otherA list with the initial abundances of all otherecosystem components. Has length zero if there are no other components.
resource_paramsList with parameters for resource.
AlinecolourA named vector of colour values, named by species.Used to give consistent colours in plots.
linetypeA named vector of linetypes, named by species.Used to give consistent line types in plots.
ft_maskAn array (species x w_full) with zeros for weights larger thanthe maximum weight of each species. Used to efficiently minimizewrap-around errors in Fourier transform calculations.
See Also
project()MizerSim()emptyParams()newMultispeciesParams()newCommunityParams()newTraitParams()
Constructor for theMizerSim class
Description
A constructor for theMizerSim class. This is used byproject() to createMizerSim objects of the rightdimensions. It is not necessary for users to use this constructor.
Usage
MizerSim(params, t_dimnames = NA, t_max = 100, t_save = 1)Arguments
params | aMizerParams object |
t_dimnames | Numeric vector that is used for the time dimensions of theslots. Default = NA. |
t_max | The maximum time step of the simulation. Only used if t_dimnames= NA. Default value = 100. |
t_save | How often should the results of the simulation be stored. Onlyused if t_dimnames = NA. Default value = 1. |
Value
An object of typeMizerSim
A class to hold the results of a simulation
Description
A class that holds the results of projecting aMizerParamsobject through time usingproject().
Details
A newMizerSim object can be created with theMizerSim()constructor, but you will never have to do that because the object iscreated automatically byproject() when needed.
As a user you should never have to access the slots of a MizerSim objectdirectly. Instead there are a range of functions to extract the information.N() andNResource() return arrays with the saved abundances ofthe 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 resultswere stored andidxFinalT() returns the index with which to accessspecifically the value at the final time in the arrays returned by the otherfunctions.getParams() returns theMizerParams object that waspassed toproject(). There are also severalsummary_functions andplotting_functionsavailable to explore the contents of aMizerSim object.
The arrays all have named dimensions. The names of thetime dimensiondenote the time in years. The names of thew dimension are weights in gramsrounded to three significant figures. The names of thesp dimension are thesame as the species name in the order specified in the species_params dataframe. The names of thegear dimension are the names of the gears, in thesame order as specified when setting up theMizerParams object.
Extensions of mizer can use then_other slot to store the abundances ofother ecosystem components and these extensions should provide their ownfunctions for accessing that information.
TheMizerSim class has changed since previous versions of mizer. To useaMizerSim object created by a previous version, you need to upgrade itwithupgradeSim().
Slots
paramsAn object of typeMizerParams.
nThree-dimensional array (time x species x size) that stores theprojected community number densities.
n_ppAn array (time x size) that stores the projected resource numberdensities.
n_otherA list array (time x component) that stores the projectedvalues for other ecosystem components.
effortAn array (time x gear) that stores the fishing effort by timeand gear.
Time series of size spectra
Description
Fetch the simulation results for the size spectra over time.
Usage
N(sim)NResource(sim)Arguments
sim | A MizerSim object |
Value
ForN(): A three-dimensional array (time x species x size) with thenumber density of consumers
ForNResource(): An array (time x size) with the number density of resource
Examples
str(N(NS_sim))str(NResource(NS_sim))Time series of other components
Description
Fetch the simulation results for other components over time.
Usage
NOther(sim)Arguments
sim | A MizerSim object |
Value
A list array (time x component) that stores the projected values forother ecosystem components.
Example interaction matrix for the North Sea example
Description
The interaction coefficient between predator and prey speciesin the North Sea.
Usage
NS_interactionFormat
A 12 x 12 matrix.
Source
Blanchard et al.
Examples
params <- MizerParams(NS_species_params_gears, interaction = NS_interaction)Example MizerParams object for the North Sea example
Description
A MizerParams object created from theNS_species_params_gears speciesparameters and theinter interaction matrix together with an initialcondition corresponding to the steady state obtained from fishing with anefforteffort = c(Industrial = 0, Pelagic = 1, Beam = 0.5, Otter = 0.5).
Usage
NS_paramsFormat
A MizerParams object
Source
Blanchard et al.
See Also
Other example parameter objects:NS_sim
Examples
sim = project(NS_params, effort = c(Industrial = 0, Pelagic = 1, Beam = 0.5, Otter = 0.5))plot(sim)Example MizerSim object for the North Sea example
Description
A MizerSim object containing a simulation with historical fishingmortalities from the North Sea, as created in the tutorial"A Multi-Species Model of the North Sea".
Usage
NS_simFormat
A MizerSim object
Source
https://sizespectrum.org/mizer/articles/a_multispecies_model_of_the_north_sea.html
See Also
Other example parameter objects:NS_params
Examples
plotBiomass(NS_sim)Example species parameter set based on the North Sea
Description
This data set is based on species in the North Sea (Blanchard et al.). It isa data.frame that contains all the necessary information to be used by theMizerParams() constructor. As there is no gear column, each species isassumed to be fished by a separate gear.
Usage
NS_species_paramsFormat
A data frame with 12 rows and 7 columns. Each row is a species.
- species
Name of the species
- w_max
Maximum size.
- w_mat
Size at maturity
- beta
Size preference ratio
- sigma
Width of the size-preference
- R_max
Maximum reproduction rate
- k_vb
The von Bertalanffy k parameter
- w_inf
The von Bertalanffy asymptotic size
Source
Blanchard et al.
Examples
params <- MizerParams(NS_species_params)Example species parameter set based on the North Sea with different gears
Description
This data set is based on species in the North Sea (Blanchard et al.).It is similar to the data setNS_species_params except thatthis one has an additional column specifying the fishing gear thatoperates on each species.
Usage
NS_species_params_gearsFormat
A data frame with 12 rows and 8 columns. Each row is a species.
- species
Name of the species
- w_max
Maximum size.
- w_mat
Size at maturity
- beta
Size preference ratio
- sigma
Width of the size-preference
- R_max
Maximum reproduction rate
- k_vb
The von Bertalanffy k parameter
- w_inf
The von Bertalanffy asymptotic size
- gear
Name of the fishing gear
Source
Blanchard et al.
Examples
params <- MizerParams(NS_species_params_gears)Ricker function to calculate density-dependent reproduction rate
Description
Takes the density-independent rates
R_{di} of egg production andreturns reduced, density-dependent ratesR_{dd} given as
R_{dd} = R_{di} \exp(- b R_{di})
Usage
RickerRDD(rdi, species_params, ...)Arguments
rdi | Vector of density-independent reproduction rates |
species_params | A species parameter dataframe. Must contain a column |
... | Unused |
Value
Vector of density-dependent reproduction rates.
See Also
Other functions calculating density-dependent reproduction rate:BevertonHoltRDD(),SheperdRDD(),constantEggRDI(),constantRDD(),noRDD()
Sheperd function to calculate density-dependent reproduction rate
Description
Takes the density-independent rates
R_{di} of egg production and returnsreduced, density-dependent ratesR_{dd} given as
R_{dd} = \frac{R_{di}}{1+(b\ R_{di})^c}
Usage
SheperdRDD(rdi, species_params, ...)Arguments
rdi | Vector of density-independent reproduction rates |
species_params | A species parameter dataframe. Must contain columns |
... | Unused |
Details
Withb = 1/R_{max} andc = 1 this reduces to the Beverton-Holtreproduction rate, seeBevertonHoltRDD().
Value
Vector of density-dependent reproduction rates.
See Also
Other functions calculating density-dependent reproduction rate:BevertonHoltRDD(),RickerRDD(),constantEggRDI(),constantRDD(),noRDD()
Add new species
Description
Takes aMizerParams object and adds additional species withgiven parameters to the ecosystem. It sets the initial values for these newspecies to their steady-state solution in the given initial state of theexisting ecosystem. This will be close to the true steady state if theabundances of the new species are sufficiently low. Hence the abundances ofthe new species are set so that they are at most 1/100th of the resourcepower law. Their reproductive efficiencies are set so as to keep them atthat low level.
Usage
addSpecies( params, species_params, gear_params = data.frame(), initial_effort, interaction)Arguments
params | A mizer params object for the original system. |
species_params | Data frame with the species parameters of the newspecies we want to add to the system. |
gear_params | Data frame with the gear parameters for the newspecies. If not provided then the new species will not be fished. |
initial_effort | A named vector with the effort for any new fishing gearintroduced in |
interaction | Interaction matrix. A square matrix giving either theinteraction coefficients between all species or only those between the newspecies. In the latter case all interaction between an old and a newspecies are set to 1. If this argument is missing, all interactionsinvolving a new species are set to 1. |
Details
The resulting MizerParams object will use the same size grid wherepossible, but if one of the new species needs a larger range of w (eitherbecause a new species has an egg size smaller than those of existingspecies or a maximum size larger than those of existing species) then thegrid will be expanded and all arrays will be enlarged accordingly.
If any of the rate arrays of the existing species had been set by the userto values other than those calculated as default from the speciesparameters, then these will be preserved. Only the rates for the newspecies will be calculated from their species parameters.
After adding the new species, the background species are not retuned andthe system is not run to steady state. This could be done withsteady().The new species will have a reproduction level of 1/4, this can then bechanged withsetBevertonHolt()
Value
An object of typeMizerParams
See Also
Examples
params <- newTraitParams()species_params <- data.frame( species = "Mullet", w_max = 173, w_mat = 15, beta = 283, sigma = 1.8, h = 30, a = 0.0085, b = 3.11)params <- addSpecies(params, species_params)plotSpectra(params)Calculate age at maturity
Description
Uses the growth rate and the size at maturity to calculate the age atmaturity
Usage
age_mat(params)Arguments
params | A MizerParams object |
Details
Using that by definition of the growth rateg(w) = dw/dt we have that
\mathrm{age_{mat}} = \int_0^{w_{mat}.}\frac{dw}{g(w)}
Value
A named vector. The names are the species names and the values arethe ages at maturity.
Examples
age_mat(NS_params)Calculate age at maturity from von Bertalanffy growth parameters
Description
This is not a good way to determine the age at maturity because the vonBertalanffy growth curve is not reliable for larvae and juveniles. Howeverthis was used in previous versions of mizer and is supplied forbackwards compatibility.
Usage
age_mat_vB(object)Arguments
object | A MizerParams object or a species_params data frame |
Details
Uses the age at maturity that is implied by the von Bertalanffy growth curvespecified by thew_inf,k_vb,t0,a andb parameters in thespecies_params data frame.
If any ofk_vb is missing for a species, the function returns NA for thatspecies. Default values ofb = 3 andt0 = 0 are used if these aremissing. Ifw_inf is missing,w_max is used instead.
Value
A named vector. The names are the species names and the values arethe ages at maturity.
Animation of the abundance spectra
Description
Usage
animateSpectra( sim, species = NULL, time_range, wlim = c(NA, NA), ylim = c(NA, NA), power = 1, total = FALSE, resource = TRUE)Arguments
sim | A MizerSim object |
species | Name or vector of names of the species to be plotted. Bydefault all species are plotted. |
time_range | The time range to animate over. Either a vector of valuesor a vector of min and max time. Default is the entire time range of thesimulation. |
wlim | A numeric vector of length two providing lower and upper limitsfor the w axis. Use NA to refer to the existing minimum or maximum. |
ylim | A numeric vector of length two providing lower and upper limitsfor the y axis. Use NA to refer to the existing minimum or maximum. Anyvalues below 1e-20 are always cut off. |
power | The abundance is plotted as the number density times the weightraised to |
total | A boolean value that determines whether the total over allspecies in the system is plotted as well. Default is FALSE. |
resource | A boolean value that determines whether resource is included.Default is TRUE. |
Value
A plotly object
See Also
Other plotting functions:plot,MizerParams,missing-method,plot,MizerSim,missing-method,plotBiomass(),plotDiet(),plotFMort(),plotFeedingLevel(),plotGrowthCurves(),plotPredMort(),plotSpectra(),plotYield(),plotYieldGear(),plotting_functions
Examples
animateSpectra(NS_sim, power = 2, wlim = c(0.1, NA), time_range = 1997:2007)Box predation kernel
Description
A predation kernel where the predator/prey mass ratio is uniformlydistributed on an interval.
Usage
box_pred_kernel(ppmr, ppmr_min, ppmr_max)Arguments
ppmr | A vector of predator/prey size ratios |
ppmr_min | Minimum predator/prey mass ratio |
ppmr_max | Maximum predator/prey mass ratio |
Details
Writing the predator mass asw and the prey mass asw_p, thefeeding kernel is 1 ifw/w_p is betweenppmr_min andppmr_max and zero otherwise. The parameters need to be given in thespecies parameter dataframe in the columnsppmr_min andppmr_max.
Value
A vector giving the value of the predation kernel at each of thepredator/prey mass ratios in theppmr argument.
See Also
Other predation kernel:lognormal_pred_kernel(),power_law_pred_kernel(),truncated_lognormal_pred_kernel()
Examples
params <- NS_params# Set all required paramters before changing kernel typespecies_params(params)$ppmr_max <- 4000species_params(params)$ppmr_min <- 200species_params(params)$pred_kernel_type <- "box"plot(w_full(params), getPredKernel(params)["Cod", 10, ], type="l", log="x")Calculate selectivity from gear parameters
Description
This function calculates the selectivity for each gear, species and size fromthe gear parameters. It is called bysetFishing() when theselectivity isnot set by the user.
Usage
calc_selectivity(params)Arguments
params | A MizerParams object |
Value
An array (gear x species x size) with the selectivity values
Examples
params <- NS_paramsstr(calc_selectivity(params))calc_selectivity(params)["Pelagic", "Herring", ]Calibrate the model scale to match total observed biomass
Description
Given a MizerParams object
params for which biomass observations areavailable for at least some species via thebiomass_observed column in thespecies_params data frame, this function returns an updated MizerParamsobject which is rescaled withscaleModel() so that the total biomass inthe model agrees with the total observed biomass.
Usage
calibrateBiomass(params)Arguments
params | A MizerParams object |
Details
Biomass observations usually only include individuals above a certain size.This size should be specified in a biomass_cutoff column of the speciesparameter data frame. If this is missing, it is assumed that all sizes areincluded in the observed biomass, i.e., it includes larval biomass.
After using this function the total biomass in the model will match thetotal biomass, summed over all species. However the biomasses of theindividual species will not match observations yet, with some specieshaving biomasses that are too high and others too low. So after thisfunction you may want to usematchBiomasses(). This is described in theblog post at https://bit.ly/2YqXESV.
If you have observations of the yearly yield instead of biomasses, you canusecalibrateYield() instead of this function.
Value
A MizerParams object
Examples
params <- NS_paramsspecies_params(params)$biomass_observed <- c(0.8, 61, 12, 35, 1.6, 20, 10, 7.6, 135, 60, 30, 78)species_params(params)$biomass_cutoff <- 10params2 <- calibrateBiomass(params)plotBiomassObservedVsModel(params2)Calibrate the model scale to match total observed number
Description
Given a MizerParams object
params for which number observations areavailable for at least some species via thenumber_observed column in thespecies_params data frame, this function returns an updated MizerParamsobject which is rescaled withscaleModel() so that the total number inthe model agrees with the total observed number.
Usage
calibrateNumber(params)Arguments
params | A MizerParams object |
Details
Number observations usually only include individuals above a certain size.This size should be specified in a number_cutoff column of the speciesparameter data frame. If this is missing, it is assumed that all sizes areincluded in the observed number, i.e., it includes larval number.
After using this function the total number in the model will match thetotal number, summed over all species. However the numbers of theindividual species will not match observations yet, with some specieshaving numbers that are too high and others too low. So after thisfunction you may want to usematchNumbers(). This is described in theblog post at https://bit.ly/2YqXESV.
If you have observations of the yearly yield instead of numbers, you canusecalibrateYield() instead of this function.
Value
A MizerParams object
Examples
params <- NS_paramsspecies_params(params)$number_observed <- c(0.8, 61, 12, 35, 1.6, 20, 10, 7.6, 135, 60, 30, 78)species_params(params)$number_cutoff <- 10params2 <- calibrateNumber(params)Calibrate the model scale to match total observed yield
Description
Usage
calibrateYield(params)Arguments
params | A MizerParams object |
Details
This function has been deprecated and will be removed in the future unlessyou have a use case for it. If you do have a use case for it, please let thedevelopers know by creating an issue athttps://github.com/sizespectrum/mizer/issues.
Given a MizerParams objectparams for which yield observations areavailable for at least some species via theyield_observed column in thespecies_params data frame, this function returns an updated MizerParamsobject which is rescaled withscaleModel() so that the total yield inthe model agrees with the total observed yield.
After using this function the total yield in the model will match thetotal observed yield, summed over all species. However the yields of theindividual species will not match observations yet, with some specieshaving yields that are too high and others too low. So after thisfunction you may want to usematchYields().
If you have observations of species biomasses instead of yields, you canusecalibrateBiomass() instead of this function.
Value
A MizerParams object
Examples
params <- NS_paramsspecies_params(params)$yield_observed <- c(0.8, 61, 12, 35, 1.6, 20, 10, 7.6, 135, 60, 30, 78)gear_params(params)$catchability <- c(1.3, 0.065, 0.31, 0.18, 0.98, 0.24, 0.37, 0.46, 0.18, 0.30, 0.27, 0.39)params2 <- calibrateYield(params)plotYieldObservedVsModel(params2)Compare two MizerParams objects and print out differences
Description
Usage
compareParams(params1, params2)Arguments
params1 | First MizerParams object |
params2 | Second MizerParams object |
Value
String describing the differences
Examples
params1 <- NS_paramsparams2 <- params1species_params(params2)$w_mat[1] <- 10compareParams(params1, params2)Alias forvalidSpeciesParams()
Description
An alias provided for backward compatibility with mizer version <= 2.5.2
Usage
completeSpeciesParams(species_params)Arguments
species_params | The user-supplied species parameter data frame |
Details
validGivenSpeciesParams() checks the validity of the given speciesparameter It throws an error if
the
speciescolumn does not exist or contains duplicatesthe maximum size is not specified for all species
If a weight-based parameter is missing but the corresponding length-basedparameter is given, as well as thea andb parameters for length-weightconversion, then the weight-based parameters are added. If both length andweight are given, then weight is used and a warning is issued if the two areinconsistent.
If aw_inf column is given but now_max then the value fromw_inf isused. This is for backwards compatibility. But note that the von Bertalanffyparameterw_inf is not the maximum size of the largest individual, but theasymptotic size of an average individual.
Some inconsistencies in the size parameters are resolved as follows:
Any
w_matthat is not smaller thanw_maxis set tow_max / 4.Any
w_mat25that is not smaller thanw_matis set to NA.Any
w_minthat is not smaller thanw_matis set to0.001orw_mat /10, whichever is smaller.Any
w_repro_maxthat is not larger thanw_matis set to4 * w_mat.
The row names of the returned data frame will be the species names.Ifspecies_params was provided as a tibble it is converted back to anordinary data frame.
The function tests for some typical misspellings of parameter names, likewrong capitalisation or missing underscores and issues a warning if itdetects such a name.
validSpeciesParams() first callsvalidGivenSpeciesParams() but thengoes further by adding default values for species parameters that were notprovided. The function sets default values if any of the following speciesparameters are missing or NA:
w_repro_maxis set tow_maxw_matis set tow_max/4w_minis set to0.001alphais set to0.6interaction_resourceis set to1nis set to3/4pis set ton
Note that the species parameters returned by these functions are notguaranteed to produce a viable model. More checks of the parameters areperformed by the individual rate-setting functions (seesetParams() for thelist of these functions).
Value
ForvalidSpeciesParams(): A valid species parameter data frame withadditional parameters with default values.
ForvalidGivenSpeciesParams(): A valid species parameter data framewithout additional parameters.
See Also
species_params(),validGearParams(),validParams(),validSim()
Choose egg production to keep egg density constant
Description
The new egg production is set to compensate for the loss of individuals fromthe smallest size class through growth and mortality. The result should notbe modified by density dependence, so this should be used together withthe
noRDD() function, see example.
Usage
constantEggRDI(params, n, e_growth, mort, ...)Arguments
params | A MizerParams object |
n | A matrix of species abundances (species x size). |
e_growth | A two dimensional array (species x size) holding the energyavailable for growth as calculated by |
mort | A two dimensional array (species x size) holding the mortalityrate as calculated by |
... | Unused |
Value
Vector with the value for each species
See Also
Other functions calculating density-dependent reproduction rate:BevertonHoltRDD(),RickerRDD(),SheperdRDD(),constantRDD(),noRDD()
Examples
# choose an example params objectparams <- NS_params# We set the reproduction rate functionsparams <- setRateFunction(params, "RDI", "constantEggRDI")params <- setRateFunction(params, "RDD", "noRDD")# Now the egg density should stay fixed no matter how we fishsim <- project(params, effort = 10, progress_bar = FALSE)# To check that indeed the egg densities have not changed, we first construct# the indices for addressing the egg densitiesno_sp <- nrow(params@species_params)idx <- (params@w_min_idx - 1) * no_sp + (1:no_sp)# Now we can check equality between egg densities at the start and the endall.equal(finalN(sim)[idx], initialN(params)[idx])Give constant reproduction rate
Description
Simply returns the value from
species_params$constant_reproduction.
Usage
constantRDD(rdi, species_params, ...)Arguments
rdi | Vector of density-independent reproduction rates |
species_params | A species parameter dataframe. Must contain a column |
... | Unused |
Value
Vectorspecies_params$constant_reproduction
See Also
Other functions calculating density-dependent reproduction rate:BevertonHoltRDD(),RickerRDD(),SheperdRDD(),constantEggRDI(),noRDD()
Helper function to keep other components constant
Description
Helper function to keep other components constant
Usage
constant_other(params, n_other, component, ...)Arguments
params | MizerParams object |
n_other | Abundances of other components |
component | Name of the component that is being updated |
... | Unused |
Value
The current value of the component
Replace a mizer function with a custom version
Description
This function allows you to make arbitrary changes to how mizer works byallowing you to replace any mizer function with your own version. Youshould do this only as a last resort, when you find that you can not usethe standard mizer extension mechanism to achieve your goal.
Usage
customFunction(name, fun)Arguments
name | Name of mizer function to replace |
fun | The custom function to use as replacement |
Details
If the function you need to overwrite is one of the mizer rate functions,then you should usesetRateFunction() instead of this function. Similarlyyou should useresource_dynamics()<- to change the resource dynamics andsetReproduction() to change the density-dependence in reproduction.You should also investigate whether you can achieve your goal by introducingadditional ecosystem components withsetComponent().
If you find that your goal really does require you to overwrite a mizerfunction, please also create an issue on the mizer issue tracker athttps://github.com/sizespectrum/mizer/issues todescribe your goal, because it will be interesting to the mizer communityand may motivate future improvements to the mizer functionality.
Note thatcustomFunction() only overwrites the function used by the mizercode. It does not overwrite the function that is exported by mizer. Thiswill become clear when you run the code in the Examples section.
This function does not in any way check that your replacement function iscompatible with mizer. Calling this function can totally break mizer.However you can always undo the effect by reloading mizer with
detach(package:mizer, unload = TRUE)library(mizer)
Value
No return value, called for side effects
Examples
## Not run: fake_project <- function(...) "Fake"customFunction("project", fake_project)mizer::project(NS_params) # This will print "Fake"project(NS_params) # This will still use the old project() function# To undo the effect:customFunction("project", project)mizer::project(NS_params) # This will again use the old project()## End(Not run)Set defaults for predation kernel parameters
Description
If the predation kernel type has not been specified for a species, then itis set to "lognormal" and the default values are set for the parametersbeta andsigma.
Usage
default_pred_kernel_params(object)Arguments
object | Either a MizerParams object or a species parameter data frame |
Value
Theobject with updated columns in the species params data frame.
Default editions
Description
Function to set and get which edition of default choices is being used.
Usage
defaults_edition(edition = NULL)Arguments
edition | NULL or a numerical value. |
Details
The mizer functions for creating new models make a lot of choices for defaultvalues for parameters that are not provided by the user. Sometimes we findbetter ways to choose the defaults and update mizer accordingly. When we dothis, we will increase the edition number.
If you calldefaults_edition() without an argument it returns thecurrently active edition. Otherwise it sets the active edition to thegiven value.
Users who want their existing code for creating models not to changebehaviour when run with future versions of mizer should explicitly set thedesired defaults edition at the top of their code.
The most recent edition is edition 2. It will become the default in thenext release. The current default is edition 1. The following defaultsare changed in edition 2:
catchability = 0.3 instead of 1
initial effort = 1 instead of 0
Value
The current edition number.
Check whether two objects are different
Description
Check whether two objects are numerically different, ignoring all attributes.
Usage
different(a, b)Arguments
a | First object |
b | Second object |
Details
We use this helper function in particular to see if a new value for a slotin MizerParams is different from the existing value in order to give theappropriate messages.
Value
TRUE or FALSE
Measure distance between current and previous state in terms of RDI
Description
This function can be used inprojectToSteady() to decide when sufficientconvergence to steady state has been achieved.
Usage
distanceMaxRelRDI(params, current, previous)Arguments
params | MizerParams |
current | A named list with entries |
previous | A named list with entries |
Value
The largest absolute relative change in rdi:max(abs((current_rdi - previous_rdi) / previous_rdi))
See Also
Other distance functions:distanceSSLogN()
Measure distance between current and previous state in terms of fish abundances
Description
Calculates the sum squared difference between log(N) in current and previousstate. This function can be used inprojectToSteady() to decide whensufficient convergence to steady state has been achieved.
Usage
distanceSSLogN(params, current, previous)Arguments
params | MizerParams |
current | A named list with entries |
previous | A named list with entries |
Value
The sum of squares of the difference in the logs of the (nonzero)fish abundances n:sum((log(current$n) - log(previous$n))^2)
See Also
Other distance functions:distanceMaxRelRDI()
Length based double-sigmoid selectivity function
Description
A hump-shaped selectivity function with a sigmoidal rise and an independentsigmoidal drop-off. This drop-off is what distinguishes this from thefunctionsigmoid_length() and it is intended to model the escape of largeindividuals from the fishing gear.
Usage
double_sigmoid_length(w, l25, l50, l50_right, l25_right, species_params, ...)Arguments
w | Vector of sizes. |
l25 | the length which gives a selectivity of 25%. |
l50 | the length which gives a selectivity of 50%. |
l50_right | the length which gives a selectivity of 50%. |
l25_right | the length which gives a selectivity of 25%. |
species_params | A list with the species params for the current species.Used to get at the length-weight parameters |
... | Unused |
Details
The selectivity is obtained as the product of two sigmoidal curves, onerising and one dropping. The sigmoidal rise is based on the two parametersl25 andl50 which determine the length at which 25% and 50% ofthe stock is selected respectively. The sigmoidal drop-off is based on thetwo parametersl50_right andl25_right which determine thelength at which the selectivity curve has dropped back to 50% and 25%respectively. The selectivity is given by the function
S(l) =\frac{1}{1 + \exp\left(\log(3)\frac{l50 -l}{l50 - l25}\right)}\frac{1}{1 +\exp\left(\log(3)\frac{l50_{right} -l}{l50_{right} -l25_{right}}\right)}
As the size-based model is weight based, and this selectivity function islength based, it uses the length-weight parametersa andb to convertbetween length and weight.
l = \left(\frac{w}{a}\right)^{1/b}
Value
Vector of selectivities at the given sizes.
See Also
gear_params() for setting the selectivity parameters.
Other selectivity functions:knife_edge(),sigmoid_length(),sigmoid_weight()
Create empty MizerParams object of the right size
Description
An internal function.Sets up a validMizerParams object with all the slotsinitialised and given dimension names, but with some slots left empty. Thisfunction is to be used by other functions to set up full parameter objects.
Usage
emptyParams( species_params, gear_params = data.frame(), no_w = 100, min_w = 0.001, max_w = NA, min_w_pp = 1e-12)Arguments
species_params | A data frame of species-specific parameter values. |
gear_params | A data frame with gear-specific parameter values. |
no_w | The number of size bins in the consumer spectrum. |
min_w | Sets the size of the eggs of all species for which this is notgiven in the |
max_w | The largest size of the consumer spectrum. By default this isset to the largest |
min_w_pp | The smallest size of the resource spectrum. |
Value
An empty but valid MizerParams object
Size grid
A size grid is created so thatthe log-sizes are equally spaced. The spacing is chosen so that there will beno_w fish size bins, with the smallest starting atmin_w and the largeststarting atmax_w. For the resource spectrum there is a larger set ofbins containing additional bins belowmin_w, with the same log size. The number of extra bins is such thatmin_w_pp comes to lie within the smallest bin.
Changes to species params
Thespecies_params slot of the returned MizerParams object may differfrom the data frame supplied as argument to this function becausedefault values are set for missing parameters.
See Also
SeenewMultispeciesParams() for a function that fillsthe slots left empty by this function.
Size spectra at end of simulation
Description
Size spectra at end of simulation
Usage
finalN(sim)finalNResource(sim)idxFinalT(sim)Arguments
sim | A MizerSim object |
Value
ForfinalN(): An array (species x size) holding the consumernumber densities at the end of the simulation
ForfinalNResource(): A vector holding the resource numberdensities at the end of the simulation for all size classes
ForidxFinalT(): An integer giving the index for extracting theresults for the final time step
Examples
str(finalN(NS_sim))# This could also be obtained using `N()` and `idxFinalT()`identical(N(NS_sim)[idxFinalT(NS_sim), , ], finalN(NS_sim))str(finalNResource(NS_sim))idx <- idxFinalT(NS_sim)idx# This coincides withlength(getTimes(NS_sim))# and corresponds to the final timegetTimes(NS_sim)[idx]# We can use this index to extract the result at the final timeidentical(N(NS_sim)[idx, , ], finalN(NS_sim))identical(NResource(NS_sim)[idx, ], finalNResource(NS_sim))Values of other ecosystem components at end of simulation
Description
Values of other ecosystem components at end of simulation
Usage
finalNOther(sim)Arguments
sim | A MizerSim object |
Value
A named list holding the values of other ecosystem components at theend of the simulation
Gear parameters
Description
These functions allow you to get or set the gear parameters stored ina MizerParams object. These are used bysetFishing() to set up theselectivity and catchability and thus together with the fishing effortdetermine the fishing mortality.
Usage
gear_params(params)gear_params(params) <- valueArguments
params | A MizerParams object |
value | A data frame with the gear parameters. |
Details
Thegear_params data has one row for each gear-species pair and onecolumn for each parameter that determines how that gear interacts with thatspecies. The columns are:
speciesThe name of the speciesgearThe name of the gearcatchabilityA number specifying how strongly this gear selects thisspecies.sel_funcThe name of the function that calculates the selectivity curve.One column for each selectivity parameter needed by the selectivityfunctions.
For the details seesetFishing().
There can optionally also be a columnyield_observed that allows you tospecify for each gear and species the total annual fisheries yield.
The fishing effort, which is also needed to determine the fishing mortalityexerted by a gear is not set via thegear_params data frame but is setwithinitial_effort() or is specified when callingproject().
If you change a gear parameter, this will be used to recalculate theselectivity andcatchability arrays by callingsetFishing(),unless you have previously set these by hand.
gear_params<- automatically sets the row names to contain the species nameand the gear name, separated by a comma and a space. The last example belowillustrates how this facilitates changing an individual gear parameter.
Value
Data frame with gear parameters
See Also
Other functions for setting parameters:setExtEncounter(),setExtMort(),setFishing(),setInitialValues(),setInteraction(),setMaxIntakeRate(),setMetabolicRate(),setParams(),setPredKernel(),setReproduction(),setSearchVolume(),species_params()
Examples
params <- NS_params# gears set up in examplegear_params(params)# setting totally different gearsgear_params(params) <- data.frame( gear = c("gear1", "gear2", "gear1"), species = c("Cod", "Cod", "Haddock"), catchability = c(0.5, 2, 1), sel_fun = c("sigmoid_weight", "knife_edge", "sigmoid_weight"), sigmoidal_weight = c(1000, NA, 800), sigmoidal_sigma = c(100, NA, 100), knife_edge_size = c(NA, 1000, NA) )gear_params(params)# changing an individual entrygear_params(params)["Cod, gear1", "catchability"] <- 0.8Calculate the total biomass of each species within a size range at each timestep.
Description
Calculates the total biomass through time within user defined size limits.The default option is to use the whole size range. You can specify minimumand maximum weight or length range for the species. Lengths take precedenceover weights (i.e. if both min_l and min_w are supplied, only min_l will beused).
Usage
getBiomass(object, ...)Arguments
object | An object of class |
... | Arguments passed on to
|
Value
If called with a MizerParams object, a vector with the biomass ingrams for each species in the model. If called with a MizerSim object, anarray (time x species) containing the biomass in grams at each time stepfor all species.
See Also
Other summary functions:getDiet(),getGrowthCurves(),getN(),getSSB(),getYield(),getYieldGear()
Examples
biomass <- getBiomass(NS_sim)biomass["1972", "Herring"]biomass <- getBiomass(NS_sim, min_w = 10, max_w = 1000)biomass["1972", "Herring"]Calculate the slope of the community abundance
Description
Calculates the slope of the community abundance through time by performing alinear regression on the logged total numerical abundance at weight andlogged weights (natural logs, not log to base 10, are used). You can specifyminimum and maximum weight or length range for the species. Lengths takeprecedence over weights (i.e. if both min_l and min_w are supplied, onlymin_l will be used). You can also specify the species to be used in thecalculation.
Usage
getCommunitySlope(sim, species = NULL, biomass = TRUE, ...)Arguments
sim | AMizerSim object |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
biomass | Boolean. If TRUE (default), the abundance is based on biomass,if FALSE the abundance is based on numbers. |
... | Arguments passed on to
|
Value
A data.frame with four columns: time step, slope, intercept and thecoefficient of determination R^2.
See Also
Other functions for calculating indicators:getMeanMaxWeight(),getMeanWeight(),getProportionOfLargeFish()
Examples
# Slope based on biomass, using all species and sizesslope_biomass <- getCommunitySlope(NS_sim)slope_biomass[1, ] # in 1976slope_biomass[idxFinalT(NS_sim), ] # in 2010# Slope based on numbers, using all species and sizesslope_numbers <- getCommunitySlope(NS_sim, biomass = FALSE)slope_numbers[1, ] # in 1976# Slope based on biomass, using all species and sizes between 10g and 1000gslope_biomass <- getCommunitySlope(NS_sim, min_w = 10, max_w = 1000)slope_biomass[1, ] # in 1976# Slope based on biomass, using only demersal species and # sizes between 10g and 1000gdem_species <- c("Dab","Whiting", "Sole", "Gurnard", "Plaice", "Haddock", "Cod", "Saithe")slope_biomass <- getCommunitySlope(NS_sim, species = dem_species, min_w = 10, max_w = 1000)slope_biomass[1, ] # in 1976Get information about other ecosystem components
Description
Get information about other ecosystem components
Usage
getComponent(params, component)Arguments
params | A MizerParams object |
component | Name of the component of interest. If missing, a list ofall components will be returned. |
Value
A list with the entriesinitial_value,dynamics_fun,encounter_fun,mort_fun,component_params for the requestedcomponent. If the requested component does not exist,NULL is returned.If nocomponent argument is given, then a list of lists for allcomponents is returned.
Get critical feeding level
Description
The critical feeding level is the feeding level at which the food intake isjust high enough to cover the metabolic costs, with nothing left over forgrowth or reproduction.
Usage
getCriticalFeedingLevel(params)Arguments
params | A MizerParams object |
Value
A matrix (species x size) with the critical feeding level
Examples
str(getFeedingLevel(NS_params))Get diet of predator at size, resolved by prey species
Description
Calculates the rate at which a predator of a particular species and sizeconsumes biomass of each prey species, resource, and other components of theecosystem. Returns either the rates in grams/year or the proportion of thetotal consumption rate.
Usage
getDiet( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), proportion = TRUE)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
proportion | If TRUE (default) the function returns the diet as aproportion of the total consumption rate. If FALSE it returns theconsumption rate in grams per year. |
Details
The ratesD_{ij}(w) at which a predator of speciesiand sizew consumes biomass from prey speciesj arecalculated from the predation kernel\phi_i(w, w_p),the search volume\gamma_i(w), the feeding levelf_i(w), thespecies interaction matrix\theta_{ij} and the prey abundance densityN_j(w_p):
D_{ij}(w, w_p) = (1-f_i(w)) \gamma_i(w) \theta_{ij}\int N_j(w_p) \phi_i(w, w_p) w_p dw_p.
The prey indexj runs over all species and the resource.
Extra columns are added for the external encounter rate and for any extraecosystem components in your model for which you have defined an encounterrate function. These encounter rates are multiplied by1-f_i(w) to givethe rate of consumption of biomass from these extra components.
This function performs the same integration asgetEncounter() but does notaggregate over prey species, and multiplies by1-f_i(w) to get theconsumed biomass rather than the available biomass. Outside the range ofsizes for a predator species the returned rate is zero.
Value
An array (predator species x predator size x(prey species + resource + other components). Dimnames are "prey", "w",and "predator".
See Also
Other summary functions:getBiomass(),getGrowthCurves(),getN(),getSSB(),getYield(),getYieldGear()
Examples
diet <- getDiet(NS_params)str(diet)Get energy rate available for growth
Description
Calculates the energy rateg_i(w) (grams/year) available by species andsize for growth after metabolism, movement and reproduction have beenaccounted for.
Usage
getEGrowth( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), t = 0, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
... | Unused |
Value
A two dimensional array (prey species x prey size)
Your own growth rate function
By defaultgetEGrowth() callsmizerEGrowth(). However you canreplace this with your own alternative growth rate function. Ifyour function is called"myEGrowth" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "EGrowth", "myEGrowth")
Your function will then be called instead ofmizerEGrowth(), with thesame arguments.
See Also
getERepro(),getEReproAndGrowth()
Other rate functions:getERepro(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getMort(),getPredMort(),getPredRate(),getRDD(),getRDI(),getRates(),getResourceMort()
Examples
params <- NS_params# Project with constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get the energy at a particular time stepgrowth <- getEGrowth(params, n = N(sim)[15, , ], n_pp = NResource(sim)[15, ], t = 15)# Growth rate at this time for Sprat of size 2ggrowth["Sprat", "2"]Get energy rate available for reproduction
Description
Calculates the energy rate (grams/year) available for reproduction aftergrowth and metabolism have been accounted for.
Usage
getERepro( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), t = 0, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
... | Unused |
Value
A two dimensional array (prey species x prey size) holding
\psi_i(w)E_{r.i}(w)
whereE_{r.i}(w) is the rate at which energy becomes available forgrowth and reproduction, calculated withgetEReproAndGrowth(),and\psi_i(w) is the proportion of this energy that is used forreproduction. This proportion is taken from theparams object and isset withsetReproduction().
Your own reproduction rate function
By defaultgetERepro() callsmizerERepro(). However you canreplace this with your own alternative reproduction rate function. Ifyour function is called"myERepro" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "ERepro", "myERepro")
Your function will then be called instead ofmizerERepro(), with thesame arguments.
See Also
Other rate functions:getEGrowth(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getMort(),getPredMort(),getPredRate(),getRDD(),getRDI(),getRates(),getResourceMort()
Examples
params <- NS_params# Project with constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get the rate at a particular time steperepro <- getERepro(params, n = N(sim)[15, , ], n_pp = NResource(sim)[15, ], t = 15)# Rate at this time for Sprat of size 2gerepro["Sprat", "2"]Get energy rate available for reproduction and growth
Description
Calculates the energy rateE_{r.i}(w) (grams/year) available forreproduction and growth after metabolism and movement have been accountedfor.
Usage
getEReproAndGrowth( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), t = 0, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
... | Unused |
Value
A two dimensional array (species x size) holding
E_{r.i}(w) = \max(0, \alpha_i\, (1 - {\tt feeding\_level}_i(w))\, {\tt encounter}_i(w) - {\tt metab}_i(w)).
Due to the form of the feeding level, calculated bygetFeedingLevel(), if the feeding level is nonzero this can also be expressed as
E_{r.i}(w) = \max(0, \alpha_i\, {\tt feeding\_level}_i(w)\, h_i(w) - {\tt metab}_i(w))
whereh_i is the maximum intake rate, set withsetMaxIntakeRate(). However this function is using the first equationabove so that it works also when the maximum intake rate is infinite, i.e.,there is no satiation.The assimilation rate\alpha_i is taken from the species parameterdata frame inparams. The metabolic ratemetab is taken fromparams and set withsetMetabolicRate().
The return value can be negative, which means that the energy intake does notcover the cost of metabolism and movement.
Your own energy rate function
By defaultgetEReproAndGrowth() callsmizerEReproAndGrowth(). However youcan replace this with your own alternative energy rate function. Ifyour function is called"myEReproAndGrowth" then you register it in aMizerParams objectparams with
params <- setRateFunction(params, "EReproAndGrowth", "myEReproAndGrowth")
Your function will then be called instead ofmizerEReproAndGrowth(), withthe same arguments.
See Also
The part of this energy rate that is invested into growth iscalculated withgetEGrowth() and the part that is invested intoreproduction is calculated withgetERepro().
Other rate functions:getEGrowth(),getERepro(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getMort(),getPredMort(),getPredRate(),getRDD(),getRDI(),getRates(),getResourceMort()
Examples
params <- NS_params# Project with constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get the energy at a particular time stepe <- getEReproAndGrowth(params, n = N(sim)[15, , ], n_pp = NResource(sim)[15, ], t = 15)# Rate at this time for Sprat of size 2ge["Sprat", "2"]Alias forgetERepro()
Description
An alias provided for backward compatibility with mizer version <= 1.0
Usage
getESpawning( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), t = 0, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
... | Unused |
Value
A two dimensional array (prey species x prey size) holding
\psi_i(w)E_{r.i}(w)
whereE_{r.i}(w) is the rate at which energy becomes available forgrowth and reproduction, calculated withgetEReproAndGrowth(),and\psi_i(w) is the proportion of this energy that is used forreproduction. This proportion is taken from theparams object and isset withsetReproduction().
Your own reproduction rate function
By defaultgetERepro() callsmizerERepro(). However you canreplace this with your own alternative reproduction rate function. Ifyour function is called"myERepro" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "ERepro", "myERepro")
Your function will then be called instead ofmizerERepro(), with thesame arguments.
See Also
Other rate functions:getEGrowth(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getMort(),getPredMort(),getPredRate(),getRDD(),getRDI(),getRates(),getResourceMort()
Examples
params <- NS_params# Project with constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get the rate at a particular time steperepro <- getERepro(params, n = N(sim)[15, , ], n_pp = NResource(sim)[15, ], t = 15)# Rate at this time for Sprat of size 2gerepro["Sprat", "2"]Fishing effort used in simulation
Description
Note that the array returned may not be exactly the same as theeffortargument that was passed in toproject(). This is because only the savedeffort is stored (the frequency of saving is determined by the argumentt_save).
Usage
getEffort(sim)Arguments
sim | A MizerSim object |
Value
An array (time x gear) that contains the fishing effort by time andgear.
Examples
str(getEffort(NS_sim))Get encounter rate
Description
Returns the rate at which a predator of speciesi andweightw encounters food (grams/year).
Usage
getEncounter( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), t = 0, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
... | Unused |
Value
A named two dimensional array (predator species x predator size) withthe encounter rates.
Predation encounter
The encounter rateE_i(w) at which a predator of speciesiand weightw encounters food has contributions from the encounter offish prey and of resource. This is determined by summing over all preyspecies and the resource spectrum and then integrating over all prey sizesw_p, weighted by predation kernel\phi(w,w_p):
E_i(w) = \gamma_i(w) \int\left( \theta_{ip} N_R(w_p) + \sum_{j} \theta_{ij} N_j(w_p) \right)\phi_i(w,w_p) w_p \, dw_p.
HereN_j(w) is the abundance density of speciesj andN_R(w) is the abundance density of resource.The overall prefactor\gamma_i(w) determines the predation power of thepredator. It could be interpreted as a search volume and is set with thesetSearchVolume() function. The predation kernel\phi(w,w_p) is set with thesetPredKernel() function. Thespecies interaction matrix\theta_{ij} is set withsetInteraction()and the resource interaction vector\theta_{ip} is taken from theinteraction_resource column inparams@species_params.
Details
The encounter rate is multiplied by1-f_0 to obtain the consumptionrate, wheref_0 is the feeding level calculated withgetFeedingLevel(). This is used by theproject() function for performingsimulations.
The function returns values also for sizes outside the size-range of thespecies. These values should not be used, as they are meaningless.
If your model contains additional components that you added withsetComponent() and for which you specified anencounter_fun function thenthe encounters of these components will be included in the returned value.
Your own encounter function
By defaultgetEncounter() callsmizerEncounter(). However you canreplace this with your own alternative encounter function. Ifyour function is called"myEncounter" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "Encounter", "myEncounter")
Your function will then be called instead ofmizerEncounter(), with thesame arguments.
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getFMort(),getFMortGear(),getFeedingLevel(),getMort(),getPredMort(),getPredRate(),getRDD(),getRDI(),getRates(),getResourceMort()
Examples
encounter <- getEncounter(NS_params)str(encounter)Get the total fishing mortality rate from all fishing gears by time, speciesand size.
Description
Calculates the total fishing mortality (in units 1/year) from all gears byspecies and size and possibly time. SeesetFishing() for details ofhow fishing gears are set up.
Usage
getFMort(object, effort, time_range, drop = TRUE)Arguments
object | A |
effort | The effort of each fishing gear. Only used if the objectargument is of class |
time_range | Subset the returned fishing mortalities by time. The timerange is either a vector of values, a vector of min and max time, or asingle value. Default is the whole time range. Only used if the |
drop | Only used when object is of type |
Details
The total fishing mortality is just the sum of the fishing mortalitiesimposed by each gear,F_i(w)=\sum_g F_{g,i,w}.The fishing mortality for each gear is obtained as catchability xselectivity x effort.
Value
An array. If the effort argument has a time dimension, or object isof classMizerSim, the output array has three dimensions (time xspecies x size). If the effort argument does not have a time dimension, theoutput array has two dimensions (species x size).
Theeffort argument is only used if aMizerParams object ispassed in. Theeffort argument can be a two dimensional array (time xgear), a vector of length equal to the number of gears (each gear has adifferent effort that is constant in time), or a single numeric value (eachgear has the same effort that is constant in time). The order of gears in theeffort argument must be the same as in theMizerParamsobject.
If the object argument is of classMizerSim then the effort slot oftheMizerSim object is used and theeffort argument is notused.
Your own fishing mortality function
By defaultgetFMort() callsmizerFMort(). However you canreplace this with your own alternative fishing mortality function. Ifyour function is called"myFMort" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "FMort", "myFMort")
Your function will then be called instead ofmizerFMort(), with thesame arguments.
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getEncounter(),getFMortGear(),getFeedingLevel(),getMort(),getPredMort(),getPredRate(),getRDD(),getRDI(),getRates(),getResourceMort()
Examples
params <- NS_params# Get the total fishing mortality in the initial stateF <- getFMort(params, effort = 1)str(F)# Get the initial total fishing mortality when effort is different# between the four gears:F <- getFMort(params, effort = c(0.5,1,1.5,0.75))# Get the total fishing mortality when effort is different# between the four gears and changes with time:effort <- array(NA, dim = c(20,4))effort[, 1] <- seq(from = 0, to = 1, length = 20)effort[, 2] <- seq(from = 1, to = 0.5, length = 20)effort[, 3] <- seq(from = 1, to = 2, length = 20)effort[, 4] <- seq(from = 2, to = 1, length = 20)F <- getFMort(params, effort = effort)str(F)# Get the total fishing mortality using the effort already held in a # MizerSim object.sim <- project(params, t_max = 20, effort = 0.5)F <- getFMort(sim)F <- getFMort(sim, time_range = c(10, 20))Get the fishing mortality by time, gear, species and size
Description
Calculates the fishing mortality rateF_{g,i,w} by gear, species andsize and possibly time (in units 1/year).
Usage
getFMortGear(object, effort, time_range)Arguments
object | A |
effort | The effort for each fishing gear. See notes below. |
time_range | Subset the returned fishing mortalities by time. The timerange is either a vector of values, a vector of min and max time, or asingle value. Default is the whole time range. Only used if the |
Value
An array. If the effort argument has a time dimension, or aMizerSim is passed in, the output array has four dimensions (time xgear x species x size). If the effort argument does not have a timedimension (i.e. it is a vector or a single numeric), the output array hasthree dimensions (gear x species x size).
Note
Here: fishing mortality = catchability x selectivity x effort.
Theeffort argument is only used if aMizerParams object ispassed in. Theeffort argument can be a two dimensional array (time xgear), a vector of length equal to the number of gears (each gear has adifferent effort that is constant in time), or a single numeric value (eachgear has the same effort that is constant in time). The order of gears in theeffort argument must be the same the same as in theMizerParamsobject. If theeffort argument is not supplied, its value is takenfrom the@initial_effort slot in the params object.
If the object argument is of classMizerSim then the effort slot oftheMizerSim object is used and theeffort argument is notused.
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getEncounter(),getFMort(),getFeedingLevel(),getMort(),getPredMort(),getPredRate(),getRDD(),getRDI(),getRates(),getResourceMort()
Examples
params <-NS_params# Get the fishing mortality in initial stateF <- getFMortGear(params, effort = 1)str(F)# Get the initial fishing mortality when effort is different# between the four gears:F <- getFMortGear(params, effort = c(0.5, 1, 1.5, 0.75))# Get the fishing mortality when effort is different# between the four gears and changes with time:effort <- array(NA, dim = c(20, 4))effort[, 1] <- seq(from=0, to = 1, length = 20)effort[, 2] <- seq(from=1, to = 0.5, length = 20)effort[, 3] <- seq(from=1, to = 2, length = 20)effort[, 4] <- seq(from=2, to = 1, length = 20)F <- getFMortGear(params, effort = effort)str(F)# Get the fishing mortality using the effort already held in a MizerSim object.sim <- project(params, t_max = 20, effort = 0.5)F <- getFMortGear(sim)F <- getFMortGear(sim, time_range = c(10, 20))Get feeding level
Description
Returns the feeding level.By default this function usesmizerFeedingLevel() to calculatethe feeding level, but this can be overruled viasetRateFunction().
Usage
getFeedingLevel(object, n, n_pp, n_other, time_range, drop = FALSE, ...)Arguments
object | A |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
time_range | A vector of times. Only the range of times is relevant,i.e., all times between the smallest and largest will be selected.The time_range can be character or numeric. |
drop | If |
... | Unused |
Value
If aMizerParams object is passed in, the function returns a twodimensional array (predator species x predator size) based on theabundances also passed in.If aMizerSim object is passed in, the function returns a threedimensional array (time step x predator species x predator size) with thefeeding level calculated at every time step in the simulation.Ifdrop = TRUE then the dimension of length 1 will be removed fromthe returned array.
Feeding level
The feeding levelf_i(w) is theproportion of its maximum intake rate at which the predator is actuallytaking in fish. It is calculated from the encounter rateE_i and themaximum intake rateh_i(w) as
f_i(w) = \frac{E_i(w)}{E_i(w)+h_i(w)}.
The encounter rateE_i is passed as an argument or calculated withgetEncounter(). The maximum intake rateh_i(w) istaken from theparams object, and is set withsetMaxIntakeRate().As a consequence of the above expression for the feeding level,1-f_i(w) is the proportion of the food available to it that thepredator actually consumes.
Your own feeding level function
By defaultgetFeedingLevel() callsmizerFeedingLevel(). However you canreplace this with your own alternative feeding level function. Ifyour function is called"myFeedingLevel" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "FeedingLevel", "myFeedingLevel")
Your function will then be called instead ofmizerFeedingLevel(), with thesame arguments.
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getMort(),getPredMort(),getPredRate(),getRDD(),getRDI(),getRates(),getResourceMort()
Examples
params <- NS_params# Get initial feeding levelfl <- getFeedingLevel(params)# Project with constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get the feeding level at all saved time stepsfl <- getFeedingLevel(sim)# Get the feeding level for years 15 - 20fl <- getFeedingLevel(sim, time_range = c(15, 20))Get growth curves giving weight as a function of age
Description
Get growth curves giving weight as a function of age
Usage
getGrowthCurves(object, species = NULL, max_age = 20, percentage = FALSE)Arguments
object | MizerSim or MizerParams object. If given aMizerSim object, uses the growth rates at the final time of asimulation to calculate the size at age. If given aMizerParams object, uses the initial growth rates instead. |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
max_age | The age up to which to run the growth curve. Default is 20. |
percentage | Boolean value. If TRUE, the size is given as a percentageof the maximal size. |
Value
An array (species x age) containing the weight in grams.
See Also
Other summary functions:getBiomass(),getDiet(),getN(),getSSB(),getYield(),getYieldGear()
Examples
growth_curves <- getGrowthCurves(NS_params, species = c("Cod", "Haddock"))str(growth_curves)library(ggplot2)ggplot(melt(growth_curves)) + geom_line(aes(Age, value)) + facet_wrap(~ Species, scales = "free") + ylab("Size[g]") + xlab("Age[years]")Deprecated function to get interaction matrix
Description
You should now useinteraction_matrix() instead.
Usage
getInteraction(params)Arguments
params | A MizerParams object |
Alias forgetPredMort()
Description
An alias provided for backward compatibility with mizer version <= 1.0
Usage
getM2(object, n, n_pp, n_other, time_range, drop = TRUE, ...)Arguments
object | A |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
time_range | A vector of times. Only the range of times is relevant,i.e., all times between the smallest and largest will be selected.The time_range can be character or numeric. |
drop | If |
... | Unused |
Value
If aMizerParams object is passed in, the function returns a twodimensional array (prey species x prey size) based on the abundances alsopassed in. If aMizerSim object is passed in, the function returns athree dimensional array (time step x prey species x prey size) with thepredation mortality calculated at every time step in the simulation.Dimensions may be dropped if they have length 1 unlessdrop = FALSE.
Your own predation mortality function
By defaultgetPredMort() callsmizerPredMort(). However you canreplace this with your own alternative predation mortality function. Ifyour function is called"myPredMort" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "PredMort", "myPredMort")
Your function will then be called instead ofmizerPredMort(), with thesame arguments.
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getMort(),getPredRate(),getRDD(),getRDI(),getRates(),getResourceMort()
Examples
params <- NS_params# Predation mortality in initial stateM2 <- getPredMort(params)str(M2)# With constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get predation mortality at one time stepM2 <- getPredMort(params, n = N(sim)[15, , ], n_pp = NResource(sim)[15, ])# Get predation mortality at all saved time stepsM2 <- getPredMort(sim)str(M2)# Get predation mortality over the years 15 - 20M2 <- getPredMort(sim, time_range = c(15, 20))Alias forgetResourceMort()
Description
An alias provided for backward compatibility with mizer version <= 1.0
Usage
getM2Background( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), t = 0, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
... | Unused |
Value
A vector of mortality rate by resource size.
Your own resource mortality function
By defaultgetResourceMort() callsmizerResourceMort(). However you canreplace this with your own alternative resource mortality function. Ifyour function is called"myResourceMort" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "ResourceMort", "myResourceMort")
Your function will then be called instead ofmizerResourceMort(), with thesame arguments.
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getMort(),getPredMort(),getPredRate(),getRDD(),getRDI(),getRates()
Examples
params <- NS_params# With constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get resource mortality at one time stepgetResourceMort(params, n = N(sim)[15, , ], n_pp = NResource(sim)[15, ])Calculate the mean maximum weight of the community
Description
Calculates the mean maximum weight of the community through time. This can becalculated by numbers or biomass. The calculation is the sum of the w_max *abundance of each species, divided by the total abundance community, whereabundance is either in biomass or numbers. You can specify minimum andmaximum weight or length range for the species. Lengths take precedence overweights (i.e. if both min_l and min_w are supplied, only min_l will be used).You can also specify the species to be used in the calculation.
Usage
getMeanMaxWeight(sim, species = NULL, measure = "both", ...)Arguments
sim | AMizerSim object |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
measure | The measure to return. Can be 'numbers', 'biomass' or 'both' |
... | Arguments passed on to
|
Value
Depends on themeasure argument. Ifmeasure = “both”then you get a matrix with two columns, one with values by numbers, theother with values by biomass at each saved time step. Ifmeasure = “numbers” or“biomass” you get a vector of the respective values ateach saved time step.
See Also
Other functions for calculating indicators:getCommunitySlope(),getMeanWeight(),getProportionOfLargeFish()
Examples
mmw <- getMeanMaxWeight(NS_sim)years <- c("1967", "2010")mmw[years, ]getMeanMaxWeight(NS_sim, species=c("Herring","Sprat","N.pout"))[years, ]getMeanMaxWeight(NS_sim, min_w = 10, max_w = 5000)[years, ]Calculate the mean weight of the community
Description
Calculates the mean weight of the community through time. This is simply thetotal biomass of the community divided by the abundance in numbers. You canspecify minimum and maximum weight or length range for the species. Lengthstake precedence over weights (i.e. if both min_l and min_w are supplied, onlymin_l will be used). You can also specify the species to be used in thecalculation.
Usage
getMeanWeight(sim, species = NULL, ...)Arguments
sim | AMizerSim object |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
... | Arguments passed on to
|
Value
A vector containing the mean weight of the community through time
See Also
Other functions for calculating indicators:getCommunitySlope(),getMeanMaxWeight(),getProportionOfLargeFish()
Examples
mean_weight <- getMeanWeight(NS_sim)years <- c("1967", "2010")mean_weight[years]getMeanWeight(NS_sim, species = c("Herring", "Sprat", "N.pout"))[years]getMeanWeight(NS_sim, min_w = 10, max_w = 5000)[years]Get total mortality rate
Description
Calculates the total mortality rate\mu_i(w) (in units 1/year) on eachspecies by size from predation mortality, background mortality and fishingmortality for a single time step.
Usage
getMort( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), effort = getInitialEffort(params), t = 0, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
effort | A numeric vector of the effort by gear or a single numericeffort value which is used for all gears. |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
... | Unused |
Details
If your model contains additional components that you added withsetComponent() and for which you specified amort_fun function thenthe mortality inflicted by these components will be included in the returnedvalue.
Value
A two dimensional array (prey species x prey size).
Your own mortality function
By defaultgetMort() callsmizerMort(). However you canreplace this with your own alternative mortality function. Ifyour function is called"myMort" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "Mort", "myMort")
Your function will then be called instead ofmizerMort(), with thesame arguments.
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getPredMort(),getPredRate(),getRDD(),getRDI(),getRates(),getResourceMort()
Examples
params <- NS_params# Project with constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get the total mortality at a particular time stepmort <- getMort(params, n = N(sim)[15, , ], n_pp = NResource(sim)[15, ], t = 15, effort = 0.5)# Mortality rate at this time for Sprat of size 2gmort["Sprat", "2"]Calculate the number of individuals within a size range
Description
Calculates the number of individuals within user-defined size limits. Thedefault option is to use the whole size range. You can specify minimum andmaximum weight or lengths for the species. Lengths take precedence overweights (i.e. if both min_l and min_w are supplied, only min_l will be used)
Usage
getN(object, ...)Arguments
object | An object of class |
... | Arguments passed on to
|
Value
If called with a MizerParams object, a vector with the numbers foreach species in the model. If called with a MizerSim object, an array (timex species) containing the numbers at each time step for all species.
See Also
Other summary functions:getBiomass(),getDiet(),getGrowthCurves(),getSSB(),getYield(),getYieldGear()
Examples
numbers <- getN(NS_sim)numbers["1972", "Herring"]# The above gave a huge number, because that included all the larvae.# The number of Herrings between 10g and 1kg is much smaller.numbers <- getN(NS_sim, min_w = 10, max_w = 1000)numbers["1972", "Herring"]Extract the parameter object underlying a simulation
Description
Extract the parameter object underlying a simulation
Usage
getParams(sim)Arguments
sim | A MizerSim object |
Value
The MizerParams object that was used to run the simulation
Examples
# This will be identical to the params object that was used to create the# simulationsim <- project(NS_params, t_max = 1)identical(getParams(sim), NS_params)Get available energy
Description
This is deprecated and is no longer used by the mizer project() method.Calculates the amountE_{a,i}(w) of food exposed to each predator asa function of predator size.
Usage
getPhiPrey(object, n, n_pp, ...)Arguments
object | AnMizerParams object |
n | A matrix of species abundances (species x size) |
n_pp | A vector of the background abundance by size |
... | Other arguments (currently unused) |
Value
A two dimensional array (predator species x predator size)
See Also
Examples
params <- NS_paramssim <- project(params, t_max = 20, effort = 0.5)n <- sim@n[21,,]n_pp <- sim@n_pp[21,]getPhiPrey(params,n,n_pp)# ->getEncounter(params) / getSearchVolume(params)Get total predation mortality rate
Description
Calculates the total predation mortality rate\mu_{p,i}(w_p) (in unitsof 1/year) on each prey species by prey size:
\mu_{p.i}(w_p) = \sum_j {\tt pred\_rate}_j(w_p)\, \theta_{ji}.
The predation ratepred_rate is returned bygetPredRate().
Usage
getPredMort(object, n, n_pp, n_other, time_range, drop = TRUE, ...)Arguments
object | A |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
time_range | A vector of times. Only the range of times is relevant,i.e., all times between the smallest and largest will be selected.The time_range can be character or numeric. |
drop | If |
... | Unused |
Value
If aMizerParams object is passed in, the function returns a twodimensional array (prey species x prey size) based on the abundances alsopassed in. If aMizerSim object is passed in, the function returns athree dimensional array (time step x prey species x prey size) with thepredation mortality calculated at every time step in the simulation.Dimensions may be dropped if they have length 1 unlessdrop = FALSE.
Your own predation mortality function
By defaultgetPredMort() callsmizerPredMort(). However you canreplace this with your own alternative predation mortality function. Ifyour function is called"myPredMort" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "PredMort", "myPredMort")
Your function will then be called instead ofmizerPredMort(), with thesame arguments.
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getMort(),getPredRate(),getRDD(),getRDI(),getRates(),getResourceMort()
Examples
params <- NS_params# Predation mortality in initial stateM2 <- getPredMort(params)str(M2)# With constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get predation mortality at one time stepM2 <- getPredMort(params, n = N(sim)[15, , ], n_pp = NResource(sim)[15, ])# Get predation mortality at all saved time stepsM2 <- getPredMort(sim)str(M2)# Get predation mortality over the years 15 - 20M2 <- getPredMort(sim, time_range = c(15, 20))Get predation rate
Description
Calculates the potential rate (in units 1/year) at which a prey individual ofa given sizew is killed by predators from speciesj. In formulas
{\tt pred\_rate}_j(w_p) = \int \phi_j(w,w_p) (1-f_j(w)) \gamma_j(w) N_j(w) \, dw.
This potential rate is used ingetPredMort() tocalculate the realised predation mortality rate on the prey individual.
Usage
getPredRate( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), t = 0, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
... | Unused |
Value
A two dimensional array (predator species x prey size),where the prey size runs over fish community plus resource spectrum.
Your own predation rate function
By defaultgetPredRate() callsmizerPredRate(). However you canreplace this with your own alternative predation rate function. Ifyour function is called"myPredRate" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "PredRate", "myPredRate")
Your function will then be called instead ofmizerPredRate(), withthe same arguments.
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getMort(),getPredMort(),getRDD(),getRDI(),getRates(),getResourceMort()
Examples
params <- NS_params# Predation rate in initial statepred_rate <- getPredRate(params)str(pred_rate)# With constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get the feeding level at one time steppred_rate <- getPredRate(params, n = N(sim)[15, , ], n_pp = NResource(sim)[15, ], t = 15)Calculate the proportion of large fish
Description
Calculates the proportion of large fish through time in theMizerSimclass within user defined size limits. The default option is to use the wholesize range. You can specify minimum and maximum size ranges for the speciesand also the threshold size for large fish. Sizes can be expressed as weightor size. Lengths take precedence over weights (i.e. if both min_l and min_ware supplied, only min_l will be used). You can also specify the species tobe used in the calculation. This function can be used to calculate the LargeFish Index. The proportion is based on either abundance or biomass.
Usage
getProportionOfLargeFish( sim, species = NULL, threshold_w = 100, threshold_l = NULL, biomass_proportion = TRUE, ...)Arguments
sim | AMizerSim object |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
threshold_w | the size used as the cutoff between large and small fish.Default value is 100. |
threshold_l | the size used as the cutoff between large and small fish. |
biomass_proportion | a boolean value. If TRUE the proportion calculatedis based on biomass, if FALSE it is based on numbers of individuals.Default is TRUE. |
... | Arguments passed on to
|
Value
A vector containing the proportion of large fish through time
See Also
Other functions for calculating indicators:getCommunitySlope(),getMeanMaxWeight(),getMeanWeight()
Examples
lfi <- getProportionOfLargeFish(NS_sim, min_w = 10, max_w = 5000, threshold_w = 500)years <- c("1972", "2010")lfi[years]getProportionOfLargeFish(NS_sim)[years]getProportionOfLargeFish(NS_sim, species=c("Herring","Sprat","N.pout"))[years]getProportionOfLargeFish(NS_sim, min_w = 10, max_w = 5000)[years]getProportionOfLargeFish(NS_sim, min_w = 10, max_w = 5000, threshold_w = 500, biomass_proportion = FALSE)[years]Get density dependent reproduction rate
Description
Calculates the density dependent rate of egg productionR_i (units1/year) for each species. This is the flux entering the smallest size classof each species. The density dependent rate is the density independentrate obtained withgetRDI() after it has been put through thedensity dependence function. This is the Beverton-Holt functionBevertonHoltRDD() by default, but this can be changed. SeesetReproduction() for more details.
Usage
getRDD( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), t = 0, rdi = getRDI(params, n = n, n_pp = n_pp, n_other = n_other, t = t), ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
rdi | A vector of density-independent reproduction rates for eachspecies. If not specified, rdi is calculated internally using |
... | Unused |
Value
A numeric vector the length of the number of species.
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getMort(),getPredMort(),getPredRate(),getRDI(),getRates(),getResourceMort()
Examples
params <- NS_params# Project with constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get the rate at a particular time stepgetRDD(params, n = N(sim)[15, , ], n_pp = NResource(sim)[15, ], t = 15)Get density independent rate of egg production
Description
Calculates the density-independent rate of total egg productionR_{di} (units 1/year) before density dependence, by species.
Usage
getRDI( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), t = 0, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
... | Unused |
Details
This rate is obtained by taking the per capita rateE_r(w)\psi(w) atwhich energy is invested in reproduction, as calculated bygetERepro(),multiplying it by the number of individualsN(w) and integrating overall sizesw and then multiplying by the reproductive efficiency\epsilon and dividing by the egg sizew_min, and by a factor of twoto account for the two sexes:
R_{di} = \frac{\epsilon}{2 w_{min}} \int N(w) E_r(w) \psi(w) \, dw
Used bygetRDD() to calculate the actual, density dependent rate.SeesetReproduction() for more details.
Value
A numeric vector the length of the number of species.
Your own reproduction function
By defaultgetRDI() callsmizerRDI(). However you canreplace this with your own alternative reproduction function. Ifyour function is called"myRDI" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "RDI", "myRDI")
Your function will then be called instead ofmizerRDI(), with thesame arguments. For an example of an alternative reproduction functionseeconstantEggRDI().
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getMort(),getPredMort(),getPredRate(),getRDD(),getRates(),getResourceMort()
Examples
params <- NS_params# Project with constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get the density-independent reproduction rate at a particular time stepgetRDI(params, n = N(sim)[15, , ], n_pp = NResource(sim)[15, ], t = 15)Get all rates
Description
Calls other rate functions in sequence and collects the results in a list.
Usage
getRates( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), effort, t = 0, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
effort | The effort for each fishing gear |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
... | Unused |
Details
By default this function returns a list with the following components:
encounter from
mizerEncounter()feeding_level from
mizerFeedingLevel()e from
mizerEReproAndGrowth()e_repro from
mizerERepro()e_growth from
mizerEGrowth()pred_rate from
mizerPredRate()pred_mort from
mizerPredMort()f_mort from
mizerFMort()mort from
mizerMort()rdi from
mizerRDI()rdd from
BevertonHoltRDD()resource_mort from
mizerResourceMort()
However you can replace any of these rate functions by your own ratefunction if you wish, seesetRateFunction() for details.
Value
List of rates.
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getMort(),getPredMort(),getPredRate(),getRDD(),getRDI(),getResourceMort()
Examples
rates <- getRates(NS_params)names(rates)identical(rates$encounter, getEncounter(NS_params))Get reproduction level
Description
The reproduction level is the ratio between the density-dependentreproduction rate and the maximal reproduction rate.
Usage
getReproductionLevel(params)Arguments
params | A MizerParams object |
Value
A named vector with the reproduction level for each species.
Examples
getReproductionLevel(NS_params)# The reproduction level can be changed without changing the steady state:params <- setBevertonHolt(NS_params, reproduction_level = 0.9)getReproductionLevel(params)# The result is the ratio of RDD and R_maxidentical(getRDD(params) / species_params(params)$R_max, getReproductionLevel(params))Deprecated functions for getting resource parameters
Description
Use
resource_dynamics(),resource_level(),resource_rate() andresource_capacity() instead.
Usage
getResourceDynamics(params)getResourceLevel(params)getResourceRate(params)getResourceCapacity(params)Arguments
params | A MizerParams object |
Value
Name of the function that determines the resource dynamics
Get predation mortality rate for resource
Description
Calculates the predation mortality rate\mu_p(w) on the resourcespectrum by resource size (in units 1/year).
Usage
getResourceMort( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), t = 0, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
... | Unused |
Value
A vector of mortality rate by resource size.
Your own resource mortality function
By defaultgetResourceMort() callsmizerResourceMort(). However you canreplace this with your own alternative resource mortality function. Ifyour function is called"myResourceMort" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "ResourceMort", "myResourceMort")
Your function will then be called instead ofmizerResourceMort(), with thesame arguments.
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getMort(),getPredMort(),getPredRate(),getRDD(),getRDI(),getRates()
Examples
params <- NS_params# With constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get resource mortality at one time stepgetResourceMort(params, n = N(sim)[15, , ], n_pp = NResource(sim)[15, ])Calculate the SSB of species
Description
Calculates the spawning stock biomass (SSB) through time of the species intheMizerSim class. SSB is calculated as the total mass of all matureindividuals.
Usage
getSSB(object)Arguments
object | An object of class |
Value
If called with a MizerParams object, a vector with the SSB ingrams for each species in the model. If called with a MizerSim object, anarray (time x species) containing the SSB in grams at each time stepfor all species.
See Also
Other summary functions:getBiomass(),getDiet(),getGrowthCurves(),getN(),getYield(),getYieldGear()
Examples
ssb <- getSSB(NS_sim)ssb[c("1972", "2010"), c("Herring", "Cod")]Times for which simulation results are available
Description
Times for which simulation results are available
Usage
getTimes(sim)Arguments
sim | A MizerSim object |
Value
A numeric vectors of the times (in years) at which simulation resultshave been stored in the MizerSim object.
Examples
getTimes(NS_sim)Calculate the rate at which biomass of each species is fished
Description
This yield rate is given in grams per year. It is calculated at each timestep saved in the MizerSim object.
Usage
getYield(object)Arguments
object | An object of class |
Details
The yield ratey_i(t) for speciesi at timet is defined as
y_i(t)=\int\mu_{f.i}(w, t)N_i(w, t)w dw
where\mu_{f.i}(w, t) is the fishing mortality of an individual ofspeciesi and weightw at timet andN_i(w, t) is theabundance density of such individuals. The factor ofw converts theabundance density into a biomass density and the integral aggregates thecontribution from all sizes.
The total catch in a time period fromt_1 tot_2 is the integralof the yield rate over that period:
C = \int_{t_1}^{t2}y_i(t)dt
In practice, as the yield rate is only availableat the saved times, one can only approximate this integral by averaging overthe available yield rates during the time period and multiplying by the timeperiod. The less the yield changes between the saved values, the moreaccurate this approximation is. So the approximation can be improved bysaving simulation results at smaller intervals, using thet_save argumenttoproject(). But this is only a concern if abundances change quicklyduring the time period of interest.
Value
If called with a MizerParams object, a vector with the yield rate ingrams per year for each species in the model. If called with a MizerSimobject, an array (time x species) containing the yield rate at each timestep for all species.
See Also
Other summary functions:getBiomass(),getDiet(),getGrowthCurves(),getN(),getSSB(),getYieldGear()
Examples
yield <- getYield(NS_sim)yield[c("1972", "2010"), c("Herring", "Cod")]# Running simulation for another year, saving intermediate time stepsparams <- setInitialValues(getParams(NS_sim), NS_sim)sim <- project(params, t_save = 0.1, t_max = 1, t_start = 2010, progress_bar = FALSE)# The yield rate for Herring decreases during the yeargetYield(sim)[, "Herring"]# We get the total catch in the year by averaging over the yearsum(getYield(sim)[1:10, "Herring"] / 10)Calculate the rate at which biomass of each species is fished by each gear
Description
This yield rate is given in grams per year. It is calculated at each timestep saved in the MizerSim object.
Usage
getYieldGear(object)Arguments
object | An object of class |
Details
For details of how the yield rate is defined see the help page ofgetYield().
Value
If called with a MizerParams object, an array (gear x species) withthe yield rate in grams per year from each gear for each species in themodel. If called with a MizerSim object, an array (time x gear x species)containing the yield rate at each time step.
See Also
Other summary functions:getBiomass(),getDiet(),getGrowthCurves(),getN(),getSSB(),getYield()
Examples
yield <- getYieldGear(NS_sim)yield["1972", "Herring", "Herring"]# (In this example MizerSim object each species was set up with its own gear)Alias forgetMort()
Description
An alias provided for backward compatibility with mizer version <= 1.0
Usage
getZ( params, n = initialN(params), n_pp = initialNResource(params), n_other = initialNOther(params), effort = getInitialEffort(params), t = 0, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
effort | A numeric vector of the effort by gear or a single numericeffort value which is used for all gears. |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
... | Unused |
Details
If your model contains additional components that you added withsetComponent() and for which you specified amort_fun function thenthe mortality inflicted by these components will be included in the returnedvalue.
Value
A two dimensional array (prey species x prey size).
Your own mortality function
By defaultgetMort() callsmizerMort(). However you canreplace this with your own alternative mortality function. Ifyour function is called"myMort" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "Mort", "myMort")
Your function will then be called instead ofmizerMort(), with thesame arguments.
See Also
Other rate functions:getEGrowth(),getERepro(),getEReproAndGrowth(),getEncounter(),getFMort(),getFMortGear(),getFeedingLevel(),getPredMort(),getPredRate(),getRDD(),getRDI(),getRates(),getResourceMort()
Examples
params <- NS_params# Project with constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# Get the total mortality at a particular time stepmort <- getMort(params, n = N(sim)[15, , ], n_pp = NResource(sim)[15, ], t = 15, effort = 0.5)# Mortality rate at this time for Sprat of size 2gmort["Sprat", "2"]Get default value for f0
Description
Fills in any missing values for f0 so that if the prey abundance wasdescribed by the power law\kappa w^{-\lambda} then the encounter ratecoming from the givengamma parameter would lead to the feeding levelf_0. This is thus doing the inverse ofget_gamma_default().Only for internal use.
Usage
get_f0_default(params)Arguments
params | A MizerParams object |
Details
For species for which no value forgamma is specified in the speciesparameter data frame, thef0 values is kept as provided in the speciesparameter data frame or it is set to 0.6 if it is not provided.
Value
A vector with the values of f0 for all species
See Also
Other functions calculating defaults:get_gamma_default(),get_h_default(),get_ks_default()
Get default value for gamma
Description
Fills in any missing values for gamma so that fish feeding on a resourcespectrum described by the power law\kappa w^{-\lambda} achieve afeeding levelf_0. Only for internal use.
Usage
get_gamma_default(params)Arguments
params | A MizerParams object |
Value
A vector with the values of gamma for all species
See Also
Other functions calculating defaults:get_f0_default(),get_h_default(),get_ks_default()
Get default value for h
Description
Setsh so that the species reaches maturity sizew_mat at the maturityageage_mat if it feeds at feeding levelf0.
Usage
get_h_default(params)Arguments
params | A MizerParams object or a species parameter data frame |
Details
Ifage_mat is missing in the species parameter data frame, then it iscalculated from the von Bertalanffy growth curve parametersk_vb and(optionallyt0) taken from the species parameter data frame. This is notreliable and a warning is issued.
If no growth information is given at all for a species, the default is settoh = 30.
Value
A vector with the values of h for all species
See Also
Other functions calculating defaults:get_f0_default(),get_gamma_default(),get_ks_default()
Calculate initial population abundances
Description
This function uses the model parameters and other parameters to calculateinitial values for the species number densities. These initialabundances are currently quite arbitrary and not close to the steady state.We intend to improve this in the future.
Usage
get_initial_n(params, n0_mult = NULL, a = 0.35)Arguments
params | The model parameters. An object of typeMizerParams. |
n0_mult | Multiplier for the abundance at size 0. Default value iskappa/1000. |
a | A parameter with a default value of 0.35. |
Value
A matrix (species x size) of population abundances.
Examples
init_n <- get_initial_n(NS_params)Get default value forks
Description
Fills in any missing values forks so that the critical feeding level neededto sustain the species is as specified in thefc column in the speciesparameter data frame. If that column is not provided the default criticalfeeding levelf_c = 0.2 is used.
Usage
get_ks_default(params)Arguments
params | A MizerParams object |
Value
A vector with the values of ks for all species
See Also
Other functions calculating defaults:get_f0_default(),get_gamma_default(),get_h_default()
Get values from feeding kernel function
Description
This involves finding the feeding kernel function for each species, using thepred_kernel_type parameter in the species_params data frame, checking that itis valid and all its arguments are contained in the species_params dataframe, and then calling this function with the ppmr vector.
Usage
get_phi(species_params, ppmr)Arguments
species_params | A species parameter data frame |
ppmr | Values of the predator/prey mass ratio at which to evaluate thepredation kernel function |
Value
An array (species x ppmr) with the values of the predation kernelfunction
Determine reproduction rate needed for initial egg abundance
Description
Determine reproduction rate needed for initial egg abundance
Usage
get_required_reproduction(params)Arguments
params | A MizerParams object |
Value
A vector of reproduction rates for all species
Get size range array
Description
Helper function that returns an array (species x size) of boolean valuesindicating whether that size bin is within the size limits specified by thearguments. Either the size limits can be the same for all species or theycan be specified as vectors with one value for each species in the model.
Usage
get_size_range_array( params, min_w = min(params@w), max_w = max(params@w), min_l = NULL, max_l = NULL, ...)Arguments
params | MizerParams object |
min_w | Smallest weight in size range. Defaults to smallest weight inthe model. |
max_w | Largest weight in size range. Defaults to largest weight in themodel. |
min_l | Smallest length in size range. If supplied, this takesprecedence over |
max_l | Largest length in size range. If supplied, this takes precedenceover |
... | Unused |
Value
Boolean array (species x size)
Length to weight conversion
Ifmin_l is specified there is no need to specifymin_w and so on.However, if a length is specified (minimum or maximum) then it is necessaryfor the species parameter data.frame to include the parametersa andbthat determine the relation between lengthl and weightw by
w = a l^b.
It is possible to mix length and weight constraints, e.g. by supplying aminimum weight and a maximum length, but this must be done the same forall species. The default values are the minimum andmaximum weights of the spectrum, i.e., the full range of the size spectrum isused.
Get_time_elements
Description
Internal function to get the array element references of the time dimensionfor the time based slots of a MizerSim object.
Usage
get_time_elements(sim, time_range, slot_name = "n")Arguments
sim | A MizerSim object |
time_range | A vector of times. Only the range of times is relevant,i.e., all times between the smallest and largest will be selected.The time_range can be character or numeric. |
slot_name | Obsolete. Was only needed in early versions of mizer wherethe effort slot could have different time dimension from the other slots. |
Value
Named boolean vector indicating for each time whether it is includedin the range or not.
Description of indicator functions
Description
Mizer provides a range of functions to calculate indicatorsfrom a MizerSim object.
Details
A list of available indicator functions for MizerSim objects is given in the table below
| Function | Returns | Description |
getProportionOfLargeFish() | A vector with values at each time step. | Calculates the proportion of large fish through time. The threshold value can be specified. It is possible to calculation the proportion of large fish based on either length or weight. |
getMeanWeight() | A vector with values at each saved time step. | The mean weight of the community through time. This is calculated as the total biomass of the community divided by the total abundance. |
getMeanMaxWeight() | Depends on the measure argument. If measure = “both” then you get a matrix with two columns, one with values by numbers, the other with values by biomass at each saved time step. If measure = “numbers” or “biomass” you get a vector of the respective values at each saved time step | The mean maximum weight of the community through time. This can be calculated by numbers or by biomass. See the help file for more details. |
getCommunitySlope() | A data.frame with four columns: time step, slope, intercept and the coefficient of determination. | Calculates the slope of the community abundance spectrum through time by performing a linear regression on the logged total numerical abundance and logged body size. |
See Also
summary_functions,plotting_functions
Initial values for fish spectra
Description
Values used as starting values for simulations withproject().
Usage
initialN(params) <- valueinitialN(object)Arguments
params | A MizerParams object |
value | A matrix with dimensions species x size holding the initialnumber densities for the fish spectra. |
object | An object of class MizerParams or MizerSim |
Value
A matrix with dimensions species x size holding the initial numberdensities for the fish spectra.
See Also
initialNResource(),initialNOther()
Examples
# Doubling abundance of Cod in the initial state of the North Sea modelparams <- NS_paramsinitialN(params)["Cod", ] <- 2 * initialN(params)["Cod", ]# Calculating the corresponding initial biomassbiomass <- initialN(params)["Cod", ] * dw(NS_params) * w(NS_params)# Of course this initial state will no longer be a steady stateparams <- steady(params)Initial values for other ecosystem components
Description
Values used as starting values for simulations withproject().
Usage
initialNOther(params) <- valueinitialNOther(object)Arguments
params | A MizerParams object |
value | A named list with the initial values of other ecosystemcomponents |
object | An object of class MizerParams or MizerSim |
Value
A named list with the initial values of other ecosystemcomponents
See Also
Initial value for resource spectrum
Description
Value used as starting value for simulations withproject().
Usage
initialNResource(params) <- valueinitialNResource(object)Arguments
params | A MizerParams object |
value | A vector with the initial number densities for the resourcespectrum |
object | An object of class MizerParams or MizerSim |
Value
A vector with the initial number densities for the resourcespectrum
See Also
Examples
# Doubling resource abundance in the initial state of the North Sea modelparams <- NS_paramsinitialNResource(params) <- 2 * initialNResource(params)# Of course this initial state will no longer be a steady stateparams <- steady(params)Initial fishing effort
Description
The fishing effort is a named vector, specifying for each fishing gear theeffort invested into fishing with that gear. The effort value for each gearis multiplied by the catchability and the selectivity to determine thefishing mortality imposed by that gear, seesetFishing() for more details.The initial effort you have set can be overruled when running a simulationby providing aneffort argument toproject() which allows you tospecify a time-varying effort.
Usage
initial_effort(params)initial_effort(params) <- valuevalidEffortVector(effort, params)Arguments
params | A MizerParams object |
value | A vector or scalar with the initial fishing effort, see Detailsbelow. |
effort | A vector or scalar with the initial fishing effort, see Detailsbelow. |
Details
A valid effort vector is a named vector with one effort value for each gear.However you can also supply the effort value in different ways:
a scalar, which is then replicated for each gear
an unnamed vector, which is then assumed to be in the same order as thegears in the params object
a named vector in which the gear names have a different order than in theparams object. This is then sorted correctly.
a named vector which only supplies values for some of the gears.The effort for the other gears is then set to zero.
These conversions are done by the functionvalidEffortVector().
Aneffort argument will lead to an error if it is either
unnamed and of the wrong length
named but where some names do not match any of the gears
not numeric
Value
Effort vector
Alias forNS_interaction
Description
An alias provided for backward compatibility with mizer version <= 2.3
Usage
interFormat
A 12 x 12 matrix.
Source
Blanchard et al.
Weight based knife-edge selectivity function
Description
A knife-edge selectivity function where weights greater or equal toknife_edge_size are fully selected and no fish smaller than this sizeare selected.
Usage
knife_edge(w, knife_edge_size, ...)Arguments
w | Vector of sizes. |
knife_edge_size | The weight at which the knife-edge operates. |
... | Unused |
Value
Vector of selectivities at the given sizes.
See Also
gear_params() for setting theknife_edge_size parameter.
Other selectivity functions:double_sigmoid_length(),sigmoid_length(),sigmoid_weight()
Length-weight conversion
Description
For each species, convert between length and weight using the relationship
w_i = a_i l_i^{b_i}
or
l_i = (w_i / a_i)^{1/b_i}
wherea andb are taken from the species parameter data frame andi is the species index.
Usage
l2w(l, species_params)w2l(w, species_params)Arguments
l | Lengths in cm. Either a single number used for all species or avector with one number for each species. |
species_params | A species parameter data frame or a MizerParams object. |
w | Weights in grams. Either a single number used for all species or avector with one number for each species. |
Details
This is useful for converting a length-based species parameter to aweight-based species parameter.
If anya orb parameters are missing the default valuesa = 0.01 andb = 3 are used for the missing values.
Value
A vector with one entry for each species.l2w() returns a vectorof weights in grams andw2l() returns a vector of lengths in cm.
Helper function to produce nice breaks on logarithmic axes
Description
This is needed when the logarithmic y-axis spans less than one order ofmagnitude, in which case the ggplot2 default produces no ticks.
Usage
log_breaks(n = 6)Arguments
n | Approximate number of ticks |
Details
Thanks to Heather Turner athttps://stackoverflow.com/questions/14255533/pretty-ticks-for-log-normal-scale-using-ggplot2-dynamic-not-manual
Value
A function that can be used as the break argument in calls toscale_y_continuous() or scale_x_continuous()
Lognormal predation kernel
Description
This is the most commonly-used predation kernel. The log of the predator/preymass ratio is normally distributed.
Usage
lognormal_pred_kernel(ppmr, beta, sigma)Arguments
ppmr | A vector of predator/prey size ratios |
beta | The preferred predator/prey size ratio |
sigma | The width parameter of the log-normal kernel |
Details
Writing the predator mass asw and the prey mass asw_p,the feeding kernel is given as
\phi_i(w, w_p) =\exp \left[ \frac{-(\ln(w / w_p / \beta_i))^2}{2\sigma_i^2} \right]
ifw/w_p is larger than 1 and zero otherwise. Here\beta_i is thepreferred predator-prey mass ratio and\sigma_i determines the width ofthe kernel. These two parameters need to be given in the species parameterdataframe in the columnsbeta andsigma.
This function is called fromsetPredKernel() to set up thepredation kernel slots in a MizerParams object.
Value
A vector giving the value of the predation kernel at each of thepredator/prey mass ratios in theppmr argument.
See Also
Other predation kernel:box_pred_kernel(),power_law_pred_kernel(),truncated_lognormal_pred_kernel()
Examples
params <- NS_paramsplot(w_full(params), getPredKernel(params)["Cod", 10, ], type="l", log="x")# The restriction that the kernel is zero for w/w_p < 1 is more# noticeable for larger sigmaspecies_params(params)$sigma <- 4plot(w_full(params), getPredKernel(params)["Cod", 10, ], type="l", log="x")Match biomasses to observations
Description
The function adjusts the abundances of the species in the model so that theirbiomasses match with observations.
Usage
matchBiomasses(params, species = NULL)Arguments
params | A MizerParams object |
species | The species to be affected. Optional. By default all observedbiomasses will be matched. A vector of species names, or a numeric vectorwith the species indices, or a logical vector indicating for each specieswhether it is to be affected (TRUE) or not. |
Details
The function works by multiplying for each species the abundance densityat all sizes by the same factor. This will of course not give a steadystate solution, even if the initial abundance densities were at steady state.So after using this function you may want to usesteady() to run the modelto steady state, after which of course the biomasses will no longer matchexactly. You could then iterate this process. This is described in theblog post at https://bit.ly/2YqXESV.
Before you can use this function you will need to have added abiomass_observed column to your model which gives the observed biomass ingrams. For species for which you have no observed biomass, you should setthe value in thebiomass_observed column to 0 or NA.
Biomass observations usually only include individuals above a certain size.This size should be specified in abiomass_cutoff column of the speciesparameter data frame. If this is missing, it is assumed that all sizes areincluded in the observed biomass, i.e., it includes larval biomass.
Value
A MizerParams object
Examples
params <- NS_paramsspecies_params(params)$biomass_observed <- c(0.8, 61, 12, 35, 1.6, 20, 10, 7.6, 135, 60, 30, 78)species_params(params)$biomass_cutoff <- 10params <- calibrateBiomass(params)params <- matchBiomasses(params)plotBiomassObservedVsModel(params)Adjust model to produce observed growth
Description
Scales the search volume, the maximum consumption rate, the metabolic rateand the external encounter rateall by the same factor in order to achieve a growth rate that allowsindividuals to reach their maturity size by their maturity age while keepingthe feeding level and the critical feeding level unchanged. Then recalculatesthe size spectra usingsteadySingleSpecies().
Usage
matchGrowth(params, species = NULL, keep = c("egg", "biomass", "number"))Arguments
params | A MizerParams object |
species | The species to be affected. Optional. By default all speciesfor which growth information is available will be affected. A vector ofspecies names, or a numeric vector with the species indices, or a logicalvector indicating for each species whether it is to be affected (TRUE) ornot. |
keep | A string determining which quantity is to be kept constant. Thechoices are "egg" which keeps the egg density constant, "biomass" whichkeeps the total biomass of the species constant and "number" which keepsthe total number of individuals constant. |
Details
Maturity size and age are taken from thew_mat andage_mat columns in thespecies_params data frame. Ifage_mat is missing, mizer calculates it fromthe von Bertalanffy growth curve parameters usingage_mat_vB(). If thoseare not available either for a species, the growth rate for that species willnot be changed.
Value
A modified MizerParams object with rescaled search volume, maximumconsumption rate and metabolic rate and rescaled species parametersgamma,h,ks andk.
Match numbers to observations
Description
The function adjusts the numbers of the species in the model so that theirnumbers match with observations.
Usage
matchNumbers(params, species = NULL)Arguments
params | A MizerParams object |
species | The species to be affected. Optional. By default all observednumbers will be matched. A vector of species names, or a numeric vectorwith the species indices, or a logical vector indicating for each specieswhether it is to be affected (TRUE) or not. |
Details
The function works by multiplying for each species the number densityat all sizes by the same factor. This will of course not give a steadystate solution, even if the initial number densities were at steady state.So after using this function you may want to usesteady() to run the modelto steady state, after which of course the numbers will no longer matchexactly. You could then iterate this process. This is described in theblog post at https://bit.ly/2YqXESV.
Before you can use this function you will need to have added anumber_observed column to your model which gives the observed number ingrams. For species for which you have no observed number, you should setthe value in thenumber_observed column to 0 or NA.
Number observations usually only include individuals above a certain size.This size should be specified in anumber_cutoff column of the speciesparameter data frame. If this is missing, it is assumed that all sizes areincluded in the observed number, i.e., it includes larval number.
Value
A MizerParams object
Examples
params <- NS_paramsspecies_params(params)$number_observed <- c(0.8, 61, 12, 35, 1.6, 20, 10, 7.6, 135, 60, 30, 78)species_params(params)$number_cutoff <- 10params <- calibrateNumber(params)params <- matchNumbers(params)Match yields to observations
Description
This function has been deprecated and will be removed in the future unlessyou have a use case for it. If you do have a use case for it, please let thedevelopers know by creating an issue athttps://github.com/sizespectrum/mizer/issues.
Usage
matchYields(params, species = NULL)Arguments
params | A MizerParams object |
species | The species to be affected. Optional. By default all observedyields will be matched. A vector of species names, or a numeric vectorwith the species indices, or a logical vector indicating for each specieswhether it is to be affected (TRUE) or not. |
Details
If you want to match the yields to observations, you should use thematchYield() function from the mizerExperimental package instead, whichadjusts the catchability to match the yield rather than by adjusting thebiomass.
The function adjusts the abundances of the species in the model so that theiryearly yields under the given fishing mortalities match with observations.
The function works by multiplying for each species the abundance densityat all sizes by the same factor. This will of course not give a steadystate solution, even if the initial abundance densities were at steady state.So after using this function you may want to usesteady() to run the modelto steady state, after which of course the yields will no longer matchexactly. You could then iterate this process. This is described in theblog post at https://bit.ly/2YqXESV.
Before you can use this function you will need to have added ayield_observed column to your model which gives the observed yields ingrams per year. For species for which you have no observed biomass, youshould set the value in theyield_observed column to 0 or NA.
Value
A MizerParams object
Examples
params <- NS_paramsspecies_params(params)$yield_observed <- c(0.8, 61, 12, 35, 1.6, 20, 10, 7.6, 135, 60, 30, 78)gear_params(params)$catchability <- c(1.3, 0.065, 0.31, 0.18, 0.98, 0.24, 0.37, 0.46, 0.18, 0.30, 0.27, 0.39)params <- calibrateYield(params)params <- matchYields(params)plotYieldObservedVsModel(params)Get energy rate available for growth needed to project standard mizer model
Description
Calculates the energy rateg_i(w) (grams/year) available by species andsize for growth after metabolism, movement and reproduction have beenaccounted for. Used byproject() for performing simulations.You would not usually call thisfunction directly but instead usegetEGrowth(), which then calls thisfunction unless an alternative function has been registered, see below.
Usage
mizerEGrowth(params, n, n_pp, n_other, t, e_repro, e, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
e_repro | The energy available for reproduction as calculated by |
e | The energy available for reproduction and growth as calculated by |
... | Unused |
Value
A two dimensional array (species x size) with the growth rates.
Your own growth rate function
By defaultgetEGrowth() callsmizerEGrowth(). However you canreplace this with your own alternative growth rate function. Ifyour function is called"myEGrowth" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "EGrowth", "myEGrowth")
Your function will then be called instead ofmizerEGrowth(), with thesame arguments.
See Also
Other mizer rate functions:mizerERepro(),mizerEReproAndGrowth(),mizerEncounter(),mizerFMort(),mizerFMortGear(),mizerFeedingLevel(),mizerMort(),mizerPredMort(),mizerPredRate(),mizerRDI(),mizerRates(),mizerResourceMort()
Get energy rate available for reproduction needed to project standard mizermodel
Description
Calculates the energy rate (grams/year) available for reproduction aftergrowth and metabolism have been accounted for.You would not usually call thisfunction directly but instead usegetERepro(), which then calls thisfunction unless an alternative function has been registered, see below.
Usage
mizerERepro(params, n, n_pp, n_other, t, e, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
e | A two dimensional array (species x size) holding the energy availablefor reproduction and growth as calculated by |
... | Unused |
Value
A two dimensional array (species x size) holding
\psi_i(w)E_{r.i}(w)
whereE_{r.i}(w) is the rate at which energy becomes available forgrowth and reproduction, calculated withmizerEReproAndGrowth(),and\psi_i(w) is the proportion of this energy that is used forreproduction. This proportion is taken from theparams object and isset withsetReproduction().
Your own reproduction rate function
By defaultgetERepro() callsmizerERepro(). However you canreplace this with your own alternative reproduction rate function. Ifyour function is called"myERepro" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "ERepro", "myERepro")
Your function will then be called instead ofmizerERepro(), with thesame arguments.
See Also
Other mizer rate functions:mizerEGrowth(),mizerEReproAndGrowth(),mizerEncounter(),mizerFMort(),mizerFMortGear(),mizerFeedingLevel(),mizerMort(),mizerPredMort(),mizerPredRate(),mizerRDI(),mizerRates(),mizerResourceMort()
Get energy rate available for reproduction and growth needed to projectstandard mizer model
Description
Calculates the energy rateE_{r.i}(w) (grams/year) available to anindividual of species i and size w for reproduction and growth aftermetabolism and movement have been accounted for.You would not usually call this function directly but instead usegetEReproAndGrowth(), which then calls this function unless an alternativefunction has been registered, see below.
Usage
mizerEReproAndGrowth( params, n, n_pp, n_other, t, encounter, feeding_level, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
encounter | An array (species x size) with the encounter rate ascalculated by |
feeding_level | An array (species x size) with the feeding level ascalculated by |
... | Unused |
Value
A two dimensional array (species x size) holding
E_{r.i}(w) = \max(0, \alpha_i\, (1 - {\tt feeding\_level}_i(w))\, {\tt encounter}_i(w) - {\tt metab}_i(w)).
Due to the form of the feeding level, calculated bygetFeedingLevel(), if the feeding level is nonzero this can also be expressed as
E_{r.i}(w) = \max(0, \alpha_i\, {\tt feeding\_level}_i(w)\, h_i(w) - {\tt metab}_i(w))
whereh_i is the maximum intake rate, set withsetMaxIntakeRate(). However this function is using the first equationabove so that it works also when the maximum intake rate is infinite, i.e.,there is no satiation.The assimilation rate\alpha_i is taken from the species parameterdata frame inparams. The metabolic ratemetab is taken fromparams and set withsetMetabolicRate().
The return value can be negative, which means that the energy intake does notcover the cost of metabolism and movement.
Your own energy rate function
By defaultgetEReproAndGrowth() callsmizerEReproAndGrowth(). However youcan replace this with your own alternative energy rate function. Ifyour function is called"myEReproAndGrowth" then you register it in aMizerParams objectparams with
params <- setRateFunction(params, "EReproAndGrowth", "myEReproAndGrowth")
Your function will then be called instead ofmizerEReproAndGrowth(), withthe same arguments.
See Also
Other mizer rate functions:mizerEGrowth(),mizerERepro(),mizerEncounter(),mizerFMort(),mizerFMortGear(),mizerFeedingLevel(),mizerMort(),mizerPredMort(),mizerPredRate(),mizerRDI(),mizerRates(),mizerResourceMort()
Get encounter rate needed to project standard mizer model
Description
Calculates the rateE_i(w) at which a predator of speciesi andweightw encounters food (grams/year). You would not usually call thisfunction directly but instead usegetEncounter(), which then calls thisfunction unless an alternative function has been registered, see below.
Usage
mizerEncounter(params, n, n_pp, n_other, t, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
... | Unused |
Value
A named two dimensional array (predator species x predator size) withthe encounter rates.
Predation encounter
The encounter rateE_i(w) at which a predator of speciesiand weightw encounters food has contributions from the encounter offish prey and of resource. This is determined by summing over all preyspecies and the resource spectrum and then integrating over all prey sizesw_p, weighted by predation kernel\phi(w,w_p):
E_i(w) = \gamma_i(w) \int\left( \theta_{ip} N_R(w_p) + \sum_{j} \theta_{ij} N_j(w_p) \right)\phi_i(w,w_p) w_p \, dw_p.
HereN_j(w) is the abundance density of speciesj andN_R(w) is the abundance density of resource.The overall prefactor\gamma_i(w) determines the predation power of thepredator. It could be interpreted as a search volume and is set with thesetSearchVolume() function. The predation kernel\phi(w,w_p) is set with thesetPredKernel() function. Thespecies interaction matrix\theta_{ij} is set withsetInteraction()and the resource interaction vector\theta_{ip} is taken from theinteraction_resource column inparams@species_params.
Details
The encounter rate is multiplied by1-f_0 to obtain the consumptionrate, wheref_0 is the feeding level calculated withgetFeedingLevel(). This is used by theproject() function for performingsimulations.
The function returns values also for sizes outside the size-range of thespecies. These values should not be used, as they are meaningless.
If your model contains additional components that you added withsetComponent() and for which you specified anencounter_fun function thenthe encounters of these components will be included in the returned value.
Your own encounter function
By defaultgetEncounter() callsmizerEncounter(). However you canreplace this with your own alternative encounter function. Ifyour function is called"myEncounter" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "Encounter", "myEncounter")
Your function will then be called instead ofmizerEncounter(), with thesame arguments.
See Also
Other mizer rate functions:mizerEGrowth(),mizerERepro(),mizerEReproAndGrowth(),mizerFMort(),mizerFMortGear(),mizerFeedingLevel(),mizerMort(),mizerPredMort(),mizerPredRate(),mizerRDI(),mizerRates(),mizerResourceMort()
Get the total fishing mortality rate from all fishing gears
Description
Calculates the total fishing mortality (in units 1/year) from all gears byspecies and size.The total fishing mortality is just the sum of the fishing mortalitiesimposed by each gear,\mu_{f.i}(w)=\sum_g F_{g,i,w}.You would not usually call thisfunction directly but instead usegetFMort(), which then calls thisfunction unless an alternative function has been registered, see below.
Usage
mizerFMort(params, n, n_pp, n_other, t, effort, e_growth, pred_mort, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
effort | A vector with the effort for each fishing gear. |
e_growth | An array (species x size) with the energy available forgrowth as calculated by |
pred_mort | A two dimensional array (species x size) with the predationmortality as calculated by |
... | Unused |
Value
An array (species x size) with the fishing mortality.
Your own fishing mortality function
By defaultgetFMort() callsmizerFMort(). However you canreplace this with your own alternative fishing mortality function. Ifyour function is called"myFMort" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "FMort", "myFMort")
Your function will then be called instead ofmizerFMort(), with thesame arguments.
Note
Here: fishing mortality = catchability x selectivity x effort.
See Also
Other mizer rate functions:mizerEGrowth(),mizerERepro(),mizerEReproAndGrowth(),mizerEncounter(),mizerFMortGear(),mizerFeedingLevel(),mizerMort(),mizerPredMort(),mizerPredRate(),mizerRDI(),mizerRates(),mizerResourceMort()
Get the fishing mortality needed to projectstandard mizer model
Description
Calculates the fishing mortality rateF_{g,i,w} by gear, species andsize.This is a helper function formizerFMort().
Usage
mizerFMortGear(params, effort)Arguments
params | AMizerParams object |
effort | A vector with the effort for each fishing gear. |
Value
An three dimensional array (gear x species x size) with thefishing mortality
Note
Here: fishing mortality = catchability x selectivity x effort.
See Also
Other mizer rate functions:mizerEGrowth(),mizerERepro(),mizerEReproAndGrowth(),mizerEncounter(),mizerFMort(),mizerFeedingLevel(),mizerMort(),mizerPredMort(),mizerPredRate(),mizerRDI(),mizerRates(),mizerResourceMort()
Get feeding level needed to project standard mizer model
Description
You would not usually call this function directly but instead usegetFeedingLevel(), which then calls this function unless an alternativefunction has been registered, see below.
Usage
mizerFeedingLevel(params, n, n_pp, n_other, t, encounter, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
encounter | A two dimensional array (predator species x predator size)with the encounter rate. |
... | Unused |
Value
A two dimensional array (predator species x predator size) with thefeeding level.
Feeding level
The feeding levelf_i(w) is theproportion of its maximum intake rate at which the predator is actuallytaking in fish. It is calculated from the encounter rateE_i and themaximum intake rateh_i(w) as
f_i(w) = \frac{E_i(w)}{E_i(w)+h_i(w)}.
The encounter rateE_i is passed as an argument or calculated withgetEncounter(). The maximum intake rateh_i(w) istaken from theparams object, and is set withsetMaxIntakeRate().As a consequence of the above expression for the feeding level,1-f_i(w) is the proportion of the food available to it that thepredator actually consumes.
Your own feeding level function
By defaultgetFeedingLevel() callsmizerFeedingLevel(). However you canreplace this with your own alternative feeding level function. Ifyour function is called"myFeedingLevel" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "FeedingLevel", "myFeedingLevel")
Your function will then be called instead ofmizerFeedingLevel(), with thesame arguments.
See Also
The feeding level is used inmizerEReproAndGrowth() and inmizerPredRate().
Other mizer rate functions:mizerEGrowth(),mizerERepro(),mizerEReproAndGrowth(),mizerEncounter(),mizerFMort(),mizerFMortGear(),mizerMort(),mizerPredMort(),mizerPredRate(),mizerRDI(),mizerRates(),mizerResourceMort()
Get total mortality rate needed to project standard mizer model
Description
Calculates the total mortality rate\mu_i(w) (in units 1/year) on eachspecies by size from predation mortality, background mortality and fishingmortality.You would not usually call thisfunction directly but instead usegetMort(), which then calls thisfunction unless an alternative function has been registered, see below.
Usage
mizerMort(params, n, n_pp, n_other, t, f_mort, pred_mort, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
f_mort | A two dimensional array (species x size) with the fishingmortality |
pred_mort | A two dimensional array (species x size) with the predationmortality |
... | Unused |
Details
If your model contains additional components that you added withsetComponent() and for which you specified amort_fun function thenthe mortality inflicted by these components will be included in the returnedvalue.
Value
A named two dimensional array (species x size) with the totalmortality rates.
Your own mortality function
By defaultgetMort() callsmizerMort(). However you canreplace this with your own alternative mortality function. Ifyour function is called"myMort" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "Mort", "myMort")
Your function will then be called instead ofmizerMort(), with thesame arguments.
See Also
Other mizer rate functions:mizerEGrowth(),mizerERepro(),mizerEReproAndGrowth(),mizerEncounter(),mizerFMort(),mizerFMortGear(),mizerFeedingLevel(),mizerPredMort(),mizerPredRate(),mizerRDI(),mizerRates(),mizerResourceMort()
Get total predation mortality rate needed to project standard mizer model
Description
Calculates the total predation mortality rate\mu_{p,i}(w_p) (in unitsof 1/year) on each prey species by prey size:
\mu_{p.i}(w_p) = \sum_j {\tt pred\_rate}_j(w_p)\, \theta_{ji}.
You would not usually call thisfunction directly but instead usegetPredMort(), which then calls thisfunction unless an alternative function has been registered, see below.
Usage
mizerPredMort(params, n, n_pp, n_other, t, pred_rate, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
pred_rate | A two dimensional array (predator species x predator size)with the feeding level. |
... | Unused |
Value
A two dimensional array (prey species x prey size) with the predationmortality
Your own predation mortality function
By defaultgetPredMort() callsmizerPredMort(). However you canreplace this with your own alternative predation mortality function. Ifyour function is called"myPredMort" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "PredMort", "myPredMort")
Your function will then be called instead ofmizerPredMort(), with thesame arguments.
See Also
Other mizer rate functions:mizerEGrowth(),mizerERepro(),mizerEReproAndGrowth(),mizerEncounter(),mizerFMort(),mizerFMortGear(),mizerFeedingLevel(),mizerMort(),mizerPredRate(),mizerRDI(),mizerRates(),mizerResourceMort()
Get predation rate needed to project standard mizer model
Description
Calculates the potential rate (in units 1/year) at which a prey individual ofa given sizew is killed by predators from speciesj. In formulas
{\tt pred\_rate}_j(w_p) = \int \phi_j(w,w_p) (1-f_j(w)) \gamma_j(w) N_j(w) \, dw.
This potential rate is used in the functionmizerPredMort() tocalculate the realised predation mortality rate on the prey individual.You would not usually call thisfunction directly but instead usegetPredRate(), which then calls thisfunction unless an alternative function has been registered, see below.
Usage
mizerPredRate(params, n, n_pp, n_other, t, feeding_level, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
feeding_level | An array (species x size) with the feeding level ascalculated by |
... | Unused |
Value
A named two dimensional array (predator species x prey size) with thepredation rate, where the prey size runs over fish community plus resourcespectrum.
Your own predation rate function
By defaultgetPredRate() callsmizerPredRate(). However you canreplace this with your own alternative predation rate function. Ifyour function is called"myPredRate" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "PredRate", "myPredRate")
Your function will then be called instead ofmizerPredRate(), withthe same arguments.
See Also
Other mizer rate functions:mizerEGrowth(),mizerERepro(),mizerEReproAndGrowth(),mizerEncounter(),mizerFMort(),mizerFMortGear(),mizerFeedingLevel(),mizerMort(),mizerPredMort(),mizerRDI(),mizerRates(),mizerResourceMort()
Get density-independent rate of reproduction needed to project standardmizer model
Description
Calculates the density-independent rate of total egg productionR_{di} (units 1/year) before density dependence, by species.You would not usually call thisfunction directly but instead usegetRDI(), which then calls thisfunction unless an alternative function has been registered, see below.
Usage
mizerRDI(params, n, n_pp, n_other, t, e_growth, mort, e_repro, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
e_growth | An array (species x size) with the energy available forgrowth as calculated by |
mort | An array (species x size) with the mortality rate as calculatedby |
e_repro | An array (species x size) with the energy available forreproduction as calculated by |
... | Unused |
Details
This rate is obtained by taking the per capita rateE_r(w)\psi(w) atwhich energy is invested in reproduction, as calculated bygetERepro(),multiplying it by the number of individualsN(w) and integrating overall sizesw and then multiplying by the reproductive efficiency\epsilon and dividing by the egg sizew_min, and by a factor of twoto account for the two sexes:
R_{di} = \frac{\epsilon}{2 w_{min}} \int N(w) E_r(w) \psi(w) \, dw
Used bygetRDD() to calculate the actual, density dependent rate.SeesetReproduction() for more details.
Value
A numeric vector with the rate of egg production for each species.
Your own reproduction function
By defaultgetRDI() callsmizerRDI(). However you canreplace this with your own alternative reproduction function. Ifyour function is called"myRDI" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "RDI", "myRDI")
Your function will then be called instead ofmizerRDI(), with thesame arguments. For an example of an alternative reproduction functionseeconstantEggRDI().
See Also
Other mizer rate functions:mizerEGrowth(),mizerERepro(),mizerEReproAndGrowth(),mizerEncounter(),mizerFMort(),mizerFMortGear(),mizerFeedingLevel(),mizerMort(),mizerPredMort(),mizerPredRate(),mizerRates(),mizerResourceMort()
Get all rates needed to project standard mizer model
Description
Calls other rate functions in sequence and collects the results in a list.
Usage
mizerRates(params, n, n_pp, n_other, t = 0, effort, rates_fns, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
effort | The effort for each fishing gear |
rates_fns | Named list of the functions to call to calculate the rates.Note that this list holds the functions themselves, not their names. |
... | Unused |
Details
By default this function returns a list with the following components:
encounter from
mizerEncounter()feeding_level from
mizerFeedingLevel()e from
mizerEReproAndGrowth()e_repro from
mizerERepro()e_growth from
mizerEGrowth()pred_rate from
mizerPredRate()pred_mort from
mizerPredMort()f_mort from
mizerFMort()mort from
mizerMort()rdi from
mizerRDI()rdd from
BevertonHoltRDD()resource_mort from
mizerResourceMort()
However you can replace any of these rate functions by your own ratefunction if you wish, seesetRateFunction() for details.
Value
List of rates.
See Also
Other mizer rate functions:mizerEGrowth(),mizerERepro(),mizerEReproAndGrowth(),mizerEncounter(),mizerFMort(),mizerFMortGear(),mizerFeedingLevel(),mizerMort(),mizerPredMort(),mizerPredRate(),mizerRDI(),mizerResourceMort()
Get predation mortality rate for resource needed to project standard mizermodel
Description
Calculates the predation mortality rate\mu_p(w) on the resourcespectrum by resource size (in units 1/year).You would not usually call thisfunction directly but instead usegetResourceMort(), which then calls thisfunction unless an alternative function has been registered, see below.
Usage
mizerResourceMort(params, n, n_pp, n_other, t, pred_rate, ...)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size). |
n_pp | A vector of the resource abundance by size |
n_other | A list of abundances for other dynamical components of theecosystem |
t | The time for which to do the calculation (Not used by standardmizer rate functions but useful for extensions with time-dependentparameters.) |
pred_rate | A two dimensional array (predator species x prey size) withthe predation rate, where the prey size runs over fish community plusresource spectrum. |
... | Unused |
Value
A vector of mortality rate by resource size.
Your own resource mortality function
By defaultgetResourceMort() callsmizerResourceMort(). However you canreplace this with your own alternative resource mortality function. Ifyour function is called"myResourceMort" then you register it in a MizerParamsobjectparams with
params <- setRateFunction(params, "ResourceMort", "myResourceMort")
Your function will then be called instead ofmizerResourceMort(), with thesame arguments.
See Also
Other mizer rate functions:mizerEGrowth(),mizerERepro(),mizerEReproAndGrowth(),mizerEncounter(),mizerFMort(),mizerFMortGear(),mizerFeedingLevel(),mizerMort(),mizerPredMort(),mizerPredRate(),mizerRDI(),mizerRates()
Determine whether a MizerParams or MizerSim object needs to be upgraded
Description
Looks at the mizer version that was used to last update the object andreturns TRUE if changes since that version require an upgrade of the object.You would not usually have to call this function. Upgrades are initiatedautomatically byvalidParams andvalidSim when necessary.
Usage
needs_upgrading(object)Arguments
object | A MizerParams or MizerSim object |
Value
TRUE or FALSE
Set up parameters for a community-type model
Description
This functions creates aMizerParams object describing acommunity-type model.The function has many arguments, all of which have default values.
Usage
newCommunityParams( max_w = 1e+06, min_w = 0.001, no_w = 100, min_w_pp = 1e-10, z0 = 0.1, alpha = 0.2, f0 = 0.7, h = 10, gamma = NA, beta = 100, sigma = 2, n = 2/3, kappa = 1000, lambda = 2.05, r_pp = 10, knife_edge_size = 1000, reproduction)Arguments
max_w | The maximum size of the community. The |
min_w | The minimum size of the community. |
no_w | The number of size bins in the consumer spectrum. |
min_w_pp | The smallest size of the resource spectrum. By default thisis set to the smallest value at which any of the consumers can feed. |
z0 | The background mortality of the community. |
alpha | The assimilation efficiency of the community. |
f0 | The average feeding level of individuals who feed on a power-lawspectrum. This value is used to calculate the search rate parameter |
h | The coefficient of the maximum food intake rate. |
gamma | Volumetric search rate. Estimated using |
beta | The preferred predator prey mass ratio. |
sigma | The width of the prey preference. |
n | The allometric growth exponent. Used as allometric exponent forthe maximum intake rate of the community as well as the intrinsic growthrate of the resource. |
kappa | The coefficient of the initial resource abundance power-law. |
lambda | Used to set power-law exponent for resource capacity if the |
r_pp | |
knife_edge_size | The size at the edge of the knife-edge-selectivityfunction. |
reproduction | The constant reproduction in the smallest size class ofthe community spectrum. By default this is set so that the communityspectrum is continuous with the resource spectrum. |
Details
A community model has several features that distinguish it from amulti-species model:
Species identities of individuals are ignored. All are aggregated into asingle community.
The resource spectrum only extends to the start of the community spectrum.
Reproductive rate is constant, independent of the energy invested inreproduction, which is set to 0.
Standard metabolism is turned off (the parameter
ksis set to 0).Consequently, the growth rate is now determined solely by the assimilatedfood
Fishing selectivity is modelled as a knife-edge function with one parameter,knife_edge_size, which determines the size at which species areselected.
The resultingMizerParams object can be projected forward usingproject() like any otherMizerParams object. When projectingthe community model it may be necessary to keep a small time step sizedt of around 0.1 to avoid any instabilities with the solver. You cancheck for these numerical instabilities by plotting the biomass or abundancethrough time after the projection.
Value
An object of typeMizerParams
References
K. H. Andersen,J. E. Beyer and P. Lundberg, 2009, Trophic andindividual efficiencies of size-structured communities, Proceedings of theRoyal Society, 276, 109-114
See Also
Other functions for setting up models:newMultispeciesParams(),newSingleSpeciesParams(),newTraitParams()
Examples
params <- newCommunityParams()sim <- project(params, t_max = 10)plotBiomass(sim)plotSpectra(sim, power = 2)# More satiation. More mortalityparams <- newCommunityParams(f0 = 0.8, z0 = 0.4)sim <- project(params, t_max = 10)plotBiomass(sim)plotSpectra(sim, power = 2)Set up parameters for a general multispecies model
Description
Sets up a multi-species size spectrum model by filling all slots in theMizerParams object based on user-provided or defaultparameters. There is a long list of arguments, but almostall of them have sensible default values. The only required argument isthespecies_params data frame. All arguments are described in moredetails in the sections below the list.
Usage
newMultispeciesParams( species_params, interaction = NULL, no_w = 100, min_w = 0.001, max_w = NA, min_w_pp = NA, pred_kernel = NULL, search_vol = NULL, intake_max = NULL, metab = NULL, p = 0.7, ext_mort = NULL, z0pre = 0.6, z0exp = n - 1, ext_encounter = NULL, maturity = NULL, repro_prop = NULL, RDD = "BevertonHoltRDD", kappa = 1e+11, n = 2/3, resource_rate = 10, resource_capacity = kappa, lambda = 2.05, w_pp_cutoff = 10, resource_dynamics = "resource_semichemostat", gear_params = NULL, selectivity = NULL, catchability = NULL, initial_effort = NULL, info_level = 3, z0 = deprecated(), r_pp = deprecated())Arguments
species_params | A data frame of species-specific parameter values. |
interaction | Optional interaction matrix of the species (predatorspecies x prey species). By default all entries are 1. See "Settinginteraction matrix" section below. |
no_w | The number of size bins in the consumer spectrum. |
min_w | Sets the size of the eggs of all species for which this is notgiven in the |
max_w | The largest size of the consumer spectrum. By default this isset to the largest |
min_w_pp | The smallest size of the resource spectrum. By default thisis set to the smallest value at which any of the consumers can feed. |
pred_kernel | Optional. An array (species x predator size x prey size)that holds the predation coefficient of each predator at size on each preysize. If not supplied, a default is set as described in section "Settingpredation kernel". |
search_vol | Optional. An array (species x size) holding the search volumefor each species at size. If not supplied, a default is set as described inthe section "Setting search volume". |
intake_max | Optional. An array (species x size) holding the maximumintake rate for each species at size. If not supplied, a default is set asdescribed in the section "Setting maximum intake rate". |
metab | Optional. An array (species x size) holding the metabolic ratefor each species at size. If not supplied, a default is set as described inthe section "Setting metabolic rate". |
p | The allometric metabolic exponent. This is only used if |
ext_mort | Optional. An array (species x size) holding the externalmortality rate. If not supplied, a default is set as described in thesection "Setting external mortality rate". |
z0pre | If |
z0exp | If |
ext_encounter | Optional. An array (species x size) holding the externalencounter rate. If not supplied, the external encounter rate is leftunchanged. Initially is is set to 0. |
maturity | Optional. An array (species x size) that holds the proportionof individuals of each species at size that are mature. If not supplied, adefault is set as described in the section "Setting reproduction". |
repro_prop | Optional. An array (species x size) that holds theproportion of consumed energy that a mature individual allocates toreproduction for each species at size. If not supplied, a default is set asdescribed in the section "Setting reproduction". |
RDD | The name of the function calculating the density-dependentreproduction rate from the density-independent rate. Defaults to" |
kappa | The coefficient of the initial resource abundance power-law. |
n | The allometric growth exponent. This can be overruled for individualspecies by including a |
resource_rate | Optional. A vector of per-capita resource birthrate for each size class or a single number giving the coefficient in thepower-law for this rate, see "Setting resource dynamics" below.Must be strictly positive. |
resource_capacity | Optional. Vector of resource intrinsic carryingcapacities or coefficient in the power-law for the capacity, see"Setting resource dynamics" below.The resource capacity must be larger than the resource abundance. |
lambda | Used to set power-law exponent for resource capacity if the |
w_pp_cutoff | The upper cut off size of the resource spectrum power lawused when |
resource_dynamics | Optional. Name of the function that determines theresource dynamics by calculating the resource spectrum at the next timestep from the current state. |
gear_params | A data frame with gear-specific parameter values. |
selectivity | Optional. An array (gear x species x size) that holds theselectivity of each gear for species and size, |
catchability | Optional. An array (gear x species) that holds the catchability ofeach species by each gear, |
initial_effort | Optional. A number or a named numeric vector specifyingthe fishing effort. If a number, the same effort is used for all gears. Ifa vector, must be named by gear. |
info_level | Controls the amount of information messages that are shownwhen the function sets default values for parameters. Higher levels leadto more messages. |
z0 |
|
r_pp |
Value
An object of typeMizerParams
Species parameters
The only essential argument is a data frame that contains the speciesparameters. The data frame is arranged species by parameter, so each columnof the parameter data frame is a parameter and each row has the values of theparameters for one of the species in the model.
There are two essential columns that must be included in the speciesparameter data.frame and that do not have default values: thespecies column that should hold strings with the names of thespecies and thew_max column with the maximum sizes of the speciesin grams. (You could alternatively specify the maximum length in cm in anl_max column.)
Thespecies_params dataframe also needs to contain the parameters neededby any predation kernel function (size selectivity function). This willbe mentioned in the appropriate sections below.
For all other species parameters, mizer will calculate default values if theyare not included in the species parameter data frame. They will beautomatically added when theMizerParams object is created. For theseparameters you can also specify values for only some species and leave theother entries as NA and the missing values will be set to the defaults.So thespecies_params data frame saved in the returned MizerParams objectwill differ from the one you supply because it will have the missingspecies parameters filled in with default values.
If you are not happy with any of the species parameter values used you canalways change them later withspecies_params<-().
All the parameters will be mentioned in the following sections.
Setting initial values
The initial values for the species number densities are set using thefunctionget_initial_n(). These are quite arbitrary and not very close tothe steady state abundances. We intend to improve this in the future.
The initial resource number densityN_R(w) is set to a power law withcoefficientkappa (\kappa) and exponent-lambda (-\lambda):
N_R(w) = \kappa\, w^{-\lambda}
for allw less thanw_pp_cutoff and zero for larger sizes.
Size grid
A size grid is created so thatthe log-sizes are equally spaced. The spacing is chosen so that there will beno_w fish size bins, with the smallest starting atmin_w and the largeststarting atmax_w. For the resource spectrum there is a larger set ofbins containing additional bins belowmin_w, with the same log size. The number of extra bins is such thatmin_w_pp comes to lie within the smallest bin.
Units in mizer
Mizer uses grams to measure weight, centimetres to measure lengths, andyears to measure time.
Mizer is agnostic about whether abundances are given as
numbers per area,
numbers per volume or
total numbers for the entire study area.
You should make the choice most convenient for your application and thenstick with it. If you make choice 1 or 2 you will also have to choose a unitfor area or volume. Your choice will then determine the units for some ofthe parameters. This will be mentioned when the parameters are discussed inthe sections below.
Your choice will also affect the units of the quantities you may want tocalculate with the model. For example, the yield will be in grams/year/m^2 incase 1 if you choose m^2 as your measure of area, in grams/year/m^3 in case 2if you choose m^3 as your unit of volume, or simply grams/year in case 3. Thesame comment applies for other measures, like total biomass, which will begrams/area in case 1, grams/volume in case 2 or simply grams in case 3. Whenmizer puts units on axes in plots, it will choose the units appropriate forcase 3. So for example inplotBiomass() it gives the unit as grams.
You can convert between these choices. For example, if you use case 1, youneed to multiply with the area of the ecosystem to get the total quantity.If you work with case 2, you need to multiply by both area and the thicknessof the productive layer. In that respect, case 2 is a bit cumbersome. ThefunctionscaleModel() is useful to change the units you are using.
Setting interaction matrix
You do not need to specify an interaction matrix. If you do not, then thepredator-prey interactions are purely determined by the size of predatorand prey and totally independent of the species of predator and prey.
The interaction matrix\theta_{ij} modifies the interaction of eachpair of species in the model. This can be used for example to allow fordifferent spatial overlap among the species.The values in the interaction matrix are used to scale the encountered foodand predation mortality (see on the websitethe section on predator-prey encounter rateand onpredation mortality).The first index refers to the predator species and the second to the preyspecies.
The interaction matrix is used when calculating the food encounter rate ingetEncounter() and the predation mortality rate ingetPredMort(). Itsentries are dimensionless numbers. If all the values in the interactionmatrix are equal then predator-prey interactions are determined entirely bysize-preference.
This function checks that the supplied interaction matrix is valid and thenstores it in theinteraction slot of theparams object.
The order of the columns and rows of theinteraction argument should bethe same as the order in the species params data frame in theparamsobject. If you supply a named array then the function will check the orderand warn if it is different. One way of creating your own interactionmatrix is to enter the data using a spreadsheet program and saving it as a.csv file. The data can then be read into R using the commandread.csv().
The interaction of the species with the resource are set via a columninteraction_resource in thespecies_params data frame. By default thiscolumn is set to all 1s.
Setting predation kernel
Kernel dependent on predator to prey size ratio
If thepred_kernel argument is not supplied, then this function sets apredation kernel that depends only on the ratio of predator mass to preymass, not on the two masses independently. The shape of that kernel is thendetermined by thepred_kernel_type column in species_params.
The default forpred_kernel_type is "lognormal". This will call the functionlognormal_pred_kernel() to calculate the predation kernel.An alternative pred_kernel type is "box", implemented by the functionbox_pred_kernel(), and "power_law", implemented by the functionpower_law_pred_kernel(). These functions require certain speciesparameters in the species_params data frame. For the lognormal kernel thesearebeta andsigma, for the box kernel they areppmr_minandppmr_max. They are explained in the help pages for the kernelfunctions. Except forbeta andsigma, no defaults are set forthese parameters. If they are missing from the species_params data frame thenmizer will issue an error message.
You can use any other string forpred_kernel_type. If for example youchoose "my" then you need to define a functionmy_pred_kernel that you canmodel on the existing functions likelognormal_pred_kernel().
When using a kernel that depends on the predator/prey size ratio only, mizerdoes not need to store the entire three dimensional array in the MizerParamsobject. Such an array can be very big when there is a large number of sizebins. Instead, mizer only needs to store two two-dimensional arrays that holdFourier transforms of the feeding kernel function that allow the encounterrate and the predation rate to be calculated very efficiently. However, ifyou need the full three-dimensional array you can calculate it with thegetPredKernel() function.
Kernel dependent on both predator and prey size
If you want to work with a feeding kernel that depends on predator mass andprey mass independently, you can specify the full feeding kernel as athree-dimensional array (predator species x predator size x prey size).
You should use this option only if a kernel dependent only on thepredator/prey mass ratio is not appropriate. Using a kernel dependent onpredator/prey mass ratio only allows mizer to use fast Fourier transformmethods to significantly reduce the running time of simulations.
The order of the predator species inpred_kernel should be the sameas the order in the species params dataframe in theparams object. If yousupply a named array then the function will check the order and warn if it isdifferent.
Setting search volume
The search volume\gamma_i(w) of an individual of speciesiand weightw multiplies the predation kernel whencalculating the encounter rate ingetEncounter() and thepredation rate ingetPredRate().
The name "search volume" is a bit misleading, because\gamma_i(w) doesnot have units of volume. It is simply a parameter that determines the rateof predation. Its units depend on your choice, see section "Units in mizer".If you have chosen to work with total abundances, then it is a rate with units1/year. If you have chosen to work with abundances per m^2 then it has unitsof m^2/year. If you have chosen to work with abundances per m^3 then it hasunits of m^3/year.
If thesearch_vol argument is not supplied, then the search volume isset to
\gamma_i(w) = \gamma_i w^q_i.
The values of\gamma_i (the search volume at 1g) andq_i (theallometric exponent of the search volume) are taken from thegamma andq columns in the species parameter dataframe. If thegammacolumn is not supplied in the species parameter dataframe, a default iscalculated by theget_gamma_default() function. Note that onlyfor predators of sizew = 1 gram is the value of the species parameter\gamma_i the same as the value of the search volume\gamma_i(w).
Setting maximum intake rate
The maximum intake rateh_i(w) of an individual of speciesi andweightw determines the feeding level, calculated withgetFeedingLevel(). It is measured in grams/year.
If theintake_max argument is not supplied, then the maximum intakerate is set to
h_i(w) = h_i w^{n_i}.
The values ofh_i (the maximum intake rate of an individual of size 1gram) andn_i (the allometric exponent for the intake rate) are takenfrom theh andn columns in the species parameter dataframe. Iftheh column is not supplied in the species parameter dataframe, it iscalculated by theget_h_default() function.
Ifh_i is set toInf, fish of species i will consume all encounteredfood.
Setting metabolic rate
The metabolic rate is subtracted from the energy income rate to calculatethe rate at which energy is available for growth and reproduction, seegetEReproAndGrowth(). It is measured in grams/year.
If themetab argument is not supplied, then for each species themetabolic ratek(w) for an individual of sizew is set to
k(w) = k_s w^p + k w,
wherek_s w^p represents the rate of standard metabolism andk wis the rate at which energy is expended on activity and movement. The valuesofk_s,p andk are taken from theks,p andk columns in the species parameter dataframe. If any of theseparameters are not supplied, the defaults arek = 0,p = n and
k_s = f_c h \alpha w_{mat}^{n-p},
wheref_c is the critical feeding level taken from thefc columnin the species parameter data frame. If the critical feeding level is notspecified, a default off_c = 0.2 is used.
Setting external mortality rate
The external mortality is all the mortality that is not due to fishing orpredation by predators included in the model. The external mortality could bedue to predation by predators that are not explicitly included in the model(e.g. mammals or seabirds) or due to other causes like illness. It is a ratewith units 1/year.
Theext_mort argument allows you to specify an external mortality ratethat depends on species and body size. You can see an example of this inthe Examples section of the help page forsetExtMort().
If theext_mort argument is not supplied, then the external mortality isassumed to depend only on the species, not on the size of the individual:\mu_{ext.i}(w) = z_{0.i}. The value of the constantz_0 for eachspecies is taken from thez0 column of the species parameter data frame, ifthat column exists. Otherwise it is calculated as
z_{0.i} = {\tt z0pre}_i\, w_{inf}^{\tt z0exp}.
Setting external encounter rate
The external encounter rate is the rate at which a predator encountersfood that is not explicitly modelled. It is a rate with units mass/year.
Theext_encounter argument allows you to specify an external encounter ratethat depends on species and body size. You can see an example of this inthe Examples section of the help page forsetExtEncounter().
Setting reproduction
For each species and at each size, the proportion\psi of theavailable energythat is invested into reproduction is the product of two factors: theproportionmaturity of individuals that are mature and the proportionrepro_prop of the energy available to a mature individual that isinvested into reproduction. There is a sizew_repro_max at which all theenergy is invested into reproduction and therefore all growth stops. Therecan be no fish larger thanw_repro_max. If you have not specified thew_repro_max column in the species parameter data frame, then the maximum sizew_max is used instead.
Maturity ogive
If the the proportion of individuals that are mature is not supplied viathematurity argument, then it is set to a sigmoidalmaturity ogive that changes from 0 to 1 at around the maturity size:
{\tt maturity}(w) = \left[1+\left(\frac{w}{w_{mat}}\right)^{-U}\right]^{-1}.
(To avoid clutter, we are not showing the species index in the equations,although each species has its own maturity ogive.)The maturity weights are taken from thew_mat column of thespecies_params data frame. Any missing maturity weights are set to 1/4 of themaximum weight in thew_max column.
The exponentU determines the steepness of the maturity ogive. Bydefault it is chosen asU = 10, however this can be overridden byincluding a columnw_mat25 in the species parameter dataframe thatspecifies the weight at which 25% of individuals are mature, which setsU = \log(3) / \log(w_{mat} / w_{mat25}).
The sigmoidal function given above would strictly reach 1 onlyasymptotically. Mizer instead sets the function equal to 1 already at a sizetaken from thew_repro_max column in the species parameter data frame, if itexists, or otherwise from thew_max column. Also, for computationalsimplicity, any proportion smaller than1e-8 is set to0.
Investment into reproduction
If the the energy available to a mature individual that isinvested into reproduction is not supplied via therepro_prop argument,it is set to the allometric form
{\tt repro\_prop}(w) = \left(\frac{w}{w_{\tt{repro\_max}}}\right)^{m-n}.
Heren is the scaling exponent of the energy income rate. Hencethe exponentm determines the scaling of the investment intoreproduction for mature individuals. By default it is chosen to bem = 1 so that the rate at which energy is invested into reproductionscales linearly with the size. This default can be overridden by including acolumnm in the species parameter dataframe. The maximum sizes are takenfrom thew_repro_max column in the species parameter data frame, if itexists, or otherwise from thew_max column.
The total proportion of energy invested into reproduction of an individualof sizew is then
\psi(w) = {\tt maturity}(w){\tt repro\_prop}(w)
Reproductive efficiency
The reproductive efficiency\epsilon, i.e., the proportion of energy allocated toreproduction that results in egg biomass, is set through theereprocolumn in the species_params data frame. If that is not provided, the defaultis set to 1 (which you will want to override). The offspring biomass dividedby the egg biomass gives the rate of egg production, returned bygetRDI():
R_{di} = \frac{\epsilon}{2 w_{min}} \int N(w) E_r(w) \psi(w) \, dw
Density dependence
The stock-recruitment relationship is an emergent phenomenon in mizer, withseveral sources of density dependence. Firstly, the amount of energy investedinto reproduction depends on the energy income of the spawners, which isdensity-dependent due to competition for prey. Secondly, the proportion oflarvae that grow up to recruitment size depends on the larval mortality,which depends on the density of predators, and on larval growth rate, whichdepends on density of prey.
Finally, to encode all the density dependence in the stock-recruitmentrelationship that is not already included in the other two sources of densitydependence, mizer puts the the density-independent rate of egg productionthrough a density-dependence function. The result is returned bygetRDD(). The name of the density-dependence function isspecified by theRDD argument. The default is the Beverton-HoltfunctionBevertonHoltRDD(), which requires anR_max columnin the species_params data frame giving the maximum egg production rate. Ifthis column does not exist, it is initialised toInf, leading to nodensity-dependence. Other functions provided by mizer areRickerRDD() andSheperdRDD() and you can easily usethese as models for writing your own functions.
Setting fishing
Gears
Inmizer, fishing mortality is imposed on species by fishing gears. Thetotal per-capita fishing mortality (1/year) is obtained by summing over themortality from all gears,
\mu_{f.i}(w) = \sum_g F_{g,i}(w),
where the fishing mortalityF_{g,i}(w) imposed by gearg onspeciesi at sizew is calculated as:
F_{g,i}(w) = S_{g,i}(w) Q_{g,i} E_{g},
whereS is the selectivity by species, gear and size,Q is thecatchability by species and gear andE is the fishing effort by gear.
Selectivity
The selectivity at size of each gear for each species is saved as a threedimensional array (gear x species x size). Each entry has a range between 0(that gear is not selecting that species at that size) to 1 (that gear isselecting all individuals of that species of that size). This threedimensional array can be specified explicitly via theselectivityargument, but usually mizer calculates it from thegear_params slot ofthe MizerParams object.
To allow the calculation of theselectivity array, thegear_params slotmust be a data frame with one row for each gear-species combination. So iffor example a gear can select three species, then that gear contributes threerows to thegear_params data frame, one for each species it can select. Thedata frame must have columnsgear, holding the name of the gear,species,holding the name of the species, andsel_func, holding the name of thefunction that calculates the selectivity curve. Some selectivity functionsare included in the package:knife_edge(),sigmoid_length(),double_sigmoid_length(), andsigmoid_weight().Users are able to write their own size-based selectivity function. The firstargument to the function must bew and the function must return a vector ofthe selectivity (between 0 and 1) at size.
Each selectivity function may have parameters. Values for theseparameters must be included as columns in the gear parameters data.frame.The names of the columns must exactly match the names of the correspondingarguments of the selectivity function. For example, the default selectivityfunction isknife_edge() that a has sudden change of selectivity from 0 to 1at a certain size. In its help page you can see that theknife_edge()function has argumentsw andknife_edge_size. The first argument,w, issize (the function calculates selectivity at size). All selectivity functionsmust havew as the first argument. The values for the other arguments mustbe found in the gear parameters data.frame. So for theknife_edge()function there should be aknife_edge_size column. Becauseknife_edge()is the default selectivity function, theknife_edge_size argument has adefault value =w_mat.
The most commonly-used selectivity function issigmoid_length(). It has asmooth transition from 0 to 1 at a certain size. Thesigmoid_length()function has the two parametersl50 andl25 that are the lengths in cm atwhich 50% or 25% of the fish are selected by the gear. If you choose thisselectivity function then thel50 andl25 columns must be included in thegear parameters data.frame.
In case each species is only selected by one gear, the columns of thegear_params data frame can alternatively be provided as columns of thespecies_params data frame, if this is more convenient for the user to setup. Mizer will then copy these columns over to create thegear_params dataframe when it creates the MizerParams object. However changing these columnsin the species parameter data frame later will not update thegear_paramsdata frame.
Catchability
Catchability is used as an additional factor to make the link between gearselectivity, fishing effort and fishing mortality. For example, it can be setso that an effort of 1 gives a desired fishing mortality. In this way effortcan then be specified relative to a 'base effort', e.g. the effort in aparticular year.
Catchability is stored as a two dimensional array (gear x species). This caneither be provided explicitly via thecatchability argument, or theinformation can be provided via acatchability column in thegear_paramsdata frame.
In the case where each species is selected by only a single gear, thecatchability column can also be provided in thespecies_params dataframe. Mizer will then copy this over to thegear_params data frame whenthe MizerParams object is created.
Effort
The initial fishing effort is stored in theMizerParams object. If it isnot supplied, it is set to zero. The initial effort can be overruled whenthe simulation is run withproject(), where it is also possible to specifyan effort that varies through time.
Setting resource dynamics
Theresource_dynamics argument allows you to choose the resource dynamicsfunction. By default, mizer uses a semichemostat model to describe theresource dynamics in each size class independently. This semichemostatdynamics is implemented by the functionresource_semichemostat(). You canchange that to use a logistic model implemented byresource_logistic() oryou can useresource_constant() which keeps the resource constant or youcan write your own function.
Both theresource_semichemostat() and theresource_logistic() dynamicsare parametrised in terms of a size-dependent birth rater_R(w) and asize-dependent capacityc_R. The help pages of these functions givethe details.
Theresource_rate argument can be a vector (with the same length asw_full(params)) specifying the intrinsic resource birth rate for each sizeclass. Alternatively it can be a single number that is used as thecoefficient in a power law: then the intrinsic birth rater_R(w) atsizew is set to
r_R(w) = r_R w^{n-1}.
The power-law exponentn is taken from then argument.
Theresource_capacity argument can be a vector specifying the intrinsicresource carrying capacity for each size class. Alternatively it can be asingle number that is used as the coefficient in a truncated powerlaw: then the intrinsic carrying capacityc_R(w) at sizewis set to
c_R(w) = c_R\, w^{-\lambda}
for allw less thanw_pp_cutoff and zero for larger sizes.The power-law exponent\lambda is taken from thelambda argument.
The values forlambda,n andw_pp_cutoff are stored in a listin theresource_params slot of the MizerParams object so that they can bere-used automatically in the future. That list can be accessed withresource_params().
See Also
Other functions for setting up models:newCommunityParams(),newSingleSpeciesParams(),newTraitParams()
Examples
params <- newMultispeciesParams(NS_species_params)Set up parameters for a single species in a power-law background
Description
This functions creates aMizerParams object with a singlespecies. This species is embedded in a fixed power-law community spectrum
N_c(w) = \kappa w^{-\lambda}
This community provides the food income for the species. Cannibalism isswitched off. The predation mortality arises only from the predators in thepower-law community and it is assumed that the predators in the communityhave the same feeding parameters as the foreground species. The function hasmany arguments, all of which have default values.
Usage
newSingleSpeciesParams( species_name = "Target species", w_max = 100, w_min = 0.001, eta = 10^(-0.6), w_mat = w_max * eta, no_w = log10(w_max/w_min) * 20 + 1, n = 3/4, p = n, lambda = 2.05, kappa = 0.005, alpha = 0.4, h = 30, beta = 100, sigma = 1.3, f0 = 0.6, fc = 0.25, ks = NA, gamma = NA, ext_mort_prop = 0, reproduction_level = 0, R_factor = deprecated(), w_inf = deprecated(), k_vb = deprecated())Arguments
species_name | A string with a name for the species. Will be used inplot legends. |
w_max | Maximum size of species |
w_min | Egg size of species |
eta | Ratio between maturity size |
w_mat | Maturity size of species. Default value is |
no_w | The number of size bins in the community spectrum. These binswill be equally spaced on a logarithmic scale. Default value is such thatthere are 20 bins for each factor of 10 in weight. |
n | Scaling exponent of the maximum intake rate. |
p | Scaling exponent of the standard metabolic rate. By default this isequal to the exponent |
lambda | Exponent of the abundance power law. |
kappa | Coefficient in abundance power law. |
alpha | The assimilation efficiency. |
h | Maximum food intake rate. |
beta | Preferred predator prey mass ratio. |
sigma | Width of prey size preference. |
f0 | Expected average feeding level. Used to set |
fc | Critical feeding level. Used to determine |
ks | Standard metabolism coefficient. If not provided, default will becalculated from critical feeding level argument |
gamma | Volumetric search rate. If not provided, default is determinedby |
ext_mort_prop | The proportion of the total mortality that comes fromexternal mortality, i.e., from sources not explicitly modelled. A number inthe interval [0, 1). |
reproduction_level | A number between 0 an 1 that determines thelevel of density dependence in reproduction, see |
R_factor | |
w_inf | |
k_vb |
Details
In addition to setting up the parameters, this function also sets up aninitial condition that is close to steady state, under the assumption ofno fishing.
Value
An object of typeMizerParams
See Also
Other functions for setting up models:newCommunityParams(),newMultispeciesParams(),newTraitParams()
Examples
params <- newSingleSpeciesParams()sim <- project(params, t_max = 5, effort = 0)plotSpectra(sim)Set up parameters for a trait-based multispecies model
Description
This functions creates aMizerParams object describing a trait-basedmodel. This is a simplification of the general size-based model used inmizer in which the species-specific parameters are the same for allspecies, except for the maximum size, which is considered the mostimportant trait characterizing a species. Other parameters are related to themaximum size. For example, the size at maturity is given byw_max *eta, whereeta is the same for all species. For the trait-based modelthe number of species is not important. For applications of the trait-basedmodel see Andersen & Pedersen (2010). See themizer website for moredetails and examples of the trait-based model.
Usage
newTraitParams( no_sp = 11, min_w_max = 10, max_w_max = 10^4, min_w = 10^(-3), max_w = max_w_max, eta = 10^(-0.6), min_w_mat = min_w_max * eta, no_w = round(log10(max_w_max/min_w) * 20 + 1), min_w_pp = 1e-10, w_pp_cutoff = min_w_mat, n = 2/3, p = n, lambda = 2.05, r_pp = 0.1, kappa = 0.005, alpha = 0.4, h = 40, beta = 100, sigma = 1.3, f0 = 0.6, fc = 0.25, ks = NA, gamma = NA, ext_mort_prop = 0, reproduction_level = 1/4, R_factor = deprecated(), gear_names = "knife_edge_gear", knife_edge_size = 1000, egg_size_scaling = FALSE, resource_scaling = FALSE, perfect_scaling = FALSE, min_w_inf = deprecated(), max_w_inf = deprecated())Arguments
no_sp | The number of species in the model. |
min_w_max | The maximum size of the smallest species in thecommunity. This will be rounded to lie on a grid point. |
max_w_max | The maximum size of the largest species in the community.This will be rounded to lie on a grid point. |
min_w | The size of the the egg of the smallest species. This alsodefines the start of the community size spectrum. |
max_w | The largest size in the model. By default this is set to thelargest maximum size |
eta | Ratio between maturity size and maximum size of a species.Ignored if |
min_w_mat | The maturity size of the smallest species. Default value is |
no_w | The number of size bins in the community spectrum. These binswill be equally spaced on a logarithmic scale. Default value is such thatthere are 20 bins for each factor of 10 in weight. |
min_w_pp | The smallest size of the resource spectrum. By default thisis set to the smallest value at which any of the consumers can feed. |
w_pp_cutoff | The largest size of the resource spectrum. Default valueis min_w_max unless |
n | Scaling exponent of the maximum intake rate. |
p | Scaling exponent of the standard metabolic rate. By default this isequal to the exponent |
lambda | Exponent of the abundance power law. |
r_pp | Growth rate parameter for the resource spectrum. |
kappa | Coefficient in abundance power law. |
alpha | The assimilation efficiency. |
h | Maximum food intake rate. |
beta | Preferred predator prey mass ratio. |
sigma | Width of prey size preference. |
f0 | Expected average feeding level. Used to set |
fc | Critical feeding level. Used to determine |
ks | Standard metabolism coefficient. If not provided, default will becalculated from critical feeding level argument |
gamma | Volumetric search rate. If not provided, default is determinedby |
ext_mort_prop | The proportion of the total mortality that comes fromexternal mortality, i.e., from sources not explicitly modelled. A number inthe interval [0, 1). |
reproduction_level | A number between 0 an 1 that determines thelevel of density dependence in reproduction, see |
R_factor | |
gear_names | The names of the fishing gears for each species. Acharacter vector, the same length as the number of species. |
knife_edge_size | The minimum size at which the gear or gears selectfish. A single value for each gear or a vector with one value for eachgear. |
egg_size_scaling |
|
resource_scaling |
|
perfect_scaling |
|
min_w_inf |
|
max_w_inf |
Details
The function has many arguments, all of which have default values. Ofparticular interest to the user are the number of species in the model andthe minimum and maximum sizes.
The characteristic weights of the smallest species are defined bymin_w (egg size),min_w_mat (maturity size) andmin_w_max (maximum size). The maximum sizes oftheno_sp speciesare logarithmically evenly spaced, ranging frommin_w_max tomax_w_max.Similarly the maturity sizes of the species are logarithmically evenlyspaced, so that the ratioeta between maturity size and maximumsize is the same for all species. Ifegg_size_scaling = TRUE then alsothe ratio between maximum size and egg size is the same for all species.Otherwise all species have the same egg size.
In addition to setting up the parameters, this function also sets up aninitial condition that is close to steady state.
The search rate coefficientgamma is calculated using the expectedfeeding level,f0.
The option of including fishing is given, but the steady state may loose itsnatural stability if too much fishing is included. In such a case the usermay wish to include stabilising effects (likereproduction_level) to ensurethe steady state is stable. Fishing selectivity is modelled as a knife-edgefunction with one parameter,knife_edge_size, which is the size at whichspecies are selected. Each species can either be fished by the same gear(knife_edge_size has a length of 1) or by a different gear (the length ofknife_edge_size has the same length as the number of species and the orderof selectivity size is that of the maximum size).
The resultingMizerParams object can be projected forward usingproject() like any otherMizerParams object. When projectingthe model it may be necessary to reducedt below 0.1 to avoid anyinstabilities with the solver. You can check this by plotting the biomass orabundance through time after the projection.
Value
An object of typeMizerParams
See Also
Other functions for setting up models:newCommunityParams(),newMultispeciesParams(),newSingleSpeciesParams()
Examples
params <- newTraitParams()sim <- project(params, t_max = 5, effort = 0)plotSpectra(sim)Give density-independent reproduction rate
Description
Simply returns itsrdi argument.
Usage
noRDD(rdi, ...)Arguments
rdi | Vector of density-independent reproduction rates |
... | Not used. |
Value
Vector of density-dependent reproduction rates.
See Also
Other functions calculating density-dependent reproduction rate:BevertonHoltRDD(),RickerRDD(),SheperdRDD(),constantEggRDI(),constantRDD()
Summary plot forMizerParams objects
Description
Produces 3 plots in the same window: abundance spectra, feedinglevel and predation mortality of each species through time. This method justuses the other plotting functions and puts them all in one window.
Usage
## S4 method for signature 'MizerParams,missing'plot(x, y, ...)Arguments
x | An object of classMizerParams |
y | Not used |
... | For additional arguments see the documentation for |
Value
A viewport object
See Also
Other plotting functions:animateSpectra(),plot,MizerSim,missing-method,plotBiomass(),plotDiet(),plotFMort(),plotFeedingLevel(),plotGrowthCurves(),plotPredMort(),plotSpectra(),plotYield(),plotYieldGear(),plotting_functions
Examples
params <- NS_paramsplot(params)Summary plot forMizerSim objects
Description
After running a projection, produces 5 plots in the same window: feedinglevel, abundance spectra, predation mortality and fishing mortality of eachspecies by size; and biomass of each species through time. This method justuses the other plotting functions and puts them all in one window.
Usage
## S4 method for signature 'MizerSim,missing'plot(x, y, ...)Arguments
x | An object of classMizerSim |
y | Not used |
... | For additional arguments see the documentation for |
Value
A viewport object
See Also
Other plotting functions:animateSpectra(),plot,MizerParams,missing-method,plotBiomass(),plotDiet(),plotFMort(),plotFeedingLevel(),plotGrowthCurves(),plotPredMort(),plotSpectra(),plotYield(),plotYieldGear(),plotting_functions
Examples
params <- NS_paramssim <- project(params, effort=1, t_max=20, t_save = 2, progress_bar = FALSE)plot(sim)Plot the biomass of species through time
Description
After running a projection, the biomass of each species can be plottedagainst time. The biomass is calculated within user defined size limits(min_w, max_w, min_l, max_l, seegetBiomass()).
Usage
plotBiomass( sim, species = NULL, start_time, end_time, y_ticks = 6, ylim = c(NA, NA), total = FALSE, background = TRUE, highlight = NULL, return_data = FALSE, ...)plotlyBiomass( sim, species = NULL, start_time, end_time, y_ticks = 6, ylim = c(NA, NA), total = FALSE, background = TRUE, highlight = NULL, ...)Arguments
sim | An object of classMizerSim |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
start_time | The first time to be plotted. Default is the beginningof the time series. |
end_time | The last time to be plotted. Default is the end of thetime series. |
y_ticks | The approximate number of ticks desired on the y axis |
ylim | A numeric vector of length two providing lower and upper limitsfor the y axis. Use NA to refer to the existing minimum or maximum. Anyvalues below 1e-20 are always cut off. Data is filtered to this range andthe axis limits are set accordingly. |
total | A boolean value that determines whether the total biomass fromall species is plotted as well. Default is FALSE. |
background | A boolean value that determines whether background speciesare included. Ignored if the model does not contain background species.Default is TRUE. |
highlight | Name or vector of names of the species to be highlighted. |
return_data | A boolean value that determines whether the formatted dataused for the plot is returned instead of the plot itself. Default value is FALSE |
... | Arguments passed on to
|
Value
A ggplot2 object, unlessreturn_data = TRUE, in which case a dataframe with the four variables 'Year', 'Biomass', 'Species', 'Legend' isreturned.
See Also
plotting_functions,getBiomass()
Other plotting functions:animateSpectra(),plot,MizerParams,missing-method,plot,MizerSim,missing-method,plotDiet(),plotFMort(),plotFeedingLevel(),plotGrowthCurves(),plotPredMort(),plotSpectra(),plotYield(),plotYieldGear(),plotting_functions
Examples
plotBiomass(NS_sim)plotBiomass(NS_sim, species = c("Sandeel", "Herring"), total = TRUE)plotBiomass(NS_sim, start_time = 1980, end_time = 1990)# Returning the data framefr <- plotBiomass(NS_sim, return_data = TRUE)str(fr)Plotting observed vs. model biomass data
Description
If biomass observations are available for at least some species via the
biomass_observed column in the species parameter data frame, this functionplots the biomass of each species in the model against the observedbiomasses. When called with a MizerSim object, the plot will use the modelbiomasses predicted for the final time step in the simulation.
Usage
plotBiomassObservedVsModel( object, species = NULL, ratio = TRUE, log_scale = TRUE, return_data = FALSE, labels = TRUE, show_unobserved = FALSE)plotlyBiomassObservedVsModel( object, species = NULL, ratio = FALSE, log_scale = TRUE, return_data = FALSE, show_unobserved = FALSE)Arguments
object | An object of classMizerParams orMizerSim. |
species | The species to be included. Optional. By default all observedbiomasses will be included. A vector of species names, or a numeric vectorwith the species indices, or a logical vector indicating for each specieswhether it is to be included (TRUE) or not. |
ratio | Whether to plot model biomass vs. observed biomass (FALSE) orthe ratio of model : observed biomass (TRUE). Default is TRUE. |
log_scale | Whether to plot on the log10 scale (TRUE) or not (FALSE).For the non-ratio plot this applies for both axes, for the ratio plot onlythe x-axis is on the log10 scale. Default is TRUE. |
return_data | Whether to return the data frame for the plot (TRUE) ornot (FALSE). Default is FALSE. |
labels | Whether to show text labels for each species (TRUE) or not(FALSE). Default is TRUE. |
show_unobserved | Whether to include also species for which nobiomass observation is available. If TRUE, these species will beshown as if their observed biomass was equal to the model biomass. |
Details
Before you can use this function you will need to have added abiomass_observed column to your model which gives the observed biomass ingrams. For species for which you have no observed biomass, you should setthe value in thebiomass_observed column to 0 or NA.
Biomass observations usually only include individuals above a certain size.This size should be specified in abiomass_cutoff column of the speciesparameter data frame. If this is missing, it is assumed that all sizes areincluded in the observed biomass, i.e., it includes larval biomass.
The total relative error is shown in the caption of the plot, calculated by
TRE = \sum_i|1-\rm{ratio_i}|
where\rm{ratio_i} is the ratio of model biomass / observedbiomass for species i.
Value
A ggplot2 object with the plot of model biomass by species comparedto observed biomass. Ifreturn_data = TRUE, the data frame used tocreate the plot is returned instead of the plot.
Examples
# create an exampleparams <- NS_paramsspecies_params(params)$biomass_observed <- c(0.8, 61, 12, 35, 1.6, NA, 10, 7.6, 135, 60, 30, NA)species_params(params)$biomass_cutoff <- 10params <- calibrateBiomass(params)# Plot with default optionsplotBiomassObservedVsModel(params, ratio = FALSE)# Plot including also species without observationsplotBiomassObservedVsModel(params, show_unobserved = TRUE, ratio = FALSE)# Show the ratio insteadplotBiomassObservedVsModel(params)Make a plot from a data frame
Description
This is used internally by most plotting functions.
Usage
plotDataFrame( frame, params, style = "line", xlab = waiver(), ylab = waiver(), xtrans = "identity", ytrans = "identity", xlim = c(NA, NA), ylim = c(NA, NA), y_ticks = 6, highlight = NULL, legend_var = NULL, wrap_var = NULL, wrap_scale = NULL)Arguments
frame | A data frame with at least three variables.The first three variables are used, in that order, as:
|
params | A MizerParams object, which is used for the line colours andline types. |
style | The style of the plot. Available options are "line' for geom_lineand "area" for geom_area. Default is "line". |
xlab | Label for the x-axis |
ylab | Label for the y-axis |
xtrans | Transformation for the x-axis. Often "log10" may be usefulinstead of the default of "identity". |
ytrans | Transformation for the y-axis. |
xlim | A numeric vector of length two providing lower and upper limitsfor the x axis. Use NA to refer to the existing minimum or maximum. |
ylim | A numeric vector of length two providing lower and upper limitsfor the y axis. Use NA to refer to the existing minimum or maximum. |
y_ticks | The approximate number of ticks desired on the y axis |
highlight | Name or vector of names of the species to be highlighted. |
legend_var | The name of the variable that should be used in the legendand to determine the line style. If NULL then the grouping variable isused for this purpose. |
wrap_var | Optional. The name of the variable that should be used forcreating wrapped facets. |
wrap_scale | Optional. Used to pass the scales argument to facet_wrap(). |
Value
A ggplot2 object
Plot diet, resolved by prey species, as function of predator at size.
Description
Plots the proportions with which eachprey species contributes to the total biomass consumed by the specifiedpredator species, as a function of the predator's size. These proportions areobtained with
getDiet().
Usage
plotDiet(object, species = NULL, return_data = FALSE)Arguments
object | An object of classMizerSim orMizerParams. |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
return_data | A boolean value that determines whether the formatted dataused for the plot is returned instead of the plot itself. Default value is FALSE |
Details
Prey species that contribute less than 1 permille to the diet are suppressedin the plot. The plot only extends to predator sizes where the predator has ameaningful abundance (defined as having a biomass density greater than 0.1%of its maximum biomass density).
If more than one predator species is selected, then the plot contains onefacet for each species.
Value
A ggplot2 object, unlessreturn_data = TRUE, in which case a dataframe with the four variables 'Predator', 'w', 'Proportion', 'Prey' isreturned.
See Also
Other plotting functions:animateSpectra(),plot,MizerParams,missing-method,plot,MizerSim,missing-method,plotBiomass(),plotFMort(),plotFeedingLevel(),plotGrowthCurves(),plotPredMort(),plotSpectra(),plotYield(),plotYieldGear(),plotting_functions
Examples
plotDiet(NS_params, species = "Cod")plotDiet(NS_params, species = 5:9)# Returning the data framefr <- plotDiet(NS_params, species = "Cod", return_data = TRUE)str(fr)Plot total fishing mortality of each species by size
Description
After running a projection, plot the total fishing mortality of each speciesby size. The total fishing mortality is averaged over the specified timerange (a single value for the time range can be used to plot a single timestep).
Usage
plotFMort( object, species = NULL, time_range, all.sizes = FALSE, highlight = NULL, return_data = FALSE, ...)plotlyFMort(object, species = NULL, time_range, highlight = NULL, ...)Arguments
object | An object of classMizerSim orMizerParams. |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
time_range | The time range (either a vector of values, a vector of minand max time, or a single value) to average the abundances over. Default isthe final time step. Ignored when called with aMizerParamsobject. |
all.sizes | If TRUE, then fishing mortality is plotted also for sizesoutside a species' size range. Default FALSE. |
highlight | Name or vector of names of the species to be highlighted. |
return_data | A boolean value that determines whether the formatted dataused for the plot is returned instead of the plot itself. Default value is FALSE |
... | Other arguments (currently unused) |
Value
A ggplot2 object, unlessreturn_data = TRUE, in which case a dataframe with the three variables 'w', 'value', 'Species' is returned.
See Also
Other plotting functions:animateSpectra(),plot,MizerParams,missing-method,plot,MizerSim,missing-method,plotBiomass(),plotDiet(),plotFeedingLevel(),plotGrowthCurves(),plotPredMort(),plotSpectra(),plotYield(),plotYieldGear(),plotting_functions
Examples
params <- NS_paramssim <- project(params, effort=1, t_max=20, t_save = 2, progress_bar = FALSE)plotFMort(sim)plotFMort(sim, highlight = c("Cod", "Haddock"))# Returning the data framefr <- plotFMort(sim, return_data = TRUE)str(fr)Plot the feeding level of species by size
Description
After running a projection, plot the feeding level of each species by size.The feeding level is averaged over the specified time range (a single valuefor the time range can be used).
Usage
plotFeedingLevel( object, species = NULL, time_range, highlight = NULL, all.sizes = FALSE, include_critical = FALSE, return_data = FALSE, ...)plotlyFeedingLevel( object, species = NULL, time_range, highlight = NULL, include_critical = FALSE, ...)Arguments
object | An object of classMizerSim orMizerParams. |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
time_range | The time range (either a vector of values, a vector of minand max time, or a single value) to average the abundances over. Default isthe final time step. Ignored when called with aMizerParamsobject. |
highlight | Name or vector of names of the species to be highlighted. |
all.sizes | If TRUE, then feeding level is plotted also for sizesoutside a species' size range. Default FALSE. |
include_critical | If TRUE, then the critical feeding level is alsoplotted. Default FALSE. |
return_data | A boolean value that determines whether the formatted dataused for the plot is returned instead of the plot itself. Default value is FALSE |
... | Other arguments (currently unused) |
Details
When called with aMizerSim object, the feeding level is averagedover the specified time range (a single value for the time range can be usedto plot a single time step). When called with aMizerParamsobject the initial feeding level is plotted.
Ifinclude_critical = TRUE then the critical feeding level (the feedinglevel at which the intake just covers the metabolic cost) is also plotted,with a thinner line. This line should always stay below the line of theactual feeding level, because the species would stop growing at any pointwhere the feeding level drops to the critical feeding level.
Value
A ggplot2 object, unlessreturn_data = TRUE, in which case a dataframe with the variables 'w', 'value' and 'Species' is returned. If alsoinclude_critical = TRUE then the data frame contains a fourth variable'Type' that distinguishes between 'actual' and 'critical' feeding level.
See Also
plotting_functions,getFeedingLevel()
Other plotting functions:animateSpectra(),plot,MizerParams,missing-method,plot,MizerSim,missing-method,plotBiomass(),plotDiet(),plotFMort(),plotGrowthCurves(),plotPredMort(),plotSpectra(),plotYield(),plotYieldGear(),plotting_functions
Examples
params <- NS_paramssim <- project(params, effort=1, t_max=20, t_save = 2, progress_bar = FALSE)plotFeedingLevel(sim)plotFeedingLevel(sim, time_range = 10:20, species = c("Cod", "Herring"), include_critical = TRUE)# Returning the data framefr <- plotFeedingLevel(sim, return_data = TRUE)str(fr)Plot growth curves
Description
The growth curves represent the average age of all the living fish of aspecies as a function of their size. So it would be natural to plot sizeon the x-axis. But to follow the usual convention from age-based models, weplot size on the y-axis and age on the x-axis.
Usage
plotGrowthCurves( object, species = NULL, max_age = 20, percentage = FALSE, species_panel = FALSE, highlight = NULL, size_at_age = NULL, return_data = FALSE, ...)plotlyGrowthCurves( object, species = NULL, max_age = 20, percentage = FALSE, species_panel = FALSE, highlight = NULL)Arguments
object | MizerSim or MizerParams object. If given aMizerSim object, uses the growth rates at the final time of asimulation to calculate the size at age. If given aMizerParams object, uses the initial growth rates instead. |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
max_age | The age up to which to run the growth curve. Default is 20. |
percentage | Boolean value. If TRUE, the size is given as a percentageof the maximal size. |
species_panel | If TRUE (default), and |
highlight | Name or vector of names of the species to be highlighted. |
size_at_age | A data frame with observed size at age data to be plottedon top of growth curve graphs. Should contain columns |
return_data | A boolean value that determines whether the formatted dataused for the plot is returned instead of the plot itself. Default value is FALSE |
... | Other arguments (currently unused) |
Details
In each panel for a single species, a horizontal line is included thatindicate the maturity size of the species and a vertical line indicating itsmaturity age.
If size at age data is passed via thesize_at_age argument, this is plottedon top of the growth curve. When comparing this to the growth curves, youneed to remember that the growth curves should only represent the averageage at each size. So a scatter in the x-direction around the curve is to beexpected.
For legacy reasons, if the species parameters contain the variablesa andb for length to weight conversion and the von Bertalanffy parameterk_vb,w_inf (and optionallyt0), then the von Bertalanffy growth curve issuperimposed in black. This was implemented before we understood that the vonBertalanffy curves (which approximates the average length at each age) shouldnot be compared to the mizer growth curves (which approximate the average ageat each length).
Value
A ggplot2 object
See Also
Other plotting functions:animateSpectra(),plot,MizerParams,missing-method,plot,MizerSim,missing-method,plotBiomass(),plotDiet(),plotFMort(),plotFeedingLevel(),plotPredMort(),plotSpectra(),plotYield(),plotYieldGear(),plotting_functions
Examples
params <- NS_paramssim <- project(params, effort=1, t_max=20, t_save = 2, progress_bar = FALSE)plotGrowthCurves(sim, percentage = TRUE)plotGrowthCurves(sim, species = "Cod", max_age = 24)plotGrowthCurves(sim, species_panel = TRUE)# Returning the data framefr <- plotGrowthCurves(sim, return_data = TRUE)str(fr)Alias forplotPredMort()
Description
An alias provided for backward compatibility with mizer version <= 1.0
Usage
plotM2( object, species = NULL, time_range, all.sizes = FALSE, highlight = NULL, return_data = FALSE, ...)Arguments
object | An object of classMizerSim orMizerParams. |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
time_range | The time range (either a vector of values, a vector of minand max time, or a single value) to average the abundances over. Default isthe final time step. Ignored when called with aMizerParamsobject. |
all.sizes | If TRUE, then predation mortality is plotted also for sizesoutside a species' size range. Default FALSE. |
highlight | Name or vector of names of the species to be highlighted. |
return_data | A boolean value that determines whether the formatted dataused for the plot is returned instead of the plot itself. Default value is FALSE |
... | Other arguments (currently unused) |
Value
A ggplot2 object, unlessreturn_data = TRUE, in which case a dataframe with the three variables 'w', 'value', 'Species' is returned.
See Also
plotting_functions,getPredMort()
Other plotting functions:animateSpectra(),plot,MizerParams,missing-method,plot,MizerSim,missing-method,plotBiomass(),plotDiet(),plotFMort(),plotFeedingLevel(),plotGrowthCurves(),plotSpectra(),plotYield(),plotYieldGear(),plotting_functions
Examples
params <- NS_paramssim <- project(params, effort=1, t_max=20, t_save = 2, progress_bar = FALSE)plotPredMort(sim)plotPredMort(sim, time_range = 10:20)# Returning the data framefr <- plotPredMort(sim, return_data = TRUE)str(fr)Plot predation mortality rate of each species against size
Description
After running a projection, plot the predation mortality rate of each speciesby size. The mortality rate is averaged over the specified time range (asingle value for the time range can be used to plot a single time step).
Usage
plotPredMort( object, species = NULL, time_range, all.sizes = FALSE, highlight = NULL, return_data = FALSE, ...)plotlyPredMort(object, species = NULL, time_range, highlight = NULL, ...)Arguments
object | An object of classMizerSim orMizerParams. |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
time_range | The time range (either a vector of values, a vector of minand max time, or a single value) to average the abundances over. Default isthe final time step. Ignored when called with aMizerParamsobject. |
all.sizes | If TRUE, then predation mortality is plotted also for sizesoutside a species' size range. Default FALSE. |
highlight | Name or vector of names of the species to be highlighted. |
return_data | A boolean value that determines whether the formatted dataused for the plot is returned instead of the plot itself. Default value is FALSE |
... | Other arguments (currently unused) |
Value
A ggplot2 object, unlessreturn_data = TRUE, in which case a dataframe with the three variables 'w', 'value', 'Species' is returned.
See Also
plotting_functions,getPredMort()
Other plotting functions:animateSpectra(),plot,MizerParams,missing-method,plot,MizerSim,missing-method,plotBiomass(),plotDiet(),plotFMort(),plotFeedingLevel(),plotGrowthCurves(),plotSpectra(),plotYield(),plotYieldGear(),plotting_functions
Examples
params <- NS_paramssim <- project(params, effort=1, t_max=20, t_save = 2, progress_bar = FALSE)plotPredMort(sim)plotPredMort(sim, time_range = 10:20)# Returning the data framefr <- plotPredMort(sim, return_data = TRUE)str(fr)Plot the abundance spectra
Description
Plots the number density multiplied by a power of the weight, with the powerspecified by thepower argument.
Usage
plotSpectra( object, species = NULL, time_range, geometric_mean = FALSE, wlim = c(NA, NA), ylim = c(NA, NA), power = 1, biomass = TRUE, total = FALSE, resource = TRUE, background = TRUE, highlight = NULL, return_data = FALSE, ...)plotlySpectra( object, species = NULL, time_range, geometric_mean = FALSE, wlim = c(NA, NA), ylim = c(NA, NA), power = 1, biomass = TRUE, total = FALSE, resource = TRUE, background = TRUE, highlight = NULL, ...)Arguments
object | An object of classMizerSim orMizerParams. |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
time_range | The time range (either a vector of values, a vector of minand max time, or a single value) to average the abundances over. Default isthe final time step. Ignored when called with aMizerParamsobject. |
geometric_mean |
|
wlim | A numeric vector of length two providing lower and upper limitsfor the w axis. Use NA to refer to the existing minimum or maximum. Datais filtered to this range and the axis limits are set accordingly. |
ylim | A numeric vector of length two providing lower and upper limitsfor the y axis. Use NA to refer to the existing minimum or maximum. Anyvalues below 1e-20 are always cut off. Data is filtered to this range andthe axis limits are set accordingly. |
power | The abundance is plotted as the number density times the weightraised to |
biomass |
|
total | A boolean value that determines whether the total over allspecies in the system is plotted as well. Note that even if the plotonly shows a selection of species, the total is including all species.Default is FALSE. |
resource | A boolean value that determines whether resource is included.Default is TRUE. |
background | A boolean value that determines whether background speciesare included. Ignored if the model does not contain background species.Default is TRUE. |
highlight | Name or vector of names of the species to be highlighted. |
return_data | A boolean value that determines whether the formatted dataused for the plot is returned instead of the plot itself. Default value is FALSE |
... | Other arguments (currently unused) |
Details
When called with aMizerSim object, the abundance is averagedover the specified time range (a single value for the time range can be usedto plot a single time step). When called with aMizerParamsobject the initial abundance is plotted.
Value
A ggplot2 object, unlessreturn_data = TRUE, in which case a dataframe with the four variables 'w', 'value', 'Species', 'Legend' isreturned.
See Also
Other plotting functions:animateSpectra(),plot,MizerParams,missing-method,plot,MizerSim,missing-method,plotBiomass(),plotDiet(),plotFMort(),plotFeedingLevel(),plotGrowthCurves(),plotPredMort(),plotYield(),plotYieldGear(),plotting_functions
Examples
params <- NS_paramssim <- project(params, effort=1, t_max=20, t_save = 2, progress_bar = FALSE)plotSpectra(sim)plotSpectra(sim, wlim = c(1e-6, NA))plotSpectra(sim, time_range = 10:20)plotSpectra(sim, time_range = 10:20, power = 0)plotSpectra(sim, species = c("Cod", "Herring"), power = 1)# Returning the data framefr <- plotSpectra(sim, return_data = TRUE)str(fr)Plot the total yield of species through time
Description
After running a projection, the total yield of each species across allfishing gears can be plotted against time. The yield is obtained withgetYield().
Usage
plotYield( sim, sim2, species = NULL, total = FALSE, log = TRUE, highlight = NULL, return_data = FALSE, ...)plotlyYield( sim, sim2, species = NULL, total = FALSE, log = TRUE, highlight = NULL, ...)Arguments
sim | An object of classMizerSim |
sim2 | An optional second object of classMizerSim. Ifthis is provided its yields will be shown on the same plot in bolder lines. |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
total | A boolean value that determines whether the total over allspecies in the system is plotted as well. Note that even if the plotonly shows a selection of species, the total is including all species.Default is FALSE. |
log | Boolean whether yield should be plotted on a logarithmic axis.Defaults to true. |
highlight | Name or vector of names of the species to be highlighted. |
return_data | A boolean value that determines whether the formatted dataused for the plot is returned instead of the plot itself. Default value is FALSE |
... | Other arguments (currently unused) |
Value
A ggplot2 object, unlessreturn_data = TRUE, in which case a dataframe with the three variables 'Year', 'Yield', 'Species' is returned.
See Also
Other plotting functions:animateSpectra(),plot,MizerParams,missing-method,plot,MizerSim,missing-method,plotBiomass(),plotDiet(),plotFMort(),plotFeedingLevel(),plotGrowthCurves(),plotPredMort(),plotSpectra(),plotYieldGear(),plotting_functions
Examples
params <- NS_paramssim <- project(params, effort = 1, t_max = 20, t_save = 0.2, progress_bar = FALSE)plotYield(sim)plotYield(sim, species = c("Cod", "Herring"), total = TRUE)# Comparing with yield from twice the effortsim2 <- project(params, effort=2, t_max=20, t_save = 0.2, progress_bar = FALSE)plotYield(sim, sim2, species = c("Cod", "Herring"), log = FALSE)# Returning the data framefr <- plotYield(sim, return_data = TRUE)str(fr)Plot the total yield of each species by gear through time
Description
After running a projection, the total yield of each species by fishing gearcan be plotted against time.
Usage
plotYieldGear( sim, species = NULL, gears = NULL, total = FALSE, highlight = NULL, return_data = FALSE, ...)plotlyYieldGear(sim, species = NULL, total = FALSE, highlight = NULL, ...)Arguments
sim | An object of classMizerSim |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
gears | A vector of gear names to be included in the plot. Default isall gears. |
total | A boolean value that determines whether the total over allspecies in the system is plotted as well. Note that even if the plotonly shows a selection of species, the total is including all species.Default is FALSE. |
highlight | Name or vector of names of the species to be highlighted. |
return_data | A boolean value that determines whether the formatted dataused for the plot is returned instead of the plot itself. Default value is FALSE |
... | Other arguments (currently unused) |
Details
This plot is pretty easy to do by hand. It justgets the biomass using thegetYieldGear() method and plots usingthe ggplot2 package. You can then fiddle about with colours and linetypesetc. Just look at the source code for details.
Value
A ggplot2 object, unlessreturn_data = TRUE, in which case a dataframe with the four variables 'Year', 'Yield', 'Species' and 'Gear' isreturned.
See Also
plotting_functions,getYieldGear()
Other plotting functions:animateSpectra(),plot,MizerParams,missing-method,plot,MizerSim,missing-method,plotBiomass(),plotDiet(),plotFMort(),plotFeedingLevel(),plotGrowthCurves(),plotPredMort(),plotSpectra(),plotYield(),plotting_functions
Examples
params <- NS_paramssim <- project(params, effort=1, t_max=20, t_save = 0.2, progress_bar = FALSE)plotYieldGear(sim)plotYieldGear(sim, species = c("Cod", "Herring"), total = TRUE)# Returning the data framefr <- plotYieldGear(sim, return_data = TRUE)str(fr)Plotting observed vs. model yields
Description
If yield observations are available for at least some species via the
yield_observed column in the species parameter data frame, this functionplots the yield of each species in the model against the observedyields. When called with a MizerSim object, the plot will use the modelyields predicted for the final time step in the simulation.
Usage
plotYieldObservedVsModel( object, species = NULL, ratio = FALSE, log_scale = TRUE, return_data = FALSE, labels = TRUE, show_unobserved = FALSE)plotlyYieldObservedVsModel( object, species = NULL, ratio = FALSE, log_scale = TRUE, return_data = FALSE, show_unobserved = FALSE)Arguments
object | An object of classMizerParams orMizerSim. |
species | The species to be included. Optional. By default all observedyields will be included. A vector of species names, or a numeric vectorwith the species indices, or a logical vector indicating for each specieswhether it is to be included (TRUE) or not. |
ratio | Whether to plot model yield vs. observed yield (FALSE) orthe ratio of model : observed yield (TRUE). Default is FALSE. |
log_scale | Whether to plot on the log10 scale (TRUE) or not (FALSE).For the non-ratio plot this applies for both axes, for the ratio plot onlythe x-axis is on the log10 scale. Default is TRUE. |
return_data | Whether to return the data frame for the plot (TRUE) ornot (FALSE). Default is FALSE. |
labels | Whether to show text labels for each species (TRUE) or not(FALSE). Default is TRUE. |
show_unobserved | Whether to include also species for which noyield observation is available. If TRUE, these species will beshown as if their observed yield was equal to the model yield. |
Details
Before you can use this function you will need to have added ayield_observed column to your model which gives the observed yield ingrams per year. For species for which you have no observed yield, you should setthe value in theyield_observed column to 0 or NA.
The total relative error is shown in the caption of the plot, calculated by
TRE = \sum_i|1-\rm{ratio_i}|
where\rm{ratio_i} is the ratio of model yield / observedyield for species i.
Value
A ggplot2 object with the plot of model yield by species comparedto observed yield. Ifreturn_data = TRUE, the data frame used tocreate the plot is returned instead of the plot.
Examples
# create an exampleparams <- NS_paramsspecies_params(params)$yield_observed <- c(0.8, 61, 12, 35, 1.6, NA, 10, 7.6, 135, 60, 30, NA)params <- calibrateYield(params)# Plot with default optionsplotYieldObservedVsModel(params)# Plot including also species without observationsplotYieldObservedVsModel(params, show_unobserved = TRUE)# Show the ratio insteadplotYieldObservedVsModel(params, ratio = TRUE)Description of the plotting functions
Description
Mizer provides a range of plotting functions for visualising the resultsof running a simulation, stored in a MizerSim object, or the initial statestored in a MizerParams object.Every plotting function exists in two versions,plotSomething andplotlySomething. The plotly version is more interactive but notsuitable for inclusion in documents.
Details
This table shows the available plotting functions.
| Plot | Description |
plotBiomass() | Plots the total biomass of each species through time. A time range to be plotted can be specified. The size range of the community can be specified in the same way as forgetBiomass(). |
plotSpectra() | Plots the abundance (biomass or numbers) spectra of each species and the background community. It is possible to specify a minimum size which is useful for truncating the plot. |
plotFeedingLevel() | Plots the feeding level of each species against size. |
plotPredMort() | Plots the predation mortality of each species against size. |
plotFMort() | Plots the total fishing mortality of each species against size. |
plotYield() | Plots the total yield of each species across all fishing gears against time. |
plotYieldGear() | Plots the total yield of each species by gear against time. |
plotDiet() | Plots the diet composition at size for a given predator species. |
plotGrowthCurves() | Plots the size as a function of age. |
plot() | Produces 5 plots (plotFeedingLevel(),plotBiomass(),plotPredMort(),plotFMort() andplotSpectra()) in the same window. |
These functions use the ggplot2 package and return the plot as a ggplotobject. This means that you can manipulate the plot further after itscreation using the ggplot grammar of graphics. The corresponding functionnames withplot replaced byplotly produce interactive plotswith the help of the plotly package.
While most plot functions take their data from a MizerSim object, some ofthose that make plots representing data at a single time can also take theirdata from the initial values in a MizerParams object.
Where plots show results for species, the line colour and line type for eachspecies are specified by thelinecolour andlinetype slots inthe MizerParams object. These were either taken from a default palettehard-coded intoemptyParams() or they were specified by the userin the species parameters dataframe used to set up the MizerParams object.Thelinecolour andlinetype slots hold named vectors, named bythe species. They can be overwritten by the user at any time.
Most plots allow the user to select to show only a subset of species,specified as a vector in thespecies argument to the plot function.
The ordering of the species in the legend is the same as the ordering inthe species parameter data frame.
See Also
summary_functions,indicator_functions
Other plotting functions:animateSpectra(),plot,MizerParams,missing-method,plot,MizerSim,missing-method,plotBiomass(),plotDiet(),plotFMort(),plotFeedingLevel(),plotGrowthCurves(),plotPredMort(),plotSpectra(),plotYield(),plotYieldGear()
Examples
sim <- NS_sim# Some example plotsplotFeedingLevel(sim)# Plotting only a subset of speciesplotFeedingLevel(sim, species = c("Cod", "Herring"))# Specifying new colours and linetypes for some speciessim@params@linetype["Cod"] <- "dashed"sim@params@linecolour["Cod"] <- "red"plotFeedingLevel(sim, species = c("Cod", "Herring"))# Manipulating the plotlibrary(ggplot2)p <- plotFeedingLevel(sim)p <- p + geom_hline(aes(yintercept = 0.7))p <- p + theme_bw()pPower-law predation kernel
Description
This predation kernel is a power-law, with sigmoidal cut-offs at large andsmall predator/prey mass ratios.
Usage
power_law_pred_kernel( ppmr, kernel_exp, kernel_l_l, kernel_u_l, kernel_l_r, kernel_u_r)Arguments
ppmr | A vector of predator/prey size ratios at which to evaluate thepredation kernel. |
kernel_exp | The exponent of the power law |
kernel_l_l | The location of the left, rising sigmoid |
kernel_u_l | The shape of the left, rising sigmoid |
kernel_l_r | The location of the right, falling sigmoid |
kernel_u_r | The shape of the right, falling sigmoid |
Details
The return value is calculated as
ppmr^kernel_exp / (1 + (exp(kernel_l_l) / ppmr)^kernel_u_l) / (1 + (ppmr / exp(kernel_l_r))^kernel_u_r)
The parameters need to be given as columns in the species parameterdataframe.
Value
A vector giving the value of the predation kernel at each of thepredator/prey mass ratios in theppmr argument.
See Also
Other predation kernel:box_pred_kernel(),lognormal_pred_kernel(),truncated_lognormal_pred_kernel()
Examples
params <- NS_params# Set all required paramters before changing kernel typespecies_params(params)["Cod", "kernel_exp"] <- -0.8species_params(params)["Cod", "kernel_l_l"] <- 4.6species_params(params)["Cod", "kernel_u_l"] <- 3species_params(params)["Cod", "kernel_l_r"] <- 12.5species_params(params)["Cod", "kernel_u_r"] <- 4.3species_params(params)["Cod", "kernel_type"] <- "power_law"plot(w_full(params), getPredKernel(params)["Cod", 10, ], type="l", log="x")Project size spectrum forward in time
Description
Runs the size spectrum model simulation.The function returns an object of typeMizerSim that can then be explored with a range ofsummary_functions,indicator_functions andplotting_functions.
Usage
project( object, effort, t_max = 100, dt = 0.1, t_save = 1, t_start = 0, initial_n, initial_n_pp, append = TRUE, progress_bar = TRUE, ...)Arguments
object | Either aMizerParams object or aMizerSim object (which contains a |
effort | The effort of each fishing gear through time. See notes below. |
t_max | The number of years the projection runs for. The default valueis 100. This argument is ignored if an array is used for the |
dt | Time step of the solver. The default value is 0.1. |
t_save | The frequency with which the output is stored. The defaultvalue is 1. This argument is ignored if an array is used for the |
t_start | The the year of the start of the simulation. The simulationwill cover the period from |
initial_n |
|
initial_n_pp |
|
append | A boolean that determines whether the new simulation resultsare appended to the previous ones. Only relevant if |
progress_bar | Either a boolean value to determine whether a progressbar should be shown in the console, or a shiny Progress object to implementa progress bar in a shiny app. |
... | Other arguments will be passed to rate functions. |
Value
An object of classMizerSim.
Note
Theeffort argument specifies the level of fishing effort during thesimulation. If it is not supplied, the initial effort stored in the paramsobject is used. The effort can be specified in four different ways:
A single numeric value. This specifies the effort of all fishing gearswhich is constant through time (i.e. all the gears have the same constanteffort).
A named vector whose names match with existing gear names.The values in the vector specify the constant fishing effort for thosefishing gears, i.e. the effort is constant through time. Theeffort for gears that are not included in the effort vector is set to 0.
A numerical vector which has the same length as the number of fishinggears. The values in the vector specify theconstant fishing effort of each of the fishing gears, with the orderingassumed to be the same as in the MizerParams object.
A numerical array with dimensions time x gear. This specifies thefishing effort of each gear at each time step. The first dimension, time,must be named numerically and increasing. The second dimension of the arraymust be named and the names must correspond to the gear names in the
MizerParamsobject. The value for the effort for a particular timeis used during the interval from that time to the next time in the array.
If effort is specified as an array then the smallest time in the array isused as the initial time for the simulation. Otherwise the initial time isset to the final time of the previous simulation ifobject is aMizerSim object or tot_start otherwise. Also, if the effort isan array then thet_max andt_save arguments are ignored and thesimulation times will be taken from the effort array.
If theobject argument is of classMizerSim then the initialvalues for the simulation are taken from the final values in theMizerSim object and the corresponding arguments to this function willbe ignored.
Examples
params <- NS_params# With constant fishing effort for all gears for 20 time stepssim <- project(params, t_max = 20, effort = 0.5)# With constant fishing effort which is different for each geareffort <- c(Industrial = 0, Pelagic = 1, Beam = 0.5, Otter = 0.5)sim <- project(params, t_max = 20, effort = effort)# With fishing effort that varies through time for each geargear_names <- c("Industrial","Pelagic","Beam","Otter")times <- seq(from = 1, to = 10, by = 1)effort_array <- array(NA, dim = c(length(times), length(gear_names)), dimnames = list(time = times, gear = gear_names))effort_array[,"Industrial"] <- 0.5effort_array[,"Pelagic"] <- seq(from = 1, to = 2, length = length(times))effort_array[,"Beam"] <- seq(from = 1, to = 0, length = length(times))effort_array[,"Otter"] <- seq(from = 1, to = 0.5, length = length(times))sim <- project(params, effort = effort_array)Project to steady state
Description
Run the full dynamics, as inproject(), but stop once the change has sloweddown sufficiently, in the sense that the distance between states atsuccessive time steps is less thantol. You determine how the distance iscalculated.
Usage
projectToSteady( params, effort = params@initial_effort, distance_func = distanceSSLogN, t_per = 1.5, t_max = 100, dt = 0.1, tol = 0.1 * t_per, return_sim = FALSE, progress_bar = TRUE, ...)Arguments
params | AMizerParams object |
effort | The fishing effort to be used throughout the simulation.This must be a vector or list with one named entry per fishing gear. |
distance_func | A function that will be called after every |
t_per | The simulation is broken up into shorter runs of |
t_max | The maximum number of years to run the simulation. Default is 100. |
dt | The time step to use in |
tol | The simulation stops when the relative change in the eggproduction RDI over |
return_sim | If TRUE, the function returns the MizerSim object holdingthe result of the simulation run, saved at intervals of |
progress_bar | A shiny progress object to implement a progress bar in ashiny app. Default FALSE. |
... | Further arguments will be passed on to your distance function. |
Value
A MizerParams or a MizerSim object
See Also
distanceSSLogN(),distanceMaxRelRDI()
Project abundances by a given number of time steps into the future
Description
This is an internal function used by the user-facingproject() function.It is of potential interest only to mizer extension authors.
Usage
project_simple( params, n = params@initial_n, n_pp = params@initial_n_pp, n_other = params@initial_n_other, effort = params@initial_effort, t = 0, dt = 0.1, steps, resource_dynamics_fn = get(params@resource_dynamics), other_dynamics_fns = lapply(params@other_dynamics, get), rates_fns = lapply(params@rates_funcs, get), ...)Arguments
params | A MizerParams object. |
n | An array (species x size) with the number density at start ofsimulation. |
n_pp | A vector (size) with the resource number density at start ofsimulation. |
n_other | A named list with the abundances of other components at startof simulation. |
effort | The fishing effort to be used throughout the simulation. Thismust be a vector or list with one named entry per fishing gear. |
t | Time at the start of the simulation. |
dt | Size of time step. |
steps | The number of time steps by which to project. |
resource_dynamics_fn | The function for the resourcedynamics. See Details. |
other_dynamics_fns | List with the functions for thedynamics of the other components. See Details. |
rates_fns | List with the functions for calculatingthe rates. See Details. |
... | Other arguments that are passed on to the rate functions. |
Details
The function does not check its arguments because it is meant to be as fastas possible to allow it to be used in a loop. For example, it is called inproject() once for every saved value. The function also does not save itsintermediate results but only returns the result at timet + dt * steps.During this time it uses the constant fishing efforteffort.
The functional arguments can be calculated from slots in theparams objectwith
resource_dynamics_fn <- get(params@resource_dynamics)other_dynamics_fns <- lapply(params@other_dynamics, get)rates_fns <- lapply(params@rates_funcs, get)
The reason the function does not do that itself is to shave 20 microsecondsof its running time, which pays when the function is called hundreds oftimes in a row.
This function is also used insteady(). In between calls toproject_simple() thesteady() function checks whether the values arestill changing significantly, so that it can stop when a steady state hasbeen approached. Mizer extension packages might have a similar need to runa simulation repeatedly for short periods to run some other code inbetween. Because this code may want to use the values of the rates at thefinal time step, these too are included in the returned list.
Value
List with the final values ofn,n_pp andn_other,rates.
Objects exported from other packages
Description
These objects are imported from other packages. Follow the linksbelow to see their documentation.
- reshape2
Remove species
Description
This function simply removes all entries from the MizerParams object thatrefer to the selected species. It does not recalculate the steady state forthe remaining species or retune their reproductive efficiency.
Usage
removeSpecies(params, species)Arguments
params | A mizer params object for the original system. |
species | The species to be removed. A vector of species names, or anumeric vector of species indices, or a logical vector indicating foreach species whether it is to be removed (TRUE) or not. |
Value
An object of typeMizerParams
Examples
params <- NS_paramsspecies_params(params)$speciesparams <- removeSpecies(params, c("Cod", "Haddock"))species_params(params)$speciesRename gears
Description
Changes the names of gears in a MizerParams object. This involves forexample changing the gear dimension names of selectivity and catchabilityarrays appropriately.
Usage
renameGear(params, replace)Arguments
params | A mizer params object |
replace | A named character vector, with new names as values, and oldnames as names. |
Value
An object of typeMizerParams
Examples
replace <- c(Industrial = "Trawl", Otter = "Beam_Trawl")params <- renameGear(NS_params, replace)gear_params(params)$gearRename species
Description
Changes the names of species in a MizerParams object. This involves forexample changing the species dimension names of rate arrays appropriately.
Usage
renameSpecies(params, replace)Arguments
params | A mizer params object |
replace | A named character vector, with new names as values, and oldnames as names. |
Value
An object of typeMizerParams
Examples
replace <- c(Cod = "Kabeljau", Haddock = "Schellfisch")params <- renameSpecies(NS_params, replace)species_params(params)$speciesKeep resource abundance constant
Description
If you set your resource dynamics to use this function then the resourceabundances are kept constant over time.
Usage
resource_constant(params, n_pp, ...)Arguments
params | AMizerParams object |
n_pp | A vector of the resource abundance by size |
... | Unused |
Details
To set your model to keep the resource constant over time you do
resource_dynamics(params) <- "resource_constant"
where you should replaceparams with the name of the variable holding yourMizerParams object.
Value
Vector containing the resource number density in each size class atthe next timestep
See Also
Other resource dynamics functions:resource_logistic(),resource_semichemostat()
Examples
params <- NS_paramsresource_dynamics(params) <- "resource_constant"Project resource using logistic model
Description
If you set your resource dynamics to use this function then the timeevolution of the resource spectrum is described by a logistic equation
\frac{\partial N_R(w,t)}{\partial t} = r_R(w) N_R(w)\Big[ 1 - \frac{N_R(w,t)}{c_R (w)} \Big] - \mu_R(w, t) N_R(w,t)
Usage
resource_logistic( params, n, n_pp, n_other, rates, t, dt, resource_rate, resource_capacity, ...)balance_resource_logistic(params, resource_rate, resource_capacity)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size) |
n_pp | A vector of the resource abundance by size |
n_other | A list with the abundances of other components |
rates | A list of rates as returned by |
t | The current time |
dt | Time step |
resource_rate | Resource replenishment rate |
resource_capacity | Resource carrying capacity |
... | Unused |
Details
Herer_R(w) is the resource regeneration rate andc_R(w) is thecarrying capacity in the absence of predation. These parameters are changedwithsetResource(). The mortality\mu_R(w, t) isdue to predation by consumers and is calculate withgetResourceMort().
This function uses the analytic solution of the above equation to calculatethe resource abundance at timet + dt from all abundances and rates at timet, keeping the mortality fixed during the timestep.
To set your model to use logistic dynamics for the resource you do
params <- setResource(params, resource_dynamics = "resource_logistic", resource_level = 0.5)
where you should replaceparams with the name of the variable holding yourMizerParams object. You can of course choose any value between 0 and 1 forthe resource level.
Thebalance_resource_logistic() function is called bysetResource() todetermine the values of the resource parameters that are needed to make thereplenishment rate at each size equal the consumption rate at that size, ascalculated bygetResourceMort(). It should be called with only one ofresource_rate orresource_capacity should and will return a named listwith the values for both.
Value
Vector containing the resource number density in each size class atthe next timestep
See Also
Other resource dynamics functions:resource_constant(),resource_semichemostat()
Resource parameters
Description
The recommended way to change the resource dynamics parameters is to usesetResource(). Theresource_params list contains values that are helpfulin setting up the actual size-dependent parameters withsetResource(). Ifyou have specified a custom resource dynamics function that requiresadditional parameters, then these should also be added to theresource_params list.
Usage
resource_params(params)resource_params(params) <- valueArguments
params | A MizerParams object |
value | A named list of resource parameters. |
Details
Theresource_params list will at least contain the slotskappa,lambda,w_pp_cutoff andn.
The resource parametern is the exponent for the power-law form for thereplenishment rater_R(w):
r_R(w) = r_R\, w^{n-1}.
The resource parameterlambda (\lambda) is the exponent for thepower-law form for the carrying capacityc_R(w) andw_pp_cutoff isits cutoff value:
c_R(w) = c_R w^{-\lambda}
for allw less thanw_pp_cutoff and zero for larger sizes.
The resource parameterkappa (\kappa) is slightly different in thatit is not a parameter for the resource dynamics. Instead it is a parameterthat determined the initial resource abundance when the model was created:
N_R(w) = \kappa\, w^{-\lambda}
for allw less thanw_pp_cutoff and zero for larger sizes. Note thatthe initial resource abundance is not changed bysetResource() even if youchange the value ofkappa in theresource_params.
Value
A named list of resource parameters.
See Also
Project resource using semichemostat model
Description
If you set your resource dynamics to use this function then the timeevolution of the resource spectrum is described by a semi-chemostat equation
\frac{\partial N_R(w,t)}{\partial t} = r_R(w) \Big[ c_R (w) - N_R(w,t) \Big] - \mu_R(w, t) N_R(w,t)
Usage
resource_semichemostat( params, n, n_pp, n_other, rates, t, dt, resource_rate, resource_capacity, ...)balance_resource_semichemostat(params, resource_rate, resource_capacity)Arguments
params | AMizerParams object |
n | A matrix of species abundances (species x size) |
n_pp | A vector of the resource abundance by size |
n_other | A list with the abundances of other components |
rates | A list of rates as returned by |
t | The current time |
dt | Time step |
resource_rate | Resource replenishment rate |
resource_capacity | Resource carrying capacity |
... | Unused |
Details
Herer_R(w) is the resource regeneration rate andc_R(w) is thecarrying capacity in the absence of predation. These parameters are changedwithsetResource(). The mortality\mu_R(w, t) isdue to predation by consumers and is calculate withgetResourceMort().
This function uses the analytic solution of the above equation to calculatethe resource abundance at timet + dt from all abundances and rates at timet, keeping the mortality fixed during the timestep.
To set your model to use semichemostat dynamics for the resource you do
params <- setResource(params, resource_dynamics = "resource_semichemostat", resource_level = 0.5)
where you should replaceparams with the name of the variable holding yourMizerParams object. You can of course choose any value between 0 and 1 forthe resource level.
Thebalance_resource_semichemostat() function is called bysetResource()to determine the values of the resource parameters that are needed to makethe replenishment rate at each size equal the consumption rate at that size,as calculated bygetResourceMort(). It should be called with only one ofresource_rate orresource_capacity and will return a named listwith the values for both.
Value
Vector containing the resource number density in each size class atthe next timestep
See Also
Other resource dynamics functions:resource_constant(),resource_logistic()
Save a MizerParams object to file, and restore it
Description
saveParams() saves a MizerParams object to a file. This can then berestored withreadParams().
Usage
saveParams(params, file)readParams(file)Arguments
params | A MizerParams object |
file | The name of the file or a connection where the MizerParams objectis saved to or read from. |
Details
Issues a warning if the model you are saving relies on some custom functions.Before saving a model you may want to set its metadata withsetMetadata().
Value
NULL invisibly
Change scale of the model
Description
The abundances in mizer and some rates depend on the size of the area towhich they refer. So they could be given per square meter or per squarekilometer or for an entire study area or any other choice of yours. Thisfunction allows you to change the scale of the model by automaticallychanging the abundances and rates accordingly.
Usage
scaleModel(params, factor)Arguments
params | A MizerParams object |
factor | The factor by which the scale is multiplied |
Details
If you rescale the model by a factorc then this function makes thefollowing rescalings in the params object:
The initial abundances are rescaled by
c.The search volume is rescaled by
1/c.The resource carrying capacity is rescaled by
cThe maximum reproduction rate
R_{max}is rescaled byc.
The effect of this is that the dynamics of the rescaled model are identicalto those of the unscaled model, in the sense that it does not matter whetherone first callsscaleModel() and then runs a simulation withproject() or whether one first runs a simulation and then rescales theresulting abundances.
Note that if you use non-standard resource dynamics or other components thenyou may need to rescale additional parameters that appear in those dynamics.
In practice you will need to use some observations to set the scale for yourmodel. If you have biomass observations you can usecalibrateBiomass(),if you have yearly yields you can usecalibrateYield().
Value
The rescaled MizerParams object
Set Beverton-Holt reproduction without changing the steady state
Description
Takes a MizerParams object
params with arbitrary density dependence inreproduction andreturns a MizerParams object with Beverton-Holt density-dependence in such away that the energy invested into reproduction by the mature individualsleads to the reproduction rate that is required to maintain the given eggabundance. Hence if you have tuned yourparams object to describe aparticular steady state, then setting the Beverton-Holt density dependencewith this function will leave you with the exact same steady state. Byspecifying one of the parameterserepro,R_max orreproduction_levelyou pick the desired reproduction curve. More details of these parameters areprovided below.
Usage
setBevertonHolt( params, R_factor = deprecated(), erepro, R_max, reproduction_level)Arguments
params | A MizerParams object |
R_factor | |
erepro | Reproductive efficiency for each species. See details. |
R_max | Maximum reproduction rate. See details. |
reproduction_level | Sets |
Details
With Beverton-Holt density dependence the relation between the energyinvested into reproduction and the number of eggs hatched is determinedby two parameters: the reproductive efficiencyerepro and the maximumreproduction rateR_max.
If no maximum is imposed on the reproduction rate(R_{max} = \infty) then the resulting density-independentreproduction rateR_{di} is proportionalto the total rateE_R at which energy is invested into reproduction,
R_{di} = \frac{\rm{erepro}}{2 w_{min}} E_R,
where the proportionality factor is given by the reproductive efficiencyerepro divided by the egg sizew_min to convert energy to egg number anddivided by 2 to account for the two sexes.
Imposing a finite maximum reproduction rateR_{max} leads to anon-linear relationship between energy invested and eggs hatched. Thisdensity-dependent reproduction rateR_{dd} is given as
R_{dd} = R_{di}\frac{R_{max}}{R_{di} + R_{max}}.
(All quantities in the above equations are species-specific but we droppedthe species index for simplicity.)
The following plot illustrates the Beverton-Holt density dependence in thereproduction rate for two different choices of parameters.
This plot shows that a given energyE_R invested into reproduction canlead to the same reproduction rateR_{dd} with different choicesof the parametersR_max anderepro.R_max determines the asymptote ofthe curve anderepro its initial slope. A higherR_max coupled with alowererepro (black curves) can give the same value as a lowerR_maxcoupled with a highererepro (blue curves).
For the given initial state in the MizerParams objectparams one cancalculate the energyE_R that is invested into reproduction by themature individuals and the reproduction rateR_{dd} that isrequired to keep the egg abundance constant. These two values determine thelocation of the black dot in the above graph. You then only need oneparameter to select one curve from the family of Beverton-Holt curves goingthrough that point. This parameter can beerepro orR_max. Instead ofR_max you can alternatively specify thereproduction_level which is theratio between the density-dependent reproduction rateR_{dd} andthe maximal reproduction rateR_{max}.
If you do not provide a value for any of the reproduction parameterarguments, thenerepro will be set to the value it has in the currentspecies parameter data frame. If you do provide one of the reproductionparameters, this can be either a vector with one value for eachspecies, or a named vector where the names determine which species areaffected, or a single unnamed value that is then used for all species. Anyspecies for which the given value isNA will remain unaffected.
The values forR_max must be larger thanR_{dd} and can rangeup toInf. If a smaller value is requested a warning is issued and thevalue is increased to the value required for a reproduction level of 0.99.
The values for thereproduction_level must be positive andless than 1. The values forerepro must be large enough to allow therequired reproduction rate. If a smaller value is requested a warning isissued and the value is increased to the smallest possible value. The valuesforerepro should also be smaller than 1 to be physiologically sensible,but this is not enforced by the function.
As can be seen in the graph above, choosing a lower value forR_max or ahigher value forerepro means that near the steady state the reproductionwill be less sensitive to a change in the energy invested into reproductionand hence less sensitive to changes in the spawning stock biomass or itsenergy income. As a result the species will also be less sensitive tofishing, leading to a higher F_MSY.
Value
A MizerParams object
Examples
params <- NS_paramsspecies_params(params)$erepro# Attempting to set the same erepro for all speciesparams <- setBevertonHolt(params, erepro = 0.1)t(species_params(params)[, c("erepro", "R_max")])# Setting erepro for some speciesparams <- setBevertonHolt(params, erepro = c("Gurnard" = 0.6, "Plaice" = 0.95))t(species_params(params)[, c("erepro", "R_max")])# Setting R_maxR_max <- 1e17 * species_params(params)$w_max^-1params <- setBevertonHolt(NS_params, R_max = R_max)t(species_params(params)[, c("erepro", "R_max")])# Setting reproduction_levelparams <- setBevertonHolt(params, reproduction_level = 0.3)t(species_params(params)[, c("erepro", "R_max")])Set line colours and line types to be used in mizer plots
Description
Used for setting the colour and type of lines representing "Total","Resource", "Fishing", "Background", "External" and possibly other categoriesin plots.
Usage
setColours(params, colours)getColours(params)setLinetypes(params, linetypes)getLinetypes(params)Arguments
params | A MizerParams object |
colours | A named list or named vector of line colours. |
linetypes | A named list or named vector of linetypes. |
Details
Colours for names that already had a colour set for them will be overwrittenby the colour you specify. Colours for names that did not yet have a colourwill be appended to the list of colours.
Do not use this for setting the colours or linetypes of species, becausethose are determined by setting thelinecolour andlinetype variables inthe species parameter data frame.
You can use the same colours in your own ggplot2 plots by addingscale_colour_manual(values = getColours(params)) to your plot. Similarlyyou can use the linetypes withscale_linetype_manual(values = getLinetypes(params)).
Value
setColours: The MizerParams object with updated line colours
getColours(): A named vector of colours
setLinetypes(): The MizerParams object with updated linetypes
getLinetypes(): A named vector of linetypes
Examples
params <- setColours(NS_params, list("Resource" = "red","Total" = "#0000ff"))params <- setLinetypes(NS_params, list("Total" = "dotted"))# Set colours and linetypes for speciesspecies_params(params)["Cod", "linecolour"] <- "black"species_params(params)["Cod", "linetype"] <- "dashed"plotSpectra(params, total = TRUE)getColours(params)getLinetypes(params)Add a dynamical ecosystem component
Description
By default, mizer models any number of size-resolved consumer speciesand a single size-resolved resource spectrum. Your model may requireadditional components, like for example detritus or carrion or multipleresources or .... This function allows you to set up such components.
Usage
setComponent( params, component, initial_value, dynamics_fun, encounter_fun, mort_fun, component_params)removeComponent(params, component)Arguments
params | A MizerParams object |
component | Name of the component |
initial_value | Initial value of the component |
dynamics_fun | Name of function to calculate value at the next time step |
encounter_fun | Name of function to calculate contribution to encounterrate. Optional. |
mort_fun | Name of function to calculate contribution to themortality rate. Optional. |
component_params | Object holding the parameters needed by the componentfunctions. This could for example be a named list of parameters. Optional. |
Details
The component can be a number, a vector, an array, a list, or any otherdata structure you like.
If you set a component with a new name, the new component will be addedto the existing components. If you set a component with an existing name,that component will be overwritten. You can remove a component withremoveComponent().
Value
The updated MizerParams object
Set external encounter rate
Description
Set external encounter rate
Usage
setExtEncounter(params, ext_encounter = NULL, ...)getExtEncounter(params)ext_encounter(params)ext_encounter(params) <- valueArguments
params | MizerParams |
ext_encounter | Optional. An array (species x size) holding the externalencounter rate. If not supplied, the external encounter rate is leftunchanged. Initially is is set to 0. |
... | Unused |
value | ext_encounter |
Value
setExtEncounter(): A MizerParams object with updated external encounterrate.
getExtEncounter() or equivalentlyext_encounter(): An array(species x size) with the external encounter rate.
Setting external encounter rate
The external encounter rate is the rate at which a predator encountersfood that is not explicitly modelled. It is a rate with units mass/year.
Theext_encounter argument allows you to specify an external encounter ratethat depends on species and body size. You can see an example of this inthe Examples section of the help page forsetExtEncounter().
See Also
Other functions for setting parameters:gear_params(),setExtMort(),setFishing(),setInitialValues(),setInteraction(),setMaxIntakeRate(),setMetabolicRate(),setParams(),setPredKernel(),setReproduction(),setSearchVolume(),species_params()
Examples
params <- newMultispeciesParams(NS_species_params)#### Setting allometric encounter rate ######################## Set coefficient for each species. Here we choose 0.1 for each speciesencounter_pre <- rep(0.1, nrow(species_params(params)))# Multiply by power of size with exponent, here chosen to be 3/4# The outer() function makes it an array species x sizeallo_encounter <- outer(encounter_pre, w(params)^(3/4))# Change the external encounter rate in the params objectext_encounter(params) <- allo_encounterSet external mortality rate
Description
Set external mortality rate
Usage
setExtMort( params, ext_mort = NULL, z0pre = 0.6, z0exp = params@resource_params$n - 1, reset = FALSE, z0 = deprecated(), ...)getExtMort(params)ext_mort(params)ext_mort(params) <- valueArguments
Value
setExtMort(): A MizerParams object with updated external mortalityrate.
getExtMort() or equivalentlyext_mort(): An array (species xsize) with the external mortality.
Setting external mortality rate
The external mortality is all the mortality that is not due to fishing orpredation by predators included in the model. The external mortality could bedue to predation by predators that are not explicitly included in the model(e.g. mammals or seabirds) or due to other causes like illness. It is a ratewith units 1/year.
Theext_mort argument allows you to specify an external mortality ratethat depends on species and body size. You can see an example of this inthe Examples section of the help page forsetExtMort().
If theext_mort argument is not supplied, then the external mortality isassumed to depend only on the species, not on the size of the individual:\mu_{ext.i}(w) = z_{0.i}. The value of the constantz_0 for eachspecies is taken from thez0 column of the species parameter data frame, ifthat column exists. Otherwise it is calculated as
z_{0.i} = {\tt z0pre}_i\, w_{inf}^{\tt z0exp}.
See Also
Other functions for setting parameters:gear_params(),setExtEncounter(),setFishing(),setInitialValues(),setInteraction(),setMaxIntakeRate(),setMetabolicRate(),setParams(),setPredKernel(),setReproduction(),setSearchVolume(),species_params()
Examples
params <- newMultispeciesParams(NS_species_params)#### Setting allometric death rate ######################## Set coefficient for each species. Here we choose 0.1 for each speciesz0pre <- rep(0.1, nrow(species_params(params)))# Multiply by power of size with exponent, here chosen to be -1/4# The outer() function makes it an array species x sizeallo_mort <- outer(z0pre, w(params)^(-1/4))# Change the external mortality rate in the params objectext_mort(params) <- allo_mortSet fishing parameters
Description
Set fishing parameters
Usage
setFishing( params, selectivity = NULL, catchability = NULL, reset = FALSE, initial_effort = NULL, ...)getCatchability(params)catchability(params)catchability(params) <- valuegetSelectivity(params)selectivity(params)selectivity(params) <- valuegetInitialEffort(params)Arguments
Value
setFishing(): A MizerParams object with updated fishingparameters.
getCatchability() or equivalentlycatchability(): An array (gearx species) that holds the catchability of each species by each gear,Q_{g,i}. The names of the dimensions are "gear, "sp".
getSelectivity() or equivalentlyselectivity(): An array (gear xspecies x size) that holds the selectivity of each gear for species andsize,S_{g,i,w}. The names of the dimensions are "gear, "sp", "w".
getInitialEffort() or equivalentlyinitial_effort(): A namedvector with the initial fishing effort for each gear.
Setting fishing
Gears
Inmizer, fishing mortality is imposed on species by fishing gears. Thetotal per-capita fishing mortality (1/year) is obtained by summing over themortality from all gears,
\mu_{f.i}(w) = \sum_g F_{g,i}(w),
where the fishing mortalityF_{g,i}(w) imposed by gearg onspeciesi at sizew is calculated as:
F_{g,i}(w) = S_{g,i}(w) Q_{g,i} E_{g},
whereS is the selectivity by species, gear and size,Q is thecatchability by species and gear andE is the fishing effort by gear.
Selectivity
The selectivity at size of each gear for each species is saved as a threedimensional array (gear x species x size). Each entry has a range between 0(that gear is not selecting that species at that size) to 1 (that gear isselecting all individuals of that species of that size). This threedimensional array can be specified explicitly via theselectivityargument, but usually mizer calculates it from thegear_params slot ofthe MizerParams object.
To allow the calculation of theselectivity array, thegear_params slotmust be a data frame with one row for each gear-species combination. So iffor example a gear can select three species, then that gear contributes threerows to thegear_params data frame, one for each species it can select. Thedata frame must have columnsgear, holding the name of the gear,species,holding the name of the species, andsel_func, holding the name of thefunction that calculates the selectivity curve. Some selectivity functionsare included in the package:knife_edge(),sigmoid_length(),double_sigmoid_length(), andsigmoid_weight().Users are able to write their own size-based selectivity function. The firstargument to the function must bew and the function must return a vector ofthe selectivity (between 0 and 1) at size.
Each selectivity function may have parameters. Values for theseparameters must be included as columns in the gear parameters data.frame.The names of the columns must exactly match the names of the correspondingarguments of the selectivity function. For example, the default selectivityfunction isknife_edge() that a has sudden change of selectivity from 0 to 1at a certain size. In its help page you can see that theknife_edge()function has argumentsw andknife_edge_size. The first argument,w, issize (the function calculates selectivity at size). All selectivity functionsmust havew as the first argument. The values for the other arguments mustbe found in the gear parameters data.frame. So for theknife_edge()function there should be aknife_edge_size column. Becauseknife_edge()is the default selectivity function, theknife_edge_size argument has adefault value =w_mat.
The most commonly-used selectivity function issigmoid_length(). It has asmooth transition from 0 to 1 at a certain size. Thesigmoid_length()function has the two parametersl50 andl25 that are the lengths in cm atwhich 50% or 25% of the fish are selected by the gear. If you choose thisselectivity function then thel50 andl25 columns must be included in thegear parameters data.frame.
In case each species is only selected by one gear, the columns of thegear_params data frame can alternatively be provided as columns of thespecies_params data frame, if this is more convenient for the user to setup. Mizer will then copy these columns over to create thegear_params dataframe when it creates the MizerParams object. However changing these columnsin the species parameter data frame later will not update thegear_paramsdata frame.
Catchability
Catchability is used as an additional factor to make the link between gearselectivity, fishing effort and fishing mortality. For example, it can be setso that an effort of 1 gives a desired fishing mortality. In this way effortcan then be specified relative to a 'base effort', e.g. the effort in aparticular year.
Catchability is stored as a two dimensional array (gear x species). This caneither be provided explicitly via thecatchability argument, or theinformation can be provided via acatchability column in thegear_paramsdata frame.
In the case where each species is selected by only a single gear, thecatchability column can also be provided in thespecies_params dataframe. Mizer will then copy this over to thegear_params data frame whenthe MizerParams object is created.
Effort
The initial fishing effort is stored in theMizerParams object. If it isnot supplied, it is set to zero. The initial effort can be overruled whenthe simulation is run withproject(), where it is also possible to specifyan effort that varies through time.
See Also
Other functions for setting parameters:gear_params(),setExtEncounter(),setExtMort(),setInitialValues(),setInteraction(),setMaxIntakeRate(),setMetabolicRate(),setParams(),setPredKernel(),setReproduction(),setSearchVolume(),species_params()
Examples
str(getCatchability(NS_params))str(getSelectivity(NS_params))str(getInitialEffort(NS_params))Set initial values to values from a simulation
Description
This is used to use the results from one simulation as the starting valuesfor another simulation.
Usage
setInitialValues(params, sim, time_range, geometric_mean = FALSE)Arguments
Details
The initial abundances (for both species and resource) in theparamsobject are set to the abundances in a MizerSim object, averaged overa range of times. Similarly, the initial effort in theparams object isset to the effort in the MizerSim object, again averaged over that rangeof times.When no time range is specified, the initial values are taken from the finaltime step of the simulation.
If the model described bysim andparams has additional componentscreated withsetComponent() then the values of these components are alsoaveraged and copied toparams.
The MizerSim object must come from a model with the same set of species andgears and other components and the same size bins as the MizerParams object.Otherwise an error is raised.
Value
Theparams object with updated initial values and initial effort.Because of the way theR language works,setInitialValues() does not make the changes to theparams object that you pass to it but instead returns a new params object.So to affect the change you call the function in the formparams <- setInitialValues(params, sim).
See Also
Other functions for setting parameters:gear_params(),setExtEncounter(),setExtMort(),setFishing(),setInteraction(),setMaxIntakeRate(),setMetabolicRate(),setParams(),setPredKernel(),setReproduction(),setSearchVolume(),species_params()
Examples
params <- NS_paramssim <- project(params, t_max = 20, effort = 0.5)params <- setInitialValues(params, sim)Set species interaction matrix
Description
Set species interaction matrix
Usage
setInteraction(params, interaction = NULL)interaction_matrix(params)interaction_matrix(params) <- valueArguments
params | MizerParams object |
interaction | Optional interaction matrix of the species (predatorspecies x prey species). By default all entries are 1. See "Settinginteraction matrix" section below. |
value | An interaction matrix |
Value
setInteraction: A MizerParams object with updated interactionmatrix
interaction_matrix(): The interaction matrix (predator species xprey species)
Setting interaction matrix
You do not need to specify an interaction matrix. If you do not, then thepredator-prey interactions are purely determined by the size of predatorand prey and totally independent of the species of predator and prey.
The interaction matrix\theta_{ij} modifies the interaction of eachpair of species in the model. This can be used for example to allow fordifferent spatial overlap among the species.The values in the interaction matrix are used to scale the encountered foodand predation mortality (see on the websitethe section on predator-prey encounter rateand onpredation mortality).The first index refers to the predator species and the second to the preyspecies.
The interaction matrix is used when calculating the food encounter rate ingetEncounter() and the predation mortality rate ingetPredMort(). Itsentries are dimensionless numbers. If all the values in the interactionmatrix are equal then predator-prey interactions are determined entirely bysize-preference.
This function checks that the supplied interaction matrix is valid and thenstores it in theinteraction slot of theparams object.
The order of the columns and rows of theinteraction argument should bethe same as the order in the species params data frame in theparamsobject. If you supply a named array then the function will check the orderand warn if it is different. One way of creating your own interactionmatrix is to enter the data using a spreadsheet program and saving it as a.csv file. The data can then be read into R using the commandread.csv().
The interaction of the species with the resource are set via a columninteraction_resource in thespecies_params data frame. By default thiscolumn is set to all 1s.
See Also
Other functions for setting parameters:gear_params(),setExtEncounter(),setExtMort(),setFishing(),setInitialValues(),setMaxIntakeRate(),setMetabolicRate(),setParams(),setPredKernel(),setReproduction(),setSearchVolume(),species_params()
Examples
params <- newTraitParams(no_sp = 3)inter <- getInteraction(params)inter[1, 2:3] <- 0params <- setInteraction(params, interaction = inter)getInteraction(params)Set maximum intake rate
Description
Set maximum intake rate
Usage
setMaxIntakeRate(params, intake_max = NULL, reset = FALSE, ...)getMaxIntakeRate(params)intake_max(params)intake_max(params) <- valueArguments
Value
setReproduction(): A MizerParams object with updated maximumintake rate.
getMaxIntakeRate() or equivalentlyintake_max(): An array(species x size) with the maximum intake rate.
Setting maximum intake rate
The maximum intake rateh_i(w) of an individual of speciesi andweightw determines the feeding level, calculated withgetFeedingLevel(). It is measured in grams/year.
If theintake_max argument is not supplied, then the maximum intakerate is set to
h_i(w) = h_i w^{n_i}.
The values ofh_i (the maximum intake rate of an individual of size 1gram) andn_i (the allometric exponent for the intake rate) are takenfrom theh andn columns in the species parameter dataframe. Iftheh column is not supplied in the species parameter dataframe, it iscalculated by theget_h_default() function.
Ifh_i is set toInf, fish of species i will consume all encounteredfood.
See Also
Other functions for setting parameters:gear_params(),setExtEncounter(),setExtMort(),setFishing(),setInitialValues(),setInteraction(),setMetabolicRate(),setParams(),setPredKernel(),setReproduction(),setSearchVolume(),species_params()
Set metabolic rate
Description
Sets the rate at which energy is used for metabolism and activity
Usage
setMetabolicRate(params, metab = NULL, p = NULL, reset = FALSE, ...)getMetabolicRate(params)metab(params)metab(params) <- valueArguments
Value
setMetabolicRate(): A MizerParams object with updated metabolic rate.
getMetabolicRate() or equivalentlymetab(): An array(species x size) with the metabolic rate.
Setting metabolic rate
The metabolic rate is subtracted from the energy income rate to calculatethe rate at which energy is available for growth and reproduction, seegetEReproAndGrowth(). It is measured in grams/year.
If themetab argument is not supplied, then for each species themetabolic ratek(w) for an individual of sizew is set to
k(w) = k_s w^p + k w,
wherek_s w^p represents the rate of standard metabolism andk wis the rate at which energy is expended on activity and movement. The valuesofk_s,p andk are taken from theks,p andk columns in the species parameter dataframe. If any of theseparameters are not supplied, the defaults arek = 0,p = n and
k_s = f_c h \alpha w_{mat}^{n-p},
wheref_c is the critical feeding level taken from thefc columnin the species parameter data frame. If the critical feeding level is notspecified, a default off_c = 0.2 is used.
See Also
Other functions for setting parameters:gear_params(),setExtEncounter(),setExtMort(),setFishing(),setInitialValues(),setInteraction(),setMaxIntakeRate(),setParams(),setPredKernel(),setReproduction(),setSearchVolume(),species_params()
Set metadata for a model
Description
Setting metadata is particularly important for sharing your model withothers. All metadata fields are optional and you can also add other fieldsof your own choosing. If you set a valuefor a field that already existed, the old value will be overwritten.
Usage
setMetadata(params, title, description, authors, url, doi, ...)getMetadata(params)Arguments
params | The MizerParams object for the model |
title | A string with the title for the model |
description | A string with a description of the model. This could forexample contain information about any publications using the model. |
authors | An author entry or a list of author entries, where each authorentry could either be just a name or could itself be a list with fieldslike |
url | A URL where more information about the model can be found. Thiscould be a blog post on the mizer blog, for example. |
doi | The digital object identifier for your model. To create a doi youcan use online services like https://zenodo.org/ or https://figshare.com. |
... | Additional metadata fields that you would like to add |
Details
In addition to the metadata fields you can set by hand, there are four fieldsthat are set automatically by mizer:
mizer_versionThe version string of the mizer version under which themodel was created or last upgraded. Can be compared to the current versionwhich is obtained withpackageVersion("mizer"). The purpose of this fieldis that if the model is not working as expected in the current version ofmizer, you can go back to the older version under which presumably it wasworking.extensionsA named vector of strings where each name is the name of andextension package needed to run the model and each value is a string givingthe information that the remotes package needs to install the correct versionof the extension package, see https://remotes.r-lib.org/. This field isset by the extension packages.time_createdA POSIXct date-time object with the creation time.time_modifiedA POSIXct date-time object with the last modified time.
Setting the metadata with this function does not count as a modification ofthe object, so thetime_modified field will not be updated.
Value
setMetadata(): The MizerParams object with updated metadata
getMetadata(): A list with all metadata entries that have been set,including at leastmizer_version,extensions,time_created andtime_modified.
Set or change any model parameters
Description
This is a convenient wrapper function calling each of the followingfunctions
See the Details section below for a discussion of how to use this function.
Usage
setParams(params, interaction = NULL, ...)Arguments
params | AMizerParams object |
interaction | Optional interaction matrix of the species (predatorspecies x prey species). By default all entries are 1. See "Settinginteraction matrix" section below. |
... | Arguments passed on to
|
Details
If you are not happy with the assumptions that mizer makes by default aboutthe shape of the model functions, for example if you want to change one ofthe allometric scaling assumptions, you can do this by providing yourchoice as an array in the appropriate argument tosetParams(). Thesections below discuss all the model functions that you can change this way.
Because of the way the R language works,setParams does not make thechanges to theparams object that you pass to it but instead returns a newparams object. So to affect the change you call the function in the formparams <- setParams(params, ...).
Usually, if you are happy with the way mizer calculates its model functionsfrom the species parameters and only want to change the values of somespecies parameters, you would make those changes in thespecies_params dataframe contained in theparams object usingspecies_params<-().Here is an example which assumes thatyou have have a MizerParams objectparams in which you just want to changethegamma parameter of the third species:
species_params(params)$gamma[[3]] <- 1000
Internally that will actually callsetParams() to recalculate any of theother parameters that are affected by the change in the species parameter.
setParams() will use the species parameters in theparams object torecalculate the values of all the model functions except those for which youhave set custom values.
Value
AMizerParams object
Units in mizer
Mizer uses grams to measure weight, centimetres to measure lengths, andyears to measure time.
Mizer is agnostic about whether abundances are given as
numbers per area,
numbers per volume or
total numbers for the entire study area.
You should make the choice most convenient for your application and thenstick with it. If you make choice 1 or 2 you will also have to choose a unitfor area or volume. Your choice will then determine the units for some ofthe parameters. This will be mentioned when the parameters are discussed inthe sections below.
Your choice will also affect the units of the quantities you may want tocalculate with the model. For example, the yield will be in grams/year/m^2 incase 1 if you choose m^2 as your measure of area, in grams/year/m^3 in case 2if you choose m^3 as your unit of volume, or simply grams/year in case 3. Thesame comment applies for other measures, like total biomass, which will begrams/area in case 1, grams/volume in case 2 or simply grams in case 3. Whenmizer puts units on axes in plots, it will choose the units appropriate forcase 3. So for example inplotBiomass() it gives the unit as grams.
You can convert between these choices. For example, if you use case 1, youneed to multiply with the area of the ecosystem to get the total quantity.If you work with case 2, you need to multiply by both area and the thicknessof the productive layer. In that respect, case 2 is a bit cumbersome. ThefunctionscaleModel() is useful to change the units you are using.
Setting interaction matrix
You do not need to specify an interaction matrix. If you do not, then thepredator-prey interactions are purely determined by the size of predatorand prey and totally independent of the species of predator and prey.
The interaction matrix\theta_{ij} modifies the interaction of eachpair of species in the model. This can be used for example to allow fordifferent spatial overlap among the species.The values in the interaction matrix are used to scale the encountered foodand predation mortality (see on the websitethe section on predator-prey encounter rateand onpredation mortality).The first index refers to the predator species and the second to the preyspecies.
The interaction matrix is used when calculating the food encounter rate ingetEncounter() and the predation mortality rate ingetPredMort(). Itsentries are dimensionless numbers. If all the values in the interactionmatrix are equal then predator-prey interactions are determined entirely bysize-preference.
This function checks that the supplied interaction matrix is valid and thenstores it in theinteraction slot of theparams object.
The order of the columns and rows of theinteraction argument should bethe same as the order in the species params data frame in theparamsobject. If you supply a named array then the function will check the orderand warn if it is different. One way of creating your own interactionmatrix is to enter the data using a spreadsheet program and saving it as a.csv file. The data can then be read into R using the commandread.csv().
The interaction of the species with the resource are set via a columninteraction_resource in thespecies_params data frame. By default thiscolumn is set to all 1s.
Setting predation kernel
Kernel dependent on predator to prey size ratio
If thepred_kernel argument is not supplied, then this function sets apredation kernel that depends only on the ratio of predator mass to preymass, not on the two masses independently. The shape of that kernel is thendetermined by thepred_kernel_type column in species_params.
The default forpred_kernel_type is "lognormal". This will call the functionlognormal_pred_kernel() to calculate the predation kernel.An alternative pred_kernel type is "box", implemented by the functionbox_pred_kernel(), and "power_law", implemented by the functionpower_law_pred_kernel(). These functions require certain speciesparameters in the species_params data frame. For the lognormal kernel thesearebeta andsigma, for the box kernel they areppmr_minandppmr_max. They are explained in the help pages for the kernelfunctions. Except forbeta andsigma, no defaults are set forthese parameters. If they are missing from the species_params data frame thenmizer will issue an error message.
You can use any other string forpred_kernel_type. If for example youchoose "my" then you need to define a functionmy_pred_kernel that you canmodel on the existing functions likelognormal_pred_kernel().
When using a kernel that depends on the predator/prey size ratio only, mizerdoes not need to store the entire three dimensional array in the MizerParamsobject. Such an array can be very big when there is a large number of sizebins. Instead, mizer only needs to store two two-dimensional arrays that holdFourier transforms of the feeding kernel function that allow the encounterrate and the predation rate to be calculated very efficiently. However, ifyou need the full three-dimensional array you can calculate it with thegetPredKernel() function.
Kernel dependent on both predator and prey size
If you want to work with a feeding kernel that depends on predator mass andprey mass independently, you can specify the full feeding kernel as athree-dimensional array (predator species x predator size x prey size).
You should use this option only if a kernel dependent only on thepredator/prey mass ratio is not appropriate. Using a kernel dependent onpredator/prey mass ratio only allows mizer to use fast Fourier transformmethods to significantly reduce the running time of simulations.
The order of the predator species inpred_kernel should be the sameas the order in the species params dataframe in theparams object. If yousupply a named array then the function will check the order and warn if it isdifferent.
Setting search volume
The search volume\gamma_i(w) of an individual of speciesiand weightw multiplies the predation kernel whencalculating the encounter rate ingetEncounter() and thepredation rate ingetPredRate().
The name "search volume" is a bit misleading, because\gamma_i(w) doesnot have units of volume. It is simply a parameter that determines the rateof predation. Its units depend on your choice, see section "Units in mizer".If you have chosen to work with total abundances, then it is a rate with units1/year. If you have chosen to work with abundances per m^2 then it has unitsof m^2/year. If you have chosen to work with abundances per m^3 then it hasunits of m^3/year.
If thesearch_vol argument is not supplied, then the search volume isset to
\gamma_i(w) = \gamma_i w^q_i.
The values of\gamma_i (the search volume at 1g) andq_i (theallometric exponent of the search volume) are taken from thegamma andq columns in the species parameter dataframe. If thegammacolumn is not supplied in the species parameter dataframe, a default iscalculated by theget_gamma_default() function. Note that onlyfor predators of sizew = 1 gram is the value of the species parameter\gamma_i the same as the value of the search volume\gamma_i(w).
Setting maximum intake rate
The maximum intake rateh_i(w) of an individual of speciesi andweightw determines the feeding level, calculated withgetFeedingLevel(). It is measured in grams/year.
If theintake_max argument is not supplied, then the maximum intakerate is set to
h_i(w) = h_i w^{n_i}.
The values ofh_i (the maximum intake rate of an individual of size 1gram) andn_i (the allometric exponent for the intake rate) are takenfrom theh andn columns in the species parameter dataframe. Iftheh column is not supplied in the species parameter dataframe, it iscalculated by theget_h_default() function.
Ifh_i is set toInf, fish of species i will consume all encounteredfood.
Setting metabolic rate
The metabolic rate is subtracted from the energy income rate to calculatethe rate at which energy is available for growth and reproduction, seegetEReproAndGrowth(). It is measured in grams/year.
If themetab argument is not supplied, then for each species themetabolic ratek(w) for an individual of sizew is set to
k(w) = k_s w^p + k w,
wherek_s w^p represents the rate of standard metabolism andk wis the rate at which energy is expended on activity and movement. The valuesofk_s,p andk are taken from theks,p andk columns in the species parameter dataframe. If any of theseparameters are not supplied, the defaults arek = 0,p = n and
k_s = f_c h \alpha w_{mat}^{n-p},
wheref_c is the critical feeding level taken from thefc columnin the species parameter data frame. If the critical feeding level is notspecified, a default off_c = 0.2 is used.
Setting external mortality rate
The external mortality is all the mortality that is not due to fishing orpredation by predators included in the model. The external mortality could bedue to predation by predators that are not explicitly included in the model(e.g. mammals or seabirds) or due to other causes like illness. It is a ratewith units 1/year.
Theext_mort argument allows you to specify an external mortality ratethat depends on species and body size. You can see an example of this inthe Examples section of the help page forsetExtMort().
If theext_mort argument is not supplied, then the external mortality isassumed to depend only on the species, not on the size of the individual:\mu_{ext.i}(w) = z_{0.i}. The value of the constantz_0 for eachspecies is taken from thez0 column of the species parameter data frame, ifthat column exists. Otherwise it is calculated as
z_{0.i} = {\tt z0pre}_i\, w_{inf}^{\tt z0exp}.
Setting external encounter rate
The external encounter rate is the rate at which a predator encountersfood that is not explicitly modelled. It is a rate with units mass/year.
Theext_encounter argument allows you to specify an external encounter ratethat depends on species and body size. You can see an example of this inthe Examples section of the help page forsetExtEncounter().
Setting reproduction
For each species and at each size, the proportion\psi of theavailable energythat is invested into reproduction is the product of two factors: theproportionmaturity of individuals that are mature and the proportionrepro_prop of the energy available to a mature individual that isinvested into reproduction. There is a sizew_repro_max at which all theenergy is invested into reproduction and therefore all growth stops. Therecan be no fish larger thanw_repro_max. If you have not specified thew_repro_max column in the species parameter data frame, then the maximum sizew_max is used instead.
Maturity ogive
If the the proportion of individuals that are mature is not supplied viathematurity argument, then it is set to a sigmoidalmaturity ogive that changes from 0 to 1 at around the maturity size:
{\tt maturity}(w) = \left[1+\left(\frac{w}{w_{mat}}\right)^{-U}\right]^{-1}.
(To avoid clutter, we are not showing the species index in the equations,although each species has its own maturity ogive.)The maturity weights are taken from thew_mat column of thespecies_params data frame. Any missing maturity weights are set to 1/4 of themaximum weight in thew_max column.
The exponentU determines the steepness of the maturity ogive. Bydefault it is chosen asU = 10, however this can be overridden byincluding a columnw_mat25 in the species parameter dataframe thatspecifies the weight at which 25% of individuals are mature, which setsU = \log(3) / \log(w_{mat} / w_{mat25}).
The sigmoidal function given above would strictly reach 1 onlyasymptotically. Mizer instead sets the function equal to 1 already at a sizetaken from thew_repro_max column in the species parameter data frame, if itexists, or otherwise from thew_max column. Also, for computationalsimplicity, any proportion smaller than1e-8 is set to0.
Investment into reproduction
If the the energy available to a mature individual that isinvested into reproduction is not supplied via therepro_prop argument,it is set to the allometric form
{\tt repro\_prop}(w) = \left(\frac{w}{w_{\tt{repro\_max}}}\right)^{m-n}.
Heren is the scaling exponent of the energy income rate. Hencethe exponentm determines the scaling of the investment intoreproduction for mature individuals. By default it is chosen to bem = 1 so that the rate at which energy is invested into reproductionscales linearly with the size. This default can be overridden by including acolumnm in the species parameter dataframe. The maximum sizes are takenfrom thew_repro_max column in the species parameter data frame, if itexists, or otherwise from thew_max column.
The total proportion of energy invested into reproduction of an individualof sizew is then
\psi(w) = {\tt maturity}(w){\tt repro\_prop}(w)
Reproductive efficiency
The reproductive efficiency\epsilon, i.e., the proportion of energy allocated toreproduction that results in egg biomass, is set through theereprocolumn in the species_params data frame. If that is not provided, the defaultis set to 1 (which you will want to override). The offspring biomass dividedby the egg biomass gives the rate of egg production, returned bygetRDI():
R_{di} = \frac{\epsilon}{2 w_{min}} \int N(w) E_r(w) \psi(w) \, dw
Density dependence
The stock-recruitment relationship is an emergent phenomenon in mizer, withseveral sources of density dependence. Firstly, the amount of energy investedinto reproduction depends on the energy income of the spawners, which isdensity-dependent due to competition for prey. Secondly, the proportion oflarvae that grow up to recruitment size depends on the larval mortality,which depends on the density of predators, and on larval growth rate, whichdepends on density of prey.
Finally, to encode all the density dependence in the stock-recruitmentrelationship that is not already included in the other two sources of densitydependence, mizer puts the the density-independent rate of egg productionthrough a density-dependence function. The result is returned bygetRDD(). The name of the density-dependence function isspecified by theRDD argument. The default is the Beverton-HoltfunctionBevertonHoltRDD(), which requires anR_max columnin the species_params data frame giving the maximum egg production rate. Ifthis column does not exist, it is initialised toInf, leading to nodensity-dependence. Other functions provided by mizer areRickerRDD() andSheperdRDD() and you can easily usethese as models for writing your own functions.
Setting fishing
Gears
Inmizer, fishing mortality is imposed on species by fishing gears. Thetotal per-capita fishing mortality (1/year) is obtained by summing over themortality from all gears,
\mu_{f.i}(w) = \sum_g F_{g,i}(w),
where the fishing mortalityF_{g,i}(w) imposed by gearg onspeciesi at sizew is calculated as:
F_{g,i}(w) = S_{g,i}(w) Q_{g,i} E_{g},
whereS is the selectivity by species, gear and size,Q is thecatchability by species and gear andE is the fishing effort by gear.
Selectivity
The selectivity at size of each gear for each species is saved as a threedimensional array (gear x species x size). Each entry has a range between 0(that gear is not selecting that species at that size) to 1 (that gear isselecting all individuals of that species of that size). This threedimensional array can be specified explicitly via theselectivityargument, but usually mizer calculates it from thegear_params slot ofthe MizerParams object.
To allow the calculation of theselectivity array, thegear_params slotmust be a data frame with one row for each gear-species combination. So iffor example a gear can select three species, then that gear contributes threerows to thegear_params data frame, one for each species it can select. Thedata frame must have columnsgear, holding the name of the gear,species,holding the name of the species, andsel_func, holding the name of thefunction that calculates the selectivity curve. Some selectivity functionsare included in the package:knife_edge(),sigmoid_length(),double_sigmoid_length(), andsigmoid_weight().Users are able to write their own size-based selectivity function. The firstargument to the function must bew and the function must return a vector ofthe selectivity (between 0 and 1) at size.
Each selectivity function may have parameters. Values for theseparameters must be included as columns in the gear parameters data.frame.The names of the columns must exactly match the names of the correspondingarguments of the selectivity function. For example, the default selectivityfunction isknife_edge() that a has sudden change of selectivity from 0 to 1at a certain size. In its help page you can see that theknife_edge()function has argumentsw andknife_edge_size. The first argument,w, issize (the function calculates selectivity at size). All selectivity functionsmust havew as the first argument. The values for the other arguments mustbe found in the gear parameters data.frame. So for theknife_edge()function there should be aknife_edge_size column. Becauseknife_edge()is the default selectivity function, theknife_edge_size argument has adefault value =w_mat.
The most commonly-used selectivity function issigmoid_length(). It has asmooth transition from 0 to 1 at a certain size. Thesigmoid_length()function has the two parametersl50 andl25 that are the lengths in cm atwhich 50% or 25% of the fish are selected by the gear. If you choose thisselectivity function then thel50 andl25 columns must be included in thegear parameters data.frame.
In case each species is only selected by one gear, the columns of thegear_params data frame can alternatively be provided as columns of thespecies_params data frame, if this is more convenient for the user to setup. Mizer will then copy these columns over to create thegear_params dataframe when it creates the MizerParams object. However changing these columnsin the species parameter data frame later will not update thegear_paramsdata frame.
Catchability
Catchability is used as an additional factor to make the link between gearselectivity, fishing effort and fishing mortality. For example, it can be setso that an effort of 1 gives a desired fishing mortality. In this way effortcan then be specified relative to a 'base effort', e.g. the effort in aparticular year.
Catchability is stored as a two dimensional array (gear x species). This caneither be provided explicitly via thecatchability argument, or theinformation can be provided via acatchability column in thegear_paramsdata frame.
In the case where each species is selected by only a single gear, thecatchability column can also be provided in thespecies_params dataframe. Mizer will then copy this over to thegear_params data frame whenthe MizerParams object is created.
Effort
The initial fishing effort is stored in theMizerParams object. If it isnot supplied, it is set to zero. The initial effort can be overruled whenthe simulation is run withproject(), where it is also possible to specifyan effort that varies through time.
See Also
Other functions for setting parameters:gear_params(),setExtEncounter(),setExtMort(),setFishing(),setInitialValues(),setInteraction(),setMaxIntakeRate(),setMetabolicRate(),setPredKernel(),setReproduction(),setSearchVolume(),species_params()
Set predation kernel
Description
The predation kernel determines the distribution of prey sizes that apredator feeds on. It is used ingetEncounter() when calculatingthe rate at which food is encountered and ingetPredRate() whencalculating the rate at which a prey is predated upon. The predation kernelcan be a function of the predator/prey size ratio or it can be a function ofthe predator size and the prey size separately. Both types can be set up withthis function.
Usage
setPredKernel(params, pred_kernel = NULL, reset = FALSE, ...)getPredKernel(params)pred_kernel(params)pred_kernel(params) <- valueArguments
Value
setPredKernel(): A MizerParams object with updated predation kernel.
getPredKernel() or equivalentlypred_kernel(): An array (predatorspecies x predator_size x prey_size)
Setting predation kernel
Kernel dependent on predator to prey size ratio
If thepred_kernel argument is not supplied, then this function sets apredation kernel that depends only on the ratio of predator mass to preymass, not on the two masses independently. The shape of that kernel is thendetermined by thepred_kernel_type column in species_params.
The default forpred_kernel_type is "lognormal". This will call the functionlognormal_pred_kernel() to calculate the predation kernel.An alternative pred_kernel type is "box", implemented by the functionbox_pred_kernel(), and "power_law", implemented by the functionpower_law_pred_kernel(). These functions require certain speciesparameters in the species_params data frame. For the lognormal kernel thesearebeta andsigma, for the box kernel they areppmr_minandppmr_max. They are explained in the help pages for the kernelfunctions. Except forbeta andsigma, no defaults are set forthese parameters. If they are missing from the species_params data frame thenmizer will issue an error message.
You can use any other string forpred_kernel_type. If for example youchoose "my" then you need to define a functionmy_pred_kernel that you canmodel on the existing functions likelognormal_pred_kernel().
When using a kernel that depends on the predator/prey size ratio only, mizerdoes not need to store the entire three dimensional array in the MizerParamsobject. Such an array can be very big when there is a large number of sizebins. Instead, mizer only needs to store two two-dimensional arrays that holdFourier transforms of the feeding kernel function that allow the encounterrate and the predation rate to be calculated very efficiently. However, ifyou need the full three-dimensional array you can calculate it with thegetPredKernel() function.
Kernel dependent on both predator and prey size
If you want to work with a feeding kernel that depends on predator mass andprey mass independently, you can specify the full feeding kernel as athree-dimensional array (predator species x predator size x prey size).
You should use this option only if a kernel dependent only on thepredator/prey mass ratio is not appropriate. Using a kernel dependent onpredator/prey mass ratio only allows mizer to use fast Fourier transformmethods to significantly reduce the running time of simulations.
The order of the predator species inpred_kernel should be the sameas the order in the species params dataframe in theparams object. If yousupply a named array then the function will check the order and warn if it isdifferent.
See Also
Other functions for setting parameters:gear_params(),setExtEncounter(),setExtMort(),setFishing(),setInitialValues(),setInteraction(),setMaxIntakeRate(),setMetabolicRate(),setParams(),setReproduction(),setSearchVolume(),species_params()
Examples
## Set up a MizerParams objectparams <- NS_params## If you change predation kernel parameters after setting up a model, # this will be used to recalculate the kernelspecies_params(params)["Cod", "beta"] <- 200## You can change to a different predation kernel typespecies_params(params)$ppmr_max <- 4000species_params(params)$ppmr_min <- 200species_params(params)$pred_kernel_type <- "box"plot(w_full(params), getPredKernel(params)["Cod", 100, ], type="l", log="x")## If you need a kernel that depends also on prey size you need to define# it yourself.pred_kernel <- getPredKernel(params)pred_kernel["Herring", , ] <- sweep(pred_kernel["Herring", , ], 2, params@w_full, "*")params<- setPredKernel(params, pred_kernel = pred_kernel)Set own rate function to replace mizer rate function
Description
If the way mizer calculates a fundamental rate entering the model isnot flexible enough for you (for example if you need to introduce timedependence) then you can write your own functions for calculating thatrate and usesetRateFunction() to register it with mizer.
Usage
setRateFunction(params, rate, fun)getRateFunction(params, rate)other_params(params)other_params(params) <- valueArguments
params | A MizerParams object |
rate | Name of the rate for which a new function is to be set. |
fun | Name of the function to use to calculate the rate. |
value | Values for other parameters |
Details
At each time step during a simulation with theproject() function, mizerneeds to calculate the instantaneous values of the various rates. Bydefault it calls themizerRates() function which creates a list with thefollowing components:
encounterfrommizerEncounter()feeding_levelfrommizerFeedingLevel()pred_ratefrommizerPredRate()pred_mortfrommizerPredMort()f_mortfrommizerFMort()mortfrommizerMort()resource_mortfrommizerResourceMort()efrommizerEReproAndGrowth()e_reprofrommizerERepro()e_growthfrommizerEGrowth()rdifrommizerRDI()rddfromBevertonHoltRDD()
For each of these you can substitute your own function. So for example ifyou have written your own function for calculating the total mortalityrate and have called itmyMort and have a mizer model stored in aMizerParams object calledparams that you want to run with your newmortality rate, then you would call
params <- setRateFunction(params, "Mort", "myMort")
In general if you want to replace a functionmizerSomeRateFunc() witha functionmyVersionOfThis() you would call
params <- setRateFunction(params, "SomeRateFunc", "myVersionOfThis")
In some extreme cases you may need to swap out the entiremizerRates()function for your own function calledmyRates(). That you can do with
params <- setRateFunction(params, "Rates", "myRates")
Your new rate functions may need their own model parameters. These youcan store inother_params(params). For example
other_params(params)$my_param <- 42
Note that your own rate functions need to be defined in the globalenvironment or in a package. If they are defined within a function thenmizer will not find them.
Value
ForsetRateFunction(): An updated MizerParams object
ForgetRateFunction(): The name of the registered rate function forthe requestedrate, or the list of all rate functions if called withoutrate argument.
Forother_params(): A named list with all the parameters for whichyou have set values.
Set reproduction parameters
Description
Sets the proportion of the total energy available for reproduction and growththat is invested into reproduction as a function of the size of theindividual and sets additional density dependence.
Usage
setReproduction( params, maturity = NULL, repro_prop = NULL, reset = FALSE, RDD = NULL, ...)getMaturityProportion(params)maturity(params)maturity(params) <- valuegetReproductionProportion(params)repro_prop(params)repro_prop(params) <- valueArguments
params | A MizerParams object |
maturity | Optional. An array (species x size) that holds the proportionof individuals of each species at size that are mature. If not supplied, adefault is set as described in the section "Setting reproduction". |
repro_prop | Optional. An array (species x size) that holds theproportion of consumed energy that a mature individual allocates toreproduction for each species at size. If not supplied, a default is set asdescribed in the section "Setting reproduction". |
reset |
|
RDD | The name of the function calculating the density-dependentreproduction rate from the density-independent rate. Defaults to" |
... | Unused |
value | . |
Value
setReproduction(): A MizerParams object with updated reproductionparameters.
getMaturityProportion() or equivalently 'maturity():An array (species x size) that holds the proportionof individuals of each species at size that are mature.
getReproductionProportion() or equivalentlyrepro_prop():An array (species x size) that holds theproportion of consumed energy that a mature individual allocates toreproduction for each species at size. For sizes where the maturityproportion is zero, also the reproduction proportion is returned as zero.
Setting reproduction
For each species and at each size, the proportion\psi of theavailable energythat is invested into reproduction is the product of two factors: theproportionmaturity of individuals that are mature and the proportionrepro_prop of the energy available to a mature individual that isinvested into reproduction. There is a sizew_repro_max at which all theenergy is invested into reproduction and therefore all growth stops. Therecan be no fish larger thanw_repro_max. If you have not specified thew_repro_max column in the species parameter data frame, then the maximum sizew_max is used instead.
Maturity ogive
If the the proportion of individuals that are mature is not supplied viathematurity argument, then it is set to a sigmoidalmaturity ogive that changes from 0 to 1 at around the maturity size:
{\tt maturity}(w) = \left[1+\left(\frac{w}{w_{mat}}\right)^{-U}\right]^{-1}.
(To avoid clutter, we are not showing the species index in the equations,although each species has its own maturity ogive.)The maturity weights are taken from thew_mat column of thespecies_params data frame. Any missing maturity weights are set to 1/4 of themaximum weight in thew_max column.
The exponentU determines the steepness of the maturity ogive. Bydefault it is chosen asU = 10, however this can be overridden byincluding a columnw_mat25 in the species parameter dataframe thatspecifies the weight at which 25% of individuals are mature, which setsU = \log(3) / \log(w_{mat} / w_{mat25}).
The sigmoidal function given above would strictly reach 1 onlyasymptotically. Mizer instead sets the function equal to 1 already at a sizetaken from thew_repro_max column in the species parameter data frame, if itexists, or otherwise from thew_max column. Also, for computationalsimplicity, any proportion smaller than1e-8 is set to0.
Investment into reproduction
If the the energy available to a mature individual that isinvested into reproduction is not supplied via therepro_prop argument,it is set to the allometric form
{\tt repro\_prop}(w) = \left(\frac{w}{w_{\tt{repro\_max}}}\right)^{m-n}.
Heren is the scaling exponent of the energy income rate. Hencethe exponentm determines the scaling of the investment intoreproduction for mature individuals. By default it is chosen to bem = 1 so that the rate at which energy is invested into reproductionscales linearly with the size. This default can be overridden by including acolumnm in the species parameter dataframe. The maximum sizes are takenfrom thew_repro_max column in the species parameter data frame, if itexists, or otherwise from thew_max column.
The total proportion of energy invested into reproduction of an individualof sizew is then
\psi(w) = {\tt maturity}(w){\tt repro\_prop}(w)
Reproductive efficiency
The reproductive efficiency\epsilon, i.e., the proportion of energy allocated toreproduction that results in egg biomass, is set through theereprocolumn in the species_params data frame. If that is not provided, the defaultis set to 1 (which you will want to override). The offspring biomass dividedby the egg biomass gives the rate of egg production, returned bygetRDI():
R_{di} = \frac{\epsilon}{2 w_{min}} \int N(w) E_r(w) \psi(w) \, dw
Density dependence
The stock-recruitment relationship is an emergent phenomenon in mizer, withseveral sources of density dependence. Firstly, the amount of energy investedinto reproduction depends on the energy income of the spawners, which isdensity-dependent due to competition for prey. Secondly, the proportion oflarvae that grow up to recruitment size depends on the larval mortality,which depends on the density of predators, and on larval growth rate, whichdepends on density of prey.
Finally, to encode all the density dependence in the stock-recruitmentrelationship that is not already included in the other two sources of densitydependence, mizer puts the the density-independent rate of egg productionthrough a density-dependence function. The result is returned bygetRDD(). The name of the density-dependence function isspecified by theRDD argument. The default is the Beverton-HoltfunctionBevertonHoltRDD(), which requires anR_max columnin the species_params data frame giving the maximum egg production rate. Ifthis column does not exist, it is initialised toInf, leading to nodensity-dependence. Other functions provided by mizer areRickerRDD() andSheperdRDD() and you can easily usethese as models for writing your own functions.
See Also
Other functions for setting parameters:gear_params(),setExtEncounter(),setExtMort(),setFishing(),setInitialValues(),setInteraction(),setMaxIntakeRate(),setMetabolicRate(),setParams(),setPredKernel(),setSearchVolume(),species_params()
Examples
# Plot maturity and reproduction ogives for Cod in North Sea modelmaturity <- getMaturityProportion(NS_params)["Cod", ]repro_prop <- getReproductionProportion(NS_params)["Cod", ]df <- data.frame(Size = w(NS_params), Reproduction = repro_prop, Maturity = maturity, Total = maturity * repro_prop)dff <- melt(df, id.vars = "Size", variable.name = "Type", value.name = "Proportion")library(ggplot2)ggplot(dff) + geom_line(aes(x = Size, y = Proportion, colour = Type))Set resource dynamics
Description
Sets the intrinsic resource birth rate and the intrinsic resource carryingcapacity as well as the name of the function used to simulate the resourcedynamics. By default, the birth rate and the carrying capacity are changedtogether in such a way that the resource replenishes at the same rate atwhich it is consumed. So you should only provide either theresource_rate or theresource_capacity (orresource_level) becausethe other is determined by the requirement that the resource replenishesat the same rate at which it is consumed.
Usage
setResource( params, resource_rate = NULL, resource_capacity = NULL, resource_level = NULL, resource_dynamics = NULL, balance = NULL, lambda = resource_params(params)[["lambda"]], n = resource_params(params)[["n"]], w_pp_cutoff = resource_params(params)[["w_pp_cutoff"]], r_pp = deprecated(), kappa = deprecated(), ...)resource_rate(params)resource_rate(params) <- valueresource_capacity(params)resource_capacity(params) <- valueresource_level(params)resource_level(params) <- valueresource_dynamics(params)resource_dynamics(params) <- valueArguments
params | A MizerParams object |
resource_rate | Optional. A vector of per-capita resource birthrate for each size class or a single number giving the coefficient in thepower-law for this rate, see "Setting resource dynamics" below.Must be strictly positive. |
resource_capacity | Optional. Vector of resource intrinsic carryingcapacities or coefficient in the power-law for the capacity, see"Setting resource dynamics" below.The resource capacity must be larger than the resource abundance. |
resource_level | Optional. The ratio between the current resource numberdensity and the resource capacity. Either a number used at all sizes or avector specifying a value for each size. Must be strictly between 0 and 1,except at sizes where the resource is zero, where it can be |
resource_dynamics | Optional. Name of the function that determines theresource dynamics by calculating the resource spectrum at the next timestep from the current state. |
balance | By default, if possible, the resource parameters areset so that the resource replenishes at the same rate at which it isconsumed. In this case you should only specify either the resource rateor the resource capacity (or resource level) because the other is thendetermined automatically. Set to FALSE if you do not want the balancing. |
lambda | Used to set power-law exponent for resource capacity if the |
n | Used to set power-law exponent for resource rate if the |
w_pp_cutoff | The upper cut off size of the resource spectrum power lawused when |
r_pp | |
kappa | |
... | Unused |
value | The desired new value for the respective parameter. |
Details
You would usually set the resource dynamics only after having finished thecalibration of the steady state. Then setting the resource dynamics withthis function will preserve that steady state, unless you explicitlychoose to setbalance = FALSE. Your choice of the resource dynamics onlyaffects the dynamics around the steady state. The higher the resource rateor the lower the resource capacity the less sensitive the model will be tochanges in the competition for resource.
If you provide theresource_level then that sets theresource_capacityto the current resource number density divided by the resource level. Soin that case you should not specifyresource_capacity as well.
If you provide none of the argumentsresource_level,resource_rate orresource_capacity then the resource rate is kept at its previous value.
Value
setResource: A MizerParams object with updated resource parameters
A vector with the intrinsic resource birth rate for each size class.
A vector with the intrinsic resource capacity for each size class.
A vector with the ratio between the current resource number densityand the resource capacity for each size class.
The name of the function that determines the resource dynamics.
Setting resource dynamics
Theresource_dynamics argument allows you to choose the resource dynamicsfunction. By default, mizer uses a semichemostat model to describe theresource dynamics in each size class independently. This semichemostatdynamics is implemented by the functionresource_semichemostat(). You canchange that to use a logistic model implemented byresource_logistic() oryou can useresource_constant() which keeps the resource constant or youcan write your own function.
Both theresource_semichemostat() and theresource_logistic() dynamicsare parametrised in terms of a size-dependent birth rater_R(w) and asize-dependent capacityc_R. The help pages of these functions givethe details.
Theresource_rate argument can be a vector (with the same length asw_full(params)) specifying the intrinsic resource birth rate for each sizeclass. Alternatively it can be a single number that is used as thecoefficient in a power law: then the intrinsic birth rater_R(w) atsizew is set to
r_R(w) = r_R w^{n-1}.
The power-law exponentn is taken from then argument.
Theresource_capacity argument can be a vector specifying the intrinsicresource carrying capacity for each size class. Alternatively it can be asingle number that is used as the coefficient in a truncated powerlaw: then the intrinsic carrying capacityc_R(w) at sizewis set to
c_R(w) = c_R\, w^{-\lambda}
for allw less thanw_pp_cutoff and zero for larger sizes.The power-law exponent\lambda is taken from thelambda argument.
The values forlambda,n andw_pp_cutoff are stored in a listin theresource_params slot of the MizerParams object so that they can bere-used automatically in the future. That list can be accessed withresource_params().
See Also
Examples
params <- NS_paramsresource_dynamics(params)resource_dynamics(params) <- "resource_constant"Alias forsetBevertonHolt()
Description
An alias provided for backward compatibility with mizer version <= 2.0.4
Usage
setRmax(params, R_factor = deprecated(), erepro, R_max, reproduction_level)Arguments
params | A MizerParams object |
R_factor | |
erepro | Reproductive efficiency for each species. See details. |
R_max | Maximum reproduction rate. See details. |
reproduction_level | Sets |
Details
With Beverton-Holt density dependence the relation between the energyinvested into reproduction and the number of eggs hatched is determinedby two parameters: the reproductive efficiencyerepro and the maximumreproduction rateR_max.
If no maximum is imposed on the reproduction rate(R_{max} = \infty) then the resulting density-independentreproduction rateR_{di} is proportionalto the total rateE_R at which energy is invested into reproduction,
R_{di} = \frac{\rm{erepro}}{2 w_{min}} E_R,
where the proportionality factor is given by the reproductive efficiencyerepro divided by the egg sizew_min to convert energy to egg number anddivided by 2 to account for the two sexes.
Imposing a finite maximum reproduction rateR_{max} leads to anon-linear relationship between energy invested and eggs hatched. Thisdensity-dependent reproduction rateR_{dd} is given as
R_{dd} = R_{di}\frac{R_{max}}{R_{di} + R_{max}}.
(All quantities in the above equations are species-specific but we droppedthe species index for simplicity.)
The following plot illustrates the Beverton-Holt density dependence in thereproduction rate for two different choices of parameters.
This plot shows that a given energyE_R invested into reproduction canlead to the same reproduction rateR_{dd} with different choicesof the parametersR_max anderepro.R_max determines the asymptote ofthe curve anderepro its initial slope. A higherR_max coupled with alowererepro (black curves) can give the same value as a lowerR_maxcoupled with a highererepro (blue curves).
For the given initial state in the MizerParams objectparams one cancalculate the energyE_R that is invested into reproduction by themature individuals and the reproduction rateR_{dd} that isrequired to keep the egg abundance constant. These two values determine thelocation of the black dot in the above graph. You then only need oneparameter to select one curve from the family of Beverton-Holt curves goingthrough that point. This parameter can beerepro orR_max. Instead ofR_max you can alternatively specify thereproduction_level which is theratio between the density-dependent reproduction rateR_{dd} andthe maximal reproduction rateR_{max}.
If you do not provide a value for any of the reproduction parameterarguments, thenerepro will be set to the value it has in the currentspecies parameter data frame. If you do provide one of the reproductionparameters, this can be either a vector with one value for eachspecies, or a named vector where the names determine which species areaffected, or a single unnamed value that is then used for all species. Anyspecies for which the given value isNA will remain unaffected.
The values forR_max must be larger thanR_{dd} and can rangeup toInf. If a smaller value is requested a warning is issued and thevalue is increased to the value required for a reproduction level of 0.99.
The values for thereproduction_level must be positive andless than 1. The values forerepro must be large enough to allow therequired reproduction rate. If a smaller value is requested a warning isissued and the value is increased to the smallest possible value. The valuesforerepro should also be smaller than 1 to be physiologically sensible,but this is not enforced by the function.
As can be seen in the graph above, choosing a lower value forR_max or ahigher value forerepro means that near the steady state the reproductionwill be less sensitive to a change in the energy invested into reproductionand hence less sensitive to changes in the spawning stock biomass or itsenergy income. As a result the species will also be less sensitive tofishing, leading to a higher F_MSY.
Value
A MizerParams object
Examples
params <- NS_paramsspecies_params(params)$erepro# Attempting to set the same erepro for all speciesparams <- setBevertonHolt(params, erepro = 0.1)t(species_params(params)[, c("erepro", "R_max")])# Setting erepro for some speciesparams <- setBevertonHolt(params, erepro = c("Gurnard" = 0.6, "Plaice" = 0.95))t(species_params(params)[, c("erepro", "R_max")])# Setting R_maxR_max <- 1e17 * species_params(params)$w_max^-1params <- setBevertonHolt(NS_params, R_max = R_max)t(species_params(params)[, c("erepro", "R_max")])# Setting reproduction_levelparams <- setBevertonHolt(params, reproduction_level = 0.3)t(species_params(params)[, c("erepro", "R_max")])Set search volume
Description
Set search volume
Usage
setSearchVolume(params, search_vol = NULL, reset = FALSE, ...)getSearchVolume(params)search_vol(params)search_vol(params) <- valueArguments
Value
setSearchVolume(): A MizerParams object with updated search volume.
getSearchVolume() or equivalentlysearch_vol(): An array (speciesx size) holding the search volume
Setting search volume
The search volume\gamma_i(w) of an individual of speciesiand weightw multiplies the predation kernel whencalculating the encounter rate ingetEncounter() and thepredation rate ingetPredRate().
The name "search volume" is a bit misleading, because\gamma_i(w) doesnot have units of volume. It is simply a parameter that determines the rateof predation. Its units depend on your choice, see section "Units in mizer".If you have chosen to work with total abundances, then it is a rate with units1/year. If you have chosen to work with abundances per m^2 then it has unitsof m^2/year. If you have chosen to work with abundances per m^3 then it hasunits of m^3/year.
If thesearch_vol argument is not supplied, then the search volume isset to
\gamma_i(w) = \gamma_i w^q_i.
The values of\gamma_i (the search volume at 1g) andq_i (theallometric exponent of the search volume) are taken from thegamma andq columns in the species parameter dataframe. If thegammacolumn is not supplied in the species parameter dataframe, a default iscalculated by theget_gamma_default() function. Note that onlyfor predators of sizew = 1 gram is the value of the species parameter\gamma_i the same as the value of the search volume\gamma_i(w).
See Also
Other functions for setting parameters:gear_params(),setExtEncounter(),setExtMort(),setFishing(),setInitialValues(),setInteraction(),setMaxIntakeRate(),setMetabolicRate(),setParams(),setPredKernel(),setReproduction(),species_params()
Deprecated function for setting up parameters for a community-type model
Description
This function has been deprecated in favour of the functionnewCommunityParams() that sets better default values.
Usage
set_community_model( max_w = 1e+06, min_w = 0.001, min_w_pp = 1e-10, z0 = 0.1, alpha = 0.2, h = 10, beta = 100, sigma = 2, q = 0.8, n = 2/3, kappa = 1000, lambda = 2 + q - n, f0 = 0.7, r_pp = 10, gamma = NA, knife_edge_size = 1000, knife_is_min = TRUE, recruitment = kappa * min_w^-lambda, rec_mult = 1, ...)Arguments
max_w | The maximum size of the community. The |
min_w | The minimum size of the community. Default value is 1e-3. |
min_w_pp | The smallest size of the resource spectrum. |
z0 | The background mortality of the community. Default value is 0.1. |
alpha | The assimilation efficiency of the community. Default value 0.2 |
h | The maximum food intake rate. Default value is 10. |
beta | The preferred predator prey mass ratio. Default value is 100. |
sigma | The width of the prey preference. Default value is 2.0. |
q | The search volume exponent. Default value is 0.8. |
n | The scaling of the intake. Default value is 2/3. |
kappa | The carrying capacity of the resource spectrum. Default valueis 1000. |
lambda | The exponent of the resource spectrum. Default value is 2 + q - n. |
f0 | The average feeding level of individuals who feed on a power-lawspectrum. This value is used to calculate the search rate parameter |
r_pp | Growth rate parameter for the resource spectrum. Default value is 10. |
gamma | Volumetric search rate. Estimated using |
knife_edge_size | The size at the edge of the knife-selectivityfunction. Default value is 1000. |
knife_is_min | Is the knife-edge selectivity function selecting above(TRUE) or below (FALSE) the edge. Default is TRUE. |
recruitment | The constant recruitment in the smallest size class of thecommunity spectrum. This should be set so that the community spectrumcontinues the resource spectrum. Default value = |
rec_mult | Additional multiplier for the constant recruitment. Defaultvalue is 1. |
... | Other arguments to pass to the |
Details
This functions creates aMizerParams object so thatcommunity-type models can be easily set up and run. A community model hasseveral features that distinguish it from the food-web type models. Only one'species' is resolved, i.e. one 'species' is used to represent the wholecommunity. The resource spectrum only extends to the start of the communityspectrum. Recruitment to the smallest size in the community spectrum isconstant and set by the user. As recruitment is constant, the proportion ofenergy invested in reproduction (the slotpsi of the returnedMizerParams object) is set to 0. Standard metabolism has been turnedoff (the parameterks is set to 0). Consequently, the growth rate isnow determined solely by the assimilated food (see the package vignette formore details).
The function has many arguments, all of which have default values. The mainarguments that the users should be concerned with arez0,recruitment,alpha andf0 as these determine the averagegrowth rate of the community.
Fishing selectivity is modelled as a knife-edge function with one parameter,knife_edge_size, which determines the size at which species areselected.
The resultingMizerParams object can be projected forward usingproject() like any otherMizerParams object. When projectingthe community model it may be necessary to keep a small time step sizedt of around 0.1 to avoid any instabilities with the solver. You cancheck for these numerical instabilities by plotting the biomass or abundancethrough time after the projection.
Value
An object of typeMizerParams
References
K. H. Andersen,J. E. Beyer and P. Lundberg, 2009, Trophic andindividual efficiencies of size-structured communities, Proceedings of theRoyal Society, 276, 109-114
Examples
params <- set_community_model(f0=0.7, z0=0.2, recruitment=3e7)# This is now achieved withparams <- newCommunityParams(f0 = 0.7, z0 = 0.2)sim <- project(params, effort = 0, t_max = 100, dt=0.1)plotBiomass(sim)plotSpectra(sim)Deprecated obsolete function for setting up multispecies parameters
Description
This function has been deprecated in favour of the functionnewMultispeciesParams() that sets better default values.
Usage
set_multispecies_model( species_params, interaction = matrix(1, nrow = nrow(species_params), ncol = nrow(species_params)), min_w_pp = 1e-10, min_w = 0.001, max_w = NULL, no_w = 100, n = 2/3, q = 0.8, f0 = 0.6, kappa = 1e+11, lambda = 2 + q - n, r_pp = 10, ...)Arguments
species_params | A data frame of species-specific parameter values. |
interaction | Optional interaction matrix of the species (predatorspecies x prey species). By default all entries are 1. See "Settinginteraction matrix" section below. |
min_w_pp | The smallest size of the resource spectrum. By default thisis set to the smallest value at which any of the consumers can feed. |
min_w | Sets the size of the eggs of all species for which this is notgiven in the |
max_w | The largest size of the consumer spectrum. By default this isset to the largest |
no_w | The number of size bins in the consumer spectrum. |
n | The allometric growth exponent. This can be overruled for individualspecies by including a |
q | Allometric exponent of search volume |
f0 | Expected average feeding level. Used to set |
kappa | The coefficient of the initial resource abundance power-law. |
lambda | Used to set power-law exponent for resource capacity if the |
r_pp | |
... | Unused |
Value
A MizerParams object
Set a species parameter to a default value
Description
If the species parameter does not yet exist in the species parameter dataframe, then create it and fill it with the default. Otherwise use the defaultonly to fill in any NAs. Optionally gives a message if the parameterdid not already exist.
Usage
set_species_param_default(object, parname, default, message = NULL)Arguments
object | Either a MizerParams object or a species parameter data frame |
parname | A string with the name of the species parameter to set |
default | A single default value or a vector with one default value foreach species |
message | A string with a message to be issued when the parameter didnot already exist |
Value
Theobject with an updated column in the species params data frame.
Deprecated function for setting up parameters for a trait-based model
Description
This function has been deprecated in favour of the functionnewTraitParams() that sets better default values.
Usage
set_trait_model( no_sp = 10, min_w_inf = 10, max_w_inf = 1e+05, no_w = 100, min_w = 0.001, max_w = max_w_inf * 1.1, min_w_pp = 1e-10, w_pp_cutoff = 1, k0 = 50, n = 2/3, p = 0.75, q = 0.9, eta = 0.25, r_pp = 4, kappa = 0.005, lambda = 2 + q - n, alpha = 0.6, ks = 4, z0pre = 0.6, h = 30, beta = 100, sigma = 1.3, f0 = 0.5, gamma = NA, knife_edge_size = 1000, gear_names = "knife_edge_gear", ...)Arguments
no_sp | The number of species in the model. The default value is 10. Themore species, the longer takes to run. |
min_w_inf | The asymptotic size of the smallest species in thecommunity. |
max_w_inf | The asymptotic size of the largest species in the community. |
no_w | The number of size bins in the community spectrum. |
min_w | The smallest size of the community spectrum. |
max_w | Obsolete argument because the maximum size of the consumerspectrum is set to max_w_inf. |
min_w_pp | Obsolete argument because the smallest resource size is setto the smallest size at which the consumers feed. |
w_pp_cutoff | The cut off size of the resource spectrum. Default valueis 1. |
k0 | Multiplier for the maximum recruitment. Default value is 50. |
n | Scaling of the intake. Default value is 2/3. |
p | Scaling of the standard metabolism. Default value is 0.75. |
q | Exponent of the search volume. Default value is 0.9. |
eta | Factor to calculate |
r_pp | Growth rate parameter for the resource spectrum. Default value is 4. |
kappa | Coefficient in abundance power law. Default value is0.005. |
lambda | Exponent of the abundance power law. Default value is (2+q-n). |
alpha | The assimilation efficiency of the community. The default valueis 0.6 |
ks | Standard metabolism coefficient. Default value is 4. |
z0pre | The coefficient of the background mortality of the community. z0= z0pre * w_inf ^ (n-1). The default value is 0.6. |
h | Maximum food intake rate. Default value is 30. |
beta | Preferred predator prey mass ratio. Default value is 100. |
sigma | Width of prey size preference. Default value is 1.3. |
f0 | Expected average feeding level. Used to set |
gamma | Volumetric search rate. Estimated using |
knife_edge_size | The minimum size at which the gear or gears selectspecies. Must be of length 1 or no_sp. |
gear_names | The names of the fishing gears. A character vector, thesame length as the number of species. Default is 1 - no_sp. |
... | Other arguments to pass to the |
Details
This functions creates aMizerParams object so that trait-based-typemodels can be easily set up and run. The trait-based size spectrum model canbe derived as a simplification of the general size-based model used inmizer. The species-specific parameters are the same for all species,except forthe asymptotic size, which is considered the most important traitcharacterizing a species. Other parameters are related to the asymptoticsize. For example, the size at maturity is given byw_max * eta,whereeta isthe same for all species. For the trait-based model the number of species isnot important. For applications of the trait-based model see Andersen &Pedersen (2010). See themizer vignette for more details and examplesof the trait-based model.
The function has many arguments, all of which have default values. Ofparticular interest to the user are the number of species in the model andthe minimum and maximum asymptotic sizes. The asymptotic sizes of the speciesare spread evenly on a logarithmic scale within this range.
The stock recruitment relationship is the default Beverton-Holt style. Themaximum recruitment is calculated using equilibrium theory (see Andersen &Pedersen, 2010) and a multiplier,k0. Users should adjustk0 toget the spectra they want.
The factor for the search volume,gamma, is calculated using theexpected feeding level,f0.
Fishing selectivity is modelled as a knife-edge function with one parameter,knife_edge_size, which is the size at which species are selected. Eachspecies can either be fished by the same gear (knife_edge_size has alength of 1) or by a different gear (the length ofknife_edge_size hasthe same length as the number of species and the order of selectivity size isthat of the asymptotic size).
The resultingMizerParams object can be projected forward usingproject like any otherMizerParams object. When projectingthe community model it may be necessary to reducedt to 0.1 to avoidany instabilities with the solver. You can check this by plotting the biomassor abundance through time after the projection.
Value
An object of typeMizerParams
References
K. H. Andersen and M. Pedersen, 2010, Damped trophic cascadesdriven by fishing in model marine ecosystems. Proceedings of the RoyalSociety V, Biological Sciences, 1682, 795-802.
Length based sigmoid selectivity function
Description
A sigmoid shaped selectivity function. Based on two parametersl25 andl50 which determine the length at which 25% and 50% of the stock isselected respectively.
Usage
sigmoid_length(w, l25, l50, species_params, ...)Arguments
w | Vector of sizes. |
l25 | the length which gives a selectivity of 25%. |
l50 | the length which gives a selectivity of 50%. |
species_params | A list with the species params for the current species.Used to get at the length-weight parameters |
... | Unused |
Details
The selectivity is given by the logistic function
S(l) = \frac{1}{1 + \exp\left(\log(3)\frac{l50 -l}{l50 - l25}\right)}
As the mizer model is weight based, and thisselectivity function is length based, it uses thelength-weight parametersa andb to convert between length and weight
l = \left(\frac{w}{a}\right)^{1/b}
Value
Vector of selectivities at the given sizes.
See Also
gear_params() for setting the selectivity parameters.
Other selectivity functions:double_sigmoid_length(),knife_edge(),sigmoid_weight()
Weight based sigmoidal selectivity function
Description
A sigmoidal selectivity function with 50% selectivity atweightsigmoidal_weight=w_{\text{sigmoid}} and widthsigmoidal_sigma=\sigma.
S(w) = \left(1 + \left(\frac{w}{w_{\text{sigmoid}}}\right)^{-\sigma}\right)^{-1}
Usage
sigmoid_weight(w, sigmoidal_weight, sigmoidal_sigma, ...)Arguments
w | Vector of sizes. |
sigmoidal_weight | The weight at which the knife-edge operates. |
sigmoidal_sigma | The width of the selection function. |
... | Unused |
Value
Vector of selectivities at the given sizes.
See Also
gear_params() for setting the selectivity parameters.
Other selectivity functions:double_sigmoid_length(),knife_edge(),sigmoid_length()
Species parameters
Description
These functions allow you to get or set the species-specific parametersstored in a MizerParams object.
Usage
species_params(params)species_params(params) <- valuegiven_species_params(params)given_species_params(params) <- valuecalculated_species_params(params)Arguments
params | A MizerParams object |
value | A data frame with the species parameters |
Details
There are a lot of species parameters and we will list them all below, butmost of them have sensible default values. The only required columns arespecies for the species name andw_max for its maximum size. Howeverif you have information about the values of other parameters then you shouldprovide them.
Mizer distinguishes between the species parameters that you have givenexplicitly and the species parameters that have been calculated by mizer orset to default values. You can retrieve the given species parameters withgiven_species_params() and the calculated ones withcalculated_species_params(). You get all species_params withspecies_params().
If you change given species parameters withgiven_species_params<-() thiswill trigger a re-calculation of the calculated species parameters, wherenecessary. However if you change species parameters withspecies_params<-()no recalculation will take place and furthermore your values could beoverwritten by a future recalculation triggered by a call togiven_species_params<-() . So in most use cases you will only want to usegiven_species_params<-().
There are some species parameters that are used to set up thesize-dependent parameters that are used in the mizer model:
gammaandqare used to set the search volume, seesetSearchVolume().handnare used to set the maximum intake rate, seesetMaxIntakeRate().k,ksandpare used to set activity and basic metabolic rate,seesetMetabolicRate().z0is used to set the external mortality rate, seesetExtMort().w_mat,w_mat25,w_repro_maxandmare used to set the allocation toreproduction, seesetReproduction().pred_kernel_typespecifies the shape of the predation kernel. The defaultis a "lognormal", for other options see the "Setting predation kernel"section in the help forsetPredKernel().betaandsigmaare parameters of the lognormal predation kernel, seelognormal_pred_kernel(). There will be other parameters if you areusing other predation kernel functions.
When you change one of the above species parameters usinggiven_species_params<-() orspecies_params<-(), the new value will beused to update the corresponding size-dependent rates automatically, unlessyou have set those size-dependent rates manually, in which case thecorresponding species parameters will be ignored.
There are some species parameters that are used directly in the modelrather than being used for setting up size-dependent parameters:
alphais the assimilation efficiency, the proportion of the consumedbiomass that can be used for growth, metabolism and reproduction, seethe help forgetEReproAndGrowth().w_minis the egg size.interaction_resourcesets the interaction strength with the resource,see "Predation encounter" section in the help forgetEncounter().ereprois the reproductive efficiency, the proportion of the energyinvested into reproduction that is converted to egg biomass, seegetRDI().Rmaxis the parameter in the Beverton-Holt density dependence added tothe reproduction, seesetBevertonHolt(). There will be other suchparameters if you use other density dependence functions, see the"Density dependence" section in the help forsetReproduction().
Two parameters are used only by functions that need to convert betweenweight and length:
aandbare the parameters in the allometric weight-lengthrelationshipw = a l ^ b.
If you have supplied thea andb parameters, then you can replace weightparameters likew_max,w_mat,w_mat25,w_repro_max andw_min bytheir corresponding length parametersl_max,l_mat,l_mat25,l_repro_max andl_min.
The parameters that are only used to calculate default values for otherparameters are:
f0is the feeding level and is used to get a default value for thecoefficient of the search volumegamma, seeget_gamma_default().fcis the critical feeding level below which the species can notmaintain itself. This is used to get a default value for the coefficientksof the metabolic rate, seeget_ks_default().age_matis the age at maturity and is used to get a default value forthe coefficienthof the maximum intake rate, seeget_h_default().
Note that setting these parameters withspecies_params<-() will have noeffect. You need to set them withgiven_species_params<-() in order totrigger a re-calculation of the other species parameters.
In the past, mizer also used the von Bertalanffy parametersk_vb,w_infandt0 to determine a default forh. This is unreliable and is thereforenow deprecated.
There are other species parameters that are used in tuning the model toobservations:
biomass_observedandbiomass_cutoffallow you to specify for eachspecies the total observed biomass above some cutoff size. This isused bycalibrateBiomass()andmatchBiomasses().yield_observedallows you to specify for eachspecies the total annual fisheries yield. This isused bycalibrateYield()andmatchYields().
Finally there are two species parameters that control the way the species arerepresented in plots:
linecolourspecifies the colour and can be any valid R colour value.linetypespecifies the line type ("solid", "dashed", "dotted", "dotdash","longdash", "twodash" or "blank")
Other species-specific information that is related to how the species isfished is specified in a gear parameter data frame, seegear_params().However in the case where each species is caught by only a single gear,this information can also optionally be provided as species parameters andnewMultispeciesParams() will transfer them to thegear_params data frame.However changing these parameters later in the species parameter data frameswill have no effect.
You are allowed to include additional columns in the species parameterdata frames. They will simply be ignored by mizer but will be stored in theMizerParams object, in case your own code makes use of them.
Value
Data frame of species parameters
See Also
validSpeciesParams(),setParams()
Other functions for setting parameters:gear_params(),setExtEncounter(),setExtMort(),setFishing(),setInitialValues(),setInteraction(),setMaxIntakeRate(),setMetabolicRate(),setParams(),setPredKernel(),setReproduction(),setSearchVolume()
Set initial values to a steady state for the model
Description
The steady state is found by running the dynamics while keeping reproduction,resource and other components constant until the size spectra no longerchange much (or until timet_max is reached, if earlier).
Usage
steady( params, t_max = 100, t_per = 1.5, dt = 0.1, tol = 0.1 * dt, return_sim = FALSE, preserve = c("reproduction_level", "erepro", "R_max"), progress_bar = TRUE)Arguments
params | AMizerParams object |
t_max | The maximum number of years to run the simulation. Default is 100. |
t_per | The simulation is broken up into shorter runs of |
dt | The time step to use in |
tol | The simulation stops when the relative change in the eggproduction RDI over |
return_sim | If TRUE, the function returns the MizerSim object holdingthe result of the simulation run, saved at intervals of |
preserve |
|
progress_bar | A shiny progress object to implement a progress bar in ashiny app. Default FALSE. |
Details
If the model use Beverton-Holt reproduction then the reproduction parametersare set to values that give the level of reproduction observed in thatsteady state. Thepreserve argument can be used to specify which of thereproduction parameters should be preserved.
Value
A MizerParams or a MizerSim object
Examples
params <- newTraitParams()species_params(params)$gamma[5] <- 3000params <- steady(params)plotSpectra(params)Set initial abundances to single-species steady state abundances
Description
This first calculates growth and death rates that arise from the currentinitial abundances. Then it uses these growth and death rates todetermine the steady-state abundances of the selected species.
Usage
steadySingleSpecies( params, species = NULL, keep = c("egg", "biomass", "number"))Arguments
params | A MizerParams object |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or a numeric vector withthe species indices, or a logical vector indicating for each specieswhether it is to be selected (TRUE) or not. |
keep | A string determining which quantity is to be kept constant. Thechoices are "egg" which keeps the egg density constant, "biomass" whichkeeps the total biomass of the species constant and "number" which keepsthe total number of individuals constant. |
Details
The result of applying this function is of course not a multi-species steadystate, because after changing the abundances of the selected species thegrowth and death rates will have changed.
Value
A MizerParams object in which the initial abundances of the selectedspecies are changed to their single-species steady state abundances.
Summarize MizerParams object
Description
Outputs a general summary of the structure and content of the object
Usage
## S4 method for signature 'MizerParams'summary(object, ...)Arguments
object | A |
... | Other arguments (currently not used). |
Value
The MizerParams object, invisibly
Examples
summary(NS_params)Summarize MizerSim object
Description
Outputs a general summary of the structure and content of the object
Usage
## S4 method for signature 'MizerSim'summary(object, ...)Arguments
object | A |
... | Other arguments (currently not used). |
Value
The MizerSim object, invisibly
Examples
summary(NS_sim)Description of summary functions
Description
Mizer provides a range of functions to summarise the results of a simulation.
Details
A list of available summary functions is given in the table below.
| Function | Returns | Description |
getDiet() | Three dimensional array (predator x size x prey) | Diet of predator at size, resolved by prey species |
getSSB() | Two dimensional array (time x species) | Total Spawning Stock Biomass (SSB) of each species through time where SSB is calculated as the sum of weight of all mature individuals. |
getBiomass() | Two dimensional array (time x species) | Total biomass of each species through time. |
getN() | Two dimensional array (time x species) | Total abundance of each species through time. |
getFeedingLevel() | Three dimensional array (time x species x size) | Feeding level of each species by size through time. |
getM2 | Three dimensional array (time x species x size) | The predation mortality imposed on each species by size through time. |
getFMort() | Three dimensional array (time x species x size) | Total fishing mortality on each species by size through time. |
getFMortGear() | Four dimensional array (time x gear x species x size) | Fishing mortality on each species by each gear at size through time. |
getYieldGear() | Three dimensional array (time x gear x species) | Total yield by gear and species through time. |
getYield() | Two dimensional array (time x species) | Total yield of each species across all gears through time. |
See Also
indicator_functions,plotting_functions
Truncated lognormal predation kernel
Description
This is like thelognormal_pred_kernel() but with an imposed maximumpredator/prey mass ratio
Usage
truncated_lognormal_pred_kernel(ppmr, beta, sigma)Arguments
ppmr | A vector of predator/prey size ratios |
beta | The preferred predator/prey size ratio |
sigma | The width parameter of the log-normal kernel |
Details
Writing the predator mass asw and the prey mass asw_p,the feeding kernel is given as
\phi_i(w, w_p) =\exp \left[ \frac{-(\ln(w / w_p / \beta_i))^2}{2\sigma_i^2} \right]
ifw/w_p is between 1 and\beta_i\exp(3\sigma_i)and zero otherwise. Here\beta_i is the preferred predator-prey massratio and\sigma_i determines the width of the kernel. These twoparameters need to be given in the species parameter dataframe in the columnsbeta andsigma.
This function is called fromsetPredKernel() to set up thepredation kernel slots in a MizerParams object.
Value
A vector giving the value of the predation kernel at each of thepredator/prey mass ratios in theppmr argument.
See Also
Other predation kernel:box_pred_kernel(),lognormal_pred_kernel(),power_law_pred_kernel()
Examples
params <- NS_paramsspecies_params(params)$pred_kernel_type <- "truncated_lognormal"plot(w_full(params), getPredKernel(params)["Cod", 10, ], type="l", log="x")Upgrade MizerParams object from earlier mizer versions
Description
This function is called fromvalidParams(). You should never need to callit directly.
Usage
upgradeParams(params)Arguments
params | An old MizerParams object to be upgraded |
Value
The upgraded MizerParams object
See Also
Upgrade MizerSim object from earlier mizer versions
Description
Upgrade MizerSim object from earlier mizer versions
Usage
upgradeSim(sim)Arguments
sim | An old MizerSim object to be upgraded |
Value
The upgraded MizerSim object
Check validity of gear parameters and set defaults
Description
The function returns a valid gear parameter data frame that can be usedbysetFishing() or it gives an error message.
Usage
validGearParams(gear_params, species_params)Arguments
gear_params | Gear parameter data frame |
species_params | Species parameter data frame |
Details
The gear_params data frame is allowed to have zero rows, but if it hasrows, then the following requirements apply:
There must be columns
speciesandgearand any species - gear pair isallowed to appear at most once. Any species that appears must also appearin thespecies_paramsdata frame.There must be a
sel_funccolumn. If a selectivity function is notsupplied, it will be set to "knife_edge".There must be a
catchabilitycolumn. If a catchability is not supplied,it will be set to 1.All the parameters required by the selectivity functions must be provided.
If gear_params is empty, then this function tries to find the necessaryinformation in the species_params data frame. This restricts each speciesto be fished by only one gear. Defaults are used for information that cannot be found in the species_params dataframe, as follows:
If there is no
gearcolumn or it is NA then a new gear named after thespecies is introduced.If there is no
sel_funccolumn or it is NA thenknife_edgeis used.If there is no
catchabilitycolumn or it is NA then this is set to 1.If the selectivity function is
knife_edgeand noknife_edge_sizeisprovided, it is set tow_mat.
The row names of the returned data frame are of the form"species, gear".
Whengear_params isNULL and there is no gear information inspecies_params, then a gear calledknife_edge_gear is set up with aknife_edge selectivity for each species and aknive_edge_size equal tow_mat. Catchability is set to 0.3 for all species.
Value
A valid gear parameter data frame
See Also
Validate MizerParams object and upgrade if necessary
Description
Checks that the given MizerParams object is valid and upgrades it ifnecessary.
Usage
validParams(params)Arguments
params | The MizerParams object to validate |
Details
It is possible to render a MizerParams object invalid by manually changingits slots. This function checks that the object is valid and if not itattempts to upgrade it to a valid object or gives an error message. If theobject is valid then it is returned unchanged. The function reports an errorif any of the rate arrays contain any non-finite numbers (except for themaximum intake rate that is allowed to be infinite).
Occasionally, during the development of new features for mizer, theMizerParams object gains extra slots. MizerParams objectscreated in older versions of mizer are then no longer valid in the newversion because of the missing slots. You need to upgrade them with thisfunction. It adds the missing slots and fills them with default values. Anyobject from version 0.4 onwards can be upgraded. Any oldMizerSim objects should be similarly updated withvalidSim().
This function usesnewMultispeciesParams() to create a newMizerParams object using the parameters extracted from the old MizerParamsobject.
Value
A valid MizerParams object
Backwards compatibility
The internal numerics in mizer have changed over time, so there may be smalldiscrepancies between the results obtained with the upgraded objectin the new version and the original object in the old version. If itis important for you to reproduce the exact results then you should installthe version of mizer with which you obtained the results. You can do thiswith
remotes::install_github("sizespectrum/mizer", ref = "v0.2")where you should replace "v0.2" with the version number you require. You cansee the list of available releases athttps://github.com/sizespectrum/mizer/tags.
If you only have a serialised version of the old object, for examplecreated viasaveRDS(), and you get an error when trying to read it inwithreadRDS() then unfortunately you will need to install the old versionof mizer first to read the params object into your workspace, then switchto the current version and then callvalidParams(). You can then savethe new version again withsaveParams().
Validate MizerSim object and upgrade if necessary
Description
Checks that the given MizerSim object is valid and upgrades it if necessary.Checks whether any abundances are non-finite and if any are found, a warningis issued and the simulation is truncated at the last time step where allresults are finite.
Usage
validSim(sim)Arguments
sim | The MizerSim object to validate |
Details
Occasionally, during the development of new features for mizer, theMizerSim class or theMizerParams class gainsextra slots. MizerSim objects created in older versions of mizer are then nolonger valid in the new version because of the missing slots. You need toupgrade them with this function.
This function adds the missing slots and fills them with default values. Italso callsvalidParams() to upgrade the MizerParams object inside theMizerSim object. Any object from version 0.4 onwards can be upgraded.
Value
A valid MizerSim object
Backwards compatibility
The internal numerics in mizer have changed over time, so there may be smalldiscrepancies between the results obtained with the upgraded objectin the new version and the original object in the old version. If itis important for you to reproduce the exact results then you should installthe version of mizer with which you obtained the results. You can do thiswith
remotes::install_github("sizespectrum/mizer", ref = "v0.2")where you should replace "v0.2" with the version number you require. You cansee the list of available releases athttps://github.com/sizespectrum/mizer/tags.
If you only have a serialised version of the old object, for examplecreated viasaveRDS(), and you get an error when trying to read it inwithreadRDS() then unfortunately you will need to install the old versionof mizer first to read the params object into your workspace, then switchto the current version and then callvalidParams(). You can then savethe new version again withsaveParams().
Validate species parameter data frame
Description
These functions check the validity of a species parameter frame and, wherenecessary, make corrections.validGivenSpeciesParams() only checks andcorrects the given species parameters but does not add default values forspecies parameters that were not provided.validSpeciesParams() first callsvalidGivenSpeciesParams() but then goes further by adding default valuesfor species parameters that were not provided.
Usage
validSpeciesParams(species_params)validGivenSpeciesParams(species_params)Arguments
species_params | The user-supplied species parameter data frame |
Details
validGivenSpeciesParams() checks the validity of the given speciesparameter It throws an error if
the
speciescolumn does not exist or contains duplicatesthe maximum size is not specified for all species
If a weight-based parameter is missing but the corresponding length-basedparameter is given, as well as thea andb parameters for length-weightconversion, then the weight-based parameters are added. If both length andweight are given, then weight is used and a warning is issued if the two areinconsistent.
If aw_inf column is given but now_max then the value fromw_inf isused. This is for backwards compatibility. But note that the von Bertalanffyparameterw_inf is not the maximum size of the largest individual, but theasymptotic size of an average individual.
Some inconsistencies in the size parameters are resolved as follows:
Any
w_matthat is not smaller thanw_maxis set tow_max / 4.Any
w_mat25that is not smaller thanw_matis set to NA.Any
w_minthat is not smaller thanw_matis set to0.001orw_mat /10, whichever is smaller.Any
w_repro_maxthat is not larger thanw_matis set to4 * w_mat.
The row names of the returned data frame will be the species names.Ifspecies_params was provided as a tibble it is converted back to anordinary data frame.
The function tests for some typical misspellings of parameter names, likewrong capitalisation or missing underscores and issues a warning if itdetects such a name.
validSpeciesParams() first callsvalidGivenSpeciesParams() but thengoes further by adding default values for species parameters that were notprovided. The function sets default values if any of the following speciesparameters are missing or NA:
w_repro_maxis set tow_maxw_matis set tow_max/4w_minis set to0.001alphais set to0.6interaction_resourceis set to1nis set to3/4pis set ton
Note that the species parameters returned by these functions are notguaranteed to produce a viable model. More checks of the parameters areperformed by the individual rate-setting functions (seesetParams() for thelist of these functions).
Value
ForvalidSpeciesParams(): A valid species parameter data frame withadditional parameters with default values.
ForvalidGivenSpeciesParams(): A valid species parameter data framewithout additional parameters.
See Also
species_params(),validGearParams(),validParams(),validSim()
Helper function to assure validity of gears argument
Description
If the gears argument contains invalid gears, then these areignored but a warning is issued.
Usage
valid_gears_arg(object, gears = NULL, error_on_empty = FALSE)Arguments
object | A MizerSim or MizerParams object from which the gearsshould be selected. |
gears | The gears to be selected. Optional. By default all gearsare selected. A vector of gear names. |
error_on_empty | Whether to throw an error if there are zero validgears. Default FALSE. |
Value
A vector of gear names.
Helper function to assure validity of species argument
Description
If the species argument contains invalid species, then these areignored but a warning is issued.
Usage
valid_species_arg( object, species = NULL, return.logical = FALSE, error_on_empty = FALSE)Arguments
object | A MizerSim or MizerParams object from which the speciesshould be selected. |
species | The species to be selected. Optional. By default all targetspecies are selected. A vector of species names, or anumeric vector with the species indices, or a logical vector indicating foreach species whether it is to be selected (TRUE) or not. |
return.logical | Whether the return value should be a logical vector.Default FALSE. |
error_on_empty | Whether to throw an error if there are zero validspecies. Default FALSE. |
Value
A vector of species names, in the same order as specified in the'species' argument. If 'return.logical = TRUE' then a logical vector isreturned instead, with length equal to the number of species, withTRUE entry for each selected species.
Size bins
Description
Functions to fetch information about the size bins used in the modeldescribed byparams.
Usage
w(params)w_full(params)dw(params)dw_full(params)Arguments
params | A MizerParams object |
Details
To represent the continuous size spectrum in the computer, the sizevariable is discretized into a vectorw of discrete weights,providing a grid of sizes spanning the range from the smallest egg sizeto the largest maximum size. These grid values divide the full sizerange into a finite number of size bins. The size bins should be chosensmall enough to avoid the discretisation errors from becoming too big.You can fetch this vector withw() and the vector of bin widths withdw().
The weight grid is set up to be logarithmically spaced, so thatw[j]=w[1]*10^(j*dx) for some fixeddx. This means that the bin widthsincrease with size:dw[j] = w[j] * (10^dx - 1).This grid is set up automatically when creating a MizerParams object.
Because the resource spectrum spans a larger range of sizes, these sizesare discretized into a different vector of weightsw_full. This usuallystarts at a much smaller size thanw, but also runs up to the samelargest size, so that the last entries ofw_full have to coincide with theentries ofw. The logarithmic spacing forw_full is the same as that forw, so that againw_full[j]=w_full[1]*10^(j*dx). The functionw_full()gives the vector of sizes anddw_full() gives the vector of bin widths.
You will need these vectors when converting number densities to numbers.For example the size spectrum of a species is stored as a vector ofvalues that represent thedensity of fish in each size bin rather thanthenumber of fish. The number of fish in the size bin betweenw[j] andw[j+1]=w[j]+dw[j] is obtained asN[j]*dw[j].
The vectorw can be used for example to convert the number of individualsin a size bin into the biomass in the size bin. The biomass in thejth bin isbiomass[j] = N[j] * dw[j] * w[j].
Of course all these calculations with discrete sizes and size bins areonly giving approximations to the continuous values, and these approximationsget better the smaller the size bins are, i.e., the more size bins areused. However using more size bins also slows down the calculations, sothere is a trade-off. This is why the functions setting up MizerParamsobjects allow you to choose the number of size binsno_w.
Value
w() returns a vector with the sizes at the start of each size binof the consumer spectrum.
w_full() returns a vector with the sizes at the start of each sizebin of the resource spectrum, which typically starts at smaller sizes thanthe consumer spectrum.
dw() returns a vector with the widths of the size bins of theconsumer spectrum.
dw_full() returns a vector with the widths of the size bins of theresource spectrum.
Examples
str(w(NS_params))str(dw(NS_params))str(w_full(NS_params))str(dw_full(NS_params))# Calculating the biomass of Cod in each bin in the North Sea modelbiomass <- initialN(NS_params)["Cod", ] * dw(NS_params) * w(NS_params)# Summing to get total biomasssum(biomass)