---
title: "Getting started with mizer"
output:
  html_document:
    toc: yes
    fig_width: 5
    fig_height: 5
bibliography: reflib.bib
link-citations: true
vignette: >
  %\VignetteIndexEntry{Getting started with mizer}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

## Overview
The mizer package implements multi-species dynamic [Size-spectrum models] in R.
It has been designed for modelling aquatic ecosystems.

Using mizer is relatively simple.  There are four main stages, each
described in more detail in sections below.

1. [Installing mizer]. 

2. [Setting the model parameters]. 

3. [Running a simulation].

4. [Exploring the results].

If you run into any difficulties or have any questions or suggestions, let us
know about it by posting about it on our [issue tracker](https://github.com/sizespectrum/mizer/issues/new). You can also twitter
to @[mizer_model](https://x.com/mizer_model). We love to hear from
you.

A good way to get into mizer is to follow the online [mizer course](https://mizer.course.sizespectrum.org).
This course has three parts, each consisting of several tutorials with example code and exercises:

-   **[Part 1: Understand](https://mizer.course.sizespectrum.org/understand/)**\
    You will gain an understanding of size spectra and their dynamics by exploring simple example systems hands-on with mizer.

-   **[Part 2: Build](https://mizer.course.sizespectrum.org/build/)**\
    You will build your own multi-species mizer model for the Celtic sea, following our example. You can also create a model for your own area of interest.

-   **[Part 3: Use](https://mizer.course.sizespectrum.org/use/)**\
    You will explore the effects of changes in fishing and changes in resource dynamics on the fish community and the fisheries yield. You will run your own model scenarios.

There is a [series of YouTube videos](https://www.youtube.com/watch?v=zh0PDyTUssw&list=PLCTMeyjMKRkqR7uohI3p-61P7ZJj8sd5B) 
by Richard Southwell about mizer which are however no longer entirely up-to-date.

## Installing mizer

If you already have R installed on your computer, then installation of the
mizer package is very simple
(assuming you have an active internet
connection). Just start an R session and then type:

```{r, eval=FALSE}
install.packages("mizer")
```

After installing mizer, to actually use it, you need to load the package using
the `library()` function. Note that whilst you only need to install the
package once, it will need to be loaded every time you start a new R session.

```{r}
library(mizer)
```
If you still need to install R or RStudio as well, or if you are interested in
installing a development version of mizer, click on the triangle below
to reveal further details:
<details>

Mizer is compatible with R versions 3.1 and later. You can install R on your
computer by following the instructions at <https://cran.r-project.org/> for your
particular platform. 

Alternatively, if you can not or do not want to install
R on your computer, you can also work with R and RStudio in your internet
browser by creating yourself a free account at <https://rstudio.cloud>. There
you can then install mizer as described above. Running mizer in the RStudio
Cloud may be slightly slower than running it locally on your machine, but the
speed is usually quite acceptable.

This guide assumes that you will be using RStudio to work with R. There is
really no reason not to use RStudio and it makes a lot of things much easier.
RStudio develops rapidly and adds useful features all the time and so it pays 
to upgrade to the [latest version](https://docs.posit.co/ide/user/#rstudio-ide-oss-downloads) 
frequently. This guide was written with version 2023.12.1.

The source code for mizer is hosted on
[GitHub](https://github.com/sizespectrum/mizer). If you are feeling brave and
wish to try out a development version of mizer you can install the package from
here using the R package devtools (which was used extensively in putting
together mizer). If you have not yet installed devtools, do
```{r, eval=FALSE}
install.packages("devtools")
```
Then you can install the latest version from GitHub using
```{r, eval=FALSE}
devtools::install_github("sizespectrum/mizer")
```
Using the same `devtools::install_github()` function you can also install code
from forked mizer repositories or from other branches on the official
repository.
</details>


## Setting the model parameters

With mizer it is possible to implement many different types of size-spectrum
models using the same basic tools and methods. 
    
Setting the model parameters is done by creating an object of `class ?
MizerParams`. This includes model parameters such as the life history parameters
of each species, and the fishing gears. For each type of sizespectrum model
there is a function for creating a new MizerParams object,
`newSingleSpeciesParams()`,
`newCommunityParams()`, `newTraitParams()` and `newMultispeciesParams()`.

These functions make
reasonable default choices for many of the model parameters that you do not want
to specify explicitly. For example to set up a simple model (described
more in the [Community Model](https://sizespectrum.org/mizer/articles/community_model.html) section) you can even let
mizer choose all the parameters for you.
```{r}
params <- newCommunityParams()
```
For a more complicated multi-species model you need to provide a data frame
with some species parameters. An example of a North Sea model is included
with the package. Here we also use a species interaction matrix for the 
North Sea species.
```{r}
params <- newMultispeciesParams(NS_species_params, NS_interaction)
```
The notes printed out by the function show us that mizer calculated
default values for many parameters that were not provided.



## Running a simulation 
This is done by calling the `project()` function (as in "project forward in
time") with the model parameters.
```{r}
sim <- project(params, t_max = 10, effort = 1)
```
This produces an object of class `MizerSim` which contains the
results of the simulation. In this example we chose to set some parameters
of the `project()` function to specify that we want to project 10 years into
the future, under the assumption of unit fishing effort. 
You can see the help page for `project()` for more details and it is described
fully in [the section on running a simulation.](https://sizespectrum.org/mizer/articles/running_a_simulation.html)

## Exploring the results
After a simulation has been run, the results can be
examined using a range of `?plotting_functions`, `?summary_functions`
and `?indicator_functions`.
The `plot()` function combines several of these plots into one:
```{r}
plot(sim)
```

Just as an example: we might be interested in how the proportion of large fish
varies over time. We can get the proportion of Herrings in terms of biomass that
have a weight above 50g in each of the 10 years:
```{r}
getProportionOfLargeFish(sim, 
                         species = "Herring", 
                         threshold_w = 50, 
                         biomass_proportion = TRUE)
```
We can then use the full power of R to work with these results.

The functionality provided by mizer to explore the simulation results is more
fully described in 
[the section on exploring the simulation results.](https://sizespectrum.org/mizer/articles/exploring_the_simulation_results.html)

## Size-spectrum models
Size spectrum models have emerged as a conceptually simple way to model a large
community of individuals which grow and change trophic level during life. There
is now a growing literature describing different types of size spectrum models
[e.g. @benoit_continuous_2004; @andersen_asymptotic_2006;
@andersen_life-history_2008; @law_size-spectra_2009; @hartvig_food_2011;
@hartvig_food_2011-1]. The models can be used to understand how marine
communities are organised [@andersen_asymptotic_2006; @andersen_trophic_2009;
@blanchard_how_2009] and how they respond to fishing [@andersen_direct_2010;
@andersen_damped_2010]. This section introduces the central assumptions,
concepts, processes, equations and parameters of size spectrum models.

Roughly speaking there are four versions of the size spectrum modelling
framework of increasing complexity: The [single-species model](https://sizespectrum.org/mizer/articles/single_species_size-spectrum_dynamics.html), the [community model]
[@benoit_continuous_2004;
@maury_modeling_2007; @blanchard_how_2009; @law_size-spectra_2009], the
[trait-based model] [@andersen_asymptotic_2006;
@andersen_damped_2010], and the [multispecies model]
[@hartvig_food_2011-1]. The single-species, community and trait-based models can be considered
as simplifications of the multispecies model. This section focuses on the
multispecies model but is also applicable to the other types of
models. Mizer is able to implement all types of model using similar
commands.

Size spectrum models are a subset of physiologically structured models
[@metz_dynamics_1986; @de_roos_physiologically_2001] as growth (and thus
maturation) is food dependent, and processes are formulated in terms of
individual level processes.  All parameters in the size spectrum models are
related to individual weight which makes it possible to formulate the model with
a small set of general parameters, which has prompted the label ``charmingly
simple'' to the model framework [@pope_modelling_2006}.

The model framework builds on the central assumption that an individual can be
characterized by its weight $w$ and its species number $i$ only. The aim of the
model is to calculate the size- and trait-spectrum ${\cal N}_i(w)$ which is the
density of individuals such that ${\cal N}_i(w)dw$ is the number of individuals
in the interval $[w:w+dw]$. Scaling from individual-level processes of growth
and mortality to the size spectrum of each trait group is achieved by means of
the McKendrick-von Foerster equation, which is simply a continuity equation that
describes the flow of biomass up the size spectrum,
\begin{equation}
  \frac{\partial N_i(w)}{\partial t} + \frac{\partial g_i(w) N_i(w)}{\partial w} = -\mu_i(w) N_i(w)
\end{equation}
where individual growth $g_i(w)$ and mortality $\mu_i(w)$ are coupled, 
because growth of one individual is due to predation on another, who
consequently dies.

The continuity equation is supplemented by a
boundary condition at the egg weight $w_0$ where the flux of individuals
(numbers per time) $g_i(w_0) N_i(w_0)$ is determined by the reproduction of
offspring by mature individuals in the population $R_i$:
\begin{equation}
  g_i(w_0)N_i(w_0) = R_i.
\end{equation}

The rest of the formulation of the model rests on a number of ``standard''
assumptions from ecology and fisheries science about how encounters between
predators and prey leads to growth $g_i(w)$ and reproduction $R_i$ of the
predators, and mortality of the prey $\mu_i(w)$.

For a more detailed exposition of the model see the section 
[The mizer size-spectrum model](https://sizespectrum.org/mizer/articles/model_description.html).

It is easiest to learn the basics of mizer through examples. We do this by
looking at four set-ups of the framework, of increasing complexity. For
each one there is an article that describes how to set up the model,
run it in different scenarios, and explore the results. We
recommend that you explore these in the following order:

### Single-species model
The [single-species model](https://sizespectrum.org/mizer/articles/single_species_size-spectrum_dynamics.html) is a good starting point because it allows one to understand the
main features of size-spectrum modelling without the complexities of multi-species
interactions. The model describes a single species in a fixed background community.
It allows exploration of how the shape of the species size spectrum is determined by
the growth and death rates of individuals of that species. The article gives you
a first glimpse of how to work with mizer, but in a simplified setting.

### Community model
In the [community model](https://sizespectrum.org/mizer/articles/community_model.html), individuals are only 
characterized by their size and are
represented by a single group representing an across-species average. Community
size spectrum models have been used to investigate how abundance size spectra
emerge solely from the individual-level process of size-based predation and how
fishing impacts metrics of community-level size spectra. Since few parameters
are required it has been used for investigating large-scale community-level
questions where detailed trait- and species-level parameterisations are not
tractable.

### Trait-based model
The [trait-based model](https://sizespectrum.org/mizer/articles/trait_model.html) resolves a continuum of species with
varying maximum sizes. The maximum size is considered to be the most
important trait that characterizes a species' life history. The continuum is
represented by a discrete number of species spread evenly over the range of
maximum sizes. The number of species is not important and does not affect the
general dynamics of the model. Many of the parameters, such as the preferred
predator-prey mass ratio, are the same for all species. Other model parameters
are determined by the maximum size. For example, the weight at maturation of
each species is a set fraction of the maximum size. In the trait-based model,
species-level complexity is captured through different life histories, and both
intra- and inter-specific size spectra emerge. This approach is powerful for
examining the generic population and whole community level responses to both
size and species selective fishing without the requirement for detailed
species-specific parameters.

### Multispecies model
In the [multispecies model](https://sizespectrum.org/mizer/articles/multispecies_model.html) individual species are
resolved in detail and each has distinct life history, feeding and reproduction
parameters. More detailed information is required to parameterise the
multispecies model but the approach can be used to address management strategies
for a realistic community in a specific region or subset of interacting species.

### Which model to use
All models predict abundance, biomass and yield as well as predation and
mortality rates at size. They are useful for establishing baselines of abundance
of unexploited communities, for understanding how fishing impacts aquatic
communities and for testing indicators that are being developed to support an
ecosystem approach to fisheries management.  

Which model to use in a specific
case depends on needs and on the amount of information available to calibrate
the model.  The multi-species model could be set up for most systems where
calibration parameters can be estimated.  This requires a lot of insight and
data.  If the parameters are just guesstimates the results of the multi-species
model will be no more accurate than the results from the trait-based model.
In such situations we therefore recommend the use of the trait-based model, even
though it only provides general information about the maximum size
distribution and not about specific species.  

The community model is useful for
large-scale community-level questions where only the average spectrum is needed.
Care should be taken when the community model is used to infer the dynamical
properties of marine ecosystems, since it is prone to unrealistically strong
oscillations due to the lack of dampening effects provided by the life-history
diversity in the trait-based and multi-species models. 

The single-species model is mainly of pedagogical use and for comparison to
other single-species fisheries models. But an important aim of size-spectrum
modelling is to get away from single-species thinking.

<!-- ## Online apps -->
<!-- Perhaps the easiest way for newcomers to get into using mizer is via -->
<!-- online apps. We are in the process to develop a variety of apps for setting -->
<!-- up and exploring models. Here is an example of an online app to  -->
<!-- [explore the effect of increased gear selectivity](https://mizer.shinyapps.io/selectivity/).  -->

## References
