% !Rnw weave = knitr

\documentclass{article}

%\VignetteIndexEntry{Introduction to mizer}
%\VignettePackage{mizer}
%\VignetteEngine{knitr::knitr}

\setlength{\parindent}{0pt}	% Eliminate the indent at the beginning of a new paragraph
\setcounter{secnumdepth}{3}	% Elimate the section numbering starting from a specific depth (see WikiBook)
\usepackage[round,sort]{natbib} 
\usepackage[english]{babel} % No idea what this is but stops the et~al problem from natbib
\usepackage{graphicx}	% To manage external pictures
\usepackage{float}
\usepackage{subfig}	% To add subfigures within figures, with labels (see WikiBooks)
\usepackage{tabularx}
\usepackage{verbatim}
\usepackage[colorlinks=true,linkcolor=blue,citecolor=blue,urlcolor=blue]{hyperref}
\usepackage{amssymb,amsbsy,amsmath}
\usepackage{epsfig}
%\usepackage{epstopdf}
\usepackage[left=3cm,top=3cm,bottom=3.5cm,right=3cm]{geometry}	% For easy management of document margins
\usepackage{fancyhdr} % To customize the header/footer (see WikiBooks)
\usepackage{rotating}
\usepackage{authblk}
\numberwithin{equation}{section}	% Equation numbers relative to sections

%% Set PDF 1.5 and compression, including object compression
%% Needed for MiKTeX -- most other distributions default to this
\ifx\pdfoutput\undefined
\else
  \ifx\pdfoutput\relax
  \else
    \ifnum\pdfoutput>0
      % PDF output
      \pdfminorversion=5
      \pdfcompresslevel=9
      \pdfobjcompresslevel=2
    \fi
  \fi
\fi

% ---------------------------------------------------------------------------------------------------------------------------------------

\newcommand{\code}[1]{{\texttt{#1}}}
\newcommand{\pkg}[1]{{\texttt{#1}}}
\newcommand{\class}[1]{{\textit{#1}}}
\newcommand{\R}{{\normalfont\textsf{R }}{}}
\newcommand{\args}[1]{{\texttt{#1}}}

\begin{document}

<<include=FALSE, cache=FALSE>>=
library(knitr)
opts_chunk$set(concordance=TRUE, cache=TRUE, message=FALSE)
@

% Makes the ACTUAL images the same width as the text
\setkeys{Gin}{width=0.95\textwidth}
% width = x, in the <<>>= affects the R plot (i.e. label size) but not the actual image width
% so width = 2 or width = 10 would give same image width in document, but labels and points etc would be different
% height = x, the acutal image height is given by the width / height ratio and the actual image width
% so image is always blown up to fit Gin width

<<include=FALSE>>=
opts_chunk$set(width = 7)
@


\title{Multispecies, trait-based and community size spectrum ecological modelling in \R (\pkg{mizer})\thanks{mizer version 0.2 authored by Finlay Scott (Cefas, Lowestoft, UK, Maritime Affairs Unit, IPSC, European Commission Joint Research Centre, IT), Julia L. Blanchard (University of Sheffield, UK) and  Ken. H. Andersen (DTU Aqua, Copenhagen, DK. Further improvements were made by Gustav Delius, Richard Southwell and Richard Law (University of York), which resulted in the current version of mizer.)}}
%\author[1,4]{Finlay Scott}
%\author[2]{Julia L. Blanchard}
%\author[3]{Ken. H. Andersen}
%\affil[1]{Cefas, Lowestoft, UK}
%\affil[2]{University of Sheffield, UK}
%\affil[3]{DTU Aqua, Copenhagen, DK}
%\affil[4]{Maritime Affairs Unit, IPSC, European Commission Joint Research Centre, IT}
%\renewcommand\Authands{ and }
\author{}
\date{\pkg{mizer} version \Sexpr{packageDescription("mizer")[["Version"]]}, 30 April 2018. }
\maketitle

\tableofcontents
\setcounter{footnote}{1} \footnotetext{This document is included as a
  vignette (a \LaTeX\ document created using the \R package
  \code{knitr}) of the package \pkg{mizer}. It is automatically
  downloaded together with the package and can be accessed through \R
  typing \code{vignette("mizer\_vignette")}.}  \newpage
\setlength{\parskip}{4pt} % Space between paragraphs

<<echo=FALSE>>=
rm(list=ls())
@ 
%-----------------------------------------------------------------------------------
\section{Summary}
Size spectrum ecological models have emerged as a conceptually simple way to model a large community of individuals that grow and change trophic level during their lives. They are a subset of physiologically structured models where growth (and thus maturation) is food dependent, and processes are formulated in terms of individual level processes.
A key feature is that of a \emph{size spectrum}, where the total abundance of individuals at size scales negatively with size: there are more small things than big things.

\pkg{mizer} is a software package for implementing size spectrum ecological models using the \R statistical programming environment.
The package has been developed to model marine ecosystems that are subject to fishing.

Roughly speaking there are three versions of the size spectrum modelling framework of increasing complexity: The \emph{community} model, in which only one ``species'' is resolved; 
the \emph{trait-based} model, in which all the species-specific parameters are the same, except for the asymptotic size which determines other life-history parameters such as the size at maturity;
and the \emph{multispecies} model in which multiple ``real'' species are resolved, each of which can have differing species-specific traits. 
The community and trait-based models can be considered as simplifications of the multispecies model.
\pkg{mizer} is able to implement all three model versions using the same set of tools.

\pkg{mizer} contains routines and methods to allow users to set up the model community, and then project it through time under different fishing strategies.
The results of the simulations can then be explored using a range of plots and summary methods, including plots of size spectra and the calculation of community indicators such as mean weight in the community and the the slope of the size spectrum.

The models created can be quite flexible and there are many options for setting up and running simulations.  For example, different stock-recruitment relationships can be implemented and fishing gears with different selectivity patterns can be set up so that different species are caught by different gears.
However, \pkg{mizer} aims to make setting up the models relatively simple.  For example, easy to use ``wrapper'' functions are provided so users can set up community and trait-based models with the minimum of \R gymnastics. Additionally, most of the methods and functions in the package have default options and assumptions. These can be changed by the user once they are familiar with the models 

This vignette starts by summarising the principles and assumptions of size spectrum models. The \pkg{mizer} package is then introduced by showing how to set up the simplest types of size spectrum models: the community and trait-based model. These sections give a basic overview of the classes and methods used by \pkg{mizer}. Simple examples are given that demonstrate how trophic-cascades can be simulated. There then follows a more detailed description of the \pkg{mizer} classes and methods using a multispecies model of the North Sea as an example. Next, there is a detailed example of a multispecies size spectrum model of the North Sea, including running projections using historical fishing patterns. After this, we introduce the scale-invariant trait-based model, which can be thought of as a modified version of the trait-based model that can be organized into a well understood steady state without the need to impose external stock-recruitment relationships. Next we describe how species from the scale-invariant can act as a type of background into which  explicit species of particular interest can be added. Finally we describe improvements that have been made to the previous version of mizer, and discuss some technical details in the appendix.

%-------------------------------------------------------------------------------
\section{Package installation and getting help}

\subsection{Installing \pkg{mizer}}

\pkg{mizer} is a package for the \R open-source statistical programming language. \R is available from the CRAN website, which is also an excellent source of documentation and tutorials.

The easiest way to install \pkg{mizer} (assuming you have an active internet connection) is to start an \R session and then type:

<<eval=FALSE>>=
install.packages("mizer")
@

After installing \pkg{mizer}, to actually use it you need to load the package using the \code{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.
<<results='hide'>>=
library(mizer)
@

The source code for \pkg{mizer} is hosted on Github (\url{https://github.com/sizespectrum/mizer}). If you are feeling brave and wish to try out a development version of \pkg{mizer} you can install the package from here using the \R package \pkg{devtools} (which was used extensively in putting together \pkg{mizer}).

\subsection{Getting help}

As you probably know, to access documentation in \R you can use the \code{help()} function. This can be used to access package documentation in a range of ways. For example:

<<label=help_demo, eval=FALSE>>=
help(package="mizer")
help(mizer)
help(project)
@

The first command gives a technical summary of the package, including the available functions.
The second command gives a brief introduction to \pkg{mizer}.
The third gives the documentation page for the method \code{project()}.

Some methods are associated with several \R classes. For example, the \code{plot()} method is generic and can be used on a wide range of \R objects.
The \code{plot()} method has been overloaded in \pkg{mizer} to plot \class{MizerSim} objects. 
To select the help page for the appropriate plotting method you can either just use \code{help(plot)} and then select from a menu of packages or you can supply the package name in the \code{help()} command:

<<label=help_plot, eval=FALSE>>=
help(plot, package="mizer")
@

There are other ways of accessing package documentation that you may not be familiar with. To access the the help page of a particular method you can use: \code{method ? method-name}. For example, to access the help page of the \code{getFeedingLevel()} method you can use:

<<label=help_FL, eval=FALSE>>=
method ? getFeedingLevel
@

This also works for getting information on a class. For example, to get the help page on the \class{MizerParams} class you can use:

<<label=help_MP_class, eval=FALSE>>=
class ? MizerParams
@

These two ways of getting help can be useful when a class and a method have the same name. For example, \class{MizerParams} is a class and also the name of the method for creating \class{MizerParams} objects.

%----------------------------------------------------------------------------------
\section{Size spectrum modelling - concepts, processes and assumptions}
\label{sec:principles}

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
\citep[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
\citep{andersen_asymptotic_2006, andersen_trophic_2009,blanchard_how_2009} and how they respond to fishing
\citep{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 three versions of the size spectrum modelling framework of increasing complexity: The \emph{community} size spectrum model
\citep{benoit_continuous_2004, maury_modeling_2007,blanchard_how_2009,law_size-spectra_2009}, the \emph{trait-based} size spectrum model \citep{andersen_asymptotic_2006, andersen_damped_2010}, and the \emph{multispecies} spectrum model \citep{hartvig_food_2011-1}.
The 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 community and trait-based models.
\pkg{mizer} is able to implement all three types of model using similar commands.

\subsection{Central concepts and assumptions}
Size spectrum models are a subset of physiologically structured models \citep{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 (Table~\ref{tab:parameters}), which has prompted the label ``charmingly simple'' to the model framework \citep{pope_modelling_2006}.

The model framework builds on two central assumption and a number of lesser standard assumption.  

The first central assumption is 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]$. The dimensions of the size spectrum are numbers per weight per volume.  Scaling from individual-level processes of growth and mortality to the size spectrum of each trait group is achieved by means of the McKendrik-von Foerster equation, which is simply a conservation equation:

\begin{equation}
  \label{eq:MvF}
  \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 both determined by the availability of food from the other species plus a background resource, $N_R(w)$, and predation by the other species. The conservation equation is supplemented by a boundary condition at the boundary at 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}
  \label{eq:3}
  g_i(w_0)N_i(w_0) = R_i.
\end{equation}

The second central assumption is that the preference of food is determined by individual weight combined with a species preference. The preference for prey weight is described by the log-normal selection model \citep{ursin_prey_1973} which prescribes prey preference in terms of the ratio between the weight of predators $w$ and prey of weight $w_p$:

\begin{equation}
  \label{eq:4}
  \phi_i(w_p/w) = \exp \left[ \frac{-(\ln(w/(w_p \beta_i)))^2}{2\sigma_i^2} \right],
\end{equation}
where $\beta_i$ is the preferred predator-prey mass ratio and $\sigma_i$ the width of the weight selection function.

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 recruitment $R_i$ of the predators, and mortality of the prey $\mu_i(w)$.
The remainder of this section looks in detail at these assumptions.

\subsection{Predator-prey encounter}
\label{sec:encounter}
The encounter of food is based on the ``Andersen-Ursin'' encounter model which was developed as part of a North-Sea ecosystem model \citep[see also][]{andersen_multispecies_1977, andersen_asymptotic_2006}.  

The available food (mass per volume) for a predator of weight $w$ is determined by integrating over all species and the background resource weighted by the size selection function (Equation~\ref{eq:4}): 

\begin{equation}
  \label{eq:1}
  E_{a.i}(w) = \int \left( N_R(w_p) + \sum_{j} \theta_{ij} N_j(w_p) \right) \phi_i(w_p/w) w_p \, dw_p.
\end{equation}

where $\theta_{ij}$ is the preference of species $i$ for species $j$. The food actually encountered $E_{e.i}$ (mass per time) depends on the search rate (volume per time) which is assumed to scale with individual weight as $\gamma_i w^q$:

\begin{equation}
  \label{eq:Ee}
  E_{e.i}(w) = \gamma_i w^q E_{a.i}(w).
\end{equation}

\subsection{Consumption}
The encountered food is consumed subjected to a standard Holling functional response type II to represent satiation.  This determines the \emph{feeding level}, $f_i(w)$, which is a dimensionless number between 0 (no food) and 1 (fully satiated) so that $1-f_i(w)$ is the proportion of the encountered food that is consumed. It is given by

\begin{equation}
  \label{eq:f}
  f_i(w) = \frac{E_{e.i}(w)}{E_{e.i}(w) + h_i w^n},
\end{equation}

where $h_i w^n$ is the maximum consumption rate. The rate at which food is
consumed is then $(1-f_i(w))E_{e.i}(w)=f_i(w) h_i w^n$.

\subsection{Growth}
\label{sec:growth}
The consumed food is assimilated with an efficiency $\alpha$ and 
used to fuel the needs for standard metabolism (at a rate $k_{s.i} w^p$) and 
activity and movement (at a rate $k_i w$). The remaining rate, if any,
\begin{equation}
  \label{eq:Er}
  E_{r.i}(w) = \max(0, \alpha f_i(w) h_i w^n - k_{s.i} w^p - k_i w)
\end{equation}
is used for growth and reproduction.
When food supply does not cover the requirements of metabolism and activity, 
growth and reproduction stops, i.e.~there is no negative growth\footnote{
The individual would then be subjected to a starvation mortality.
Starvation is usually not an important process in the multispecies model with Beverton-Holt recruitment.
It is therefore not implemented in mizer at the moment.}.

The proportion of $E_{r.i}(w)$ that is used for reproduction is given by
a function $\psi_i(w)$ that changes between 
zero around the weight of maturation $w_{m.i}$ to one at the asymptotic weight 
$W_i$ where all available energy is used for reproduction:
\begin{equation}
  \label{eq:psi}
  \psi_i(w) = \left[ 1 + \left( \frac{w}{w_{m.i}} \right)^{-u} \right]^{-1} \left( \frac{w}{W_i} \right)^{1-n},
\end{equation}
The default value of $u$ is $10.$ The term in the square bracket is a function that varies smoothly from 0 to 1 around the weight at maturation.  The last term describes how the relative amount of energy invested in reproduction increases as the weight approaches the asymptotic weight.  

Thus the somatic growth function is given by
\begin{equation}
  \label{eq:growth}
  g_i(w) = E_{r.i}(w)\left(1-\psi_i(w)\right).
\end{equation}


\begin{figure}[t]
  \centering
 %\includegraphics[width=0.8\textwidth]{Growth_curve.eps}
 \includegraphics[width=0.8\textwidth]{Growth_curve.pdf}
  \caption{The growth curve of an individual found by solving (Equation~\protect\ref{eq:growth}) with a constant feeding level $f_0 = 0.6$ (solid line), compared to a von Bertalanffy growth curve with the von Bertalanffy growth parameter $K = (\alpha f_0 h w^n - k_{s} w^n) W^{n-1}/3$ (dashed line) \protect\citep{andersen_how_2009}.}
  \label{fig:growth}
\end{figure}

The form of the allocation function (\ref{eq:psi}) is chosen such that the growth curve approximates a von Bertalanffy growth curve if the feeding level is constant (see Figure~\ref{fig:growth} and \citet{hartvig_food_2011-1} for details about the derivation). The actual emerging growth curves from the model will depend on the feeding level, and may even result in stunted growth curves if the feeding level drops below the \emph{critical feeding level} where the assimilated food is just enough to satisfy standard metabolism:

\begin{equation}
  \label{eq:fc}
  f_{c.i}(w) = \frac{k_{s.i} w^p+k_i w}{\alpha h_i w^n}.
\end{equation}

If $n=p$ and $k=0$ (which is the case for the set of default parameters chosen here), $f_c$ is independent of $w$.

\subsection{Reproduction}
\label{sec:reproduction}
The total production rate of eggs $R_{p.i}$ (numbers per time) is found by 
integrating the contribution from all individuals:
\begin{equation}
  \label{eq:Rp}
  R_{p.i} = \frac{\epsilon}{2 w_0} \int N_i(w)  E_{r.i}(w) \psi_i(w) \, dw,
\end{equation}
where the individual contribution is obtained by multiplying the rate at which the
individual allocates energy to reproduction by an efficiency factor $\epsilon$ 
and then dividing by the egg weight $w_0$ to convert the energy into number of eggs.
The result is multiplied by a factor $1/2$ to take into account that only 
females reproduce.

\subsection{Recruitment}
\label{sec:recruitment}

\begin{figure}[t]
  \centering
  %\includegraphics{recruitment.eps}
  \includegraphics{recruitment.pdf}
  \caption{The Beverton-Holt recruitment function (thick line) which determines the recruitment $R$ as a function of the egg production (the ``physiological recruitment'') $R_p$ via (Equation~\protect\ref{eq:R}).}
  \label{fig:recruitment}
\end{figure}

One of the fundamental assumptions in fisheries science is that marine fish populations experience significant density dependence early in life \citep{ricker_stock_1954}.  This assumption has some empirical backing for selected, well-studied stocks \citep{myers_density-dependent_1993} and is also supported by the general observation that marine fish do not experience strong, food-dependent growth. This is in contrast to fish in lakes where stunted growth is not uncommon. From a technical point of view, additional density dependence is needed to stabilize the model community to avoid some of the trait classes going extinct \citep{hartvig_food_2011}. An alternative way to ensure coexistence of many species is to introduce a random food web matrix describing species-specific food preference \citep{hartvig_food_2011-1} or an abstract notion of space \citep{hartvig_food_2011}.

In \pkg{mizer}, density dependence is modelled as a compensation on the egg production. This can be considered as the stock-recruitment relationship (SRR).
The default functional form is such that the recruitment flux $R_i$ (numbers per time) approaches a maximum recruitment as the egg production increases, modelled mathematically analogous to the Holling type II function response as a ``Beverton-Holt'' type of SRR:

\begin{equation}
  \label{eq:R}
  R_i = R_{\max.i} \frac{R_{p.i}}{R_{p.i} + R_{\max.i}},
\end{equation}
where $R_{\max.i}$ is the maximum recruitment flux of each trait class (Figure~\ref{fig:recruitment}). 

The ``Beverton-Holt'' type of SRR is not the only density dependence model that \pkg{mizer} can use. Users are able to write their own model so it is possible to set a range of SRRs, e.g. fixed recruitment (as used in the community-type model) or ``hockey-stick''. This is explored in more detail in Section~\ref{sec:srr}.

\subsection{Mortality}
The mortality rate of an individual $\mu_i(w)$ has three sources: predation mortality $\mu_{p.i}(w)$, background mortality $\mu_{b.i}(w)$ and fishing mortality $\mu_{f.i}(w)$. 

Predation mortality is calculated such that all that is eaten translates into corresponding predation mortalities on the ingested prey individuals. Recalling that $1-f_j(w)$ is the proportion of the food encountered by a predator of species $j$ and weight $w$ that is actually consumed, this gives:

\begin{equation}
  \label{eq:mup}
  \mu_{p.i}(w_p) = \sum_j \theta_{ji} \int \phi_j(w_p/w) (1-f_j(w)) \gamma_j w^q N_j(w) \, dw
\end{equation}
(see \citet[Appendix~A]{hartvig_food_2011-1} for derivation)

% Starvation mortality is assumed proportional to the energy deficiency $k_{s.i} w^p - \alpha f_i(w) h_i w^n$, and is inversely proportional to lipid reserves, which are assumed proportional to body weight:
% \begin{equation}
%   \label{eq:mu_s}
%   \mu_{s.i}(w) = \left\{ \begin{array}{lc}
% 0 & \alpha f_i(w) h_i w^n > k_{s.i} w^p \\
%  \frac{k_{s.i} w^p - \alpha f_i(w) h_i w^n}{\xi w} & \mathrm{otherwise}
% \end{array} \right. .
% \end{equation}

Background mortality $\mu_{b .i}(w)$ can be set freely in mizer. By default
it is assumed to be constant within a species and inversely proportional to 
generation time \citep{peters_ecological_1986}:
\begin{equation}
  \label{eq:mu_b}
  \mu_{b.i} = \mu_0 W_i^{n-1}.
\end{equation}
The background mortality is needed to ensure that the largest individuals in the community also experience mortality as they are not predated upon by any individuals from the community spectrum.  

Fishing mortality $\mu_{f.i}(w)$ is discussed further in section \ref{sec:fishing_gear}.


\subsection{Resource dynamics}
The background resource spectrum $N_R(w)$ represents food items for the smallest individuals (smaller than $\beta w_0$). The temporal evolution of each size group in the resource spectrum is described using semi-chemostatic growth:
\begin{equation}
  \label{eq:nb}
  \frac{\partial N_R(w,t)}{\partial t} = r_0 w^{p-1} \Big[ c_p (w) - N_R(w,t) \Big] - \mu_p(w) N_R(w,t),
\end{equation}
where $r_0 w^{p-1}$ is the population regeneration rate \citep{fenchel_intrinsic_1974,savage_effects_2004} and $c_p(w)$ is the carrying capacity, which takes the value $\kappa w^{-\lambda} = \kappa w^{-2-q+n}$ by default. 
The predation mortality rate is given by a similar expression as in \eqref{eq:mup}:
\begin{equation}
  \label{eq:mupp}
  \mu_{p}(w_p) = \sum_j \int \phi_j(w_p/w) (1-f_j(w)) \gamma_j w^q N_j(w) \, dw.
\end{equation}

\subsection{Parameters}
\label{sec:parameters}

The default parameter values for the model have been derived on the basis of meta-analyses of data on marine fish (Table~\ref{tab:parameters}). Two parameters deserving special mention are the initial and critical feeding levels. These are used as physiological measures characterizing the productivity of the system and the metabolic requirements of the individuals.

The system is driven by the production of the resource. The ratio between the production and the maximum consumption will determine the feeding level $f_0$ of small individuals feeding mainly on the background resource. If $f_0$ is close to 1 the individuals are satiated, and growth will be largely independent of changes in food availability. If $f_0$ is in the linear range of the functional response, growth will be dependent on available food. If $f_0$ is close to the critical feeding level $f_c$, where the available food is only sufficient to cover standard metabolism, growth will be stunted. The initial feeding level $f_0$, calculated as the feeding level of an individual feeding on the resource at carrying capacity, is used as the control parameter for the resource productivity. The initial feeding level is then used to calculate the search rate parameter $\gamma$, see \citep[Appendix B]{andersen_asymptotic_2006}:

\begin{equation}
  \label{eq:gamma}
  \gamma_i(f_0) = \frac{f_0 h_i \beta_i^{2-\lambda}\exp(-(\lambda-2)^2 \sigma_i^2/2)}{(1-f_0)\sqrt{2\pi}\kappa \sigma_i}.
\end{equation}

Similar to the way the initial feeding level $f_0$ is used to describe the relation between the production and the maximum consumption, the critical feeding level $f_c$ (Equation~\ref{eq:fc}) is used to describe the relation between the factors for standard metabolism $k_s$ and maximum consumption $h$. A critical feeding level of $f_c \approx 0.2$ seems to be reasonable \citep{hartvig_food_2011-1}.

The free parameter $\kappa$ may in principle be determined analytically, based on an assumption that all species have maximum recruitment, $R_i = R_{\mathrm{max}.i}$.
However, the depletion of resources makes it difficult to find an analytical approximation of $\kappa$ and until that has been achieved, $\kappa$ has to be adjusted manually such that the resulting community spectrum forms a continuation of the resource spectrum.

\begin{table}[t]
  \centering
  \caption{Parameters in the model with dimensions and ``default'' values. For a detailed explanation of the determination of the values see \protect\citep[App.~E]{hartvig_food_2011-1}.}
  \label{tab:parameters}
  \begin{tabular}{llllp{8.5cm}}
    %&  & Value & Units & Description \\
    \hline
    \multicolumn{5}{l}{ Resource spectrum} \\
    & $\kappa$ & $5\cdot{}10^{-3}$ & g$^{\lambda-1}/$m$^3$ & Magnitude of the resource spectrum \\
    & $\lambda$ & 2.05 & - & Exponent of resource spectrum ($=2-n+q$)\\
    & $r_0$ & 4 & g$^{1-p}$/yr & Constant for regeneration rate of resources \\
    & $w_{cut}$ & 0.5 & g & Upper weight limit of the resource spectrum \\
    \multicolumn{5}{l}{ Individual growth} \\
    & $f_0$ & 0.6 & - & Initial feeding level\\
    & $\alpha$ & 0.6 & - & Assimilation efficiency\\
    & $h$ & 40$^\dagger$ & $\mathrm{g}^{1-n}$/yr & Constant for max. food intake \\
    & $n$ & 0.75 & - & Exponent for max. food intake \\
    & $k_s$ & 4.8$^\dagger$ & g$^{1-p}/$yr & Constant for std. metabolism and activity \\
    & $p$ & 0.75 & - & Exponent of standard metabolism* \\
    & $\beta$ & 100 & - & Preferred predator-prey mass ratio \\
    & $\sigma$ & 1.3$^\P$ & - & Width of size selection function \\
    & $\gamma$ & Eq.~(\protect \ref{eq:gamma}) & g$^{-q}m^3$/yr & Constant for volumetric search rate \\
    & $q$ & 0.8$^\S$ & - & Exponent for volumetric search rate \\
    \multicolumn{5}{l}{ Mortality} \\
    & $\xi$ & 0.1 & - & Fraction of body weight containing reserves \\
    & $\mu_0$ & 3$^\dagger$ & g$^{1-n}/$yr & Constant for background mortality \\
    \multicolumn{5}{l}{Reproduction and recruitment} \\
    & $w_0$ & 0.5 & mg & Offspring weight \\
%   & $\eta$ & 0.25 & - & Weight at maturation divided by  $W$  \\
    & $\epsilon$ & 0.1 & - & Efficiency of offspring production \\
    & $k_0$ & 50$^\ddagger$ & - & Factor for maximum recruitment in trait-based model \\
    \hline
    \multicolumn{5}{p{\textwidth}}{\footnotesize *Laboratory experiments on fish indicate that the exponent of standard metabolism should be higher, around $p=0.86$ \protect\citep{winberg_rate_1956,killen_little_2007}. The practical implication of choosing $p>n$ is that a maximum weight for individuals at which all energy, even if $f=1$, is used for standard metabolism at $W_+ = [ (\alpha h)/k_s ]^{1/(p-n)}$ \citep[Eq.~8]{andersen_life-history_2008}. Here a value of $p=n$ is used to make the analysis of the model output easier. }\\
\multicolumn{5}{p{\textwidth}}{\footnotesize $^\dagger$Adjusted to a different value than in \protect\citep{hartvig_food_2011-1} to give growth rates similar to growth rates of species in the North Sea. }\\
\multicolumn{5}{p{\textwidth}}{\footnotesize $^\P$The width of the selection function is chosen to be larger in the trait-based model than in the species-based model \protect\citep{hartvig_food_2011-1} to emulate the diversity in prey-preferences of the species within a trait-class. The practical implication of enlarging $\sigma$ is that the model is more stable (fewer oscillations) \protect\citep{datta_jump-growth_2010}.} \\
\multicolumn{5}{p{\textwidth}}{\footnotesize $^\ddagger$This value should be a little higher but it has been lowered to give a stable output which will facilitate analysis of model output.}\\
\multicolumn{5}{p{\textwidth}}{\footnotesize $^\S$If the value of the search exponent is set to $n$ a lot of the formulas involving exponential factors and power-laws of $\beta$ are simplified significantly as these factor then just becomes 1. Therefore using $q=n$ is preferred for analytical work.}

  \end{tabular}
\end{table}


%--------------------------------------------------------------------
\section{Introducing \pkg{mizer}}

With \pkg{mizer} is is possible to implement the three types of model mentioned above (with increasing complexity): community, trait-based and multispecies, using the same basic tools and methods.
For the remainder of this vignette we present examples of how to set up, project and analyse all three types of model.

Using the package is relatively simple.  There are three main stages to implementing a model:

\begin{itemize}
    \item Setting the model parameters. This is done by creating an object of class \class{MizerParams}. This includes model parameters such as the life history parameters of each species, and the fishing gears. It is possible to create a \class{MizerParams} object directly using the class constructor or by using one of the convenient wrapper functions provided in the package.
    \item Running a simulation. This is done by calling the \code{project()} method on the model parameters. This produces an object of \class{MizerSim} which contains the results of the simulation. The \code{project()} method controls the length and time-step of the simulation, as well as the levels of fishing effort.
    \item Exploring the results. After a simulation has been run, the results can be examined using a range of plots and summaries.
\end{itemize}

These stages and the accompanying classes and methods are explained in detail in the rest of the document.

It is probably easier to learn the basics of mizer through examples. We do this by looking at three set-ups of the framework: the community model, the trait-based model and the multi-species model.  The three types of model represents a hierarchy of complexity: the community model is the simplest and the multi-species model the most complex.  The common denominator is the reliance of a size-based description of the structure of the fish community and of the predator-prey interactions between individuals.

In the community model, 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 individual-level process of size-based predation and how fishing impacts metrics of community-level size spectra \citep{benoit_continuous_2004, law_size-spectra_2009}. 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 \citep{barange_impacts_2014}.

The trait-based model resolves a continuum of species with varying asymptotic sizes. The asymptotic size, $W_\infty$, is considered to be the most important trait that characterizes the species life history.
The continuum is represented by a discrete number of species spread evenly over the range of asymptotic sizes. The number of species is not important and does not affect the general dynamics of the model \citep{andersen_damped_2010}.
Many of the parameters, such as $\beta$ and $\sigma$, are the same for all species. Other model parameters are determined by the asymptotic size.
For example, the weight at maturation is given by, $W_{mat} = \eta_m W_\infty$ , where the default value of $\eta_m$ is 0.25. In the trait-based model species-level complexity is captured through different life histories, and both intra- and inter-specific size spectra emerge \citep{andersen_asymptotic_2006, andersen_damped_2010}.
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 \citep{andersen_direct_2010, jacobsen_consequences_2014}.

In the multispecies model 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 \citep{blanchard_multispecies_2014}.

All three 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 asymptotic 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 \citep{zhang_trait_2013}. 

%------------------------------------------------------
\section{Implementing a community-type model}
\label{sec:comm_model}

\subsection{Introduction}
\label{sec:community_model_intro}
The simplest version of the size spectrum model is the community model, originally introduced by \citep{benoit_continuous_2004}.
%The community model can be derived as a simplification of the trait-based model \citep{zhang_trait_2013}.
In this model only one ``species'' is resolved. Reproduction is not considered, so $\psi(w)=0$ and the recruitment flux $R$ is set to be constant.
The resource spectrum only extends to the start of the community spectrum.
Standard metabolism is turned off by setting $k_{s}$ to 0. 
Growth is therefore given by the simpler equation:
\begin{equation}
    \label{eq:comm_growth}
    g(w) = \alpha f(w) h w^n
\end{equation}

where $f(w) h w^n$ is the consumed food and $\alpha$ is the efficiency with which the consumed food is transformed into growth.
The growth rate can also be written as:

\begin{equation}
  \label{eq:2}
  g(w) = \overline{\epsilon}_I E_a
\end{equation}
where $\overline{\epsilon}_I$ is the average growth efficiency which can be derived from the full model \citep[see][]{andersen_trophic_2009, zhang_trait_2013}.

In this section we describe how a community model can be set up and projected through time. We then use a community model to illustrate the idea of a 'trophic cascade'. Due to the relative simplicity of this type of model they are useful for gently introducing some of the concepts behind the \pkg{mizer} package. Consequently, this section should hopefully serve as an introduction to using \pkg{mizer} and some of the main classes and methods.

\subsection{Setting up a community model}
\label{sec:set_up_comm_model}

As mentioned above, the first stage in implementing a model using \pkg{mizer} is to create an object of class \class{MizerParams}. This class contains the model parameters including the life-history parameters of the species in the model, the stock-recruitment relationships, the fishing selectivity functions and the parameters of the resource spectrum. The class is fully described in Section~\ref{sec:MizerParams}.

To avoid having to make a \class{MizerParams} object directly, a wrapper function, \code{set\_community\_model()}, has been provided that conveniently creates a \class{MizerParams} object specifically for a community model. The documentation for the function can be seen by entering:

<<label=help_set_community_model, eval=FALSE>>=
?set_community_model
@

As can be seen in the help page, the function can take many arguments. These are passed on to the \class{MizerParams} constructor when the function is called. We can ignore most of these arguments for the moment as they almost all come with default values. Full details of those arguments can be seen in Section~\ref{sec:MizerParams}.

The arguments that you should pay attention to are: \args{z0} (the level of background mortality), \args{alpha} (the assimilation efficiency of the community), \args{f0} (the average feeding level of the community which is used to calculate $\gamma$ in Equation~\ref{eq:gamma}) and \args{recruitment} (the level of constant recruitment).

Although default values for these parameters are provided, you are encouraged to explore how changing the values affects the simulated community. For example, the default value of \args{z0} is 0.1. Increasing this value effectively 'shortens' the length of the community spectrum. 
The value of the constant recruitment should be set so that the community spectrum is a continuation of the background spectrum. This can be done with trial and error.  A reasonable value for \args{alpha} is 0.2 \citep{andersen_life-history_2008}. 

The \code{set\_community\_model()} function is called by passing in the arguments by name. Any parameter that is not passed in is set to the default value. For example, the following line sets up the parameters with \args{z0} = 1, \args{f0} = 0.7, \args{alpha} = 0.2 and \args{recruitment} = 4e7. All other parameters will have their default value:

<<label=demo_comm_model_params>>=
params <- set_community_model(z0 = 0.1, f0 = 0.7, alpha = 0.2, recruitment = 4e7)
@

Calling the function creates and returns an object of type \class{MizerParams}. We can check this using the \code{class()} function.
<<label=class_comm_params>>=
class(params)
@

If you are going through this vignette for the first time, it is likely that you have no idea what a \class{MizerParams} object actually is. In ``R-speak'' it is an \code{S4} object, which means it is an object made up of ``slots''. Slots are essentially containers that store the object data. The names of these slots can be seen by calling the \code{slotNames()} method on the object:

<<label=slots_MP>>=
slotNames(params)
@

As you can see, the \code{params} object is made up of lots of slots. They are discussed in detail in Section~\ref{sec:MizerParams}. A quick description can be found in the \class{MizerParams} help page (run \code{class ? MizerParams}. The slots of an object are accessed by using the \code{@} operator. For example, to access the \code{w} slot (which contains a vector of the size bins in the model) you would use:

<<label=demo_slot_accessor, results='hide'>>=
params@w
@

Rather than picking through the slots to find out what is in a particular \class{MizerParams} object, a summary of the object can be seen by calling the \code{summary()} method on it:

<<label=summary_comm_params>>=
summary(params)
@

In the summary you can see that the size range of the community spectrum has been set from \Sexpr{min(params@w)} to \Sexpr{max(params@w)} and these are spread over \Sexpr{length(params@w)} size bins. Similar information is available for the background resource spectrum.
Additionally, the community is made up of only one species, called ``Community'', which has an asymptotic size of \Sexpr{params@species_params$w_inf[1]} and a preferred predator prey mass ratio of \Sexpr{params@species_params$beta[1]}. The \args{w\_mat} parameter has been set to \code{NA} as it is not used when running a community model. These values have all been set by default using the \code{set\_community\_model()} function. If you want to set different values for these, you will need to call the \code{set\_community\_model()} function and pass in the the desired argument values. 

\subsection{Running the community model}
\label{sec:running_comm_model}
By using the \code{set\_community\_model()} method we now have a \class{MizerParams} object that contains all the information we need about the model community. We can use this to perform a simulation and project the community through time.
In the \pkg{mizer} package, projections are performed using the \code{project()} method. You can see the help page for \code{project()} for more details and it is described fully in Section~\ref{sec:projection}.
We will ignore the details for the moment and just use \code{project()} to run some simple projections.
The arguments for \code{project()} that we need to be concerned with are \args{effort}, which determines the fishing effort (and therefore fishing mortality) through time, and \args{t\_max}, which is the length of the simulation.
Initial population abundances are set automatically by the \code{get\_initial\_n()} function. It is possible to set your own initial abundances but we will not do this here.

To run a projection for 50 time steps, with no fishing effort (i.e. we want to model an unexploited community) we run:
<<label=demo_comm_run>>=
sim <- project(params, t_max=50, effort = 0)
@

The resulting object, \code{sim}, is of type \class{MizerSim}. This class holds the results of the simulation, including the community and background resource abundances at size through time, as well as the original model parameters. It is explained in detail in Section~\ref{sec:projection}.

After running the projection, it is possible to explore the results using a range of plots and analyses. These are described fully in Section~\ref{sec:exploring}. To quickly look at the results of the projection you can call the generic \code{plot()} method. This plots the feeding level, predation mortality, fishing mortality and abundance by size in the last time step of the simulation, and the biomass through time (Figure~\ref{fig:plot_comm_demo}) Each of the plots can be show individually if desired.

<<plot_comm_sim, eval=FALSE>>=
plot(sim)
@

\begin{figure}
<<label=print_plot_comm_sim, echo=FALSE, fig.height=9>>=
<<plot_comm_sim>>
@
\caption{Example plot of the community model.}
\label{fig:plot_comm_demo}
\end{figure}

In Figure~\ref{fig:plot_comm_demo} there are several things going on that are worth talking about. Looking at the total biomass of the community against time, you can see that the biomass quickly reaches a stable equilibrium. The other panels show what is happening at the last time step in the simulation, which in this case is when the community is at equilibrium.
Fishing mortality is 0 because we set the \args{effort} argument to 0 when running the simulation.
The predation mortality rate (M2) is clearly a function of size, with the smallest sizes experiencing the highest levels of predation.
The feeding level describes how satiated an individual is, with 0 being unfed, and 1 being full satiated. The feeding level at size will be strongly affected by the values of the \args{f0} and \args{alpha} arguments passed to the \code{set\_community\_model()} function.
The background resource and community spectra are shown in the bottom panel of the plot (the plotted background resource spectrum has been truncated to make for a better plot, but really extends all the way back to \Sexpr{signif(params@w_full[1],3)} g).
You can see that the community spectrum forms a continuum with the resource spectrum. This is strongly affected by the level of fixed recruitment (the \args{recruitment} argument passed to \code{set\_community\_model()}).

Note the ``hump'' in the biomass at the largest end of the community spectrum. This is because the size spectrum model can be broadly described as 'big things eating little things'. Given this, what is eating the very biggest things? Without fishing pressure, the mortality of the largest individuals is only from the background mortality (determined by the \args{z0} argument) and the mortality from predation is almost 0. This is difficult to see in the plot due to the M2 being so high for the smaller individuals.

We can see this more clearly by extracting the predation mortality information from the \class{MizerSim} object, \code{sim}, that we created above.
This is easily done by using the \code{getM2()} method (see the help page for more details). There are several methods that can be used for extracting information from a \class{MizerSim} object, e.g. \code{getFeedingLevel()} and \code{getFMort()}. For more information see Section~\ref{sec:exploring}. Here we just call \code{getM2()} using the \code{sim} object:

<<label=get_m2_comm>>=
m2 <- getM2(sim)
@

This \code{m2} object is a array that contains the predation mortality at time by species by size. Here we only have one species so the species dimension is dropped, leaving us with a two dimensional array of time by size. We projected the model for \Sexpr{dim(m2)[1]-1} time steps but the length of the time dimension is \Sexpr{dim(m2)[1]} as the initial population is also included as a time step.

To pull out the predation mortality at size in the final time step we use:
<<label=m2_comm_final_time_step, results='hide'>>=
m2[51,]
@

If you plot this predation mortality on a log-log scale you can see how the predation mortality declines to almost zero for the largest sizes (Figure~\ref{fig:plot_comm_m2}).

\begin{figure}
<<label=print_plot_comm_m2, echo=FALSE, warning=FALSE, fig.height=4>>=
plot(x = sim@params@w, y = m2[51,], log="xy", type="l", xlab = "Size", ylab = "Predation mortality")
@
\caption{Predation mortality without fishing in the community model (note the log scales for both axes).}
\label{fig:plot_comm_m2}
\end{figure}

\subsection{Example of a trophic cascade with the community model}
\label{sec:trophic_cascade_comm_model}
It is possible to use the community model to simulate a trophic cascade, similar to those seen in \citet{andersen_damped_2010}.
To do this we need to perform two simulations, one with fishing and one without.

This means we need to consider how fishing is handled in \pkg{mizer}.
The \code{set\_community\_model()} function automatically sets the fishing selectivity to have a knife-edge shape, with only individuals larger than 1 kg selected (the size at the knife-edge can be changed by setting the \args{knife\_edge\_size} argument). Although it is possible to change the selectivity function, here we will use the default knife-edge selectivity. Here we set up the parameter object exactly as before, but now we are explicitly setting the size at which individuals are selected by the fishing gear.

<<label=set_comm_fishing>>=
params_knife <- set_community_model(z0 = 0.1, recruitment = 4e7,
    alpha = 0.2, f0 = 0.7, knife_edge_size = 1000)
@

First we perform a simulation without fishing in the same way we did above by setting the \args{effort} argument to 0:

<<label=sim_comm_no_fish>>=
sim0 <- project(params_knife, effort = 0, t_max = 50)
@

Now we want to simulate again, this time with fishing. In the simulations, fishing mortality is calculated as the product of the fishing selectivity, effort and catchability (see Section~\ref{sec:fishing_gear} for more details). By default catchability is set to 1. This means that a fishing effort of 1 will result in a fishing mortality of 1 for fully selected sizes. Here we run a simulation with fishing effort set to 1 for the duration of the simulation:

<<label=sim_comm_with_fish>>=
sim1 <- project(params_knife, effort = 1, t_max = 50)
@

You can compare the difference between these scenarios by using the \code{plot()} method as before (Figure~\ref{fig:plot_comm_fmort}). Of particular interest is the fishing mortality at size. The knife-edge selectivity at 1000 g can be clearly seen and an effort of 1 has resulted in a fishing mortality of 1 for the fully selected sizes.

<<label=plot_comm_fmort, eval=FALSE>>=
plot(sim1)
@

\begin{figure}
<<label=print_plot_comm_fmort, echo=FALSE, fig.height=9>>=
<<plot_comm_fmort>>
@
\caption{Summary plot for the community model when fishing with knife-edge selectivity at size = 1000 g.}
\label{fig:plot_comm_fmort}
\end{figure}

To explore the presence of a trophic cascade, we are interested in looking at the relative change in abundance when the community is fished compared to when it is not fished. To do this we need to get the abundances at size from the simulation objects. The abundances are store in the \code{n} slot of the \class{MizerSim} objects. The \code{n} slot contains a three dimensional array with dimensions time x species x size. Here we have 51 time steps (50 from the simulation plus one which stores the initial population), 1 species and 100 sizes:

<<label='dim_n'>>=
dim(sim0@n)
@

We want the abundances in the final time step, and we can use these to calculate the relative abundances:

<<label='relative_comm_abundance'>>=
relative_abundance <- sim1@n[51,,] / sim0@n[51,,]
@

This can then be plotted (Figure~\ref{fig:plot_relative_comm_abund}) using basic \R plotting commands.
The sizes are stored in the \code{params@w} slot (a slot of a slot!).

<<label=plot_relative_comm_abund, eval=FALSE>>=
plot(x=sim0@params@w, y=relative_abundance, log="x", type="n",
    xlab = "Size (g)", ylab="Relative abundance")
lines(x=sim0@params@w, y=relative_abundance)
lines(x=c(min(sim0@params@w),max(sim0@params@w)), y=c(1,1),lty=2)
@

\begin{figure}
<<label=print_plot_relative_comm_abund, echo=FALSE, fig.height=4>>=
<<plot_relative_comm_abund>>
@
\caption{Relative abundances from the unfished (dashed line) and fished (solid line) community model.}
\label{fig:plot_relative_comm_abund}
\end{figure}

The impact of fishing on species larger than 1000g can be clearly seen.
As described in \citep{andersen_damped_2010}, the fishing pressure lowers the abundance of large fish (the decrease in relative abundance at 1000 g). This then relieves the predation pressure on their smaller prey (the preferred predator-prey size ratio is given by the $\beta$ parameter, which is set to 100 by default), leading to an increase in their abundance. This in turn increases the predation mortality on their smaller prey, which reduces their abundance and so on.  

\subsection{The impact of changing $\sigma$}
\label{sec:comm_model_change_sigma}

As described above, the $\sigma$ parameter determines the width of the predator prey size preference. Here we take a look at how changing the value of $\sigma$ can affect the dynamics of the community.
In the examples above, $\sigma$ is set in the \code{set\_community\_model()} function by default to a value of \Sexpr{params_knife@species_params$sigma[1]}.
When projected through time, the community abundances converge to a stable equilibrium.
What happens if we reduce the value of $\sigma$, for example by setting it to 1.0? We can do this by passing in the new value of $\sigma$ into \code{set\_community\_model()}.

<<label=comm_params_sigma1>>=
params_sigma1 <- set_community_model(z0 = 0.1,
     f0 = 0.7, alpha = 0.2, recruitment = 4e7, sigma = 1)
@

We want to project this new model through time using the \code{project()} method. Note that we have introduced a new argument: $dt$. This is the step size of the solver. It does not have anything to do with the biology in the model. It only affects the internal engine of \code{project()} that performs the projection. 
As you can see in the underlying model equations in Section~\ref{sec:principles}, the model runs in continuous time. Therefore, to project it forward, \code{project()} must solve the system of equations using numerical methods. The quality of these methods is strongly affected by $dt$. 
The default value of $dt$ is 0.1, which will be fine for most of the projections we run in this Vignette. Here it is necessary to reduce the value to 0.01 to avoid introducing any artefacts into the projected values. Decreasing $dt$ increases the time it takes to run a projection.
Here we project the new parameters object for 50 time steps without fishing:

<<label=comm_project_sigma1>>=
sim_sigma1 <- project(params_sigma1, effort = 0, t_max = 50, dt=0.01)
@

Let's take a look at how the abundances change through time. We can do this with the \code{plotBiomass()} method:

<<label=plot_comm_biomass_sigma1, eval=FALSE>>=
plotBiomass(sim_sigma1)
@

\begin{figure}
<<label=print_plot_comm_biomass_sigma1, echo=FALSE, fig.height=4, fig.keep='last'>>=
<<plot_comm_biomass_sigma1>>
@
\caption{Biomass of the community model when $\sigma$ is reduced to a value of 1.0.}
\label{fig:plot_comm_biomass_sigma1}
\end{figure}

Figure~\ref{fig:plot_comm_biomass_sigma1} shows that abundances of the community no longer converge to a stable equilibrium and the dynamics appear to be chaotic. The ecological significance of the change in dynamics, and of the ability of simple community models to show chaotic behaviour, is still being debated. It can be argued that the size of the oscillations are too large to be 'true'. Additionally, when a trait-based model (see Section~\ref{sec:trait_based_model}) is implemented, the magnitude of the oscillations are much smaller.

%-----------------------------------------------------------------------
\section{Implementing a trait-based model}
\label{sec:trait_based_model}

\subsection{Introduction}
As mentioned above,the trait-based size spectrum model can be derived as a simplification of the general model outline in Section~\ref{sec:principles}.
It is more complicated than a community model and the most significant difference between the two is that while the community model only resolves a single ``species'', the trait-based model resolves many species.
In a trait-based model the asymptotic size is considered to be the most important ``trait'' characterizing a species. All of the species-specific parameters, such as $\beta$ and $\sigma$, are the same for all species. Other model parameters are determined by the asymptotic size.
For example, the weight at maturation, $w_m = \eta_m W$, where $\eta_m = 0.25$.  The number of species is not important and does not affect the general dynamics of the model. The asymptotic sizes of the species are spread evenly over the size range of the community.
For applications of the trait-based model see \citet{andersen_damped_2010} and \citet{andersen_direct_2010}.

\subsection{Setting up a trait-based model}
\label{sec:set_up_trait_model}

To help set up a trait-based model, there is a wrapper function, \code{set\_trait\_model()}. Like the \code{set\_community\_model()} function described above, this function can take many arguments. Most of them have default values so you don't need to worry about them for the moment. See the help page for more details.

<<label=help_set_trait_model, eval=FALSE>>=
?set_trait_model
@

The main parameters of interest are the number of the species in the model (\args{no\_sp}) and the minimum and maximum asymptotic sizes (\args{min\_w\_inf} and \args{max\_w\_inf} respectively, the asymptotic sizes are spread evenly on a logarithmic scale).

One of the key differences between the community type model described above and the trait-based model is that reproduction and egg production are considered.
In the community model, recruitment is constant and there is no relationship between the abundance in the community and egg production.
In the trait-based model, the egg production is modeled using a ``Beverton-Holt'' type function (the default in \pkg{mizer}, see Section~\ref{sec:recruitment}) where the recruitment flux $R_i$ (numbers per time) approaches a maximum recruitment as the egg production increases.
The maximum recruitment flux is calculated using equilibrium theory \citep[see][]{andersen_damped_2010} and a recruitment multiplier $k_0$, which can be passed in as an argument (\args{k0}) to the \code{set\_trait\_model()} function. \args{k0} has a default value of 50. 

Here we set up the model to have 10 species, with asymptotic sizes ranging from 10 g to 100 kg. All the other parameters have default values. 

<<label=demo_trait_model_params>>=
params <- set_trait_model(no_sp = 10, min_w_inf = 10, max_w_inf = 1e5)
@

This function returns an object of type \class{MizerParams}, which holds all the model information, including species parameters.

<<label=class_trait_params>>=
class(params)
@

This object can therefore be interrogated in the same way as described in Section~\ref{sec:comm_model} above, either by inspecting the individual slots or by using the \code{summary()} function.

<<label=summary_comm_params2>>=
summary(params)
@

The summary shows us that now we have 10 species in the model, with asymptotic sizes ranging from \Sexpr{min(params@species_params$w_inf)}
to \Sexpr{max(params@species_params$w_inf)}. The size at maturity (\args{w\_{mat}}) is linearly related to the asymptotic size. Each species has the same preferred predator-prey mass ratio parameter values (\args{beta} and \args{sigma}, see Equation \ref{eq:4}). There are \Sexpr{length(params@w)} size bins in the community and \Sexpr{length(params@w_full)} size bins including the background resource spectrum.
Ignore the summary section on fishing gear for the moment. This is explained later.

\subsection{Running the trait-based model}
\label{sec:running_trait_model}

As with the community model described above, we can project the model through time using the \code{project()} method.
Here we project the model for 75 time steps and without any fishing (the \args{effort} argument is set to 0).
We use the default initial population abundances given by the \code{get\_initial\_n()} function so there is no need to pass in any initial population values (see Section \ref{sec:setting_initial_abundances}).

<<label=trait_project_no_fishing>>=
sim <- project(params, t_max=75, effort = 0)
@

This results in a \class{MizerSim} object which contains the abundances of the community and background resource spectra through time, as well as the original \class{MizerParams} object.
As with the community model, we can get a quick overview of the results of the simulation by calling the generic \code{plot()} method:

<<plot_comm_sim_2, eval=FALSE>>=
plot(sim)
@

\begin{figure}
<<label=print_plot_trait_sim, echo=FALSE, fig.height=9>>=
<<plot_comm_sim_2>>
@
\caption{Example plot of the trait-based model with no fishing.}
\label{fig:plot_trait_demo}
\end{figure}

The summary plot has the same panels as the one generated by the community model, but here you can see that all the species in the community are plotted (Figure~\ref{fig:plot_trait_demo}). The panels show the situation in the final time step of the simulation, apart from the biomass through time plot.
As this is a trait-based model where all species fully interact with each other, the predation mortality (M2) and feeding level by size is the same for each species.
The biomasses quickly settle down to equilibria. In this simulation we turned fishing off so the fishing mortality is 0.
The size-spectra show the abundances at size to be evenly spaced by asymptotic size.

\subsection{Example of a trophic cascade with the trait-based model}
\label{sec:trophic_cascade_trait_model}

As with the community model, it is possible to use the trait-based model to simulate a trophic cascade, similar to those seen in \citet{andersen_damped_2010}.
Again, we perform two simulations, one with fishing and one without. We therefore need to consider how fishing gears and selectivity have been set up by the \code{set\_trait\_model()} function. 

The default fishing selectivity function is a knife-edge function, which only selects individuals larger than 1000 g. There is also only one fishing gear in operation, and this selects all of the species. You can see this if you call the \code{summary()} method on the $params$ argument we set up above. At the bottom of the summary there is a section on ``Fishing gear details''. You can see that there is only one gear, called ``knife\_edge\_gear'' and that it selects species 1 to 10.
To control the size at which individuals are selected there is a \args{knife\_edge\_size} argument to the \code{set\_trait\_model()} function. This has a default value of 1000 g.

In \pkg{mizer} it is possible to include more than one fishing gear in the model and for different species to be caught by different gears. We will ignore this for now, but will explore it further below when we introduce an industrial fishery to the trait-based model. 

To set up the trait-based model to have fishing we set up the \class{MizerParams} object in exactly the same way as we did before but here the \args{knife\_edge\_size} argument is explicitly passed in for clarity:

<<label=set_trait_fishing>>=
params_knife <- set_trait_model(no_sp = 10, min_w_inf = 10, max_w_inf = 1e5,
    knife_edge_size = 1000)
@

First we perform a simulation without fishing in the same way we did above by setting the \args{effort} argument to 0:

<<label=sim_trait_no_fish>>=
sim0 <- project(params_knife, effort = 0, t_max = 75)
@

Now we simulate with fishing. Here, we use an effort of 0.75. As mentioned in Section~\ref{sec:trophic_cascade_comm_model}, the fishing mortality on a species is calculated as the product of effort, catchability and selectivity (see Section~\ref{sec:fishing_gear} for more details). Selectivity ranges between 0 (not selected) and 1 (fully selected). The default value of catchability is 1. Therefore, in this simulation the fishing mortality of a fully selected individual is simply equal to the effort. This effort is constant throughout the duration of the simulation (however, this is does not necessarily have to be the case, see Section\ref{sec:projection}).

<<label=sim_trait_with_fish>>=
sim1 <- project(params_knife, effort = 0.75, t_max = 75)
@

Again, we can plot the summary of the fished community using the default \code{plot()} function (Figure \ref{fig:plot_trait_fmort}). The knife-edge selectivity at 1000 g can be clearly seen in the fishing mortality panel:

<<label=plot_trait_fmort, eval=FALSE>>=
plot(sim1)
@

\begin{figure}
<<label=print_plot_trait_fmort, echo=FALSE, fig.height=9>>=
<<plot_trait_fmort>>
@
\caption{Summary plot for the trait-based model when fishing with knife-edge selectivity at size = 1000 g.}
\label{fig:plot_trait_fmort}
\end{figure}

The trophic cascade can be explored by comparing the total abundances of all species at size when the community is fished and unfished.
As mentioned above, the abundances are stored in the \code{n} slot of the \class{MizerSim} object. The \code{n} slot returns a three dimensional array with dimensions time x species x size. Here we have 76 time steps (75 from the simulation plus one which stores the initial population), 10 species and 100 sizes:

<<label=trait_dim_n>>=
dim(sim0@n)
@

As with the community model, we are interested in the relative total abundances by size in the final time step  so we want to pull out the 76th time step from the abundances and sum over the species.
We can use the \code{apply()} function to help us:

<<label = total_abund_trait>>=
total_abund0 <- apply(sim0@n[76,,],2,sum)
total_abund1 <- apply(sim1@n[76,,],2,sum)
@

We can then use these vectors to calculate the relative abundances:

<<label='relative_comm_abundance2'>>=
relative_abundance <- total_abund1 / total_abund0
@

Which can be plotted using (Figure~\ref{fig:plot_relative_comm_abund2}):

<<label=plot_relative_comm_abund2, eval=FALSE>>=
plot(x=sim0@params@w, y=relative_abundance, log="xy", type="n", xlab = "Size (g)",
    ylab="Relative abundance", ylim = c(0.1,10))
lines(x=sim0@params@w, y=relative_abundance)
lines(x=c(min(sim0@params@w),max(sim0@params@w)), y=c(1,1),lty=2)
@

\begin{figure}
<<label=show_plot_relative_comm_abund, echo=FALSE, fig.height=4>>=
<<plot_relative_comm_abund2>>
@
\caption{Relative abundances from the unfished (dashed line) and fished (solid line) trait based model.}
\label{fig:plot_relative_comm_abund2}
\end{figure}

The impact of fishing on species larger than 1000 g can be clearly seen.
As described above and in \citep{andersen_damped_2010}, the fishing pressure lowers the abundance of large fish ($> 1000$ g). This then relieves the predation pressure on their smaller prey (the preferred predator-prey size ratio is given by the $\beta$ parameter, which is set to 100 by default), leading to an increase in their abundance. This in turn increases the predation mortality on their smaller prey, which reduces their abundance and so on.  

This impact can also be seen by looking at the predation mortality by size. 
The predation mortalities are retrieved using the \code{getM2()} method for \class{MizerSim} objects. This returns a three dimensional array of predation mortalities by time x species x size (see the help page for \code{getM2()} for more details). As mentioned above, for the trait based model the predation mortality by size is the same for each species. Therefore we only look at the predation mortality of the first species. 

<<label='get_M2_trait'>>=
m2_no_fishing <- getM2(sim0)[76,1,]
m2_with_fishing <- getM2(sim1)[76,1,]
@

The predation mortalities can then be plotted (see Figure \ref{fig:plot_m2_comm}).

<<label=plot_relative_trait_m2, eval=FALSE>>=
plot(x = sim0@params@w, y = m2_no_fishing, log="x", type="n", xlab = "Size (g)",
    ylab = "M2")
lines(x = sim0@params@w, y = m2_no_fishing, lty=2)
lines(x = sim0@params@w, y = m2_with_fishing)
@

\begin{figure}
<<label=print_plot_relative_trait_m2, echo = FALSE, fig.height=4>>=
<<plot_relative_trait_m2>>
@
\caption{Predation mortalities from the unfished (dashed line) and fished (solid line) trait-based model.}
\label{fig:plot_m2_comm}
\end{figure}

\subsection{Setting up an industrial fishing gear}
\label{sec:trait_additional_gear}

In this section we only want to operate an ``industrial'' fishery, like in \citet{andersen_damped_2010}. Industrial fishing targets the small zooplanktivorous species that are typically used for fishmeal production.

In the previous simulations we had only one fishing gear and it targeted all the species in the community. This gear had a knife-edge selectivity that only selected species larger than 1 kg. Here we expand the model to include multiple fishing gears.
This requires us to look more closely at how fishing gears are handled in \pkg{mizer}.
In \pkg{mizer} it is possible for a fishing gear to catch only a subset of the species in the model. This is useful because when running a simulation with \code{project()} you can specify the effort per gear and so you can turn gears on or off as you want. The shape of the selectivity function of each gear will be the same for all of the species it catches but the selectivity parameter values for each species may be different. For example, we can set up an ``industrial'' gear to catch only a subset of species. Each species it catches will be caught with knife-edge selectivity but they may have a different knife-edge positions.

Using the trait-based model wrapper function it is only possible to have a knife-edge selectivity.
Each species in the model must be given the position of the knife edge and the name of the fishing gear. This is done using the \code{knife\_edge\_size} argument (which we have already seen) and the \code{gear\_names} argument of the \code{set\_trait\_model()} function.
In the previous examples, we passed in the \args{knife\_edge\_size} argument as a single value which was used for all the species. This effectively set up a single gear, that caught all species using the same selectivity pattern. The \code{gear\_names} argument was not used.
Now we are going to pass the \args{knife\_edge\_size} argument as a vector with the same length as the number of species in the model. The values in the vector will be the positions of the knife-edge for each species.
We are also going to pass in a new argument, \code{gear\_names} which is a vector of the names of the gears. The vector must have the same length as the number of species in the model.

We will set up the model to include two fishing gears: an ``industrial'' gear that only catches species with an asymptotic size less than or equal to 500g, and a second gear, ``other'', that catches everything else.
The position of the knife-edge for both gears will occur at 0.05 x the asymptotic size i.e. the selectivity parameters will be different for each species and will depend on the asymptotic size.

To start with we need to know what the asymptotic sizes of the species in the model are so we can determine the knife-edge positions for each species.
As mentioned above, the \code{set\_trait\_model()} function spaces the asymptotic sizes equally on a logarithmic scale. This means we can calculate them by hand.

<<label=calc_trait_winf>>=
no_sp <- 10
min_w_inf <- 10
max_w_inf <- 1e5
w_inf <- 10^seq(from=log10(min_w_inf), to = log10(max_w_inf), length=no_sp)
@

We can then use these asymptotic sizes to set a vector of knife-edges that are 0.05 times the asymptotic size:

<<label=calc_knife_edge_trait>>=
knife_edges <- w_inf * 0.05
@

Now we want to assign each species to either the ``industrial'' or ``other'' gear,
We want to create a vector of gear names. This vector must be the same length as the number of species in the model.

<<label=trait_industrial_gear_names>>=
other_gears <- w_inf > 500
gear_names <- rep("Industrial", no_sp)
gear_names[other_gears] <- "Other"
@

Finally, we can create our \class{MizerParams} object by passing in the \code{knife\_edge\_sizes} and \code{gear\_names} argument. All the other arguments are the same as before:

<<label=set_trait_multiple_gears>>=
params_multi_gear <- set_trait_model(no_sp = no_sp, min_w_inf = min_w_inf,
    max_w_inf = max_w_inf, knife_edge_size = knife_edges, gear_names = gear_names)
@

To check what has just happened we can take a look inside the \class{MizerParams} object. There is a slot in the object called \code{species\_params}. This is a \class{data.frame} that contains the life-history parameters of the species in the model (the results of running this command are not shown):

<<label=looking_at_trait_species_params, results='hide'>>=
params_multi_gear@species_params
@

This \class{data.frame} is pretty interesting as it allows you to investigate the parameters for each species. For example, you can see that the predator-prey mass ratio parameters, \args{beta} and \args{sigma}, are indeed the same for each species.
The columns of the \code{species\_params} \class{data.frame} that we are interested in here are \args{species} (the name of the species, here just numerical identifiers), \args{w\_inf} (the asymptotic size), \args{sel\_func} (the name of the selectivity function for that species), \args{knife\_edge\_size} (the position of the knife-edge of the selectivity) and \args{gear} (the name of the fishing gear). You can see that two gears have been set up, ``Industrial'' and ``Other'' and that they catch different species depending on their asymptotic size.

Having created our \class{MizerParams} object with multiple gears, we can now turn our attention to running a projection with multiple gears.
In our previous examples of calling \code{project()} we have specified the fishing effort with the \args{effort} argument using a single value. This fixes the fishing effort for all gears in the model, for all time steps. We can do this with our multi-gear parameter object:

<<label=project_multi_gear_trait_single_effort>>=
sim_multi_gear <- project(params_multi_gear, t_max = 75, effort = 0.5)
@

By plotting this you can see that the fishing mortality for each species now has a different selectivity pattern (Figure~\ref{fig_trait_multi_gear_single_effort}), and that the position of the selectivity knife-edge is given by the asymptotic size of the species.

<<label=plot_multi_gear_trait_single_effort, eval=FALSE>>=
plot(sim_multi_gear)
@

\begin{figure}
<<label=print_plot_trait_multi_gear_single_effort, echo=FALSE, fig.height=9>>=
<<plot_multi_gear_trait_single_effort>>
@
\caption{Summary plot for the trait-based model with multiple gears when all gears are operational.}
\label{fig_trait_multi_gear_single_effort}
\end{figure}

For the industrial fishery we said that we only wanted species with an asymptotic size of 500 g or less to be fished.
There are several ways of specifying the \args{effort} argument for \code{project()} .
Above we specified a single value that was used for all gears, for all time steps. It is also possible to specify a separate effort for each gear that will be used for all time steps.
To do this we pass in effort as a named vector. Here we set the effort for the ``Industrial'' gear to 0.75, and the effort of the ``Other'' gear to 0 (effectively turning it off).

<<label=project_trait_multigear>>=
sim_multi_gear <- project(params_multi_gear, t_max = 75,
    effort = c(Industrial = 0.75, Other = 0))
@

Now you can see that the ``Industrial'' gear has been operating and that fishing mortality for species larger than 500 g is 0 (Figure~\ref{fig_trait_multi_gear}).

<<label=plot_multi_gear_trait, eval=FALSE>>=
plot(sim_multi_gear)
@

\begin{figure}
<<label=print_plot_trait_multi_gear, echo=FALSE, fig.height=9>>=
<<plot_multi_gear_trait>>
@
\caption{Summary plot for the trait-based model with multiple gears when only the industrial gear that fishes on species with asymptotic size of 500 g or less is operational.}
\label{fig_trait_multi_gear}
\end{figure}

\subsection{The impact of industrial fishing}

In the previous section we set up and ran a model in which an industrial fishery was operating that only selected smaller species.
We can now answer the question: what is the impact of such a fishery?
We can again compare abundances of the fished ($sim\_industrial1$) and unfished ($sim\_industrial0$) cases:

<<label = industrial_fishery_simulation>>=
sim_industrial0 <- project(params_multi_gear, t_max = 75, effort = 0)
sim_industrial1 <- project(params_multi_gear, t_max = 75,
    effort = c(Industrial = 0.75, Other = 0))
total_abund0 <- apply(sim_industrial0@n[76,,],2,sum)
total_abund1 <- apply(sim_industrial1@n[76,,],2,sum)
relative_abundance <- total_abund1 / total_abund0
@

And plot the relative abundances:

<<label=plot_relative_comm_abund_industrial, eval=FALSE>>=
plot(x=sim0@params@w, y=relative_abundance, log="xy", type="n", xlab = "Size (g)",
    ylab="Relative abundance", ylim = c(0.1,10))
lines(x=sim0@params@w, y=relative_abundance)
lines(x=c(min(sim0@params@w),max(sim0@params@w)), y=c(1,1),lty=2)
@

\begin{figure}
<<label=show_plot_relative_comm_abund_industrial, echo=FALSE, fig.height = 4>>=
<<plot_relative_comm_abund_industrial>>
@
\caption{Relative abundances from the unfished (dashed line) and fished (solid line) trait based model with an industrial fishery that targets species with an asymptotic size of 500 g or less.}
\label{fig:plot_relative_comm_abund_industrial}
\end{figure}

This shows another trophic cascade (Figure~\ref{fig:plot_relative_comm_abund_industrial}), although this time one driven by fishing the species at the midrange part of the spectrum, not the largest individuals as before. This trophic cascade acts in both directions. The cascade upwards is driven by the lack of food for predators leading to smaller realised maximum sizes. The cascade downwards has the same mechanism as fishing on large fish, a combination of predation mortality and food limitation.

%---------------------------------------------------

\section{Introducing multispecies models}

The previous sections have used wrapper functions to set up \class{MizerParams} objects that are appropriate for community and trait-based simulations.
We now turn our attention to multispecies, or species-specific, models.
These are potentially more complicated than the community and trait-based models and use the full power of the \pkg{mizer} package.

In multispecies type models multiple species are resolved. However, unlike in the trait-based model which also resolves multiple species, explicit species are represented.
There are several advantages to this approach. As well as investigating the community as a whole (as was done for the community and trait-based models), we are able to investigate the dynamics of individual species. This means that species specific management rules can be tested and species specific metrics, such as yield, can be compared to reference levels.

A multispecies model can take more effort to set up.
For example, each species will have different life-history parameters; there may be multiple gear types with different selectivities targeting different groups of species; the fishing effort of each gear may change with time instead of just being constant (which has been the case in the simulations we have looked at so far); the interactions between the species needs to be considered.

For the remainder of this vignette we build up a multispecies model for the North Sea.
To effectively use \pkg{mizer} for a multispecies model we are going to have to take a closer look at the \class{MizerParams} class and the \code{project()} method.
This will all be done in the context of examples so hopefully everything will be clear.

We also take a closer look at some of the summary plots and analyses that can be performed, for example, calculating a range of size-based indicators.

\section{Setting up a multispecies model}
\label{sec:MizerParams}

\subsection{Overview}
The \class{MizerParams} class is used for storing model parameters.
We have already met the \class{MizerParams} class when we looked at community and trait-based models.
However, direct handling of the class was largely hidden by the use of the wrapper functions.
To set up a multispecies model we need to directly create and use the \class{MizerParams} class.
This is probably the most complicated part of using the \pkg{mizer} package so we will take it slowly.
For additional help you can look at the help page for the class by entering \code{class ? MizerParams}.

The \class{MizerParams} class stores the:
\begin{itemize}
    \item life-history parameters of the species in the community, such as $W_{\infty}$;
    \item size-based biological parameters for the species, such as the search volume, $V(w)$;
    \item stock-recruitment relationship functions and parameters of each species;
    \item interaction matrix to describe the spatial overlap of pairs of species;
    \item parameters relating to the growth and dynamics of the background resource spectrum;
    \item fishing gear parameters: selectivity and catchability.
\end{itemize}

Note that the \class{MizerParams} class does not store any parameters that can vary through time,
such as fishing effort or population abundance. These are stored in the \class{MizerSim} class which
we will come to later in Section~\ref{sec:projection}.

Although the \class{MizerParams} class seems complicated, it is relatively straightforward to set up and use.
Objects of class \class{MizerParams} are created using the constructor method \code{MizerParams()}.
This constructor method can take many arguments. However, creation is simplified because many of the arguments have default values.

In the rest of this section we look at the main arguments to the \code{MizerParams()} constructor method.
To help understand how the constructor is used and how the \class{MizerParams} class
relates to the equations given in Section~\ref{sec:principles}, there is an example
section where we create example parameter objects using data that comes with the
\pkg{mizer} package.

\subsection{The species parameters}
\label{sec:species_parameters_dataframe}

Although many of the arguments used when creating a \class{MizerParams} object are optional, there is one argument that must be supplied by the user: the \emph{species specific parameters}.  These are stored in a single \class{data.frame} object. The \class{data.frame} is arranged species by parameter, so each column is a parameter and each row has the parameters for one of the species in the model.
Although it is possible to create the data.frame by hand in \R, it is probably easier to create the data externally as a .csv file (perhaps using a suitable open source spreadsheet such as LibreOffice) and then read the data into \R.

For each species in the model community there are certain parameters that are essential and that do not have default values. The user must provide values for these parameters.
There are also some essential parameters that have default values, such as the selectivity function parameters, and some that are calculated internally using default relationships if not explicitly provided. These defaults are used if the parameters are not found in the data.frame.
A description of the columns of the species parameter data.frame and any default values can be seen Table~\ref{tab:species_params}.

The essential columns of the species parameters data.frame that have no default values are: \args{species}, the names of the species in the community; \args{w\_inf}, the asymptotic mass of the species; \args{w\_mat}, the mass at maturation; \args{beta} and \args{sigma}, the predator-prey mass ratio parameters $\beta$ and $\sigma$ (see Equation~\ref{eq:4}); stock-recruitment parameters (by default, the stock-recruitment function is a Beverton-Holt type and so, unless a different SRR function is used, a \args{r\_max} column must be provided - see Section~\ref{sec:srr} for more details).

Essential columns that have default values are: \args{k}, the activity coefficient (default = 0); \args{alpha}, the assimilation efficiency (default = 0.6); \args{erepro}, the reproductive efficiency (default value = 1); \args{w\_min}, the size of recruits (default value is the smallest size of the community size spectrum); \args{sel\_func}, the name of the fishing selectivity function (default value = "knife\_edge"); \args{gear}, the name of the fishing gear that catches the species (default value is the name of the species in the \args{species} column); \args{catchability}, the catchability of the fishing gear on that species (default value = 1). Additionally, columns that contain the selectivity function parameters are needed. As mentioned, the default selectivity function is a ``knife\_edge'' function. This has an argument \args{knife\_edge\_size} that determines the knife-edge position and has a default value of \args{w\_min}.
If any of these columns are not included in the species parameter data.frame, the default values are used.

As mentioned above, there are some columns that are essential but if they are not provided, values for them are estimated using the values in the other columns. These columns are:
\args{h}, the maximum food intake; \args{gamma}, the volumetric search rate; \args{ks}, the coefficient for standard metabolism; \args{z0}, the mortality from other sources ($\mu_{b,i}$ in Equation~\ref{eq:mu_b}). These parameters can be included as columns in the species parameters \class{data.frame} if they are available. If they are not provided then the \code{MizerParams()} construction method will try to calculate them.

The \args{h} column is calculated as:

\begin{equation}
    h = \frac{3 k_{vb}}{\alpha f_0} W_\infty^{1/3}
\end{equation}

where $k_{vb}$ is the von Bertalanffy $K$ parameter and $f_0$ is the feeding level of small individuals feeding mainly on the background resource.
This mean that if an \args{h} column is not included in the species parameter data.frame, a column for \args{k\_vb} is necessary. If it is not included then the \code{MizerParams()} method will fail with an error message. The calculation also requires a value of the feeding level of small individuals. This can be passed as an additional argument, \args{f0}, to the \code{MizerParams()} constructor and it has a default value of 0.6.

The \args{gamma} column is calculated using Equation~\ref{eq:gamma}.
This calculation requires that the \args{h} column is available, either included in the species parameter data.frame, or calculated internally using the \args{k\_vb} column as described above. This means that if you include a \args{k\_vb} column in the data.frame, \args{h} and \args{gamma} will be calculated from it.

The \args{z0} column (mortality from other sources) is calculated using Equation~\ref{eq:mu_b}. \args{z0pre} (equivalent to $\mu_0$) and \args{z0exp} (the power that $W_\infty$ is raised to) can be passed as arguments to the \code{MizerParams()} constructor and have default values of 0.6 and \args{n}-1 (\args{n} has a default value of 2/3 - see below) respectively.

The \args{ks} column is calculated as 20\% of \args{h}, i.e. the standard metabolism coefficient is 20\% of the maximum consumption.
Standard metabolism is used in calculation of the growth of individuals as $ks * w_i^p$ (see Section~\ref{sec:growth}).

%\begin{sidewaystable}[ht]
\begin{table}[ht]
    \begin{center}
	%\begin{tabular}{r|p{7cm}|p{7cm}}
	%\begin{tabularx}{r|X|X}
	    %\begin{tabularx}{\linewidth}{r|p{7cm}|X}
	    \begin{tabularx}{\linewidth}{r|X|X}
	    \hline
	    Column name & Description & Default value \\
	    \hline
	    \multicolumn{3}{c}{Life history parameters} \\
	    \hline
	    species & Name of the species & Compulsory (no default)\\
	    w\_inf & The asymptotic mass of the species & Compulsory (no default)\\
	    w\_mat & Maturation mass. Used to calculate values for $\psi$. WHAT IS WMAT IN TERMS OF BIOLOGY? Is it the mass at first maturity? & Compulsory (no default)\\
	    beta & Preferred predator prey mass ratio & Compulsory (no default)\\
	    sigma & Width of prey size preference & Compulsory (no default)\\
        h & Maximum food intake rate. If this is not provided, it is calculated using the \args{k\_vb} column. Therefore, either \args{h} or \args{k\_vb} must be provided. & Optional (no default) \\
        k\_vb & The von Bertalanffy $K$ parameter. Only used to calculate \args{h} if that column is not provided & Optional (no default)\\
	    gamma & Volumetric search rate. If this is not provided, it is calculated using the \args{h} column and other parameters. & Optional (no default)\\
        ks & Standard metabolism coefficient & \args{h} * 0.2\\
        z0 & Background mortality (constant for all sizes). If this is not provided then \args{z0} is calculated as $z0pre * w_{\infty} ^{z0exp}$. \args{z0pre} and \args{z0exp} have default values of 0.6 and -1/3 respectively.  & Optional (no default)\\
	    k & Activity coefficient & 0.0\\
	    alpha & Assimilation efficiency & 0.6 \\
	    erepro & Reproductive efficiency & 1 \\
	    w\_min & The size class that recruits are placed in. & smallest size class of the species size spectrum \\
	    \hline
	    \multicolumn{3}{c}{Fishing gear parameters (see Section~\ref{sec:fishing_gear} for more details).} \\
	    \hline
	    sel\_func & The name of the selectivity function to be used.  & "knife\_edge".\\
	    gear & The name of the fishing gear that selects the species. At the moment a species can only be selected by one gear. & Name of the species \\
	    catchability & The catchability of the fishing gear. & 1\\
	    %a & Length-weight conversion coefficient & Only necessary if length-weight conversion is used (e.g. if specifying length ranges when calculating indicators, or in the fishing selectivity function) \\
	    %b & Length-weight conversion power & See notes for column $a$\\
	    other columns & Other parameters used by the selectivity function. For example, if the default "knife\_edge" function is used then the parameters "knife\_edge\_size" must also be specified as columns (see Section~\ref{sec:fishing_gear}). & \\ 
	    \hline
	    \multicolumn{3}{c}{Stock recruitment parameters (see Section~\ref{sec:srr} for more details).} \\
	    \hline
	    other columns & Any arguments that appear in the stock-recruitment function must also have a column of values (see Section~\ref{sec:srr}) & \\
	%\end{tabular}
	\end{tabularx}
	\caption{Columns of the species parameters data.frame}
	\label{tab:species_params}
    \end{center}
%\end{sidewaystable}
\end{table}

You can see in Table~\ref{tab:species_params} that most of the species specific
parameters relate to the life history of the species.
The others relate to the gear selectivity function and the stock-recruitment relationship.
These are explained further in Sections~\ref{sec:fishing_gear} and \ref{sec:srr} respectively. 



\subsection{Fishing gears and selectivity}
\label{sec:fishing_gear}
%As well as life-history parameters, the parameter data.frame must also have columns that specify
%parameter values for the chosen fishing selectivity function. This is covered in more detail
%in Section~\ref{sec:fishing_gear}. In brief, any parameter that is used in the selectivity
%function (apart from size) must also be included in the parameter data.frame.
%For example, the default selectivity function uses the parameters \code{l25}, \code{l50},
%\code{a} and \code{b}. This means that if the default selectivity function is being used then
%these must also be included in the parameter data.frame.

In this section we take a look at how fishing is implemented and how fishing gears are set up within
\pkg{mizer}.

In \pkg{mizer}, fishing mortality is imposed on species by fishing gears. The total fishing
mortality is obtained by summing over the mortality from all gears,
\begin{equation}
    \label{eq:muf}
    \mu_{f.i}(w) = \sum_g F_{g,i}(w),
\end{equation}
where the fishing mortality $F_{g,i}(w)$ imposed by gear $g$ on species $i$ at size $w$ is calculated as:
\begin{equation}
    \label{eq:sel}
    F_{g,i}(w) = S_{g,i}(w) Q_{g,i} E_{g}
\end{equation}
where $S$ is the selectivity by species, gear and size, $Q$ is the catchability by species
and gear and $E$ is the fishing effort by gear.
The selectivity at size has a range between 0 (not selected at that size) to 1 (fully selected at
that size).
Catchability is used as an additional scalar to make the link between gear selectivity, fishing
effort and fishing mortality. 
For example, it can be set so that an effort of 1 gives a desired fishing mortality.
In this way effort can then be specified relative to a 'base effort', e.g. the effort
in a particular year.
Fishing effort is not stored in the \class{MizerParams} object.
Instead, effort is set when the simulation is run and can vary through time (see Section~\ref{sec:projection}).

At the moment a species can only be selected by one fishing gear, although each gear can select more than one species (this is a limitation with the current package that will be developed in future releases).

The selectivity at size of each gear is given by a selectivity function. Some selectivity
functions are included in the package. New functions can be defined by the user. 
Each gear has the same selectivity function for all the species it selects, but the parameter
values for each species may be different, e.g. the lengths of species that a gear selects may be different.

The name of the selectivity function is given by the $sel\_func$ column in the species parameters data.frame.
Each selectivity function has a range of arguments. Values for these arguments
must be included as columns in the species parameters data.frame. The names of the columns must exactly
match the names of the arguments. 
For example, the default selectivity function is \code{knife\_edge} which has sudden change of selectivity from 0 to 1 at a certain size.
The arguments for this selectivity function can be seen in the help page
for this function. To see them enter:

<<eval=FALSE>>=
?knife_edge
@

It can be seen that the \code{knife\_edge()} function has arguments \args{w} and \args{knife\_edge\_size}
The first argument, \code{w}, is size (the function calculates selectivity at size).
All selectivity functions must have \code{w} as the first argument.
The values for the other arguments must be found in the species parameters data.frame.
So for the \code{knife\_edge()} function there should be a \args{knife\_edge\_size} column (but note that because \code{knife\_edge()} is the default selectivity function, the \args{knife\_edge\_size} argument actually has a default value = \args{w\_mat}).
This can be seen in the example in Section \ref{sec:params_example}.
If the columns of the selectivity function arguments are not in the species parameter data.frame, an error is thrown when the \class{MizerParams} object is created.

Users are able to write their own size based selectivity function. The first argument to the
function must be \code{w} and the function must return a vector of the selectivity
(between 0 and 1) at size.

The name of the fishing gear is given in the \args{gear} column of the species parameter
data.frame. If the \args{gear} column is not specified, the default gear name is simply
the name of the species. This implies that each species is fished by a different gear.
This approach can be used to explore the impacts of changing fishing mortality on individual species.

\subsection{The stock-recruitment relationship}
\label{sec:srr}

In size spectrum modelling recruitment refers to the flux of individuals that enter the size-spectrum at the smallest size group of that species (given by the parameter \args{w\_min} in the species parameter data.frame).
As can be seen in Section~\ref{sec:principles}, calculating the recruitment flux involves calculating the ``density independent'' recruitment, $R_{p.i}$ (see Section~\ref{sec:reproduction}).
The $R_{p.i}$ is then modified by a stock-recruitment relationship (SRR) to impose some form of density-dependence. This then results in the density-dependent recruitment, $R_i$ (see Section~\ref{sec:recruitment}).
Without this density dependence, the realised recruitment flux to the smallest size class is determined only by $R_{p.i}$.
The default SRR is a Beverton-Holt type function (see Equation~\ref{eq:R}).

Similar to the fishing selectivity functions, any parameter used in the stock-recruitment function, other than $R_{p.i}$, must be in the species parameter data.frame and the column must have the same name as the function argument.
For example, the default stock-recruitment function has a second argument to it, \args{r\_max}. Therefore the species parameter data.frame must have an \args{r\_max} column.

Users are able to write their own stock-recruitment function. The first argument to the function must be \args{rdi}, which is the density independent recruitment $R_{p.i}$, the second argument must be \args{species\_params}, the dataframe with the species parameters. This function should then be assigned to the \args{srr} slot of the MizerParams object.


\subsection{The interaction matrix}
\label{sec:interaction_matrix}

The interaction matrix describes the interaction of each pair of species
in the model. This can be viewed as a proxy for spatial interaction
e.g. to model predator-prey interaction that is not size based.
The values in the interaction matrix are used to scale the encountered food and predation mortality (see Section~\ref{sec:encounter}).
The matrix is square with every element being the interaction between a pair of species. The dimensions, nrows and ncolumns, therefore equal the number of species.
The values are between 0 (species do not overlap and therefore do not interact with each other) to 1 (species overlap perfectly).
If all the values in the interaction matrix are set to 1 then predator-prey interactions are determined entirely by size-preference.

The interaction matrix must be of type \class{array} or \class{matrix}. 
One way of creating your own is to enter the data using a spreadsheet (such as LibreOffice) and saving it as a .csv file. 
The data can be read into \R using the command \code{read.csv()}. This reads in the data as a data.frame. We then need
to convert this to a matrix using the \code{as()} function. An example of how to do this is given in Section~\ref{sec:params_example}.

It should be noted that the order of species in the interaction matrix has to be the same as the order in the species parameters data.frame.
Although you can specify the dimnames of the interaction matrix, these names are overwritten by the species names from the species parameters data.frame
inside the \class{MizerParams} constructor.

If an interaction matrix is not specified to the \code{MizerParams()} constructor the default iteration matrix is used. This has all values set to 1. 

\subsection{The other \code{MizerParams()} arguments}
\label{sec:other_mizerparams_arguments}

As well as the essential species parameters data.frame and the interaction
matrix, there are several other arguments to the \code{MizerParams} constructor.
These have default values. 
The arguments can be seen in Table~\ref{tab:other_params}.

\begin{table}[ht]
    \begin{center}
	\begin{tabularx}{\linewidth}{r|X|X}
	\hline
	Argument & Description & Default value \\
	\hline
	min\_w & The smallest size of the species community size spectrum. Note that this a different w\_min to the one in the species parameter data.frame. & 0.001 \\
	max\_w & The largest size of the species size spectrum. & The largest w\_inf in the species parameters data.frame * 1.1 \\
	no\_w & The number of size bins in the species size spectrum. & 100 \\
	min\_w\_pp & The smallest size of the background size spectrum. & 1e-10 \\
	no\_w\_pp & The number of size bins in the background size spectrum. & round(no\_w) * 0.3 \\
	n & The scaling of intake. & 2/3 \\
	p & The scaling of standard metabolism. & 0.7 \\
	q & The search volume exponent. & 0.8 \\
	r\_pp & The growth rate of the primary productivity (the background spectrum). & 10 \\
	kappa & The carrying capacity of the background spectrum. & 1e11 \\
	lambda & The exponent of the background spectrum. & 2+q-n \\
	w\_pp\_cutoff & The cut off size of the background spectrum. & 10 \\
    f0 & The feeding level of small individuals feeding mainly on the background resource. Used to calculate \args{h} and \args{gamma} if they are not provided in the species parameter data.frame. & 0.6\\
    z0pre & If \args{z0}, the mortality from other sources, is not a column in the species data.frame, it is calculated as $z0pre * w_\infty ^{z0exp}$. & 0.6 \\
    z0exp & See z0pre & n - 1\\
	\end{tabularx}
	\caption{Other parameters to the \code{MizerParams()} constructor}
	\label{tab:other_params}
    \end{center}
\end{table}

Some of these parameters may be used to calculate the species specific parameters if they are not provided. For example, if there is no \args{gamma} column in the species parameter data.frame, then it is calculated using \args{kappa} and \args{f0}.
This means that depending on which columns have been provided in the species parameters data.frame, some of the parameters in Table~\ref{tab:other_params} may not be used. For example, if the column \args{z0} (the mortality from other sources) has been included, then the arguments \args{z0pre} and \args{z0exp} are not used.

Determining a value for the \args{kappa} argument can be difficult and may need to be estimated through some kind calibration process.
The default value \args{kappa} is for the North Sea model.

\subsection{Examples of making a \class{MizerParams} objects}
\label{sec:params_example}

As mentioned in the preceding sections, an object of \class{MizerParams} is created by using the \code{MizerParams()}
constructor method. You can see the help page for the constructor:

<<label=help_MP_constructor, eval=FALSE>>=
help(MizerParams)
@

This shows that the constructor takes the following arguments:
\begin{description}
    \item[object] The species parameter data.frame (see Section~\ref{sec:species_parameters_dataframe}). This is compulsory with no default value.
    \item[inter] The interaction matrix (see Section~\ref{sec:interaction_matrix}). The default is a matrix of 1s.
    \item[...] Other model parameters (see Section~\ref{sec:other_mizerparams_arguments}).
\end{description}

In the rest of this section we demonstrate how to pull these elements together to make \class{MizerParams} objects. 

The first step is to prepare the species specific parameter data.frame.
As mentioned above, one way of doing this is to use a spreadsheet and save it as a .csv file. We will use this approach here.
An example .csv file has been included in the package. This contains the species parameters for a multispecies North Sea model \citep{blanchard_multispecies_2014}.
This file is placed in the \code{doc} folder of the package installation.
The location of the file can be found by running:

<<label = get_location_for_ns_params,eval=FALSE>>=
system.file("doc/NS_species_params.csv",package="mizer")
@

This file can be opened with most spreadsheets or a text editor for you to inspect.
This can be loaded into \R using the following code (after you
have told \R to look in the right directory):

<<>>=
params_data <- read.csv("NS_species_params.csv")
@ 

This reads the .csv file into \R in the form of a data.frame.
You can check this with the \code{class}:

<<>>=
class(params_data)
@

The example data.frame can be inspected by entering the name of the object.

<<label=show_simple_params_data>>=
params_data
@

You can see that there are \Sexpr{nrow(params_data)} species and \Sexpr{ncol(params_data)} columns of parameters: \args{species}, \args{w\_inf},\args{w\_mat},\args{beta},\args{sigma},\args{r\_max} and \args{k\_vb}.

Of these parameters, \args{species}, \args{w\_inf}, \args{w\_mat}, \args{beta} and \args{sigma} are essential and have no default values (as described in Section~\ref{sec:species_parameters_dataframe}).
\args{r\_max} is a SRR parameter. We are going to use the default Beverton-Holt type SRR which has \args{r\_max} as an argument (see Section~\ref{sec:srr}), making this column also essential.
The final column, \args{k\_vb}, will be used to calculate values for \args{h} and then \args{gamma}. This column is only essential here because the \args{h} and \args{gamma} are not included in the data.frame. It would also have been possible to include \args{h} and \args{gamma} columns in the data.frame and not include the \args{k\_vb} column.

The values of the non-essential species specific parameters \args{alpha}, \args{k}, \args{ks}, \args{z0}, \args{w\_min} and \args{erepro} are not included in the data.frame. This means that the default values will be automatically used when we create the \class{MizerParams} object.

Note that there are no columns describing the fishing selectivity. There is no \args{sel\_func} column to determine the selectivity function.
This means that the default selectivity function, \code{knife\_edge}, will be used. As mentioned in Section~\ref{sec:fishing_gear},
this function also needs another argument, \args{knife\_edge\_size}. This is not present in the data.frame and so it will be set to the default value of \args{w\_mat}. Also, there is no \args{catchability} column so a default value for \args{catchability} of 1 will be used for all gears and species.

This species parameter data.frame is the minimum we need to create a \class{MizerParams} object as it contains only essential columns. To create the \class{MizerParams} object we pass the data.frame into the \code{MizerParams()} constructor method:

<<label=first_MP, results='hide'>>=
params <- MizerParams(params_data)
@

We have just created a \class{MizerParams} object:

<<label=class_MP>>=
class(params)
@

As has been mentioned in Sections~\ref{sec:comm_model} and~\ref{sec:trait_based_model}, a \class{MizerParams} object is made up of ``slots'' that store a wide range of model parameters. Each of these slots contains information on the parameters in the model. A description of these slots can be found by calling \code{help()} on the class: \code{help("MizerParams-class")}.
The different slots can be accessed using the \code{@} operator.

The slot \args{species\_params} contains the species parameters data.frame that was passed in to the constructor. We can inspect this slot with:

<<label=looking_at_params_slot>>=
params@species_params
@

We can see that this contains the original species data.frame (with \args{w\_inf} and so on), plus any default values that may not have been included in the original data.frame. For example, we can see that there are no columns for \args{alpha} and \args{h} and \args{gamma} etc.

Also note how the default fishing gears have been set up. Because we did not specify gear names in the original species parameter data.frame, each species is fished by a unique gear named after the species.  This can be seen in the new \args{gear} column which holds the names of the fishing gears.
Also, the selectivity function for each fishing gear has been set in the \args{sel\_func} column to the default function, \code{knife\_edge()}.
A \args{catchability} column has been added with a default value of 1 for each of the species that the gear catches.
An example of setting the catchability by hand can be seen in Section~\ref{sec:north_sea_example}.

As has been shown in Sections~\ref{sec:comm_model} and~\ref{sec:trait_based_model}, there is a \code{summary()} method for \class{MizerParams} objects which prints a useful summary of the model parameters:

<<label=summary_params, results='hide'>>=
summary(params)
@

As well as giving a summary of the species in the model and what gear is fishing what species, it gives a summary of the size structure of the community. For example there are \Sexpr{length(params@w)} size classes in the community, ranging from \Sexpr{signif(min(params@w),3)} to \Sexpr{signif(max(params@w),3)}. These values are controlled by the arguments \args{no\_w}, \args{min\_w} and \args{max\_w} respectively. For example, if we wanted 200 size classes in the model we would use:

<<label=MP_200, eval=FALSE>>=
params200 <- MizerParams(params_data, no_w=200)
summary(params200)
@

So far we have created a \class{MizerParams} object by passing in only the species parameter data.frame argument.
This means the interaction matrix will be set to the default value (see Section~\ref{sec:interaction_matrix}). This is a matrix of 1s, implying that all species fully interact with each other, i.e. the species are spread homogeneously across the model area.
For the North Sea this is not the case and so the model would be improved by also including an interaction matrix which describes the spatial overlap between species (see Section~\ref{sec:interaction_matrix}).

An example interaction matrix for the North Sea has been included in \pkg{mizer} as a .csv file.  The location of the file can be found by running:

<<eval=FALSE>>=
system.file("doc/inter.csv",package="mizer")
@

Take a look at it in a spreadsheet if you want.  As mentioned above, to read this file into \R we can make use of the \code{read.csv()} function. However, this time we want the first column of the .csv file to be the row names. We therefore use an additional argument to the \code{read.csv()} function: \args{row.names}.

<<>>=
inter <- read.csv("inter.csv", row.names=1)
@

The \code{read.csv()} function reads the data into a data.frame.  We want the interaction matrix to be of class \class{matrix} so we need to make use of the \code{as()} function.

<<label=inter_df_to_matrix>>=
inter <- as(inter, "matrix")
@

We now have an interaction matrix that can be passed to the \class{MizerParams} constructor along with the species parameter data.frame.
To make the \class{MizerClass} object you just call the constructor method and pass in the arguments.
We will use default values for the remainder of the arguments to the \code{MizerParams()} method (see Section~\ref{sec:other_mizerparams_arguments} and Table~\ref{tab:other_params}).
This means that we only need to pass in two arguments to the constructor:

<<results='hide'>>=
params <- MizerParams(params_data, interaction = inter)
@

Note that the first argument must be the species parameters data.frame.
The remaining arguments can be in any order but should be named.
If we didn't want to use default values for the other arguments we would pass them in to the constructor by name.

We now have all we need to start running projections. Before we get to that though, we'll take a quick look at how different fishing gears can be set up.



%-------------------------------------------------------------------------------------
\subsection{Setting different gears}
\label{sec:setting_different_gears}

In the above example, each species is caught by a different gear (named after the species it catches). This is the default when there is no \args{gear} column in the species parameter data.frame.

Here, we look at an example where we do specify the fishing gears.  We take the original \code{params\_data} species parameter data.frame that was read in above and bind an additional column, \args{gear}, to it. This \args{gear} column contains the name of the gear that catches the species in that row.
Here we set up four different gears: Industrial, Pelagic, Beam and Otter trawl, that catch different combinations of species.

<<>>=
params_data_gears <- params_data
params_data_gears$gear <- c("Industrial","Industrial","Industrial",
		      "Pelagic","Beam","Otter",
		      "Beam","Otter","Beam",
		      "Otter","Otter","Otter")
@

If you inspect the \code{params\_data} object you will see a new column, \args{gear}, has been added to it.  
We then make a new \class{MizerParams} object as before:

<<label=set_params_gears, results='hide'>>=
params_gears <- MizerParams(params_data_gears, interaction = inter)
@

You can see the result by calling \code{summary()} on the \args{params\_gears} object.

In this example the same gear now catches multiple stocks. For example, the ``Industrial'' gear catches Sprat, Sandeel and Norway Pout.
Why would we want to set up the gears like this?
In the next section we will see that to project the model through time you can specify the fishing effort for each gear through time.
By setting the gears up in this way you can run different management scenarios of changing the efforts of the fishing gears rather than on
individual species.
It also means that after a simulation has been run you can examine the catches by gear.

%-------------------------------------------------------------------------------------
\section{Running a simulation}
\label{sec:projection}

In the preceding section and in the sections on the community and trait-based models above, we used the \code{project()} method to perform simple simulations where the fishing effort was held constant throughout the duration of the simulation.
In the trait-based model example, we also looked at how the effort for different gears could be specified.
In this section we take a detailed look at how the \code{project()} method works and the different ways in which effort and time can be set up.

In \pkg{mizer}, simulations are performed using the \code{project()} method. This method takes a \class{MizerParams} object and projects it
forward through time, starting from an initial population abundance and with a pre-determined fishing effort pattern.

Running a projection with \code{project()} requires various arguments:
\begin{description}
    \item[A \class{MizerParams} object] The model parameters (see previous
	section);
    \item[Fishing effort] The fishing effort of each gear through time;
    \item[Initial population] The initial abundances of the stocks and the
	background spectrum;
    \item[Time arguments] Arguments to control the time of the simulation,
	including the simulation time step, the length of the simulation
	and how frequently the output is stored.
\end{description}

The help page for \code{project()} describes the arguments in more detail.

The \class{MizerParams} class was explored in the previous section.
In this section we will look at the other arguments and use examples to perform some simple projections.

The object returned from calling \code{project()} is of class \class{MizerSim}. This contains the abundances of the species in the model by time and size. It is described fully in Section~\ref{sec:mizersim}.

\subsection{The time arguments}
\label{sec:time_arguments}

There are three arguments that control time in the \code{project()} method:
\args{dt}, \args{t\_max} and \args{t\_save}. All of them have default values.

\args{t\_max} determines the maximum time of the simulation, i.e. how long the projection is run for.
The default value for \args{t\_max} is 100 respectively.

\args{dt} is the time step used by the numerical solver in \code{project()}.
This is the time step on which the model operates. The smaller the value, the longer the model will take to run. However, sometimes it is necessary to use a small value to avoid numerical instabilities. The default value is 0.1.

The final argument is \args{t\_save}. This sets how frequently \code{project()} stores the state of the model in the resulting \class{MizerSim} object.
For example, if \args{t\_save} = 2, the state of the model is stored at t = 0, 2, 4... etc.
\args{t\_save} must be a multiple of \args{dt}. The default value of \args{t\_save} is 1.

\subsection{Setting the fishing effort}

The fishing effort argument describes the effort of the fishing gears in the model through time. We have already seen that information on the fishing gears and their selectivities and catchabilities is stored in the \code{MizerParams} argument.

There are three ways of setting the fishing effort. Examples of all three can be seen in Section~\ref{sec:projection_examples}.

The simplest way is by passing the \args{effort} argument as a single number.
This value is then used as the fishing effort by all of the gears at each time step of the projection, i.e. fishing effort is constant throughout the simulation and is the same for all gears. We have seen this method in the community and trait-based model sections above.
The length of the simulation is determined by the \args{t\_max} argument (see Section~\ref{sec:time_arguments}).

The second method for setting the fishing effort is to use a numeric vector that has the same length as the number of gears.
The values in the vector are used as the fishing effort of each gear at each time step, i.e. again, the fishing effort is constant through time but now each gear can have a different constant effort.
The effort vector must be named and the names must be the same as the gears in the \code{MizerParams} object.
Again, the length of the simulation is determined by the \args{t\_max} argument.

Finally, the most sophisticated way of setting the fishing effort is to use a two-dimensional array or matrix of values, set up as time step by gear.
Each row of the array has the effort values of each fishing gear by time.
The array must have dimension names. The names of the first dimension (the row names) are the times. The steps between the times can be greater than the \args{dt} argument but must be contiguous.
The names of the second dimension (the column names) must match the names of the gears in the \class{MizerParams} object used in the projection.

It is not necessary to supply a \args{t\_max} argument when the effort is specified as an array because the maximum time of the simulation is taken from the dimension names. If a value for \args{t\_max} is also supplied it is ignored.

\subsection{Setting the initial population abundance}
\label{sec:setting_initial_abundances}

When running a simulation with the \code{project()} method, the initial populations of the species and the background spectrum need to be specified. These are passed to \code{project()} as the arguments \args{initial\_n} and \args{initial\_n\_pp} respectively.
\args{initial\_n} is a matrix (with dimensions species x size) that contains the initial abundances of each species at size (the sizes must match those in the species size spectrum). \args{initial\_n\_pp} is a vector of the same length as the the length of the full spectrum (which can be seen as slot \args{w\_full} in the \class{MizerParams} object).

By default, the \args{initial\_n} argument has values automatically calculated by the function \code{get\_initial\_n()}.
The default value for \args{initial\_n\_pp} is the carrying capacity of the background spectrum, stored in the \args{cc\_pp} slot of the
\class{MizerParams} parameters object.

\subsection{What do you get from running \code{project()}?}
\label{sec:mizersim}

Running \code{project()} returns an object of type \class{MizerSim} that stores the results of the projection.
Like the \class{MizerParams} class this is also made up of various ``slots'', which can be accessed using the \code{@} operator.
An object of \class{MizerSim} has four slots, details of which can be seen in the help page (\code{help("MizerSim-class"}).
The \args{params} slot holds the \class{MizerParams} object that was passed in to \code{project()}.
The \args{effort} slot holds the fishing effort of each gear through time. Note that the \args{effort} slot may not be exactly the same as the \args{effort} argument that was passed in to \code{project()}. This is because only the saved effort is stored (the frequency of saving is determined by the argument \args{t\_save}).
The \args{n} and \args{n\_pp} slots hold the saved abundances of the species and the background population at size respectively. 

\subsection{Projection examples}
\label{sec:projection_examples}

In this section we'll look at how to run simulations with the \code{project()} method.
The examples will focus on how fishing effort can be specified in different ways.
The results of the simulations will not be explored in detail. We will leave that for Section~\ref{sec:summaries}.

%We will use the \args{params\_gears} object with four gears that was created in the \class{MizerParams} example above.
Remember that the fishing mortality by size on a species is the product of the selectivity, the catchability and the effort of the gear that caught it (see Equation~\ref{eq:sel}). We have not specified any catchability values in the species parameter data.frame so the default value of 1 is used. The selectivity ranges between 0 and 1. This means that in these examples the fishing mortality of a fully selected species is given by the effort of the gear that catches it.

\subsubsection{Projections with single, simple constant effort}

When we use a single value for the \args{effort} argument, the value is used as a constant effort for all the gears.
This method can be particularly useful for quickly projecting forward without fishing (you just set the \args{effort} argument to 0).

We will use the \args{params} object that was created in Section \ref{sec:params_example} 
in which each species is caught by a separate gear.
Here we make the object again:

<<label = remaking_simple_ms_params, results='hide'>>=
params <- MizerParams(params_data, interaction = inter)
@

As described above, effort is associated with fishing gears.
Because we haven't specified any gears in the \args{params\_data} species parameter data.frame, each species is caught by a separate gear, named after the species.

As well as thinking about the \args{effort} argument we also need to consider the time parameters.
We will project the populations forward until time equals 10 (\args{t\_max} = 10), with a time step of 0.1 (\args{dt} = 0.1), saving the output every time step (\args{t\_save} = 1). We use a constant effort value of 1.0.

<<label=siple_projection_single_effort>>=
sim <- project(params, effort = 1, t_max = 10, dt = 0.1, t_save = 1)
@


The resulting \args{sim} object is of class \class{MizerSim}.
At this point we won't explore how the results can be investigated in detail. However, we will use the basic summary plot that you have seen before:

<<label=plot_basic_ms_sim, eval=FALSE>>=
plot(sim)
@

\begin{figure}
<<label=print_plot_basic_ms_sim, echo=FALSE, fig.height=9>>=
<<plot_basic_ms_sim>>
@
\caption{Plot of the North Sea multispecies model with no default fishing gears and constant effort of 1.}
\label{fig:plot_food_demo}
\end{figure}

Without fishing the community settles down to equilibria at about t = 50 (Figure~\ref{fig:plot_food_demo}). The big difference between this multispecies model and the trait-based model can be seen in the range of M2 and feeding level values. With the trait-based model all the ``species'' had the same M2 and feeding level patterns (see Figure~\ref{fig:plot_trait_demo}). Here the species all have different patterns, driven by their differing life history characteristics and the heterogeneous interaction matrix.

You can also see in Figure~\ref{fig:plot_food_demo} that each species has different fishing selectivity (see the Total fishing mortality panel). Remember that the default setting for the fishing gears is a knife-edge gear where the knife-edge is positioned at the species \args{w\_mat} parameter.

The effort through time can be inspected by looking at the \args{effort} slot (we use the \code{head()} function to just show the first few lines).
The \args{effort} slot shows the effort by time and gear.
You can see here that each species is caught by a separate gear, and the gear is named after the species.
In this example, we specified the \args{effort} argument as a single numeric of value 1. As you can see this results in the same effort being used for all gears for all time steps:

<<label=show_effort>>=
head(sim@effort)
@

A \code{summary()} method is also available for objects of type \class{MizerSim}. This is essentially the same as the summary for \class{MizerParams} objects, but includes information on the simulation time parameters.

<<summary_mizersim,eval=FALSE>>=
summary(sim)
@

If we decrease \args{t\_save} but keep \args{t\_max} the same then we can see that the time dimension of the \args{effort} slot changes accordingly.
This will also be true of the \args{n} and \args{n\_pp} slots.
Here we reduce \args{t\_save} to 0.5, meaning that the effort and abundance information is stored at t = 1.0, 1.5, 2.0 etc.

<<label=simple_proj_tsave05>>=
sim <- project(params_gears, effort = 1, t_max = 10, dt = 0.1, t_save = 0.5)
head(sim@effort)
@

\subsubsection{Setting constant effort for different gears}
\label{sec:proj_diff_gears_constant_effort}

As mentioned above, we can also set the effort values for each gear separately using a vector of effort values. This still keeps the efforts constant through time but it means that each gear can have a different constant effort.

Here we will use the \class{MizerParams} object with four gears, \args{params\_gears}, that we created in Section~\ref{sec:setting_different_gears}.
The names of the gears are \Sexpr{paste(unique(params_gears@species_params$gear), collapse = ", ")}.
We need to create a named vector of effort, where the names match the gears.
For example, here we want to switch off the industrial gear (i.e. effort = 0), keep the pelagic gear effort at 1, set the effort of the beam trawl gears to 0.3 and the effort of the otter trawl gear to 0.7.
We set the \args{effort} like this: 

<<label=set_effort_vector>>=
effort <- c(Industrial = 0, Pelagic = 1, Beam = 0.3, Otter = 0.7)
@

We then call \code{project()} with this effort and inspect the resulting \args{effort} slot (again we use the \code{head()} function to just show the first few lines):

<<label=project_effort_vector>>=
sim <- project(params_gears, effort = effort, t_max = 10, dt = 1, t_save = 1)
head(sim@effort)
@

You can see that the effort for each gear is constant but each gear has the effort that was specified in the \args{effort} argument.

This impact of this can be seen plotting the fishing mortality. There is a dedicated plot, \code{plotFMort()}, that shows the fishing mortality at size for each species at a particular time step (the default is the final time step).
The fishing mortality on each of the species is determined by the effort of the gear that caught it (Figure~\ref{fig:plotFmort_example}).

<<label=plotFMort, eval=FALSE>>=
plotFMort(sim)
@

\begin{figure}
<<label=print_plotFMort, echo=FALSE, fig.height=4, fig.keep='last'>>=
<<plotFMort>>
@
\caption{An example of using the \code{plotFMort()} method to show how different efforts for different gears can be specified.}
\label{fig:plotFmort_example}
\end{figure}

\subsubsection{An example of changing effort through time}

In this example we set up a more complicated fishing effort structure that allows the fishing effort of each gear to change through time.
As mentioned above, to do this, effort must be supplied as a two dimensional array or matrix. The first dimension is time and the second dimension is gear.
The dimensions must be named. The gear names must match the gears in the \class{MizerParams} object.
Also, as mentioned above, if effort is passed in as an array then the length of the simulation is determined by the time dimension names and the argument \args{t\_max} is not used. Instead the simulation runs from
the earliest time in the effort array to the latest.

Here, we will use the \args{params\_gears} object we created in 
Section~\ref{sec:setting_different_gears} which has four gears.
The names of the gears are \Sexpr{paste(unique(params_gears@species_params$gear), collapse = ", ")}.

In this example, we will project forward from time $t=1$ to time $t=10$. The effort of the industrial gear is held constant at 0.5, the effort of the pelagic gear is increased linearly from 1 to 2, the effort of the beam trawl decreases linearly from 1 to 0, whilst the effort of the otter trawl decreases linearly from 1 to 0.5.

First we create the empty \args{effort} array:
<<label=set_empty_effort_array>>=
gear_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))
@

Then we fill it up, one gear at a time, making heavy use of the \code{seq()} function to create a sequence:

<<label=fill_effort_array>>=
effort_array[,"Industrial"] <- 0.5
effort_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))
@

The first few rows of the effort array are shown as an illustration:
<<label=show_effort_array>>=
head(effort_array)
@
The first row gives the effort between times 1 and 2, the second between times 
2 and 3, and so on. The time 10 row in the array is not actually used, except
to set the final time for the simulation.
Now we can use this effort array in the projection:

<<label=project_effort_array>>=
sim <- project(params_gears,effort=effort_array, dt=0.1, t_save = 1)
head(sim@effort)
@

As you can see, it can be quite fiddly to set up a complicated effort array so it may be easier to prepare it in advance as a .csv file and read it in, similar to how we read in the interaction matrix in Section~\ref{sec:params_example}.
We give an example of this in Section~\ref{sec:north_sea_example}.

Note that in this example we set up the effort array so that the effort was set every whole time step (e.g. time = 1, 2, etc). This does not have to be the case and it is possible to set the effort more frequently than that, e.g. at time = 1.0, 1.5, 2.0, 2.5 etc. The only restriction is that the difference between time dimension names must be at least as big as the \args{dt} argument.

%-------------------------------------------------------------
\section{Exploring the simulation results}
\label{sec:exploring}

In the previous sections we saw how to set up a model and project it forward through time under our desired fishing scenario. The result of running a projection is an object of class \class{MizerSim}. What do we then do?  How can we explore the results of the simulation? In this section we introduce a range of summaries, plots and indicators that can be easily produced using methods included in \pkg{mizer}.

We will use the same \class{MizerSim} object for these examples:

<<label = exploration_simulation>>=
sim <- project(params_gears,effort=effort_array, dt=0.1, t_save = 1)
@

\subsection{Directly accessing the slots of \class{MizerSim} objects}

We have seen in previous sections that a \class{MizerSim} object is made up of various ``slots'' that contain the original parameters (\args{species\_params}), the population abundances (\args{n}), the abundance of the background resource spectrum (\args{n\_pp}) and the fishing effort (\args{effort}).

The projected species abundances at size through time can be seen in the \args{n} slot.  This is a three-dimensional array (time x species x size).
Consequently, this array can get very big so inspecting it can be difficult.
In the example we have just run the time dimension of the \args{n} slot has \Sexpr{dim(sim@n)[1]} rows (one for the initial population and then one for each of the saved time steps). There are also 12 species each with 100 sizes. We can check this by running the \code{dim()} function and looking at the dimensions of the \args{n} array:

<<label=show_dim_n>>=
dim(sim@n)
@

To pull out the abundances of a particular species through time at size you can subset the array. For example to look at Cod through time you can use:

<<results='hide'>>=
sim@n[,"Cod",]
@

This returns a two-dimensional array: time x size, containing the cod abundances. The time dimension depends on the value of the argument \args{t\_save} when \code{project()} was run. You can see that even though we specified \args{dt} to be 0.1 when we called \code{project()}, the \args{t\_save} argument had means that the output is only saved every time step.

The \args{n\_pp} slot can be accessed in the same way.

\subsection{Summary methods for \class{MizerSim} objects}
\label{sec:summaries}

As well as the \code{summary()} methods that are available for both \class{MizerParams} and \class{MizerSim} objects, there are some useful summary methods to pull information out of a \class{MizerSim} object (see Table~\ref{tab:summary_methods}). All of these methods have help files to explain how they are used.
(It is also possible to use most of these methods with a \class{MizerParams} object if you also supply the population abundance as an argument. This can be useful for exploring how changes in parameter value or abundance can affect summary statistics and indicators. We won't explore this here but you can see their help files for more details.)

\begin{table}[ht]
    \begin{center}
	\begin{tabularx}{\linewidth}{r|X|X}
	\hline
	Method & Returns & Description \\
	\hline
	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.\\
	%getPhiPrey() & & \\
	getFeedingLevel() & Three dimensional array (time x species x size) & Feeding level of each species by size through time. \\
	%getPredRate() & &\\
	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.\\
	%getZ() & & \\
	%getRDI & & \\
	%getRDD & & \\ % Need to add these
	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. \\
	\hline
	\end{tabularx}
	\caption{Summary methods for \class{MizerSim} objects.}
	\label{tab:summary_methods}
    \end{center}
\end{table}

The methods \code{getBiomass()} and \code{getN()} have additional arguments that allow the user to set the size range over which to calculate the summary statistic.  This is done by passing in a combination of the arguments \args{min\_l}, \args{min\_w}, \args{max\_l} and \args{max\_w} for the minimum and maximum length or weight.

If \args{min\_l} is specified there is no need to specify \args{min\_w} and so on. However, if a length is specified (minimum or maximum) then it is necessary for the species parameter data.frame (see Section~\ref{sec:species_parameters_dataframe}) to include the parameters \args{a} and \args{b} for length-weight conversion.
It is possible to mix length and weight constraints, e.g. by supplying a minimum weight and a maximum length. The default values are the minimum and maximum weights of the spectrum, i.e. the full range of the size spectrum is used.


\subsubsection{Examples of using the summary methods}
\label{sec:summaries_example}

Here we show a simple demonstration of using a summary method using the \code{sim} object we created earlier.
Here, we use \code{getSSB()} to calculate the SSB of each species through time (note the use of the \code{head()} function to only display the first few rows).

<<label = getSSB_demo>>=
ssb <- getSSB(sim)
dim(ssb)
head(ssb)
@

As mentioned above, we can specify the size range for the \code{getBiomass()} and \code{getN()} methods. For example, here we calculate the total biomass of each species but only include individuals that are larger than 10 g and smaller than 1000 g.

<<label = getBiomass_demo>>=
biomass <- getBiomass(sim, min_w = 10, max_w = 1000)
head(biomass)
@

\subsection{Methods for calculating indicators}

Methods are available to calculate a range of indicators from a \class{MizerSim} object after a projection.
These can be seen in Table~\ref{tab:indicator_methods}.
You can read the help pages for each of the methods for full instructions on how to use them, along with examples.

With all of the methods in the table it is possible to specify the size range of the community to be used in the calculation (e.g. to exclude very small or very large individuals) so that the calculated metrics can be compared to empirical data. This is used in the same way that we saw with the method \code{getBiomass()} in Section~\ref{sec:summaries}.
It is also possible to specify which species to include in the calculation.  See the help files for more details.

\begin{table}[ht]
    \begin{center}
	\begin{tabularx}{\linewidth}{r|X|X}
	\hline
	Method & Returns & Description \\
	\hline
	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 \args{measure} argument. If \args{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 \args{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 $R^2$ value. & 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. \\
	\hline
	\end{tabularx}
	\caption{Indicator methods for \class{MizerSim} objects.}
	\label{tab:indicator_methods}
    \end{center}
\end{table}

\subsubsection{Examples of calculating indicators}
\label{sec:indicators_example}

For these examples we use the \code{sim} object we created earlier.

The slope of the community can be calculated using the \code{getCommunitySlope()} method. Initially we include all species and all sizes in the calculation (only the first five rows are shown):

<<label=getCommunitySlope_demo>>=
slope <- getCommunitySlope(sim)
head(slope)
@

This gives the slope, intercept and $R^2$ value through time (see the help file for \code{getCommunitySlope} for more details).

We can include only the species we want with the \args{species} argument. Here we only include demersal species.  We also restrict the size range of the community that is used in the calculation to between 10 g and 5 kg.
The \args{species} is a character vector of the names of the species that we want to include in the calculation.

<<label = getCommunitySlope_with_args>>=
dem_species <- c("Dab","Whiting","Sole","Gurnard","Plaice","Haddock",
    "Cod","Saithe")
slope <- getCommunitySlope(sim, min_w = 10, max_w = 5000, 
    species = dem_species)
head(slope)
@

\subsection{Plotting the results}

\R is very powerful when it comes to exploring data through plots.  A useful package for plotting is \pkg{ggplot2}.  \pkg{ggplot2} uses data.frames for input data. Many of the summary methods and slots of the \pkg{mizer} classes are arrays or matrices. Fortunately it is straightforward to turn arrays and matrices into data.frames using the command \code{melt} which is in the \pkg{reshape2} package.
Although \pkg{mizer} does include some dedicated plots, it is definitely worth your time getting to grips with these \pkg{ggplot2} and other plotting packages. This will make it possible for you to make your own plots.

Included in \pkg{mizer} are several dedicated plots that use \class{MizerSim} objects as inputs (see Table~\ref{tab:plots}).
As well as displaying the plots, these methods all return objects of type \class{ggplot} from the \pkg{ggplot2} package meaning that they can be further modified by the user (e.g. by changing the plotting theme).
See the help page of the individual plot methods for more details.
The generic \code{plot()} method has also been overloaded for \class{MizerSim} objects. This produces several plots in the same window to provide a snapshot of the results of the simulation.

Some of the plots plot values by size (for example \code{plotFeedingLevel()} and \code{plotSpectra()}).
For these plots, the default is to use the data at the final time step of the projection.
With these plotting methods, it is also possible to specify a different time step or a time range to average the values over before plotting. 

\begin{table}[ht]
    \begin{center}
	\begin{tabularx}{\linewidth}{r|X}
	\hline
	Plot & Description \\
	\hline
	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 the method \code{getBiomass()}.\\
	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.\\
	plotM2() & 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.\\
	plot() & Produces 5 plots (\code{plotFeedingLevel()}, \code{plotBiomass()}, \code{plotM2()}, \code{plotFMort()} and \code{plotSpectra()}) in the same window as a summary.\\
	\hline
	\end{tabularx}
	\caption{Plot methods for \class{MizerSim} objects.}
	\label{tab:plots}
    \end{center}
\end{table}

\subsubsection{Plotting examples}
\label{sec:plot_examples}

Using the plotting methods is straightforward. For example, to plot the total biomass of each species against time you use the \code{plotBiomass()} method:

<<label=plotBiomass, eval=FALSE>>=
plotBiomass(sim)
@

\begin{figure}
<<label=print_plotBiomass, echo=FALSE, fig.height=4, fig.keep='last'>>=
<<plotBiomass>>
@
\caption{An example of using the \code{plotBiomass()} method.}
\label{fig:plotBiomass_example}
\end{figure}

As mentioned above, some of the plot methods plot values against size at a point in time (or averaged over a time period).
For these plots it is possible to specify the time step to plot, or the time period to average the values over. The default is to use the final time step.
Here we plot the abundance spectra (biomass), averaged over time = 5 to 10 (see Figure~\ref{fig:plotSpectra_example}):

<<label=plotSpectra_example,eval=FALSE>>=
plotSpectra(sim, time_range = 5:10, biomass=TRUE)
@

\begin{figure}
<<label=print_plotSpectra_example, echo=FALSE, fig.height=4, fig.keep='last'>>=
<<plotSpectra_example>>
@
\caption{An example of using the \code{plotSpectra()} method, plotting values averaged over the period $t$ = 5 to 10.}
\label{fig:plotSpectra_example}
\end{figure}

As mentioned above, and as we have seen several times in this vignette, the generic \code{plot()} method has also been overloaded.  This produces 5 plots in the same window (\code{plotFeedingLevel()}, \code{plotBiomass()}, \code{plotM2()}, \code{plotFMort()} and \code{plotSpectra()}, see Figure~\ref{fig:plot_example}). It is possible to pass in the same arguments that these individual plots use, e.g. arguments to change the time period over which the data is averaged.

<<label=demo_summary_plot,eval=FALSE>>=
plot(sim)
@

\begin{figure}
<<label=plot_example, echo=FALSE, fig.height=9>>=
<<demo_summary_plot>>
@
\caption{Example output from using the summary \code{plot()} method.}
\label{fig:plot_example}
\end{figure}

%------------------------------------------------------------------------------------
\section{A multispecies model of the North Sea}
\label{sec:north_sea_example}

In this section we try to pull everything together with an extended example of a multispecies model for the North Sea.
First we will set up the model, project it through time using historical levels of fishing effort, and then examine the results.
We then run two different future projection scenarios.
This example is based on the multispecies model in \citet{blanchard_multispecies_2014}.

\subsection{Setting up the North Sea model}

The first job is to set up the \class{MizerParams} object for the North Sea model.
In the previous multispecies examples we have already been using the life-history parameters and the interaction matrix for the North Sea model used in \citet{blanchard_multispecies_2014}.
We will use them again here but will make some changes. In particular we set up the fishing gears differently.

The parameters and the interaction matrix are stored as *.csv files that need to be read in. We can use the \code{system.file()} function to tell us the location of the files.
Remember that we need to convert the interaction file into a matrix, hence the use of the \code{as()} function.

<<label = show_load_ns_species_params, eval=FALSE>>=
params_location <- system.file("doc/NS_species_params.csv",package="mizer")
params_data <- read.csv(params_location)
inter_location <- system.file("doc/inter.csv",package="mizer")
inter <- as(read.csv(inter_location, row.names=1),"matrix")
@

<<label = load_ns_species_params, echo=FALSE>>=
params_data <- read.csv("NS_species_params.csv")
inter <- as(read.csv("inter.csv", row.names=1),"matrix")
@

The species in the model are \Sexpr{paste(params_data[,"species"], collapse=", ")} which account for about 90\% of the total biomass of all species sampled by research trawl surveys in the North Sea. 
The \args{params\_data} object is a data.frame with columns for \args{species}, \args{w\_inf}, \args{w\_mat}, \args{beta}, \args{sigma}, \args{r\_max} and \args{k\_vb}.
% These don't work for some reason - maybe the underscore?
%\Sexpr{cat(gsub("_","\\\\_",paste(colnames(params_data),collapse=", "), fixed=TRUE))}
%\Sexpr{paste(colnames(params_data), collapse=", ")}
We have seen before that only having these columns in the species data.frame is sufficient to make a \class{MizerParams} object. Any missing columns will be added by the default values and relationships in the \class{MizerParams} constructor.
For example, the data.frame does not include columns for \args{h} or \args{gamma}. This means that they will be estimated using the \args{k\_vb} column (see Section~\ref{sec:species_parameters_dataframe}).

We will use the default stock-recruitment relationship, which is the Beverton-Holt shape. As we saw in Section~\ref{sec:srr}, this requires a column \args{r\_max} in the species data.frame which contains the maximum recruitment flux for each species. This column is already in the \args{params\_data} data.frame. The values for \args{r\_max} are taken from \citet{blanchard_multispecies_2014}.
The values were found through a calibration process which is not covered here but will be added to a later version of this manual. 

At the moment, the species data.frame does not contain any information on the selectivity of the species.
By default, the selectivity function is a knife-edge which only takes a single argument, \args{knife\_edge\_size}.
In this model we want the selectivity pattern to be a sigmoid shape which more accurately reflects the selectivity pattern of trawlers in the North Sea.
The sigmoid selectivity function is expressed in terms of length rather than weight and uses the parameters \args{l25} and \args{l50}, which are the lengths at which 25\% and 50\% of the stock is selected. The length based sigmoid selectivity looks like:

\begin{equation}
    \label{eq:trawl_sel}
    S_l = \frac{1}{1 + \exp(S1 - S2\ l)}
\end{equation}

where $l$ is the length of an individual, $S_l$ is the selectivity at length, $S2 = \log(3) / (l50 - l25)$ and $S1$ = $l50 \cdot S2$.

This selectivity function is included in \pkg{mizer} as \code{sigmoid\_length()}. You can see the help page for more details.
As well as the arguments \args{l25} and \args{l50}, this function has the arguments \args{a} and \args{b} to convert between length and weight: $w = a l^b$.
This is because the sigmoid selectivity function is defined in terms of length, and the size spectrum model works in terms of weight.
As explained in Section~\ref{sec:fishing_gear}, all arguments of the selectivity function need to be in the species parameter data.frame.
Therefore, columns for \args{l25}, \args{l50}, \args{a} and \args{b} need to be added to \args{params\_data}.
We also add a column specifying the name of the selectivity function we wish to use.
The data is taken from \citet{blanchard_multispecies_2014}.
Note it would probably be easier to add this data directly to the *.csv file and then read it in rather than type it in by hand like we do here:

<<label=adding_sel_params>>=
params_data$sel_func <- "sigmoid_length"
params_data$l25 <- c(7.6, 9.8, 8.7, 10.1, 11.5, 19.8, 16.4, 19.8, 11.5,
    19.1, 13.2, 35.3)
params_data$l50 <- c(8.1, 11.8, 12.2, 20.8, 17.0, 29.0, 25.8, 29.0, 17.0,
    24.3, 22.9, 43.6)
params_data$a <- c(0.007, 0.001, 0.009, 0.002, 0.010, 0.006, 0.008, 0.004,
0.007, 0.005, 0.005, 0.007)
params_data$b <- c(3.014, 3.320, 2.941, 3.429, 2.986, 3.080, 3.019, 3.198,
    3.101, 3.160, 3.173, 3.075)
@

Note that we do not set up a \args{gear} column to give specific gear names. This means that each species will be caught by a separate gear named after the species.

In this model we are interested in projecting forward using historical fishing mortalities.
%GET UPDATED Fs from JB
%AND ALSO SOMETHING ABOUT GOING FROM FBAR TO FMAX OF SEL FUNCTION
%We are using the fishing mortality at full selectivity
The historical fishing mortality from 1967 to 2010 for each species is stored in the csv file \code{NS\_f\_history.csv} included in the package.
As before, we can use \code{read.csv()} to read in the data. This reads the data in as a \class{data.frame}.
We want this to be a \class{matrix} so we use the \code{as()} function:

<<label=show_load_f_history, eval = FALSE>>=
f_location <- system.file("doc/NS_f_history.csv",package="mizer")
f_history <- as(read.csv(f_location, row.names=1), "matrix")
@

<<label=load_f_history, echo = FALSE>>=
f_history <- as(read.csv("NS_f_history.csv", row.names=1), "matrix")
@

We can take a look at the first years of the data:
<<label=head_f_history>>=
head(f_history)
@

As mentioned in Section~\ref{sec:fishing_gear}, fishing mortality is calculated as the product of selectivity, catchability and fishing effort (see Equation~\ref{eq:sel}).
The values in \code{f\_history} are absolute levels of fishing mortality.
We have seen that the fishing mortality in the \pkg{mizer} simulations is driven by the fishing effort argument passed to the \code{project()} function.
Therefore if we want to project forward with historical fishing levels, we need to provide \code{project()} with effort values that will result in these historical fishing mortality levels.

One of the model parameters that we have not really considered so far is \args{catchability}. Catchability is a scalar parameter used to modify the fishing mortality at size given the selectivity at size and effort of the fishing gear.
By default catchability has a value of 1, meaning that an effort of 1 results in a fishing mortality of 1 for a fully selected species.
When considering the historical fishing mortality, one option is therefore to leave catchability at 1 for each species and then use the \args{f\_history} matrix as the fishing effort.
However, an alternative method is to use the effort relative to a chosen reference year. This can make the effort levels used in the model more meaningful.
Here we use the year 1990 as the reference year. If we set the catchability of each species to be the same as the fishing mortality in 1990 then an effort of 1 in 1990 will result in the fishing mortality being what it was in 1990. The effort in the other years will be relative to the effort in 1990.

The catchability can be set by including a \args{catchability} column in the species parameters data.frame. Doing this overwrites the default values when the \class{MizerParams} constructor is called.

<<label=set_catchability>>=
params_data$catchability <- as.numeric(f_history["1990",])
@

Considering the other model parameters, we will use default values for all of the other parameters apart from \args{kappa}, the carrying capacity of the resource spectrum (see Section~\ref{sec:parameters}).
This was estimated along with the values \args{r\_max} as part of the calibration process described in \citet{blanchard_multispecies_2014}.

We now have all the information we need to create the \code{MizerParams} object using the species parameters data.frame.

<<label=make_ns_params, results='hide'>>=
params <- MizerParams(params_data, inter, kappa = 9.27e10)
@

\subsection{Setting up and running the simulation}

As we set our catchability to be the level of fishing mortality in 1990, before we can run the projection we need to rescale the effort matrix to get a matrix of efforts relative to 1990. 
To do this we want to rescale the \code{f\_history} object to 1990 so that the relative fishing effort in 1990 = 1.
This is done using \R function \code{sweep()}.
We then check a few rows of the effort matrix to check this has happened:

<<label=rescale_effort>>=
relative_effort <- sweep(f_history,2,f_history["1990",],"/")
relative_effort[as.character(1988:1992),]
@

We could just project forward with these relative efforts. However, the population dynamics in the early years will be strongly determined by the initial population abundances (known as the transient behaviour - essentially the initial behaviour before the long term dynamics are reached).
As this is ecology, we don't know what the initial abundance are.
One way around this is to project forward at a constant fishing mortality equal to the mortality in the first historical year until equilibrium is reached.
We then can carry on projecting forward using the remaining years of effort.
This approach reduces the impact of transient dynamics.

% This is really unnecessarily complex. A single extra row with the year 1867 would be enough.
Here we make an initial effort matrix of 100 years at the first effort level. We need to include dimension names for the time dimension.
We then stick it on top of the original matrix of historical relative effort using \code{rbind()}.

<<label=add_transient_years>>=
initial_effort <- matrix(relative_effort[1,],byrow=TRUE, nrow=100,
    ncol=ncol(relative_effort), dimnames = list(1867:1966))
relative_effort <- rbind(initial_effort,relative_effort)
@

We now have our parameter object and out matrix of efforts relative to 1990.
This includes an initial 100 years of constant relative effort at the 1957 level, followed by the relative effort from 1957 to 2010.
We use this effort matrix as the \args{effort} argument to the \code{project()} method.
We use \code{dt} = 0.5 (the simulation will run faster than with the default value of 0.1, but tests show that the results are still stable) and save the results every year.

<<label=project_ns_model>>=
sim <- project(params, effort=relative_effort, dt = 0.5, t_save = 1)
@

Plotting the results, we can see how the biomasses of the stocks change over time (Figure~\ref{fig:plot_ns_biomass}).
You can see the 100 year period of transients with constant fishing fishing mortality before the historical relative mortality is used from 1967.

<<label = plot_ns_biomass, eval=FALSE>>=
plotBiomass(sim)
@

\begin{figure}
<<label=print_plot_ns_biomass, echo=FALSE, fig.height=4, fig.keep='last'>>=
<<plot_ns_biomass>>
@
\caption{Simulated biomasses of stocks in the North Sea with 100 years of transients.}
\label{fig:plot_ns_biomass}
\end{figure}

%More usefully, we can plot only the years for which we have fishing mortality data, i.e. without the transients:
%
%<<label = plot_ns_biomass_no_trans, eval=FALSE>>=
%plotBiomass(sim, start_time = 1967)
%@
%
%\begin{figure}
%<<label=print_plot_ns_biomass_no_trans, fig=TRUE, echo=FALSE, height = 4>>=
%<<plot_ns_biomass_no_trans>>
%@
%\caption{Simulated biomasses of stocks in the North Sea without the transients.}
%\label{fig:plot_ns_biomass_no_trans}
%\end{figure}

To explore the state of the community it is useful to calculate indicators of the unexploited community.
Therefore we also project forward for 100 years with 0 fishing effort.

<<label=unexploited_na>>=
sim0 <- project(params, effort=0, dt = 0.5, t_save = 1, t_max = 100)
@

\subsection{Exploring the model outputs}

Here we look at some of the ways the results of the simulation can be explored.
%We are going to compare the simulated SSB and yield for each species to the ``official'' values from ICES.
We calculate the community indicators ``mean maximum weight``, ``mean individual weight``, ``community slope`` and the ''large fish indicator'' (LFI) over the simulation period, and compare them to the unexploited values.
We also compare the simulated values of the LFI to a community target based on achieving a high proportion of the unexploited value of the LFI of $0.8 LFI_{F=0}$ \citep{rochet_does_2011}.

%Growth curves... (S2)

%NEED OFFICIAL DATA FROM ICES
%Compare outputs to ICES data.
%SSB time series (Figure 2 in NS paper) - compare to biodiversity targets 
%Yield time series (Figure 3) These plots go all the way to 2050 after scenarios

The indicators are calculated using the methods described in see Table~\ref{tab:indicator_methods} and Section~\ref{sec:summaries}.
Here we calculate the LFI and the other community indicators for the unexploited community. As in \citet{blanchard_multispecies_2014}, when calculating these indicators we only include demersal species and individuals in the size range 10 g to 100 kg, and the LFI is based on species larger than 40 cm.
Each of these methods returns a time series. We are interested only in the equilibrium unexploited values so we just select the final time step (year = \args{100}).

<<label=ns_comm_ref_point>>=
demersal_species <- c("Dab","Whiting","Sole","Gurnard","Plaice","Haddock",
    "Cod","Saithe")
lfi0 <- getProportionOfLargeFish(sim0, species = demersal_species,
    min_w = 10, max_w = 100e3, threshold_l = 40)["100"]
mw0 <- getMeanWeight(sim0, species = demersal_species,
    min_w = 10,max_w = 100e3)["100"]
mmw0 <- getMeanMaxWeight(sim0, species = demersal_species,
    min_w = 10, max_w = 100e3)["100","mmw_biomass"]
slope0 <- getCommunitySlope(sim0, species = demersal_species,
    min_w = 10, max_w = 100e3)["100","slope"]
@
% Higher than Blanchards (0.4)

We also calculate the time series of these indicators for the exploited community (we are only interested in the fishing history years, 1967 to 2010, ignoring the transients):
<<label=ns_comm_indicators>>=
years <- 1967:2010
lfi <- getProportionOfLargeFish(sim, species = demersal_species,
    min_w = 10, max_w = 100e3, threshold_l = 40)[as.character(years)]
mw <- getMeanWeight(sim, species = demersal_species,
    min_w = 10, max_w = 100e3)[as.character(years)]
mmw <- getMeanMaxWeight(sim, species = demersal_species,
    min_w = 10, max_w = 100e3)[as.character(years),"mmw_biomass"]
slope <- getCommunitySlope(sim, species = demersal_species,
    min_w = 10, max_w = 100e3)[as.character(years),"slope"]
@

We can plot the exploited and unexploited indicators, along LFI reference level.
Here we do it using \pkg{ggplot2} which uses data.frames
We make three data.frames (one for the time series, one for the unexploited levels and one for the reference level):
Each data.frame is a data.frame of each of the measures, stacked on top of each other.
<<label=plot_ns_indicators, eval = FALSE>>=
library(ggplot2)
# Simulated data
community_plot_data <- rbind(
    data.frame(year = years, measure = "LFI", data = lfi),
    data.frame(year = years, measure = "Mean Weight", data = mw),
    data.frame(year = years, measure = "Mean Max Weight", data = mmw),
    data.frame(year = years, measure = "Slope", data = slope))
# Unexploited data
community_unfished_data <- rbind(
    data.frame(year = years, measure = "LFI", data = lfi0[[1]]),
    data.frame(year = years, measure = "Mean Weight", data = mw0[[1]]),
    data.frame(year = years, measure = "Mean Max Weight", data = mmw0[[1]]),
    data.frame(year = years, measure = "Slope", data = slope0[[1]]))
# Reference level
community_reference_level <-
    data.frame(year=years, measure = "LFI", data = lfi0[[1]] * 0.8)
# Build up the plot
p <- ggplot(community_plot_data) + geom_line(aes(x=year, y = data)) +
    facet_wrap(~measure, scales="free")
p <- p + geom_line(aes(x=year,y=data), linetype="dashed",
    data = community_unfished_data)
p + geom_line(aes(x=year,y=data), linetype="dotted",
    data = community_reference_level)
@

\begin{figure}
<<label=print_plot_ns_indicators, echo=FALSE, fig.height=6>>=
<<plot_ns_indicators>>
@
\caption{Historical (solid) and unexploited (dashed) and reference (dotted) community indicators for the North Sea multispecies model.}
\label{fig:plot_ns_comm_indicators}
\end{figure}

According to our simulations, historically the LFI in the North Sea has been below the reference level.
% Duh!

\subsection{Future projections}

As well as investigating the historical simulations, we can run projections into the future.
Here we run two projections to 2050 with different fishing scenarios.
\begin{enumerate}
    \item Continue fishing at 2010 levels (the status quo scenario).
    \item From 2010 to 2015 linearly change the fishing mortality to approach $F_{MSY}$ and then continue at $F_{MSY}$ until 2050.
\end{enumerate}

Rather than looking at community indicators here, we will calculate the SSB of each species in the model and compare the projected levels to a biodiversity target based on the reference point $0.1 SSB_{F=0}$ \citep{rochet_does_2011}.
The $F_{MSY}$ values are also taken from \citet{rochet_does_2011}.

Before we can run the simulations, we need to set up arrays of future effort.
We will continue to use effort relative to the level in 1990.
Here we build on our existing array of relative effort to make an array for the first scenario. Note the use of the \code{t()} command to transpose the array. This is needed because \R recycles by rows, so we need to build the array with the dimensions rotated to start with.
We make an array of the future effort, and then bind it underneath the \args{relative\_effort} array used in the previous section.

<<label = ns_scenario1_relative_effort>>=
scenario1 <- t(array(relative_effort["2010",], dim=c(12,40),
    dimnames=list(NULL,year = 2011:2050)))
scenario1 <- rbind(relative_effort, scenario1)
@

The relative effort array for the second scenario is more complicated to make and requires a little bit of \R gymnastics
(it might be easier for you to prepare this in a spreadsheet and read it in).
For this one we need values of $F_{MSY}$.  
<<label = ns_scenario2_relative_effort>>=
fmsy <- c(Sprat = 0.2, Sandeel = 0.2, N.pout = 0.2, Herring = 0.25, Dab = 0.2,
    Whiting = 0.2, Sole = 0.22, Gurnard = 0.2, Plaice = 0.25, Haddock = 0.3,
    Cod = 0.19, Saithe = 0.3)
scenario2 <- t(array(fmsy, dim=c(12,40), dimnames=list(NULL,year = 2011:2050)))
scenario2 <- rbind(relative_effort, scenario2)
for (sp in dimnames(scenario2)[[2]]){
    scenario2[as.character(2011:2015),sp] <- scenario2["2010",sp] +
        (((scenario2["2015",sp] - scenario2["2010",sp]) / 5) * 1:5)
}
@

Both of our new effort scenarios still include 100 years at the 1967 level to reduce the impact of the transient behaviour.
We are now ready to project the two scenarios.
<<label = project_ns_future_scenarios>>=
sim1 <- project(params, effort = scenario1, dt = 0.5, t_save = 1)
sim2 <- project(params, effort = scenario2, dt = 0.5, t_save = 1)
@

We can now compare the projected SSB values in both scenarios to the biodiversity reference points.
First we calculate the biodiversity reference points (from the final time step in the unexploited \args{sim0} simulation):
<<label=ns_biodiv_ref_point>>=
ssb0 <- getSSB(sim0)["100",]
@
% Do these match Table S5 in supplementary material?
% 71, 3015, 327, 692, 6, 100, 42, 19, 365, 68, 1287, 338 in 000 tonnes
% unexploited_ssb / 1e9
% Nope...

Now we build a data.frame of the projected SSB for each species, ignoring the transients.
We make use of the \code{melt()} function in the very useful \pkg{reshape2} package (REF).
<<label=projected_ssb_ns, eval=FALSE>>=
library(reshape2)
years <- 1967:2050
ssb1 <- getSSB(sim1)[as.character(years),]
ssb2 <- getSSB(sim2)[as.character(years),]
ssb1_df <- melt(ssb1)
ssb2_df <- melt(ssb2)
ssb_df <- rbind(
    cbind(ssb1_df, scenario = "Scenario 1"),
    cbind(ssb2_df, scenario = "Scenario 2"))
ssb_unexploited_df <- cbind(expand.grid(
    sp = names(ssb0),
    time = 1967:2050),
    value = as.numeric(ssb0),
    scenario = "Unexploited")
ssb_reference_df <- cbind(expand.grid(
    sp = names(ssb0),
    time = 1967:2050),
    value = as.numeric(ssb0*0.1),
    scenario = "Reference")
ssb_all_df <- rbind(
    ssb_df,
    ssb_unexploited_df,
    ssb_reference_df)
p <- ggplot(ssb_all_df) +
    geom_line(aes(x = time, y = value, colour = scenario)) +
    facet_wrap(~sp, scales = "free", nrow = 4)
p + theme(legend.position = "none")
@

\begin{figure}
<<label=print_projected_ssb_ns, echo=FALSE, fig.height=9>>=
<<projected_ssb_ns>>
@
\caption{Historical and projected SSB under two fishing scenarios. Status quo (red), Fmsy (yellow). Unexploited (blue) and reference levels (purple) are also shown. }
\label{fig:plot_projected_ssb_ns}
\end{figure}

% Yields and trade-offs


%We could also look at the community indicators using the same procedure as in the previous section.





%\section{Under the hood of \pkg{mizer}: notes for developers}
%
%Still to come.
%
%Classes and whatnot

%---------------------------------------------------

\section{Scale-invariant, trait-based model}
\label{sec:scale_invariant_trait_based_model}

\subsection{Introduction}

Constructing models that allow fish species to coexist is not trivial. This
applies as much to size-spectrum models that use the mizer software tool, as 
it does to other kinds of multispecies models.  Current size-spectrum models 
achieve coexistence by assuming that stock-recruitment relationships are strong 
enough within species to promote coexistance of the species.  They do this 
by making the controlling parameter $R_{max.i}$ in Equation~\ref{eq:R} sufficiently 
small. Although coexistence can be achieved in this way, it can necessitate 
rather small values of $R_{max.i}$, with major effects on persistence and 
stability of species.

<<plot_scale_sense2, eval=FALSE, echo=FALSE, warning=FALSE, message=FALSE>>=
params_trait <- set_trait_model(no_sp = 10, min_w_inf = 10, max_w_inf = 1e3,
                          knife_edge_size = 100)
sim_trait_initial <- project(params_trait, t_max=100, effort = 0)
sim_trait <- project(params_trait,
                     initial_n = sim_trait_initial@n[dim(
                         sim_trait_initial@n)[1],,],
                     initial_n_pp = sim_trait_initial@
                         n_pp[dim(sim_trait_initial@n_pp)[1],], t_max=15,
                     effort = 1)
params <- set_scaling_model(no_sp = 10, min_w_inf = 10, max_w_inf = 1e3,
                            min_egg = 1e-4, min_w_mat = 10^(0.4), rfac = Inf,
                            knife_edge_size = 100,kappa = 0.005)
sim <- project(params, t_max=15, effort = 1)
b_trait <- getBiomassFrame(sim_trait)
b <- getBiomassFrame(sim)
display_frames(b_trait, b, params)
@



\begin{figure}
<<label=print_plot_scale_sense, echo=FALSE, warning=FALSE, message=FALSE, fig.height=4, fig.keep='last'>>=
<<plot_scale_sense2>>
@
\caption{Biomass plots following introduction of fishing (1) in the trait-based 
model from Section~\ref{sec:trait_based_model}, and (2) in the scale-invariant 
model developed here.  There are ten species; $W$ is taken over a range 10 g
%to 100 kg, 
to 1000 g,
uniformly spaced on the log-scaled mass axis. The 
initial state is close to the steady state in the absence of fishing.  
Recruitment to the multispecies fishery is knife-edge at
%1 kg
100 g
%for all 
%fish with $W > 1$ kg,
and fishing mortality rate is set 
at 
%$F = 0.75$ yr$^{-1}$.}
$F = 1$ yr$^{-1}$.}
\label{fig:plot_biomass_tb_vs_si}
\end{figure}

This and the next Section~\ref{sec:explicit} provide an alternative way of 
generating sets of coexisting species, without the need for such strong 
stock-recruitment relationships. This makes stocks more sensitive to changes 
in the environment, such as those caused by fishing. To motivate the new approach, 
Figure~\ref{fig:plot_biomass_tb_vs_si} compares it with the trait-based model 
in Section~\ref{sec:trait_based_model} in the presence of a substantial
amount of fishing.  In the case of the trait-based model, all species
persist under fishing (Figure~\ref{fig:plot_biomass_tb_vs_si}.1).
In this instance, the species with largest maximum weight enters the 
fishery at about 
%1/25
half
% knife_edge = 100, max(w_mat) = 239
of its weight at maturation, and persists because
its stock-recruitment relationship is sufficiently strong to boost its 
rate of increase when rare. You can construct 
Figure~\ref{fig:plot_biomass_tb_vs_si}.1, using the following code:

<<label=demo_trait_model_insensitive, eval=FALSE, warning=FALSE, message=FALSE>>=
params_trait <- set_trait_model(no_sp = 10, min_w_inf = 10, max_w_inf = 1e3,
                          knife_edge_size = 100)
sim_trait_initial <- project(params_trait, t_max=100, effort = 0)
sim_trait <- project(params_trait,
                     initial_n = sim_trait_initial@n[dim(
                         sim_trait_initial@n)[1],,],
                     initial_n_pp = sim_trait_initial@
                         n_pp[dim(sim_trait_initial@n_pp)[1],], t_max=15,
                     effort = 1)
plotBiomass(sim_trait)
@


The approach developed below allows the stock-recruitment relationship
to be weakened or completely removed, with the result that species are 
more sensitive to fishing (Figure~\ref{fig:plot_biomass_tb_vs_si}.2).  
In the example shown, fishing drives the largest and most vulnerable species 
to extinction (there is no stock-recruitment relationship in this instance).  
Some density-dependent feedbacks still remain, but they emerge from the 
internal dynamics \cite{rossberg_2013}.
You can construct Figure~\ref{fig:plot_biomass_tb_vs_si}.2, using the 
following code:

<<label=demo_scale_model_sensitive, eval=FALSE, warning=FALSE, message=FALSE>>=
params <- set_scaling_model(no_sp = 10, min_w_inf = 10, max_w_inf = 1e3,
                            min_egg = 1e-4, min_w_mat = 10^(0.4), rfac = Inf,
                            knife_edge_size = 100,kappa = 0.005)
sim <- project(params, t_max=15, effort = 1)
plotBiomass(sim)
@



The key for constructing these models is a special power-law relationship 
between body weight and density, which marine ecosystems are often observed 
to be near, after aggregating over species \cite{sheldon_1972}.  The significance 
of the power law is that, in its neighbourhood, coexistence of species 
becomes easier to achieve.  In fact, on the exact power-law, it has been 
proved that an infinite number of species coexist in a unicellular plankton 
model \cite{cuesta_2018}.  Related numerical simulations using  finite
number of species support the proposition that coexistence of multiple 
species is easier to achieve near the power law \cite{law_2016}.  
These properties readily extend to multicellular fish assemblages 
(Southwell, Delius unpublished results).

We build the alternative approach here in two steps.  First, this section 
describes a background spectrum designed to bring the trait-based model 
(see Section~\ref{sec:trait_based_model}) close to a scale-invariant form 
(see Section~\ref{sec:appendix}), for which the steady-state is known
analytically (Equation~\ref{eq:steady}).  For want of a better 
term, we call this model the \emph{scale-invariant}, trait-based model, 
with the caveat that the model is close to, but not exactly, scale invariant.  

Second, in the following 
Section~\ref{sec:explicit}, these background species are replaced 
by foreground species with specified properties in a fish assemblage.  


\subsection{Scale invariance}

Dynamical systems with scale-invariant properties are not standard 
currency in ecology, and this subsection can be skipped.  However the approach 
is underpinned by scale invariance with respect to body weight, so we 
briefly introduce some key concepts here.  There is little more in this
than allometric scalings of ecological rates with respect to body weight, 
for the most part familiar and widely documented in ecology. 

{\bf What is scale invariance?}  
Consider a species with some characteristic weight (maximum weight $W$
will do for the purpose), and with a density 
function $N(w,t)$ that has dynamics given by the size-spectrum model 
(Equation~\ref{eq:MvF}).  Consider a second species with maximum 
weight $cW,$ where $c$ is a positive rescaling factor. Then Equation~\ref{eq:MvF} 
would be scale-invariant, if the latter species had dynamics the same as the 
first when rescaled as $c^{\lambda + 1} N(c w, c^{1-n} t),$ for any $c>0$. 
Here $\lambda$ is the exponent of the resource spectrum, and $n$ is the 
exponent for maximum food intake. 

This rather delphic statement basically says that, under scale invariance, 
knowing the dynamics of one species is enough to know the dynamics of 
every species.  Strictly speaking, it could only apply to Equation~\ref{eq:MvF} 
if there was a continuum of maximum weights, with a species at
every $W > 0$.  Clearly, this cannot be the case in a multispecies spectrum with 
a finite set of species, because the $W$s are typically separated by finite 
intervals, and the spectrum has fixed lower and upper boundaries, outside which 
there are no species.  Therefore, a scale-invariant system is, at best, an 
idealisation of a size-spectrum model with a finite number of species.


%These boundaries are dealt with by special assumptions described below, 
%to retain the property of 'close-to-scale-invariance'.

%We avoid the problem of having to model arbitrarily small species by replacing them with the background resource, so the 
%smallest species we explicitly model still have something to eat. We avoid the 
%problem of having to model arbitrarily large species by choosing the background 
%mortality term $\mu_b (w)$ to emulate the effect of predators larger than the 
%explicitly modelled species.
  
{\bf Why bother with scale invariance?} 
There is an ecological reason and a mathematical one.  The ecological reason 
is that, in marine ecosystems, abundance (aggregated over species) as a 
function of body mass, is often observed to be quite close to a power law 
\cite{sheldon_1972}.  The existence of this remarkable regularity, plus the 
fact that it promotes coexistence of species, supports the development 
of scale-invariant models.

The mathematical reason is that scale-invariant systems possess symmetries 
which make them easier to understand.  For instance, the assumption of scale 
invariance in the system with a continuum of maximum weights allows an exact 
analytic expression for a steady state of the system to be derived. Although 
scale invariance cannot be met exactly in the system with a finite number of 
species, it can still guide the choice of parameter values that are likely 
to permit coexistence of species. 

Note that we are not suggesting that real assemblages of fish species are 
at rest on an exact power-law.  Rather we use scale invariance to 
construct \emph{background} assemblages that facilitate coexistence of 
observed fish species (\emph{foreground} species), without calling for 
strong stock-recruitment relationships. 


\subsection{Implementing the scale-invariant model}

Here we describe how to run the scale-invariant model, and make some 
comparisons with the trait-based model in Section~\ref{sec:trait_based_model}. 
%Details about our scale-invariant model and its motivations are given in
%Section~\ref{sec:appendix}.

To help set up a scale invariant trait-based model, there is a wrapper function, \code{set\_scaling\_model()}. 
Like the \code{set\_community\_model()} 
and 
\code{set\_tait\_model()} 
functions described above, this function can take many arguments. Most of 
them have default values so you don't need to worry about them for the moment. Now let us give an example of how to setup the scale-invariant trait-based model:

<<label=demo_scaling_model_params>>=
params <- set_scaling_model(no_sp = 10, min_w_inf = 10, max_w_inf = 1e3,
                            min_egg = 1e-4, min_w_mat = 10^(0.4), 
                            knife_edge_size = 100, kappa = 0.005)
@


The main parameters of interest are the number of the species in the model 
(\args{no\_sp}), 
the minimum egg size %(\args{min\_egg}), 
the minimum maturity size of a species %(\args{min\_w\_mat}) 
and the minimum and maximum asymptotic sizes %(\args{min\_w\_inf}) 
and 
(\args{max\_w\_inf}) 
respectively. The egg, maturity and asymptotic sizes are spread evenly on a logarithmic scale. The Beverton-Holt stock recruitment relationship is turned off by default.  

Once a 
\class{MizerParams} 
object has been created for the scale-invariant model, it can be run in the 
usual way:

<<label = scale_run>>=
sim <- project(params, t_max=5, effort = 0)
@

We make a plot of the biomass over time (Figure~\ref{fig:plot_scale_demo}) as follows:

<<plot_scale_sim, eval=FALSE>>=
plotBiomass(sim)
@

\begin{figure}
<<label=print_plot_scale_sim, echo=FALSE, fig.height=4, fig.keep='last'>>=
<<plot_scale_sim>>
@
\caption{A plot of time vs biomass for the scale invariant trait-based model with no fishing.}
\label{fig:plot_scale_demo}
\end{figure}

One can see from Figure~\ref{fig:plot_scale_demo} that the system is 
initiated very close to a steady state, and it is further attracted to 
the steady state without the need to impose any stock recruitment 
relationship (at least under default settings).

We can check that the steady state lies close to a power law by plotting the biomass 
densities of the different species, as well as their total, which evidently is close 
to the power law (Figure~\ref{fig:plot_scale_demoBS}).

<<plot_scale_simBS, eval=FALSE>>=
plotSpectra(sim, total = TRUE)
@

\begin{figure}
<<label=print_plot_scale_simBS, echo=FALSE, fig.height=4, fig.keep='last'>>=
<<plot_scale_simBS>>
@
\caption{A plot of weight vs biomass density for the steady state of the scale invariant trait-based model with no fishing.}
\label{fig:plot_scale_demoBS}
\end{figure}



%By comparing Figure~\ref{fig:plot_scale_demo} with 
%Figure~\ref{fig:plot_trait_demo}, one can see that the output of the 
%scale-invariant, trait-based model is somewhat similar to that of the 
%previous trait-based model. The key difference
%is that a strong stock-recruitment relationship is present in the original 
%trait-based model. This allows the number of fish to increase rapidly, 
%initially, until the population growth is eventually halted 
%by the stock-recruitment relationship. If one removed the stock recruitment 
%relationship, the populations in the original trait based model would 
%continue to grow rapidly, but they are being \emph{held back} by the stock 
%recruitment relationship. The result is that the stock in the original 
%trait based model is somewhat insensitive to changes in the environment, 
%because its steady state is the result of a strong force for population 
%growth being halted by a strong breaking force (the stock-recruitment 
%relationship) . 



\subsection{Details of changes to the trait-based model}
\label{subsec:bullets}

Here we document the changes made to the Mizer software tool described in 
Section~\ref{sec:principles}, in order to generate species assemblages close to 
scale invariance.  The new model is similar to the original trait-based model of 
Section~\ref{sec:trait_based_model}, but includes some modifications and restrictions to 
get assemblages that are close to scale invariance.  The changes are as follows.

%The scale invariant trait-based model corresponds to a special case 
%of the general size spectrum model described in Section~\ref{sec:principles}. 
%Essentially the scale invariant trait-based model is very similar to the 
%original trait-based model of Section~\ref{sec:explicit}, however there are 
%the following differences:

\begin{itemize}

 \item For the model to be scale invariant, the exponent of 
 metabolic intake $n$ needs to be equal to the exponent $p$ of metabolic loss.
 
 \item Scale invariance also requires that the exponent of the resource 
 spectrum $\lambda$ must satisfy the relation $\lambda = 2-n+q$, where 
 $n$ is the exponent of metabolic intake and $q$ is the exponent of the 
 volumetric search rate.  
 
 \item 
 (Equation~\ref{eq:1}) Feeding depends on prey body size, but not on 
 prey species identity, so $\theta_{ij}=1$ for all $i,j$. Note however 
 that the feeding preference function $\phi_i(w_p/w)$ already has scale 
 invariance built into it, because predation depends on the ratio of prey 
 to predator weight.  Thus no modification to growth and mortality 
 caused by predation is needed in moving to scale invariance.
 
 \item (Equation~\ref{eq:psi}) We assume that the proportion of energy allocated to 
 reproduction $\psi_i(w)$ is given by the step-like function
 \begin{equation}
 \psi_i(w)=\begin{cases}
 0 & \text{if \ensuremath{w<w_{*.i}}}\\
 \left(\frac{w}{W_i}\right)^{1-n} & \text{otherwise}
 \end{cases}
 \end{equation}
 This can be achieved by taking the form given by Equation~\ref{eq:psi}, 
 and letting $u \rightarrow \infty.$  This is not a requirement 
 for scale invariance;  the assumption was made for the mathematical 
 reason that it is then possible to get a closed-form expression for 
 the steady state.

 \item (Equation~\ref{eq:Rp})
 Scale invariance requires egg weight to 
 be a fixed fraction of maximum weight.  It is therefore indexed by 
 species $w_{0,i}$, rather than taking a single size $w_0$.
 Egg size does vary over about two orders of magnitude in teleosts,
 but there is evidence that at least the larger teleosts are unusual in 
 marine systems in lacking a scaling relationship between egg wight and 
 adult weight \cite{andersen_2016}.  Scale invariance of egg 
 weight should therefore be seen as a mathematical restriction required 
 to generate the scale-invariant background assemblage, in so far as the 
 background comprises teleost fish.  

 \item (Equation~\ref{eq:R})  A stock-recruitment relationship is not 
 required to create a steady state in the scale-invariant, trait-based model.  
 However, a stock-recruitment relationship can be included in the 
 scale-invariant trait-based model by setting the value of \args{r\_fac}. 
 Here \args{r\_fac} equals the maximum recruitment $R_{max.i}$ divided by the actual 
 recruitment $R_i$ at our steady state. By default the stock-recruitment 
 relationship is turned off, by setting 
 %\args{r\_fac} 
 to go to infinity. This has the effect of also making 
 $R_{max.i}\rightarrow \infty$, and so Equation~\ref{eq:R} is effectively 
 replaced with the simple relationship $R_i = R_{p.i}.$ 

 \item (Equation~\ref{eq:mu_b}) Beyond the upper limit of body weight. 
 The total mortality
 needs to scale with body weight. In practice, body weight always has an upper 
 limit in a real ecosystem, and predation mortality goes to zero as this limit 
 is approached.  Some compensation is needed for this in the background 
 mortality.  Thus, we replace the background mortality in 
 Equation~\ref{eq:mu_b} with a more intricate expression $\mu_b(w)$ given by 
 Equation~\ref{eq:newmub}. 
 Essentially this term represents the predation mortality which would be 
 induced by predators beyond the upper limit of body sizes explicitly modelled, 
 under the assumption that the abundance of such predators continue the scale 
 invariant pattern. 
 %We arrived at our expression for $\mu_b(w)$ by considering that in the inf use the expression $ \mu_{b.i}(w) = \max \{ \mu_0 w^{n-1} - \mu_{f.i}(w) - \mu_{p.i}(w),0 \}$ where 
 %\begin{equation}
 %\mu_0 = (1 - f_0)  \sqrt{2 \pi} \kappa  \gamma  \sigma \beta ^{n - 1} \exp\left(\frac{\sigma ^ 2  (n - 1) ^ 2} {2}\right),
 %\end{equation}
 %and $\mu_{f.i}(w)$ is the fishing mortality (as determined by the fishing gears), and %$\mu_{p.i} (w)$ is the predation mortality, given by (Equation~\ref{eq:mup}), where the abundance $N$ is the abundance at our steady state {\bf where shall we give N's formula ?}.  This is done to ensure that the total mortality rate on explicitly modeled species is $ \mu_0 w^{n-1},$ which scales with weight in the way required for scale invariance.
%We have to choose parameters so that $\mu _0$ is sufficiently large that $ \mu_{b.i}(w) = \mu_0 w^{n-1} - \mu_{f.i}(w) - \mu_{p.i}(w)\geq 0. $ 

\item (Equation~\ref{eq:nb}) The resource spectrum extends from the smallest weight at which an explicitly 
modeled fish may eat. We define the carrying capacity $c_p(w)$ of the 
background resource so when our system is at steady state, the 
combination of the background resource spectrum and the aggregate abundance of 
the explicitly modeled species is the power law $\kappa w^{-\lambda}.$ 
An expression for how we set $c_p(w)$ within the scale-invariant trait-based 
model is given by Equation~\ref{eq:cp}. 
%This is achieved choosing the carrying capacity of the background resource to be 
%\begin{equation} c_{p} (w)=
%   \begin{cases}
%      \min \left\{ \left(1+\frac{\mu_p(w)}{r_0 w^{p-1}} \right)\left( \kappa w^{-\lambda} - \sum_i N_i(w) \right),0\right\}, & \text{if}\ w<\min\{w_{*i}\} \\
%     0, & \text{otherwise}
%    \end{cases}
%\end{equation}
%Note that, much like in the background mortality term, we require that the aggregate abundance $\sum_i N_i(w)$ is less than or equal to the power law $\kappa w^{-\lambda} $ within the appropriate size range (i.e., for $w\leq\min\{w_{*i}\}$), 
%so that we do not have to use our $\min\{ *, 0\}$ operation to rewrite negative entries. We also arrange things so that as $w$ approaches $\min\{w_{*i}\}$ from below, the carrying capacity of the background resource declines to zero.  

\item By default the scale-invariant trait-based model is initialized at a 
 steady state (Equation~\ref{eq:steady}) (provided no fishing is being 
 performed), whereas the original trait based model is not initialized 
 near its steady state.

\end{itemize}





%---------------------------------------------------

%---------------------------------------------------


\section{Implementing explicit species in a scale-invariant background}
\label{sec:explicit}


\subsection{Introduction}

In Section~\ref{sec:scale_invariant_trait_based_model} we saw that using strong stock recruitment relationships, as implemented within the models discussed in sections \ref{sec:trait_based_model} and \ref{sec:north_sea_example} can lead to scenarios where the stock levels are unrealistically insensitive to changes in the environment. In order to fix this issue we want to create a model where species of interest can co-exist and interact without imposing a strong stock recruitment relationship. The key to our approach is to use species from the scale-invariant trait based model as a type of background or substrate, into which the heterogeneous species of specific interest (the \emph{foreground species}) can added. 

We begin with only the scale-invariant background, which is setup close to a steady state by the \code{set\_scaling\_model()} command. We add new species using the \code{addSpecies()} command, in such a way that the resulting system remains close to a steady state. To achieve this we lower the abundances of the background species in our candidate steady state to compensate for the addition of the new foreground species, so that the background species still have the same food levels, and growth rates, as they did in the original system. We also choose the abundance curve for the newly added species so that it will be time-invariant under Equation~\ref{eq:MvF}. Additional steps are taken to fine tune the resulting state to make sure that the background species are close to time-invariant under Equation~\ref{eq:MvF}, and that the quantity of fish growing up from the egg size is balanced by the rate of egg production.

%We get relatively close to a steady state by altering the abundance of the background species when a foreground species This is basically achieved by ensure that the background species experience the same growth rates and death rates as they did in the previous scale-invariant system. One can make an analogy here with other transplants of biological organs/organisms, where post transplant survival is based on the transplanted entity and its surrounds receiving similar stimuli before and after the transplant. We ensure that the background species encounter the same growth rates after the transplant as they did before by depressing the abundance of the background species to \emph{make room} for the newly added species, so that the aggregate abundance of all the species remains at the power law. We do not however ensure that the death rates of background individuals will be the same as those in the original system. However, if the newly added species is put in at low abundance, it will cause little change to the death rates of the pre-existing background species, and hence the abundances of the background species will remain stationary as they were before. The abundance curves of the newly added species are calculated under the assumption that their growth and death rates are the ones they would experience in the scale invariant system (as if they were at such a low abundance that self-interaction can be neglected). The more abundant the foreground species is, relative to the background, the worse our approximation to a steady state will be. However in practice, our initial condition often tends to be close enough to a true steady state that it will be attracted to it under the system dynamics.

\subsection{Adding a foreground species to a scale-invariant background}


Initially, when we start with the scale-invariant trait-based model, these species are organized, so that their aggregate abundance follows a power-law. This can be done using the \code{set\_scaling\_model()} command (discussed in Section \ref{sec:scale_invariant_trait_based_model}) as follows:

<<label=seed_scaling_model_params>>=
params_bg  <- setBackground(
  set_scaling_model(no_sp = 10, no_w = 400,
                    min_w_inf = 10, max_w_inf = 1e5,
                    min_egg = 1e-4, min_w_mat = 10^(0.4),
                    knife_edge_size = Inf, kappa = 10000,
                    lambda = 2.08, f0 = 0.6, h = 34)
)
@


Let us introduce a species which we are interested in modelling explicitly into this background using our \code{addSpecies()} command. For the sake of example we shall introduce a red mullet, we start by specifying its parameters using a dataframe with a single row:

<<label=mullet_data>>=
species_params <- data.frame(
  species = "Mullet",
  w_min = 0.001, 
  w_inf = 173.2425, 
  w_mat = 15.14863, 
  beta = 283, 
  sigma = 1.8, 
  z0 = 0,
  alpha = 0.6, 
  erepro = 0.1, 
  sel_func = "sigmoid_length", 
  gear = "sigmoid_gear",
  l25 = 13.17291,
  l50 = 15.48,
  k = 0,
  k_vb = 0.6,
  a = 0.0085,
  b = 3.11,
  gamma = 0.0017,
  h = 50,
  linecolour = "red",
  linetype = "solid"
)
@

Foreground species of specific interest can be introduced into our background using the following command:

<<label=mullet_add>>=
params_bg_m <- addSpecies(params_bg, species_params, SSB = 2800, effort=0.4, 
                rfac = 1.01)
@

This code creates a new \class{MizerParams} object containing the original background species and the new foreground species, mullet. The \code{addSpecies()} command attempts to construct a new approximate steady state (\args{params\_out@initial\_n})
including the new species. 

%This is done by decreasing the abundance of the pre-existing background species, so that when the new foreground species is added (at an abundance such that the total biomass of individuals above weight \args{min\_w\_observed} is \args{biomass}), the aggregate abundance of all species in the system will still given by the power-law $\kappa w^{-\lambda}.$ 

%The abundance curve of the newly added species would correspond to a steady state in the case where its abundance (as controlled by the value of \args{biomass}) is negligible compared to the abundance of the background species. As one increases the value of \args{biomass} this approximation becomes less acceptable, and the initial condition given by \args{params\_out@initial\_n}
%will be further from a steady state. Another problem with setting the value of \args{biomass} too high is that if the abundance of the newly added species exceeds that of the target power-law, it will obviously be impossible that including background species as well will yield the power-law. The code will return an error message about negative abundance multipliers in this case. One way to fix such problems (about the background community being insufficiently abundant to support the value of \args{biomass} of the species one wishes to add) is to increase the value of \args{kappa} in the \code{set\_scaling\_model()} command. 

The stock recruitment relationship can be controlled by setting the value of \args{r\_fac}, as described in Subsection \ref{subsec:bullets}.

We can perform a simulation with our new system, including the mullet, in the usual way: 

<<label = mullet_run>>=
sim <- project(params_bg_m, t_max = 25, effort = 0.4)
@

We can see from the resulting plot of time vs biomass that the system is initiated close to a steady state (Figure~\ref{fig:plot_mullet_demo}):

<<plot_mullet_sim, eval=FALSE>>=
plotBiomass(sim)
@

\begin{figure}
<<label=print_plot_mullet_sim, echo=FALSE, fig.height=4, fig.keep='last'>>=
<<plot_mullet_sim>>
@
\caption{Example plot of time vs biomass for the scale invariant trait-based model plus mullet.}
\label{fig:plot_mullet_demo}
\end{figure}

We can also visualize the relative abundances of the different species (Figure~\ref{fig:plot_mullet_demo2}) with the following command:

<<plot_mullet_sim2, eval=FALSE>>=
plotSpectra(sim)
@

\begin{figure}
<<label=print_plot_mullet_sim2, echo=FALSE, fig.height=4, fig.keep='last'>>=
<<plot_mullet_sim2>>
@
\caption{Example plot of weight vs abundance for the scale invariant trait-based model plus mullet, in the final state of our simulation.}
\label{fig:plot_mullet_demo2}
\end{figure}




%We can compare the growth curves of the mullet with the predictions from the von Bertalanffy model (Figure~\ref{fig:plot_mullet_growth}) using the following command:

%
%<<plot_mullet_growth, eval=FALSE>>=
%plotGrowthCurves(sim, species = "mullet", max_age = 15)
%@


%\begin{figure}
%<<label=print_plot_mullet_growth, echo=FALSE, fig.height=4, fig.keep='last'%>>=
%<<plot_mullet_growth>>
%@
%\caption{A plot showing the growth (time vs weight) of the mullet. The black curve shows the von Bertalanffy growth curve and the red curve shows the prediction of our model with mullet in a scale-invariant background}
%\label{fig:plot_mullet_growth}
%\end{figure}
 

\subsection{Adding another species}

In practical fisheries science one will have several species that one wishes to model explicitly. Further foreground species can be added into our system by repeated use of the \code{addSpecies()} command. Let us demonstrate this by adding hake into our system with background and mullet. We start by specifying the data for the hake:

%Again we see that the system is at a stable steady state without the need to impose stock recruitment relationships.

<<label=hake_data>>=
species_params <- data.frame(
  species = "Hake",
  w_min = 0.001, 
  w_inf = 4174.194, 
  w_mat = 183.5169, 
  beta = 11.02318, 
  sigma = 1.1, 
  z0 = 0,
  alpha = 0.6, 
  erepro = 0.1, 
  sel_func = "sigmoid_length", 
  gear = "sigmoid_gear",
  l25 = 16.09244,
  l50 = 16.6,
  k = 0,
  k_vb = 0.1, 
  a = 0.0046,
  b = 3.12,
  gamma = 0.003,
  h = 20,
  linecolour = "blue",
  linetype = "solid"
)
@

Now we add the hake into our system:

<<label=add_hake>>=
params_bg_m_h <- addSpecies(params_bg_m, species_params, SSB = 1200,
                            effort=0.4, rfac = 1.01)
@

We visualize the initial condition, close to steady state (Figure~\ref{fig:plot_mullet_hake_spectra}) using the following command:


<<plot_mullet_hake_spectra, eval=FALSE>>=
plotSpectra(params_bg_m_h)
@

\begin{figure}
<<label=print_plot_mullet_hake_spectra, echo=FALSE, fig.height=4, fig.keep='last'>>=
<<plot_mullet_hake_spectra>>
@
\caption{A plot of weight vs biomass density for the near steady state created by adding mullet and hake to a scale-invariant background.}
\label{fig:plot_mullet_hake_spectra}
\end{figure}

To see that this is close to a steady state we shall evolve the system and show how biomass changes over time (Figure~\ref{fig:plot_mullet_hake_biomass}):

<<plot_mullet_hake_biomass, eval=FALSE>>=
sim <- project(params_bg_m_h, t_max = 50, t_save = 5, effort = 0.4)
plotBiomass(sim)
@

\begin{figure}
<<label=print_plot_mullet_hake_biomass, echo=FALSE, fig.height=4, fig.keep='last'>>=
<<plot_mullet_hake_biomass>>
@
\caption{A plot of time vs biomass showing our system with background species, mullet and hake,  evolving to a nearby steady state.}
\label{fig:plot_mullet_hake_biomass}
\end{figure}

The \code{steady()} command can be used to fine tune the initial condition to be very close to a steady state:

<<mullet_hake_steady>>=
params_bg_m_h2 <- steady(params_bg_m_h, effort = 0.4)
@


This results in a a configuration very close to a steady state, as we can see by evolving the system and plotting how biomass changes over time (Figure~\ref{fig:plot_mullet_hake_biomass_steady}):

<<plot_mullet_hake_biomass_steady, eval=FALSE>>=
sim2 <- project(params_bg_m_h2, t_max = 50, t_save = 5, effort = 0.4)
plotBiomass(sim2)
@

\begin{figure}
<<label=print_plot_mullet_hake_biomass_steady, echo=FALSE, fig.height=4, fig.keep='last'>>=
<<plot_mullet_hake_biomass_steady>>
@
\caption{A plot of time vs biomass showing our system with background species, mullet and hake evolving from our fine tuned nearby steady state.}
\label{fig:plot_mullet_hake_biomass_steady}
\end{figure}


%\subsection{Adding fishing}

%In order to model the effect of fishing one could simply take the previous setup, and turn on fishing effort, but that would likely lead to the extinction of some species. The reason is that the system was setup to be at steady state for a system without any fishing, and without a strong stock recruitment relationship imposed the system reacts more sensitively to dramatic changes in the environment than the models in sections \ref{sec:trait_based_model} and \ref{sec:north_sea_example}. 

%In order to model the effects of fishing in our systems we organize include fishing effort within the \code{addSpecies()} command. This means that the fishing mortality is accounted for when the abundance curves of the newly added species are computed for the approximate steady state in the resulting \class{MizerParams} object. Including the effort during the system setup in this way emulates the way real marine systems reorganize themselves in such a way that they can sustain themselves under a moderate degree of fishing.

%\subsection{Comparing fishing gears}

%The scenario discussed just previously corresponds to a system in the Mediterranean sea where * fishing gear is used to catch mullet and hake. One focus of {\bf Assessment of the relative catch performance of hake, red mullet and striped
%red mullet in a modified trawl extension with T90 netting} was to determine the effect using a T90 extension to the fishing gear to alter its selectivity curve. We can see the effects of such a change as follows.  

%---------------------------------------------------
% 
% \section{Improvements to the previous version }
% \label{sec:news}
% 
% Version 0.2 of mizer was authored by Finlay Scott, Julia Blanchard and Ken Andersen. In January 2017 Gustav Delius and Richard Southwell took over the job of improving mizer and made the following additions:
% 
% \begin{itemize}
% 
% \item {\bf Applied spectral methods to speed up integration:} Each time step mizer has to compute integrals to determine the growth rates and death rates. These integrals are convolution integrals. The mizer code was modified so these integrals are performed using spectral methods (using the fast Fourier transform). This led to a dramatic speedup of mizer.
% 
% \item {\bf Used C++ code for faster numerical solving of the PDE:} Used C++ for the inner loop in the project method for extra speed.
% 
% \item {\bf Improved plotting:} Added new plotting methods, fixed bugs, and added a progress bar while the simulation is running.
% 
% \item {\bf Added the scale-invariant model:} Added a function that computes parameters and a steady state for scale free trait-based models.
% 
% \item {\bf Allowed explicit species to be added to the a scale-invariant background:} Added a function that adds news species to a scale-invariant background, and computes an approximately steady state close to the power law.
% 
% \item {\bf Created web interface:} Made an example shiny app that allow people to use mizer through a web browser to explore the effect of more selective fishing gear without having to install the software.
% 
% \item {\bf Created tutorial videos:} Made videos explaining how to install and use mizer.
% 
% 
% \end{itemize}
% 

%---------------------------------------------------%%

\section{Appendix}
\label{sec:appendix}
In this section we give some of the more technical details behind the scale-invariant model, and how it is implemented in mizer.


\subsection{A steady state solution}
Assuming scale invariance allows us to find the following exact analytic expression for a steady state. This corresponds to the following form for the abundance within the discrete approximation to the scale-invariant system implemented by mizer:
\begin{equation}
\label{eq:steady}
N_i (w,t) = H \left(\frac{w_{0,1}}{w_{0,i}}\right)^{\lambda} \left(\frac{w_{0,i}}{w}\right)^{\mu _0/\hbar} \hbar^{-1} w^{-n} M_i (w)
\end{equation}
where 
\begin{equation} M_i (w)=
   \begin{cases}
      1, & \text{if}\ w<w_{*i} \\
      \frac{1}{\left(1-\left(\frac{w}{W_{i}}\right)^{1-n}\right)}\left(\frac{1-\left(\frac{w}{W_{i}}\right)^{1-n}}{1-\left(\frac{w_{*i}}{W_{i}}\right)^{1-n}}\right)^{\frac{1}{1-n}\left(\frac{\mu_{0}}{\hbar}\right)}, & \text{otherwise}
    \end{cases}
\end{equation}
and 
\begin{equation}
\label{eq:mu0}
 \mu_0 = (1 - f_0)  \sqrt{2 \pi} \kappa  \gamma  \sigma \beta ^{n - 1} \exp\left(\frac{\sigma ^ 2  (n - 1) ^ 2} {2}\right). 
 \end{equation}
As the number of species becomes large we have that $\sum_i N_i (w)$ is approximately proportional to $\kappa w^{-\lambda},$  $\forall w \in [\min \{w_{*i} \} , \max \{w_{*i} \}].$ The constant $H$ is chosen so that $\sum_i N_i (w)$ is approximately equal to $\kappa w^{-\lambda}$ $\forall w \in [\min \{w_{*i} \} , \max \{w_{*i} \}].$
This steady state is special because it is invariant under the type of rescaling described above. 
We also have to choose parameters in such a way that Equation~\ref{eq:Rp} holds. However, if it holds for one species, then it holds for all species due to scale-invariance.
Although the original trait based model had a similar level of simplicity, and a partial description of something like a steady state was possible, a careful reading of  Section 3 of \cite{hartvig_food_2010} reveals that it was in fact impossible to setup such a system so that the average number of offspring produced over an individuals lifespan is one, for each species, without imposing a stock recruitment relationship. This is part of the reason why stock recruitment relationships were imposed on previous models. However we believe that the stock recruitment relationships should emerge out of the life histories which size spectrum models claim to be able to model, rather than being imposed for outside the model.


\subsection{Background mortality in the scale invariant model}

We arrived at our expression for $\mu_b(w)$ by considering that in the steady state of continuous scale-invariant trait based model, the total mortality rate of of individuals is given by the power-law $\mu_0 w^{n-1}$. In the finite system in mizer, individuals are only modelled up to a given size, and so we define $\mu_b(w)$ as the difference between the desired power-law mortality rate, and the predation rate exhibited by explicitly modeled species at our steady state:  

\begin{equation}
 \label{eq:newmub}
  \mu_{b.i}(w) = \max \{ \mu_0 w^{n-1} - \mu_{p.i}(w),0 \}
  \end{equation}
  where $\mu_0$ is given by Equation~\ref{eq:mu0}, and $\mu_{p.i} (w)$ is the predation mortality, given by Equation~\ref{eq:mup}, where the abundance $N$ is the abundance at our steady state, given by Equation~\ref{eq:steady}.  This is done so that (provided we choose parameters so $ \mu_{b.i}(w) = \mu_0 w^{n-1}  - \mu_{p.i}(w)\geq 0. $) 
) we ensure that the total mortality rate on explicitly modeled species is $ \mu_0 w^{n-1},$ which scales with weight in the way required for scale invariance.


\subsection{Background resources in the scale invariant model}

We define the carrying capacity $c_p(w)$ of the background resource so when our system is at steady state, the 
combination of the background resource spectrum and the aggregate abundance of the explicitly modeled species is the power law $\kappa w^{-\lambda}.$ 
This is achieved choosing the carrying capacity of the background resource to be 
\begin{equation} 
\label{eq:cp}
c_{p} (w)= \min \left\{ \left(1+\frac{\mu_p(w)}{r_0 w^{p-1}} \right)\left( \kappa w^{-\lambda} - \sum_i N_i(w) \right),0\right\}
\end{equation}
Note that, much like in the background mortality term, we require that the aggregate abundance $\sum_i N_i(w)$ is less than or equal to the power law $\kappa w^{-\lambda} $ within the appropriate size range (i.e., for $w\leq\min\{w_{*i}\}$), 
so that we do not have to use our $\min\{ *, 0\}$ operation to rewrite negative entries. 
%We also arrange things so that as $w$ approaches $\min\{w_{*i}\}$ from below, the carrying capacity of the background resource declines to zero.


%---------------------------------------------------

\section{Acknowledgements}

Finlay Scott would like to thank the Cefas Seedcorn Project DP266 and the Defra project MF1225 for supporting this work.
This project has received funding from the European Union's Horizon 2020 Research and Innovation programme under Grant Agreement No 634495 (MINOUW).

The work of Gustav Delius, Richard Southwell and Richard Law on updating mizer was funded by the European Commission Horizon 2020
Research and Innovation Programme under Grant Agreement No. 634495
for the project MINOUW (\url{http://minouw-project.eu/}).

%-------------------------------------------------------------------------
% References
%------------------------------------------------------------------------

\bibliography{reflib}{}
%\bibliographystyle{plain}
\bibliographystyle{plainnat}

\end{document}

