R/RcppExports.R

Defines functions lambda3 .demolition3sp .demolition3 .demolition4 .bambi2 .bambi3 edit_lM supplemental density_input actualstage3 sf_create create_pm .stovokor .snaltre3matrix .sltre3matrix .ltre3matrix .stoch_senselas slambda3 projection3 .proj3sp .proj3 .elas3sp_hlefko .elas3hlefko .elas3sp_matrix .elas3matrix .sens3hlefko_sp .sens3hlefko .sens3matrix_spinp .sens3sp_matrix .sens3matrix .rv3matrix_sp .rv3matrix .ss3matrix_sp .ss3matrix mpm_create f_projection3 .sf_reassess add_stage lmean hist_null sf_skeleton .binomial_test .integer_test logistic3 usher3 beverton3 ricker3 cond_diff cond_hmpm .hoffmannofstuttgart_sp .hoffmannofstuttgart .density3 .jpf .pfj

Documented in actualstage3 add_stage beverton3 cond_diff cond_hmpm create_pm density_input edit_lM f_projection3 hist_null lambda3 lmean logistic3 mpm_create projection3 ricker3 sf_create sf_skeleton slambda3 supplemental usher3

# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393

#' Create Vertical Structure for Horizontal Data Frame Input
#' 
#' Function \code{pfj()} powers the R function \code{\link{verticalize3}()},
#' creating the vertical structure and rearranging the data in that shape.
#' 
#' @name .pfj
#' 
#' @param data The horizontal data file.
#' @param stageframe The stageframe object describing the life history model.
#' This should be the full stageframe.
#' @param noyears The number of years or observation periods in the dataset.
#' @param firstyear The first year or time of observation.
#' @param popidcol Column number corresponding to the identity of the
#' population for each individual.
#' @param patchidcol Column number corresponding to the identity of the patch
#' for each individual.
#' @param individcol Column number corresponding to the identity of each 
#' individual.
#' @param blocksize The number of variables corresponding to each time step in 
#' the input dataset designated in \code{data}.
#' @param xcol Vector of column numbers corresponding to the x coordinate of
#' each individual in Cartesian space.
#' @param ycol Vector of column numbers corresponding to the y coordinate of
#' each individual in Cartesian space.
#' @param juvcol Vector of column numbers that marks individuals in immature
#' stages within the dataset.
#' @param sizeacol Vector of column numbers corresponding to the first or main
#' size variable associated with the first year or observation time in the
#' dataset.
#' @param sizebcol Vector of column numbers corresponding to the second size
#' variable associated with the first year or observation time in the dataset.
#' @param sizeccol Vector of column numbers corresponding to the third size
#' variable associated with the first year or observation time in the dataset.
#' @param repstracol Vector of column numbers corresponding to the main 
#' variable coding the production of reproductive structures associated with
#' the first year or observation period in the input dataset.
#' @param repstrbcol Vector of column numbers corresponding to a second
#' variable coding the production of reproductive structures associated with
#' the first year or observation period in the input dataset.
#' @param fecacol Vector of column numbers corresponding to the main variable
#' coding for fecundity associated with the first year or observation period in
#' the dataset.
#' @param fecbcol Vector of column numbers corresponding to a second variable
#' coding for fecundity associated with the first year or observation period in
#' the dataset.
#' @param indcovacol Vector of column numbers corresponding to an individual
#' covariate.
#' @param indcovbcol Vector of column numbers corresponding to an individual
#' covariate.
#' @param indcovccol Vector of column numbers corresponding to an individual
#' covariate.
#' @param aliveacol Vector of column numbers that details whether an individual
#' is alive at a given time.
#' @param deadacol Vector of column numbers that details whether an individual
#' is dead at a given time.
#' @param obsacol Vector of column numbers that details whether an individual
#' is in an observable stage at a given time.
#' @param nonobsacol Vector of column numbers that details whether an
#' individual is in an unobservable stage at a given time.
#' @param censorcol Vector of column numbers corresponding to the first entry
#' of a censor variable.
#' @param stagecol Vector of column numbers corresponding to the first entry of
#' a column designating stages.
#' @param repstrrel This is a scalar modifier for that makes the variable in
#' \code{repstrbcol} equivalent to \code{repstracol}.
#' @param fecrel This is a scalar modifier for that makes the variable in
#' \code{fecbcol} equivalent to \code{fecacol}.
#' @param NAas0 If TRUE, then all NA entries for size and fecundity variables
#' will be set to 0.
#' @param NRasRep If TRUE, then will treat non-reproductive but mature
#' individuals as reproductive during stage assignment.
#' @param RepasObs If TRUE, then will treat individuals with size 0 as observed
#' if and only if they are reproductive. Otherwise, all individuals with size 0
#' are treated as not observed.
#' @param NOasObs If TRUE, then will treat unobserved individuals as observed
#' during stage assignment.
#' @param stassign A logical value indicating whether to assign stages.
#' @param stszcol Integer describing which size variable or combination of size
#' variables to use in stage estimation.
#' @param censorkeep The value of the censoring variable identifying data
#' that should be included in analysis. Defaults to 0, but may take any numeric
#' value including NA.
#' @param censbool A logical variable determining whether NA denotes the value
#' of the censoring variable identifying data to keep. If used, then will set
#' all NAs to 0 and all other values to 1, treating 0 as the value to keep.
#' @param censrepeat A logical value indicating whether censor variable is a
#' single static column, or whether censor variables repeat across blocks.
#' @param coordsrepeat A logical value indicating whether coordinate variables
#' are single static columns, or whether they repeat across blocks.
#' @param retain_alive0 A logical variable indicating whether to keep or remove
#' data rows for individuals not alive in time \emph{t}.
#' @param reduce A logical variable determining whether unused variables and
#' some invariant state variables should be removed from the output dataset.
#' Defaults to \code{TRUE}.
#' @param quiet A logical value indicating whether to silense warnings.
#' 
#' @return The output is currently a 7 element list, where each element is a
#' data frame with the same number of rows.
#' 
#' @keywords internal
#' @noRd
.pfj <- function(data, stageframe, noyears, firstyear, popidcol, patchidcol, individcol, blocksize, xcol, ycol, juvcol, sizeacol, sizebcol, sizeccol, repstracol, repstrbcol, fecacol, fecbcol, indcovacol, indcovbcol, indcovccol, aliveacol, deadacol, obsacol, nonobsacol, censorcol, stagecol, repstrrel, fecrel, NAas0, NRasRep, RepasObs, NOasObs, stassign, stszcol, censorkeep, censbool, censrepeat, coordsrepeat, retain_alive0, reduce, quiet) {
    .Call('_lefko3_pfj', PACKAGE = 'lefko3', data, stageframe, noyears, firstyear, popidcol, patchidcol, individcol, blocksize, xcol, ycol, juvcol, sizeacol, sizebcol, sizeccol, repstracol, repstrbcol, fecacol, fecbcol, indcovacol, indcovbcol, indcovccol, aliveacol, deadacol, obsacol, nonobsacol, censorcol, stagecol, repstrrel, fecrel, NAas0, NRasRep, RepasObs, NOasObs, stassign, stszcol, censorkeep, censbool, censrepeat, coordsrepeat, retain_alive0, reduce, quiet)
}

#' Create Historical Vertical Structure for Ahistorical Vertical Data Frame
#' 
#' Function \code{jpf()} is the core kernel for function
#' \code{\link{historicalize3}()}, creating the historical, vertical structure
#' and rearranging the data in that shape.
#' 
#' @name .jpf
#' 
#' @param data The horizontal data file.
#' @param stageframe The stageframe object identifying the life history model
#' being operationalized. This should be the full stageframe.
#' @param popidcol Column number corresponding to the identity of the
#' population for each individual.
#' @param patchidcol Column number corresponding to the identity of the patch
#' for each individual.
#' @param individcol Column number corresponding to the identity of each 
#' individual.
#' @param year2col Column number of year or occasion in time \emph{t}.
#' @param year3col Column number of year or occasion in time \emph{t}+1.
#' @param xcol Column number corresponding to the x coordinate of each
#' individual in Cartesian space.
#' @param ycol Column number corresponding to the y coordinate of each
#' individual in Cartesian space.
#' @param juv2col Column number coding for status as a juvenile in time
#' \emph{t}.
#' @param juv3col Column number coding for status as a juvenile in time
#' \emph{t}+1.
#' @param sizea2col Column number corresponding to the primary size variable in
#' time \emph{t}.
#' @param sizea3col Column number corresponding to the primary size variable in
#' time \emph{t}+1.
#' @param sizeb2col Column number corresponding to the secondary size variable
#' in time \emph{t}.
#' @param sizeb3col Column number corresponding to the secondary size variable
#' in time \emph{t}+1.
#' @param sizec2col Column number corresponding to the tertiary size variable
#' in time \emph{t}.
#' @param sizec3col Column number corresponding to the tertiary size variable
#' in time \emph{t}+1.
#' @param repstra2col Column number corresponding to the main variable coding
#' for the production of reproductive structures, such as flowers, in time
#' \emph{t}.
#' @param repstra3col Column number corresponding to the main variable coding
#' for the production of reproductive structures, such as flowers, in time
#' \emph{t}+1.
#' @param repstrb2col Column number corresponding to a second variable coding
#' for the production of reproductive structures, such as flowers, in time
#' \emph{t}.
#' @param repstrb3col Column number corresponding to a second variable coding
#' for the production of reproductive structures, such as flowers, in time
#' \emph{t}+1.
#' @param feca2col Column number corresponding to the main variable coding for
#' fecundity in time \emph{t}.
#' @param feca3col Column number corresponding to the main variable coding for
#' fecundity in time \emph{t}+1.
#' @param fecb2col Column number corresponding to a second variable coding for
#' fecundity in time \emph{t}.
#' @param fecb3col Column number corresponding to a second variable coding for
#' fecundity in time \emph{t}+1.
#' @param indcova2col Column number corresponding to an individual covariate in
#' time \emph{t}.
#' @param indcova3col Column number corresponding to an individual covariate in
#' time \emph{t}+1.
#' @param indcovb2col Column number corresponding to an individual covariate in
#' time \emph{t}.
#' @param indcovb3col Column number corresponding to an individual covariate in
#' time \emph{t}+1.
#' @param indcovc2col Column number corresponding to an individual covariate in
#' time \emph{t}.
#' @param indcovc3col Column number corresponding to an individual covariate in
#' time \emph{t}+1.
#' @param alive2col Column number detailing whether an individual is alive in 
#' time \emph{t}.
#' @param alive3col Column number detailing whether an individual is alive in 
#' time \emph{t}+1.
#' @param dead2col Column number detailing whether an individual is dead in 
#' time \emph{t}.
#' @param dead3col Column number detailing whether an individual is dead in 
#' time \emph{t}+1.
#' @param obs2col Column number detailing whether an individual is in an
#' observable stage in time \emph{t}.
#' @param obs3col Column number detailing whether an individual is in an
#' observable stage in time \emph{t}+1.
#' @param nonobs2col Column number detailing whether an individual is in an
#' unobservable stage in time \emph{t}.
#' @param nonobs3col Column number detailing whether an individual is in an
#' unobservable stage in time \emph{t}+1.
#' @param repstrrel This is a scalar multiplier for that makes the variable in
#' \code{repstrb2col} equivalent to \code{repstra2col}.
#' @param fecrel This is a scalar multiplier for that makes the variable in
#' \code{fecb2col} equivalent to \code{feca2col}.
#' @param stage2col Column number corresponding to life history stage in time
#' \emph{t}.
#' @param stage3col Column number corresponding to life history stage in time
#' \emph{t}+1.
#' @param censorcol Column number corresponding to a censor variable within the
#' dataset.
#' @param NAas0 If \code{TRUE}, then all \code{NA} entries for size and
#' fecundity variables will be set to 0.
#' @param NRasRep If \code{TRUE}, then non-reproductive but mature individuals
#' will be treated as reproductive during stage assignment.
#' @param NOasObs If TRUE, then will treat unobserved individuals as observed
#' during stage assignment.
#' @param stassign A logical value indicating whether to assign stages.
#' @param stszcol Integer describing which size variable to use in stage 
#' estimation. Numbers 1 through 8 are possible.
#' @param censorkeep Numeric value of censor variable, denoting elements to
#' keep. If \code{NA} is to be used, then set this variable to \code{0} and set
#' \code{censbool = TRUE}.
#' @param censbool A logical variable determining whether \code{NA} denotes the
#' value of the censoring variable identifying data to keep.
#' @param retain_alive0 A logical variable indicating whether to keep or remove
#' data rows for individuals not alive in time \emph{t}.
#' @param reduce A logical variable determining whether unused variables and
#' some invariant state variables should be removed from the output dataset.
#' Defaults to \code{TRUE}.
#' @param quiet A logical value indicating whether to silense warnings.
#' 
#' @return The output is currently a list coerced into the data frame class,
#' and is read as a data frame by R. It is secondarily in class \code{hfvdata}.
#' 
#' @keywords internal
#' @noRd
.jpf <- function(data, stageframe, popidcol, patchidcol, individcol, year2col, year3col, xcol, ycol, juv2col, juv3col, sizea2col, sizea3col, sizeb2col, sizeb3col, sizec2col, sizec3col, repstra2col, repstra3col, repstrb2col, repstrb3col, feca2col, feca3col, fecb2col, fecb3col, indcova2col, indcova3col, indcovb2col, indcovb3col, indcovc2col, indcovc3col, alive2col, alive3col, dead2col, dead3col, obs2col, obs3col, nonobs2col, nonobs3col, repstrrel, fecrel, stage2col, stage3col, censorcol, NAas0, NRasRep, NOasObs, stassign, stszcol, censorkeep, censbool, retain_alive0, reduce, quiet) {
    .Call('_lefko3_jpf', PACKAGE = 'lefko3', data, stageframe, popidcol, patchidcol, individcol, year2col, year3col, xcol, ycol, juv2col, juv3col, sizea2col, sizea3col, sizeb2col, sizeb3col, sizec2col, sizec3col, repstra2col, repstra3col, repstrb2col, repstrb3col, feca2col, feca3col, fecb2col, fecb3col, indcova2col, indcova3col, indcovb2col, indcovb3col, indcovc2col, indcovc3col, alive2col, alive3col, dead2col, dead3col, obs2col, obs3col, nonobs2col, nonobs3col, repstrrel, fecrel, stage2col, stage3col, censorcol, NAas0, NRasRep, NOasObs, stassign, stszcol, censorkeep, censbool, retain_alive0, reduce, quiet)
}

#' Estimate Radial Density in Cartesian Space
#' 
#' Function \code{.density3()} estimates radial density on the basis of
#' Cartesian coordinates and spacing information supplied as input. It is used
#' internally by \code{\link{historicalize3}()} and
#' \code{\link{verticalize3}()}.
#' 
#' @name .density3
#' 
#' @param data Demographic dataset in historical vertical format.
#' @param xcol Number of column in \code{data} corresponding to x position.
#' @param ycol Number of column in \code{data} corresponding to y position.
#' @param yearcol Number of column in \code{data} corresponding to occasion
#' \emph{t}.
#' @param spacing Resolution of density estimation, as a scalar numeric.
#' 
#' @return This function returns a vector counting the number of individuals
#' within the specified distance of each individual in the historically
#' formatted vertical dataset.
#' 
#' @section Notes:
#' The process used to estimate density is one in which the distances between
#' all pairs of individuals are calculated via the Pythagorean theorem, and
#' then individual density equals the number of these individuals with
#' distances within the number input as \code{spacing}, respectively for each
#' individual.
#' 
#' This function assumes that all individuals are alive in time \emph{t}, and
#' so data should be filtered appropriately beforehand. Any rows with NA in X
#' or Y will not be counted, and density is estimated specific to time \emph{t}.
#' 
#' @keywords internal
#' @noRd
.density3 <- function(data, xcol, ycol, yearcol, spacing) {
    .Call('_lefko3_density3', PACKAGE = 'lefko3', data, xcol, ycol, yearcol, spacing)
}

#' Core Engine for cond_hmpm()
#' 
#' Creates a list of conditional ahistorical matrices in the style noted in
#' deVries and Caswell (2018).
#' 
#' @name .hoffmannofstuttgart
#' 
#' @param mainmat Historical matrix.
#' @param indices Data frame including the stages at times \emph{t}-1,
#' \emph{t}, and \emph{t}+1, asvwell as indices corresponding to elements in
#' the main historical matrix andvthe conditional matrices to be produced.
#' @param ahstages The number of stages in the stageframe.
#' @param stageframe The original stageframe for the input matrices.
#'
#' @return A list of ahistorical matrices.
#' 
#' @keywords internal
#' @noRd
.hoffmannofstuttgart <- function(mainmat, indices, ahstages, stagenames) {
    .Call('_lefko3_hoffmannofstuttgart', PACKAGE = 'lefko3', mainmat, indices, ahstages, stagenames)
}

#' Core Engine for cond_hmpm()
#' 
#' Creates a list of conditional ahistorical matrices in the style noted in
#' deVries and Caswell (2018).
#' 
#' @name .hoffmannofstuttgart_sp
#' 
#' @param mainmat Historical matrix in sparse format.
#' @param indices Data frame including the stages at times \emph{t}-1,
#' \emph{t}, and \emph{t}+1, asvwell as indices corresponding to elements in
#' the main historical matrix andvthe conditional matrices to be produced.
#' @param ahstages The number of stages in the stageframe.
#' @param stageframe The original stageframe for the input matrices.
#'
#' @return A list of ahistorical matrices.
#' 
#' @keywords internal
#' @noRd
.hoffmannofstuttgart_sp <- function(mainmat, indices, ahstages, stagenames) {
    .Call('_lefko3_hoffmannofstuttgart_sp', PACKAGE = 'lefko3', mainmat, indices, ahstages, stagenames)
}

#' Extract Conditional Ahistorical Matrices from Historical MPM
#' 
#' Function \code{cond_hmpm()} takes historical MPMs and decomposes them into 
#' ahistorical matrices conditional upon stage in time \emph{t}-1. In effect,
#' the function takes each historical matrix within a lefkoMat object, and
#' forms one ahistorical matrix for each stage in time \emph{t}-1.
#' 
#' @name cond_hmpm
#' 
#' @param hmpm A historical matrix projection model of class \code{lefkoMat}.
#' @param matchoice A character denoting whether to use A, U, or F matrices.
#' Defaults to \code{A} matrices.
#' @param err_check A logical value denoting whether to include a data frame
#' of element equivalence from the conditional matrices to the original
#' matrices. Used only for debugging purposes. Defaults to \code{FALSE}.
#' 
#' @return A \code{lefkoCondMat} object, with the following elements:
#' 
#' \item{Mcond}{A multi-level list holding the conditional A matrices derived
#' from the input \code{lefkoMat} object. The top level of the list corresponds
#' to each historical matrix in turn, and the lower level corresponds to each
#' stage in time \emph{t}-1, with individual conditional matrices named for the
#' latter.}
#' \item{hstages}{A data frame matrix showing the pairing of ahistorical stages
#' used to create historical stage pairs.}
#' \item{ahstages}{A data frame detailing the characteristics of associated
#' ahistorical stages.}
#' \item{labels}{A data frame showing the patch and year of each input full A 
#' matrix in order.}
#' \item{err_check}{An optional data frame showing the order of used element
#' indices to create conditional matrices.}
#' 
#' @examples
#' data(cypdata)
#'  
#' sizevector <- c(0, 0, 0, 0, 0, 0, 1, 2.5, 4.5, 8, 17.5)
#' stagevector <- c("SD", "P1", "P2", "P3", "SL", "D", "XSm", "Sm", "Md",
#'   "Lg", "XLg")
#' repvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' obsvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' matvector <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' immvector <- c(0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 0, 0, 0, 0, 0.5, 0.5, 1, 1, 2.5, 7)
#' 
#' cypframe_raw <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector, 
#'   propstatus = propvector, immstatus = immvector, indataset = indataset,
#'   binhalfwidth = binvec)
#' 
#' cypraw_v1 <- verticalize3(data = cypdata, noyears = 6, firstyear = 2004,
#'   patchidcol = "patch", individcol = "plantid", blocksize = 4, 
#'   sizeacol = "Inf2.04", sizebcol = "Inf.04", sizeccol = "Veg.04", 
#'   repstracol = "Inf.04", repstrbcol = "Inf2.04", fecacol = "Pod.04",
#'   stageassign = cypframe_raw, stagesize = "sizeadded", NAas0 = TRUE, 
#'   NRasRep = TRUE)
#' 
#' cypsupp3r <- supplemental(stage3 = c("SD", "SD", "P1", "P1", "P2", "P3", "SL",
#'     "D", "XSm", "Sm", "D", "XSm", "Sm", "mat", "mat", "mat", "SD", "P1"),
#'   stage2 = c("SD", "SD", "SD", "SD", "P1", "P2", "P3", "SL", "SL", "SL", "SL",
#'     "SL", "SL", "D", "XSm", "Sm", "rep", "rep"),
#'   stage1 = c("SD", "rep", "SD", "rep", "SD", "P1", "P2", "P3", "P3", "P3",
#'     "SL", "SL", "SL", "SL", "SL", "SL", "mat", "mat"),
#'   eststage3 = c(NA, NA, NA, NA, NA, NA, NA, "D", "XSm", "Sm", "D", "XSm", "Sm",
#'     "mat", "mat", "mat", NA, NA),
#'   eststage2 = c(NA, NA, NA, NA, NA, NA, NA, "XSm", "XSm", "XSm", "XSm", "XSm",
#'     "XSm", "D", "XSm", "Sm", NA, NA),
#'   eststage1 = c(NA, NA, NA, NA, NA, NA, NA, "XSm", "XSm", "XSm", "XSm", "XSm",
#'     "XSm", "XSm", "XSm", "XSm", NA, NA),
#'   givenrate = c(0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.25, NA, NA, NA, NA, NA, NA,
#'     NA, NA, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
#'     NA, 0.5, 0.5),
#'   type = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3),
#'   type_t12 = c(1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
#'   stageframe = cypframe_raw, historical = TRUE)
#' 
#' cypmatrix3r <- rlefko3(data = cypraw_v1, stageframe = cypframe_raw,
#'   year = "all", patch = "all", stages = c("stage3", "stage2", "stage1"),
#'   size = c("size3added", "size2added", "size1added"),
#'   supplement = cypsupp3r, yearcol = "year2", patchcol = "patchid",
#'   indivcol = "individ")
#' 
#' cypcondmats <- cond_hmpm(cypmatrix3r)
#' summary(cypcondmats)
#' 
#' @export cond_hmpm
cond_hmpm <- function(hmpm, matchoice = NULL, err_check = NULL) {
    .Call('_lefko3_cond_hmpm', PACKAGE = 'lefko3', hmpm, matchoice, err_check)
}

#' Extract Conditional Ahistorical Difference Matrices
#' 
#' Function \code{cond_diff()} takes a set of historical difference matrices
#' resulting from function \code{\link{diff_lM}()} and decomposes them into 
#' ahistorical difference matrices conditional upon stage in time \emph{t}-1.
#' 
#' @name cond_diff
#' 
#' @param lDiff An object of class \code{lefkoDiff}.
#' @param ref Choice of mpm to use as reference. Defaults to \code{1}, which
#' means that the \code{ahstages}, \code{hstages}, and \code{labels} elements
#' for mpm1 will be used for all calculations. Only \code{1} amd \code{2} are
#' possible inputs.
#' @param matchoice A character denoting whether to use A, U, or F matrices.
#' Defaults to \code{A} matrices.
#' @param err_check A logical value denoting whether to include a data frame
#' of element equivalence from the conditional matrices to the original
#' matrices. Used only for debugging purposes. Defaults to \code{FALSE}.
#' 
#' @return A \code{lefkoCondDiff} object, with the following elements:
#' 
#' \item{Mcond}{A multi-level list holding the conditional matrices derived
#' from the input \code{lefkoDiff} object. The top level of the list
#' corresponds to each historical difference matrix in turn, and the lower
#' level corresponds to each stage in time \emph{t}-1, with individual
#' conditional matrices named for the latter.}
#' \item{hstages}{A data frame matrix showing the pairing of ahistorical stages
#' used to create historical stage pairs.}
#' \item{ahstages}{A data frame detailing the characteristics of associated
#' ahistorical stages.}
#' \item{labels}{A data frame showing the patch and year of each input full A 
#' matrix in order.}
#' \item{err_check}{An optional data frame showing the order of used element
#' indices to create conditional matrices.}
#' 
#' @examples
#' sizevector <- c(0, 0, 0, 0, 0, 0, 1, 3, 6, 11, 19.5)
#' stagevector <- c("SD", "P1", "P2", "P3", "SL", "D", "XSm", "Sm", "Md", "Lg",
#'   "XLg")
#' repvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' obsvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' matvector <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' immvector <- c(0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 0, 0, 0, 0, 0.5, 0.5, 1.5, 1.5, 3.5, 5)
#' comments <- c("Dormant seed", "1st yr protocorm", "2nd yr protocorm",
#'   "3rd yr protocorm", "Seedling", "Dormant adult",
#'   "Extra small adult (1 shoot)", "Small adult (2-4 shoots)",
#'   "Medium adult (5-7 shoots)", "Large adult (8-14 shoots)",
#'   "Extra large adult (>14 shoots)")
#' cypframe_raw <- sf_create(sizes = sizevector, stagenames = stagevector, 
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector,
#'   propstatus = propvector, immstatus = immvector, indataset = indataset, 
#'   binhalfwidth = binvec, comments = comments)
#' 
#' cypraw_v1 <- verticalize3(data = cypdata, noyears = 6, firstyear = 2004, 
#'   patchidcol = "patch", individcol = "plantid", blocksize = 4,
#'   sizeacol = "Inf2.04", sizebcol = "Inf.04", sizeccol = "Veg.04",
#'   repstracol = "Inf.04", repstrbcol = "Inf2.04", fecacol = "Pod.04",
#'   stageassign = cypframe_raw, stagesize = "sizeadded", NAas0 = TRUE,
#'   NRasRep = TRUE)
#' 
#' seeds_per_pod <- 5000
#' 
#' cypsupp2_raw <- supplemental(stage3 = c("SD", "P1", "P2", "P3", "SL", "SL", "D", 
#'     "XSm", "SD", "P1"),
#'   stage2 = c("SD", "SD", "P1", "P2", "P3", "SL", "SL", "SL", "rep", "rep"),
#'   eststage3 = c(NA, NA, NA, NA, NA, NA, "D", "XSm", NA, NA),
#'   eststage2 = c(NA, NA, NA, NA, NA, NA, "XSm", "XSm", NA, NA),
#'   givenrate = c(0.03, 0.15, 0.1, 0.1, 0.1, 0.05, NA, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, NA, NA, NA, NA, (0.5 * seeds_per_pod),
#'     (0.5 * seeds_per_pod)),
#'   type =c(1, 1, 1, 1, 1, 1, 1, 1, 3, 3),
#'   stageframe = cypframe_raw, historical = FALSE)
#' cypsupp3_raw <- supplemental(stage3 = c("SD", "SD", "P1", "P1", "P2", "P3", "SL",
#'     "D", "XSm", "Sm", "D", "XSm", "Sm", "mat", "mat", "mat", "SD", "P1"),
#'   stage2 = c("SD", "SD", "SD", "SD", "P1", "P2", "P3", "SL", "SL", "SL", "SL",
#'     "SL", "SL", "D", "XSm", "Sm", "rep", "rep"),
#'   stage1 = c("SD", "rep", "SD", "rep", "SD", "P1", "P2", "P3", "P3", "P3",
#'     "SL", "SL", "SL", "SL", "SL", "SL", "mat", "mat"),
#'   eststage3 = c(NA, NA, NA, NA, NA, NA, NA, "D", "XSm", "Sm", "D", "XSm", "Sm",
#'     "mat", "mat", "mat", NA, NA),
#'   eststage2 = c(NA, NA, NA, NA, NA, NA, NA, "XSm", "XSm", "XSm", "XSm", "XSm",
#'     "XSm", "D", "XSm", "Sm", NA, NA),
#'   eststage1 = c(NA, NA, NA, NA, NA, NA, NA, "XSm", "XSm", "XSm", "XSm", "XSm",
#'     "XSm", "XSm", "XSm", "XSm", NA, NA),
#'   givenrate = c(0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.25, NA, NA, NA, NA, NA, NA,
#'     NA, NA, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
#'     NA, 0.5, 0.5),
#'   type = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3),
#'   type_t12 = c(1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
#'   stageframe = cypframe_raw, historical = TRUE)
#' 
#' cypmatrix2rp <- rlefko2(data = cypraw_v1, stageframe = cypframe_raw,
#'   year = "all", patch = "all", stages = c("stage3", "stage2"),
#'   size = c("size3added", "size2added"), supplement = cypsupp2_raw, 
#'   yearcol = "year2", patchcol = "patchid", indivcol = "individ")
#' 
#' cypmatrix2r <- rlefko2(data = cypraw_v1, stageframe = cypframe_raw,
#'   year = "all", stages = c("stage3", "stage2"),
#'   size = c("size3added", "size2added"), supplement = cypsupp2_raw, 
#'   yearcol = "year2", patchcol = "patchid", indivcol = "individ")
#' 
#' cypmatrix3rp <- rlefko3(data = cypraw_v1, stageframe = cypframe_raw,
#'   year = "all", patch = "all", stages = c("stage3", "stage2", "stage1"), 
#'   size = c("size3added", "size2added", "size1added"), supplement = cypsupp3_raw, 
#'   yearcol = "year2", patchcol = "patchid", indivcol = "individ")
#' 
#' cypmatrix3r <- rlefko3(data = cypraw_v1, stageframe = cypframe_raw,
#'   year = "all", stages = c("stage3", "stage2", "stage1"), 
#'   size = c("size3added", "size2added", "size1added"), supplement = cypsupp3_raw, 
#'   yearcol = "year2", patchcol = "patchid", indivcol = "individ")
#' 
#' cypmatrix2r_3 <- hist_null(cypmatrix2r)
#' cypmatrix2r_3 <- delete_lM(cypmatrix2r_3, year = 2004)
#' diff_r <- diff_lM(cypmatrix3r, cypmatrix2r_3)
#' 
#' cypmatrix2rp_3 <- hist_null(cypmatrix2rp)
#' cypmatrix2rp_3 <- delete_lM(cypmatrix2rp_3, year = 2004)
#' diff_rp <- diff_lM(cypmatrix3rp, cypmatrix2rp_3)
#' 
#' condr1 <- cond_diff(diff_r, ref = 1)
#' condr2 <- cond_diff(diff_r, ref = 2)
#' 
#' condrp1 <- cond_diff(diff_rp, matchoice = "U", ref = 1)
#' condrp2 <- cond_diff(diff_rp, matchoice = "F", ref = 2)
#' 
#' @export cond_diff
cond_diff <- function(lDiff, ref = 1L, matchoice = NULL, err_check = NULL) {
    .Call('_lefko3_cond_diff', PACKAGE = 'lefko3', lDiff, ref, matchoice, err_check)
}

#' Two-parameter Ricker function
#' 
#' Function \code{ricker3()} creates a vector of values produced by the two-
#' parameter Ricker function as applied with a user-specified time lag. The
#' two-parameter Ricker function is given as 
#' \eqn{\phi_{t+1} = \phi_t \alpha e^{-\beta n_t}}. Here, if no
#' \code{separate_N} vector is provided, then \eqn{n_t = \phi_t}.
#' 
#' @name ricker3
#' 
#' @param start_value A positive number to start the return vector in time 0.
#' @param alpha The alpha parameter in the two-parameter Ricker function. Must
#' be non-negative.
#' @param beta The beta parameter in the two-parameter Ricker function.
#' @param time_steps The number of time steps to run the projection. Must be a
#' positive integer.
#' @param time_lag A positive integer denoting the number of time steps back
#' for the value of phi in the two-parameter Ricker function.
#' @param pre0_subs A logical value indicating whether to use a number other
#' than that given in \code{start_value} for values of phi lagged from times
#' prior to time 0.
#' @param pre0_value A positive number to use for phi lagged from times prior
#' to time 0. Only used if \code{pre0_subs = TRUE}.
#' @param substoch An integer value indicating the kind of substochasticity to
#' use. Values include: \code{0}, no substochasticity enforced (the default);
#' \code{1}, all numbers must be non-negative; and \code{2}, all numbers should
#' be forced to the interval [0, 1].
#' @param separate_N An optional numeric vector with values of N in each time,
#' if phi is to be treated as different from N in the two-parameter model.
#' 
#' @return A numeric vector of values showing values projected under the two-
#' parameter Ricker function.
#' 
#' @examples
#' trial_run1 <- ricker3(1, alpha = 0.5, beta = -0.009)
#' plot(trial_run1)
#' 
#' trial_run2 <- ricker3(1, alpha = 0.5, beta = 0.009)
#' plot(trial_run2)
#' 
#' trial_run3 <- ricker3(1, alpha = 1, beta = -0.009)
#' plot(trial_run3)
#' 
#' trial_run4 <- ricker3(1, alpha = 1, beta = 0.009)
#' plot(trial_run4)
#' 
#' trial_run5 <- ricker3(1, alpha = 5, beta = -0.009)
#' plot(trial_run5)
#' 
#' trial_run6 <- ricker3(1, alpha = 5, beta = 0.009)
#' plot(trial_run6)
#' 
#' used_Ns <- c(10, 15, 12, 14, 14, 150, 15, 1, 5, 7, 9, 14, 13, 16, 17, 19,
#'   25, 26)
#' trial_run7 <- ricker3(1, alpha = 1, beta = -0.009, separate_N = used_Ns)
#' plot(trial_run7)
#' 
#' @export ricker3
ricker3 <- function(start_value, alpha, beta, time_steps = 100L, time_lag = 1L, pre0_subs = FALSE, pre0_value = 0.0, substoch = 0L, separate_N = NULL) {
    .Call('_lefko3_ricker3', PACKAGE = 'lefko3', start_value, alpha, beta, time_steps, time_lag, pre0_subs, pre0_value, substoch, separate_N)
}

#' Two-parameter Beverton-Holt function
#' 
#' Function \code{beverton3()} creates a vector of values produced by the two-
#' parameter Beverton-Holt function as applied with a user-specified time lag.
#' The two-parameter Beverton-Holt function is given as 
#' \eqn{\phi_{t+1} = \phi_t \alpha / (1 + \beta n_t)}. Here, if no
#' \code{separate_N} vector is provided, then \eqn{n_t = \phi_t}.
#' 
#' @name beverton3
#' 
#' @param start_value A positive number to start the return vector in time 0.
#' @param alpha The alpha parameter in the two-parameter Beverton-Holt
#' function. Must be non-negative.
#' @param beta The beta parameter in the two-parameter Beverton-Holt function.
#' Must be non-negative.
#' @param time_steps The number of time steps to run the projection. Must be a
#' positive integer.
#' @param time_lag A positive integer denoting the number of time steps back
#' for the value of phi in the two-parameter Beverton-Holt function.
#' @param pre0_subs A logical value indicating whether to use a number other
#' than that given in \code{start_value} for values of phi lagged from times
#' prior to time 0.
#' @param pre0_value A positive number to use for phi lagged from times prior
#' to time 0. Only used if \code{pre0_subs = TRUE}.
#' @param substoch An integer value indicating the kind of substochasticity to
#' use. Values include: \code{0}, no substochasticity enforced (the default);
#' \code{1}, all numbers must be non-negative; and \code{2}, all numbers should
#' be forced to the interval [0, 1].
#' @param separate_N An optional numeric vector with values of N in each time,
#' if phi is to be treated as different from N in the two-parameter model.
#' 
#' @return A numeric vector of values showing values projected under the two-
#' parameter Beverton-Holt function.
#' 
#' @examples
#' trial_run1 <- beverton3(1, alpha = 0.5, beta = 0.009)
#' plot(trial_run1)
#' 
#' trial_run2 <- beverton3(1, alpha = 0.5, beta = 0.9)
#' plot(trial_run2)
#' 
#' trial_run3 <- beverton3(1, alpha = 1, beta = 0.009)
#' plot(trial_run3)
#' 
#' trial_run4 <- beverton3(1, alpha = 1, beta = 0.9)
#' plot(trial_run4)
#' 
#' trial_run5 <- beverton3(1, alpha = 5, beta = 0.009)
#' plot(trial_run5)
#' 
#' trial_run6 <- beverton3(1, alpha = 5, beta = 0.9)
#' plot(trial_run6)
#' 
#' used_Ns <- c(10, 15, 12, 14, 14, 150, 15, 1, 5, 7, 9, 14, 13, 16, 17, 19,
#'   25, 26)
#' trial_run7 <- beverton3(1, alpha = 1, beta = 0.009, separate_N = used_Ns)
#' plot(trial_run7)
#' 
#' @export beverton3
beverton3 <- function(start_value, alpha, beta, time_steps = 100L, time_lag = 1L, pre0_subs = FALSE, pre0_value = 0.0, substoch = 0L, separate_N = NULL) {
    .Call('_lefko3_beverton3', PACKAGE = 'lefko3', start_value, alpha, beta, time_steps, time_lag, pre0_subs, pre0_value, substoch, separate_N)
}

#' Two-parameter Usher function
#' 
#' Function \code{usher3()} creates a vector of values produced by the two-
#' parameter Usher function as applied with a user-specified time lag.
#' The Usher function is given as 
#' \eqn{\phi_{t+1} = \phi_t / (1 + e^{\alpha n_t + \beta})}. Here,
#' if no \code{separate_N} vector is provided, then \eqn{n_t = \phi_t}.
#' 
#' @name usher3
#' 
#' @param start_value A positive number to start the return vector in time 0.
#' @param alpha The alpha parameter in the two-parameter Usher
#' function.
#' @param beta The beta parameter in the two-parameter Usher function.
#' @param time_steps The number of time steps to run the projection. Must be a
#' positive integer.
#' @param time_lag A positive integer denoting the number of time steps back
#' for the value of phi in the two-parameter Usher function.
#' @param pre0_subs A logical value indicating whether to use a number other
#' than that given in \code{start_value} for values of phi lagged from times
#' prior to time 0.
#' @param pre0_value A positive number to use for phi lagged from times prior
#' to time 0. Only used if \code{pre0_subs = TRUE}.
#' @param substoch An integer value indicating the kind of substochasticity to
#' use. Values include: \code{0}, no substochasticity enforced (the default);
#' \code{1}, all numbers must be non-negative; and \code{2}, all numbers should
#' be forced to the interval [0, 1].
#' @param separate_N An optional numeric vector with values of N in each time,
#' if phi is to be treated as different from N in the two-parameter model.
#' 
#' @return A numeric vector of values showing values projected under the two-
#' parameter Usher function.
#' 
#' @examples
#' trial_run1 <- usher3(1, alpha = -0.5, beta = 0.005)
#' plot(trial_run1)
#' 
#' trial_run2 <- usher3(1, alpha = 0.5, beta = 0.005)
#' plot(trial_run2)
#' 
#' trial_run3 <- usher3(1, alpha = -5, beta = 0.005)
#' plot(trial_run3)
#' 
#' trial_run4 <- usher3(1, alpha = 5, beta = 0.005)
#' plot(trial_run4)
#' 
#' trial_run5 <- usher3(1, alpha = -25, beta = 0.005)
#' plot(trial_run5)
#' 
#' trial_run6 <- usher3(1, alpha = 25, beta = 0.005)
#' plot(trial_run6)
#' 
#' used_Ns <- c(10, 15, 12, 14, 14, 150, 15, 1, 5, 7, 9, 14, 13, 16, 17, 19,
#'   25, 26)
#' trial_run7 <- usher3(1, alpha = -0.5, beta = 0.005, separate_N = used_Ns)
#' plot(trial_run7)
#' 
#' @export usher3
usher3 <- function(start_value, alpha, beta, time_steps = 100L, time_lag = 1L, pre0_subs = FALSE, pre0_value = 0.0, substoch = 0L, separate_N = NULL) {
    .Call('_lefko3_usher3', PACKAGE = 'lefko3', start_value, alpha, beta, time_steps, time_lag, pre0_subs, pre0_value, substoch, separate_N)
}

#' Two-parameter logistic function
#' 
#' Function \code{logistic3()} creates a vector of values produced by the
#' logistic function as applied with a user-specified time lag. The logistic
#' function is given as 
#' \eqn{\phi_{t+1} = \phi_t \lambda (1 - n_t / K)}. Here,
#' if no \code{separate_N} vector is provided, then \eqn{n_t = \phi_t}. If
#' \eqn{\lambda} is not provided, then it defaults to \code{1.0}.
#' 
#' @name logistic3
#' 
#' @param start_value A positive number to start the return vector in time 0.
#' @param alpha The carrying capacity K.
#' @param beta If set to some positive number, then this number is the maximum
#' value of phi to enforce. Otherwise, equals \code{0} and enforces no limit.
#' @param lambda The value of the discrete population growth rate to use.
#' Equal to the natural logarithm of the instantaneous growth rate, r.
#' @param time_steps The number of time steps to run the projection. Must be a
#' positive integer.
#' @param time_lag A positive integer denoting the number of time steps back
#' for the value of phi in the logistic function.
#' @param pre0_subs A logical value indicating whether to use a number other
#' than that given in \code{start_value} for values of phi lagged from times
#' prior to time 0.
#' @param pre0_value A positive number to use for phi lagged from times prior
#' to time 0. Only used if \code{pre0_subs = TRUE}.
#' @param substoch An integer value indicating the kind of substochasticity to
#' use. Values include: \code{0}, no substochasticity enforced (the default);
#' \code{1}, all numbers must be non-negative; and \code{2}, all numbers should
#' be forced to the interval [0, 1].
#' @param separate_N An optional numeric vector with values of N in each time,
#' if phi is to be treated as different from N in the logistic model.
#' 
#' @return A numeric vector of values showing values projected under the-
#' logistic function.
#' 
#' @examples
#' trial_run1 <- logistic3(1, alpha = 5)
#' plot(trial_run1)
#' 
#' trial_run2 <- logistic3(1, alpha = 5, beta = 5)
#' plot(trial_run2)
#' 
#' trial_run3 <- logistic3(1, alpha = 100)
#' plot(trial_run3)
#' 
#' trial_run4 <- logistic3(1, alpha = 100, beta = 50)
#' plot(trial_run4)
#' 
#' trial_run5 <- logistic3(1, alpha = 500)
#' plot(trial_run5)
#' 
#' trial_run6 <- logistic3(1, alpha = 500, beta = 501)
#' plot(trial_run6)
#' 
#' used_Ns <- c(10, 15, 12, 14, 14, 150, 15, 1, 5, 7, 9, 14, 13, 16, 17, 19,
#'   25, 26)
#' trial_run7 <- logistic3(1, alpha = 500, beta = 501, separate_N = used_Ns)
#' plot(trial_run7)
#' 
#' @export logistic3
logistic3 <- function(start_value, alpha, beta = 0.0, lambda = 1.0, time_steps = 100L, time_lag = 1L, pre0_subs = FALSE, pre0_value = 0.0, substoch = 0L, separate_N = NULL) {
    .Call('_lefko3_logistic3', PACKAGE = 'lefko3', start_value, alpha, beta, lambda, time_steps, time_lag, pre0_subs, pre0_value, substoch, separate_N)
}

#' Function to Test Whether a Numeric Vector Is Composed Only of Integers
#' 
#' Function \code{.integer_test()} tests whether the elements of a numeric
#' vector are integers.
#' 
#' @name .integer_test
#' 
#' @param numeric_input A numeric vector to be tested.
#' 
#' @return This function returns an integer equal to the number of elements
#' that are not integers in \code{numeric_input}.
#' 
#' @keywords internal
#' @noRd
.integer_test <- function(numeric_input) {
    .Call('_lefko3_integer_test', PACKAGE = 'lefko3', numeric_input)
}

#' Function to Test Whether an Integer Vector Is Entirely Binomial
#' 
#' Function \code{.binomial_test()} tests whether an integer vector is composed
#' only of \code{0} and \code{1} elements.
#' 
#' @name .binomial_test
#' 
#' @param integer_input An integer vector to be tested.
#' 
#' @return This function returns an integer equal to the number of elements
#' that are not \code{0}s and \code{1}s.
#' 
#' @keywords internal
#' @noRd
.binomial_test <- function(integer_input) {
    .Call('_lefko3_binomial_test', PACKAGE = 'lefko3', integer_input)
}

#' Create Element Index for Matrix Estimation
#' 
#' Function \code{simplepizzle()} creates a data frame object used by function
#' \code{\link{hist_null}()} to provide an index for estimation of null
#' historical matrices from ahistorical MPM inputs.
#' 
#' @name simplepizzle
#' 
#' @param StageFrame The stageframe object identifying the life history model
#' being operationalized.
#' @param format Integer indicating whether historical matrices should be in
#' (1) Ehrlen or (2) deVries format.
#' 
#' @return The output is composed of three elements:
#' \item{ahstages}{A new stageframe, which only differs from the input
#' stageframe in deVries format.}
#' \item{hstages}{A new historical stage-pair index for the new historical
#' matrices.}
#' \item{allstages}{A large data frame describing every element to be estimated
#' in the new historical matrices.}
#' 
#' @keywords internal
#' @noRd
NULL

#' Create Historically Structured Version of ahMPM
#' 
#' Function \code{thefifthhousemate()} takes an ahistorical MPM as input, and
#' uses the \code{allstages} index to create a historically structured version
#' of it.
#' 
#' @name thefifthhousemate
#' 
#' @param mpm The original ahMPM, supplied as a \code{lefkoMat} object.
#' @param allstages The index dataframe named \code{allstages}, in the third
#' element of output developed by \code{simplepizzle()}.
#' @param hstages The index dataframe named \code{hstages}, in the second
#' element of output developed by \code{simplepizzle()}.
#' @param stageframe The ahistorical stageframe supplied by
#' \code{simplepizzle()}.
#' @param format Integer indicating whether historical matrices should be in
#' (1) Ehrlen or (2) deVries format.
#' 
#' @return This will return a list of lists. The first list is composed of all
#' new \code{A} matrices. The second list is composed of all new \code{U}
#' matrices. The third list is composed of all new \code{F} matrices.
#' 
#' @keywords internal
#' @noRd
NULL

#' Create Skeleton Stageframe
#' 
#' Function \code{sf_skeleton()} creates a skeleton \code{stageframe} object.
#' 
#' @name sf_skeleton
#' 
#' @param stages The number of stages, as an integer.
#' @param standard A logical value indicating whether to create a standard
#' \code{stageframe} object (\code{TRUE}, the default), or a reassessed
#' \code{stageframe} object as created by function \code{mpm_create()}
#' (\code{FALSE}).
#' 
#' @return A dat frame of class \code{stageframe}.
#' 
#' @export
sf_skeleton <- function(stages, standard = TRUE) {
    .Call('_lefko3_sf_skeleton', PACKAGE = 'lefko3', stages, standard)
}

#' Create Historical MPMs Assuming No Influence of Individual History
#' 
#' Function \code{hist_null()} uses ahistorical MPMs to create the equivalent
#' MPMs in the structure of historical MPMs. These MPMs have the same
#' dimensions and stage structure of hMPMs but assume no influence of
#' individual history, and so can be compared to actual hMPMs.
#' 
#' @name hist_null
#' 
#' @param mpm An ahistorical MPM of class \code{lefkoMat}.
#' @param format An integer stipulating whether historical matrices should be
#' produced in Ehrlen format (\code{1}) or deVries format (\code{2}).
#' @param err_check A logical value indicating whether to output the main index
#' data frames used to sort elements in the matrices.
#' 
#' @return An object of class \code{lefkoMat}, with the same list structure as
#' the input object, but with \code{A}, \code{U}, and \code{F} elements
#' replaced with lists of historically-structured matrices, and with element
#' \code{hstages} changed from \code{NA} to an index of stage pairs
#' corresponding to the rows and columns of the new matrices. If
#' \code{err_check = TRUE}, then a list of three data frames showing the values
#' used to determine matrix element index values is also exported.
#' 
#' @section Notes:
#' This function does not currently identify biologically impossible
#' transitions. Ahistorical transition values are placed in all theoretically
#' possible historical transitions.
#' 
#' @examples
#' sizevector <- c(1, 1, 2, 3)
#' stagevector <- c("Sdl", "Veg", "SmFlo", "LFlo")
#' repvector <- c(0, 0, 1, 1)
#' obsvector <- c(1, 1, 1, 1)
#' matvector <- c(0, 1, 1, 1)
#' immvector <- c(1, 0, 0, 0)
#' propvector <- c(0, 0, 0, 0)
#' indataset <- c(1, 1, 1, 1)
#' binvec <- c(0.5, 0.5, 0.5, 0.5)
#' 
#' anthframe <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector,
#'   immstatus = immvector, indataset = indataset, binhalfwidth = binvec,
#'   propstatus = propvector)
#' 
#' # POPN C 2003-2004
#' XC3 <- matrix(c(0, 0, 1.74, 1.74,
#' 0.208333333, 0, 0, 0.057142857,
#' 0.041666667, 0.076923077, 0, 0,
#' 0.083333333, 0.076923077, 0.066666667, 0.028571429), 4, 4, byrow = TRUE)
#' 
#' # 2004-2005
#' XC4 <- matrix(c(0, 0, 0.3, 0.6,
#' 0.32183908, 0.142857143, 0, 0,
#' 0.16091954, 0.285714286, 0, 0,
#' 0.252873563, 0.285714286, 0.5, 0.6), 4, 4, byrow = TRUE)
#' 
#' mats_list <- list(XC3, XC4)
#' yr_ord <- c(1, 2)
#' pch_ord <- c(1, 1)
#' 
#' anth_lefkoMat <- create_lM(mats_list, anthframe, hstages = NA, historical = FALSE,
#'   poporder = 1, patchorder = pch_ord, yearorder = yr_ord)
#'   
#' nullmodel1 <- hist_null(anth_lefkoMat, 1) # Ehrlen format
#' nullmodel2 <- hist_null(anth_lefkoMat, 2) # deVries format
#' 
#' @export hist_null
hist_null <- function(mpm, format = 1L, err_check = FALSE) {
    .Call('_lefko3_hist_null', PACKAGE = 'lefko3', mpm, format, err_check)
}

#' Estimate Mean Projection Matrices
#' 
#' Function \code{lmean()} estimates mean projection matrices as element-wise
#' arithmetic means. It produces \code{lefkoMat} objects if provided with them,
#' or single matrices in a simple one-element list if provided a list of
#' matrices.
#' 
#' @name lmean
#' 
#' @param mats A \code{lefkoMat} object, or a list of square matrices of equal
#' dimension.
#' @param matsout A string identifying which means to estimate. Option
#' \code{"pop"} indicates population-level only, \code{"patch"} indicates
#' patch-level only, and \code{"all"} indicates that both patch- and
#' population-level means should be estimated. Defaults to \code{"all"}.
#' @param force_sparse A logical value identifying whether to output the mean
#' matrices in sparse format, if input as standard matrices.
#' 
#' @return Yields a \code{lefkoMat} object with the following characteristics:
#' 
#' \item{A}{A list of full mean projection matrices in order of sorted
#' populations, patches, and years. These are typically estimated as the sums
#' of the associated mean \code{U} and \code{F} matrices. All matrices output
#' in either the \code{matrix} class, or the \code{dgCMatrix} class.}
#' \item{U}{A list of mean survival-transition matrices sorted as in \code{A}.
#' All matrices output in the \code{matrix} class.}
#' \item{F}{A list of mean fecundity matrices sorted as in \code{A}. All
#' matrices output in the \code{matrix} class.}
#' \item{hstages}{A data frame showing the pairing of ahistorical stages used
#' to create historical stage pairs. Given if the MPM is historical.}
#' \item{ahstages}{A data frame detailing the characteristics of associated
#' ahistorical stages.}
#' \item{labels}{A data frame detailing the order of population, patch, and
#' year of each mean matrix. If \code{pop}, \code{patch}, or \code{year2} are
#' \code{NA} in the original \code{labels} set, then these will be re-labeled
#' as \code{A}, \code{1}, or \code{1}, respectively.}
#' \item{matrixqc}{A short vector describing the number of non-zero elements in
#' \code{U} and \code{F} mean matrices, and the number of annual matrices.}
#' \item{modelqc}{This is the \code{qc} portion of the \code{modelsuite} input.
#' Only output from \code{lefkoMat} objects resulting from function-based
#' estimation.}
#' \item{dataqc}{A vector showing the numbers of individuals and rows in the
#' vertical dataset used as input. Only output from \code{lefkoMat} objects
#' resulting from raw matrix estimation.}
#' 
#' @examples
#' data(cypdata)
#' 
#' sizevector <- c(0, 0, 0, 0, 0, 0, 1, 2.5, 4.5, 8, 17.5)
#' stagevector <- c("SD", "P1", "P2", "P3", "SL", "D", "XSm", "Sm", "Md", "Lg",
#'   "XLg")
#' repvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' obsvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' matvector <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' immvector <- c(0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 0, 0, 0, 0, 0.5, 0.5, 1, 1, 2.5, 7)
#' 
#' cypframe_raw <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector,
#'   propstatus = propvector, immstatus = immvector, indataset = indataset,
#'   binhalfwidth = binvec)
#' 
#' cypraw_v1 <- verticalize3(data = cypdata, noyears = 6, firstyear = 2004,
#'   patchidcol = "patch", individcol = "plantid", blocksize = 4,
#'   sizeacol = "Inf2.04", sizebcol = "Inf.04", sizeccol = "Veg.04",
#'   repstracol = "Inf.04", repstrbcol = "Inf2.04", fecacol = "Pod.04",
#'   stageassign = cypframe_raw, stagesize = "sizeadded", NAas0 = TRUE,
#'   NRasRep = TRUE)
#' 
#' cypsupp2r <- supplemental(stage3 = c("SD", "P1", "P2", "P3", "SL", "D", 
#'     "XSm", "Sm", "SD", "P1"),
#'   stage2 = c("SD", "SD", "P1", "P2", "P3", "SL", "SL", "SL", "rep",
#'     "rep"),
#'   eststage3 = c(NA, NA, NA, NA, NA, "D", "XSm", "Sm", NA, NA),
#'   eststage2 = c(NA, NA, NA, NA, NA, "XSm", "XSm", "XSm", NA, NA),
#'   givenrate = c(0.10, 0.20, 0.20, 0.20, 0.25, NA, NA, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, NA, NA, NA, NA, 0.5, 0.5),
#'   type =c(1, 1, 1, 1, 1, 1, 1, 1, 3, 3),
#'   stageframe = cypframe_raw, historical = FALSE)
#' 
#' cypmatrix2r <- rlefko2(data = cypraw_v1, stageframe = cypframe_raw, 
#'   year = "all", patch = "all", stages = c("stage3", "stage2", "stage1"),
#'   size = c("size3added", "size2added"), supplement = cypsupp2r,
#'   yearcol = "year2", patchcol = "patchid", indivcol = "individ")
#' 
#' cyp2mean <- lmean(cypmatrix2r)
#' 
#' @export
lmean <- function(mats, matsout = NULL, force_sparse = FALSE) {
    .Call('_lefko3_lmean', PACKAGE = 'lefko3', mats, matsout, force_sparse)
}

#' Add a New Stage to an Existing LefkoMat Object
#' 
#' Function \code{add_stage()} adds a new stage to an existing \code{lefkoMat}
#' object. In addition to altering the \code{ahstages} object within the MPM,
#' it alters the \code{hstages} and \code{agestages} objects and adds the
#' appropriate number of new rows and columns depending on the kind of MPM
#' input.
#' 
#' @name add_stage
#' 
#' @param mpm The \code{lefkoMat} object to add a stage to.
#' @param add_before The index of the stage to insert a new stage before. This
#' index should be derived from the \code{ahstages} of the input \code{mpm}.
#' Cannot be set if \code{add_after} is to be used.
#' @param add_after The index of the stage to insert a new stage after. This
#' index should be derived from the \code{ahstages} of the input \code{mpm}.
#' Cannot be set if \code{add_before} is to be used.
#' @param stage_name The name of the new stage to add. Defaults to
#' \code{new_stage}. 
#' 
#' @return A new copy of the original MPM edited to include new rows and
#' columns in the associated matrices, and with \code{ahstages},
#' \code{agestages}, and \code{hstages} objects edited to include the new
#' stage.
#' 
#' @seealso \code{\link{edit_lM}()}
#' 
#' @examples
#' data(cypdata)
#' 
#' cyp_lesl_data <- verticalize3(data = cypdata, noyears = 6, firstyear = 2004, 
#'   patchidcol = "patch", individcol = "plantid", blocksize = 4, 
#'   sizeacol = "Inf2.04", sizebcol = "Inf.04", sizeccol = "Veg.04", 
#'   repstracol = "Inf.04", repstrbcol = "Inf2.04", fecacol = "Pod.04", 
#'   stagesize = "sizeadded", NAas0 = TRUE, age_offset = 2)
#' 
#' cyp_lesl_vital <- modelsearch(cyp_lesl_data, historical = FALSE,
#'   approach = "mixed", suite = "cons", bestfit = "AICc&k", age = "obsage",
#'   vitalrates = c("surv", "fec"), fecdist = "poisson", indiv = "individ",
#'   year = "year2", year.as.random = TRUE, patch.as.random = TRUE,
#'   show.model.tables = TRUE, fec.zero = TRUE, global.only = TRUE,
#'   test.age = TRUE, quiet = "partial")
#' 
#' germination <- 0.08
#' protocorm_to_seedling <- 0.10
#' seeding_to_adult <- 0.20
#' seeds_per_fruit <- 8000
#' 
#' cyp_lesl_supp <- supplemental(historical = FALSE, stagebased = FALSE,
#'   agebased = TRUE, age2 = c(1, 2), type = c(1, 1),
#'   givenrate = c(protocorm_to_seedling, seeding_to_adult))
#' 
#' cyp_lesl_fb_mpm <- fleslie(data = cyp_lesl_data,
#'   modelsuite = cyp_lesl_vital, last_age = 7, fecage_min = 3,
#'   fecmod = (germination * seeds_per_fruit), supplement = cyp_lesl_supp)
#' 
#' altered1 <- add_stage(cyp_lesl_fb_mpm, add_before = 1, stage_name = "DS")
#' 
#' @export add_stage
add_stage <- function(mpm, add_before = 0L, add_after = 0L, stage_name = NULL) {
    .Call('_lefko3_add_stage', PACKAGE = 'lefko3', mpm, add_before, add_after, stage_name)
}

#' Create Stageframe for Population Matrix Projection Analysis
#' 
#' Function \code{sf_leslie()} returns a data frame describing each age in a
#' Leslie MPM in terms of ahistorical stage information. This function is
#' internal to \code{rleslie()} and \code{fleslie()}.
#' 
#' @name sf_leslie
#' 
#' @param min_age The first age to include in the matrix.
#' @param max_age The maximum age to include in the matrix.
#' @param min_fecage The first age in which reproduction is possible.
#' @param max_fecage The final age in which reproduction is possible.
#' @param cont A logical value indicating whether survival continues past the
#' last described age.
#' 
#' @return A data frame of class \code{stageframe}, which includes information
#' on the stage name, size, reproductive status, observation status, propagule 
#' status, immaturity status, maturity status, presence within the core dataset, 
#' stage group classification, raw bin half-width, and the minimum, 
#' center, and maximum of each size bin, as well as its width. If minimum and
#' maximum ages were specified, then these are also included. Also includes an 
#' empty string variable that can be used to describe stages meaningfully.
#' 
#' Variables in this data frame include the following:
#' \item{stage_id}{An unique integer representing each age, in order.}
#' \item{stage}{The unique names of the ages to be analyzed.}
#' \item{original_size}{The typical or representative size at which each stage
#' occurs. Since ages are not characterized by size, this is generally
#' \code{NA}.}
#' \item{original_size_b}{Size at which each stage occurs in terms of a second
#' size variable, if one exists. In Leslie MPMs, generally \code{NA}.}
#' \item{original_size_c}{Size at which each stage occurs in terms of a third
#' size variable, if one exists. In Leslie MPMs, generally \code{NA}.}
#' \item{min_age}{The minimum age at which the stage may occur. In Leslie MPMs,
#' defaults to the current age.}
#' \item{max_age}{The maximum age at which the stage may occur. In Leslie MPMs,
#' will generally equal the current age or \code{NA}, depending on whether
#' individuals are allowed to remain at the maximum age.}
#' \item{repstatus}{A binomial variable showing whether each age is
#' reproductive.}
#' \item{obsstatus}{A binomial variable showing whether each age is
#' observable.}
#' \item{propstatus}{A binomial variable showing whether each age is a
#' propagule.}
#' \item{immstatus}{A binomial variable showing whether each age can occur as
#' immature.}
#' \item{matstatus}{A binomial variable showing whether each age occurs in
#' maturity.}
#' \item{entrystage}{A binomial variable showing whether each age is an entry
#' stage. In Leslie MPMs, only the first stage is set to \code{1}, while all
#' others are set to \code{0}.}
#' \item{indataset}{A binomial variable describing whether each age occurs in
#' the input dataset.}
#' \item{binhalfwidth_raw}{The half-width of the size bin, as input.}
#' \item{sizebin_min}{The minimum primary size at which the age may occur.}
#' \item{sizebin_max}{The maximum primary size at which the age may occur.}
#' \item{sizebin_center}{The midpoint of the primary size bin at which the age
#' may occur.}
#' \item{sizebin_width}{The width of the primary size bin corresponding to the
#' age.}
#' \item{binhalfwidthb_raw}{The half-width of the size bin of a second size
#' variable, as input.}
#' \item{sizebinb_min}{The minimum secondary size at which the age may occur.}
#' \item{sizebinb_max}{The maximum secondary size at which the age may occur.}
#' \item{sizebinb_center}{The midpoint of the secondary size bin at which the
#' age may occur.}
#' \item{sizebinb_width}{The width of the secondary size bin corresponding to
#' the age.}
#' \item{binhalfwidthc_raw}{The half-width of the size bin of a third size
#' variable, as input.}
#' \item{sizebinc_min}{The minimum tertiary size at which the age may occur.}
#' \item{sizebinc_max}{The maximum tertiary size at which the age may occur.}
#' \item{sizebinc_center}{The midpoint of the tertiary size bin at which the
#' age may occur.}
#' \item{sizebinc_width}{The width of the tertiary size bin corresponding to
#' the age.}
#' \item{group}{An integer denoting the size classification group that the
#' age falls within.}
#' \item{comments}{A text field for stage descriptions.}
#' \item{alive}{An integer vector denoting whether the age is alive. Defaults
#' to \code{1} for all ages.}
#' \item{almost_born}{An integer vector denoting whether the age corresponds to
#' the prior stage of a newly produced individual in a historical model. In
#' Leslie MPMs, defaults to \code{0}.}
#' 
#' @keywords internal
#' @noRd
NULL

#' Create hstages Index Object
#' 
#' Function \code{hst_maker()} creates \code{hstages} index data frames from
#' \code{stageframe} inputs.
#' 
#' @name hst_maker
#' 
#' @param sframe The ahistorical stageframe used in MPM development.
#' 
#' @return A data frame with the following columns:
#' \item{stage_id_2}{Integer index of stage in time \emph{t}+1.}
#' \item{stage_id_1}{Integer index of stage in time \emph{t}.}
#' \item{stage_2}{String name of stage in time \emph{t}+1.}
#' \item{stage_1}{String name of stage in time \emph{t}.}
#' 
#' @keywords internal
#' @noRd
NULL

#' Create agestages Index Object
#' 
#' Function \code{age_maker()} creates \code{agestages} index data frames from
#' \code{stageframe} inputs.
#' 
#' @name age_maker
#' 
#' @param sframe The ahistorical stageframe used in MPM development.
#' 
#' @return A data frame with the following columns:
#' \item{stage_id}{Integer index of stage.}
#' \item{stage}{String name of stage.}
#' \item{age}{The age of stage in current time.}
#' 
#' @keywords internal
#' @noRd
NULL

#' Create Element Index for Matrix Estimation
#' 
#' Function \code{theoldpizzle()} creates a data frame object used by 
#' functions \code{specialpatrolgroup()}, \code{normalpatrolgroup()},
#' \code{subvertedpatrolgroup()}, and \code{jerzeibalowski()} to estimate
#' raw and function-based matrices.
#' 
#' @name theoldpizzle
#'
#' @param StageFrame The stageframe object identifying the life history model
#' being operationalized.
#' @param OverWrite The supplement or overwrite table used in analysis, as
#' modified by \code{sf_reassess()}.
#' @param repmatrix The reproductive matrix used in analysis.
#' @param firstage The first age to be used in the analysis. Should typically
#' be \code{0} for pre-breeding and \code{1} for post-breeding life history
#' models. If not building age-by-stage MPMs, then should be set to \code{0}.
#' @param finalage The final age to be used in analysis. If not building
#' age-by-stage MPMs, then should be set to \code{0}.
#' @param format Indicates whether historical matrices should be in (\code{1})
#' Ehrlen or (\code{2}) deVries format.
#' @param style The style of analysis, where \code{0} is historical, \code{1}
#' is ahistorical, and \code{2} is age-by-stage.
#' @param cont Denotes whether age-by-stage matrix continues past the final
#' age.
#' @param filter An integer denoting whether to filter the output data frame to
#' eliminate unusable rows, and if so, how to do so. Possible values: \code{0}:
#' no filtering, \code{1}: filter out rows with \code{index321 == -1}, and
#' \code{2}: filter out rows with \code{aliveandequal == -1}.
#' 
#' @return The output is a large data frame describing every element to be
#' estimated in matrices.
#' 
#' @keywords internal
#' @noRd
NULL

#' Estimate All Elements of Raw Historical Matrix
#' 
#' Function \code{specialpatrolgroup()} swiftly calculates matrix transitions
#' in raw historical matrices, and serves as the core workhorse function behind
#' \code{rlefko3()}.
#' 
#' @name specialpatrolgroup
#' 
#' @param sge9l The Allstages data frame developed for \code{rlefko3()}
#' covering stage pairs across times \emph{t}+1, \emph{t} and \emph{t}-1.
#' Generally termed \code{stageexpansion9}.
#' @param sge3index21 Integer index vector of stages in times \emph{t}-1 and
#' \emph{t}, from \code{stageexpansion3}.
#' @param MainData The demographic dataset modified to hold \code{usedfec}
#' columns.
#' @param StageFrame The full stageframe for the analysis.
#' @param format Indicates whether to output Ehrlen-format hMPMs (\code{1}) or
#' deVries-format hMPMs (\code{2}).
#' @param err_switch A logical value. If set to \code{TRUE}, then will also
#' output \code{probsrates} and \code{stage2fec}. Defaults to \code{FALSE}.
#' @param loypop A string vector giving the order of populations in the list of
#' years.
#' @param loypatch A string vector giving the order of patches in the list of
#' years.
#' @param loyyear2 A string vector giving the order of years at time \emph{t}
#' in the list of years.
#' @param yearorder The integer year order corresponding to \code{loyyear2}.
#' @param pop_var_int The variable number coding for population in the main
#' data set.
#' @param patch_var_int The variable number coding for patch in the main data
#' set.
#' @param year_var_int The variable number coding for year in time \emph{t} in
#' the main data set.
#' @param loy_pop_used A logical value indicating whether the population
#' variable is to be used.
#' @param loy_patch_used A logical value indicating whether the patch variable
#' is to be used.
#' @param simplicity If \code{TRUE}, then only outputs matrices \code{U} and
#' \code{F}, rather than also outputting matrix \code{A}. Defaults to
#' \code{FALSE}.
#' @param sparse If \code{TRUE}, then output will be in sparse matrix format.
#' Defaults to \code{FALSE}.
#' 
#' @return If \code{err_switch = FALSE}, then will return a list of three
#' matrices, including the survival-transition (\code{U}) matrix, the fecundity
#' matrix (\code{F}), and the sum (\code{A}) matrix, with the \code{A} matrix
#' first, followed by the \code{ahstages}, \code{agestages}, \code{hstages},
#' and \code{labels} data frames, and the \code{matrixqc} and \code{dataqc}
#' vectors. If \code{err_switch = TRUE}, then will also output four further
#' elements: \code{probsrates_all} and \code{stage2fec_all}. The former is a
#' matrix composed of the following vectors in order: \code{sge9index321},
#' which gives the historical index number for each transition possible and
#' in order (from \code{stageexpansion9}); \code{aliveandequal}, which gives
#' the element index in the matrix associated with that transition (or
#' \code{-1} if the transition is impossible); \code{probsrates0}, which gives
#' the total number of individuals counted for a particular historical
#' transition; \code{probsrates1}, which gives the total number of individuals
#' associated with a particular paired stage in times \emph{t}-1 and \emph{t};
#' \code{probsrates2}, which gives the total number of individuals for each
#' paired stage in times \emph{t}-1 and \emph{t} that survive into time
#' \emph{t}+1; \code{probsrates3}, which gives the total fecundity found for
#' the historical transition; \code{sge9fec32}, which gives the predicted
#' reproductive status of the historical transition as given in the
#' \code{repmatrix}; \code{probsrates0p}, which is \code{probsrates0} but
#' assuming a prior stage; \code{probsrates1p}, which is \code{probsrates1} but
#' assuming a prior stage; \code{probsrates2p}, which is \code{probsrates2} but
#' assuming a prior stage; and \code{probsrates3p}, which is \code{probsrates3}
#' but assuming a prior stage. Element \code{stage2fec_all} is a matrix
#' composed of two vectors: \code{stage2fec} is the fecundity associated with
#' each paired historical stage, and \code{stage2fecp} is the equivalent
#' assuming a prior stage. The final two elements are \code{dataindex321_prior}
#' and the edited dataset.
#' 
#' @keywords internal
#' @noRd
NULL

#' Estimate All Elements of Raw Ahistorical Population Projection Matrix
#' 
#' Function \code{normalpatrolgroup()} swiftly calculates matrix transitions
#' in raw ahistorical matrices, and serves as the core workhorse function
#' behind \code{rlefko2()}.
#' 
#' @name normalpatrolgroup
#' 
#' @param sge3 The Allstages data frame developed for \code{rlefko2()} covering
#' stage pairs across times \emph{t}+1 and \emph{t}. Generally termed
#' \code{stageexpansion3}.
#' @param sge2stage2 An integer index vector giving the stage in time \emph{t},
#' from \code{stageexpansion2}.
#' @param MainData The demographic dataset modified to hold \code{usedfec} and
#' \code{usedstage} columns.
#' @param StageFrame The full stageframe for the analysis.
#' @param err_switch A logical value. If set to \code{TRUE}, then will also
#' output \code{probsrates}, \code{stage2fec}, and the edited dataset.
#' @param loypop A string vector giving the order of populations in the list of
#' years.
#' @param loypatch A string vector giving the order of patches in the list of
#' years.
#' @param loyyear2 A string vector giving the order of years at time \emph{t}
#' in the list of years.
#' @param yearorder The integer year order corresponding to \code{loyyear2}.
#' @param pop_var_int The variable number coding for population in the main
#' data set.
#' @param patch_var_int The variable number coding for patch in the main data
#' set.
#' @param year_var_int The variable number coding for year in time \emph{t} in
#' the main data set.
#' @param loy_pop_used A logical value indicating whether the population
#' variable is to be used.
#' @param loy_patch_used A logical value indicating whether the patch variable
#' is to be used.
#' @param simplicity If \code{TRUE}, then only outputs matrices \code{U} and
#' \code{F}, rather than also outputting matrix \code{A}. Defaults to
#' \code{FALSE}.
#' @param sparse If \code{TRUE}, then output will be in sparse matrix format.
#' Defaults to \code{FALSE}.
#' 
#' @return In the standard output, a list of three lists, called \code{A},
#' \code{U}, and \code{F}, each containing A, U, or F matrices, respectively.
#' Further information on the output is provided in the documentation for
#' \code{specialpatrolgroup()}.
#' 
#' @keywords internal
#' @noRd
NULL

#' Estimate All Elements of Raw Ahistorical Population Projection Matrix
#' 
#' Function \code{minorpatrolgroup()} swiftly calculates matrix transitions
#' in raw Leslie MPMs, and is used internally in \code{rleslie()}.
#' 
#' @name minorpatrolgroup
#' 
#' @param MainData The demographic dataset modified internally to have needed
#' variables for living status, reproduction status, and fecundity.
#' @param StageFrame The full stageframe for the analysis.
#' @param supplement A supplement table as produced by function
#' \code{supplemental()} and edited and age-expanded by pre-processing within
#' function \code{mpm_create()}.
#' @param start_age An integer denoting the first age incorporated in the MPM.
#' @param last_age An integer denoting the last age incorporated in the MPM,
#' not including ages set to equal the last estimated age.
#' @param cont Should a self-loop transition be estimated for the final age.
#' @param fec_mod A multiplier on raw fecundity to estimate true fecundity.
#' @param err_switch A logical value. If set to \code{TRUE}, then will also
#' output \code{probsrates} and \code{stage2fec}.
#' @param loypop A string vector giving the order of populations in the list of
#' years.
#' @param loypatch A string vector giving the order of patches in the list of
#' years.
#' @param loyyear2 A string vector giving the order of years at time \emph{t}
#' in the list of years.
#' @param yearorder The integer year order corresponding to \code{loyyear2}.
#' @param pop_var_int The variable number coding for population in the main
#' data set.
#' @param patch_var_int The variable number coding for patch in the main data
#' set.
#' @param year_var_int The variable number coding for year in time \emph{t} in
#' the main data set.
#' @param loy_pop_used A logical value indicating whether the population
#' variable is to be used.
#' @param loy_patch_used A logical value indicating whether the patch variable
#' is to be used.
#' @param simplicity If \code{TRUE}, then only outputs matrices \code{U} and
#' \code{F}, rather than also outputting matrix \code{A}. Defaults to
#' \code{FALSE}.
#' @param sparse If \code{TRUE}, then output will be in sparse matrix format.
#' Defaults to \code{FALSE}.
#' 
#' @return List of three matrices, including the survival-transition (\code{U})
#' matrix, the fecundity matrix (\code{F}), and the sum (\code{A}) matrix, with
#' the \code{A} matrix first. Further information on outputs is provided in the
#' documentation for \code{specialpatrolgroup()}.
#' 
#' @keywords internal
#' @noRd
NULL

#' Estimate All Elements of Raw Age-By-Stage Population Projection Matrix
#' 
#' Function \code{subvertedpatrolgroup()} swiftly calculates matrix
#' transitions in raw age-by-stage matrices, and serves as the core workhorse
#' function behind \code{arlefko2()}.
#' 
#' @name subvertedpatrolgroup
#' 
#' @param sge3 The Allstages data frame developed for \code{rlefko2()} covering
#' stage pairs across times \emph{t}+1 and \emph{t}. Generally termed
#' \code{stageexpansion3}.
#' @param sge2index21 An integer index vector of stage in times \emph{t}-1 and
#' \emph{t} from \code{stageexpansion2}.
#' @param MainData The demographic dataset modified to hold \code{usedfec} and
#' \code{usedstage} columns.
#' @param StageFrame The full stageframe for the analysis.
#' @param firstage The first true age to start the matrix with.
#' @param finalage The last true age to estimate.
#' @param cont A logical value indicating whether to lump survival past the
#' last age into a final age transition set on the supermatrix diagonal.
#' @param err_switch A logical value. If set to \code{TRUE}, then will also
#' output \code{probsrates} and \code{stage2fec}.
#' @param loypop A string vector giving the order of populations in the list of
#' years.
#' @param loypatch A string vector giving the order of patches in the list of
#' years.
#' @param loyyear2 A string vector giving the order of years at time \emph{t}
#' in the list of years.
#' @param yearorder The integer year order corresponding to \code{loyyear2}.
#' @param pop_var_int The variable number coding for population in the main
#' data set.
#' @param patch_var_int The variable number coding for patch in the main data
#' set.
#' @param year_var_int The variable number coding for year in time \emph{t} in
#' the main data set.
#' @param loy_pop_used A logical value indicating whether the population
#' variable is to be used.
#' @param loy_patch_used A logical value indicating whether the patch variable
#' is to be used.
#' @param simplicity If \code{TRUE}, then only outputs matrices \code{U} and
#' \code{F}, rather than also outputting matrix \code{A}. Defaults to
#' \code{FALSE}.
#' @param sparse If \code{TRUE}, then outputs matrices in sparse format.
#' Defaults to \code{FALSE}.
#' 
#' @return In the standard output, a list of three lists, called \code{A},
#' \code{U}, and \code{F}, each containing A, U, or F matrices, respectively.
#' Further information on outputs is provided in the documentation for
#' \code{specialpatrolgroup()}.
#' 
#' @keywords internal
#' @noRd
NULL

#' Key Function Passing Models and Other Parameters to Matrix Estimators
#' 
#' Function \code{raymccooney()} takes the various vital rate models and other
#' parameters and coordinates them as input into the function-based matrix
#' estimation functions.
#' 
#' @name raymccooney
#' 
#' @param listofyears A data frame where the rows designate the exact order of
#' years and patches to produce matrices for.
#' @param modelsuite An object of class \code{lefkoMod}, a similarly structured
#' list object, or a \code{vrm_input} object. All 14 vital rate models and the
#' \code{paramnames} data frame are required if not using a \code{vrm_input}
#' object.
#' @param mainyears A string vector of all times at time \emph{t}.
#' @param mainpatches A string vector of patch names.
#' @param maingroups A string vector of stage group names.
#' @param mainindcova Typically a string vector of individual covariate
#' category names.
#' @param mainindcovb Typically a string vector of individual covariate
#' category names.
#' @param mainindcovc Typically a string vector of individual covariate
#' category names.
#' @param StageFrame The stageframe object identifying the life history model
#' being operationalized.
#' @param OverWrite The supplement or overwrite table used in analysis, as
#' modified by \code{.sf_reassess()} (which technically uses function
#' \code{supp_reassess()}). Must be processed via \code{.supp_reassess} rather
#' than being a raw overwrite or supplement table.
#' @param repmatrix The reproductive matrix used in analysis.
#' @param f2_inda_num A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual covariate \code{a} at
#' each time \emph{t} to be used in analysis.
#' @param f1_inda_num A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual covariate \code{a} at
#' each time \emph{t}-1 to be used in analysis.
#' @param f2_indb_num A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual covariate \code{b} at
#' each time \emph{t} to be used in analysis.
#' @param f1_indb_num A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual covariate \code{b} at
#' each time \emph{t}-1 to be used in analysis.
#' @param f2_indc_num A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual covariate \code{c} at
#' each time \emph{t} to be used in analysis.
#' @param f1_indc_num A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual covariate \code{c} at
#' each time \emph{t}-1 to be used in analysis.
#' @param f2_inda_cat A string vector of length equal to the number of years,
#' holding categories of individual covariate \code{a} at each time \emph{t} to
#' be used in analysis.
#' @param f1_inda_cat A string vector of length equal to the number of years,
#' holding categories of individual covariate \code{a} at each time \emph{t-1}
#' to be used in analysis.
#' @param f2_indb_cat A string vector of length equal to the number of years,
#' holding categories of individual covariate \code{b} at each time \emph{t} to
#' be used in analysis.
#' @param f1_indb_cat A string vector of length equal to the number of years,
#' holding categories of individual covariate \code{b} at each time \emph{t-1}
#' to be used in analysis.
#' @param f2_indc_cat A string vector of length equal to the number of years,
#' holding categories of individual covariate \code{c} at each time \emph{t} to
#' be used in analysis.
#' @param f1_indc_cat A string vector of length equal to the number of years,
#' holding categories of individual covariate \code{c} at each time \emph{t-1}
#' to be used in analysis.
#' @param r2_inda A string vector of length equal to the number of years,
#' holding categories of individual random covariate \code{a} at each time
#' \emph{t} to be used in analysis.
#' @param r1_inda A string vector of length equal to the number of years,
#' holding categories of individual random covariate \code{a} at each time
#' \emph{t-1} to be used in analysis.
#' @param r2_indb A string vector of length equal to the number of years,
#' holding categories of individual random covariate \code{b} at each time
#' \emph{t} to be used in analysis.
#' @param r1_indb A string vector of length equal to the number of years,
#' holding categories of individual random covariate \code{b} at each time
#' \emph{t-1} to be used in analysis.
#' @param r2_indc A string vector of length equal to the number of years,
#' holding categories of individual random covariate \code{c} at each time
#' \emph{t} to be used in analysis.
#' @param r1_indc A string vector of length equal to the number of years,
#' holding categories of individual random covariate \code{c} at each time
#' \emph{t-1} to be used in analysis.
#' @param dev_terms A numeric vector containing the deviations to the linear
#' models input by the user. The order is: survival, observation status, size,
#' size_b, size_c, reproductive status, fecundity, juvenile survival, juvenile
#' observation status, juvenile size, juvenile size_b, juvenile size_c,
#' juvenile reproductive status, and juvenile maturity status.
#' @param dens A numeric value equal to the density to be used in calculations.
#' @param fecmod A scalar multiplier for fecundity.
#' @param firstage The first age to be used in the analysis. Should typically
#' be \code{0} for pre-breeding and \code{1} for post-breeding life history
#' models. If not building age-by-stage MPMs, then should be set to \code{0}.
#' @param finalage The final age to be used in analysis. If not building
#' age-by-stage MPMs, then should be set to \code{0}.
#' @param format Indicates whether historical matrices should be in (1) Ehrlen
#' or (2) deVries format.
#' @param style The style of analysis, where 0 is historical, 1 is ahistorical,
#' and 2 is age-by-stage.
#' @param cont Denotes whether age-by-stage matrix continues past the final
#' age.
#' @param filter An integer denoting whether to filter the DataFrame to
#' eliminate unusable rows, and if so, how to do so. Possible values: \code{0}:
#' no filtering, \code{1}: filter out rows with \code{index321 == -1}, and
#' \code{2}: filter out rows with \code{aliveandequal == -1}.
#' @param negfec A logical value denoting whether to change negative estimated
#' fecundity to 0. Defaults to \code{FALSE}.
#' @param nodata A logical value indicating whether the modelsuite contains
#' all parameter coefficients and no hfv dataset is provided (\code{TRUE}), or
#' whether an hfv dataset and a true modelsuite are provided (\code{FALSE}).
#' Defaults to \code{FALSE}.
#' @param exp_tol A numeric value indicating the maximum limit for the
#' \code{exp()} function to be used in vital rate calculations. Defaults to
#' \code{700.0}.
#' @param theta_tol A numeric value indicating a maximum value for theta in
#' negative binomial probability density estimation. Defaults to
#' \code{100000000.0}.
#' @param cdf A logical value indicating whether to estimate size transitions
#' using the cumulative density function in cases with continuous
#' distributions. Defaults to \code{TRUE}, with the midpoint method used if
#' \code{FALSE}.
#' @param err_check If \code{TRUE}, then also output objects \code{prob_out}
#' and \code{allstages} for error checking purposes.
#' @param simplicity If \code{TRUE}, then only outputs matrices \code{U} and
#' \code{F}, rather than also outputting matrix \code{A}. Defaults to
#' \code{FALSE}.
#' @param sparse If \code{TRUE}, then outputs matrices in sparse format.
#' Defaults to \code{FALSE}.
#' 
#' @return A list with with up to 5 elements. In order: \code{A}: a list of A
#' matrices, or a list of \code{NULL} values if \code{simplicity = TRUE};
#' \code{U}: a list of U matrices, in the same order as \code{A}; \code{F}:
#' a list of F matrices, in the same order as \code{A}; \code{prob_out}: a list
#' of error-checking conditional probability matrices, or a list of \code{NULL}
#' values if \code{err_check = FALSE}; and \code{allstages}: a data frame
#' showing the used values of all variables used in transition calculations.
#' 
#' @keywords internal
#' @noRd
NULL

#' Function Passing Models and Other Parameters to Leslie Matrix Estimator
#' 
#' This function takes the various vital rate models and other parameters and
#' coordinates them as input into function \code{fleslie()}.
#' 
#' @name mothermccooney
#' 
#' @param listofyears A data frame where the rows designate the exact order of
#' years and patches to produce matrices for.
#' @param modelsuite An object of class \code{lefkoMod}, a similarly structured
#' list object, or a \code{vrm_input} object. Survival model, fecundity model,
#' and the \code{paramnames} data frame are required if not using a
#' \code{vrm_input} object.
#' @param actualages An integer vector of all actual ages to be included in the
#' matrices, in order.
#' @param mainyears A numeric vector of all times at time \emph{t}.
#' @param mainpatches A string vector of patch names.
#' @param maingroups A string vector of stage group names.
#' @param mainindcova Typically a string vector of individual covariate
#' category names.
#' @param mainindcovb Typically a string vector of individual covariate
#' category names.
#' @param mainindcovc Typically a string vector of individual covariate
#' category names.
#' @param ageframe The modified stageframe used in matrix calculations.
#' @param supplement The supplement table used in analysis, as modified by
#' \code{age_expanded()} and other pre-MPM processing.
#' @param f2_inda_num A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual covariate \code{a} at
#' each time \emph{t} to be used in analysis.
#' @param f1_inda_num A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual covariate \code{a} at
#' each time \emph{t}-1 to be used in analysis.
#' @param f2_indb_num A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual covariate \code{b} at
#' each time \emph{t} to be used in analysis.
#' @param f1_indb_num A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual covariate \code{b} at
#' each time \emph{t}-1 to be used in analysis.
#' @param f2_indc_num A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual covariate \code{c} at
#' each time \emph{t} to be used in analysis.
#' @param f1_indc_num A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual covariate \code{c} at
#' each time \emph{t}-1 to be used in analysis.
#' @param f2_inda_cat A string vector of length equal to the number of years,
#' holding categories of individual covariate \code{a} at each time \emph{t} to
#' be used in analysis.
#' @param f1_inda_cat A string vector of length equal to the number of years,
#' holding categories of individual covariate \code{a} at each time \emph{t-1}
#' to be used in analysis.
#' @param f2_indb_cat A string vector of length equal to the number of years,
#' holding categories of individual covariate \code{b} at each time \emph{t} to
#' be used in analysis.
#' @param f1_indb_cat A string vector of length equal to the number of years,
#' holding categories of individual covariate \code{b} at each time \emph{t-1}
#' to be used in analysis.
#' @param f2_indc_cat A string vector of length equal to the number of years,
#' holding categories of individual covariate \code{c} at each time \emph{t} to
#' be used in analysis.
#' @param f1_indc_cat A string vector of length equal to the number of years,
#' holding categories of individual covariate \code{c} at each time \emph{t-1}
#' to be used in analysis.
#' @param r2_inda A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual random covariate
#' \code{a} at each time \emph{t} to be used in analysis.
#' @param r1_inda A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual random covariate
#' \code{a} at each time \emph{t}-1 to be used in analysis.
#' @param r2_indb A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual random covariate
#' \code{b} at each time \emph{t} to be used in analysis.
#' @param r1_indb A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual random covariate
#' \code{b} at each time \emph{t}-1 to be used in analysis.
#' @param r2_indc A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual random covariate
#' \code{c} at each time \emph{t} to be used in analysis.
#' @param r1_indc A numeric vector of length equal to the number of years,
#' holding values equal to the mean value of individual random covariate
#' \code{c} at each time \emph{t}-1 to be used in analysis.
#' @param dev_terms A numeric vector containing the deviations to the linear
#' models input by the user. The order is: survival, and fecundity.
#' @param dens A numeric value equal to the density to be used in calculations.
#' @param fecmod A scalar multiplier for fecundity.
#' @param finalage The final age to be used in analysis.
#' @param cont Denotes whether age-by-stage matrix continues past the final
#' age.
#' @param negfec A logical value denoting whether to change negative estimated
#' fecundity to 0. Defaults to \code{FALSE}.
#' @param nodata A logical value indicating whether the modelsuite contains
#' all parameter coefficients and no hfv dataset is provided (\code{TRUE}), or
#' whether an hfv dataset and a true modelsuite are provided (\code{FALSE}).
#' Defaults to \code{FALSE}.
#' @param exp_tol A numeric value indicating the maximum limit for the
#' \code{exp()} function to be used in vital rate calculations. Defaults to
#' \code{700.0}.
#' @param theta_tol A numeric value indicating a maximum value for theta in
#' negative binomial probability density estimation. Defaults to
#' \code{100000000.0}.
#' @param err_check If \code{TRUE}, then also output objects \code{prob_out}
#' and \code{allstages} for error checking purposes.
#' @param simplicity If \code{TRUE}, then only outputs matrices \code{U} and
#' \code{F}, rather than also outputting matrix \code{A}. Defaults to
#' \code{FALSE}.
#' @param sparse If \code{TRUE}, then outputs matrices in sparse format.
#' Defaults to \code{FALSE}.
#' 
#' @return A list with with up to 5 elements. In order: \code{A}: a list of A
#' matrices, or a list of \code{NULL} values if \code{simplicity = TRUE};
#' \code{U}: a list of U matrices, in the same order as \code{A}; \code{F}:
#' a list of F matrices, in the same order as \code{A}; \code{prob_out}: a list
#' of error-checking conditional probability matrices, or a list of \code{NULL}
#' values if \code{err_check = FALSE}; and \code{allstages}: a data frame
#' showing the used values of all variables used in transition calculations.
#' 
#' @keywords internal
#' @noRd
NULL

#' Core Time-based Density-Dependent Population Matrix Projection Function
#' 
#' Function \code{proj3dens()} runs density-dependent matrix projections.
#' 
#' @name proj3dens
#' 
#' @param start_vec The starting population vector for the projection.
#' @param core_list A list of full projection matrices, corresponding to the 
#' \code{A} list within a \code{lefkoMat} object.
#' @param mat_order A vector giving the order of matrices to use at each occasion.
#' @param growthonly A logical value stating whether to output only a matrix
#' showing the change in population size from one year to the next for use in
#' stochastic population growth rate estimation (TRUE), or a larger matrix also
#' containing the w and v projections for stochastic perturbation analysis,
#' stage distribution estimation, and reproductive value estimation.
#' @param integeronly A logical value indicating whether to round all projected
#' numbers of individuals to the nearest integer.
#' @param substoch An integer value indicating whether to force survival-
#' transition matrices to be substochastic in density dependent simulations.
#' Defaults to \code{0}, which does not force substochasticity. Alternatively,
#' \code{1} forces all survival-transition elements to range from 0.0 to 1.0
#' and fecundity to be non-negative, and \code{2} forces all column rows to
#' total no more than 1.0.
#' @param dens_input The original \code{lefkoDens} data frame supplied through
#' the \code{\link{density_input}()} function.
#' @param dens_index A list giving the indices of elements in object
#' \code{dens_input}.
#' @param sparse_auto A logical value indicating whether to determine whether
#' to use sparse matrix encoding automatically.
#' @param sparse A logical value indicating whether to use sparse matrix
#' encoding if \code{sparse_auto = FALSE}.
#' @param sparse_input A logical value indicating whether matrices in the input
#' MPM are in sparse format (class \code{dgCMatrix}). If so, then all
#' projection will be handled in sparse format. Defaults to \code{FALSE}.
#' @param allow_warnings A logical value indicating whether the function should
#' send warnings if estimated values fall outside of the realm of possibility.
#' 
#' @return A matrix in which, if \code{growthonly = TRUE}, each row is the
#' population vector at each projected occasion, and if \code{growthonly =
#' FALSE}, the top third of the matrix is the actual number of individuals in
#' each stage across time, the second third is the w projection (stage
#' distribution), and the bottom third is the v projection (reproductive
#' values) for use in estimation of stochastic sensitivities and elasticities
#' (in addition, a further row is appended to the bottom, corresponding to the
#' \emph{R} vector, which is the sum of the unstandardized \emph{w} vector
#' resulting from each occasion's projection).
#' 
#' @section Notes:
#' There is no option to standardize population vectors here, because density
#' dependence requires the full population size to be tracked.
#' 
#' @keywords internal
#' @noRd
NULL

#' Standardize Stageframe For MPM Analysis
#' 
#' Function \code{sf_reassess()} takes a stageframe as input, and uses
#' information supplied there and through the supplement, reproduction and
#' overwrite tables to rearrange this into a format usable by the matrix
#' creation functions, \code{mpm_create()}, \code{flefko3()},
#' \code{flefko2()}, \code{aflefko2()}, \code{rlefko3()}, and \code{rlefko2()}.
#' 
#' @name .sf_reassess
#' 
#' @param stageframe The original stageframe.
#' @param supplement The original supplemental data input (class
#' \code{lefkoSD}). Can also equal NA.
#' @param overwrite An overwrite table.
#' @param repmatrix The original reproduction matrix. Can also equal \code{NA},
#' \code{0}, or \code{NULL} (the last value by default).
#' @param agemat A logical value indicating whether MPM is age-by-stage.
#' @param historical A logical value indicating whether MPM is historical.
#' @param format An integer indicating whether matrices will be in Ehrlen
#' format (if set to 1), or deVries format (if set to 2). Setting to deVries
#' format adds one extra stage to account for the prior status of newborns.
#' 
#' @return This function returns a list with a modified \code{stageframe}
#' usable in MPM construction, an associated \code{repmatrix}, and a general
#' \code{supplement} table that takes over for any input \code{supplement} or
#' \code{overwrite} table. Note that if a \code{supplement} is provided and a
#' \code{repmatrix} is not, or if \code{repmatrix} is set to 0, then it will be
#' assumed that a \code{repmatrix} should not be used.
#' 
#' @keywords internal
#' @noRd
.sf_reassess <- function(stageframe, supplement = NULL, overwrite = NULL, repmatrix = NULL, agemat = FALSE, historical = FALSE, format = 1L) {
    .Call('_lefko3_sf_reassess', PACKAGE = 'lefko3', stageframe, supplement, overwrite, repmatrix, agemat, historical, format)
}

#' Project Function-based Matrix Projection Model
#' 
#' Function \code{f_projection3()} develops and projects function-based matrix
#' models. Unlike \code{\link{projection3}()}, which uses matrices provided as
#' input via already created \code{lefkoMat} objects, function
#' \code{f_projection3()} creates matrices at each time step from vital rate
#' models and parameter inputs provided. Projections may be stochastic or not,
#' and may be density dependent in either case. Also handles replication.
#' 
#' @name f_projection3
#' 
#' @param data The historical vertical demographic data frame used to estimate
#' vital rates (class \code{hfvdata}), which is required to initialize times and
#' patches properly. Variable names should correspond to the naming conventions
#' in \code{\link{verticalize3}()} and \code{\link{historicalize3}()}.
#' @param format An integer indicating the kind of function-based MPM to create.
#' Possible choices include: \code{1}, Ehrlen-format historical MPM; \code{2},
#' deVries-format historical MPM; \code{3}, ahistorical MPM; \code{4},
#' age-by-stage MPM; and \code{5}, Leslie (age-based) MPM.
#' @param prebreeding A logical value indicating whether the life history model
#' is a pre-breeding model. Only used in Leslie and age-by-stage MPMs. Defaults
#' to \code{TRUE}.
#' @param start_age The age from which to start the matrix. Defaults to
#' \code{NA}, in which case age \code{1} is used if \code{prebreeding = TRUE},
#' and age \code{0} is used if \code{prebreeding = FALSE}.
#' @param last_age The final age to use in the matrix. Defaults to \code{NA}, in
#' which case the highest age in the dataset is used.
#' @param fecage_min The minimum age at which reproduction is possible. Defaults
#' to \code{NA}, which is interpreted to mean that fecundity should be assessed
#' starting in the minimum age observed in the dataset.
#' @param fecage_max The maximum age at which reproduction is possible. Defaults
#' to \code{NA}, which is interpreted to mean that fecundity should be assessed
#' until the final observed age.
#' @param cont A logical value designating whether to allow continued survival
#' of individuals past the final age noted in the stageframe, using the 
#' demographic characteristics of the final age. Defaults to \code{TRUE}.
#' @param stochastic A logical value denoting whether to conduct a stochastic
#' projection or a deterministic / cyclical projection.
#' @param standardize A logical value denoting whether to re-standardize the
#' population size to \code{1.0} at each occasion. Used in density-independent
#' simulations in which it is more important to know the general trend in
#' population growth than the explicit growth rate. Defaults to \code{FALSE}.
#' @param growthonly A logical value indicating whether to produce only the
#' projected population size at each occasion (\code{TRUE}), or also to produce
#' vectors showing the stage distribution at each occasion (\code{FALSE}).
#' Defaults to \code{TRUE}.
#' @param repvalue A logical value indicating whether to calculate reproductive
#' value vectors at each time step. Can only be set to \code{TRUE} if 
#' \code{growthonly = FALSE}. Setting to \code{TRUE} may dramatically increase
#' the duration of calculations. Defaults to \code{FALSE}.
#' @param integeronly A logical value indicating whether to round the number of
#' individuals projected in each stage at each occasion to the nearest
#' integer. Defaults to \code{FALSE}.
#' @param substoch An integer value indicating whether to force survival-
#' transition matrices to be substochastic in density dependent and density
#' independent simulations. Defaults to \code{0}, which does not enforce
#' substochasticity. Alternatively, \code{1} forces all survival-transition
#' elements to range from 0.0 to 1.0, and forces fecundity to be non-negative;
#' and \code{2} forces all column rows in the survival-transition matrices to
#' total no more than 1.0, in addition to the actions outlined for option
#' \code{1}. Both settings \code{1} and \code{2} change negative fecundity
#' elements to \code{0.0}.
#' @param ipm_cdf A logical value indicating whether to estimate size
#' transitions using the cumulative density function in cases with continuous
#' distributions. Defaults to \code{TRUE}, with the midpoint method used if
#' \code{FALSE}.
#' @param nreps The number of replicate projections. Defaults to \code{1}.
#' @param times Number of occasions to iterate per replicate. Defaults to
#' \code{10000}.
#' @param repmod A scalar multiplier of fecundity. Defaults to \code{1}.
#' @param exp_tol A numeric value used to indicate a maximum value to set
#' exponents to in the core kernel to prevent numerical overflow. Defaults to
#' \code{700}.
#' @param theta_tol A numeric value used to indicate a maximum value to theta as
#' used in the negative binomial probability density kernel. Defaults to
#' \code{100000000}, but can be reset to other values during error checking.
#' @param random_inda A logical value denoting whether to treat individual
#' covariate \code{a} as a random, categorical variable. Otherwise is treated as
#' a fixed, numeric variable. Defaults to \code{FALSE}.
#' @param random_indb A logical value denoting whether to treat individual
#' covariate \code{b} as a random, categorical variable. Otherwise is treated as
#' a fixed, numeric variable. Defaults to \code{FALSE}.
#' @param random_indc A logical value denoting whether to treat individual
#' covariate \code{c} as a random, categorical variable. Otherwise is treated as
#' a fixed, numeric variable. Defaults to \code{FALSE}.
#' @param err_check A logical value indicating whether to append extra output
#' for debugging purposes. Defaults to \code{FALSE}.
#' @param quiet A logical value indicating whether warning messages should be
#' suppressed. Defaults to \code{FALSE}.
#' @param stageframe An object of class \code{stageframe}. These objects are
#' generated by function \code{\link{sf_create}()}, and include information on
#' the size, observation status, propagule status, reproduction status,
#' immaturity status, maturity status, stage group, size bin widths, and other
#' key characteristics of each ahistorical stage. Required for all MPM formats
#' except Leslie MPMs.
#' @param supplement An optional data frame of class \code{lefkoSD} that
#' provides supplemental data that should be incorporated into the MPM. Three
#' kinds of data may be integrated this way: transitions to be estimated via the
#' use of proxy transitions, transition overwrites from the literature or
#' supplemental studies, and transition multipliers for survival and fecundity.
#' This data frame should be produced using the \code{\link{supplemental}()}
#' function. Can be used in place of or in addition to an overwrite table (see 
#' \code{overwrite} below) and a reproduction matrix (see \code{repmatrix}
#' below).
#' @param repmatrix An optional reproduction matrix. This matrix is composed
#' mostly of \code{0}s, with non-zero entries acting as element identifiers and
#' multipliers for fecundity (with \code{1} equaling full fecundity). If left
#' blank, and no \code{supplement} is provided, then \code{flefko3()} will
#' assume that all stages marked as reproductive produce offspring at 1x that of
#' estimated fecundity, and that offspring production will yield the first stage
#' noted as propagule or immature. May be the dimensions of either a historical
#' or an ahistorical matrix. If the latter, then all stages will be used in
#' occasion \emph{t}-1 for each suggested ahistorical transition.
#' @param overwrite An optional data frame developed with the
#' \code{\link{overwrite}()} function describing transitions to be overwritten
#' either with given values or with other estimated transitions. Note that this
#' function supplements overwrite data provided in \code{supplement}.
#' @param modelsuite A \code{lefkoMod} object, at minimum with all required
#' best-fit vital rate models and a \code{paramnames} data frame, and following
#' the naming conventions used in this package. If given, then
#' \code{surv_model}, \code{obs_model}, \code{size_model}, \code{sizeb_model},
#' \code{sizec_model}, \code{repst_model}, \code{fec_model}, \code{jsurv_model},
#' \code{jobs_model}, \code{jsize_model}, \code{jsizeb_model},
#' \code{jsizec_model}, \code{jrepst_model}, \code{jmatst_model},
#' \code{paramnames}, \code{yearcol}, and \code{patchcol} are not required.
#' Although this is optional input, it is recommended, and without it separate
#' vital rate model inputs (named \code{XX_model}) are required.
#' @param paramnames A data frame with three columns, the first describing all
#' terms used in linear modeling, the second (must be called \code{mainparams})
#' giving the general model terms that will be used in matrix creation, and the
#' third showing the equivalent terms used in modeling (must be named
#' \code{modelparams}). Function \code{\link{create_pm}()} can be used to
#' create a skeleton \code{paramnames} object, which can then be edited. Only
#' required if \code{modelsuite} is not supplied.
#' @param year Either a single integer value corresponding to the year to
#' project, or a vector of \code{times} elements with the year to use at each
#' time step. Defaults to \code{NA}, in which the first year in the set of years
#' in the dataset is projected. If a vector shorter than \code{times} is
#' supplied, then this vector will be cycled.
#' @param patch A value of \code{NA}, a single string value corresponding to the
#' patch to project, or a vector of \code{times} elements with the patch to use
#' at each time step. If a vector shorter than \code{times} is supplied, then
#' this vector will be cycled. Note that this function currently does not
#' handle multiple projections for different patches in the same run.
#' @param sp_density Either a single numeric value of spatial density to use in
#' vital rate models in all time steps, or a vector of \code{times} elements of
#' such numeric values. Defaults to \code{NA}.
#' @param ind_terms An optional data frame with 3 columns and \code{times} rows
#' giving the values of individual covariates a, b, and c, respectively, for
#' each projected time. Unused terms must be set to \code{0} (use of \code{NA}
#' will produce errors.)
#' @param dev_terms An optional data frame with 14 columns and \code{times}
#' rows showing the values of the deviation terms to be added to each linear
#' vital rate. The column order should be: 1: survival, 2: observation, 3:
#' primary size, 4: secondary size, 5: tertiary size, 6: reproduction, 7:
#' fecundity, 8: juvenile survival, 9: juvenile observation, 10: juvenile
#' primary size, 11: juvenile secondary size, 12: juvenile tertiary size, 13:
#' juvenile reproduction, and 14: juvenile maturity transition.  Unused terms
#' must be set to \code{0} (use of \code{NA} will produce errors.)
#' @param surv_model A linear model predicting survival probability. This can 
#' be a model of class \code{glm} or \code{glmer}, and requires a predicted
#' binomial variable under a logit link. Ignored if \code{modelsuite} is
#' provided. This model must have been developed in a modeling exercise testing
#' the impacts of occasions \emph{t} and \emph{t}-1.
#' @param obs_model A linear model predicting sprouting or observation
#' probability. This can be a model of class \code{glm} or \code{glmer}, and
#' requires a predicted binomial variable under a logit link. Ignored if
#' \code{modelsuite} is provided. This model must have been developed in a
#' modeling exercise testing the impacts of occasions \emph{t} and \emph{t}-1.
#' @param size_model A linear model predicting primary size. This can be a model
#' of class \code{glm}, \code{glmer}, \code{glmmTMB}, \code{zeroinfl},
#' \code{vglm}, \code{lm}, or \code{lmer}. Ignored if \code{modelsuite} is
#' provided. This model must have been developed in a modeling exercise testing
#' the impacts of occasions \emph{t} and \emph{t}-1.
#' @param sizeb_model A linear model predicting secondary size. This can be a
#' model of class \code{glm}, \code{glmer}, \code{glmmTMB}, \code{zeroinfl},
#' \code{vglm}, \code{lm}, or \code{lmer}. Ignored if \code{modelsuite} is
#' provided. This model must have been developed in a modeling exercise testing
#' the impacts of occasions \emph{t} and \emph{t}-1.
#' @param sizec_model A linear model predicting tertiary size. This can be a
#' model of class \code{glm}, \code{glmer}, \code{glmmTMB}, \code{zeroinfl},
#' \code{vglm}, \code{lm}, or \code{lmer}. Ignored if \code{modelsuite} is
#' provided. This model must have been developed in a modeling exercise testing
#' the impacts of occasions \emph{t} and \emph{t}-1.
#' @param repst_model A linear model predicting reproduction probability. This 
#' can be a model of class \code{glm} or \code{glmer}, and requires a predicted
#' binomial variable under a logit link. Ignored if \code{modelsuite} is
#' provided. This model must have been developed in a modeling exercise testing
#' the impacts of occasions \emph{t} and \emph{t}-1.
#' @param fec_model A linear model predicting fecundity. This can be a model of
#' class \code{glm}, \code{glmer}, \code{glmmTMB}, \code{zeroinfl}, \code{vglm},
#' \code{lm}, or \code{lmer}. Ignored if \code{modelsuite} is provided. This
#' model must have been developed in a modeling exercise testing the impacts of
#' occasions \emph{t} and \emph{t}-1.
#' @param jsurv_model A linear model predicting juvenile survival probability.
#' This can be a model of class \code{glm} or \code{glmer}, and requires a
#' predicted binomial variable under a logit link. Ignored if \code{modelsuite}
#' is provided. This model must have been developed in a modeling exercise
#' testing the impacts of occasions \emph{t} and \emph{t}-1.
#' @param jobs_model A linear model predicting juvenile sprouting or observation
#' probability. This can be a model of class \code{glm} or \code{glmer}, and
#' requires a predicted binomial variable under a logit link. Ignored if
#' \code{modelsuite} is provided. This model must have been developed in a
#' modeling exercise testing the impacts of occasions \emph{t} and \emph{t}-1.
#' @param jsize_model A linear model predicting juvenile primary size. This
#' can be a model of class \code{glm}, \code{glmer}, \code{glmmTMB},
#' \code{zeroinfl}, \code{vglm}, \code{lm}, or \code{lmer}. Ignored if
#' \code{modelsuite} is provided. This model must have been developed in a
#' modeling exercise testing the impacts of occasions \emph{t} and \emph{t}-1.
#' @param jsizeb_model A linear model predicting juvenile secondary size. This
#' can be a model of class \code{glm}, \code{glmer}, \code{glmmTMB},
#' \code{zeroinfl}, \code{vglm}, \code{lm}, or \code{lmer}. Ignored if
#' \code{modelsuite} is provided. This model must have been developed in a
#' modeling exercise testing the impacts of occasions \emph{t} and \emph{t}-1.
#' @param jsizec_model A linear model predicting juvenile tertiary size. This
#' can be a model of class \code{glm}, \code{glmer}, \code{glmmTMB},
#' \code{zeroinfl}, \code{vglm}, \code{lm}, or \code{lmer}. Ignored if
#' \code{modelsuite} is provided. This model must have been developed in a
#' modeling exercise testing the impacts of occasions \emph{t} and \emph{t}-1.
#' @param jrepst_model A linear model predicting reproduction probability of a 
#' mature individual that was immature in time \emph{t}. This can be a model
#' of class \code{glm} or \code{glmer}, and requires a predicted binomial
#' variable under a logit link. Ignored if \code{modelsuite} is provided. This
#' model must have been developed in a modeling exercise testing the impacts of
#' occasions \emph{t} and \emph{t}-1.
#' @param jmatst_model A linear model predicting maturity probability of an 
#' individual that was immature in time \emph{t}. This can be a model of class
#' \code{glm} or \code{glmer}, and requires a predicted binomial variable under
#' a logit link. Ignored if \code{modelsuite} is provided. This model must have
#' been developed in a modeling exercise testing the impacts of occasions
#' \emph{t} and \emph{t}-1.
#' @param start_vec An optional numeric vector denoting the starting stage
#' distribution for the projection. Defaults to a single individual of each
#' stage.
#' @param start_frame An optional data frame characterizing stages, age-stages,
#' or stage-pairs that should be set to non-zero values in the starting vector,
#' and what those values should be. Can only be used with \code{lefkoMat}
#' objects.
#' @param tweights An optional numeric vector denoting the probabilistic
#' weightings of year terms. Defaults to equal weighting among occasions.
#' @param density An optional data frame describing the matrix elements that
#' will be subject to density dependence, and the exact kind of density
#' dependence that they will be subject to. The data frame used should be an
#' object of class \code{lefkoDens}, which is the output from function
#' \code{\link{density_input}()}.
#' @param density_vr An optional data frame describing density dependence
#' relationships in vital rates, if such relationships are to be assumed. The
#' data frame must be of class \code{lefkoDensVR}, which is the output from the
#' function \code{\link{density_vr}()}.
#' @param sparse A text string indicating whether to use sparse matrix encoding
#' (\code{"yes"}) or dense matrix encoding (\code{"no"}). Defaults to
#' \code{"auto"}, in which case sparse matrix encoding is used with square
#' matrices with at least 50 rows and no more than 50\% of elements with values
#' greater than zero. Can also be entered as a logical value if forced sparse
#' (\code{TRUE}) or forced dense (\code{FALSE}) projection is desired.
#' 
#' @return A list of class \code{lefkoProj}, which always includes the first
#' three elements of the following, and also includes the remaining elements
#' below when a \code{lefkoMat} object is used as input:
#' \item{projection}{A list of lists of matrices showing the total number of
#' individuals per stage per occasion. The first list corresponds to each
#' pop-patch followed by each population (this top-level list is a single
#' element in \code{f_projection3()}). The inner list corresponds to
#' replicates within each pop-patch or population.}
#' \item{stage_dist}{A list of lists of the actual stage distribution in each
#' occasion in each replicate in each pop-patch or population. The list
#' structure is the same as in \code{\link{projection3}()}.}
#' \item{rep_value}{A list of lists of the actual reproductive value in each
#' occasion in each replicate in each pop-patch or population. The list
#' structure is the same as in \code{\link{projection3}()}.}
#' \item{pop_size}{A list of matrices showing the total population size in each
#' occasion per replicate (row within data frame) per pop-patch or population
#' (list element). Only a single pop-patch or population is allowed in
#' \code{f_projection3()}.}
#' \item{labels}{A data frame showing the order of populations and patches in
#' item \code{projection}.}
#' \item{ahstages}{The original stageframe used in the study.}
#' \item{hstages}{A data frame showing the order of historical stage pairs.}
#' \item{agestages}{A data frame showing the order of age-stage pairs.}
#' \item{labels}{A short data frame indicating the population (always \code{1}),
#' and patch (either the numeric index of the single chosen patch, or \code{1}
#' in all other cases).}
#' \item{control}{A short vector indicating the number of replicates and the
#' number of occasions projected per replicate.}
#' \item{density}{The data frame input under the density option. Only provided
#' if input by the user.}
#' \item{density_vr}{The data frame input under the density_vr option. Only
#' provided if input by the user.}
#' 
#' @section Notes:
#' Population projection can be a very time-consuming activity, and it is most
#' time-consuming when matrices need to be created at each time step. We have
#' created this function to work as quickly as possible, but some options will
#' slow analysis. First, the \code{err_check} option should always be set to
#' \code{FALSE}, as the added created output will not only slow the analysis
#' down but also potentially crash the memory if matrices are large enough.
#' Second, the \code{repvalue} option should be set to \code{FALSE} unless
#' reproductive values are genuinely needed, since this step requires
#' concurrent backward projection and so in some cases may double total run
#' time. Finally, if the only needed data is the total population size and
#' age/stage structure at each time step, then setting \code{growthonly = TRUE}
#' will yield the quickest possible run time.
#' 
#' Projections with large matrices may take a long time to run. To assess the
#' likely running time, try using a low number of iterations on a single
#' replicate first. For example, set \code{nreps = 1} and \code{times = 10} for
#' a trial run. If a full run is set and takes too long, press the STOP button
#' in RStudio to cancel the projection run, or click \code{esc}.
#' 
#' This function currently allows three forms of density dependence. The first
#' modifies matrix elements on the basis of the input provided in option
#' \code{density}, and so alters matrix elements once the matrix has already
#' been created. The second form alters the vital rates estimated, and so
#' estimates matrix elements using vital rate values already modified by
#' density. This second form uses the input provided in option
#' \code{density_vr}. These two forms of density dependence utilize the
#' projected population size at some time to make these alterations. The third
#' form of density dependence also alters the vital rates, but using spatial
#' density supplied via option \code{sp_density} and only in vital rates in
#' which spatial density is included as a fixed factor in the associated
#' vital rate model.
#' 
#' When running density dependent simulations involving user-set exponents,
#' such as the beta term in the Ricker function and both the alpha and beta
#' terms in the Usher function, values above or below the computer limits may
#' cause unpredictable behavior. Noted odd behavior includes sudden shifts in
#' population size to negative values. This function produces warnings when
#' such values are used, and the values used for warnings may be reset with the
#' \code{exp_tol} term. In addition, this function resets beta values for the
#' Ricker function automatically to positive or negative \code{exp_tol}, giving
#' a warning when doing so.
#' 
#' Consistently positive population growth can quickly lead to population size
#' numbers larger than can be handled computationally. In that circumstance, a
#' continuously rising population size will suddenly become \code{NaN} for the
#' remainder of the projection.
#' 
#' This function does not reduce the dimensionality of matrices developed for
#' projection.
#' 
#' Speed can sometimes be increased by shifting from automatic sparse matrix
#' determination to forced dense or sparse matrix projection. This will most
#' likely occur when matrices have between 30 and 300 rows and columns.
#' Defaults work best when matrices are very small and dense, or very large and
#' sparse.
#' 
#' @seealso \code{\link{projection3}()}
#' @seealso \code{\link{flefko3}()}
#' @seealso \code{\link{flefko2}()}
#' @seealso \code{\link{aflefko2}()}
#' @seealso \code{\link{fleslie}()}
#' 
#' @examples
#' \donttest{
#' data(lathyrus)
#' 
#' sizevector <- c(0, 4.6, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8,
#'   9)
#' stagevector <- c("Sd", "Sdl", "Dorm", "Sz1nr", "Sz2nr", "Sz3nr", "Sz4nr",
#'   "Sz5nr", "Sz6nr", "Sz7nr", "Sz8nr", "Sz9nr", "Sz1r", "Sz2r", "Sz3r", 
#'   "Sz4r", "Sz5r", "Sz6r", "Sz7r", "Sz8r", "Sz9r")
#' repvector <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1)
#' obsvector <- c(0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
#' matvector <- c(0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
#' immvector <- c(1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
#'   0)
#' indataset <- c(0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 4.6, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 
#'   0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5)
#' 
#' lathframeln <- sf_create(sizes = sizevector, stagenames = stagevector, 
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector, 
#'   immstatus = immvector, indataset = indataset, binhalfwidth = binvec, 
#'   propstatus = propvector)
#' 
#' lathvertln <- verticalize3(lathyrus, noyears = 4, firstyear = 1988,
#'   patchidcol = "SUBPLOT", individcol = "GENET", blocksize = 9, 
#'   juvcol = "Seedling1988", sizeacol = "lnVol88", repstracol = "Intactseed88",
#'   fecacol = "Intactseed88", deadacol = "Dead1988", 
#'   nonobsacol = "Dormant1988", stageassign = lathframeln, stagesize = "sizea",
#'   censorcol = "Missing1988", censorkeep = NA, NAas0 = TRUE, censor = TRUE)
#' 
#' lathvertln$feca2 <- round(lathvertln$feca2)
#' lathvertln$feca1 <- round(lathvertln$feca1)
#' lathvertln$feca3 <- round(lathvertln$feca3)
#' 
#' lathmodelsln3 <- modelsearch(lathvertln, historical = TRUE, 
#'   approach = "mixed", suite = "main", 
#'   vitalrates = c("surv", "obs", "size", "repst", "fec"), juvestimate = "Sdl",
#'   bestfit = "AICc&k", sizedist = "gaussian", fecdist = "poisson", 
#'   indiv = "individ", patch = "patchid", year = "year2", year.as.random = TRUE,
#'   patch.as.random = TRUE, show.model.tables = TRUE, quiet = "partial")
#' 
#' lathsupp3 <- supplemental(stage3 = c("Sd", "Sd", "Sdl", "Sdl", "mat", "Sd", "Sdl"), 
#'   stage2 = c("Sd", "Sd", "Sd", "Sd", "Sdl", "rep", "rep"),
#'   stage1 = c("Sd", "rep", "Sd", "rep", "Sd", "mat", "mat"),
#'   eststage3 = c(NA, NA, NA, NA, "mat", NA, NA),
#'   eststage2 = c(NA, NA, NA, NA, "Sdl", NA, NA),
#'   eststage1 = c(NA, NA, NA, NA, "Sdl", NA, NA),
#'   givenrate = c(0.345, 0.345, 0.054, 0.054, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, NA, 0.345, 0.054),
#'   type = c(1, 1, 1, 1, 1, 3, 3), type_t12 = c(1, 2, 1, 2, 1, 1, 1),
#'   stageframe = lathframeln, historical = TRUE)
#' 
#' # While we do not use MPMs to initialize f_projections3(), we do use MPMs to
#' # initialize functions start_input() and density_input().
#' lathmat3ln <- flefko3(year = "all", patch = "all", stageframe = lathframeln, 
#'   modelsuite = lathmodelsln3, data = lathvertln, supplement = lathsupp3, 
#'   reduce = FALSE)
#' 
#' e3m_sv <- start_input(lathmat3ln, stage2 = "Sd", stage1 = "Sd", value = 1000)
#' 
#' e3d <- density_input(lathmat3ln, stage3 = c("Sd", "Sdl"),
#'   stage2 = c("rep", "rep"), stage1 = c("all", "all"), style = 1,
#'   time_delay = 1, alpha = 1, beta = 0, type = c(2, 2), type_t12 = c(1, 1))
#' 
#' trial7a <- f_projection3(format = 1, data = lathvertln,
#'   modelsuite = lathmodelsln3, stageframe = lathframeln, nreps = 2,
#'   times = 100, stochastic = TRUE, standardize = FALSE, growthonly = TRUE,
#'   integeronly = FALSE, substoch = 0, sp_density = 0, start_frame = e3m_sv,
#'   density = e3d)
#' summary(trial7a)
#' }
#' 
#' @export f_projection3
f_projection3 <- function(format, prebreeding = TRUE, start_age = NA_integer_, last_age = NA_integer_, fecage_min = NA_integer_, fecage_max = NA_integer_, cont = TRUE, stochastic = FALSE, standardize = FALSE, growthonly = TRUE, repvalue = FALSE, integeronly = FALSE, substoch = 0L, ipm_cdf = TRUE, nreps = 1L, times = 10000L, repmod = 1.0, exp_tol = 700.0, theta_tol = 1e8, random_inda = FALSE, random_indb = FALSE, random_indc = FALSE, err_check = FALSE, quiet = FALSE, data = NULL, stageframe = NULL, supplement = NULL, repmatrix = NULL, overwrite = NULL, modelsuite = NULL, paramnames = NULL, year = NULL, patch = NULL, sp_density = NULL, ind_terms = NULL, dev_terms = NULL, surv_model = NULL, obs_model = NULL, size_model = NULL, sizeb_model = NULL, sizec_model = NULL, repst_model = NULL, fec_model = NULL, jsurv_model = NULL, jobs_model = NULL, jsize_model = NULL, jsizeb_model = NULL, jsizec_model = NULL, jrepst_model = NULL, jmatst_model = NULL, start_vec = NULL, start_frame = NULL, tweights = NULL, density = NULL, density_vr = NULL, sparse = NULL) {
    .Call('_lefko3_f_projection3', PACKAGE = 'lefko3', format, prebreeding, start_age, last_age, fecage_min, fecage_max, cont, stochastic, standardize, growthonly, repvalue, integeronly, substoch, ipm_cdf, nreps, times, repmod, exp_tol, theta_tol, random_inda, random_indb, random_indc, err_check, quiet, data, stageframe, supplement, repmatrix, overwrite, modelsuite, paramnames, year, patch, sp_density, ind_terms, dev_terms, surv_model, obs_model, size_model, sizeb_model, sizec_model, repst_model, fec_model, jsurv_model, jobs_model, jsize_model, jsizeb_model, jsizec_model, jrepst_model, jmatst_model, start_vec, start_frame, tweights, density, density_vr, sparse)
}

#' General Matrix Projection Model Creation
#' 
#' Function \code{mpm_create()} is the core workhorse function that creates
#' all flavors of MPM in \code{lefko3}. All other MPM creation functions act
#' as wrappers for this function. As such, this function provides the most
#' general and most detailed control over the MPM creation process.
#' 
#' @name mpm_create
#' 
#' @param historical A logical value indicating whether to build a historical
#' MPM. Defaults to \code{FALSE}.
#' @param stage A logical value indicating whether to build a stage-based MPM.
#' If both \code{stage = TRUE} and \code{age = TRUE}, then will proceed to
#' build an age-by-stage MPM. Defaults to \code{TRUE}.
#' @param age A logical value indicating whether to build an age-based MPM. If
#' both \code{stage = TRUE} and \code{age = TRUE}, then will proceed to build
#' an age-by-stage MPM. Defaults to \code{FALSE}.
#' @param devries  A logical value indicating whether to use deVries format
#' for historical MPMs. Defaults to \code{FALSE}, in which case historical MPMs
#' are created in Ehrlen format.
#' @param reduce A logical value denoting whether to remove ages, ahistorical
#' stages, or historical stages associated exclusively with zero transitions.
#' These are removed only if the respective row and column sums in ALL matrices
#' estimated equal 0. Defaults to \code{FALSE}.
#' @param simple A logical value indicating whether to produce \code{A},
#' \code{U}, and \code{F} matrices, or only the latter two. Defaults to
#' \code{FALSE}, in which case all three are output.
#' @param err_check A logical value indicating whether to append extra
#' information used in matrix calculation within the output list. Defaults to
#' \code{FALSE}.
#' @param data A data frame of class \code{hfvdata}. Required for all MPMs,
#' except for function-based MPMs in which \code{modelsuite} is set to a
#' \code{vrm_input} object.
#' @param year A variable corresponding to observation occasion, or a set of
#' such values, given in values associated with the \code{year} term used in
#' vital rate model development. Can also equal \code{"all"}, in which case
#' matrices will be estimated for all occasions. Defaults to \code{"all"}.
#' @param pop A variable designating which populations will have matrices
#' estimated. Should be set to specific population names, or to \code{"all"} if
#' all populations should have matrices estimated. Only used in raw MPMs.
#' @param patch A variable designating which patches or subpopulations will have
#' matrices estimated. Should be set to specific patch names, or to \code{"all"}
#' if matrices should be estimated for all patches. Defaults to \code{NULL}, in
#' which case patch designations are ignored.
#' @param stageframe An object of class \code{stageframe}. These objects are
#' generated by function \code{\link{sf_create}()}, and include information on
#' the size, observation status, propagule status, reproduction status,
#' immaturity status, maturity status, stage group, size bin widths, and other
#' key characteristics of each ahistorical stage. Not needed for purely
#' age-based MPMs.
#' @param supplement An optional data frame of class \code{lefkoSD} that
#' provides supplemental data that should be incorporated into the MPM. Three
#' kinds of data may be integrated this way: transitions to be estimated via the
#' use of proxy transitions, transition overwrites from the literature or
#' supplemental studies, and transition multipliers for survival and fecundity.
#' This data frame should be produced using the \code{\link{supplemental}()}
#' function. Can be used in place of or in addition to an overwrite table (see 
#' \code{overwrite} below) and a reproduction matrix (see \code{repmatrix}
#' below).
#' @param overwrite An optional data frame developed with the
#' \code{\link{overwrite}()} function describing transitions to be overwritten
#' either with given values or with other estimated transitions. Note that this
#' function supplements overwrite data provided in \code{supplement}.
#' @param repmatrix An optional reproduction matrix. This matrix is composed
#' mostly of \code{0}s, with non-zero entries acting as element identifiers and
#' multipliers for fecundity (with \code{1} equaling full fecundity). If left
#' blank, and no \code{supplement} is provided, then all stages marked as
#' reproductive produce offspring at 1x that of estimated fecundity, and that
#' offspring production will yield the first stage noted as propagule or
#' immature. May be the dimensions of either a historical or an ahistorical
#' matrix. If the latter, then all stages will be used in occasion \emph{t}-1
#' for each suggested ahistorical transition. Not used in purely age-based
#' MPMs.
#' @param alive A vector of names of binomial variables corresponding to status
#' as alive (\code{1}) or dead (\code{0}) in occasions \emph{t}+1, \emph{t},
#' and \emph{t}-1, respectively. Defaults to 
#' \code{c("alive3", "alive2", "alive1")} for historical MPMs, and
#' \code{c("alive3", "alive2")} for ahistorical MPMs. Only needed for raw MPMs.
#' @param obsst A vector of names of binomial variables corresponding to
#' observation status in occasions \emph{t}+1, \emph{t}, and \emph{t}-1,
#' respectively. Defaults to \code{c("obsstatus3", "obsstatus2", "obsstatus1")}
#' for historical MPMs, and \code{c("obsstatus3", "obsstatus2")} for
#' ahistorical MPMs. Only needed for raw MPMs.
#' @param size A vector of names of variables coding the primary size variable
#' in occasions \emph{t}+1, \emph{t}, and \emph{t}-1, respectively. Defaults to 
#' \code{c("sizea3", "sizea2", "sizea1")} for historical MPMs, and
#' \code{c("sizea3", "sizea2")} for ahistorical MPMs. Only needed for raw,
#' stage-based MPMs.
#' @param sizeb A vector of names of variables coding the secondary size
#' variable in occasions \emph{t}+1, \emph{t}, and \emph{t}-1, respectively.
#' Defaults to an empty set, assuming that secondary size is not used. Only
#' needed for raw, stage-based MPMs.
#' @param sizec A vector of names of variables coding the tertiary size
#' variable in occasions \emph{t}+1, \emph{t}, and \emph{t}-1, respectively.
#' Defaults to an empty set, assuming that tertiary size is not used. Only
#' needed for raw, stage-based MPMs.
#' @param repst A vector of names of binomial variables corresponding to
#' reproductive status in occasions \emph{t}+1, \emph{t}, and \emph{t}-1,
#' respectively. Defaults to \code{c("repstatus3", "repstatus2", "repstatus1")}
#' for historical MPMs, and \code{c("repstatus3", "repstatus2")} for
#' ahistorical MPMs. Only needed for raw MPMs.
#' @param matst A vector of names of binomial variables corresponding to
#' maturity status in occasions \emph{t}+1, \emph{t}, and \emph{t}-1,
#' respectively. Defaults to \code{c("matstatus3", "matstatus2", "matstatus1")}
#' for historical MPMs, and \code{c("matstatus3", "matstatus2")} for
#' ahistorical MPMs. Must be provided if building raw MPMs, and \code{stages}
#' is not provided.
#' @param fec A vector of names of variables coding for fecundity in occasions
#' \emph{t}+1, \emph{t}, and \emph{t}-1, respectively. Defaults to
#' \code{c("feca3", "feca2", "feca1")} for historical MPMs, and
#' \code{c("feca3", "feca2")} for ahistorical MPMs. Only needed for raw,
#' stage-based MPMs.
#' @param stages An optional vector denoting the names of the variables within
#' the main vertical dataset coding for the stages of each individual in
#' occasions \emph{t}+1 and \emph{t}, and \emph{t}-1, if historical. The names
#' of stages in these variables should match those used in the
#' \code{stageframe} exactly. If left blank, then \code{rlefko3()} will attempt
#' to infer stages by matching values of \code{alive}, \code{obsst},
#' \code{size}, \code{sizev}, \code{sizec}, \code{repst}, and \code{matst} to
#' characteristics noted in the associated \code{stageframe}. Only used in raw,
#' stage-based MPMs.
#' @param yearcol The variable name or column number corresponding to occasion
#' \emph{t} in the dataset. Defaults to \code{"year2"}. Only needed for raw
#' MPMs.
#' @param popcol The variable name or column number corresponding to the
#' identity of the population. Defaults to \code{"popid"} if a value is
#' provided for \code{pop}; otherwise empty. Only needed for raw MPMs.
#' @param patchcol The variable name or column number corresponding to patch in 
#' the dataset. Defaults to \code{"patchid"} if a value is provided for
#' \code{patch}; otherwise empty.  Only needed for raw MPMs.
#' @param indivcol The variable name or column number coding individual
#' identity. Only needed for raw MPMs.
#' @param agecol The variable name or column corresponding to age in time
#' \emph{t}. Defaults to \code{"obsage"}. Only used in raw age-based and
#' age-by-stage MPMs.
#' @param censorcol The variable name or column number denoting the censor
#' status. Only needed in raw MPMs, and only if \code{censor = TRUE}.
#' @param modelsuite One of three kinds of lists. The first is a
#' \code{lefkoMod} object holding the vital rate models and associated
#' metadata. Alternatively, an object of class \code{vrm_input} may be
#' provided. Finally, this argument may simply be a list of models used to
#' parameterize the MPM. In the final scenario, \code{data} and
#' \code{paramnames} must also be given, and all variable names must match
#' across all objects. If entered, then a function-based MPM will be developed.
#' Otherwise, a raw MPM will be developed. Only used in function-based MPMs.
#' @param paramnames A data frame with three columns, the first describing all
#' terms used in linear modeling, the second (must be called \code{mainparams})
#' giving the general model terms that will be used in matrix creation, and the
#' third showing the equivalent terms used in modeling (must be named
#' \code{modelparams}). Function \code{\link{create_pm}()} can be used to
#' create a skeleton \code{paramnames} object, which can then be edited. Only
#' required to build function-based MPMs if \code{modelsuite} is neither a
#' \code{lefkoMod} object nor a \code{vrm_input} object.
#' @param inda Can be a single value to use for individual covariate \code{a}
#' in all matrices, a pair of values to use for times \emph{t} and \emph{t}-1
#' in historical matrices, or a vector of such values corresponding to each
#' occasion in the dataset. Defaults to \code{NULL}. Only used in
#' function-based MPMs.
#' @param indb Can be a single value to use for individual covariate \code{b}
#' in all matrices, a pair of values to use for times \emph{t} and \emph{t}-1
#' in historical matrices, or a vector of such values corresponding to each
#' occasion in the dataset. Defaults to \code{NULL}. Only used in
#' function-based MPMs.
#' @param indc Can be a single value to use for individual covariate \code{c}
#' in all matrices, a pair of values to use for times \emph{t} and \emph{t}-1
#' in historical matrices, or a vector of such values corresponding to each
#' occasion in the dataset. Defaults to \code{NULL}. Only used in
#' function-based MPMs.
#' @param dev_terms A numeric vector of 2 elements in the case of a Leslie MPM,
#' and of 14 elements in all other cases. Consists of scalar additions to the
#' y-intercepts of vital rate linear models used to estimate vital rates in
#' function-based MPMs. Defaults to \code{0} values for all vital rates.
#' @param density A numeric value indicating density value to use to propagate
#' matrices. Only needed if density is an explanatory term used in one or more
#' vital rate models. Defaults to \code{NA}. Only used in function_based MPMs.
#' @param CDF A logical value indicating whether to use the cumulative
#' distribution function to estimate size transition probabilities in
#' function-based MPMs. Defaults to \code{TRUE}, and should only be changed to
#' \code{FALSE} if approximate probabilities calculated via the midpoint method
#' are preferred.
#' @param random_inda A logical value denoting whether to treat individual
#' covariate \code{a} as a random, categorical variable. Otherwise is treated
#' as a fixed, numeric variable. Defaults to \code{FALSE}. Only used in
#' function-based MPMs.
#' @param random_indb A logical value denoting whether to treat individual
#' covariate \code{b} as a random, categorical variable. Otherwise is treated
#' as a fixed, numeric variable. Defaults to \code{FALSE}. Only used in
#' function-based MPMs.
#' @param random_indc A logical value denoting whether to treat individual
#' covariate \code{c} as a random, categorical variable. Otherwise is treated
#' as a fixed, numeric variable. Defaults to \code{FALSE}. Only used in
#' function-based MPMs.
#' @param negfec A logical value denoting whether fecundity values estimated to
#' be negative should be reset to \code{0}. Defaults to \code{FALSE}.
#' @param exp_tol A numeric value used to indicate a maximum value to set
#' exponents to in the core kernel to prevent numerical overflow. Defaults to
#' \code{700}. Only used in function-based MPMs.
#' @param theta_tol A numeric value used to indicate a maximum value to theta
#' as used in the negative binomial probability density kernel. Defaults to
#' \code{100000000}, but can be reset to other values during error checking.
#' Only used in function-based MPMs.
#' @param censor If \code{TRUE}, then data will be removed according to the
#' variable set in \code{censorcol}, such that only data with censor values
#' equal to \code{censorkeep} will remain. Defaults to \code{FALSE}. Only
#' used in raw MPMs.
#' @param censorkeep The value of the censor variable denoting data elements to
#' keep. Defaults to \code{0}. Only used in raw MPMs.
#' @param start_age The age from which to start the matrix. Defaults to
#' \code{NULL}, in which case age \code{1} is used if
#' \code{prebreeding = TRUE}, and age \code{0} is used if
#' \code{prebreeding = FALSE}. Only used in age-based MPMs.
#' @param last_age The final age to use in the matrix. Defaults to \code{NULL},
#' in which case the highest age in the dataset is used. Only used in age-based
#' and age-by-stage MPMs.
#' @param fecage_min The minimum age at which reproduction is possible.
#' Defaults to \code{NULL}, which is interpreted to mean that fecundity should
#' be assessed starting in the minimum age observed in the dataset. Only used
#' in age-based MPMs.
#' @param fecage_max The maximum age at which reproduction is possible.
#' Defaults to \code{NULL}, which is interpreted to mean that fecundity should
#' be assessed until the final observed age. Only used in age-based MPMs.
#' @param fectime  An integer indicating whether to estimate fecundity using
#' the variable given for \code{fec} in time \emph{t} (\code{2}) or time
#' \emph{t}+1 (\code{3}). Only used for purely age-based MPMs. Defaults to
#' \code{2}.
#' @param fecmod A scalar multiplier for fecundity. Only used for purely
#' age-based MPMs. Defaults to \code{1.0}.
#' @param cont A logical value designating whether to allow continued survival
#' of individuals past the final age noted in age-based and age-by-stage MPMs,
#' using the demographic characteristics of the final age. Defaults to
#' \code{TRUE}.
#' @param prebreeding A logical value indicating whether the life history model
#' is a pre-breeding model. Defaults to \code{TRUE}.
#' @param stage_NRasRep A logical value indicating whether to treat
#' non-reproductive individuals as reproductive. Used only in raw, stage-based
#' MPMs in cases where stage assignment must still be handled. Not used in
#' function-based MPMs, and in stage-based MPMs in which a valid \code{hfvdata}
#' class data frame with stages already assigned is provided.
#' @param sparse_output A logical value indicating whether to output matrices
#' in sparse format. Defaults to \code{FALSE}, in which case all matrices are
#' output in standard matrix format.
#' 
#' @return An object of class \code{lefkoMat}. This is a list that holds the
#' matrix projection model and all of its metadata. The structure has the
#' following elements:
#' 
#' \item{A}{A list of full projection matrices in order of sorted patches and
#' occasion times. All matrices output in R's \code{matrix} class, or in
#' the \code{dgCMatrix} class from the \code{Matrix} package if sparse.}
#' \item{U}{A list of survival transition matrices sorted as in \code{A}. All 
#' matrices output in R's \code{matrix} class, or in the \code{dgCMatrix} class
#' from the \code{Matrix} package if sparse.}
#' \item{F}{A list of fecundity matrices sorted as in \code{A}. All matrices 
#' output in R's \code{matrix} class, or in the \code{dgCMatrix} class from the
#' \code{Matrix} package if sparse.}
#' \item{hstages}{A data frame matrix showing the pairing of ahistorical stages
#' used to create historical stage pairs. Only used in historical MPMs.}
#' \item{agestages}{A data frame showing age-stage pairs. Only used in
#' age-by-stage MPMs.}
#' \item{ahstages}{A data frame detailing the characteristics of associated
#' ahistorical stages, in the form of a modified stageframe that includes
#' status as an entry stage through reproduction. Used in all stage-based and
#' age-by-stage MPMs.}
#' \item{labels}{A data frame giving the population, patch, and year of each
#' matrix in order.}
#' \item{dataqc}{A vector showing the numbers of individuals and rows in the
#' vertical dataset used as input.}
#' \item{matrixqc}{A short vector describing the number of non-zero elements in
#' \code{U} and \code{F} matrices, and the number of annual matrices.}
#' \item{modelqc}{This is the \code{qc} portion of the \code{modelsuite}
#' input.}
#' \item{prob_out}{An optional element only added if \code{err_check = TRUE}.
#' This is a list of vital rate probability matrices, with 7 columns in the
#' order of survival, observation probability, reproduction probability, primary
#' size transition probability, secondary size transition probability, tertiary
#' size transition probability, and probability of juvenile transition to
#' maturity.}
#' \item{allstages}{An optional element only added if \code{err_check = TRUE}.
#' This is a data frame giving the values used to determine each matrix element
#' capable of being estimated.}
#' \item{data}{An optional element only added if \code{err_check = TRUE} and a
#' raw MPM is requested. This consists of the original dataset as edited by
#' this function for indexing purposes.}
#' 
#' @section General Notes:
#' This function automatically determines whether to create a raw or
#' function-based MPM given inputs supplied by the user.
#' 
#' If used, the reproduction matrix (field \code{repmatrix}) may be supplied as
#' either historical or ahistorical. If provided as historical, then
#' a historical MPM must be estimated.
#' 
#' @section Function-based MPM Notes:
#' Users may at times wish to estimate MPMs using a dataset incorporating
#' multiple patches or subpopulations, but without discriminating between those
#' patches or subpopulations. Should the aim of analysis be a general MPM that
#' does not distinguish these patches or subpopulations, the
#' \code{modelsearch()} run should not include patch terms.
#' 
#' Input options including multiple variable names must be entered in the order
#' of variables in occasion \emph{t}+1, \emph{t}, and \emph{t}-1. Rearranging
#' the order will lead to erroneous calculations, and will may lead to fatal
#' errors.
#' 
#' This function provides two different means of estimating the probability of
#' size transition. The midpoint method (\code{CDF = FALSE}) refers to the
#' method in which the probability is estimated by first estimating the
#' probability associated with transition from the exact size at the midpoint
#' of the size class using the corresponding probability density function, and
#' then multiplying that value by the bin width of the size class. Doak et al.
#' 2021 (Ecological Monographs) noted that this method can produce biased
#' results, with total size transitions associated with a specific size not
#' totaling to 1.0 and even specific size transition probabilities capable of
#' being estimated at values greater than 1.0. The alternative and default
#' method (\code{CDF = TRUE}) uses the cumulative density function to estimate
#' the probability of size transition as the cumulative probability of size
#' transition at the greater limit of the size class minus the cumulative
#' probability of size transition at the lower limit of the size class. This
#' latter method avoids this bias. Note, however, that both methods are exact
#' and unbiased for negative binomial and Poisson distributions.
#' 
#' Under the Gaussian and gamma size distributions, the number of estimated
#' parameters may differ between the two \code{ipm_method} settings. Because
#' the midpoint method has a tendency to incorporate upward bias in the
#' estimation of size transition probabilities, it is more likely to yield non-
#' zero values when the true probability is extremely close to 0. This will
#' result in the \code{summary.lefkoMat()} function yielding higher numbers of
#' estimated parameters than the \code{ipm_method = "CDF"} yields in some cases.
#' 
#' @examples
#' \donttest{
#' # Lathyrus historical function-based MPM example
#' data(lathyrus)
#' 
#' sizevector <- c(0, 4.6, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8,
#'   9)
#' stagevector <- c("Sd", "Sdl", "Dorm", "Sz1nr", "Sz2nr", "Sz3nr", "Sz4nr",
#'   "Sz5nr", "Sz6nr", "Sz7nr", "Sz8nr", "Sz9nr", "Sz1r", "Sz2r", "Sz3r", 
#'   "Sz4r", "Sz5r", "Sz6r", "Sz7r", "Sz8r", "Sz9r")
#' repvector <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1)
#' obsvector <- c(0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
#' matvector <- c(0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
#' immvector <- c(1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
#'   0)
#' indataset <- c(0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 4.6, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 
#'   0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5)
#' 
#' lathframeln <- sf_create(sizes = sizevector, stagenames = stagevector, 
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector, 
#'   immstatus = immvector, indataset = indataset, binhalfwidth = binvec, 
#'   propstatus = propvector)
#' 
#' lathvertln <- verticalize3(lathyrus, noyears = 4, firstyear = 1988,
#'   patchidcol = "SUBPLOT", individcol = "GENET", blocksize = 9, 
#'   juvcol = "Seedling1988", sizeacol = "lnVol88", repstracol = "Intactseed88",
#'   fecacol = "Intactseed88", deadacol = "Dead1988", 
#'   nonobsacol = "Dormant1988", stageassign = lathframeln, stagesize = "sizea",
#'   censorcol = "Missing1988", censorkeep = NA, NAas0 = TRUE, censor = TRUE)
#' 
#' lathvertln$feca2 <- round(lathvertln$feca2)
#' lathvertln$feca1 <- round(lathvertln$feca1)
#' lathvertln$feca3 <- round(lathvertln$feca3)
#' 
#' lathmodelsln3 <- modelsearch(lathvertln, historical = TRUE, 
#'   approach = "mixed", suite = "main", 
#'   vitalrates = c("surv", "obs", "size", "repst", "fec"), juvestimate = "Sdl",
#'   bestfit = "AICc&k", sizedist = "gaussian", fecdist = "poisson", 
#'   indiv = "individ", patch = "patchid", year = "year2", year.as.random = TRUE,
#'   patch.as.random = TRUE, show.model.tables = TRUE, quiet = "partial")
#' 
#' lathsupp3 <- supplemental(stage3 = c("Sd", "Sd", "Sdl", "Sdl", "mat", "Sd", "Sdl"), 
#'   stage2 = c("Sd", "Sd", "Sd", "Sd", "Sdl", "rep", "rep"),
#'   stage1 = c("Sd", "rep", "Sd", "rep", "Sd", "mat", "mat"),
#'   eststage3 = c(NA, NA, NA, NA, "mat", NA, NA),
#'   eststage2 = c(NA, NA, NA, NA, "Sdl", NA, NA),
#'   eststage1 = c(NA, NA, NA, NA, "Sdl", NA, NA),
#'   givenrate = c(0.345, 0.345, 0.054, 0.054, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, NA, 0.345, 0.054),
#'   type = c(1, 1, 1, 1, 1, 3, 3), type_t12 = c(1, 2, 1, 2, 1, 1, 1),
#'   stageframe = lathframeln, historical = TRUE)
#' 
#' lathmat3ln <- mpm_create(historical = TRUE, year = "all", patch = "all",
#'   stageframe = lathframeln, modelsuite = lathmodelsln3, data = lathvertln,
#'   supplement = lathsupp3)
#' }
#' 
#' @export mpm_create
mpm_create <- function(historical = FALSE, stage = TRUE, age = FALSE, devries = FALSE, reduce = FALSE, simple = FALSE, err_check = FALSE, data = NULL, year = NULL, pop = NULL, patch = NULL, stageframe = NULL, supplement = NULL, overwrite = NULL, repmatrix = NULL, alive = NULL, obsst = NULL, size = NULL, sizeb = NULL, sizec = NULL, repst = NULL, matst = NULL, fec = NULL, stages = NULL, yearcol = NULL, popcol = NULL, patchcol = NULL, indivcol = NULL, agecol = NULL, censorcol = NULL, modelsuite = NULL, paramnames = NULL, inda = NULL, indb = NULL, indc = NULL, dev_terms = NULL, density = NA_real_, CDF = TRUE, random_inda = FALSE, random_indb = FALSE, random_indc = FALSE, negfec = FALSE, exp_tol = 700L, theta_tol = 1e8L, censor = FALSE, censorkeep = NULL, start_age = NA_integer_, last_age = NA_integer_, fecage_min = NA_integer_, fecage_max = NA_integer_, fectime = 2L, fecmod = 1.0, cont = TRUE, prebreeding = TRUE, stage_NRasRep = FALSE, sparse_output = FALSE) {
    .Call('_lefko3_mpm_create', PACKAGE = 'lefko3', historical, stage, age, devries, reduce, simple, err_check, data, year, pop, patch, stageframe, supplement, overwrite, repmatrix, alive, obsst, size, sizeb, sizec, repst, matst, fec, stages, yearcol, popcol, patchcol, indivcol, agecol, censorcol, modelsuite, paramnames, inda, indb, indc, dev_terms, density, CDF, random_inda, random_indb, random_indc, negfec, exp_tol, theta_tol, censor, censorkeep, start_age, last_age, fecage_min, fecage_max, fectime, fecmod, cont, prebreeding, stage_NRasRep, sparse_output)
}

#' Estimate Stable Stage Distribution of Any Population Matrix
#' 
#' \code{ss3matrix()} returns the stable stage distribution for a 
#' dense or sparse population matrix.
#' 
#' @name .ss3matrix
#' 
#' @param Amat A population projection matrix of class \code{matrix}.
#' @param sparse A logical value indicating whether to use sparse or dense
#' format in matrix calculations.
#' 
#' @return This function returns the stable stage distribution corresponding to
#' the input matrix.
#' 
#' @seealso \code{\link{stablestage3}()}
#' @seealso \code{\link{stablestage3.lefkoMat}()}
#' 
#' @keywords internal
#' @noRd
.ss3matrix <- function(Amat, sparse) {
    .Call('_lefko3_ss3matrix', PACKAGE = 'lefko3', Amat, sparse)
}

#' 
#' \code{ss3matrix_sp()} returns the stable stage distribution for a sparse
#' population matrix.
#' 
#' @name ss3matrix_sp
#' 
#' @param Amat A population projection matrix of class \code{dgCMatrix}.
#' 
#' @return This function returns the stable stage distribution corresponding to
#' the input matrix.
#' 
#' @seealso \code{\link{stablestage3}()}
#' @seealso \code{\link{stablestage3.lefkoMat}()}
#' 
#' @keywords internal
#' @noRd
.ss3matrix_sp <- function(Amat) {
    .Call('_lefko3_ss3matrix_sp', PACKAGE = 'lefko3', Amat)
}

#' Estimate Reproductive Value of Any Population Matrix
#' 
#' \code{rv3matrix()} returns the reproductive values for stages in a
#' dense or sparse population matrix (both provided in dense matrix format).
#' The function provides standard reproductive values, meaning that the overall
#' reproductive values of basic life history stages in a historical matrix are
#' not provided (the \code{\link{repvalue3.lefkoMat}()} function estimates
#' these on the basis of stage description information provided in the
#' \code{lefkoMat} object used as input in that function).
#' 
#' @name .rv3matrix
#' 
#' @param Amat A population projection matrix of class \code{matrix}.
#' @param sparse A logical value indicating whether to use sparse or dense
#' format in matrix calculations.
#' 
#' @return This function returns a vector characterizing the reproductive
#' values for stages of a population projection matrix.
#' 
#' @seealso \code{\link{repvalue3}()}
#' @seealso \code{\link{repvalue3.lefkoMat}()}
#' 
#' @keywords internal
#' @noRd
.rv3matrix <- function(Amat, sparse) {
    .Call('_lefko3_rv3matrix', PACKAGE = 'lefko3', Amat, sparse)
}

#' Estimate Reproductive Value of Any Population Matrix
#' 
#' \code{rv3matrix_sp()} returns the reproductive values for stages in a
#' sparse population matrix (both provided in dense matrix format).
#' The function provides standard reproductive values, meaning that the overall
#' reproductive values of basic life history stages in a historical matrix are
#' not provided (the \code{\link{repvalue3.lefkoMat}()} function estimates
#' these on the basis of stage description information provided in the
#' \code{lefkoMat} object used as input in that function).
#' 
#' @name .rv3matrix_sp
#' 
#' @param Amat A population projection matrix of class \code{matrix}.
#' 
#' @return This function returns a vector characterizing the reproductive
#' values for stages of a population projection matrix.
#' 
#' @seealso \code{\link{repvalue3}()}
#' @seealso \code{\link{repvalue3.lefkoMat}()}
#' 
#' @keywords internal
#' @noRd
.rv3matrix_sp <- function(Amat) {
    .Call('_lefko3_rv3matrix_sp', PACKAGE = 'lefko3', Amat)
}

#' Estimate Deterministic Sensitivities of Any Population Matrix
#' 
#' \code{sens3matrix()} returns the sensitivity of lambda with respect
#' to each element in a dense or sparse matrix (provided in dense matrix
#' format). This is accomplished via the \code{eig_gen}() and \code{eigs_gen}()
#' functions in the C++ Armadillo library.
#' 
#' @name .sens3matrix
#' 
#' @param Amat A population projection matrix of class \code{matrix}.
#' @param sparse A logical value indicating whether to use sparse or dense
#' format in matrix calculations.
#' 
#' @return This function returns a matrix of deterministic sensitivities. 
#' 
#' @keywords internal
#' @noRd
.sens3matrix <- function(Amat, sparse) {
    .Call('_lefko3_sens3matrix', PACKAGE = 'lefko3', Amat, sparse)
}

#' Estimate Deterministic Sensitivities of A Spars Matrixe
#' 
#' \code{sens3sp_matrix()} returns the sensitivity of lambda with respect
#' to each element in a sparse matrix, provided in sparse matrix format. This
#' is accomplished via the \code{eigs_gen}() function in the C++ Armadillo
#' library.
#' 
#' @name .sens3sp_matrix
#' 
#' @param Aspmat A population projection matrix in sparse matrix format.
#' @param refmat A sparse matrix used for reference to create associated 0s in
#' the sensitivity matrix.
#' 
#' @return This function returns a sparse matrix of deterministic
#' sensitivities. Zeroes are derived from the reference matrix, and replace
#' non-zero entries that will be zeroed out in the following math. Currently
#' used in LTRE estimation.
#' 
#' @keywords internal
#' @noRd
.sens3sp_matrix <- function(Aspmat, refmat) {
    .Call('_lefko3_sens3sp_matrix', PACKAGE = 'lefko3', Aspmat, refmat)
}

#' Estimate Deterministic Sensitivities of Any Population Matrix
#' 
#' \code{sens3matrix_spinp()} returns the sensitivity of lambda with respect
#' to each element in a sparse matrix. This is accomplished via the
#' \code{eigs_gen()} function in the C++ Armadillo library.
#' 
#' @name .sens3matrix_spinp
#' 
#' @param Amat A population projection matrix of class \code{dgCMatrix}.
#' 
#' @return This function returns a standard matrix of deterministic
#' sensitivities. 
#' 
#' @keywords internal
#' @noRd
.sens3matrix_spinp <- function(Amat) {
    .Call('_lefko3_sens3matrix_spinp', PACKAGE = 'lefko3', Amat)
}

#' Estimate Deterministic Sensitivities of a Historical LefkoMat Object
#' 
#' \code{sens3hlefko()} returns the sensitivity of lambda with respect
#' to each historical stage-pair in the matrix, and the associated
#' sensitivity for each life history stage. This is accomplished via the 
#' \code{eigs_gen}() function in the C++ Armadillo library.
#' 
#' @name .sens3hlefko
#' 
#' @param Amat A population projection matrix of class \code{matrix}.
#' @param ahstages An integar vector of unique ahistorical stages.
#' @param hstages An integar vector of unique historical stage pairs.
#' 
#' @return This function returns a list with two deterministic sensitivity
#' matrices:
#' \item{h_smat}{Matrix of sensitivities corresponding to the historical
#' matrix.}
#' \item{ah_smat}{Matrix of sensitivities corresponding to the ahistorical
#' matrix.}
#' 
#' @keywords internal
#' @noRd
.sens3hlefko <- function(Amat, ahstages, hstages) {
    .Call('_lefko3_sens3hlefko', PACKAGE = 'lefko3', Amat, ahstages, hstages)
}

#' Estimate Deterministic Sensitivities of a Historical LefkoMat Object
#' 
#' \code{sens3hlefko()} returns the sensitivity of lambda with respect
#' to each historical stage-pair in the matrix, and the associated
#' sensitivity for each life history stage. This is accomplished via the 
#' \code{eigs_gen}() function in the C++ Armadillo library.
#' 
#' @name .sens3hlefko_sp
#' 
#' @param Amat A population projection matrix of class \code{matrix}.
#' @param ahstages An integar vector of unique ahistorical stages.
#' @param hstages An integar vector of unique historical stage pairs.
#' 
#' @return This function returns a list with two deterministic sensitivity
#' matrices:
#' \item{h_smat}{Matrix of sensitivities corresponding to the historical
#' matrix.}
#' \item{ah_smat}{Matrix of sensitivities corresponding to the ahistorical
#' matrix.}
#' 
#' @keywords internal
#' @noRd
.sens3hlefko_sp <- function(Amat, ahstages, hstages) {
    .Call('_lefko3_sens3hlefko_sp', PACKAGE = 'lefko3', Amat, ahstages, hstages)
}

#' Estimate Deterministic Elasticities of Any Population Matrix
#' 
#' \code{elas3matrix()} returns the elasticity of lambda with respect
#' to each element in a dense or sparse matrix, both provided in dense matrix
#' format. This is accomplished via the \code{eig_gen}() and \code{eigs_gen}()
#' functions in the C++ Armadillo library.
#' 
#' @name .elas3matrix
#' 
#' @param Amat A population projection matrix of class \code{matrix}.
#' @param sparse A logical value indicating whether to use sparse or dense
#' format in matrix calculations.
#' 
#' @return This function returns a matrix of deterministic elasticities. 
#' 
#' @keywords internal
#' @noRd
.elas3matrix <- function(Amat, sparse) {
    .Call('_lefko3_elas3matrix', PACKAGE = 'lefko3', Amat, sparse)
}

#' Estimate Deterministic Elasticities of Any Population Matrix (Sparse Output)
#' 
#' This function conducts a deterministic elasticity analysis but returns the
#' output in sparse matrix format.
#' 
#' @name .elas3sp_matrix
#' 
#' @param Amat A population projection matrix of class \code{matrix}.
#' 
#' @return This function returns a matrix of deterministic elasticities. 
#' 
#' @keywords internal
#' @noRd
.elas3sp_matrix <- function(Amat) {
    .Call('_lefko3_elas3sp_matrix', PACKAGE = 'lefko3', Amat)
}

#' Estimate Deterministic Elasticities of a Historical LefkoMat Object
#' 
#' \code{elas3hlefko()} returns the elasticity of lambda with respect
#' to each historical stage-pair in the matrix, and the summed elasticities
#' for each life history stage. This is accomplished via the \code{eigs_gen}()
#' function in the C++ Armadillo library.
#' 
#' @name .elas3hlefko
#' 
#' @param Amat A population projection matrix.
#' @param ahstages An integar vector of unique ahistorical stages.
#' @param hstages An integar vector of unique historical stage pairs.
#' 
#' @return This function returns a list with two deterministic elasticity
#' matrices:
#' \item{h_emat}{Matrix of elasticities corresponding to the historical matrix.}
#' \item{ah_emat}{Matrix of elasticities corresponding to the ahistorical
#' matrix, but using summed historical elasticities as the basis of estimation.}
#' 
#' @keywords internal
#' @noRd
.elas3hlefko <- function(Amat, ahstages, hstages) {
    .Call('_lefko3_elas3hlefko', PACKAGE = 'lefko3', Amat, ahstages, hstages)
}

#' Estimate Deterministic Elasticities of a Historical LefkoMat Object
#' 
#' \code{elas3hlefko()} returns the elasticity of lambda with respect
#' to each historical stage-pair in the matrix, and the summed elasticities
#' for each life history stage. This is accomplished via the \code{eigs_gen}()
#' function in the C++ Armadillo library.
#' 
#' @name .elas3sp_hlefko
#' 
#' @param Amat A population projection matrix.
#' @param ahstages An integar vector of unique ahistorical stages.
#' @param hstages An integar vector of unique historical stage pairs.
#' 
#' @return This function returns a list with two deterministic elasticity
#' matrices:
#' \item{h_emat}{Matrix of elasticities corresponding to the historical matrix.}
#' \item{ah_emat}{Matrix of elasticities corresponding to the ahistorical
#' matrix, but using summed historical elasticities as the basis of estimation.}
#' 
#' @keywords internal
#' @noRd
.elas3sp_hlefko <- function(Amat, ahstages, hstages) {
    .Call('_lefko3_elas3sp_hlefko', PACKAGE = 'lefko3', Amat, ahstages, hstages)
}

#' Core Time-based Population Matrix Projection Function
#' 
#' Function \code{proj3()} runs the matrix projections used in other functions
#' in package \code{lefko3}.
#' 
#' @name proj3
#' 
#' @param start_vec The starting population vector for the projection.
#' @param core_list A list of full projection matrices, corresponding to the 
#' \code{$A} list within a \code{lefkoMat} object.
#' @param mat_order A vector giving the order of matrices to use at each occasion.
#' @param standardize A logical value stating whether to standardize population
#' size vector to sum to 1 at each estimated occasion.
#' @param growthonly A logical value stating whether to output only a matrix
#' showing the change in population size from one year to the next for use in
#' stochastic population growth rate estimation (TRUE), or a larger matrix also
#' containing the w and v projections for stochastic perturbation analysis,
#' stage distribution estimation, and reproductive value estimation.
#' @param integeronly A logical value indicating whether to round all projected
#' numbers of individuals to the nearest integer.
#' @param sparse_auto A logical value indicating whether to determine whether
#' to use sparse matrix encoding automatically.
#' @param sparse A logical value indicating whether to use sparse matrix
#' encoding if \code{sparse_auto = FALSE}.
#' 
#' @return A matrix in which, if \code{growthonly = TRUE}, each row is the
#' population vector at each projected occasion, and if \code{growthonly =
#' FALSE}, the top third of the matrix is the actual number of individuals in
#' each stage across time, the second third is the w projection (stage
#' distribution), and the bottom third is the v projection (reproductive
#' values) for use in estimation of stochastic sensitivities and elasticities
#' (in addition, a further row is appended to the bottom, corresponding to the
#' \emph{R} vector, which is the sum of the unstandardized \emph{w} vector
#' resulting from each occasion's projection).
#' 
#' @keywords internal
#' @noRd
.proj3 <- function(start_vec, core_list, mat_order, standardize, growthonly, integeronly, sparse_auto, sparse) {
    .Call('_lefko3_proj3', PACKAGE = 'lefko3', start_vec, core_list, mat_order, standardize, growthonly, integeronly, sparse_auto, sparse)
}

#' Slimmed-down Time-based Population Sparse Matrix Projection Function
#' 
#' Function \code{proj3sp()} runs the matrix projections used in some other
#' functions in package \code{lefko3}, but only when the input is sparse. This
#' is a slimmed down version of function \code{proj3()}
#' 
#' @name proj3sp
#' 
#' @param start_vec The starting population vector for the projection.
#' @param core_list A list of full projection matrices, corresponding to
#' the \code{$A} list within a \code{lefkoMat} object. Matrices must be in
#' \code{arma::sp_mat} format.
#' @param mat_order A vector giving the order of matrices to use at each occasion.
#' @param standardize A logical value stating whether to standardize population
#' size vector to sum to 1 at each estimated occasion.
#' @param growthonly A logical value stating whether to output only a matrix
#' showing the change in population size from one year to the next for use in
#' stochastic population growth rate estimation (TRUE), or a larger matrix also
#' containing the w and v projections for stochastic perturbation analysis,
#' stage distribution estimation, and reproductive value estimation.
#' @param integeronly A logical value indicating whether to round all projected
#' numbers of individuals to the nearest integer.
#' 
#' @return A matrix in which, if \code{growthonly = TRUE}, each row is the
#' population vector at each projected occasion, and if \code{growthonly =
#' FALSE}, the top third of the matrix is the actual number of individuals in
#' each stage across time, the second third is the w projection (stage
#' distribution), and the bottom third is the v projection (reproductive
#' values) for use in estimation of stochastic sensitivities and elasticities
#' (in addition, a further row is appended to the bottom, corresponding to the
#' \emph{R} vector, which is the sum of the unstandardized \emph{w} vector
#' resulting from each occasion's projection).
#' 
#' @keywords internal
#' @noRd
.proj3sp <- function(start_vec, core_list, mat_order, standardize, growthonly, integeronly) {
    .Call('_lefko3_proj3sp', PACKAGE = 'lefko3', start_vec, core_list, mat_order, standardize, growthonly, integeronly)
}

#' Conduct Population Projection Simulations
#' 
#' Function \code{projection3()} runs projection simulations. It projects the
#' population and patches forward in time by a user-defined number of
#' occasions. A given set of matrices is utilized and not recreated, although
#' elements may be altered if density dependence is set. Projections may be
#' deterministic or stochastic, and may be density dependent in either case. If
#' deterministic, then projections will be cyclical if matrices exist covering
#' multiple occasions for each population or patch. If stochastic, then annual
#' matrices will be shuffled within patches and populations. Also produces
#' replicates if set.
#' 
#' @name projection3
#' 
#' @param mpm A matrix projection model of class \code{lefkoMat}, or a list of
#' full matrix projection matrices.
#' @param nreps The number of replicate projections.
#' @param times Number of occasions to iterate per replicate. Defaults to
#' 10,000.
#' @param historical An optional logical value only used if object \code{mpm}
#' is a list of matrices, rather than a \code{lefkoMat} object. Defaults to
#' \code{FALSE} for the former case, and overridden by information supplied in
#' the \code{lefkoMat} object for the latter case.
#' @param stochastic A logical value denoting whether to conduct a stochastic
#' projection or a deterministic / cyclical projection.
#' @param standardize A logical value denoting whether to re-standardize the
#' population size to 1.0 at each occasion. Defaults to \code{FALSE}.
#' @param growthonly A logical value indicating whether to produce only the
#' projected population size at each occasion, or a vector showing the stage
#' distribution followed by the reproductive value vector followed by the full
#' population size at each occasion. Defaults to \code{TRUE}.
#' @param integeronly A logical value indicating whether to round the number of
#' individuals projected in each stage at each occasion to the nearest
#' integer. Defaults to \code{FALSE}.
#' @param substoch An integer value indicating whether to force survival-
#' transition matrices to be substochastic in density dependent simulations.
#' Defaults to \code{0}, which does not force substochasticity. Alternatively,
#' \code{1} forces all survival-transition elements to range from 0.0 to 1.0,
#' and forces fecundity to be non-negative; and \code{2} forces all column rows
#' in the survival-transition matrices to total no more than 1.0, in addition
#' to the actions outlined for option \code{1}.
#' @param exp_tol A numeric value used to indicate a maximum value to set
#' exponents to in the core kernel to prevent numerical overflow. Defaults to
#' \code{700}.
#' @param sub_warnings A logical value indicating whether to warn the user if
#' density dependence yields matrix values outside of the realm of possibility.
#' Generally, this means that survival-transition elements altered to values
#' outside of the interval [0, 1], and negative fecundity values, will both
#' yield warnings. Defaults to \code{TRUE}, but becomes \code{FALSE} if
#' \code{quiet = TRUE}.
#' @param quiet A logical value indicating whether to suppress warnings.
#' Defaults to \code{FALSE}.
#' @param year Either a single integer value corresponding to the year to
#' project, or a vector of \code{times} elements with the year to use at each
#' time step. If a vector shorter than \code{times} is supplied, then this
#' vector will be cycled. If not provided, then all annual matrices will be
#' cycled within patches or populations.
#' @param start_vec An optional numeric vector denoting the starting stage
#' distribution for the projection. Defaults to a single individual of each
#' stage.
#' @param start_frame An optional data frame characterizing stages, age-stages,
#' or stage-pairs that should be set to non-zero values in the starting vector,
#' and what those values should be. Can only be used with \code{lefkoMat}
#' objects.
#' @param tweights An optional numeric vector denoting the probabilistic
#' weightings of annual matrices. Defaults to equal weighting among occasions.
#' @param density An optional data frame describing the matrix elements that
#' will be subject to density dependence, and the exact kind of density
#' dependence that they will be subject to. The data frame used should be an
#' object of class \code{lefkoDens}, which is the output from function
#' \code{\link{density_input}()}.
#' @param sparse A text string indicating whether to use sparse matrix encoding
#' (\code{"yes"}) or dense matrix encoding (\code{"no"}), if the
#' \code{lefkoMat} object input as \code{mpm} is composed of standard matrices.
#' Defaults to \code{"auto"}, in which case sparse matrix encoding is used with
#' standard, square matrices with at least 50 rows and no more than 50\% of
#' elements with values greater than zero, or when input \code{lefkoMat}
#' objects include matrices of class \code{dgCMatrix}.
#' 
#' @return A list of class \code{lefkoProj}, which always includes the first
#' three elements of the following, and also includes the remaining elements
#' below when a \code{lefkoMat} object is used as input:
#' \item{projection}{A list of lists of matrices showing the total number of
#' individuals per stage per occasion. The first list corresponds to each
#' pop-patch followed by each population. The inner list corresponds to
#' replicates within each pop-patch or population.}
#' \item{stage_dist}{A list of lists of the actual stage distribution in each
#' occasion in each replicate in each pop-patch or population. The list order
#' is the same as in \code{projection}.}
#' \item{rep_value}{A list of lists of the actual reproductive value in each
#' occasion in each replicate in each pop-patch or population. The list order
#' is the same as in \code{projection}.}
#' \item{pop_size}{A list of data frames showing the total population size in
#' each occasion per replicate (row within data frame) per pop-patch or
#' population (list element).}
#' \item{labels}{A data frame showing the order of populations and patches in
#' item \code{projection}.}
#' \item{ahstages}{The original stageframe used in the study.}
#' \item{hstages}{A data frame showing the order of historical stage pairs.}
#' \item{agestages}{A data frame showing the order of age-stage pairs.}
#' \item{control}{A short vector indicating the number of replicates and the
#' number of occasions projected per replicate.}
#' \item{density}{The data frame input under the density option. Only provided
#' if input by the user.}
#' 
#' @section Notes:
#' Projections are run both at the patch level and at the population level.
#' Population level estimates will be noted at the end of the data frame with
#' \code{0} entries for patch designation.
#' 
#' Weightings given in \code{tweights} do not need to sum to 1. Final
#' weightings used will be based on the proportion per element of the sum of
#' elements in the user-supplied vector.
#' 
#' Starting vectors can be input in one of two ways: 1) as \code{start_vec}
#' input, which is a vector of numbers of the numbers of individuals in each
#' stage, stage pair, or age-stage, with the length of the vector necessarily
#' as long as there are rows in the matrices of the MPM; or 2) as
#' \code{start_frame} input, which is a data frame showing only those stages,
#' stage pairs, or age-stages that should begin with more than 0 individuals,
#' and the numbers of individuals that those stages should start with (this
#' object is created using the \code{\link{start_input}()} function). If both
#' are provided, then \code{start_frame} takes precedence and \code{start_vec}
#' is ignored. If neither is provided, then \code{projection3()} automatically
#' assumes that each stage, stage pair, or age-stage begins with a single
#' individual. Importantly, if a \code{lefkoMat} object is not used, and a list
#' of matrices is provided instead, then \code{start_frame} cannot be utilized
#' and a full \code{start_vec} must be provided to conduct a simulation with
#' starting numbers of individuals other than 1 per stage.
#' 
#' The resulting data frames in element \code{projection} are separated by
#' pop-patch according to the order provided in element \code{labels}, but the
#' matrices for each element of \code{projection} have the result of each
#' replicate stacked in order on top of one another without any break or
#' indication. Results for each replicate must be separated using the
#' information provided in elements \code{control} and the 3 stage
#' descriptor elements.
#' 
#' Density dependent projections are automatically set up if object
#' \code{density} is input. If this object is not included, then density
#' independent projections will be set up. Note that currently, density
#' dependent projections can only be performed with \code{lefkoMat} objects.
#' 
#' When running density dependent simulations involving user-set exponents,
#' such as the beta term in the Ricker function and both the alpha and beta
#' terms in the Usher function, values above or below the computer limits may
#' cause unpredictable behavior. Noted odd behavior includes sudden shifts in
#' population size to negative values. This function produces warnings when
#' such values are used, and the values used for warnings may be reset with the
#' \code{exp_tol} term.
#' 
#' The stage distributions and reproductive values produced are not the
#' asymptotic values as would be given by the standardized right and left
#' eigenvectors associated with the dominant eigenvalue of a matrix, but are
#' vectors describing these values at the specific points in time projected.
#' See equations 14.86 and 14.88 and section 14.4 on Sensitivity and Elasticity
#' Analysis under Environmental Stochasticity in Caswell (2001, Matrix
#' Population Models, Sinauer Associates) for more details.
#' 
#' Consistently positive population growth can quickly lead to population size
#' numbers larger than can be handled computationally. In that circumstance, a
#' continuously rising population size will suddenly become \code{NaN} for the
#' remainder of the projection.
#' 
#' Users wishing to run a projection of a single patch in a \code{lefkoMat}
#' object with multiple patches should subset the MPM first to contain only
#' the patch needed. This can be accomplished with the
#' \code{\link{subset_lM}()} function.
#' 
#' Speed can sometimes be increased by shifting from automatic sparse matrix
#' determination to forced dense or sparse matrix projection. This will most
#' likely occur when matrices have between 30 and 300 rows and columns.
#' Defaults work best when matrices are very small and dense, or very large and
#' sparse.
#' 
#' @seealso \code{\link{start_input}()}
#' @seealso \code{\link{density_input}()}
#' @seealso \code{\link{f_projection3}()}
#' 
#' @examples
#' # Lathyrus example
#' data(lathyrus)
#' 
#' sizevector <- c(0, 100, 13, 127, 3730, 3800, 0)
#' stagevector <- c("Sd", "Sdl", "VSm", "Sm", "VLa", "Flo", "Dorm")
#' repvector <- c(0, 0, 0, 0, 0, 1, 0)
#' obsvector <- c(0, 1, 1, 1, 1, 1, 0)
#' matvector <- c(0, 0, 1, 1, 1, 1, 1)
#' immvector <- c(1, 1, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 100, 11, 103, 3500, 3800, 0.5)
#' 
#' lathframe <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector,
#'   immstatus = immvector, indataset = indataset, binhalfwidth = binvec,
#'   propstatus = propvector)
#' 
#' lathvert <- verticalize3(lathyrus, noyears = 4, firstyear = 1988,
#'   patchidcol = "SUBPLOT", individcol = "GENET", blocksize = 9,
#'   juvcol = "Seedling1988", sizeacol = "Volume88", repstracol = "FCODE88",
#'   fecacol = "Intactseed88", deadacol = "Dead1988",
#'   nonobsacol = "Dormant1988", stageassign = lathframe, stagesize = "sizea",
#'   censorcol = "Missing1988", censorkeep = NA, censor = TRUE)
#' 
#' lathsupp3 <- supplemental(stage3 = c("Sd", "Sd", "Sdl", "Sdl", "Sd", "Sdl"), 
#'   stage2 = c("Sd", "Sd", "Sd", "Sd", "rep", "rep"),
#'   stage1 = c("Sd", "rep", "Sd", "rep", "all", "all"), 
#'   givenrate = c(0.345, 0.345, 0.054, 0.054, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, 0.345, 0.054),
#'   type = c(1, 1, 1, 1, 3, 3), type_t12 = c(1, 2, 1, 2, 1, 1),
#'   stageframe = lathframe, historical = TRUE)
#' 
#' ehrlen3 <- rlefko3(data = lathvert, stageframe = lathframe,
#'   year = c(1989, 1990), stages = c("stage3", "stage2", "stage1"),
#'   supplement = lathsupp3, yearcol = "year2", indivcol = "individ")
#' 
#' lathproj <- projection3(ehrlen3, nreps = 5, stochastic = TRUE)
#' 
#' # Cypripedium example
#' data(cypdata)
#'  
#' sizevector <- c(0, 0, 0, 0, 0, 0, 1, 2.5, 4.5, 8, 17.5)
#' stagevector <- c("SD", "P1", "P2", "P3", "SL", "D", "XSm", "Sm", "Md", "Lg",
#'   "XLg")
#' repvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' obsvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' matvector <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' immvector <- c(0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 0, 0, 0, 0, 0.5, 0.5, 1, 1, 2.5, 7)
#' 
#' cypframe_raw <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector, 
#'   propstatus = propvector, immstatus = immvector, indataset = indataset,
#'   binhalfwidth = binvec)
#' 
#' cypraw_v1 <- verticalize3(data = cypdata, noyears = 6, firstyear = 2004,
#'   patchidcol = "patch", individcol = "plantid", blocksize = 4, 
#'   sizeacol = "Inf2.04", sizebcol = "Inf.04", sizeccol = "Veg.04", 
#'   repstracol = "Inf.04", repstrbcol = "Inf2.04", fecacol = "Pod.04",
#'   stageassign = cypframe_raw, stagesize = "sizeadded", NAas0 = TRUE, 
#'   NRasRep = TRUE)
#' 
#' cypsupp3r <- supplemental(stage3 = c("SD", "SD", "P1", "P1", "P2", "P3", "SL",
#'     "D", "XSm", "Sm", "D", "XSm", "Sm", "mat", "mat", "mat", "SD", "P1"),
#'   stage2 = c("SD", "SD", "SD", "SD", "P1", "P2", "P3", "SL", "SL", "SL", "SL",
#'     "SL", "SL", "D", "XSm", "Sm", "rep", "rep"),
#'   stage1 = c("SD", "rep", "SD", "rep", "SD", "P1", "P2", "P3", "P3", "P3",
#'     "SL", "SL", "SL", "SL", "SL", "SL", "mat", "mat"),
#'   eststage3 = c(NA, NA, NA, NA, NA, NA, NA, "D", "XSm", "Sm", "D", "XSm", "Sm",
#'     "mat", "mat", "mat", NA, NA),
#'   eststage2 = c(NA, NA, NA, NA, NA, NA, NA, "XSm", "XSm", "XSm", "XSm", "XSm",
#'     "XSm", "D", "XSm", "Sm", NA, NA),
#'   eststage1 = c(NA, NA, NA, NA, NA, NA, NA, "XSm", "XSm", "XSm", "XSm", "XSm",
#'     "XSm", "XSm", "XSm", "XSm", NA, NA),
#'   givenrate = c(0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.25, NA, NA, NA, NA, NA, NA,
#'     NA, NA, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
#'     NA, 0.5, 0.5),
#'   type = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3),
#'   type_t12 = c(1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
#'   stageframe = cypframe_raw, historical = TRUE)
#' 
#' cypmatrix3r <- rlefko3(data = cypraw_v1, stageframe = cypframe_raw, 
#'   year = "all", patch = "all", stages = c("stage3", "stage2", "stage1"),
#'   size = c("size3added", "size2added", "size1added"), 
#'   supplement = cypsupp3r, yearcol = "year2", 
#'   patchcol = "patchid", indivcol = "individ")
#' 
#' cypstoch <- projection3(cypmatrix3r, nreps = 5, stochastic = TRUE)
#' 
#' @export projection3
projection3 <- function(mpm, nreps = 1L, times = 10000L, historical = FALSE, stochastic = FALSE, standardize = FALSE, growthonly = TRUE, integeronly = FALSE, substoch = 0L, exp_tol = 700.0, sub_warnings = TRUE, quiet = FALSE, year = NULL, start_vec = NULL, start_frame = NULL, tweights = NULL, density = NULL, sparse = NULL) {
    .Call('_lefko3_projection3', PACKAGE = 'lefko3', mpm, nreps, times, historical, stochastic, standardize, growthonly, integeronly, substoch, exp_tol, sub_warnings, quiet, year, start_vec, start_frame, tweights, density, sparse)
}

#' Estimate Stochastic Population Growth Rate
#' 
#' Function \code{slambda3()} estimates the stochastic population growth rate,
#' \eqn{a}, defined as the long-term arithmetic mean of the log population 
#' growth rate estimated per simulated occasion. This function can handle both
#' lefkoMat objects and lists of full A matrices as input. 
#' 
#' @name slambda3
#' 
#' @param mpm A matrix projection model of class \code{lefkoMat}, or a list of
#' full matrix projection matrices.
#' @param times Number of occasions to iterate. Defaults to \code{10000}.
#' @param historical An optional logical value only used if object \code{mpm}
#' is a list of matrices, rather than a \code{lefkoMat} object. Defaults to
#' \code{FALSE} for the former case, and overridden by information supplied in
#' the \code{lefkoMat} object for the latter case.
#' @param tweights Numeric vector denoting the probabilistic weightings of
#' annual matrices. Defaults to equal weighting among occasions.
#' @param force_sparse A text string indicating whether to force sparse matrix 
#' encoding (\code{"yes"}) or not (\code{"no"}) if the MPM is composed of
#' simple matrices. Defaults to \code{"auto"}, in which case sparse matrix
#' encoding is used with simple square matrices with at least 50 rows and no
#' more than 50\% of elements with values greater than zero.
#' 
#' @return A data frame with the following variables:
#' \item{pop}{The identity of the population.}
#' \item{patch}{The identity of the patch.}
#' \item{a}{Estimate of stochastic growth rate, estimated as the arithmetic
#' mean of the log population growth rate across simulated occasions.}
#' \item{var}{The estimated variance of a.}
#' \item{sd}{The standard deviation of a.}
#' \item{se}{The standard error of a.}
#' 
#' @section Notes:
#' The log stochastic population growth rate, \eqn{a}, is as given in equation
#' 2 of Tuljapurkar, Horvitz, and Pascarella 2003. This term is estimated via
#' projection of randomly sampled matrices, similarly to the procedure outlined
#' in Box 7.4 of Morris and Doak (2002).
#' 
#' Stochastic growth rate is estimated both at the patch level and at the
#' population level. Population level estimates will be noted at the end of the
#' data frame with 0 entries for patch designation.
#' 
#' Weightings given in \code{tweights} do not need to sum to 1. Final
#' weightings used will be based on the proportion per element of the sum of
#' elements in the user-supplied vector.
#' 
#' Speed can sometimes be increased by shifting from automatic sparse matrix
#' determination to forced dense or sparse matrix projection. This will most
#' likely occur when matrices have between 30 and 300 rows and columns.
#' Defaults work best when matrices are very small and dense, or very large and
#' sparse.
#' 
#' @examples
#' data(cypdata)
#' 
#' sizevector <- c(0, 0, 0, 0, 0, 0, 1, 2.5, 4.5, 8, 17.5)
#' stagevector <- c("SD", "P1", "P2", "P3", "SL", "D", "XSm", "Sm", "Md", "Lg",
#'   "XLg")
#' repvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' obsvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' matvector <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' immvector <- c(0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 0, 0, 0, 0, 0.5, 0.5, 1, 1, 2.5, 7)
#' 
#' cypframe_raw <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector, 
#'   propstatus = propvector, immstatus = immvector, indataset = indataset,
#'   binhalfwidth = binvec)
#' 
#' cypraw_v1 <- verticalize3(data = cypdata, noyears = 6, firstyear = 2004,
#'   patchidcol = "patch", individcol = "plantid", blocksize = 4, 
#'   sizeacol = "Inf2.04", sizebcol = "Inf.04", sizeccol = "Veg.04", 
#'   repstracol = "Inf.04", repstrbcol = "Inf2.04", fecacol = "Pod.04",
#'   stageassign = cypframe_raw, stagesize = "sizeadded", NAas0 = TRUE, 
#'   NRasRep = TRUE)
#' 
#' cypsupp3r <- supplemental(stage3 = c("SD", "SD", "P1", "P1", "P2", "P3", "SL",
#'     "D", "XSm", "Sm", "D", "XSm", "Sm", "mat", "mat", "mat", "SD", "P1"),
#'   stage2 = c("SD", "SD", "SD", "SD", "P1", "P2", "P3", "SL", "SL", "SL", "SL",
#'     "SL", "SL", "D", "XSm", "Sm", "rep", "rep"),
#'   stage1 = c("SD", "rep", "SD", "rep", "SD", "P1", "P2", "P3", "P3", "P3",
#'     "SL", "SL", "SL", "SL", "SL", "SL", "mat", "mat"),
#'   eststage3 = c(NA, NA, NA, NA, NA, NA, NA, "D", "XSm", "Sm", "D", "XSm", "Sm",
#'     "mat", "mat", "mat", NA, NA),
#'   eststage2 = c(NA, NA, NA, NA, NA, NA, NA, "XSm", "XSm", "XSm", "XSm", "XSm",
#'     "XSm", "D", "XSm", "Sm", NA, NA),
#'   eststage1 = c(NA, NA, NA, NA, NA, NA, NA, "XSm", "XSm", "XSm", "XSm", "XSm",
#'     "XSm", "XSm", "XSm", "XSm", NA, NA),
#'   givenrate = c(0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.25, NA, NA, NA, NA, NA, NA,
#'     NA, NA, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
#'     NA, 0.5, 0.5),
#'   type = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3),
#'   type_t12 = c(1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
#'   stageframe = cypframe_raw, historical = TRUE)
#' 
#' cypmatrix3r <- rlefko3(data = cypraw_v1, stageframe = cypframe_raw, 
#'   year = "all", patch = "all", stages = c("stage3", "stage2", "stage1"),
#'   size = c("size3added", "size2added", "size1added"), 
#'   supplement = cypsupp3r, yearcol = "year2", 
#'   patchcol = "patchid", indivcol = "individ")
#' 
#' cypstoch <- slambda3(cypmatrix3r)
#' 
#' @export slambda3
slambda3 <- function(mpm, times = 10000L, historical = FALSE, tweights = NULL, force_sparse = NULL) {
    .Call('_lefko3_slambda3', PACKAGE = 'lefko3', mpm, times, historical, tweights, force_sparse)
}

#' Estimate Stochastic Sensitivity or Elasticity of Matrix Set
#' 
#' Function \code{stoch_senselas()} estimates the sensitivity and elasticity to
#' matrix elements of \eqn{a}, defined as the long-term arithmetic mean of the
#' log population growth estimated per simulated occasion (as given in equation 2
#' in Tuljapurkar, Horvitz, and Pascarella 2003). 
#' 
#' @name .stoch_senselas
#' 
#' @param mpm A matrix projection model of class \code{lefkoMat}, or a list of
#' full matrix projection matrices.
#' @param times Number of occasions to iterate. Defaults to 10,000.
#' @param historical An optional logical value only used if object \code{mpm}
#' is a list of matrices, rather than a \code{lefkoMat} object. Defaults to
#' \code{FALSE} for the former case, and overridden by information supplied in
#' the \code{lefkoMat} object for the latter case.
#' @param style An integer designating whether to estimate sensitivity matrices
#' (\code{1}) or elasticity matrices (\code{2}). Defaults to \code{1}.
#' @param sparse An integer denoting whether to run the projection in sparse
#' (\code{1}) format or standard (\code{0}) format.
#' @param tweights Numeric vector denoting the probabilistic weightings of
#' annual matrices. Defaults to equal weighting among occasions.
#' 
#' @return A list of one or two cubes (3d array) where each slice corresponds
#' to a sensitivity or elasticity matrix for a specific pop-patch, followed by
#' the sensitivity or elasticity matrices of all populations (only if multiple
#' pop-patches occur in the input). Two such cubes are only provided when a
#' historical lefkoMat object is used as input, in which case the first
#' element is the historical sensitivity/elasticity matrix, and the second is
#' the ahistorical sensitivity/elasticity matrix.
#' 
#' @section Notes:
#' Weightings given in \code{tweights} do not need to sum to 1. Final
#' weightings used will be based on the proportion per element of the sum of
#' elements in the user-supplied vector.
#' 
#' This function currently requires all patches to have the same occasions, if
#' a \code{lefkoMat} object is used as input. Asymmetry in the number of
#' occasions across patches and/or populations will likely cause errors.
#'
#' @keywords internal
#' @noRd
.stoch_senselas <- function(mpm, times = 10000L, historical = FALSE, style = 1L, sparse = 0L, tweights = NULL) {
    .Call('_lefko3_stoch_senselas', PACKAGE = 'lefko3', mpm, times, historical, style, sparse, tweights)
}

#' Estimate LTRE of Any Population Matrix
#' 
#' \code{ltre3matrix()} returns the one-way fixed deterministic LTRE matrix of
#' a dense or sparse set of input matrices.
#' 
#' @name .ltre3matrix
#' 
#' @param Amats A list of population projection matrices (not an entire
#' \code{lefkoMat} object.
#' @param refnum An integer vector giving the numbers of the matrices to use as
#' reference from_ \code{refmats}.
#' @param refmats_ A list of reference population projection matrices.
#' @param mean A logical value indicating whether to use the element-wise mean
#' matrix as the reference.
#' @param sparse A logical value indicating whether to use sparse or dense
#' format in matrix calculations.
#' 
#' @return This function returns a one-element list with a list of LTRE
#' contributions, each element a matrix of contributions corresponding to each
#' input matrix in \code{Amats}. 
#' 
#' @keywords internal
#' @noRd
.ltre3matrix <- function(Amats, refnum, refmats_ = NULL, mean = TRUE, sparse = FALSE) {
    .Call('_lefko3_ltre3matrix', PACKAGE = 'lefko3', Amats, refnum, refmats_, mean, sparse)
}

#' Estimate sLTRE of Any Population Matrix
#' 
#' \code{sltre3matrix()} returns the one-way stochastic LTRE of a dense or
#' sparse set of input matrices.
#' 
#' @name .sltre3matrix
#' 
#' @param Amats A list of population projection matrices (not an entire
#' \code{lefkoMat} object).
#' @param labels The data frame included in the input \code{lefkoMat} object.
#' @param refnum An integer vector giving the numbers of the matrices to use as
#' reference from \code{refmats}.
#' @param refmats_ A list of reference population projection matrices.
#' @param tweights_ Numeric vector denoting the probabilistic weightings of
#' annual matrices. Defaults to equal weighting among occasions.
#' @param steps The number of occasions to project the stochastic simulation
#' forward, if performing an sLTRE. Defaults to \code{10000}. Note that the
#' total number of occasions projected equals this number plus the number given
#' in object \code{burnin}.
#' @param burnin The number of initial occasions to project the population
#' without calculating population metrics. Defaults to \code{3000}.
#' @param sparse A logical value indicating whether to use sparse or dense
#' format in matrix calculations.
#' @param tol_used A double precision numeric value indicating a lower positive
#' limit to matrix element values used in calculations. Matrix elements lower
#' than this value will be treated as \code{0.0} values.
#' 
#' @return This function returns a list of two lists of matrices. The first,
#' \code{cont_mean}, holds the sLTRE contributions of shifts in mean elements.
#' The second, \code{cont_sd}, holds the sLTRE contributions of shifts in
#' temporal standard deviations of matrix elements.
#' 
#' @section Notes:
#' This function uses the simulation approach developed in Davison et al.
#' (2010), which is a good approximation though not an analytical solution.
#' 
#' @keywords internal
#' @noRd
.sltre3matrix <- function(Amats, labels, refnum, refmats_ = NULL, tweights_ = NULL, steps = 10000L, burnin = 3000L, sparse = FALSE, tol_used = 1e-30) {
    .Call('_lefko3_sltre3matrix', PACKAGE = 'lefko3', Amats, labels, refnum, refmats_, tweights_, steps, burnin, sparse, tol_used)
}

#' Estimate SNA-LTRE of Any Population Matrix
#' 
#' \code{snaltre3matrix()} returns the one-way small noise approximation LTRE
#' of a dense or sparse set of input matrices.
#' 
#' @name .snaltre3matrix
#' 
#' @param Amats A list of population projection matrices (not an entire
#' \code{lefkoMat} object).
#' @param labels The data frame included in the input \code{lefkoMat} object.
#' @param refnum An integer vector giving the numbers of the matrices to use as
#' reference from \code{refmats}.
#' @param refmats_ A list of reference population projection matrices.
#' @param tweights_ Numeric vector denoting the probabilistic weightings of
#' annual matrices. Defaults to equal weighting among occasions.
#' @param sparse A logical value indicating whether to use sparse or dense
#' format in matrix calculations.
#' @param tol_used A double precision numeric value indicating a lower positive
#' limit to matrix element values used in calculations. Matrix elements lower
#' than this value will be treated as \code{0.0} values.
#' 
#' @return This function returns a list of four lists of matrices. The first,
#' \code{cont_mean}, holds the sLTRE contributions of shifts in mean elements.
#' The second, \code{cont_elas}, holds the sLTRE contributions of shifts in
#' deterministic elasticity across matrices. The third, \code{cont_cv}, holds
#' the sLTRE contributions of shifts in temporal coefficients of variation of
#' matrix elements. The fourth, \code{cont_corr}, holds the contributions of
#' shifts in temporal correlations across matrices.
#' 
#' @section Notes:
#' This function uses the simulation approach developed in Davison et al.
#' (2019), which provides an analytical solution to the stochastic LTRE.
#' 
#' @keywords internal
#' @noRd
.snaltre3matrix <- function(Amats, labels, refnum, refmats_ = NULL, tweights_ = NULL, sparse = FALSE, tol_used = 1e-30) {
    .Call('_lefko3_snaltre3matrix', PACKAGE = 'lefko3', Amats, labels, refnum, refmats_, tweights_, sparse, tol_used)
}

#' Main Formula Creation for Function \code{modelsearch()}
#'
#' Function \code{praxis()} is the workhorse function used by function
#' \code{stovokor} to create individual vital rate model formulae, which are
#' then used as input in the global model calls used in function
#' \code{\link{modelsearch}()}.
#' 
#' @name praxis
#' 
#' @param surv A vector of strings indicating the names of the variables coding
#' survival.
#' @param obs A vector of strings indicating the names of the variables coding
#' observation status.
#' @param size A vector of strings indicating the names of the variables coding
#' primary size.
#' @param sizeb A vector of strings indicating the names of the variables
#' coding secondary size.
#' @param sizec A vector of strings indicating the names of the variables
#' coding tertiary size.
#' @param repst A vector of strings indicating the names of the variables
#' coding reproductive status.
#' @param fec A vector of strings indicating the names of the variables coding
#' fecundity.
#' @param matstat A vector of strings indicating the names of the variables
#' coding for maturity status.
#' @param historical A logical value indicating whether to create global models
#' with historical effects.
#' @param response An integer coding for the vital rate to be modeled. Codes
#' are as follows: 1) survival, 2) observation status, 3) primary size,
#' 4) secondary size, 5) tertiary size, 6) reproductive status, 7) fecundity,
#' and 8) maturity status.
#' @param suite A string indicating the scope of independent factors included
#' in the global models. Options include \code{"full"}, \code{"main"},
#' \code{"size"}, \code{"rep"}, and \code{"const"}.
#' @param approach A string indicating whether to use mixed model encoding 
#' (\code{"mixed"}) or GLM encoding (\code{"glm"}).
#' @param nojuvs A logical value indicating that juvenile rates should be
#' estimated (\code{FALSE}) or not (\code{TRUE}).
#' @param juvsize A logical value indicating whether to include size terms in
#' juvenile models.
#' @param indiv A string indicating the name of the variable coding individual
#' identity.
#' @param patch A string indicating the name of the variable coding patch
#' identity.
#' @param year A string indicating the name of the variable coding time
#' \emph{t}.
#' @param age A string indicating the name of the variable coding age.
#' @param densitycol The name of the density variable, or \code{"none"}.
#' @param indcova_raw A vector of strings indicating the names in times
#' \emph{t}+1, \emph{t}, and \emph{t}-1 of a specific individual covariate used
#' in the dataset.
#' @param indcovb_raw A vector of strings indicating the names in times
#' \emph{t}+1, \emph{t}, and \emph{t}-1 of a specific individual covariate used
#' in the dataset.
#' @param indcovc_raw A vector of strings indicating the names in times
#' \emph{t}+1, \emph{t}, and \emph{t}-1 of a specific individual covariate used
#' in the dataset.
#' @param sizebused A logical value denoting if secondary size variables are to
#' be used.
#' @param sizecused A logical value denoting if tertiary size variables are to
#' be used.
#' @param grouptest A logical value indicating whether to test for group
#' effect.
#' @param ageused A logical value indicating whether to test for age effect.
#' @param densityused A logical value indicating whether the density variable
#' is to be used.
#' @param indcovaused Logical value indicating whether individual covariate a
#' is used.
#' @param indcovbused Logical value indicating whether individual covariate b
#' is used.
#' @param indcovcused Logical value indicating whether individual covariate c
#' is used.
#' @param pasrand A logical value indicating whether to treat patch as a random
#' variable within mixed models.
#' @param yasrand A logical value indicating whether to treat year as a random
#' variable within mixed models.
#' @param iaasrand A logical value indicating whether to treat indcova as
#' random.
#' @param ibasrand A logical value indicating whether to treat indcovb as
#' random.
#' @param icasrand A logical value indicating whether to treat indcovc as
#' random.
#' @param iaasfac A logical value indicating whether to treat indcova as a
#' factor variable.
#' @param ibasfac A logical value indicating whether to treat indcovb as a
#' factor variable.
#' @param icasfac A logical value indicating whether to treat indcovc as a
#' factor variable.
#' @param fectime An integer indicating whether to use reproductive output in
#' time \emph{t} (2) or time \emph{t}+1 (3) as the response for fecundity.
#' @param repstcheck A boolean variable denoting whether reproductive status is
#' being tested as a response within the suite of vital rates being estimated.
#' 
#' @return A list with four elements. The first and second are both one-element
#' string vectors, with the first coding for the adult vital rate global model,
#' and the second coding the juvenile vital rate global model. The third and
#' fourth code the number of terms tested in each of these models,
#' respectively.
#'
#' @keywords internal
#' @noRd
NULL

#' Main Formula Creation for Function \code{modelsearch()}
#'
#' Function \code{stovokor()} creates the list of formulae to be used as input
#' in the global model calls used in function \code{\link{modelsearch}()}.
#' 
#' @name stovokor
#' 
#' @param surv A vector of strings indicating the names of the variables coding
#' survival.
#' @param obs A vector of strings indicating the names of the variables coding
#' observation status.
#' @param size A vector of strings indicating the names of the variables coding
#' primary size.
#' @param sizeb A vector of strings indicating the names of the variables
#' coding secondary size.
#' @param sizec A vector of strings indicating the names of the variables
#' coding tertiary size.
#' @param repst A vector of strings indicating the names of the variables
#' coding reproductive status.
#' @param fec A vector of strings indicating the names of the variables coding
#' fecundity.
#' @param matstat A vector of strings indicating the names of the variables
#' coding for maturity status.
#' @param vitalrates A vector of strings indicating which vital rates will be
#' estimated.
#' @param historical A logical value indicating whether to create global models
#' with historical effects.
#' @param suite A string indicating the scope of independent factors included
#' in the global models. Options include \code{"full"}, \code{"main"},
#' \code{"size"}, \code{"rep"}, and \code{"const"}.
#' @param approach A string indicating whether to use mixed model encoding 
#' (\code{"mixed"}) or GLM encoding (\code{"glm"}).
#' @param nojuvs A logical value indicating that juvenile rates should be
#' estimated (\code{FALSE}) or not (\code{TRUE}).
#' @param juvsize A logical value indicating whether to include size terms in
#' juvenile models.
#' @param indiv A string indicating the name of the variable coding individual
#' identity.
#' @param patch A string indicating the name of the variable coding patch
#' identity.
#' @param year A string indicating the name of the variable coding time
#' \emph{t}.
#' @param age A string indicating the name of the variable coding age.
#' @param densitycol The name of the density variable, or \code{"none"}.
#' @param indcova A vector of strings indicating the names in times \emph{t}+1,
#' \emph{t}, and \emph{t}-1 of a specific individual covariate used in the
#' dataset.
#' @param indcovb A vector of strings indicating the names in times \emph{t}+1,
#' \emph{t}, and \emph{t}-1 of a specific individual covariate used in the
#' dataset.
#' @param indcovc A vector of strings indicating the names in times \emph{t}+1,
#' \emph{t}, and \emph{t}-1 of a specific individual covariate used in the
#' dataset.
#' @param sizebused A logical vector indicating if secondary size variables are
#' to be tested in each of the 14 vital rate models.
#' @param sizecused A logical vector indicating if tertiary size variables are
#' to be tested in each of the 14 vital rate models.
#' @param grouptest A logical vector indicating if group is to be tested in
#' each of the 14 vital rate models.
#' @param ageused A logical vector indicating if age is to be tested in each of
#' the 14 vital rate models.
#' @param densityused A logical vector indicating if density is to be tested in
#' each of the 14 vital rate models.
#' @param indcovaused A logical vector indicating if individual covariate a is
#' to be tested in each of the 14 vital rate models.
#' @param indcovbused A logical vector indicating if individual covariate b is
#' to be tested in each of the 14 vital rate models.
#' @param indcovcused A logical vector indicating if individual covariate c is
#' to be tested in each of the 14 vital rate models.
#' @param pasrand A logical value indicating whether to treat patch as a random
#' variable within mixed models.
#' @param yasrand A logical value indicating whether to treat year as a random
#' variable within mixed models.
#' @param iaasrand A logical value indicating whether to treat indcova as
#' random.
#' @param ibasrand A logical value indicating whether to treat indcovb as
#' random.
#' @param icasrand A logical value indicating whether to treat indcovc as
#' random.
#' @param iaasfac A logical value indicating whether to treat indcova as a
#' factor variable.
#' @param ibasfac A logical value indicating whether to treat indcovb as a
#' factor variable.
#' @param icasfac A logical value indicating whether to treat indcovc as a
#' factor variable.
#' @param fectime An integer indicating whether to use reproductive output in
#' time \emph{t} (2) or time \emph{t}+1 (3) as the response for fecundity.
#' @param size_zero A boolean variable indicating whether the primary size
#' model is zero-inflated.
#' @param sizeb_zero A boolean variable indicating whether the secondary size
#' model is zero-inflated.
#' @param sizec_zero A boolean variable indicating whether the tertiary size
#' model is zero-inflated.
#' @param jsize_zero A boolean variable indicating whether the juvenile primary
#' size model is zero-inflated.
#' @param jsizeb_zero A boolean variable indicating whether the juvenile
#' secondary size model is zero-inflated.
#' @param jsizec_zero A boolean variable indicating whether the juvenile
#' tertiary size model is zero-inflated.
#' 
#' @return A list of four lists. The first list includes the 14 main global
#' models covering all 14 vital rate responses, followed by an associated
#' \code{paramnames} object, and a vector of 14 integers showing the number of
#' terms tested in each respective model. The next three lists repeat this
#' structure without a new paramnames object, but for a reduced set of models
#' (\code{alternate}), a glm-only version of the models (\code{glm.alternate}),
#' and a version without any individual covariates (\code{nocovs.alternate}).
#'
#' @keywords internal
#' @noRd
.stovokor <- function(surv, obs, size, sizeb, sizec, repst, fec, matstat, vitalrates, historical, suite, approach, nojuvs, juvsize, indiv, patch, year, age, densitycol, indcova, indcovb, indcovc, sizebused, sizecused, grouptest, ageused, densityused, indcovaused, indcovbused, indcovcused, pasrand, yasrand, iaasrand, ibasrand, icasrand, iaasfac, ibasfac, icasfac, fectime, size_zero, sizeb_zero, sizec_zero, jsize_zero, jsizeb_zero, jsizec_zero) {
    .Call('_lefko3_stovokor', PACKAGE = 'lefko3', surv, obs, size, sizeb, sizec, repst, fec, matstat, vitalrates, historical, suite, approach, nojuvs, juvsize, indiv, patch, year, age, densitycol, indcova, indcovb, indcovc, sizebused, sizecused, grouptest, ageused, densityused, indcovaused, indcovbused, indcovcused, pasrand, yasrand, iaasrand, ibasrand, icasrand, iaasfac, ibasfac, icasfac, fectime, size_zero, sizeb_zero, sizec_zero, jsize_zero, jsizeb_zero, jsizec_zero)
}

#' Creates a Skeleton Paramnames Object for Use in Function-based Modeling
#' 
#' Creates a simple skeleton \code{paramnames} object that can be entered as
#' input in functions \code{\link{flefko2}()}, \code{\link{flefko3}()}, and
#' \code{\link{aflefko2}()}.
#' 
#' @name create_pm
#' 
#' @param name_terms A logical value indicating whether to start each variable
#' name as \code{none} if \code{FALSE}, or as the default \code{modelparams}
#' name if \code{TRUE}. Defaults to \code{FALSE}.
#' 
#' @return A three column data frame, of which the first describes the
#' parameters in reasonably plain English, the second gives the name of the
#' parameter within the MPM generating functions, and the third is to be
#' edited with the names of the variables as they appear in the models.
#' 
#' @section Notes:
#' The third column in the resulting object should be edited with the names only
#' of those variables actually used in vital rate modeling. This
#' \code{paramnames} object should apply to all models used in a single MPM
#' building exercise. So, for example, if the models used include random terms,
#' then they should all have the same random terms. Fixed terms can vary,
#' however.
#' 
#' @examples 
#' our_pm <- create_pm()
#' our_pm
#' 
#' @export
create_pm <- function(name_terms = FALSE) {
    .Call('_lefko3_create_pm', PACKAGE = 'lefko3', name_terms)
}

#' Check and Reorganize Density Input Table Into Usable Format
#' 
#' Function \code{density_reassess()} takes a density input table as supplied
#' by the \code{\link{density_input}()} function, and checks and rearranges it
#' into a single, complete density input table.
#' 
#' @name density_reassess
#' 
#' @param stageframe The correct stageframe, already modified by
#' \code{\link{sf_reassess}()}.
#' @param dens_inp The density input data frame as is toward the end of
#' \code{\link{density_input}()}.
#' @param agestages The agestages element from the used \code{lefkoMat} object.
#' Only needed if an age-by-stage MPM will be used.
#' @param historical A logical value denoting whether MPM is historical.
#' Defaults to \code{FALSE}.
#' @param agebystage A logical value denoting whether MPM is age-by-stage.
#' Defaults to \code{FALSE}.
#' 
#' @return A corrected density input data frame, usable in density-dependent
#' MPM creation.
#' 
#' @keywords internal
#' @noRd
NULL

#' Create Stageframe for Population Matrix Projection Analysis
#' 
#' Function \code{sf_create()} returns a data frame describing each ahistorical
#' life history stage in the life history model. This data frame can be used as 
#' input into MPM creation functions including \code{\link{flefko3}()}, 
#' \code{\link{flefko2}()}, \code{\link{aflefko2}()}, \code{\link{rlefko3}()},
#' \code{\link{rlefko2}()}, and \code{\link{arlefko2}()}, in which it
#' determines how each stage is treated during matrix estimation.
#' 
#' @name sf_create
#' 
#' @param sizes A numeric vector of the typical or representative size of each
#' life history stage. If making function-based MPMs, then this may be a
#' vector composed of the midpoints of each size bin, or simply of sizes
#' characteristic of the size bins. If denoting the boundary of an automated
#' size classification group, then should denote the absolute minimum size of
#' that group, or the absolute size of that group (see \code{Notes}).
#' @param stagenames A vector of stage names, in the same order as elements in
#' sizes. Can also be set to \code{ipm} for automated size classification (see
#' \code{Notes} section).
#' @param sizesb An optional numeric vector for a second size metric for each
#' life history stage. Only to be used if stages are defined by at least two
#' size metrics in all cases. Same issues apply as in \code{sizes}.
#' @param sizesc An optional numeric vector for a third size metric for each
#' life history stage. Only to be used if stages are defined by at least three
#' size metrics in all cases. Same issues apply as in \code{sizes}.
#' @param repstatus A vector denoting the binomial reproductive status of each
#' life history stage. Defaults to \code{1}.
#' @param obsstatus A vector denoting the binomial observation status of each
#' life history stage. Defaults to \code{1}, but may be changed for
#' unobservable stages.
#' @param propstatus A vector denoting whether each life history stage is a 
#' propagule. Such stages are generally only used in fecundity estimation. 
#' Defaults to \code{0}.
#' @param matstatus A vector denoting whether each stage is mature. Must be
#' composed of binomial values if given. Defaults to 1 for all stages defined 
#' in \code{sizes}.
#' @param immstatus A vector denoting whether each stage is immature. Must be
#' composed of binomial values if given. Defaults to the complement of vector
#' \code{matstatus}.
#' @param minage An optional vector denoting the minimum age at which a stage
#' can occur. Only used in age x stage matrix development. Defaults to
#' \code{NA}.
#' @param maxage An optional vector denoting the maximum age at which a stage
#' should occur. Only used in age x stage matrix development. Defaults to
#' \code{NA}.
#' @param indataset A vector designating which stages are found within the 
#' dataset. While \code{\link{rlefko2}()} and \code{\link{rlefko3}()} can use
#' all stages in the input dataset, \code{\link{flefko3}()} and
#' \code{\link{flefko2}()} can only handle size-classified stages with
#' non-overlapping combinations of size and status variables. Stages that do
#' not actually exist within the dataset should be marked as \code{0} in this
#' vector.
#' @param sizemin A vector giving the absolute minimum values corresponding to
#' each size in the \code{sizes} vector. Requires associated values for
#' \code{sizemax} if used. Only required if not using \code{binhalfwidth}.
#' @param sizebmin A vector giving the absolute minimum values corresponding to
#' each size in the \code{sizesb} vector. Requires associated values for
#' \code{sizebmax} if used. Only required if not using \code{binhalfwidthb}.
#' @param sizecmin A vector giving the absolute minimum values corresponding to
#' each size in the \code{sizesc} vector. Requires associated values for
#' \code{sizecmax} if used. Only required if not using \code{binhalfwidthc}.
#' @param sizemax A vector giving the absolute maximum values corresponding to
#' each size in the \code{sizes} vector. Requires associated values for
#' \code{sizemin} if used. Only required if not using \code{binhalfwidth}.
#' @param sizebmax A vector giving the absolute maximum values corresponding to
#' each size in the \code{sizesb} vector. Requires associated values for
#' \code{sizebmin} if used. Only required if not using \code{binhalfwidthb}.
#' @param sizecmax A vector giving the absolute maximum values corresponding to
#' each size in the \code{sizesc} vector. Requires associated values for
#' \code{sizecmin} if used. Only required if not using \code{binhalfwidthc}.
#' @param binhalfwidth A numeric vector giving the half-width of size bins.
#' Required if \code{sizemin} and \code{sizemax} are not used. Defaults to
#' \code{0.5} for all sizes.
#' @param binhalfwidthb A numeric vector giving the half-width of size bins
#' used for the optional second size metric. Required if \code{sizebmin} and
#' \code{sizebmax} are not used but two or three size classes are used.
#' Defaults to \code{0.5} for all sizes.
#' @param binhalfwidthc A numeric vector giving the half-width of size bins
#' used for the optional third size metric. Required if \code{sizecmin} and
#' \code{sizecmax} are not used but three size classes are used. Defaults to
#' \code{0.5} for all sizes.
#' @param group An integer vector providing information on each respective
#' stage's size classification group. If used, then function-based MPM creation
#' functions \code{\link{flefko2}()}, \code{\link{flefko3}()}, and
#' \code{\link{aflefko2}()} will estimate transitions only within these groups
#' and for allowed cross-group transitions noted within the supplement table.
#' Defaults to \code{0}.
#' @param comments An optional vector of text entries holding useful text
#' descriptions of all stages.
#' @param roundsize This parameter sets the precision of size classification,
#' and equals the number of digits used in rounding sizes. Defaults to
#' \code{5}.
#' @param roundsizeb This parameter sets the precision of size classification
#' in the optional second size metric, and equals the number of digits used in
#' rounding sizes. Defaults to \code{5}.
#' @param roundsizec This parameter sets the precision of size classification
#' in the optional third size metric, and equals the number of digits used in
#' rounding sizes. Defaults to \code{5}.
#' @param ipmbins An integer giving the number of size bins to create using the
#' primary size classification variable. This number is in addition to any
#' stages that are not size classified. Defaults to \code{100}, and numbers
#' greater than this yield a warning about the loss of statistical power and
#' increasing chance of matrix over-parameterization resulting from increasing
#' numbers of stages.
#' @param ipmbinsb An optional integer giving the number of size bins to create
#' using the secondary size classification variable. This number is in addition
#' to any stages that are not size classified, as well as in addition to any
#' automated size classification using the primary and tertiary size variables.
#' Defaults to \code{NA}, and must be set to a positive integer for automated
#' size classification to progress.
#' @param ipmbinsc An optional integer giving the number of size bins to create
#' using the tertiary size classification variable. This number is in addition
#' to any stages that are not size classified, as well as in addition to any
#' automated size classification using the primary and secondary size
#' variables. Defaults to \code{NA}, and must be set to a positive integer for
#' automated size classification to progress.
#' 
#' @return A data frame of class \code{stageframe}, which includes information
#' on the stage name, size, reproductive status, observation status, propagule 
#' status, immaturity status, maturity status, presence within the core dataset, 
#' stage group classification, raw bin half-width, and the minimum, 
#' center, and maximum of each size bin, as well as its width. If minimum and
#' maximum ages were specified, then these are also included. Also includes an 
#' empty string variable that can be used to describe stages meaningfully. This
#' object can be used as the \code{stageframe} input for \code{\link{flefko3}()} 
#' \code{\link{flefko2}()}, \code{\link{rlefko3}()}, and \code{\link{rlefko2}()}.
#' 
#' Variables in this data frame include the following:
#' \item{stage}{The unique names of the stages to be analyzed.}
#' \item{size}{The typical or representative size at which each stage occurs.}
#' \item{size_b}{Size at which each stage occurs in terms of a second size
#' variable, if one exists.}
#' \item{size_c}{Size at which each stage occurs in terms of a third size
#' variable, if one exists.}
#' \item{min_age}{The minimum age at which the stage may occur.}
#' \item{max_age}{The maximum age at which the stage may occur.}
#' \item{repstatus}{A binomial variable showing whether each stage is
#' reproductive.}
#' \item{obsstatus}{A binomial variable showing whether each stage is
#' observable.}
#' \item{propstatus}{A binomial variable showing whether each stage is a
#' propagule.}
#' \item{immstatus}{A binomial variable showing whether each stage can occur as
#' immature.}
#' \item{matstatus}{A binomial variable showing whether each stage occurs in
#' maturity.}
#' \item{indataset}{A binomial variable describing whether each stage occurs in
#' the input dataset.}
#' \item{binhalfwidth_raw}{The half-width of the size bin, as input.}
#' \item{sizebin_min}{The minimum size at which the stage may occur.}
#' \item{sizebin_max}{The maximum size at which the stage may occur.}
#' \item{sizebin_center}{The midpoint of the size bin at which the stage may
#' occur.}
#' \item{sizebin_width}{The width of the size bin corresponding to the stage.}
#' \item{binhalfwidthb_raw}{The half-width of the size bin of a second size
#' variable, as input.}
#' \item{sizebinb_min}{The minimum size at which the stage may occur.}
#' \item{sizebinb_max}{The maximum size at which the stage may occur.}
#' \item{sizebinb_center}{The midpoint of the size bin at which the stage may
#' occur, in terms of a second size variable.}
#' \item{sizebinb_width}{The width of the size bin corresponding to the stage,
#' in terms of a second size variable.}
#' \item{binhalfwidthc_raw}{The half-width of the size bin of a third size
#' variable, as input.}
#' \item{sizebinc_min}{The minimum size at which the stage may occur, in terms
#' of a third size variable.}
#' \item{sizebinc_max}{The maximum size at which the stage may occur, in terms
#' of a third size variable.}
#' \item{sizebinc_center}{The midpoint of the size bin at which the stage may
#' occur, in terms of a third size variable.}
#' \item{sizebinc_width}{The width of the size bin corresponding to the stage,
#' in terms of a third size variable.}
#' \item{group}{An integer denoting the size classification group that the
#' stage falls within.}
#' \item{comments}{A text field for stage descriptions.}
#' 
#' @section Notes:
#' Vectors used to create a stageframe may not mix \code{NA} values with
#' non-\code{NA} values.
#' 
#' If an IPM or function-based matrix with automated size classification is
#' desired, then two stages that occur within the dataset and represent the
#' lower and upper size limits of the IPM must be marked with \code{ipm} in
#' the stagenames vector. These stages should have all characteristics other
#' than size equal, and the size input for whichever size will be classified
#' automatically must include the minimum in one stage and the maximum in the
#' other. The actual characteristics of the first stage encountered in the
#' inputs will be used as the template for the creation of these sizes. Note
#' that \code{ipm} refers to size classification with the primary size
#' variable. To automate size classification with the secondary size variable,
#' use \code{ipmb}, and to automate size classification with the tertiary size
#' variable, use \code{ipmc}. To nest automated size classifications, use 
#' \code{ipmab} for the primary and secondary size variables, \code{ipmac} for
#' the primary and tertiary size variables, \code{ipmbc} for the secondary and
#' tertiary size variables, and \code{ipmabc} for all three size variables.
#' The primary size variable can also be set with \code{ipma}.
#' 
#' If two or more groups of stages, each with its own characteristics, are to
#' be developed for an IPM or function-based MPM, then an even number of stages
#' with two stages marking the minimum and maximum size of each group should be
#' marked with the same code as given above, with all other characteristics
#' equal within each group.
#' 
#' Stage classification groups set with the \code{group} variable create zones
#' within function-based matrices in which survival transitions are estimated.
#' These groups should not be set if transitions are possible between all
#' stages regardless of group. To denote specific transitions as estimable
#' between stage groups, use the \code{\link{supplemental}()} function.
#' 
#' If importing an IPM rather than building one with \code{lefko3}: Using the
#' \code{vrm_input} approach to building function-based MPMs with provided
#' linear model slope coefficients requires careful attention to the
#' stageframe. Although no hfv data frame needs to be entered in this instance,
#' stages for which vital rates are to be estimated via linear models
#' parameterized with coefficients provided via function
#' \code{\link{vrm_import}()} should be marked as occurring within the dataset.
#' Stages for which the provided coefficients should not be used should be
#' marked as not occurring within the dataset.
#' 
#' @examples
#' # Lathyrus example
#' data(lathyrus)
#' 
#' sizevector <- c(0, 100, 13, 127, 3730, 3800, 0)
#' stagevector <- c("Sd", "Sdl", "VSm", "Sm", "VLa", "Flo", "Dorm")
#' repvector <- c(0, 0, 0, 0, 0, 1, 0)
#' obsvector <- c(0, 1, 1, 1, 1, 1, 0)
#' matvector <- c(0, 0, 1, 1, 1, 1, 1)
#' immvector <- c(1, 1, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 100, 11, 103, 3500, 3800, 0.5)
#' 
#' lathframe <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector,
#'   immstatus = immvector, indataset = indataset, binhalfwidth = binvec,
#'   propstatus = propvector)
#' 
#' # Cypripedium example
#' data(cypdata)
#' 
#' sizevector <- c(0, 0, 0, 0, 0, 0, 1, 2.5, 4.5, 8, 17.5)
#' stagevector <- c("SD", "P1", "P2", "P3", "SL", "D", "XSm", "Sm", "Md", "Lg",
#'   "XLg")
#' repvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' obsvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' matvector <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' immvector <- c(0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 0, 0, 0, 0, 0.5, 0.5, 1, 1, 2.5, 7)
#' 
#' cypframe_raw <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector,
#'   propstatus = propvector, immstatus = immvector, indataset = indataset,
#'   binhalfwidth = binvec)
#' 
#' @export sf_create
sf_create <- function(sizes, stagenames = NULL, sizesb = NULL, sizesc = NULL, repstatus = NULL, obsstatus = NULL, propstatus = NULL, matstatus = NULL, immstatus = NULL, minage = NULL, maxage = NULL, indataset = NULL, sizemin = NULL, sizebmin = NULL, sizecmin = NULL, sizemax = NULL, sizebmax = NULL, sizecmax = NULL, binhalfwidth = NULL, binhalfwidthb = NULL, binhalfwidthc = NULL, group = NULL, comments = NULL, roundsize = 5L, roundsizeb = 5L, roundsizec = 5L, ipmbins = 100L, ipmbinsb = NA_integer_, ipmbinsc = NA_integer_) {
    .Call('_lefko3_sf_create', PACKAGE = 'lefko3', sizes, stagenames, sizesb, sizesc, repstatus, obsstatus, propstatus, matstatus, immstatus, minage, maxage, indataset, sizemin, sizebmin, sizecmin, sizemax, sizebmax, sizecmax, binhalfwidth, binhalfwidthb, binhalfwidthc, group, comments, roundsize, roundsizeb, roundsizec, ipmbins, ipmbinsb, ipmbinsc)
}

#' Calculate Actual Stage, Age, Stage-Pair, or Age-Stage Distributions
#' 
#' Function \code{actualstage3()} shows the frequencies and proportions of
#' each stage, stage pair, age-stage, or age in each year.
#' 
#' @name actualstage3
#' 
#' @param data A demographic dataset in hfv format.
#' @param check_stage A logical value indicating whether to assess frequencies
#' and proportions of stages. Defaults to \code{TRUE}.
#' @param check_age A logical value indicating whether to assess frequencies and
#' proportions of ages. Defaults to \code{FALSE}.
#' @param historical A logical value indicating whether the stage structure
#' should be ahistorical (\code{FALSE}) or historical (\code{TRUE}). Defaults to
#' \code{FALSE}.
#' @param year2 A string value indicating the name of the variable coding for
#' monitoring occasion at time \emph{t}. Defaults to \code{"year2"}.
#' @param indices A vector of three strings, indicating the stage indices for
#' times \emph{t}+1, \emph{t}, and \emph{t}-1, respectively, in \code{data}.
#' Defaults to \code{c("stage3index", "stage2index", "stage1index")}.
#' @param stagecol A vector of three strings, indicating the stage name columns
#' for times \emph{t}+1, \emph{t}, and \emph{t}-1, respectively, in \code{data}.
#' Defaults to \code{stagecol = c("stage3", "stage2", "stage1")}.
#' @param agecol A single string indicating the age of individuals in time
#' \emph{t}. Defaults to \code{"obsage"}.
#' @param remove_stage A string vector indicating the names of stages to remove
#' from consideration. Defaults to \code{"NotAlive"}.
#' @param t1_allow A string vector indicating which stages to be removed should
#' be allowed in the stage at time \emph{t}-1 portion of historical stage
#' pairs, if \code{historical = TRUE}. Defaults to \code{"NotAlive"}. Can also
#' be set to \code{"none"}.
#' 
#' @return A data frame with the following variables:
#' \item{rowid}{A string identifier term, equal to the monitoring occasion in
#' time \emph{t} and the stage index.}
#' \item{stageindex}{The stageframe index of the stage. Only output if
#' \code{check_stage = TRUE}.}
#' \item{stage}{The name of each stage, or \code{NA}. Only output if
#' \code{check_stage = TRUE}.}
#' \item{stage2}{The name of the stage in time \emph{t}. Only output if
#' \code{check_stage = TRUE}.}
#' \item{stage1}{The name of the stage in time \emph{t}-1, or \code{NA}. Only
#' output if \code{check_stage = TRUE}.}
#' \item{age}{The age at time \emph{t}. Only output if \code{check_age = TRUE}.}
#' \item{year2}{Monitoring occasion in time \emph{t}.}
#' \item{frequency}{The number of individuals in the respective stage and time.}
#' \item{actual_prop}{The proportion of individuals alive in time \emph{t} in
#' the respective stage.}
#' 
#' @section Notes:
#' This function produces frequencies and proportions of stages in hfv formatted
#' data using stage index variables rather than stage name variables, and so
#' requires the former. The latter is only required if the user wants to know
#' the associated stage names.
#' 
#' Frequencies and proportions will be calculated for all times, including the
#' last time, which is generally found in the \code{stage3} columns of the last
#' \code{year2} entry in object \code{data}. The default is to treat the
#' \code{year2} entry for that time as \code{max(year2) + 1}.
#' 
#' If \code{check_stage = TRUE} and \code{check_age = FALSE}, then this function
#' will assess frequencies and proportions of stages or historical stage-pairs.
#' If both \code{check_stage = TRUE} and \code{check_age = TRUE}, then this
#' function will assess frequencies and proportions of age-stages. If
#' \code{check_stage = FALSE} and \code{check_age = TRUE}, then the frequencies
#' and proportions of ages only will be assessed.
#' 
#' Note that no stageframe is required for this function to operate. Stage
#' names and their order are inferred directly from the object \code{data}.
#' 
#' @examples
#' sizevector <- c(0, 0, 0, 0, 0, 0, 1, 3, 6, 11, 19.5)
#' stagevector <- c("SD", "P1", "P2", "P3", "SL", "D", "XSm", "Sm", "Md", "Lg",
#'   "XLg")
#' repvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' obsvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' matvector <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' immvector <- c(0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 0, 0, 0, 0, 0.5, 0.5, 1.5, 1.5, 3.5, 5)
#' comments <- c("Dormant seed", "1st yr protocorm", "2nd yr protocorm",
#'   "3rd yr protocorm", "Seedling", "Dormant adult",
#'   "Extra small adult (1 shoot)", "Small adult (2-4 shoots)",
#'   "Medium adult (5-7 shoots)", "Large adult (8-14 shoots)",
#'   "Extra large adult (>14 shoots)")
#' cypframe_raw <- sf_create(sizes = sizevector, stagenames = stagevector, 
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector,
#'   propstatus = propvector, immstatus = immvector, indataset = indataset, 
#'   binhalfwidth = binvec, comments = comments)
#' 
#' cypraw_v1 <- verticalize3(data = cypdata, noyears = 6, firstyear = 2004, 
#'   patchidcol = "patch", individcol = "plantid", blocksize = 4,
#'   sizeacol = "Inf2.04", sizebcol = "Inf.04", sizeccol = "Veg.04",
#'   repstracol = "Inf.04", repstrbcol = "Inf2.04", fecacol = "Pod.04",
#'   stageassign = cypframe_raw, stagesize = "sizeadded", NAas0 = TRUE,
#'   NRasRep = TRUE, age_offset = 4)
#' 
#' all_stage_props_ah <- actualstage3(cypraw_v1)
#' all_stage_props_h <- actualstage3(cypraw_v1, historical = TRUE)
#' all_stage_props_h_NANotAllow <- actualstage3(cypraw_v1, historical = TRUE,
#'   t1_allow = "none")
#' all_stage_props_as <- actualstage3(cypraw_v1, check_age = TRUE)
#' all_age_props <- actualstage3(cypraw_v1, check_stage = FALSE,
#'   check_age = TRUE)
#' 
#' @export actualstage3
actualstage3 <- function(data, check_stage = TRUE, check_age = FALSE, historical = FALSE, year2 = NULL, indices = NULL, stagecol = NULL, agecol = NULL, remove_stage = NULL, t1_allow = NULL) {
    .Call('_lefko3_actualstage3', PACKAGE = 'lefko3', data, check_stage, check_age, historical, year2, indices, stagecol, agecol, remove_stage, t1_allow)
}

#' Set Density Dependence Relationships in Matrix Elements
#' 
#' Function \code{density_input()} provides all necessary data to incorporate
#' density dependence into a \code{lefkoMat} object, a list of matrices, or a
#' single matrix. Four forms of density dependence are allowed, including the
#' Ricker function, the Beverton-Holt function, the Usher function, and the
#' logistic function. In each case, density must have an effect with a delay of
#' at least one time-step (see Notes). The resulting data frame provides a
#' guide for other \code{lefko3} functions to modify matrix elements by
#' density.
#'
#' @name density_input
#' 
#' @param mpm The \code{lefkoMat} object that will be subject to density
#' dependent projection.
#' @param stage3 A vector showing the name or number of the stage in occasion
#' \emph{t}+1 in the transitions to be affected by density. Abbreviations for
#' groups of stages are also usable (see Notes).
#' @param stage2 A vector showing the name or number of the stage in occasion
#' \emph{t} in the transition to be affected by density. Abbreviations for
#' groups of stages are also usable (see Notes).
#' @param stage1 A vector showing the name or number of the stage in occasion
#' \emph{t}-1 in the transition to be affected by density. Only needed if a
#' historical MPM is used. Abbreviations for groups of stages are also usable
#' (see Notes).
#' @param age2 A vector showing the age of the stage in occasion \emph{t} in the
#' transition to be affected by density. Only needed if an age-by-stage MPM is
#' used.
#' @param style A vector coding for the style of density dependence on each
#' transition subject to density dependence. Options include \code{1},
#' \code{ricker}, \code{ric}, or \code{r} for the Ricker function; \code{2},
#' \code{beverton}, \code{bev}, and \code{b} for the Beverton-Holt function;
#' \code{3}, \code{usher}, \code{ush}, and \code{u} for the Usher function; and
#' \code{4}, \code{logistic}, \code{log}, and \code{l} for the logistic
#' function. If only a single code is provided, then all noted transitions are
#' assumed to be subject to this style of density dependence. Defaults to
#' \code{ricker}.
#' @param time_delay An integer vector indicating the number of occasions back
#' on which density dependence operates. Defaults to \code{1}, and may not equal
#' any integer less than 1. If a single number is input, then all noted
#' transitions are assumed to be subject to this time delay.  Defaults to
#' \code{1}.
#' @param alpha A vector indicating the numeric values to use as the
#' alpha term in the two parameter Ricker, Beverton-Holt, or Usher function, or
#' the value of the carrying capacity \emph{K} to use in the logistic equation
#' (see \code{Notes} section for more on this term). If a single number is
#' provided, then all noted transitions are assumed to be subject to this value
#' of alpha. Defaults to \code{1}.
#' @param beta A vector indicating the numeric values to use as the beta term in
#' the two parameter Ricker, Beverton-Holt, or Usher function. Used to indicate
#' whether to use \emph{K} as a hard limit in the logistic equation (see section
#' \code{Notes} below). If a single number is provided, then all noted
#' transitions are assumed to be subject to this value of \code{beta}. Defaults
#' to \code{1}.
#' @param type A vector denoting the kind of transition between occasions
#' \emph{t} and \emph{t}+1 to be replaced. This should be entered as \code{1},
#' \code{S}, or \code{s} for the replacement of a survival transition; or 
#' \code{2}, \code{F}, or \code{f} for the replacement of a fecundity
#' transition. If empty or not provided, then defaults to \code{1} for survival
#' transition.
#' @param type_t12 An optional vector denoting the kind of transition between
#' occasions \emph{t}-1 and \emph{t}. Only necessary if a historical MPM in
#' deVries format is desired. This should be entered as \code{1}, \code{S}, or
#' \code{s} for a survival transition; or \code{2}, \code{F}, or \code{f} for a
#' fecundity transitions. Defaults to \code{1} for survival transition, with
#' impacts only on the construction of deVries-format hMPMs.
#' 
#' @return A data frame of class \code{lefkoDens}. This object can be used as
#' input in function \code{\link{projection3}()}.
#' 
#' Variables in this object include the following:
#' \item{stage3}{Stage at occasion \emph{t}+1 in the transition to be replaced.}
#' \item{stage2}{Stage at occasion \emph{t} in the transition to be replaced.}
#' \item{stage1}{Stage at occasion \emph{t}-1 in the transition to be replaced,
#' if applicable.}
#' \item{age2}{Age at occasion \emph{t} in the transition to be replaced, if
#' applicable.}
#' \item{style}{Style of density dependence, coded as 1, 2, 3, or 4 for the
#' Ricker, Beverton-Holt, Usher, or logistic function, respectively.}
#' \item{time_delay}{The time delay on density dependence, in time steps.}
#' \item{alpha}{The value of alpha in the Ricker, Beverton-Holt, or Usher
#' function, or the value of carrying capacity, \emph{K}, in the logistic
#' function.}
#' \item{beta}{The value of beta in the Ricker, Beverton-Holt, or Usher
#' function.}
#' \item{type}{Designates whether the transition from occasion \emph{t} to
#' occasion \emph{t}+1 is a survival transition probability (1), or a fecundity
#' rate (2).}
#' \item{type_t12}{Designates whether the transition from occasion \emph{t}-1 to
#' occasion \emph{t} is a survival transition probability (1), a fecundity rate
#' (2).}
#' 
#' @section Notes:
#' This function provides inputs when density dependence is operationalized
#' directly on matrix elements. It can be used in both \code{projection3()} and
#' \code{f_projection3()}. Users wishing to modify vital rate functions by
#' density dependence functions for use in function-based projections with
#' function \code{f_projection3()} should use function \code{density_vr()} to
#' provide the correct inputs.
#' 
#' The parameters \code{alpha} and \code{beta} are applied according to the
#' two-parameter Ricker function, the two-parameter Beverton-Holt function, the
#' two-parameter Usher function, or the one-parameter logistic function.
#' Although the default is that a 1 time step delay is assumed, greater time
#' delays can be set through the \code{time_delay} option.
#' 
#' Entries in \code{stage3}, \code{stage2}, and \code{stage1} can include
#' abbreviations for groups of stages. Use \code{rep} if all reproductive stages
#' are to be used, \code{nrep} if all mature but non-reproductive stages are to
#' be used, \code{mat} if all mature stages are to be used, \code{immat} if all
#' immature stages are to be used, \code{prop} if all propagule stages are to be
#' used, \code{npr} if all non-propagule stages are to be used, \code{obs} if
#' all observable stages are to be used, \code{nobs} if all unobservable stages
#' are to be used, and leave empty or use \code{all} if all stages in stageframe
#' are to be used.
#' 
#' When using the logistic function, it is possible that the time delay used in
#' density dependent simulations will cause matrix elements to become negative.
#' To prevent this behavior, set the associated \code{beta} term to \code{1.0}.
#' Doing so will set \code{K} as the hard limit in the logistic equation,
#' essentially setting a minimum limit at \code{0} for all matrix elements
#' modified.
#' 
#' @seealso \code{\link{start_input}()}
#' @seealso \code{\link{projection3}()}
#' 
#' @examples
#' \donttest{
#' data(lathyrus)
#' 
#' sizevector <- c(0, 100, 13, 127, 3730, 3800, 0)
#' stagevector <- c("Sd", "Sdl", "VSm", "Sm", "VLa", "Flo", "Dorm")
#' repvector <- c(0, 0, 0, 0, 0, 1, 0)
#' obsvector <- c(0, 1, 1, 1, 1, 1, 0)
#' matvector <- c(0, 0, 1, 1, 1, 1, 1)
#' immvector <- c(1, 1, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 100, 11, 103, 3500, 3800, 0.5)
#' 
#' lathframe <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector,
#'   immstatus = immvector, indataset = indataset, binhalfwidth = binvec,
#'   propstatus = propvector)
#' 
#' lathvert <- verticalize3(lathyrus, noyears = 4, firstyear = 1988,
#'   patchidcol = "SUBPLOT", individcol = "GENET", blocksize = 9,
#'   juvcol = "Seedling1988", sizeacol = "Volume88", repstracol = "FCODE88",
#'   fecacol = "Intactseed88", deadacol = "Dead1988",
#'   nonobsacol = "Dormant1988", stageassign = lathframe, stagesize = "sizea",
#'   censorcol = "Missing1988", censorkeep = NA, censor = TRUE)
#' 
#' lathsupp3 <- supplemental(stage3 = c("Sd", "Sd", "Sdl", "Sdl", "Sd", "Sdl", "mat"),
#'   stage2 = c("Sd", "Sd", "Sd", "Sd", "rep", "rep", "Sdl"),
#'   stage1 = c("Sd", "rep", "Sd", "rep", "npr", "npr", "Sd"),
#'   eststage3 = c(NA, NA, NA, NA, NA, NA, "mat"),
#'   eststage2 = c(NA, NA, NA, NA, NA, NA, "Sdl"),
#'   eststage1 = c(NA, NA, NA, NA, NA, NA, "NotAlive"),
#'   givenrate = c(0.345, 0.345, 0.054, 0.054, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, 0.345, 0.054, NA),
#'   type = c(1, 1, 1, 1, 3, 3, 1), type_t12 = c(1, 2, 1, 2, 1, 1, 1),
#'   stageframe = lathframe, historical = TRUE)
#' 
#' ehrlen3 <- rlefko3(data = lathvert, stageframe = lathframe, year = "all", 
#'   stages = c("stage3", "stage2", "stage1"), supplement = lathsupp3,
#'   yearcol = "year2", indivcol = "individ")
#' 
#' ehrlen3mean <- lmean(ehrlen3)
#' 
#' e3d <- density_input(ehrlen3mean, stage3 = c("Sd", "Sdl"),
#'   stage2 = c("rep", "rep"), stage1 = c("all", "all"), style = 1,
#'   time_delay = 1, alpha = 1, beta = 0, type = c(2, 2), type_t12 = c(1, 1))
#' 
#' lathproj <- projection3(ehrlen3, nreps = 5, stochastic = TRUE, substoch = 2,
#'   density = e3d)
#' }
#' 
#' @export density_input
density_input <- function(mpm, stage3 = NULL, stage2 = NULL, stage1 = NULL, age2 = NULL, style = NULL, time_delay = NULL, alpha = NULL, beta = NULL, type = NULL, type_t12 = NULL) {
    .Call('_lefko3_density_input', PACKAGE = 'lefko3', mpm, stage3, stage2, stage1, age2, style, time_delay, alpha, beta, type, type_t12)
}

#' Create a Data Frame of Supplemental Data for MPM Development
#' 
#' Function \code{supplemental()} provides all necessary supplemental data for
#' matrix estimation, particularly bringing together data on proxy rates, data
#' to overwrite existing rates, identified reproductive transitions complete,
#' and fecundity multipliers. The function should be used to incorporate data
#' that affects all matrices to be created. To edit MPMs after creation, use
#' \code{\link{edit_lM}()} instead.
#' 
#' @name supplemental
#' 
#' @param historical A logical value indicating whether the MPMs intended will
#' be historical or ahistorical. Defaults to \code{TRUE}.
#' @param stagebased A logical value indicating whether the MPM will be stage-
#' based or age-by-stage. Defaults to \code{TRUE}.
#' @param agebased A logical value indicating whether the MPM will be age-based
#' or age-by-stage. Defaults to \code{FALSE}.
#' @param stageframe The stageframe used to produce the MPM. Required if
#' producing any stage-based or age-by-stage MPM. Must be omitted for purely
#' age-based MPMs.
#' @param stage3 The name of the stage in occasion \emph{t}+1 in the transition
#' to be replaced. Abbreviations for groups of stages are also usable (see
#' \code{Notes}). Required in all stage-based and age-by-stage MPMs.
#' @param stage2 The name of the stage in occasion \emph{t} in the transition
#' to be replaced. Abbreviations for groups of stages are also usable (see
#' \code{Notes}). Required in all stage-based and age-by-stage MPMs.
#' @param stage1 The name of the stage in occasion \emph{t}-1 in the transition
#' to be replaced. Only needed if a historical matrix is to be produced.
#' Abbreviations for groups of stages are also usable (see \code{Notes}).
#' Required for historical stage-based MPMs.
#' @param age2 An integer vector of the ages in occasion \emph{t} to use in
#' transitions to be changed or replaced. Required for all age- and
#' age-by-stage MPMs.
#' @param eststage3 The name of the stage to replace \code{stage3} in a proxy
#' transition. Only needed if a transition will be replaced by another
#' estimated transition, and only in stage-based and age-by-stage MPMs.
#' @param eststage2 The name of the stage to replace \code{stage2} in a proxy
#' transition. Only needed if a transition will be replaced by another
#' estimated transition, and only in stage-based and age-by-stage MPMs.
#' @param eststage1 The name of the stage to replace \code{stage1} in a proxy
#' historical transition. Only needed if a transition will be replaced by
#' another estimated transition, and the matrix to be estimated is historical
#' and stage-based. Stage \code{NotAlive} is also possible for raw hMPMs as a
#' means of handling the prior stage for individuals entering the population in
#' occasion \emph{t}.
#' @param estage2 The age at time \emph{t} to replace \code{age2} in a proxy
#' transition. Only needed if a transition will be replaced by another
#' estimated transition, and only in age-based and age-by-stage MPMs.
#' @param givenrate A fixed rate or probability to replace for the transition
#' described by \code{stage3}, \code{stage2}, and \code{stage1}.
#' @param multiplier A vector of numeric multipliers for fecundity or for proxy
#' transitions. Defaults to \code{1}.
#' @param type A vector denoting the kind of transition between occasions
#' \emph{t} and \emph{t}+1 to be replaced. This should be entered as \code{1},
#' \code{S}, or \code{s} for the replacement of a survival transition;
#' \code{2}, \code{F}, or \code{f} for the replacement of a fecundity
#' transition; or \code{3}, \code{R}, or \code{r} for a fecundity set value /
#' general multiplier. If empty or not provided, then defaults to \code{1} for
#' survival transition.
#' @param type_t12 An optional vector denoting the kind of transition between
#' occasions \emph{t}-1 and \emph{t}. Only necessary if a historical MPM in
#' deVries format is desired. This should be entered as \code{1}, \code{S}, or
#' \code{s} for a survival transition; or \code{2}, \code{F}, or \code{f} for a
#' fecundity transitions. Defaults to \code{1} for survival transition, with
#' impacts only on the construction of deVries-format hMPMs.
#' 
#' @return A data frame of class \code{lefkoSD}. This object can be used as
#' input in \code{\link{flefko3}()}, \code{\link{flefko2}()}, 
#' \code{\link{rlefko3}()}, \code{\link{rlefko2}()}, and 
#' \code{\link{aflefko2}()}.
#' 
#' Variables in this object include the following:
#' \item{stage3}{Stage at occasion \emph{t}+1 in the transition to be
#' replaced.}
#' \item{stage2}{Stage at occasion \emph{t} in the transition to be replaced.}
#' \item{stage1}{Stage at occasion \emph{t}-1 in the transition to be
#' replaced.}
#' \item{age2}{Age at occasion \emph{t} in the transition to be replaced.}
#' \item{eststage3}{Stage at occasion \emph{t}+1 in the transition to replace
#' the transition designated by \code{stage3}, \code{stage2}, and 
#' \code{stage1}.}
#' \item{eststage2}{Stage at occasion \emph{t} in the transition to replace the
#' transition designated by \code{stage3}, \code{stage2}, and \code{stage1}.}
#' \item{eststage1}{Stage at occasion \emph{t}-1 in the transition to replace
#' the transition designated by \code{stage3}, \code{stage2}, and 
#' \code{stage1}.}
#' \item{estage2}{Age at occasion \emph{t} in the transition to replace the
#' transition designated by \code{age2}.}
#' \item{givenrate}{A constant to be used as the value of the transition.}
#' \item{multiplier}{A multiplier for proxy transitions or for fecundity.}
#' \item{convtype}{Designates whether the transition from occasion \emph{t} to
#' occasion \emph{t}+1 is a survival transition probability (1), a fecundity
#' rate (2), or a fecundity multiplier (3).}
#' \item{convtype_t12}{Designates whether the transition from occasion
#' \emph{t}-1 to occasion \emph{t} is a survival transition probability (1), a
#' fecundity rate (2).}
#' 
#' @section Notes:
#' Negative values are not allowed in \code{givenrate} and \code{multiplier}
#' input. Stage entries should not be used for purely age-based MPMs, and age
#' entries should not be used for purely stage-based MPMs.
#' 
#' Fecundity multiplier data supplied via the \code{supplemental()} function
#' acts in the same way as non-zero entries supplied via a reproductive matrix,
#' but gets priority in all matrix creations. Thus, in cases where fecundity
#' multipliers are provided for the same function via the reproductive matrix
#' and function \code{supplemental()}, the latter is used.
#' 
#' Entries in \code{stage3}, \code{stage2}, and \code{stage1} can include
#' abbreviations for groups of stages. Use \code{rep} if all reproductive
#' stages are to be used, \code{nrep} if all mature but non-reproductive stages
#' are to be used, \code{mat} if all mature stages are to be used, \code{immat}
#' if all immature stages are to be used, \code{prop} if all propagule stages
#' are to be used, \code{npr} if all non-propagule stages are to be used,
#' \code{obs} if all observable stages are to be used, \code{nobs} if all
#' unobservable stages are to be used, and leave empty or use \code{all} if all
#' stages in stageframe are to be used. Also use \code{groupX} to denote all
#' stages in group X (e.g. \code{group1} will use all stages in the respective
#' stageframe's group 1).
#' 
#' Type 3 conversions are referred to as fecundity set values, or general
#' fecundity multipliers. These set the transitions to be used as fecundity
#' transitions. Transitions set here will be interpreted as being generally
#' reproductive, meaning that the from and to stages will be used to determine
#' the general fecundity transitions to incorporate into stage-based MPMs,
#' while the age portion of the input will be used to incorporate the actual
#' multiplier(s) specified. If only stage transitions at certain ages are
#' expected to be the sole contributors to fecundity, then type 2 conversions
#' should also be included in the supplement (Type 1 and 2 conversions can be
#' purely age-specific, and do not set reproductive transitions in MPM
#' creation). For example, if all stage 2 to stage 3 transitions above age 2
#' yield fecundity, then stage 2 to stage 3 can be set to
#' \code{multiplier = 1.0} with \code{convtype = 3}, and the same transition
#' for \code{age2 = c(1, 2)} can be set to \code{multiplier = c(0, 0)}.
#' 
#' @seealso \code{\link{edit_lM}()}
#' 
#' @examples
#' # Lathyrus example
#' data(lathyrus)
#' 
#' sizevector <- c(0, 100, 13, 127, 3730, 3800, 0)
#' stagevector <- c("Sd", "Sdl", "VSm", "Sm", "VLa", "Flo", "Dorm")
#' repvector <- c(0, 0, 0, 0, 0, 1, 0)
#' obsvector <- c(0, 1, 1, 1, 1, 1, 0)
#' matvector <- c(0, 0, 1, 1, 1, 1, 1)
#' immvector <- c(1, 1, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 100, 11, 103, 3500, 3800, 0.5)
#' 
#' lathframe <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector,
#'   immstatus = immvector, indataset = indataset, binhalfwidth = binvec,
#'   propstatus = propvector)
#' 
#' lathvert <- verticalize3(lathyrus, noyears = 4, firstyear = 1988,
#'   patchidcol = "SUBPLOT", individcol = "GENET", blocksize = 9,
#'   juvcol = "Seedling1988", sizeacol = "Volume88", repstracol = "FCODE88",
#'   fecacol = "Intactseed88", deadacol = "Dead1988",
#'   nonobsacol = "Dormant1988", stageassign = lathframe, stagesize = "sizea",
#'   censorcol = "Missing1988", censorkeep = NA, censor = TRUE)
#' 
#' lathsupp3 <- supplemental(stage3 = c("Sd", "Sd", "Sdl", "Sdl", "Sd", "Sdl", "mat"),
#'   stage2 = c("Sd", "Sd", "Sd", "Sd", "rep", "rep", "Sdl"),
#'   stage1 = c("Sd", "rep", "Sd", "rep", "npr", "npr", "Sd"),
#'   eststage3 = c(NA, NA, NA, NA, NA, NA, "mat"),
#'   eststage2 = c(NA, NA, NA, NA, NA, NA, "Sdl"),
#'   eststage1 = c(NA, NA, NA, NA, NA, NA, "NotAlive"),
#'   givenrate = c(0.345, 0.345, 0.054, 0.054, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, 0.345, 0.054, NA),
#'   type = c(1, 1, 1, 1, 3, 3, 1), type_t12 = c(1, 2, 1, 2, 1, 1, 1),
#'   stageframe = lathframe, historical = TRUE)
#' 
#' ehrlen3 <- rlefko3(data = lathvert, stageframe = lathframe, year = "all", 
#'   stages = c("stage3", "stage2", "stage1"), supplement = lathsupp3,
#'   yearcol = "year2", indivcol = "individ")
#' 
#' # Cypripedium example
#' data(cypdata)
#' 
#' sizevector <- c(0, 0, 0, 0, 0, 0, 1, 2.5, 4.5, 8, 17.5)
#' stagevector <- c("SD", "P1", "P2", "P3", "SL", "D", "XSm", "Sm", "Md", "Lg",
#'   "XLg")
#' repvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' obsvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' matvector <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' immvector <- c(0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 0, 0, 0, 0, 0.5, 0.5, 1, 1, 2.5, 7)
#' 
#' cypframe_raw <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector,
#'   propstatus = propvector, immstatus = immvector, indataset = indataset,
#'   binhalfwidth = binvec)
#' 
#' cypraw_v1 <- verticalize3(data = cypdata, noyears = 6, firstyear = 2004,
#'   patchidcol = "patch", individcol = "plantid", blocksize = 4,
#'   sizeacol = "Inf2.04", sizebcol = "Inf.04", sizeccol = "Veg.04",
#'   repstracol = "Inf.04", repstrbcol = "Inf2.04", fecacol = "Pod.04",
#'   stageassign = cypframe_raw, stagesize = "sizeadded", NAas0 = TRUE,
#'   NRasRep = TRUE)
#' 
#' cypsupp2r <- supplemental(stage3 = c("SD", "P1", "P2", "P3", "SL", "D", 
#'     "XSm", "Sm", "SD", "P1"),
#'   stage2 = c("SD", "SD", "P1", "P2", "P3", "SL", "SL", "SL", "rep",
#'     "rep"),
#'   eststage3 = c(NA, NA, NA, NA, NA, "D", "XSm", "Sm", NA, NA),
#'   eststage2 = c(NA, NA, NA, NA, NA, "XSm", "XSm", "XSm", NA, NA),
#'   givenrate = c(0.10, 0.20, 0.20, 0.20, 0.25, NA, NA, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, NA, NA, NA, NA, 0.5, 0.5),
#'   type =c(1, 1, 1, 1, 1, 1, 1, 1, 3, 3),
#'   stageframe = cypframe_raw, historical = FALSE)
#' 
#' cypmatrix2r <- rlefko2(data = cypraw_v1, stageframe = cypframe_raw, 
#'   year = "all", patch = "all", stages = c("stage3", "stage2", "stage1"),
#'   size = c("size3added", "size2added"), supplement = cypsupp2r,
#'   yearcol = "year2", patchcol = "patchid", indivcol = "individ")
#' 
#' @export supplemental
supplemental <- function(historical = TRUE, stagebased = TRUE, agebased = FALSE, stageframe = NULL, stage3 = NULL, stage2 = NULL, stage1 = NULL, age2 = NULL, eststage3 = NULL, eststage2 = NULL, eststage1 = NULL, estage2 = NULL, givenrate = NULL, multiplier = NULL, type = NULL, type_t12 = NULL) {
    .Call('_lefko3_supplemental', PACKAGE = 'lefko3', historical, stagebased, agebased, stageframe, stage3, stage2, stage1, age2, eststage3, eststage2, eststage1, estage2, givenrate, multiplier, type, type_t12)
}

#' Edit an MPM based on Supplemental Data
#' 
#' Function \code{edit_lM()} edits existing \code{lefkoMat} objects with
#' external data supplied by the user. The effects are similar to function
#' \code{\link{supplemental}()}, though function \code{edit_lM()} allows
#' individuals matrices within \code{lefkoMat} objects to be edited after
#' creation, while \code{\link{supplemental}()} provides external data that
#' modifies all matrices within a \code{lefkoMat} object.
#' 
#' @name edit_lM
#' 
#' @param mpm The \code{lefkoMat} object to be edited.
#' @param pop A string vector denoting the populations to be edited. Defaults
#' to \code{NULL}, in which case all populations are edited.
#' @param patch A string vector denoting the patches to be edited. Defaults
#' to \code{NULL}, in which case all patches are edited.
#' @param year2 A string vector denoting the years to be edited. Defaults
#' to \code{NULL}, in which case all years are edited.
#' @param stage3 The name of the stage in occasion \emph{t}+1 in the transition
#' to be replaced. Abbreviations for groups of stages are also usable (see
#' \code{Notes}). Required in all stage-based and age-by-stage MPMs.
#' @param stage2 The name of the stage in occasion \emph{t} in the transition
#' to be replaced. Abbreviations for groups of stages are also usable (see
#' \code{Notes}). Required in all stage-based and age-by-stage MPMs.
#' @param stage1 The name of the stage in occasion \emph{t}-1 in the transition
#' to be replaced. Only needed if a historical matrix is to be produced.
#' Abbreviations for groups of stages are also usable (see \code{Notes}).
#' Required for historical stage-based MPMs.
#' @param age2 An integer vector of the ages in occasion \emph{t} to use in
#' transitions to be changed or replaced. Required for all age- and
#' age-by-stage MPMs.
#' @param eststage3 The name of the stage to replace \code{stage3} in a proxy
#' transition. Only needed if a transition will be replaced by another
#' estimated transition, and only in stage-based and age-by-stage MPMs.
#' @param eststage2 The name of the stage to replace \code{stage2} in a proxy
#' transition. Only needed if a transition will be replaced by another
#' estimated transition, and only in stage-based and age-by-stage MPMs.
#' @param eststage1 The name of the stage to replace \code{stage1} in a proxy
#' historical transition. Only needed if a transition will be replaced by
#' another estimated transition, and the matrix to be estimated is historical
#' and stage-based. Stage \code{NotAlive} is also possible for raw hMPMs as a
#' means of handling the prior stage for individuals entering the population in
#' occasion \emph{t}.
#' @param estage2 The age at time \emph{t} to replace \code{age2} in a proxy
#' transition. Only needed if a transition will be replaced by another
#' estimated transition, and only in age-based and age-by-stage MPMs.
#' @param givenrate A fixed rate or probability to replace for the transition
#' described by \code{stage3}, \code{stage2}, and \code{stage1}.
#' @param multiplier A vector of numeric multipliers for fecundity or for proxy
#' transitions. Defaults to \code{1}.
#' @param type A vector denoting the kind of transition between occasions
#' \emph{t} and \emph{t}+1 to be replaced. This should be entered as \code{1},
#' \code{S}, or \code{s} for the replacement of a survival transition;
#' \code{2}, \code{F}, or \code{f} for the replacement of a fecundity
#' transition; or \code{3}, \code{R}, or \code{r} for a fecundity multiplier.
#' If empty or not provided, then defaults to \code{1} for survival transition.
#' @param type_t12 An optional vector denoting the kind of transition between
#' occasions \emph{t}-1 and \emph{t}. Only necessary if a historical MPM in
#' deVries format is desired. This should be entered as \code{1}, \code{S}, or
#' \code{s} for a survival transition; or \code{2}, \code{F}, or \code{f} for a
#' fecundity transitions. Defaults to \code{1} for survival transition, with
#' impacts only on the construction of deVries-format hMPMs.
#' 
#' @return An edited copy of the original MPM is returned, also as a
#' \code{lefkoMat} object.
#' 
#' @section Notes:
#' Entries in \code{stage3}, \code{stage2}, and \code{stage1} can include
#' abbreviations for groups of stages. Use \code{rep} if all reproductive
#' stages are to be used, \code{nrep} if all mature but non-reproductive stages
#' are to be used, \code{mat} if all mature stages are to be used, \code{immat}
#' if all immature stages are to be used, \code{prop} if all propagule stages
#' are to be used, \code{npr} if all non-propagule stages are to be used,
#' \code{obs} if all observable stages are to be used, \code{nobs} if all
#' unobservable stages are to be used, and leave empty or use \code{all} if all
#' stages in stageframe are to be used. Also use \code{groupX} to denote all
#' stages in group X (e.g. \code{group1} will use all stages in the respective
#' stageframe's group 1).
#' 
#' @seealso \code{\link{supplemental}()}
#' 
#' @examples
#' data(cypdata)
#' 
#' cypraw_v1 <- verticalize3(data = cypdata, noyears = 6, firstyear = 2004,
#'   patchidcol = "patch", individcol = "plantid", blocksize = 4,
#'   sizeacol = "Inf2.04", sizebcol = "Inf.04", sizeccol = "Veg.04",
#'   repstracol = "Inf.04", repstrbcol = "Inf2.04", fecacol = "Pod.04",
#'   age_offset = 3, NAas0 = TRUE, NRasRep = TRUE)
#' 
#' cyp_rl <- rleslie(data = cypraw_v1, start_age = 0, last_age = 6, continue = TRUE,
#'   fecage_min = 3, year = "all", pop = NA, patch = "all", yearcol = "year2",
#'   patchcol = "patchid", indivcol = "individ")
#' 
#' ddd1 <- edit_lM(cyp_rl, age2 = c(0, 1, 2, 3, 4, 5, 6),
#'   givenrate = c(0.25, 0.25, 0.4, 0.4, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, 2000, 2000, 2000),
#'   type = c(1, 1, 1, 1, 3, 3, 3))
#'   
#' ddd1 <- edit_lM(ddd1, age2 = 6, multiplier = 1.5, type = 3, patch = "B",
#'   year2 = "2005")
#' 
#' @export edit_lM
edit_lM <- function(mpm, pop = NULL, patch = NULL, year2 = NULL, stage3 = NULL, stage2 = NULL, stage1 = NULL, age2 = NULL, eststage3 = NULL, eststage2 = NULL, eststage1 = NULL, estage2 = NULL, givenrate = NULL, multiplier = NULL, type = NULL, type_t12 = NULL) {
    .Call('_lefko3_edit_lM', PACKAGE = 'lefko3', mpm, pop, patch, year2, stage3, stage2, stage1, age2, eststage3, eststage2, eststage1, estage2, givenrate, multiplier, type, type_t12)
}

#' Creates Size Index for Elasticity Summaries of hMPMs
#' 
#' Function \code{bambi3()} creates an index of estimable elements in
#' historical matrices, and details the kind of transition that it is.
#' 
#' @name .bambi3
#' 
#' @param stages This is the core stageframe held by \code{mats}, equivalent to
#' \code{ahstages}.
#' @param hstages This is the \code{hstages} object held by \code{mats}.
#' 
#' @return A data frame with the following elements:
#' \item{index}{Vector index of matrix element in C++ terms.}
#' \item{transition}{Category of transition.}
#' \item{size3}{Size in occasion \emph{t}+1.}
#' \item{repstatus3}{Reproductive status in occasion \emph{t}+1.}
#' \item{entrystatus3}{Entry status in occasion \emph{t}+1.}
#' \item{size2}{Size in occasion \emph{t}.}
#' \item{repstatus2}{Reproductive status in occasion \emph{t}.}
#' \item{entrystatus2}{Entry status in occasion \emph{t}.}
#' \item{size1}{Size in occasion \emph{t}-1.}
#' \item{repstatus1}{Reproductive status in occasion \emph{t}-1.}
#' \item{entrystatus1}{Entry status in occasion \emph{t}-1.}
#'
#' The kind of transitions conforms to the following code: \code{10}: full
#' stasis, \code{11}: stasis to growth, \code{12}: full growth, \code{13}:
#' growth to stasis, \code{14}: stasis to shrinkage, \code{15}: full shrinkage,
#' \code{16}: shrinkage to stasis, \code{17}: growth to shrinkage, \code{18}:
#' shrinkage to growth, \code{20}: stasis to fecundity, \code{21}: growth to
#' fecundity, \code{22}: shrinkage to fecundity, \code{23}: fecundity to
#' stasis, \code{24}: fecundity to growth, \code{25}: fecundity to shrinkage,
#' \code{26}: fecundity to fecundity.
#' 
#' @keywords internal
#' @noRd
.bambi3 <- function(stages, hstages) {
    .Call('_lefko3_bambi3', PACKAGE = 'lefko3', stages, hstages)
}

#' Creates Size Index for Elasticity Summaries of ahMPMs
#' 
#' Function \code{bambi2()} creates an index of estimable elements in
#' ahistorical matrices, and details the kind of transition that it is.
#' 
#' @name .bambi2
#' 
#' @param stages This is the core stageframe held by \code{mats}, equivalent to
#' \code{ahstages}.
#' 
#' @return A data frame with the following elements:
#' \item{index}{Vector index of matrix element in C++ terms.}
#' \item{transition}{Category of transition.}
#' \item{stage3}{Stage in occasion \emph{t}+1.}
#' \item{size3}{Size in occasion \emph{t}+1.}
#' \item{repstatus3}{Reproductive status in occasion \emph{t}+1.}
#' \item{entrystatus3}{Entry status in occasion \emph{t}+1.}
#' \item{stage2}{Stage in occasion \emph{t}.}
#' \item{size2}{Size in occasion \emph{t}.}
#' \item{repstatus2}{Reproductive status in occasion \emph{t}.}
#' \item{entrystatus2}{Entry status in occasion \emph{t}.}
#'
#' The kind of transitions conforms to the following code: \code{1}: stasis, 
#' \code{2}: growth, \code{3}: shrinkage, \code{4}: fecundity.
#' 
#' @keywords internal
#' @noRd
.bambi2 <- function(stages) {
    .Call('_lefko3_bambi2', PACKAGE = 'lefko3', stages)
}

#' Sum Positive and Negative LTRE or Elasticity Contributions
#' 
#' @name .demolition4
#' 
#' Function \code{demolition4()} takes \code{lefkoElas} and \code{lefkoLTRE}
#' inputs and returns a data frame summarizing their positive and negative
#' contributions.
#' 
#' @param cmats Any \code{lefkoElas} or \code{lefkoLTRE} object.
#' 
#' @return A data frame with three columns per contribution type, corresponding
#' to summed positive, negative, and total contributions, and rows
#' corresponding to each input matrix.
#' 
#' @keywords internal
#' @noRd
.demolition4 <- function(cmats) {
    .Call('_lefko3_demolition4', PACKAGE = 'lefko3', cmats)
}

#' Creates Summary Data for Elasticity Matrix Inputs
#' 
#' Function \code{demolition3()} sums elasticity values from elasticity
#' matrices, and LTRE contributions from LTRE and sLTRE matrices, according to
#' the categories developed by functions \code{bambi2()} and \code{bambi3()}.
#' It requires \code{matrix} class inputs.
#' 
#' @name .demolition3
#' 
#' @param e_amat A single elasticity, LTRE, or sLTRE matrix of class
#' \code{matrix}.
#' @param bambesque This is the output from \code{bambi2()} or \code{bambi3()}
#' corresponding to the current lefkoMat object. The format is a data frame
#' giving the indices and characteristics of all predicted potential non-zero
#' elements in the supplied matrix.
#' @param amat_ The A matrix corresponding to \code{e_amat}. If not supplied,
#' then only \code{bambesque} is used to determine transition categories. If
#' provided, then fecundity transitions may be split between fecundity and
#' survival portions.
#' @param fmat_ The F matrix corresponding to \code{e_amat}. If not supplied,
#' then only \code{bambesque} is used to determine transition categories. If
#' provided, then fecundity transitions may be split between fecundity and
#' survival portions.
#' 
#' @return A list with two data frames, one showing the summed elasticities for
#' the historical matrix supplied (if supplied), and the other showing the
#' ahistorical summary of the historical matrix or the summed elasticities of
#' a supplied ahistorical elasticity matrix. Also includes sums of only the
#' positive elements and only the negative elements, in all cases.
#' 
#' @keywords internal
#' @noRd
.demolition3 <- function(e_amat, bambesque, amat_ = NULL, fmat_ = NULL) {
    .Call('_lefko3_demolition3', PACKAGE = 'lefko3', e_amat, bambesque, amat_, fmat_)
}

#' Creates Summary Data for Elasticity Matrix Inputs
#' 
#' Function \code{demolition3sp()} sums elasticity values from elasticity
#' matrices, and LTRE contributions from LTRE and sLTRE matrices, according to
#' the categories developed by functions \code{bambi2()} and \code{bambi3()}.
#' It requires \code{dgCMatrix} class inputs.
#' 
#' @name .demolition3sp
#' 
#' @param e_amat A single elasticity, LTRE, or sLTRE matrix of class
#' \code{dgCMatrix}.
#' @param bambesque This is the output from \code{bambi2()} or \code{bambi3()}
#' corresponding to the current lefkoMat object. The format is a data frame
#' giving the indices and characteristics of all predicted potential non-zero
#' elements in the supplied matrix.
#' @param amat_ The A matrix corresponding to \code{e_amat}. If not supplied,
#' then only \code{bambesque} is used to determine transition categories. If
#' provided, then fecundity transitions may be split between fecundity and
#' survival portions. Must also be of class \code{dgCMatrix}.
#' @param fmat_ The F matrix corresponding to \code{e_amat}. If not supplied,
#' then only \code{bambesque} is used to determine transition categories. If
#' provided, then fecundity transitions may be split between fecundity and
#' survival portions. Must also be of class \code{dgCMatrix}.
#' 
#' @return A list with two data frames, one showing the summed elasticities for
#' the historical matrix supplied (if supplied), and the other showing the
#' ahistorical summary of the historical matrix or the summed elasticities of
#' a supplied ahistorical elasticity matrix. Also includes sums of only the
#' positive elements and only the negative elements, in all cases.
#' 
#' @keywords internal
#' @noRd
.demolition3sp <- function(e_amat, bambesque, amat_ = NULL, fmat_ = NULL) {
    .Call('_lefko3_demolition3sp', PACKAGE = 'lefko3', e_amat, bambesque, amat_, fmat_)
}

#' Estimate Deterministic Population Growth Rate As Dominant Eigenvalue
#' 
#' Function \code{lambda3()} is a generic function that returns the dominant
#' eigenvalue of a matrix, set of dominant eigenvalues of a set of matrices,
#' or set of dominant eigenvalues for a \code{lefkoMat} object. It can handle
#' large and sparse matrices supplied as \code{lefkoMat} objects or as
#' individual matrices, and can be used with large historical matrices, IPMs, 
#' age x stage matrices, as well as smaller ahistorical matrices.
#' 
#' @param mpm A lefkoMat object, a list of projection matrices, or a single
#' projection matrix.
#' @param force_sparse A logical value or string detailing whether to force
#' sparse matrix encoding for simple matrix input. Defaults to \code{"auto"},
#' which only forces sparse matrix coding if simple matrices are input that are
#' both sparse (i.e, percentage of matrix elements that are non-zero <= 50%)
#' and have more than 20 rows. Can also be set to \code{"yes"}, \code{"no"},
#' \code{TRUE}, or \code{FALSE}. Note that sparse matrix coding is always used
#' for \code{lefkoMat} objects with matrices in sparse format (class
#' \code{dgCMatrix}).
#' 
#' @return The value returned depends on the class of the \code{mats} argument.
#' If a \code{lefkoMat} object is provided, then this function will return the
#' \code{labels} data frame with a new column named \code{lambda} showing the
#' dominant eigenvalues for each matrix. If a list of matrices is provided,
#' then this function will produce a numeric vector with the dominant
#' eigenvalues provided in order of matrix. If a single matrix is provided,
#' then this function will return the dominant eigenvalue of that matrix. Only
#' the largest real parts of the eigenvalues are returned.
#' 
#' @seealso \code{\link{slambda3}()}
#' 
#' @examples
#' # Lathyrus example
#' data(lathyrus)
#' 
#' sizevector <- c(0, 100, 13, 127, 3730, 3800, 0)
#' stagevector <- c("Sd", "Sdl", "VSm", "Sm", "VLa", "Flo", "Dorm")
#' repvector <- c(0, 0, 0, 0, 0, 1, 0)
#' obsvector <- c(0, 1, 1, 1, 1, 1, 0)
#' matvector <- c(0, 0, 1, 1, 1, 1, 1)
#' immvector <- c(1, 1, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 100, 11, 103, 3500, 3800, 0.5)
#' 
#' lathframe <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector,
#'   immstatus = immvector, indataset = indataset, binhalfwidth = binvec,
#'   propstatus = propvector)
#' 
#' lathvert <- verticalize3(lathyrus, noyears = 4, firstyear = 1988,
#'   patchidcol = "SUBPLOT", individcol = "GENET", blocksize = 9,
#'   juvcol = "Seedling1988", sizeacol = "Volume88", repstracol = "FCODE88",
#'   fecacol = "Intactseed88", deadacol = "Dead1988",
#'   nonobsacol = "Dormant1988", stageassign = lathframe, stagesize = "sizea",
#'   censorcol = "Missing1988", censorkeep = NA, censor = TRUE)
#' 
#' lathsupp3 <- supplemental(stage3 = c("Sd", "Sd", "Sdl", "Sdl", "Sd", "Sdl", "mat"),
#'   stage2 = c("Sd", "Sd", "Sd", "Sd", "rep", "rep", "Sdl"),
#'   stage1 = c("Sd", "rep", "Sd", "rep", "npr", "npr", "Sd"),
#'   eststage3 = c(NA, NA, NA, NA, NA, NA, "mat"),
#'   eststage2 = c(NA, NA, NA, NA, NA, NA, "Sdl"),
#'   eststage1 = c(NA, NA, NA, NA, NA, NA, "NotAlive"),
#'   givenrate = c(0.345, 0.345, 0.054, 0.054, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, 0.345, 0.054, NA),
#'   type = c(1, 1, 1, 1, 3, 3, 1), type_t12 = c(1, 2, 1, 2, 1, 1, 1),
#'   stageframe = lathframe, historical = TRUE)
#' 
#' ehrlen3 <- rlefko3(data = lathvert, stageframe = lathframe, year = "all", 
#'   stages = c("stage3", "stage2", "stage1"), supplement = lathsupp3,
#'   yearcol = "year2", indivcol = "individ")
#' 
#' ehrlen3mean <- lmean(ehrlen3)
#' lambda3(ehrlen3mean)
#' 
#' # Cypripedium example
#' data(cypdata)
#' 
#' sizevector <- c(0, 0, 0, 0, 0, 0, 1, 2.5, 4.5, 8, 17.5)
#' stagevector <- c("SD", "P1", "P2", "P3", "SL", "D", "XSm", "Sm", "Md", "Lg",
#'   "XLg")
#' repvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' obsvector <- c(0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1)
#' matvector <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' immvector <- c(0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(0, 0, 0, 0, 0, 0.5, 0.5, 1, 1, 2.5, 7)
#' 
#' cypframe_raw <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector,
#'   propstatus = propvector, immstatus = immvector, indataset = indataset,
#'   binhalfwidth = binvec)
#' 
#' cypraw_v1 <- verticalize3(data = cypdata, noyears = 6, firstyear = 2004,
#'   patchidcol = "patch", individcol = "plantid", blocksize = 4,
#'   sizeacol = "Inf2.04", sizebcol = "Inf.04", sizeccol = "Veg.04",
#'   repstracol = "Inf.04", repstrbcol = "Inf2.04", fecacol = "Pod.04",
#'   stageassign = cypframe_raw, stagesize = "sizeadded", NAas0 = TRUE,
#'   NRasRep = TRUE)
#' 
#' # Here we use supplemental() to provide overwrite and reproductive info
#' cypsupp2r <- supplemental(stage3 = c("SD", "P1", "P2", "P3", "SL", "D", 
#'     "XSm", "Sm", "SD", "P1"),
#'   stage2 = c("SD", "SD", "P1", "P2", "P3", "SL", "SL", "SL", "rep",
#'     "rep"),
#'   eststage3 = c(NA, NA, NA, NA, NA, "D", "XSm", "Sm", NA, NA),
#'   eststage2 = c(NA, NA, NA, NA, NA, "XSm", "XSm", "XSm", NA, NA),
#'   givenrate = c(0.10, 0.20, 0.20, 0.20, 0.25, NA, NA, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, NA, NA, NA, NA, 0.5, 0.5),
#'   type =c(1, 1, 1, 1, 1, 1, 1, 1, 3, 3),
#'   stageframe = cypframe_raw, historical = FALSE)
#' 
#' cypmatrix2r <- rlefko2(data = cypraw_v1, stageframe = cypframe_raw, 
#'   year = "all", patch = "all", stages = c("stage3", "stage2", "stage1"),
#'   size = c("size3added", "size2added"), supplement = cypsupp2r,
#'   yearcol = "year2", patchcol = "patchid", indivcol = "individ")
#' 
#' lambda3(cypmatrix2r)
#' 
#' @export lambda3
lambda3 <- function(mpm, force_sparse = NULL) {
    .Call('_lefko3_lambda3', PACKAGE = 'lefko3', mpm, force_sparse)
}

Try the lefko3 package in your browser

Any scripts or data that you put into this service are public.

lefko3 documentation built on Oct. 14, 2023, 1:07 a.m.