R/RcppExports.R

Defines functions sltre3matrix ltre3matrix demolition3 bambi2 bambi3 stoch_senselas slambda3 projection3 proj3sp proj3 elas3hlefko elas3matrix sens3hlefko sens3sp_matrix sens3matrix rv3matrix ss3matrix lambda3matrix decomp3sp_inp decomp3sp decomp3 geodiesel turbogeodiesel spmat_log moreflagrantcrap flagrantcrap stovokor jerzeibalowski normalpatrolgroup specialpatrolgroup cond_hmpm hoffmannofstuttgart density3 theoldpizzle jpf pfj ovreplace

Documented in cond_hmpm projection3 slambda3

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

#' Re-index Projection Matrix On Basis of Overwrite Table
#' 
#' This function takes matrix indices provided by functions
#' \code{\link{rlefko3}()}, \code{\link{rlefko2}()}, \code{\link{flefko3}()},
#' \code{\link{flefko2}()}, and \code{\link{aflefko2}()} and updates them with
#' information provided in the overwrite table used as input in that function.
#' 
#' @param allst321 Vector containing the original element-by-element matrix
#' index.
#' @param idx321old Vector containing the indices of matrix elements to be
#' updated.
#' @param idx321new Vector containing the replacement matrix element indices.
#' @param convtype Vector denoting survival transition (1), fecundity (2), or
#' fecundity multiplier (3).
#' @param eststag3 Vector of new stages in time \emph{t}+1.
#' @param gvnrate Vector of replacement transition values.
#' @param multipl Vector of fecundity multipliers.
#' 
#' @return Vector of updated matrix indices and, where appropriate, replacement
#' matrix element values.
#' 
#' @keywords internal
#' @noRd
ovreplace <- function(allst321, idx321old, idx321new, convtype, eststag3, gvnrate, multipl) {
    .Call('_lefko3_ovreplace', PACKAGE = 'lefko3', allst321, idx321old, idx321new, convtype, eststag3, gvnrate, multipl)
}

#' 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.
#' 
#' @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 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 stassign A logical value indicating whether to assign stages.
#' @param stszcol Column number describing which size variable 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.
#' 
#' @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, stassign, stszcol, censorkeep, censbool, censrepeat, coordsrepeat) {
    .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, stassign, stszcol, censorkeep, censbool, censrepeat, coordsrepeat)
}

#' Create Historical Vertical Structure for Ahistorical Vertical Data Frame
#' 
#' Function \code{jpf()} powers the R function \code{\link{historicalize3}()},
#' creating the historical, vertical structure and rearranging the data in that
#' shape.
#'
#' @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 time step in time \emph{t}.
#' @param year3col Column number of year or time step 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
#' the production of reproductive structures, such as flowers, in time \emph{t}.
#' @param repstra3col Column number corresponding to the main variable coding
#' the production of reproductive structures, such as flowers, in time
#' \emph{t}+1.
#' @param repstrb2col Column number corresponding to a second variable coding
#' the production of reproductive structures, such as flowers, in time \emph{t}.
#' @param repstrb3col Column number corresponding to a second variable coding
#' 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
#' unobservable stage in time \emph{t}.
#' @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 modifier for that makes the variable in
#' \code{repstrb2col} equivalent to \code{repstra2col}.
#' @param fecrel This is a scalar modifier 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 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 stassign A logical value indicating whether to assign stages.
#' @param stszcol Column number describing which size variable to use in stage 
#' estimation.
#' @param censorkeep Numeric value of censor variable, denoting elements to
#' keep. If NA is to be used, then set this variable to 0 and set
#' \code{censbool = TRUE}.
#' @param censbool A logical variable determining whether NA denotes the value
#' of the censoring variable identifying data to keep.
#' 
#' @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
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, stassign, stszcol, censorkeep, censbool) {
    .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, stassign, stszcol, censorkeep, censbool)
}

#' Create Element Index for Matrix Estimation
#' 
#' Function \code{theoldpizzle()} create a data frame object spread across
#' three 20-element long list objects that is used by \code{jerzeibalowski()}
#' to estimate function-derived matrices, and also provides the element map for
#' raw matrices.
#'
#' @param StageFrame The stageframe object identifying the life history model
#' being operationalized.
#' @param OverWrite The overwrite table used in analysis, as modified by 
#' \code{.overwrite_reassess}. Must be processed via \code{.overwrite_reassess}
#' rather than being a raw overwrite or supplement table.
#' @param repmatrix The reproductive matrix used in analysis.
#' @param finalage The final age to be used in analysis.
#' @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.
#' 
#' @return The output is currently a three element list, where each element is
#' a data frame with the same number of rows. These are combined into one data
#' frame by \code{\link{flefko3}()}, \code{\link{flefko2}()}, and
#' \code{\link{aflefko2}()}.
#' 
#' @keywords internal
#' @noRd
theoldpizzle <- function(StageFrame, OverWrite, repmatrix, finalage, format, style, cont) {
    .Call('_lefko3_theoldpizzle', PACKAGE = 'lefko3', StageFrame, OverWrite, repmatrix, finalage, format, style, cont)
}

#' Estimate Radial Density in Cartesian Space
#' 
#' \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}()}.
#' 
#' @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).
#'
#' @param mainmat Historical matrix.
#' @param indices Data frame including the stages at times t-1, t, and t+1, as
#' well as indices corresponding to elements in the main historical matrix and
#' the 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)
}

#' 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.
#' 
#' @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 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 FALSE.
#' 
#' @return A \code{lefkoCondMat} object, with the following elements:
#' 
#' \item{Acond}{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.}
#' 
#' @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", "SL", "SL", "D", "XSm", "Sm", "D", "XSm", "Sm", "SD", "P1"),
#'   stage2 = c("SD", "SD", "SD", "SD", "P1", "P2", "P3", "SL", "SL", "SL",
#'     "SL", "SL", "SL", "SL", "SL", "rep", "rep"),
#'   stage1 = c("SD", "rep", "SD", "rep", "SD", "P1", "P2", "P3", "SL", "P3",
#'     "P3", "P3", "SL", "SL", "SL", "all", "all"),
#'   eststage3 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, "D", "XSm", "Sm", "D",
#'     "XSm", "Sm", NA, NA),
#'   eststage2 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, "XSm", "XSm", "XSm",
#'     "XSm", "XSm", "XSm", NA, NA),
#'   eststage1 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, "XSm", "XSm", "XSm",
#'     "XSm", "XSm", "XSm", NA, NA),
#'   givenrate = c(0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.25, 0.4, 0.4, 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,
#'     0.5, 0.5),
#'   type = c(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),
#'   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)
}

#' Estimate All Elements of Function-based Population Projection Matrix
#' 
#' Function \code{jerzeibalowski} swiftly calculates matrix elements in
#' function-based population projection matrices. Used in
#' \code{\link{flefko3}()}, \code{\link{flefko2}()}, and
#' \code{\link{aflefko2}()}.
#' 
#' @param ppy A data frame with one row, showing the population, patch, and
#' year.
#' @param AllStages A large data frame giving all required inputs for vital
#' rate estimation other than the vital rate model coefficients themselves.
#' Contains a row for each ultimate matrix element.
#' @param stageframe The modified stageframe used in matrix calculations.
#' @param matrixformat An integer representing the style of matrix to develop.
#' Options include Ehrlen-format hMPM (1), deVries-format hMPM (2), ahMPM (3),
#' and age-by-stage MPM (4).
#' @param survproxy List of coefficients estimated in model of survival.
#' @param obsproxy List of coefficients estimated in model of observation.
#' @param sizeproxy List of coefficients estimated in model of size.
#' @param repstproxy List of coefficients estimated in model of reproductive 
#' status.
#' @param fecproxy List of coefficients estimated in model of fecundity.
#' @param jsurvproxy List of coefficients estimated in model of juvenile
#' survival.
#' @param jobsproxy List of coefficients estimated in model of juvenile
#' observation.
#' @param jsizeproxy List of coefficients estimated in model of juvenile size.
#' @param jrepstproxy List of coefficients estimated in model of juvenile
#' reproductive status.
#' @param inda A numeric value equal to the value of individual covariate a to
#' be used in analysis.
#' @param indb A numeric value equal to the value of individual covariate b to
#' be used in analysis.
#' @param indc A numeric value equal to the value of individual covariate c to
#' be used in analysis.
#' @param survdev Scalar value to be added to the y-intercept of the linear
#' model of survival probability.
#' @param obsdev Scalar value to be added to the y-intercept of the linear
#' model of observation probability.
#' @param sizedev Scalar value to be added to the y-intercept of the linear
#' model of size transition.
#' @param repstdev Scalar value to be added to the y-intercept of the linear
#' model of reproduction probability.
#' @param fecdev Scalar value to be added to the y-intercept of the linear
#' model of fecundity.
#' @param jsurvdev Scalar value to be added to the y-intercept of the linear
#' model of juvenile survival probability.
#' @param jobsdev Scalar value to be added to the y-intercept of the linear
#' model of juvenile observation probability.
#' @param jsizedev Scalar value to be added to the y-intercept of the linear
#' model of juvenile size transition.
#' @param jrepstdev Scalar value to be added to the y-intercept of the linear
#' model of juvenile reproduction probability.
#' @param fecmod A scalar multiplier for fecundity.
#' @param summedvars Summed variance-covariance terms in Poisson size
#' distribution.
#' @param sigma Standard deviation of Gaussian size distribution.
#' @param jsummedvars Summed variance-covariance terms in Poisson juvenile size
#' distribution.
#' @param jsigma Standard deviation of Gaussian juvenile size distribution.
#' @param maxsize The maximum size to be used in element estimation.
#' @param finalage The final age to be included in age-by-stage MPM estimation.
#' @param sizedist Designates whether size is Gaussian (2), Poisson (0), or
#' negative binomial (1) distributed.
#' @param fecdist Designates whether fecundity is Gaussian (2), Poisson (0), or
#' negative binomial (1) distributed.
#' @param negfec Logical value denoting whether to change negative estimated
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{\link{rlefko3}()}.
#' 
#' @param sge9l The Allstages data frame developed for rlefko3() covering stage
#' pairs across times \emph{t}+1, \emph{t} and \emph{t}-1. Generally termed
#' \code{stageexpansion9}.
#' @param sge3 The data frame covering all stages in times \emph{t} and
#' \emph{t}-1. Generally termed \code{stageexpansion3}.
#' @param MainData The demographic dataset modified to hold \code{usedfec}
#' columns.
#' @param StageFrame The full stageframe for the analysis.
#' @param repmatrix The modified repmatrix used in the course of computation.
#' This is used particularly when deVries-format hMPMs are desired.
#' @param format Indicates whether to output Ehrlen-format hMPMs (1) or
#' deVries-format hMPMs (2).
#' @param err_switch If set to 1, then will also output probsrates and
#' stage2fec.
#' 
#' @return List of three matrices, including the survival-transition (U)
#' matrix, the fecundity matrix (F), and the sum (A) matrix, with A first.
#' 
#' @keywords internal
#' @noRd
specialpatrolgroup <- function(sge9l, sge3, MainData, StageFrame, format, err_switch) {
    .Call('_lefko3_specialpatrolgroup', PACKAGE = 'lefko3', sge9l, sge3, MainData, StageFrame, format, err_switch)
}

#' 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{\link{rlefko2}()}.
#' 
#' @param sge3 The Allstages data frame developed for rlefko2() covering stage
#' pairs across times \emph{t}+1 and \emph{t}. Generally termed
#' \code{stageexpansion3}.
#' @param sge2 The data frame covering all stages in time \emph{t}. Generally
#' termed \code{stageexpansion2}.
#' @param MainData The demographic dataset modified to hold \code{usedfec}
#' columns.
#' @param StageFrame The full stageframe for the analysis.
#' 
#' @return List of three matrices, including the survival-transition (U)
#' matrix, the fecundity matrix (F), and the sum (A) matrix, with A first.
#' 
#' @keywords internal
#' @noRd
normalpatrolgroup <- function(sge3, sge2, MainData, StageFrame) {
    .Call('_lefko3_normalpatrolgroup', PACKAGE = 'lefko3', sge3, sge2, MainData, StageFrame)
}

#' 
#' @return A list of 3 matrices, including the main MPM (A), the survival-
#' transition matrix (U), anf a fecundity matrix (F). With tweaking, can also
#' produce a 4 column matrix showing survival probability, observation
#' probability, reproduction probability, and size transition probability, for
#' each element of the final MPM.
#' 
#' @keywords internal
#' @noRd
jerzeibalowski <- function(ppy, AllStages, stageframe, matrixformat, survproxy, obsproxy, sizeproxy, repstproxy, fecproxy, jsurvproxy, jobsproxy, jsizeproxy, jrepstproxy, inda, indb, indc, survdev, obsdev, sizedev, repstdev, fecdev, jsurvdev, jobsdev, jsizedev, jrepstdev, fecmod, summedvars, sigma, jsummedvars, jsigma, maxsize, finalage, sizedist, fecdist, negfec) {
    .Call('_lefko3_jerzeibalowski', PACKAGE = 'lefko3', ppy, AllStages, stageframe, matrixformat, survproxy, obsproxy, sizeproxy, repstproxy, fecproxy, jsurvproxy, jobsproxy, jsizeproxy, jrepstproxy, inda, indb, indc, survdev, obsdev, sizedev, repstdev, fecdev, jsurvdev, jobsdev, jsizedev, jrepstdev, fecmod, summedvars, sigma, jsummedvars, jsigma, maxsize, finalage, sizedist, fecdist, negfec)
}

#' Main Formula Creation for \code{modelsearch()}
#'
#' Function \code{stovokor()} creates formulae to be used as input in the
#' global model calls used in function \code{\link{modelsearch}()}.
#'
#' @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
#' 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 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 sizedist A string variable indicating the distribution to use to
#' model size.
#' @param fecdist A string variable indicating the distribution to use to
#' model fecundity.
#' @param nojuvs A logical value indicating that juvenile rates should be
#' estimated (\code{FALSE}) or not (\code{TRUE}).
#' @param age A string indicating the name of the variable coding age.
#' @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 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 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 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 juvsize A logical value indicating whether to include size terms in
#' juvenile models.
#' @param size0 A logical value indicating whether size distribution should
#' be zero-inflated. Only applies to Poisson and negative binomial
#' distributions.
#' @param fec0 A logical value indicating whether size distribution should
#' be zero-inflated. Only applies to Poisson and negative binomial
#' distributions.
#' 
#' @return Vector of 9 strings, each a formula to be used as input in function.
#' \code{modelsearch()}.
#'
#' @keywords internal
#' @noRd
stovokor <- function(surv, obs, size, repst, fec, vitalrates, historical, suite, approach, sizedist, fecdist, nojuvs, age, indcova, indcovb, indcovc, indiv, patch, year, pasrand, yasrand, fectime, juvsize, size0, fec0) {
    .Call('_lefko3_stovokor', PACKAGE = 'lefko3', surv, obs, size, repst, fec, vitalrates, historical, suite, approach, sizedist, fecdist, nojuvs, age, indcova, indcovb, indcovc, indiv, patch, year, pasrand, yasrand, fectime, juvsize, size0, fec0)
}

#' Vectorize Matrix for Historical Mean Matrix Estimation
#' 
#' Function \code{flagrantcrap()} vectorizes core indices of matrices
#' input as list elements.
#' 
#' @param Xmat A matrix originally a part of a list object.
#' @param allindices A vector of indices to remove from the matrix
#' 
#' @return A column vector of specifically called elements from the input
#' matrix.
#' 
#' @keywords internal
#' @noRd
flagrantcrap <- function(Xmat, allindices) {
    .Call('_lefko3_flagrantcrap', PACKAGE = 'lefko3', Xmat, allindices)
}

#' Vectorize Matrix for Ahistorical Mean Matrix Estimation
#' 
#' Function \code{moreflagrantcrap()} vectorizes matrices input as list
#' elements.
#' 
#' @param Xmat A matrix originally a part of a list object.
#' 
#' @return A column vector of the input matrix.
#' 
#' @keywords internal
#' @noRd
moreflagrantcrap <- function(Xmat) {
    .Call('_lefko3_moreflagrantcrap', PACKAGE = 'lefko3', Xmat)
}

#' Calculate Logarithms of Non-Zero Elements of Sparse Matrix
#' 
#' Function \code{spmat_log} finds the non-zero elements in a sparse matrix,
#' calculates their logs, and inserts them back into the matrix and returns it.
#' Based on code developed by Coatless Professor and posted by him on
#' StackOverflow.
#' 
#' @param B A sparse matrix. Note that this is assumed to be a population
#' projection matrix, meaning that all values are either 0 or positive.
#' 
#' @return A sparse matrix with non-zero values as logs of the elements in the
#' input matrix.
#' 
#' @keywords internal
#' @noRd
spmat_log <- function(coremat) {
    .Call('_lefko3_spmat_log', PACKAGE = 'lefko3', coremat)
}

#' Estimates Mean LefkoMat Object for Historical MPM
#' 
#' Function \code{turbogeodiesel()} estimates mean historical population
#' projection matrices, treating the mean as element-wise arithmetic.
#' 
#' @param loy A data frame denoting the population, patch, and occasion
#' designation for each matrix. Includes a total of 9 variables.
#' @param Umats A matrix with all U matrices turned into columns.
#' @param Fmats A matrix with all F matrices turned into columns.
#' @param hstages This is the \code{hstages} object held by \code{mats}.
#' @param agestages This is the \code{agestages} object held by \code{mats}.
#' @param stages This is the core stageframe held by \code{mats}, equivalent to
#' \code{ahstages}.
#' @param patchmats A logical value stating whether to estimate patch-level
#' means.
#' @param popmats A logical value stating whether to estimate population-level
#' means.
#' 
#' @return A list using the structure of a lefkoMat object.
#' 
#' @keywords internal
#' @noRd
turbogeodiesel <- function(loy, Umats, Fmats, hstages, agestages, stages, patchmats, popmats) {
    .Call('_lefko3_turbogeodiesel', PACKAGE = 'lefko3', loy, Umats, Fmats, hstages, agestages, stages, patchmats, popmats)
}

#' Estimates Mean LefkoMat Object for Ahistorical MPM
#' 
#' Function \code{geodiesel()} estimates mean ahistorical population
#' projection matrices, treating the mean as element-wise arithmetic. The
#' function can handle both normal ahistorical MPMs and age x stage ahistorical
#' MPMs.
#' 
#' @param loy A data frame denoting the population, patch, and occasion
#' designation of each matrix. Includes a total of 9 variables.
#' @param Umats A matrix with all U matrices turned into columns.
#' @param Fmats A matrix with all F matrices turned into columns.
#' @param agestages This is the \code{agestages} object held by \code{mats}.
#' @param stages This is the core stageframe held by \code{mats}, equivalent to
#' \code{ahstages}.
#' @param patchmats A logical value stating whether to estimate patch-level
#' means.
#' @param popmats A logical value stating whether to estimate population-level
#' means.
#' 
#' @return A list using the structure of a LefkoMat object.
#' 
#' @keywords internal
#' @noRd
geodiesel <- function(loy, Umats, Fmats, agestages, stages, patchmats, popmats) {
    .Call('_lefko3_geodiesel', PACKAGE = 'lefko3', loy, Umats, Fmats, agestages, stages, patchmats, popmats)
}

#' Full Eigen Analysis of a Single Dense Matrix
#' 
#' Function \code{decomp3()} returns all eigenvalues, right eigenvectors, and
#' left eigenvectors estimated for a matrix by the \code{eig_gen}() function
#' in the C++ Armadillo library. Works with dense matrices.
#' 
#' @param Amat A population projection matrix of class \code{matrix}.
#'
#' @return This function returns all estimated eigenvalues, right
#' eigenvectors, and left eigenvectors of a single matrix. This output is
#' provided as a list with three parts, named appropriately.
#' 
#' @keywords internal
#' @noRd
decomp3 <- function(Amat) {
    .Call('_lefko3_decomp3', PACKAGE = 'lefko3', Amat)
}

#' Full Eigen Analysis of a Single Sparse Matrix
#' 
#' Function \code{decomp3sp()} returns all eigenvalues, right eigenvectors, and
#' left eigenvectors estimated for a matrix by the \code{eigs_gen}() function
#' in the C++ Armadillo library. Works with sparse matrices.
#' 
#' @param Amat A population projection matrix of class \code{matrix}.
#'
#' @return This function returns all estimated eigenvalues, right
#' eigenvectors, and left eigenvectors of a single matrix. This output is
#' provided as a list with three parts, named appropriately.
#' 
#' @keywords internal
#' @noRd
decomp3sp <- function(Amat) {
    .Call('_lefko3_decomp3sp', PACKAGE = 'lefko3', Amat)
}

#' Full Eigen Analysis of a Single Sparse Matrix, with Sparse Input
#' 
#' \code{decomp3sp_inp()} returns all eigenvalues, right eigenvectors, and left
#' eigenvectors estimated for a matrix by the \code{eigs_gen}() function
#' in the C++ Armadillo library. Works with sparse matrices.
#' 
#' @param Amat A population projection matrix of class \code{matrix}.
#'
#' @return This function returns all estimated eigenvalues, right
#' eigenvectors, and left eigenvectors of a single matrix. This output is
#' provided as a list with three parts, named appropriately.
#' 
#' @section Notes:
#' This function works slightly differently from function \code{decomp3sp()} in
#' that the latter function requires a sparse matrix provided in dense format,
#' while this function requires a sparse matrix in sparse format.
#' 
#' @keywords internal
#' @noRd
decomp3sp_inp <- function(spAmat) {
    .Call('_lefko3_decomp3sp_inp', PACKAGE = 'lefko3', spAmat)
}

#' Estimate Deterministic Population Growth Rate of Any Matrix
#' 
#' \code{lambda3matrix()} returns the dominant eigenvalue of a single
#' dense or sparse projection matrix, provided in dense matrix format.
#' 
#' @param Amat A population projection matrix of class \code{matrix}.
#' @param sparse A logical value indicating whether to use sparse matrix
#' format.
#'
#' @return This function returns the dominant eigenvalue of the matrix. This
#' is given as the largest real part of all eigenvalues estimated via the 
#' \code{eig_gen}() and \code{eigs_gen}() functions in the C++ Armadillo
#' library.
#' 
#' @keywords internal
#' @noRd
lambda3matrix <- function(Amat, sparse) {
    .Call('_lefko3_lambda3matrix', PACKAGE = 'lefko3', Amat, sparse)
}

#' Estimate Stable Stage Distribution of Any Population Matrix
#' 
#' \code{ss3matrix()} returns the stable stage distribution for a 
#' dense or sparse population matrix.
#' 
#' @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)
}

#' 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).
#' 
#' @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 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.
#' 
#' @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.
#' 
#' @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 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.
#' 
#' @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 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.
#' 
#' @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 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.
#' 
#' @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)
}

#' Core Time-based Population Matrix Projection Function
#' 
#' Function \code{proj3()} runs the matrix projections used in other functions
#' in package \code{lefko3}.
#' 
#' @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.
#' 
#' @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 half of the matrix is the w projection (stage distribution) and the
#' bottom half 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 R vector, which is the
#' sum of the unstandardized w vector resulting from each occasion's
#' projection).
#' 
#' @keywords internal
#' @noRd
proj3 <- function(start_vec, core_list, mat_order, standardize, growthonly, integeronly) {
    .Call('_lefko3_proj3', PACKAGE = 'lefko3', start_vec, core_list, mat_order, standardize, growthonly, integeronly)
}

#' 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()}
#' 
#' @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 half of the matrix is the w projection (stage distribution) and the
#' bottom half 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 R vector, which is the
#' sum of the unstandardized 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 forward in time by a user-defined number of occasions, and can
#' perform these projections as replicates. Projections may be deterministic or
#' stochastic. 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. There is no limit to the number of replicates.
#' 
#' @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 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 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 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 FALSE.
#' @param start_vec An optional numeric vector denoting the starting stage
#' distribution for the projection. Defaults to a single individual of each
#' stage.
#' @param tweights An optional numeric vector denoting the probabilistic
#' weightings of annual matrices. Defaults to equal weighting among occasions.
#' 
#' @return A list of class \code{lefkoProj}, which always includes the first
#' three elements of the following, and also includes the remaiing elements
#' below when a \code{lefkoMat} object is used as input:
#' \item{projection}{A list of matrices showing the total number of individuals
#' per stage per occasion, or showing the former with the projected stage 
#' distribution and reproductive value per stage per occasion followed by
#' the total population size per occasion (all row-bound in order). Each matrix
#' corresponds to a different patch or population. If more than 1 replicate is
#' projected, then the results from these replicates will be stacked within the
#' same data frame.}
#' \item{labels}{A data frame showing the order of populations and patches in
#' item \code{projection}.}
#' \item{control}{A short vector indicating the number of replicates and the
#' number of occasions projected per replicate.}
#' \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.}
#' 
#' @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 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.
#' 
#' 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.
#'
#' @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)
#' 
#' lathrepm <- matrix(0, 7, 7)
#' lathrepm[1, 6] <- 0.345
#' lathrepm[2, 6] <- 0.054
#' 
#' 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"),
#'   repmatrix = lathrepm, supplement = lathsupp3, yearcol = "year2",
#'   indivcol = "individ")
#' 
#' lathproj <- projection3(ehrlen3, nreps = 5, stochastic = TRUE)
#' 
#' # Cypripedium example
#' rm(list = ls(all=TRUE))
#' 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", "SD", "P1"),
#'   stage2 = c("SD", "SD", "SD", "SD", "P1", "P2", "P3", "SL", "SL", "SL", "SL",
#'     "SL", "SL", "rep", "rep"),
#'   stage1 = c("SD", "rep", "SD", "rep", "SD", "P1", "P2", "P3", "P3", "P3",
#'     "SL", "SL", "SL", "mat", "mat"),
#'   eststage3 = c(NA, NA, NA, NA, NA, NA, NA, "D", "XSm", "Sm", "D", "XSm", "Sm",
#'     NA, NA),
#'   eststage2 = c(NA, NA, NA, NA, NA, NA, NA, "XSm", "XSm", "XSm", "XSm", "XSm",
#'     "XSm", NA, NA),
#'   eststage1 = c(NA, NA, NA, NA, NA, NA, NA, "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),
#'   multiplier = c(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, 3, 3),
#'   type_t12 = c(1, 2, 1, 2, 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, stochastic = FALSE, standardize = FALSE, growthonly = TRUE, integeronly = FALSE, start_vec = NULL, tweights = NULL) {
    .Call('_lefko3_projection3', PACKAGE = 'lefko3', mpm, nreps, times, stochastic, standardize, growthonly, integeronly, start_vec, tweights)
}

#' 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 (as given in equation 2 in
#' 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). Can handle both lefkoMat objects and
#' lists of full A matrices. 
#' 
#' @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 tweights Numeric vector denoting the probabilistic weightings of
#' annual matrices. Defaults to equal weighting among occasions.
#' 
#' @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:
#' 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.
#'
#' @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)
#' 
#' lathrepm <- matrix(0, 7, 7)
#' lathrepm[1, 6] <- 0.345
#' lathrepm[2, 6] <- 0.054
#' 
#' lathover3 <- overwrite(stage3 = c("Sd", "Sd", "Sdl"),
#'   stage2 = c("Sd", "Sd", "Sd"), stage1 = c("Sd", "rep", "rep"),
#'   givenrate = c(0.345, 0.345, 0.054))
#' 
#' ehrlen3 <- rlefko3(data = lathvert, stageframe = lathframe,
#'   year = c(1989, 1990), stages = c("stage3", "stage2", "stage1"),
#'   repmatrix = lathrepm, overwrite = lathover3, yearcol = "year2",
#'   indivcol = "individ")
#' 
#' slambda3(ehrlen3)
#' 
#' # 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", "SD", "P1"),
#'   stage2 = c("SD", "SD", "SD", "SD", "P1", "P2", "P3", "SL", "SL", "SL", "SL",
#'     "SL", "SL", "rep", "rep"),
#'   stage1 = c("SD", "rep", "SD", "rep", "SD", "P1", "P2", "P3", "P3", "P3",
#'     "SL", "SL", "SL", "mat", "mat"),
#'   eststage3 = c(NA, NA, NA, NA, NA, NA, NA, "D", "XSm", "Sm", "D", "XSm", "Sm",
#'     NA, NA),
#'   eststage2 = c(NA, NA, NA, NA, NA, NA, NA, "XSm", "XSm", "XSm", "XSm", "XSm",
#'     "XSm", NA, NA),
#'   eststage1 = c(NA, NA, NA, NA, NA, NA, NA, "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),
#'   multiplier = c(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, 3, 3),
#'   type_t12 = c(1, 2, 1, 2, 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)
#' cypstoch
#' 
#' @export slambda3
slambda3 <- function(mpm, times = 10000L, tweights = NULL) {
    .Call('_lefko3_slambda3', PACKAGE = 'lefko3', mpm, times, tweights)
}

#' 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). 
#' 
#' @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 style An integer designating whether to estimate sensitivity matrices
#' (\code{1}) or elasticity matrices (\code{2}). Defaults to 1.
#' @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, style = 1L, tweights = NULL) {
    .Call('_lefko3_stoch_senselas', PACKAGE = 'lefko3', mpm, times, style, tweights)
}

#' 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.
#' 
#' @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}11.}
#' \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.
#' 
#' @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)
}

#' 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()}.
#' 
#' @param e_amat A single elasticity, LTRE, or sLTRE 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.
#' 
#' @section Notes:
#' If the original matrices are provided, then this function was made to split
#' co-occurring survival-fecundity elasticities according to the ratio of the
#' fecundity portion of the element to the survival portion of that element.
#' However, this transition splitting capability developed using the original
#' matrices does not currently work properly, and so it is better to use this
#' function without objects \code{amat_} and \code{fmat_}, forcing co-occurring
#' survival-fecundity transitions to be treated as fecundity only.
#' 
#' @keywords internal
#' @noRd
demolition3 <- function(e_amat, bambesque, amat_ = NULL, fmat_ = NULL) {
    .Call('_lefko3_demolition3', PACKAGE = 'lefko3', e_amat, bambesque, amat_, fmat_)
}

#' 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.
#' 
#' @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 cube of LTRE contributions, with each slice
#' corresponding to each input matrix in 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 matrix of
#' a dense or sparse set of input matrices.
#' 
#' @param Amats A list of population projection matrices (not an entire
#' \code{lefkoMat} object).
#' @param loy A data frame showing the order of populations, patches, and
#' occasions of the matrices provided in object \code{Amats}.
#' @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 10,000. 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 3000.
#' @param sparse A logical value indicating whether to use sparse or dense
#' format in matrix calculations.
#' 
#' @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, loy, refnum, refmats_ = NULL, tweights_ = NULL, steps = 10000L, burnin = 3000L, sparse = FALSE) {
    .Call('_lefko3_sltre3matrix', PACKAGE = 'lefko3', Amats, loy, refnum, refmats_, tweights_, steps, burnin, sparse)
}

Try the lefko3 package in your browser

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

lefko3 documentation built on Sept. 8, 2021, 9:07 a.m.