% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/CM.R
\name{fit_CM}
\alias{fit_CM}
\alias{sample_CM}
\title{Fit conditioning model to historical data}
\usage{
fit_CM(
  data,
  start = list(),
  map = list(),
  lower = list(),
  upper = list(),
  do_fit = TRUE,
  silent = TRUE,
  control = list(eval.max = 1e+05, iter.max = 1e+05),
  ...
)

sample_CM(fit, ...)
}
\arguments{
\item{data}{A list containing data inputs. See details.}

\item{start}{An optional list containing parameter starting values. See details.}

\item{map}{An optional list that describes how parameters are fixed in the model. See \code{\link[TMB:MakeADFun]{TMB::MakeADFun()}}.}

\item{lower}{Named list containing lower bounds for parameters. See details.}

\item{upper}{Named list containing upper bounds for parameters. See details.}

\item{do_fit}{Logical, whether to do the fit and estimate the Hessian.}

\item{silent}{Logical, whether to silence output from RTMB to the console.}

\item{control}{List, \code{control} argument to pass to \code{\link[stats:nlminb]{stats::nlminb()}}.}

\item{...}{For \code{fit_CM}, arguments to \code{\link[RTMB:TMB-interface]{RTMB::MakeADFun()}}. For \code{sample_CM}, arguments to \code{rstan::sampling()}}

\item{fit}{List of output from \code{fit_CM()}}
}
\value{
\itemize{
\item \code{fit_CM()} returns a named list containing the RTMB model (\code{obj}), nlminb output (\code{opt}), standard errors (\code{SD}),
and parameter bounds (\code{lower} and \code{upper})
\item \code{sample_CM()} returns a \code{stanfit} object containing the MCMC chains
}
}
\description{
{
Bayesian stock reconstruction model of natural and hatchery origin fish population.
Maturity and age-1 natural mortality are estimated from coded wire tag catch and escapement at age.
A separate series of observed escapement, and hatchery releases reconstructs the population of interest,
informed by natural mortality and maturity from CWT (\href{https://publications.gc.ca/site/eng/9.940685/publication.html}{Korman and Walters 2024}).
The model estimates time-varying maturity rate as well as time-varying ocean survival as a linear model of covariates (separate covariates
for age 1 vs. ages 2+).
The model can include either a preterminal juvenile fishery, terminal return fishery, or both (see Data and start sections of the documentation).

\code{fit_CM()} generates the RTMB model from data which can then be passed to \code{sample_CM()} to run the MCMC in Stan. Generate a markdown report with \code{\link[=report_CM]{report_CM()}}.

More information is available on the \href{https://docs.salmonmse.com/articles/conditioning.html}{salmonMSE} website
}
}
\section{Data}{

Data should passed through a named list with the following entries.
\itemize{
\item \code{Nages} Integer, number of age classes in the model
\item \code{Ldyr} Integer, number of years in the model
\item \code{lht} Integer, life history type. Should be 1 for now
\item \code{n_r} Integer, number of release strategies for CWT, subset of a hatchery-origin brood year that differ in maturity rate. Default is 1.
\item \code{cwtrelease} Matrix \verb{[Ldyr, n_r]}, coded wire tag (CWT) releases by \strong{release year and release strategy}
\item \code{cwtesc} Array \verb{[Ldyr, Nages, n_r]}. CWT escapement \strong{by release year, age, and release strategy} (assumes broodyear is release year minus 1). Poisson likelihood.
\item \code{cwtcatPT} Array \verb{[Ldyr, Nages, n_r]}. CWT preterminal catch (juvenile fish), \strong{by release year, age, and release strategy}. Poisson likelihood. Set all values to zero to turn off
parameters related to the preterminal fishery.
\item \code{cwtcatT} Array \verb{[Ldyr, Nages, n_r]}. CWT terminal catch (returning, mature fish), \strong{by release year, age, and release strategy}. Poisson likelihood. Set all values to zero to turn off
parameters related to the terminal fishery.
\item \code{bvulPT} Vector length \code{Nages}. Prior mean for the vulnerability at age to the preterminal fishery.
\item \code{bvulT} Vector length \code{Nages}. Prior mean for the vulnerability at age to the terminal fishery.
\item \code{RelRegFPT} Vector \code{Ldyr}. Trend in relative regional preterminal fishing mortality. Fishing mortality is estimated by estimating a scaling
coefficient and annual deviations from this vector. Default is \code{rep(1, d$Ldyr)} (no prior trend) if \code{cwtcatPT} is provided, otherwise zero.
\item \code{RelRegFT} Vector \code{Ldyr}. Trend in relative regional terminal fishing mortality.
Default is \code{rep(1, d$Ldyr)} (no prior trend) if \code{cwtcatT} is provided, otherwise zero.
\item \code{bmatt} Vector length \code{Nages}. Proportion maturity at age, base values for calculating the unfished replacement line. Also the prior means if year-specific
maturity rates are estimated.
\item \code{mobase}. Vector length \code{Nages}. Natural mortality at age, base values for calculating the unfished replacement line and the
the equilibrium spawners at age.
\item \code{covariate1} \emph{Optional}. Matrix \verb{Ldyr, ncov1} of linear covariates that predict natural mortality for age 1.
\item \code{covariate} \emph{Optional}. Matrix \verb{Ldyr, ncov} of linear covariates that predict natural mortality for ages 2+.
\item \code{hatchsurv} Numeric, survival of hatchery releases into the smolt life stage. Density-independent. Default is 1. If less than 1, then hatchery origin fish have
lower survival to age 2 (after first year of marine life stage) compared to natural origin fish.
\item \code{gamma} \emph{Optional}. Numeric, the relative spawning success of hatchery origin spawners. Default is 1.
\item \code{ssum} Numeric, proportion of spawners that is female. Can also be a vector \code{Nages}
\item \code{fec} Vector length \code{Nages}. Fecundity, egg production at age
\item \code{r_matt} Integer, the release strategy for which to use maturity parameter for the natural system. Default is 1.
\item \code{obsescape} Vector length \code{Ldyr} by \strong{return year}, total observed escapement from fisheries, i.e., return to river (all ages and both hatchery/natural fish). Lognormal likelhood.
\item \code{propwildspawn} Vector length \code{Ldyr} by \strong{return year}, proportion of the escapement that spawn (accounts for en-route mortality and broodtake)
\item \code{hatchrelease} Vector length \code{Ldyr+1} by \strong{release year}, number of hatchery releases for the population. Default is zero.
\item \code{obs_pHOS} \emph{Optional}. Vector length \code{Ldyr} by \strong{return year}, observations of proportion of hatchery origin spawners (census) (between 0-1) \emph{by brood year}. Fitted to model with logistic-normal likelihood.
\item \code{pHOS_sd} Numeric, logistic-normal standard deviation of pHOS observations. Default is 1.
\item \code{pHOS_init} Numeric, initial pHOS for equilibrium abundance in the first year of the model. Default is 0.
\item \code{s_enroute} Numeric, survival of escapement to spawning grounds. Default is 1.
\item \code{so_mu} Numeric, the prior mean for spawners at unfished replacement in logspace. Default is \code{log(3 * max(data$obsescape))}.
\item \code{so_sd} Numeric, the prior standard deviation for spawners at unfished replacement in logspace. Default is 0.5.
\item \code{finitPT} Numeric, initial preterminal fishing mortality for calculating the equilibrium juvenile proportions at age in the first year of the model. Default is 0. Set to \code{"estimate"} to allow the model to estimate
the equilibrium condition.
\item \code{finitT} Numeric, initial terminal fishing mortality for calculating the equilibrium juvenile proportions at age in the first year of the model. Default is 0. Set to \code{"estimate"} to allow the model to estimate
the equilibrium condition.
\item \code{spawn_init} Numeric, initial spawners to calculate equilibrium abundance in the first year of the model. Default is \code{obsescape[1]}.
\item \code{cwtExp} Numeric, the CWT expansion factor, typically the reciprocal of the catch sampling rate (higher factors for lower sampling rate).
The model scales down the CWT predictions to match the observations. In other words,
the model assumes that the CWT catch and escapement are not expanded. For example, \code{cwtExp = 10} divides the CWT predictions by 10 for the likelihood. Default is 1.
The Poisson distribution is used for the likelihood of the CWT observations, and the expansion parameter can be used to downweight the CWT likelihood relative to the escapement time series.
However it requires adjustments of the CWT catches prior to fitting to ensure the proper population scale.
If the expanded catch is 100, then the input CWT catch should be 10 and 50 with \code{cwtExp} of 10 and 2, respectively, to maintain the same population scale.
The Poisson variance scales with the mean and is higher with \code{cwtExp = 2}.
\item \code{fitness} Logical, whether to calculate fitness effects on survival. Default is \code{FALSE}.
\item \code{theta} Vector length 2, the optimum phenotype value for the natural and hatchery environments. Default is 100 and 80, respectively. See
\href{https://docs.salmonmse.com/articles/equations.html#fitness-effects-on-survival}{online article} for more information.
\item \code{rel_loss} Vector length 3, the loss in fitness apportioned between the egg, fry (both prior to density-dependence), and smolt (after density-dependence) life stage. The three values should sum to 1.
\item \code{zbar_start} Vector length 2, the mean phenotype of the spawners and broodtake in the natural and hatchery environment, respectively, at the start of the model. Default values of 100 and 100, implying maximum fitness at
for the natural environment at the start of the model.
\item \code{fitness_variance} Numeric. The variance (omega-squared) of the fitness function. Assumed identical between the natural and hatchery environments. Default is 100.
\item \code{phenotype_variance} Numeric. The variance (sigma-squared) of the phenotypic trait (with optimum theta). Assumed identical between the natural and hatchery environments. Default is 10.
\item \code{heritability} Numeric. The heritability (h-squared) of the phenotypic trait. Between 0-1. Default is 0.5.
\item \code{fitness_floor} Numeric. The minimum fitness value in the natural and hatchery environments. Default is 0.5.
}
}

\section{start}{

Starting values for parameters can be provided through a named list:
\itemize{
\item \code{log_cr} Numeric, log of the compensation ratio (productivity). Default is 3.
\item \code{log_so} Numeric, unfished spawners in logspace. Default is \code{log(3 * max(data$obsescape))}.
\item \code{moadd} Numeric, additive term to base natural mortality rate for age 1 juveniles. Default is zero.
\item \code{wt} Vector \code{Ldyr}. Annual deviates in natural mortality during the freshwater life stage (affects egg to smolt survival).
Estimated with normal prior with mean zero and standard deviation \code{p$wt_sd}. Default is zero.
\item \code{wto} Vector \code{Ldyr}. Annual deviates in natural mortality for age 1 juveniles (marine life stage).
Estimated with normal prior with mean zero and standard deviation \code{p$wto_sd}. Default is zero.
\item \code{log_FbasePT} Numeric, scaling coefficient to estimate preterminal fishing mortality from \code{data$RelRegFPT}. Default is \code{log(0.1)}.
\item \code{log_FbaseT} Numeric, scaling coefficient to estimate preterminal fishing mortality from \code{data$RelRegFT}. Default is \code{log(0.1)}.
\item \code{log_fanomalyPT} Vector \code{Ldyr}. Annual lognormal deviates from \code{exp(log_FbasePT) * data$RelRegFPT} to estimate preterminal fishing mortality.
Estimated with normal prior with mean zero and standard deviation \code{p$fanomaly_sd}. Default is zero.
\item \code{log_fanomalyT} Vector \code{Ldyr}. Annual lognormal deviates from \code{exp(log_FbaseT) * data$RelRegFT} to estimate terminal fishing mortality.
Estimated with normal prior with mean zero and standard deviation \code{p$fanomalyPT_sd}. Default is zero.
\item \code{lnE_sd} Numeric, lognormal standard deviation of the observed escapement. Estimated with hierarchical \code{gamma(2, 5)} prior. Default is 0.1.
\item \code{wt_sd} Numeric, lognormal standard deviation of the egg to smolt (freshwater) natural mortality deviates. Estimated with hierarchical \code{gamma(2, 5)} prior. Default is 1.
\item \code{wto_sd} Numeric, lognormal standard deviation of the age 1 (marine) natural mortality deviates. Estimated with hierarchical \code{gamma(2, 5)} prior. Default is 1.
\item \code{fanomalyPT_sd} Numeric, lognormal standard deviation of \code{fanomalyPT}. Estimated with hierarchical \code{gamma(2, 5)} prior. Default is 1.
\item \code{fanomalyT_sd} Numeric, lognormal standard deviation of \code{fanomalyT}. Estimated with hierarchical \code{gamma(2, 5)} prior. Default is 1.
\item \code{logit_vulPT} Vector \code{Nages-2} of preterminal vulnerability at age in logit space. Fixed to zero and one at age 1 and the maximum age, respectively.
Default is \code{qlogis(data$bvul_PT[-c(1, data$Nages)])}.
\item \code{logit_vulT} Vector \code{Nages-2} of terminal vulnerability at age in logit space. Fixed to zero and one at age 1 and the maximum age, respectively.
Default is \code{qlogis(data$bvul_T[-c(1, data$Nages)])}.
\item \code{logit_matt} Matrix \verb{Ldyr, Nages-2} maturity by year and age in logit space. Maturity is fixed to zero and one at age 1 and the maximum age, respectively.
Default is \code{matrix(qlogis(data$bmatt[-c(1, data$Nages)]), data$Ldyr, data$Nages-2, byrow = TRUE)}.
\item \code{sd_matt} Vector \code{Nages-2}. Logit standard deviation of maturity (\code{logit_matt}) by age class. Default is 0.5.
\item \code{b1} Vector \code{ncov1} of coefficients for linear covariates that predict natural mortality for age 1. Default is zero.
\item \code{b} Vector \code{ncov} of coefficients for linear covariates that predict natural mortality for ages 2+. Default is zero.
}
}

\section{Bounds}{


By default, the standard deviation parameters and parameters in normal space (e.g., \code{FbasePT}, \code{Fbase_T}) have a lower bound of zero.
\code{moadd} has a lower bound of zero by default, but it is feasible that this parameter can be negative as well.
Deviation parameters centred around zero are bounded between -3 to 3.
The \code{log_cr} parameter has a lower bound of zero.

All other parameters are unbounded.
}

\section{Covariates on natural mortality}{


Natural mortality is modeled as the sum of a base value \eqn{M^\textrm{base}}, additional scaling factor for age 1 \eqn{M^\textrm{add}},
a linear system of covariates \eqn{X} and coefficients \eqn{b}:

\deqn{
M_{y,a} =
\begin{cases}
M^\textrm{base}_a + M^\textrm{add} + \sum_j b^1_j X^1_{y,j} & \quad a = 1\\
M^\textrm{base}_a + \sum_j b_j X_{y,j} & \quad a = 2, \ldots, A
\end{cases}
}
}

\references{
Korman, J. and Walters, C. 2024. A life cycle model for Chinook salmon population dynamics. Canadian Contractor Report of Hydrography and Ocean
Sciences 62: vi + 60 p.
}
\seealso{
\code{\link[=report_CM]{report_CM()}}

\code{\link[=CM2SOM]{CM2SOM()}}
}
\author{
Q. Huynh from Stan code provided by J. Korman and C. Walters
}
