R/RcppExports.R

Defines functions trait_axis ta_skeleton invade3 batch_project3 project3

Documented in batch_project3 invade3 project3 ta_skeleton trait_axis

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

#' Clean Up RObject Inputs to Projection Functions
#' 
#' This function takes RObject inputs in the core projection functions, and
#' uses them to create the strict inputs for projection.
#' 
#' @name cleanup3
#' 
#' @param mpms An optional list of MPMs. Each MPM must be of class
#' \code{lefkoMat}.
#' @param vrms An optional list of \code{vrm_input} objects, each corresponding
#' to a distinct MPM that will be created during projection. Each
#' \code{vrm_input} object requires its own stageframe, entered in the same
#' order via argument \code{stageframes}.
#' @param stageframes An optional list of stageframes, corresponding in number
#' and order to the MPMs in argument \code{vrms}. Each stageframe must be of
#' class \code{stageframe}.
#' @param supplements An optional list of data frames of class \code{lefkoSD}
#' that provide supplemental data that should be incorporated into
#' function-based MPMs, or for post-processing in pre-existing MPMs. If used,
#' then should be the same number of elements as the number of MPMs provided in
#' the list for argument \code{vrms}, with each element either a data frame or
#' \code{NULL}. See \code{\link[lefko3]{supplemental}()} for details.
#' @param format An optional integer vector indicating the kind of
#' function-based MPM to create for each \code{vrm_input} object entered in
#' argument \code{vrms}. Possible choices include: \code{1}, Ehrlen-format
#' historical MPM; \code{2}, deVries-format historical MPM; \code{3},
#' ahistorical MPM (default); \code{4}, age-by-stage MPM; and \code{5}, Leslie
#' (age-based) MPM.
#' @param firstage An optional integer vector used for function-based Leslie
#' and age-by-stage MPMs giving the starting ages in such MPMs. Use only if at
#' least one MPM is both function-based and has age structure. Typically,
#' the starting age in such MPMs should be set to \code{0} if post-breeding and
#' \code{1} if pre-breeding. All other MPMs should be set to \code{0}. Do not
#' use if no MPM has age structure. Defaults to \code{1} in age-based and age-
#' by-stage MPMs.
#' @param finalage An optional integer vector used for function-based Leslie
#' and age-by-stage MPMs giving the final ages in such MPMs. Use only if at
#' least one MPM is both function-based and has age structure. Do not use if no
#' MPM has age structure.
#' @param fecage_min An optional integer vector used for function-based Leslie
#' MPMs giving the first age at which organisms can be reproductive in such
#' MPMs. Use only if at least one MPM is a function-based Leslie MPM. Defaults
#' to the values given in \code{firstage}.
#' @param fecage_max An optional integer vector used for function-based Leslie
#' MPMs giving the final age at which organisms can be reproductive in such
#' MPMs. Use only if at least one MPM is a function-based Leslie MPM. Defaults
#' to the values given in \code{finalage}.
#' @param cont An optional vector used for function-based Leslie and
#' age-by-stage MPMs stating whether the MPM should should include a stasis
#' transition within the final age. This should be used only when an organism
#' can maintain the demographic characteristics of the final described age
#' after reaching that age. Can be entered as a logical vector or an integer
#' vector. MPMs without age structure should be entered as \code{0} or
#' \code{FALSE}. Do not use if no MPM has age structure.
#' @param fecmod An optional vector used for function-based MPMs giving scalar
#' multipliers for fecundity terms, when two fecundity variables are used for a
#' collective fecundity per individual. Each entry refers to each 
#' \code{vrm_input} object in argument \code{vrms}, in the same order.
#' @param starts An optional list of \code{lefkoSV} objects, which are data
#' frames providing the starting numbers of individuals of each stage. If
#' provided, then one is needed per MPM. If not provided, then all projections
#' start with a single individual of each stage per MPM.
#' @param patches An optional string vector with length equal to the number of
#' MPMs, detailing the name of each patch to project for each MPM, in order.
#' Only a single pop-patch may be projected for each MPM given. A value of
#' \code{NA} can be supplied to indicate that the population-level matrices
#' should be projected (if argument \code{mpms} is used and a population-level
#' set of matrices exist), or that the first patch noted should be used.
#' Defaults to the population-level set or the first patch, depending on
#' whether the former exists.
#' @param years An optional term corresponding either to a single integer
#' vector of time \code{t} values, if all MPMs will use the same time \code{t}
#' or set of time \code{t}'s, or a list of such vectors with each vector
#' corresponding to each MPM in order. In the latter case, a vector composed of
#' a single \code{NA} value is interpreted to mean that all time \code{t}
#' values in the MPM should be utilized. If a vector shorter than \code{times}
#' is supplied, then this vector will be cycled.
#' @param tweights An optional list composed of numeric vectors or matrices
#' denoting the probabilities of choosing each matrix in each MPM in a
#' stochastic projection. If an element of the list is a matrix, then a
#' first-order Markovian environment is assumed, in which the probability of
#' choosing a specific annual matrix depends on which annual matrix is
#' currently chosen. If an element of the list is a vector, then the choice of
#' annual matrix is assumed to be independent of the current matrix. Defaults
#' to equal weighting among matrices. If used, then one element per MPM is
#' required, with equal weighting assumed for any element set to \code{NULL}.
#' @param density An optional list of data frames of class \code{lefkoDens},
#' which provide details for density dependence in MPM elements and have been
#' created with function \code{\link[lefko3]{density_input}()}, or a two-
#' layered list of such data frames, with a data frame per annual matrix per
#' MPM.
#' @param entry_time An optional integer vector giving the entry time for each
#' MPM into the projection. Defaults to a zero vector with the length of the
#' number of MPMs, as given either by argument \code{mpms} or \code{vrms}.
#' @param density_vr An optional list of data frames of class
#' \code{lefkoDensVR}, which provide details for density dependence in vital
#' rate models and have been created with function
#' \code{link[lefko3]{density_vr}()}. If used, then one such data frame per MPM
#' is required. MPMs to be run without vital describing density dependence
#' relationships in vital rates should be set to \code{NULL}. Can only be used
#' with function-based projections.
#' @param sp_density An optional argument for use with \code{vrm_input} objects
#' that specifies the spatial density to be used in each time step. If used,
#' may either be a numeric vector giving a single spatial density for each
#' \code{vrm_input} object entered in argument \code{vrms} (in this case, the
#' value of spatial density given for each \code{vrm_input} object will be held
#' constant through the projection), or a list of as many numeric vectors as
#' \code{vrm_input} objects, with the length of each vector giving the spatial
#' density at each time step. If vectors are shorter than specified in 
#' \code{times}, then these values will be cycled.
#' @param ind_terms An optional argument providing values of individual or
#' environmental covariate values for \code{vrm_input} objects used in
#' function-based projection. Can be set either to a single data frame with 3
#' columns giving values for up to 3 covariates across time (rows give the time
#' order of these values), or a list of as many such data frames as
#' \code{vrm_input} objects. In the latter case, \code{vrm_input} objects that
#' do not use such covariates should have the associated element set to
#' \code{NULL}. Unused terms within each data frame must be set to \code{0}
#' (use of \code{NA} will produce errors.) If the number of rows is less than
#' \code{times}, then these values will be cycled.
#' @param dev_terms An optional list of data frames, one for each
#' \code{vrm_input} object. Each should include 14 or 17 columns and up to
#' \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. In addition, these may be followed by 3
#' columns designating additive deviations to: 15: individual covariate a,
#' 16: individual covariate b, and 17: individual covariate c. Unused terms
#' must be set to \code{0} (use of \code{NA} will produce errors). Single or
#' small numbers of values per vital rate model are also allowed, and if the
#' number of rows is less than \code{times}, then the terms will be cycled.
#' @param fb_sparse A logical vector indicating whether function-based MPMs
#' should be produced in sparse matrix format. Defaults to \code{FALSE} for
#' each MPM.
#' @param equivalence An optional numeric vector, list of numeric vectors,
#' data frame of class \code{adaptEq} or class \code{lefkoEq}, or a list of such
#' data frames. If a numeric vector, then must have the same number of elements
#' as the number of MPMs, with each element giving the effect of an individual
#' of each MPM relative to a reference individual. If a list of vectors, then
#' the list should be composed of as many numeric vectors as MPMs, or as a two-
#' layered list of such vectors for each annual matrix per MPM, with each
#' vector giving the effect of each individual in each stage relative to a
#' reference individual. Data frames of class \code{adaptEq}, and lists of such
#' data frames, can be made with function \code{\link{equiv_input}()}. Numeric
#' entries used in these vectors can be thought of as Lotka-Volterra
#' competition terms, such as are used in multiple species competition models.
#' @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 prep_mats An integer value for use when creating function-based MPM
#' projections. If using \code{vrms} input instead of \code{mpms} input, then
#' this argument determines how many matrices should be used as a limit to
#' develop matrices prior to running the projection. See \code{Notes} for
#' further details.
#' @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 force_fb A logical value indicating whether to force function-based
#' MPMs to be developed at each time step even if fewer than \code{prep_mats}.
#' Defaults to \code{FALSE}.
#' @param stochastic A Boolean value indicating to perform a temporally
#' stochastic projection.
#' @param err_check A logical value indicating whether to add extra terms to
#' the output.
#' 
#' @return A list of R-defined objects, including vectors, lists, integers, and
#' data frames, for use in later stages of analysis.
#' 
#' @keywords internal
#' @noRd
NULL

#' Engine Projecting Multiple Existing MPMs With or Without Density Dependence
#' 
#' Function \code{project3_pre_core} is the main function running processing of
#' projections with existing MPMs supplied by the user.
#' 
#' @name project3_pre_core
#' 
#' @param agg_density A numeric matrix giving the aggregate community density
#' by time (column) and replicate (row).
#' @param N_out The main list of final population sizes, supplied as a
#' reference and altered by this function.
#' @param comm_out The main list of full projection results for the community,
#' supplied as a pointer and altered by this function.
#' @param extreme_mpm_list A multi-level list output if
#' \code{err_check = "extreme"}.
#' @param mpm_list A list of MPMs in \code{lefkoMat} format.
#' @param A_list A list of lists of \code{A} matrices covering all entered
#' MPMs.
#' @param tweights_list A list of tweights vectors covering all MPMs.
#' @param start_list A list of starting information, supplied in \code{lefkoSV}
#' format.
#' @param vrm_list A list of \code{vrm_input} objects.
#' @param stageframe_list A list of stageframe objects covering all MPMs.
#' @param allmodels_all A list of extracted vrm inputs for all MPMs.
#' @param allstages_all A list of data frames giving the \code{allstages}
#' stage expansions giving indices for all matrix elements.
#' @param supplement_list A list of supplements in \code{lefkoSD} format.
#' @param year_list A list of vectors giving the main years used in each MPM.
#' @param ind_terms_num_list List of data frames giving values of numeric
#' individual covariates for each MPM.
#' @param ind_terms_cat_list List of data frames giving values of factor
#' individual covariates for each MPM.
#' @param dev_terms_list List of deviations for vital rate models in all MPMs,
#' plus additive deviations to inda, indb, and indc.
#' @param density_vr_list List of \code{lefkoDensVR} objects holding density
#' relationships for all 14 vital rate models, for all MPMs.
#' @param sp_density_list A list of values of spatial density for all MPMs.
#' @param density_list A list of data frames of class \code{lefkoDens} for all
#' MPMs.
#' @param dens_index_list A list of data frames giving indices for density
#' dependent transitions for each MPM.
#' @param equivalence_list An optional numeric vector, list of numeric vectors,
#' data frame of class \code{adaptEq}, or list of data frames of class
#' \code{adaptEq}. If a numeric vector, then must have the same number of
#' elements as the number of MPMs, with each element giving the effect of an
#' individual of each MPM relative to a reference individual. If a list of
#' vectors, then the list should be composed of as many numeric vectors as
#' MPMs, with each vector giving the effect of each individual in each stage
#' relative to a reference individual. Data frames of class \code{adaptEq}, and
#' lists of such data frames, can be made with function
#' \code{\link{equiv_input}()}. Numeric entries used in these vectors can be
#' thought of as Lotka-Volterra interaction terms, such as are used in multiple
#' species competition models.
#' @param dev_terms_num_vec A vector giving the number of vital rate deviations
#' in each MPM. Used to create function-based matrices under override option.
#' @param sp_density_num_vec A vector giving the number of spatial density
#' terms per MPM. Used to create function-based matrices under override option.
#' @param firstage_vec An integer vector containing the first age values for
#' all MPMs in order.
#' @param finalage_vec  An integer vector containing the final age values for
#' all MPMs in order.
#' @param stagecounts An integer vector containing the number of stages in each
#' MPM.
#' @param entry_time_vec An integer vector containing the entry time of each
#' mutant, population, or species, as given by each MPM.
#' @param format_vec An integer vector giving the MPM format of each MPM.
#' @param inda_terms_num_vec An integer vector giving the number of numeric
#' terms given in individual covariate a.
#' @param indb_terms_num_vec An integer vector giving the number of numeric
#' terms given in individual covariate b.
#' @param indc_terms_num_vec An integer vector giving the number of numeric
#' terms given in individual covariate c.
#' @param inda_terms_cat_vec An integer vector giving the number of factor
#' terms given in individual covariate a.
#' @param indb_terms_cat_vec An integer vector giving the number of factor
#' terms given in individual covariate b.
#' @param indc_terms_cat_vec An integer vector giving the number of factor
#' terms given in individual covariate c.
#' @param dens_yn_vec A vector stating whether density dependence is used in
#' each MPM, given through \code{lefkoDens} objects.
#' @param dens_vr_yn_vec A vector stating whether density dependence is used in
#' each MPM, given through \code{lefkoDensVR} objects.
#' @param dens_list_length_vec A vector giving the number of data frames of
#' density info per MPM, if lists of such data frames are used.
#' @param eq_list_length_vec A vector giving the number of data frames of
#' equivalence info per MPM, if lists of such data frames are used.
#' @param tweights_type_vec An integer vector giving the style of
#' \code{tweights} used in each MPM.
#' @param fecmod_vec A numeric vector giving the fecmod values for all MPMs.
#' @param sparse_vec A logical vector stating whether each MPM is in sparse
#' matrix format or not.
#' @param patch_vec A string vector giving the name of each patch used in each
#' MPM projection.
#' @param vrm_count An integer giving the number of vrm_inputs supplied.
#' @param mpm_count An integer giving the number of existing MPMs supplied.
#' @param nreps An integer giving the number of replicates to perform.
#' @param times An integer giving the amount of time steps to run the
#' projection for.
#' @param substoch An integer giving the level of sustochasticity to enforce.
#' @param exp_tol The maximum tolerated exponent.
#' @param theta_tol The maximum tolerated limit for theta, in non-linear
#' models such as those using the negative binomial.
#' @param integeronly A Boolean value indicating whether to allow only whole
#' values of individuals or not.
#' @param stages_not_equal A Boolean value indicating whether equivalence
#' info is supplied suggesting even stages within MPMs are not equal.
#' @param stochastic A Boolean value indicating to perform a temporally
#' stochastic projection.
#' @param entry_time_vec_use A Boolean value indicating whether entry
#' times differ among MPMs.
#' @param err_check A Boolean value indicating whether to include an extra list
#' of output objects for error checking.
#' @param err_check_extreme A Boolean value indicating whether to include an
#' extra list of all matrices projected in the \code{err_check} object.
#' @param benchmark_bool A Boolean value indicating whether to issue benchmark
#' statements on progress through the projection.
#' 
#' @return The first three arguments are directly manipulated without any
#' values returned.
#' 
#' @keywords internal
#' @noRd
NULL

#' Engine Projecting Multiple Function-based MPMs With or Without Density Dependence
#' 
#' Function \code{project3_fb_core} is the main function running processing of
#' projections in which matrices must be created at each time step.
#' 
#' @name project3_fb_core
#' 
#' @param agg_density A numeric matrix giving the aggregate community density
#' by time (column) and replicate (row).
#' @param N_out The main list of final population sizes, supplied as a
#' reference and altered by this function.
#' @param comm_out The main list of full projection results for the community,
#' supplied as a pointer and altered by this function.
#' @param extreme_mpm_out A multi-level list output if
#' \code{err_check = "extreme"}.
#' @param errcheck_fb_out A multi-level list of out matrices from matrix
#' calculation, output if \code{err_check = TRUE}.
#' @param start_list A list of starting information, supplied in \code{lefkoSV}
#' format.
#' @param vrm_list A list of unextracted \code{vrm_input} objects holding model
#' information for all MPMs to be created.
#' @param tweights_list A list of tweights vectors covering all MPMs.
#' @param stageframe_list A list of stageframe objects covering all MPMs.
#' @param allmodels_all A list of extracted vrm inputs for all MPMs.
#' @param allstages_all A list of data frames giving the \code{allstages}
#' stage expansions giving indices for all matrix elements.
#' @param supplement_list A list of supplements in \code{lefkoSD} format.
#' @param year_list A list of vectors giving the main years used in each MPM.
#' @param ind_terms_num_list List of data frames giving values of numeric
#' individual covariates for each MPM.
#' @param ind_terms_cat_list List of data frames giving values of factor
#' individual covariates for each MPM.
#' @param dev_terms_list List of deviations for vital rate models in all MPMs.
#' @param density_vr_list List of \code{lefkoDensVR} objects holding density
#' relationships for all 14 vital rate models, for all MPMs.
#' @param sp_density_list A list of values of spatial density for all MPMs.
#' @param density_list A list of data frames of class \code{lefkoDens} for all
#' MPMs.
#' @param dens_index_list A list of data frames giving indices for density
#' dependent transitions for each MPM.
#' @param equivalence_list An optional numeric vector, list of numeric vectors,
#' data frame of class \code{adaptEq}, or list of data frames of class
#' \code{adaptEq}. If a numeric vector, then must have the same number of
#' elements as the number of MPMs, with each element giving the effect of an
#' individual of each MPM relative to a reference individual. If a list of
#' vectors, then the list should be composed of as many numeric vectors as
#' MPMs, with each vector giving the effect of each individual in each stage
#' relative to a reference individual. Data frames of class \code{adaptEq}, and
#' lists of such data frames, can be made with function
#' \code{\link{equiv_input}()}. Numeric entries used in these vectors can be
#' thought of as Lotka-Volterra interaction terms, such as are used in multiple
#' species competition models.
#' @param dev_terms_num_vec A vector giving the number of vital rate deviations
#' in each MPM. Used to create function-based matrices under override option.
#' @param sp_density_num_vec A vector giving the number of spatial density
#' terms per MPM. Used to create function-based matrices under override option.
#' @param firstage_vec An integer vector containing the first age values for
#' all MPMs in order.
#' @param finalage_vec  An integer vector containing the final age values for
#' all MPMs in order.
#' @param stagecounts An integer vector containing the number of stages in each
#' MPM.
#' @param entry_time_vec An integer vector containing the entry time of each
#' mutant, population, or species, as given by each MPM.
#' @param format_vec An integer vector giving the MPM format of each MPM.
#' @param inda_terms_num_vec An integer vector giving the number of numeric
#' terms given in individual covariate a.
#' @param indb_terms_num_vec An integer vector giving the number of numeric
#' terms given in individual covariate b.
#' @param indc_terms_num_vec An integer vector giving the number of numeric
#' terms given in individual covariate c.
#' @param inda_terms_cat_vec An integer vector giving the number of factor
#' terms given in individual covariate a.
#' @param indb_terms_cat_vec An integer vector giving the number of factor
#' terms given in individual covariate b.
#' @param indc_terms_cat_vec An integer vector giving the number of factor
#' terms given in individual covariate c.
#' @param dens_yn_vec A vector stating whether density dependence is used in
#' each MPM, given through \code{lefkoDens} objects.
#' @param dens_vr_yn_vec A vector stating whether density dependence is used in
#' each MPM, given through \code{lefkoDensVR} objects.
#' @param dens_list_length_vec A vector giving the number of data frames of
#' density info per MPM, if lists of such data frames are used.
#' @param eq_list_length_vec A vector giving the number of data frames of
#' equivalence info per MPM, if lists of such data frames are used.
#' @param tweights_type_vec An integer vector giving the style of
#' \code{tweights} used in each MPM.
#' @param fecmod_vec A numeric vector giving the fecmod values for all MPMs.
#' @param sparse_vec A logical vector stating whether each MPM is in sparse
#' matrix format or not.
#' @param patch_vec A string vector giving the name of each patch used in each
#' MPM projection.
#' @param vrm_count An integer giving the number of vrm_inputs supplied.
#' @param nreps An integer giving the number of replicates to perform.
#' @param times An integer giving the amount of time steps to run the
#' projection for.
#' @param substoch An integer giving the level of sustochasticity to enforce.
#' @param exp_tol The maximum tolerated exponent.
#' @param theta_tol The maximum tolerated limit for theta, in non-linear
#' models such as those using the negative binomial.
#' @param integeronly A Boolean value indicating whether to allow only whole
#' values of individuals or not.
#' @param stages_not_equal A Boolean value indicating whether equivalence
#' info is supplied suggesting even stages within MPMs are not equal.
#' @param stochastic A Boolean value indicating to perform a temporally
#' stochastic projection.
#' @param err_check A logical value indicating whether to include an extra list
#' of output objects for error checking.
#' @param err_check_extreme A Boolean value indicating whether to include an
#' extra list of all matrices projected in the \code{err_check} object.
#' @param benchmark_bool A Boolean value indicating whether to issue benchmark
#' statements on progress through the projection.
#' 
#' @return The first three arguments are directly manipulated without any
#' values returned.
#' 
#' @keywords internal
#' @noRd
NULL

#' Clean Up RObject Inputs for Invasion Analysis
#' 
#' This function takes RObject inputs in the core projection functions, and
#' uses them to create the strict inputs for projection.
#' 
#' @name cleanup3_inv
#' 
#' @param mpm An MPM of class \code{lefkoMat}, for use if using existing MPMs.
#' @param vrm A \code{vrm_input} object corresponding to a distinct MPM that
#' will be created during analysis. Requires a stageframe, entered in argument
#' \code{stageframe}.
#' @param stageframe A stageframe defining stages and the life cycle for the
#' entered object in argument \code{vrms}. Must be of class \code{stageframe}.
#' @param supplement An optional data frame of class \code{lefkoSD} providing
#' supplemental data that should be incorporated into function-based MPMs. See
#' \code{\link[lefko3]{supplemental}()} for details. Use only with argument
#' \code{vrm}.
#' @param format An optional integer indicating the kind of function-based MPM
#' to create, if argument \code{vrm} is provided. Possible choices include:
#' \code{1}, Ehrlen-format historical MPM; \code{2}, deVries-format historical
#' MPM; \code{3}, ahistorical MPM (default); \code{4}, age-by-stage MPM; and
#' \code{5}, Leslie (age-based) MPM. Defaults to \code{3}.
#' @param firstage An optional integer used for function-based Leslie and
#' age-by-stage MPMs giving the starting ages in such MPMs. Use only if MPM is
#' both function-based and has age structure. Typically, the starting age in
#' such MPMs should be set to \code{0} if post-breeding and \code{1} if
#' pre-breeding. All other MPMs should be set to \code{0}. Do not use if not
#' using age structure. 
#' @param finalage An optional integer used for function-based Leslie and
#' age-by-stage MPMs giving the final ages in such MPMs. Use only if MPM is
#' both function-based and has age structure. Do not use if not using age
#' structure.
#' @param fecage_min An optional integer used for function-based Leslie MPMs
#' giving the first age at which organisms can be reproductive. Use only for
#' function-based Leslie MPMs. Defaults to the values given in \code{firstage}.
#' @param fecage_max An integer value used for function-based Leslie MPMs
#' giving the final age at which organisms can be reproductive. Use only for
#' function-based Leslie MPMs. Defaults to the values given in \code{finalage}.
#' @param cont An optional vector used for function-based Leslie and
#' age-by-stage MPMs stating whether the MPM should should include a stasis
#' transition within the final age. This should be used only when an organism
#' can maintain the demographic characteristics of the final described age
#' after reaching that age. Can be entered as a logical value or an integer. 
#' MPMs without age structure should be entered as \code{0} or \code{FALSE}.
#' Do not use if not using age structure.
#' @param fecmod An optional value used for function-based MPMs giving scalar
#' multipliers for fecundity terms, when two fecundity variables are used for a
#' collective fecundity per individual.
#' @param start An optional \code{lefkoSV} object, which is a data frame
#' providing the starting numbers of individuals of each stage. If not
#' provided, then all projections start with a single individual of each stage.
#' @param patch An optional string giving the name of the patch to project.
#' Only a single pop-patch may be projected. A value of \code{NA} can be
#' supplied to indicate that the population-level matrices should be projected
#' (if argument \code{mpm} is used and a population-level set of matrices
#' exist), or that the first patch noted should be used. Defaults to the
#' population-level set or the first patch, depending on whether the former
#' exists.
#' @param years An optional term corresponding to a single integer vector of
#' time \code{t} values. If a vector shorter than \code{times} is supplied,
#' then this vector will be cycled. Defaults to a vector of all detected
#' years in argument \code{mpm} or argument \code{vrm}.
#' @param tweights An optional numeric vector or matrix denoting the
#' probabilities of choosing each matrix in each MPM in a stochastic
#' projection. If a matrix, then a first-order Markovian environment is
#' assumed, in which the probability of choosing a specific annual matrix
#' depends on which annual matrix is currently chosen. If an element of the
#' list is a vector, then the choice of annual matrix is assumed to be
#' independent of the current matrix. Defaults to equal weighting among
#' matrices.
#' @param density An optional data frames of class \code{lefkoDens}, which
#' provides details for density dependence in MPM elements and is created with
#' function \code{\link[lefko3]{density_input}()}. Defaults to \code{NULL}, in
#' which case no density dependence is built into matrix elements.
#' @param entry_time An optional integer vector giving the entry time for each
#' variant into each simulation. Defaults to a zero vector with length equal to
#' the number of variants to run concurrently in each simulation, as given by
#' argument \code{var_per_run}.
#' @param density_vr An optional data frame of class \code{lefkoDensVR}, which
#' provides details for density dependence in vital rate models and has been
#' created with function \code{link[lefko3]{density_vr}()}. Can only be used
#' with function-based projections. Defaults to \code{NULL}, in which case no
#' density dependence is built into vital rates.
#' @param sp_density An optional argument for use with argument \code{vrm} that
#' specifies the spatial density to be used in each time step. If used, then
#' may either be a numeric vector giving a single spatial density for each
#' time step. If vectors are shorter than specified in \code{times}, then these
#' values will be cycled.
#' @param ind_terms An optional argument providing values of individual or
#' environmental covariate values for argument \code{vrm}. Should be set to a
#' single data frame with 3 columns giving values for up to 3 covariates across
#' time (rows give the time order of these values). Unused terms within the
#' data frame must be set to \code{0} (use of \code{NA} will produce errors).
#' If the number of rows is less than \code{times}, then these values will be
#' cycled.
#' @param dev_terms An optional list of data frames, one for each
#' \code{vrm_input} object. Each should include 14 or 17 columns and up to
#' \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. In addition, these may be followed by 3
#' columns designating additive deviations to: 15: individual covariate a,
#' 16: individual covariate b, and 17: individual covariate c. Unused terms
#' must be set to \code{0} (use of \code{NA} will produce errors). Single or
#' small numbers of values per vital rate model are also allowed, and if the
#' number of rows is less than \code{times}, then the terms will be cycled.
#' @param fb_sparse A logical vector indicating whether function-based MPMs
#' should be produced in sparse matrix format. Defaults to \code{FALSE} for
#' each MPM.
#' @param equivalence An optional object of class \code{adaptEq} giving the
#' degree to which individuals in each stage are equivalent to one another.
#' May also be a numeric vector, in which case the vector must have the same
#' number of elements as the number of rows in the associated MPM, with each
#' element giving the effect of an individual of that age, stage, age-stage, or
#' stage-pair, depending on whether the MPM is age-based, ahistorical
#' stage-based, age-by-stage, or historical stage-based, respectively. Numeric
#' entries used in these vectors can be thought of as Lotka-Volterra
#' interaction terms, such as are used in multiple species competition models.
#' @param prebreeding An optional value stating whether the life cycle is
#' prebreeding. If no value is entered for \code{firstage}, then a value of
#' \code{TRUE} sets the minimum age to 0, and a value of \code{FALSE} sets it
#' to 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 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 variant_count An integer giving the number of variants total.
#' @param var_per_run The number of variants to run in each simulation.
#' Defaults to \code{2}, resulting in pairwise invasibility analysis. See
#' \code{Notes} for details.
#' 
#' @return A list of R-defined objects, including vectors, lists, integers, and
#' data frames, for use in later stages of analysis.
#' 
#' @keywords internal
#' @noRd
NULL

#' Core Pre-Existing MPM Projection Engine for ESS Evaluation
#' 
#' Function \code{invpre_optim_single} runs single simulation instances of the
#' optimization projections in function \code{invade3_pre_core}, and is used to
#' estimate ESS values.
#' 
#' @name invpre_optim_singlerun
#' 
#' @param out_df A data frame created by reference to hold the fitness values
#' produced by the run.
#' @param base_trait_axis The currently used trait axis.
#' @param N_out A matrix giving the final population sizes of the run. Supplied
#' as a reference.
#' @param comm_out The main list of full projection results for the community,
#' supplied as a pointer and altered by this function. Needs to be essentially
#' blank to work properly. Needs to me a lst with only one level, with elements
#' as matrics.
#' @param new_stageexpansion_list A list with stage expansions only for the
#' variants to run, in order.
#' @param used_times A list of year numbers for each time per run.
#' @param zero_stage_vec_list A list of population stage vectors full of zeros.
#' @param start_list A list of starting information, supplied in \code{lefkoSV}
#' format.
#' @param equivalence_list A list giving the effect of each individual in each
#' stage relative to a reference individual.
#' @param A_list A list of all A matrices.
#' @param U_list A list of all U matrices.
#' @param F_list A list of all F matrices.
#' @param density_df A data frame of class \code{lefkoDens}.
#' @param dens_index_df A data frame giving indices for density dependent
#' transitions.
#' @param entry_time_vec An IntegerVector containing the entry time of each
#' mutant, population, or species, as given by each MPM.
#' @param times An integer giving the number of occasions to project.
#' @param fitness_times The number of occasions at the end of each run to use
#' to estimate the Lyapunov coefficient.
#' @param format_int An integer giving the MPM format.
#' @param firstage_int An integer giving the first age in a Leslie or
#' age-by-stage MPM.
#' @param finalage_int  An integer giving the final age in a Leslie or
#' age-by-stage MPM.
#' @param substoch An integer giving the level of sustochasticity to enforce.
#' @param exp_tol The maximum tolerated exponent.
#' @param theta_tol The maximum tolerated limit for theta, in non-linear
#' @param conv_threshold The lower limit for the absolute value of fitness,
#' below which fitness is rounded to 0. Defaults to 0.00000001.
#' @param sparse_bool A Boolean value indiating whether the MPM is in sparse
#' matrix format.
#' @param A_only A Boolean value indicating whether to export U and F matrices
#' for alteration, or only A matrices.
#' @param stages_not_equal A Boolean value indicating whether equivalence
#' info is supplied suggesting even stages within MPMs are not equal.
#' @param integeronly A Boolean value indicating whether to allow only whole
#' values of individuals or not.
#' @param dens_yn_bool A Boolean value stating whether density dependence is
#' used, given through \code{lefkoDens} objects.
#' @param zap_min A Boolean value describing whether to round fitness values
#' below the value given in \code{threshold}.
#' 
#' @return An arma style matrix is produced and returned via reference.
#' 
#' @keywords internal
#' @noRd
NULL

#' Find ESS Values of Traits in Pre-Existing MPM Invasibility Analyses
#' 
#' This function attempts to estimate any ESS trait values in the trait axis.
#' These ESS trait values are initially identified as possible given flipped
#' signs of elasticity fitness at points along the input trait axis to use in
#' optimization.
#' 
#' @name ESS_optimizer_pre
#' 
#' @param ESS_Lyapunov A data frame to hold the ESS trait values, built by
#' reference.
#' @param ESS_trait_axis A data frame giving the minimum and maximum values of
#' variable traits, and the constant values of all others, in the trait axis.
#' @param Lyapunov_optim Main data frame giving Lyapunov coefficients for all
#' trait combinations developed for the ESS optima table. Holds elasticity
#' fitness values.
#' @param optim_trait_axis Main trait axis data frame corresponding to
#' \code{Lyapunov_optim}.
#' @param ESS_var_traits An integer vector modified by this function by
#' reference, indicating the actual traits that vary. The element order is:
#' 1, givenrate; 2, offset; 3, multiplier; 4, surv_dev; 5, obs_dev;
#' 6, size_dev; 7, sizeb_dev; 8, sizec_dev; 9, repst_dev; 10, fec_dev;
#' 11, jsurv_dev; 12, jobs_dev; 13, jsize_dev; 14, jsizeb_dev; 15, jsizec_dev;
#' 16, jrepst_dev; 17, jmatst_dev; 18, indcova; 19, indcovb; and 20, indcovc.
#' @param flipped_traits An integer vector with 17 elements, giving the
#' identities of variables with both positive and negative values.
#' @param new_stageexpansion_list A list with stage expansions for all
#' variant data used in ESS evaluation. This list includes an extra layer of
#' list elements, corresponding to the optim_ta and optim_ta_995 data.
#' @param used_times A list of year numbers for each time per run.
#' @param zero_stage_vec_list A list of population stage vectors full of zeros.
#' @param start_list A list of starting information, supplied in \code{lefkoSV}
#' format.
#' @param equivalence_list A list giving the effect of each individual in each
#' stage relative to a reference individual.
#' @param A_list A list of all A matrices.
#' @param U_list A list of all U matrices.
#' @param F_list A list of all F matrices.
#' @param density_df A data frame of class \code{lefkoDens}.
#' @param dens_index_df A data frame giving indices for density dependent
#' transitions.
#' @param stageframe_df A stageframe object covering the MPM.
#' @param entry_time_vec An IntegerVector containing the entry time of each
#' mutant, population, or species, as given by each MPM.
#' @param times An integer giving the number of occasions to project.
#' @param fitness_times AN integer giving the number of occasions at the end of
#' the run to use to estimate Lyapunov coefficients.
#' @param format_int An integer giving the MPM format.
#' @param stagecounts An integer giving the number of stages in the life
#' history.
#' @param firstage_int An integer giving the first age in a Leslie or
#' age-by-stage MPM.
#' @param finalage_int  An integer giving the final age in a Leslie or
#' age-by-stage MPM.
#' @param substoch An integer giving the level of sustochasticity to enforce.
#' @param exp_tol The maximum tolerated exponent.
#' @param theta_tol The maximum tolerated limit for theta, in non-linear
#' vital rate models (particulaly negative binomial models).
#' @param sparse_bool A Boolean value indiating whether the MPM is in sparse
#' matrix format.
#' @param A_only A Boolean value indicating whether to export U and F matrices
#' for alteration, or only A matrices.
#' @param stages_not_equal A Boolean value indicating whether equivalence
#' info is supplied suggesting even stages within MPMs are not equal.
#' @param integeronly A Boolean value indicating whether to allow only whole
#' values of individuals or not.
#' @param dens_yn_bool A Boolean value stating whether density dependence is
#' used, given through \code{lefkoDens} objects.
#' @param conv_threshold The convergence threshold value for Lyapunov
#' coefficients estimated in ESS optimization.
#' @param opt_res If evaluating optima, then this integer gives the number
#' of variants to create between each minimum and maximum for each trait found
#' to be variable in the input trait axis. A relic value that equals the number
#' of variants in the entered trait axis.
#' @param opt_res_orig The original value of \code{opt_res}, prior to the
#' determination of the number of variable traits. Equal to \code{opt_res} if
#' the number of variable traits is 1, and to the square root of \code{opt_res}
#' if the number of variable traits is 2.
#' @param ehrlen An integer stating if historical MPMs should be in Ehrlen
#' format.
#' @param style An integer giving the style (e.g. ahistorical vs. historical)
#' of MPM.
#' @param loop_max The maximum number of times to attempt optimization, if
#' convergence does not occur.
#' @param filter An integer giving cleanup options for MPMs.
#' @param elast_mult A multiplier for traits to assess the elasticity of
#' fitness in trait optimization. Defaults to 0.995.
#' @param zap_min A Boolean value describing whether to round fitness values
#' below the value given in \code{threshold}.
#' 
#' @return A final data frame giving the zeros associated with variable traits.
#' 
#' @keywords internal
#' @noRd
NULL

#' Core Function-Based Projection Engine for ESS Evaluation
#' 
#' Function \code{invfb_optim_singlerun} runs single simulation instances of the
#' optimization projections in function \code{invade3_fb_core}, and is used to
#' estimate ESS values.
#' 
#' @name invfb_optim_singlerun
#' 
#' @param out_df A data frame created by reference to hold the fitness values
#' produced by the run.
#' @param surv_dev_nta The survival column in the reassessed trait axis.
#' @param obs_dev_nta The observation status column in the reassessed trait
#' axis.
#' @param size_dev_nta The primary size column in the reassessed trait axis.
#' @param sizeb_dev_nta The secondary size column in the reassessed trait axis.
#' @param sizec_dev_nta The tertiary size column in the reassessed trait axis.
#' @param repst_dev_nta The reproductive status column in the reassessed trait
#' axis.
#' @param fec_dev_nta The fecundity column in the reassessed trait axis.
#' @param jsurv_dev_nta The juvenile survival column in the reassessed trait
#' axis.
#' @param jobs_dev_nta The juvenile observation status column in the reassessed
#' trait axis.
#' @param jsize_dev_nta The juvenile primary size column in the reassessed
#' trait axis.
#' @param jsizeb_dev_nta The juvenile secondary size column in the reassessed
#' trait axis.
#' @param jsizec_dev_nta The juvenile tertiary size column in the reassessed
#' trait axis.
#' @param jrepst_dev_nta The juvenile reproductive status column in the
#' reassessed trait axis.
#' @param jmatst_dev_nta The juvenile maturity status column in the reassessed
#' trait axis.
#' @param indcova_nta The individual covariate a column in the reassessed
#' trait axis.
#' @param indcovb_nta The individual covariate b column in the reassessed
#' trait axis.
#' @param indcovc_nta The individual covariate c column in the reassessed
#' trait axis.
#' @param variant_nta The variant column in the reassessed 995 trait axis.
#' @param base_trait_axis The currently used trait axis.
#' @param N_out A matrix giving the final population sizes of the run. Supplied
#' as a reference.
#' @param comm_out The main list of full projection results for the community,
#' supplied as a pointer and altered by this function. Needs to be essentially
#' blank to work properly. Needs to me a lst with only one level, with elements
#' as matrices.
#' @param errcheck_mpm A list of all MPMs post-processing. Only output if
#' \code{err_check = "extreme"}.
#' @param errcheck_mpmout A list of all mpm_out matrices from MPM processing. 
#' Only output if \code{err_check = "extreme"}.
#' @param new_stageexpansion_list A list with stage expansions for all
#' variant data used in ESS evaluation. This list includes an extra layer of
#' list elements, corresponding to the optim_ta and optim_ta_995 data.
#' @param used_times A list of year numbers for each time per run.
#' @param allmodels_all A list of extracted vrm inputs for all MPMs.
#' @param vrm_list A list of \code{vrm_input} objects.
#' @param allstages_all The allstages indexing data frame used to produce MPMs.
#' @param dev_terms_list List of deviations for vital rate models.
#' @param ind_terms_num_list List of data frames giving values of numeric
#' individual covariates.
#' @param ind_terms_cat_list List of data frames giving values of factor
#' individual covariates.
#' @param stageexpansion_ta_devterms_by_variant A list giving trait axis info
#' by variant, with each variant given a list element.
#' @param sp_density_list A list of values of spatial density for all MPMs.
#' @param start_list A list of starting information, supplied in \code{lefkoSV}
#' format.
#' @param equivalence_list A list giving the effect of each individual in each
#' stage relative to a reference individual.
#' @param density_vr_list Data frame of \code{lefkoDensVR} objects holding
#' density relationships for all 14 vital rate models.
#' @param current_stageframe The main stageframe, including extra stages.
#' @param current_supplement A supplement in \code{lefkoSD} format.
#' @param density_df A data frame of class \code{lefkoDens}.
#' @param dens_index_df A data frame giving indices for density dependent
#' transitions.
#' @param entry_time_vec An IntegerVector containing the entry time of each
#' mutant, population, or species, as given by each MPM.
#' @param sp_density_num_vec A vector giving the number of spatial density
#' terms.
#' @param inda_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate a.
#' @param indb_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate b.
#' @param indc_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate c.
#' @param inda_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate a.
#' @param indb_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate b.
#' @param indc_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate c.
#' @param dens_vr_yn_vec A vector stating whether density dependence is used,
#' given through \code{lefkoDensVR} objects.
#' @param fecmod_vec A numeric vector giving the fecmod values.
#' @param year_vec A vector giving the main years used.
#' @param patch_vec A vector giving the name of each patch used in projection.
#' @param times An integer giving the number of occasions to project.
#' @param fitness_times An integer giving the number of occasions at the end of
#' each run to use to estimate Lyapunov coefficients.
#' @param format_int An integer giving the MPM format.
#' @param firstage_int An integer giving the first age in a Leslie or
#' age-by-stage MPM.
#' @param finalage_int  An integer giving the final age in a Leslie or
#' age-by-stage MPM.
#' @param dev_terms_times_int A vector giving the number of occasions over
#' which vital rate y-intercept deviations cycle.
#' @param substoch An integer giving the level of sustochasticity to enforce.
#' @param opt_res If evaluating optima, then this integer gives the number
#' of variants to create between each minimum and maximum for each trait found
#' to be variable in the input trait axis. Note that the version used in this
#' function is actually equivalent to \code{opt_res_true}.
#' @param opt_res_orig The original value of \code{opt_res}, prior to the
#' determination of the number of variable traits. Equal to \code{opt_res} if
#' the number of variable traits is 1, and to the square root of \code{opt_res}
#' if the number of variable traits is 2.
#' @param exp_tol The maximum tolerated exponent.
#' @param theta_tol The maximum tolerated limit for theta, in non-linear
#' models such as those using the negative binomial.
#' @param conv_threshold The lower limit for the absolute value of fitness,
#' below which fitness is rounded to 0. Defaults to 0.00000001.
#' @param sparse_bool A Boolean value indiating whether the MPM is in sparse
#' matrix format.
#' @param A_only A Boolean value indicating whether to export U and F matrices
#' for alteration, or only A matrices.
#' @param stages_not_equal A Boolean value indicating whether equivalence
#' info is supplied suggesting even stages within MPMs are not equal.
#' @param integeronly A Boolean value indicating whether to allow only whole
#' values of individuals or not.
#' @param dens_yn_bool A Boolean value stating whether density dependence is
#' used, given through \code{lefkoDens} objects.
#' @param err_check A logical value indicating whether to include an extra list
#' of output objects for error checking.
#' @param zap_min A Boolean value describing whether to round fitness values
#' below the value given in \code{threshold}.
#' 
#' @return The first four arguments are directly manipulated without any
#' values returned.
#' 
#' @keywords internal
#' @noRd
NULL

#' Find ESS Values of Traits in Function-Based MPM Invasibility Analyses
#' 
#' @name ESS_optimizer_fb
#' 
#' @param ESS_Lyapunov A data frame to hold the ESS trait values, built by
#' reference.
#' @param ESS_trait_axis A data frame giving the minimum and maximum values of
#' variable traits, and the constant values of all others, in the trait axis.
#' @param Lyapunov_optim Main data frame giving Lyapunov coefficients for all
#' trait combinations developed for the ESS optima table. Holds elasticity
#' fitness values.
#' @param optim_trait_axis Main trait axis data frame corresponding to
#' \code{Lyapunov_optim}.
#' @param ESS_var_traits An integer vector modifed by this function by
#' reference, indicating the actual traits that vary. The element order is:
#' 1, givenrate; 2, offset; 3, multiplier; 4, surv_dev; 5, obs_dev;
#' 6, size_dev; 7, sizeb_dev; 8, sizec_dev; 9, repst_dev; 10, fec_dev;
#' 11, jsurv_dev; 12, jobs_dev; 13, jsize_dev; 14, jsizeb_dev; 15, jsizec_dev;
#' 16, jrepst_dev; 17, jmatst_dev; 18, indcova; 19, indcovb; and 20, indcovc.
#' @param flipped_traits An integer vector with 17 elements, giving the
#' identities of variables with both positive and negative values.
#' @param surv_dev_nta The survival column in the reassessed trait axis.
#' @param obs_dev_nta The observation status column in the reassessed trait
#' axis.
#' @param size_dev_nta The primary size column in the reassessed trait axis.
#' @param sizeb_dev_nta The secondary size column in the reassessed trait axis.
#' @param sizec_dev_nta The tertiary size column in the reassessed trait axis.
#' @param repst_dev_nta The reproductive status column in the reassessed trait
#' axis.
#' @param fec_dev_nta The fecundity column in the reassessed trait axis.
#' @param jsurv_dev_nta The juvenile survival column in the reassessed trait
#' axis.
#' @param jobs_dev_nta The juvenile observation status column in the reassessed
#' trait axis.
#' @param jsize_dev_nta The juvenile primary size column in the reassessed
#' trait axis.
#' @param jsizeb_dev_nta The juvenile secondary size column in the reassessed
#' trait axis.
#' @param jsizec_dev_nta The juvenile tertiary size column in the reassessed
#' trait axis.
#' @param jrepst_dev_nta The juvenile reproductive status column in the
#' reassessed trait axis.
#' @param jmatst_dev_nta The juvenile maturity status column in the reassessed
#' trait axis.
#' @param indcova_nta The individual covariate a column in the reassessed
#' trait axis.
#' @param indcovb_nta The individual covariate b column in the reassessed
#' trait axis.
#' @param indcovc_nta The individual covariate c column in the reassessed
#' trait axis.
#' @param variant_nta The variant column in the reassessed 995 trait axis.
#' @param new_stageexpansion_list A list with stage expansions for all
#' variant data used in ESS evaluation. This list includes an extra layer of
#' list elements, corresponding to the optim_ta and optim_ta_995 data.
#' @param used_times A list of year numbers for each time per run.
#' @param errcheck_mpm An optional list of all MPMs post-processing. Only
#' output if \code{err_check = "extreme"}.
#' @param errcheck_mpmout An optional list of all mpm_out matrices from MPM
#' processing. Only output if \code{err_check = "extreme"}.
#' @param allmodels_all A list of extracted vrm inputs for all MPMs.
#' @param vrm_list A list of \code{vrm_input} objects.
#' @param allstages_all The allstages indexing data frame used to produce MPMs.
#' @param dev_terms_list List of deviations for vital rate models.
#' @param ind_terms_num_list List of data frames giving values of numeric
#' individual covariates.
#' @param ind_terms_cat_list List of data frames giving values of factor
#' individual covariates.
#' @param stageexpansion_ta_devterms_by_variant A list giving trait axis info
#' by variant, with each variant given a list element.
#' @param sp_density_list A list of values of spatial density for all MPMs.
#' @param start_list A list of starting information, supplied in \code{lefkoSV}
#' format.
#' @param equivalence_list A list giving the effect of each individual in each
#' stage relative to a reference individual.
#' @param density_vr_list Data frame of \code{lefkoDensVR} objects holding
#' density relationships for all 14 vital rate models.
#' @param current_stageframe The main stageframe, including extra stages.
#' @param current_supplement A supplement in \code{lefkoSD} format.
#' @param density_df A data frame of class \code{lefkoDens}.
#' @param dens_index_df A data frame giving indices for density dependent
#' transitions.
#' @param stageframe_df A stageframe object covering the MPM.
#' @param entry_time_vec An IntegerVector containing the entry time of each
#' mutant, population, or species, as given by each MPM.
#' @param sp_density_num_vec A vector giving the number of spatial density
#' terms.
#' @param inda_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate a.
#' @param indb_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate b.
#' @param indc_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate c.
#' @param inda_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate a.
#' @param indb_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate b.
#' @param indc_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate c.
#' @param dens_vr_yn_vec A vector stating whether density dependence is used,
#' given through \code{lefkoDensVR} objects.
#' @param fecmod_vec A numeric vector giving the fecmod values.
#' @param year_vec A vector giving the main years used.
#' @param patch_vec A vector giving the name of each patch used in projection.
#' @param times An integer giving the number of occasions to project.
#' @param fitness_times An integer giving the number of occasions at the end of
#' each run to use to estimate Lyapunov coefficients.
#' @param format_int An integer giving the MPM format.
#' @param stagecounts An integer giving the number of stages in the life
#' history.
#' @param firstage_int An integer giving the first age in a Leslie or
#' age-by-stage MPM.
#' @param finalage_int  An integer giving the final age in a Leslie or
#' age-by-stage MPM.
#' @param dev_terms_times_int A vector giving the number of occasions over
#' which vital rate y-intercept deviations cycle.
#' @param substoch An integer giving the level of sustochasticity to enforce.
#' @param exp_tol The maximum tolerated exponent.
#' @param theta_tol The maximum tolerated limit for theta, in non-linear
#' models such as those using the negative binomial.
#' @param sparse_bool A Boolean value indiating whether the MPM is in sparse
#' matrix format.
#' @param A_only A Boolean value indicating whether to export U and F matrices
#' for alteration, or only A matrices.
#' @param stages_not_equal A Boolean value indicating whether equivalence
#' info is supplied suggesting even stages within MPMs are not equal.
#' @param integeronly A Boolean value indicating whether to allow only whole
#' values of individuals or not.
#' @param dens_yn_bool A Boolean value stating whether density dependence is
#' used, given through \code{lefkoDens} objects.
#' @param conv_threshold The convergence threshold for Lyapunov coefficients
#' used in ESS optimization.
#' @param opt_res If evaluating optima, then this integer gives the number
#' of variants to create between each minimum and maximum for each trait found
#' to be variable in the input trait axis. A relic value currently equal to the
#' number of variants in the entered trait axis.
#' @param opt_res_orig The original value of \code{opt_res}, prior to the
#' determination of the number of variable traits. Equal to \code{opt_res} if
#' the number of variable traits is 1, and to the square root of \code{opt_res}
#' if the number of variable traits is 2.
#' @param ehrlen An integer stating if historical MPMs should be in Ehrlen
#' format.
#' @param style An integer giving the style (e.g. ahistorical vs. historical)
#' of MPM.
#' @param loop_max The maximum number of times to attempt optimization, if
#' convergence does not occur.
#' @param filter An integer giving cleanup options for MPMs.
#' @param err_check A logical value indicating whether to include an extra list
#' of output objects for error checking.
#' @param elast_mult A multiplier for traits to assess the elasticity of
#' fitness in trait optimization. Defaults to 0.995.
#' @param zap_min A Boolean value describing whether to round fitness values
#' below the value given in \code{threshold}.
#' 
#' @return A final data frame giving the zeros associated with variable traits.
#' 
#' @keywords internal
#' @noRd
NULL

#' Core Pre-Existing MPM Projection Engine
#' 
#' Function \code{invpre_project} runs the projections in function
#' \code{invade3_pre_core}.
#' 
#' @name invpre_project
#' 
#' @param var_run_mat A matrix giving the the variants to be run in each
#' projection, with rows giving the projections and columns giving the
#' variants.
#' @param N_out_pre The main list of final population sizes, supplied as a
#' reference and altered by this function.
#' @param comm_out_pre The main list of full projection results for the community,
#' supplied as a pointer and altered by this function.
#' @param new_stageexpansion_list A list with stage expansions for all trait
#' axis data leading to matrix element changes with each list element
#' corresponding to each respective variant.
#' @param errcheck_mpm_reps An optional list of all MPMs post-processing. Only
#' output if \code{err_check = "extreme"}.
#' @param used_times A list of year numbers for each time per run.
#' @param zero_stage_vec_list A list of population stage vectors full of zeros.
#' @param start_list A list of starting information, supplied in \code{lefkoSV}
#' format.
#' @param equivalence_list A list giving the effect of each individual in each
#' stage relative to a reference individual.
#' @param A_list A list of allA matrices.
#' @param U_list A list of all U matrices.
#' @param F_list A list of all F matrices.
#' @param density_df A data frame of class \code{lefkoDens}.
#' @param dens_index_df A data frame giving indices for density dependent
#' transitions.
#' @param entry_time_vec An IntegerVector containing the entry time of each
#' mutant, population, or species, as given by each MPM.
#' @param var_per_run An integer giving the number of variants per run.
#' @param times An integer giving the number of occasions to project.
#' @param var_mat_length An integer giving the number of rows in the variant
#' matrix.
#' @param format_int An integer giving the MPM format.
#' @param current_rep The integer giving the current replicate.
#' @param firstage_int An integer giving the first age in a Leslie or
#' age-by-stage MPM.
#' @param finalage_int  An integer giving the final age in a Leslie or
#' age-by-stage MPM.
#' @param substoch An integer giving the level of sustochasticity to enforce.
#' @param exp_tol The maximum tolerated exponent.
#' @param theta_tol The maximum tolerated limit for theta, in non-linear
#' @param err_check A logical value indicating whether to include an extra list
#' of output objects for error checking.
#' @param err_check_extreme A logical value indicating whether to include an
#' extra list of all matrices projected in the \code{err_check} object.
#' @param sparse_bool A Boolean value indiating whether the MPM is in sparse
#' matrix format.
#' @param A_only A Boolean value indicating whether to export U and F matrices
#' for alteration, or only A matrices.
#' @param stages_not_equal A Boolean value indicating whether equivalence
#' info is supplied suggesting even stages within MPMs are not equal.
#' @param integeronly A Boolean value indicating whether to allow only whole
#' values of individuals or not.
#' @param dens_yn_bool A Boolean value stating whether density dependence is
#' used, given through \code{lefkoDens} objects.
#' @param benchmark_bool A Boolean value indicating whether to issue benchmark
#' statements on progress through the projection.
#' 
#' @return Arguments 2 through 7 are directly manipulated without any values
#' returned.
#' 
#' @keywords internal
#' @noRd
NULL

#' Core Pre-Existing MPM Projection Engine for ESS Evaluation
#' 
#' Function \code{invpre_optim} runs the optimization projections in function
#' \code{invade3_pre_core} used to estimate ESS values.
#' 
#' @name invpre_optim
#' 
#' @param N_out_pre The main list of final population sizes, supplied as a
#' reference and altered by this function.
#' @param comm_out_pre The main list of full projection results for the community,
#' supplied as a pointer and altered by this function.
#' @param new_stageexpansion_list A list with stage expansions for all
#' variant data used in ESS evaluation. This list includes an extra layer of
#' list elements, corresponding to the optim_ta and optim_ta_995 data.
#' @param errcheck_mpm_reps An optional list of all MPMs post-processing. Only
#' output if \code{err_check = "extreme"}.
#' @param used_times A list of year numbers for each time per run.
#' @param zero_stage_vec_list A list of population stage vectors full of zeros.
#' @param start_list A list of starting information, supplied in \code{lefkoSV}
#' format.
#' @param equivalence_list A list giving the effect of each individual in each
#' stage relative to a reference individual.
#' @param A_list A list of all A matrices.
#' @param U_list A list of all U matrices.
#' @param F_list A list of all F matrices.
#' @param density_df A data frame of class \code{lefkoDens}.
#' @param dens_index_df A data frame giving indices for density dependent
#' transitions.
#' @param entry_time_vec An IntegerVector containing the entry time of each
#' mutant, population, or species, as given by each MPM.
#' @param var_per_run An integer giving the number of variants per run.
#' @param times An integer giving the number of occasions to project.
#' @param var_mat_length An integer giving the number of rows in the variant
#' matrix.
#' @param format_int An integer giving the MPM format.
#' @param current_rep The integer giving the current replicate.
#' @param firstage_int An integer giving the first age in a Leslie or
#' age-by-stage MPM.
#' @param finalage_int  An integer giving the final age in a Leslie or
#' age-by-stage MPM.
#' @param substoch An integer giving the level of sustochasticity to enforce.
#' @param opt_res If evaluating optima, then this integer gives the number
#' of variants to create between each minimum and maximum for each trait found
#' to be variable in the input trait axis. Note that the version used in this
#' function is actually equivalent to \code{opt_res_true}.
#' @param opt_res_orig The original value of \code{opt_res}, prior to the
#' determination of the number of variable traits. Equal to \code{opt_res} if
#' the number of variable traits is 1, and to the square root of \code{opt_res}
#' if the number of variable traits is 2.
#' @param exp_tol The maximum tolerated exponent.
#' @param theta_tol The maximum tolerated limit for theta, in non-linear
#' @param threshold The lower limit for the absolute value of fitness, below
#' which fitness is rounded to 0. Defaults to 0.00000001.
#' @param err_check A logical value indicating whether to include an extra list
#' of output objects for error checking.
#' @param err_check_extreme A logical value indicating whether to include an
#' extra list of all matrices projected in the \code{err_check} object.
#' @param sparse_bool A Boolean value indiating whether the MPM is in sparse
#' matrix format.
#' @param A_only A Boolean value indicating whether to export U and F matrices
#' for alteration, or only A matrices.
#' @param stages_not_equal A Boolean value indicating whether equivalence
#' info is supplied suggesting even stages within MPMs are not equal.
#' @param integeronly A Boolean value indicating whether to allow only whole
#' values of individuals or not.
#' @param dens_yn_bool A Boolean value stating whether density dependence is
#' used, given through \code{lefkoDens} objects.
#' @param benchmark_bool A Boolean value indicating whether to issue benchmark
#' statements on progress through the projection.
#' 
#' @return Arguments 2 through 7 are directly manipulated without any values
#' returned.
#' 
#' @keywords internal
#' @noRd
NULL

#' Set-Up Running Invasion Analyses of Existing MPMs
#' 
#' Function \code{invade3_pre_core} is the main function running invasion
#' analyses with existing MPMs supplied by the user.
#' 
#' @name invade3_pre_core
#' 
#' @param Lyapunov The main data frame giving the Lyapunov coefficients
#' estimated, as well as the circumstances resulting in them.
#' @param Lyapunov_optim Main data frame giving Lyapunov coefficients for all
#' trait combinations developed for the ESS optima table. Holds elasticity
#' fitness values.
#' @param ESS_Lyapunov A data frame provided by reference that will hold the
#' ESS optima.
#' @param var_run_mat A matrix giving the order of trait variants in each
#' run.
#' @param N_out The main list of final population sizes, supplied as a
#' reference and altered by this function.
#' @param comm_out The main list of full projection results for the community,
#' supplied as a pointer and altered by this function.
#' @param N_out_optim The main list of final population sizes from ESS
#' optimization, supplied as a reference and altered by this function.
#' @param comm_out_optim The main list of full projection results for the
#' community resulting from ESS optimization, supplied as a pointer and altered
#' by this function.
#' @param zero_stage_vec_list A list of vectors giving zero stage vectors for
#' each MPM, if entry times are staggered.
#' @param trait_axis A data frame of class \code{adaptAxis} holding the trait
#' data to test.
#' @param new_trait_axis A data frame giving trait axis data post-processing
#' with function \code{ta_reassess()}.
#' @param optim_trait_axis A data frame giving trait axis data processed for
#' ESS optimization.
#' @param optim_trait_axis_995 A data frame giving trait axis data processed
#' for ESS optimization for variants 99.5% the values of the core frame.
#' @param new_stageexpansion_list A list with stage expansions for all trait
#' axis data leading to matrix element changes with each list element
#' corresponding to each respective variant.
#' @param new_stageexpansion_list_optima A list with stage expansions for all
#' variant data used in ESS evaluation.
#' @param errcheck_mpms An optional list of all MPMs post-processing. Only
#' output if \code{err_check = TRUE}.
#' @param errcheck_mpms_optim An optional list of all MPMs used in ESS optima
#' evaluation. Only output if \code{err_check = TRUE}.
#' @param chosen_mpm An MPM in \code{lefkoMat} format.
#' @param tweights_list The tweights vector or matrix covering the MPM.
#' @param start_list The data frame or vector of starting information, ideally
#' supplied in \code{lefkoSV} format.
#' @param vrm_list The unextracted \code{vrm_input} object.
#' @param stageframe_df A stageframe object covering the MPM.
#' @param allmodels_all The list holding the extracted vrm input.
#' @param allstages_all The allstages indexing data frame used to produce MPMs.
#' @param supplement_df A supplement in \code{lefkoSD} format.
#' @param chosen_years A string vector giving the main years used.
#' @param sp_density_list A list of values of spatial density for all MPMs.
#' @param density_df A data frame of class \code{lefkoDens}.
#' @param dens_index_df A data frame giving indices for density dependent
#' transitions.
#' @param equivalence_list A list giving the effect of each individual in each
#' stage in each MPM relative to a reference individual. Each element of the
#' list corresponds to each respective MPM.
#' @param sp_density_num_vec A vector giving the number of
#' spatial density terms per MPM.
#' @param entry_time_vec An integer vector containing the entry time of each
#' mutant, population, or species, as given by each MPM.
#' @param inda_terms_num_vec A vector giving the number of
#' numeric terms given in individual covariate a.
#' @param indb_terms_num_vec A vector giving the number of
#' numeric terms given in individual covariate b.
#' @param indc_terms_num_vec A vector giving the number of
#' numeric terms given in individual covariate c.
#' @param inda_terms_cat_vec A vector giving the number of
#' factor terms given in individual covariate a.
#' @param indb_terms_cat_vec A vector giving the number of
#' factor terms given in individual covariate b.
#' @param indc_terms_cat_vec A vector giving the number of
#' factor terms given in individual covariate c.
#' @param dens_vr_yn_vec A vector stating whether density dependence is used
#' in each MPM, given through \code{lefkoDensVR} objects.
#' @param tweights_type_vec A vector giving the style of \code{tweights} used
#' in each MPM.
#' @param fecmod_vec A numeric vector giving fecmod values.
#' @param patch_vec A vector giving the name of each patch used in projection.
#' @param variant_count An integer giving the number of variants to run in
#' invasion analysis.
#' @param var_per_run The number of variants to run in each projection.
#' @param nreps An integer giving the number of replicates to perform.
#' @param times An integer giving the amount of time steps to run the
#' projection for.
#' @param fitness_times An integer giving how many time steps at the end of
#' each run to use to estimate fitness.
#' @param stagecounts Integer denoting the number of stages in the MPM.
#' @param substoch An integer giving the level of sustochasticity to enforce.
#' @param format_int An integer giving the MPM format.
#' @param preexisting_mpm_size The number of elements per MPM matrix.
#' @param firstage_int An integer giving the first age in a Leslie or
#' age-by-stage MPM.
#' @param finalage_int  An integer giving the final age in a Leslie or
#' age-by-stage MPM.
#' @param main_optim_res An integer giving the number of variants being tested.
#' @param opt_res If evaluating optima, then this integer gives the number
#' of variants to create between each minimum and maximum for each trait found
#' to be variable in the input trait axis.
#' @param exp_tol The maximum tolerated exponent.
#' @param theta_tol The maximum tolerated limit for theta, in non-linear
#' models such as those using the negative binomial.
#' @param loop_max The maximum number of times to attempt optimization, if
#' convergence does not occur.
#' @param integeronly A Boolean value indicating whether to allow only whole
#' values of individuals or not.
#' @param stages_not_equal A Boolean value indicating whether equivalence
#' info is supplied suggesting even stages within MPMs are not equal.
#' @param stochastic A Boolean value indicating to perform a temporally
#' stochastic projection.
#' @param dens_yn_bool A Boolean value stating whether density dependence is
#' used in the MPM, given through a \code{lefkoDens} object.
#' @param entry_time_vec_use A Boolean value indicating whether entry times
#' differ among MPMs.
#' @param sparse_bool A Boolean value stating whether the MPM is in sparse
#' matrix format.
#' @param historical A Boolean value indicating whether the MPM is historical.
#' @param pure_leslie A Boolean value indicating whether the MPM is Leslie.
#' @param A_only A Boolean value indicating whether to export U and F matrices
#' for alteration, or only A matrices.
#' @param err_check A logical value indicating whether to include an extra list
#' of output objects for error checking.
#' @param err_check_extreme A logical value indicating whether to include an
#' extra list of all matrices projected in the \code{err_check} object.
#' @param threshold The lower limit for the absolute value of fitness, below
#' which fitness is rounded to 0. Defaults to 0.00000001.
#' @param fitness_table A Boolean value dictating whether to include a data
#' frame giving Lyapunov coefficients for all combinations of variants tested.
#' Necessary for the creation of pairwise invasibility plots (PIPs). Defaults
#' to \code{TRUE}.
#' @param ESS_optima A logical value indicating whether to assess the values of
#' ESS optima for traits that vary among variants in the given \code{adaptAxis}
#' table. Defaults to \code{TRUE}.
#' @param elast_mult A multiplier for traits to assess the elasticity of
#' fitness in trait optimization. Defaults to 0.995.
#' @param zap_min A Boolean value describing whether to round fitness values
#' below the value given in \code{threshold}.
#' @param benchmark_bool A Boolean value indicating whether to issue benchmark
#' statements on progress through the projection.
#' 
#' @return The first four arguments are directly manipulated without any
#' values returned.
#' 
#' @keywords internal
#' @noRd
NULL

#' Core Function-Based Projection Engine
#' 
#' Function \code{invfb_project} runs the projections in function
#' \code{invade3_fb_core}.
#' 
#' @name invfb_project
#' 
#' @param var_run_mat A matrix giving the the variants to be run in each
#' projection, with rows giving the projections and columns giving the
#' variants.
#' @param surv_dev_nta The survival column in the reassessed trait axis.
#' @param obs_dev_nta The observation status column in the reassessed trait
#' axis.
#' @param size_dev_nta The primary size column in the reassessed trait axis.
#' @param sizeb_dev_nta The secondary size column in the reassessed trait axis.
#' @param sizec_dev_nta The tertiary size column in the reassessed trait axis.
#' @param repst_dev_nta The reproductive status column in the reassessed trait
#' axis.
#' @param fec_dev_nta The fecundity column in the reassessed trait axis.
#' @param jsurv_dev_nta The juvenile survival column in the reassessed trait
#' axis.
#' @param jobs_dev_nta The juvenile observation status column in the reassessed
#' trait axis.
#' @param jsize_dev_nta The juvenile primary size column in the reassessed
#' trait axis.
#' @param jsizeb_dev_nta The juvenile secondary size column in the reassessed
#' trait axis.
#' @param jsizec_dev_nta The juvenile tertiary size column in the reassessed
#' trait axis.
#' @param jrepst_dev_nta The juvenile reproductive status column in the
#' reassessed trait axis.
#' @param jmatst_dev_nta The juvenile maturity status column in the reassessed
#' trait axis.
#' @param indcova_nta The individual covariate a column in the reassessed trait
#' axis.
#' @param indcovb_nta The individual covariate b column in the reassessed trait
#' axis.
#' @param indcovc_nta The individual covariate c column in the reassessed trait
#' axis.
#' @param variant_nta The variant column in the reassessed trait axis.
#' @param N_out_pre The main list of final population sizes, supplied as a
#' reference and altered by this function.
#' @param comm_out_pre The main list of full projection results for the community,
#' supplied as a pointer and altered by this function.
#' @param new_stageexpansion_list A list with stage expansions for all trait
#' axis data leading to matrix element changes with each list element
#' corresponding to each respective variant.
#' @param errcheck_mpm_reps An optional list of all MPMs post-processing. Only
#' output if \code{err_check = "extreme"}.
#' @param errcheck_mpmout_reps An optional list of all mpm_out matrices from MPM
#' processing. Only output if \code{err_check = "extreme"}.
#' @param mdtl The modified dev terms list.
#' @param used_times A list of year numbers for each time per run.
#' @param allmodels_all A list of extracted vrm inputs for all MPMs.
#' @param vrm_list A list of \code{vrm_input} objects.
#' @param allstages_all The allstages indexing data frame used to produce MPMs.
#' @param dev_terms_list List of deviations for vital rate models.
#' @param ind_terms_num_list List of data frames giving values of numeric
#' individual covariates.
#' @param ind_terms_cat_list List of data frames giving values of factor
#' individual covariates.
#' @param stageexpansion_ta_devterms_by_variant A list giving trait axis info
#' by variant, with each variant given a list element.
#' @param sp_density_list A list of values of spatial density for all MPMs.
#' @param start_list A list of starting information, supplied in \code{lefkoSV}
#' format.
#' @param equivalence_list A list giving the effect of each individual in each
#' stage relative to a reference individual.
#' @param density_vr_list Data frame of \code{lefkoDensVR} objects holding
#' density relationships for all 14 vital rate models.
#' @param current_stageframe The main stageframe, including extra stages.
#' @param current_supplement A supplement in \code{lefkoSD} format.
#' @param density_df A data frame of class \code{lefkoDens}.
#' @param dens_index_df A data frame giving indices for density dependent
#' transitions.
#' @param entry_time_vec An IntegerVector containing the entry time of each
#' mutant, population, or species, as given by each MPM.
#' @param sp_density_num_vec A vector giving the number of spatial density
#' terms.
#' @param inda_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate a.
#' @param indb_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate b.
#' @param indc_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate c.
#' @param inda_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate a.
#' @param indb_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate b.
#' @param indc_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate c.
#' @param dens_vr_yn_vec A vector stating whether density dependence is used,
#' given through \code{lefkoDensVR} objects.
#' @param sp_density_counter A matrix counting the use of spatial density terms
#' across variants and times.
#' @param inda_num_terms_previous A vector with numeric individual covariate a
#' terms for time t-1.
#' @param indb_num_terms_previous A vector with numeric individual covariate b
#' terms for time t-1.
#' @param indc_num_terms_previous A vector with numeric individual covariate c
#' terms for time t-1.
#' @param inda_cat_terms_previous A vector with categorical individual
#' covariate a terms for time t-1.
#' @param indb_cat_terms_previous A vector with categorical individual
#' covariate b terms for time t-1.
#' @param indc_cat_terms_previous A vector with categorical individual
#' covariate c terms for time t-1.
#' @param inda_num_terms_counter A vector with numeric individual covariate a
#' terms for time t.
#' @param indb_num_terms_counter A vector with numeric individual covariate b
#' terms for time t.
#' @param indc_num_terms_counter A vector with numeric individual covariate c
#' terms for time t.
#' @param inda_cat_terms_counter A vector with categorical individual covariate
#' a terms for time t.
#' @param indb_cat_terms_counter A vector with categorical individual covariate
#' b terms for time t.
#' @param indc_cat_terms_counter A vector with categorical individual covariate
#' c terms for time t.
#' @param dev_num_counter A vector giving the number of vital rate deviations
#' in each MPM.
#' @param fecmod_vec A numeric vector giving the fecmod values.
#' @param year_vec A vector giving the main years used.
#' @param patch_vec A vector giving the name of each patch used in projection.
#' @param var_per_run An integer giving the number of variants per run.
#' @param times An integer giving the number of occasions to project.
#' @param var_mat_length An integer giving the number of rows in the variant
#' matrix.
#' @param format_int An integer giving the MPM format.
#' @param current_rep The integer giving the current replicate.
#' @param firstage_int An integer giving the first age in a Leslie or
#' age-by-stage MPM.
#' @param finalage_int  An integer giving the final age in a Leslie or
#' age-by-stage MPM.
#' @param dev_terms_times_int A vector giving the number of occasions over
#' which vital rate y-intercept deviations cycle.
#' @param substoch An integer giving the level of sustochasticity to enforce.
#' @param year_counter An integer for year counts during projection.
#' @param exp_tol The maximum tolerated exponent.
#' @param theta_tol The maximum tolerated limit for theta, in non-linear
#' models such as those using the negative binomial.
#' @param err_check A logical value indicating whether to include an extra list
#' of output objects for error checking.
#' @param err_check_extreme A logical value indicating whether to include an
#' extra list of all matrices projected in the \code{err_check} object.
#' @param sparse_bool A Boolean value indiating whether the MPM is in sparse
#' matrix format.
#' @param A_only A Boolean value indicating whether to export U and F matrices
#' for alteration, or only A matrices.
#' @param stages_not_equal A Boolean value indicating whether equivalence
#' info is supplied suggesting even stages within MPMs are not equal.
#' @param integeronly A Boolean value indicating whether to allow only whole
#' values of individuals or not.
#' @param dens_yn_bool A Boolean value stating whether density dependence is
#' used, given through \code{lefkoDens} objects.
#' @param benchmark_bool A Boolean value indicating whether to issue benchmark
#' statements on progress through the projection.
#' 
#' @return The first four arguments are directly manipulated without any
#' values returned.
#' 
#' @keywords internal
#' @noRd
NULL

#' Core Function-Based Projection Engine for ESS Evaluation
#' 
#' Function \code{invfb_optim} runs the optimization projections in function
#' \code{invade3_fb_core}. These are responsible for the estimation of ESS
#' values.
#' 
#' @name invfb_optim
#' 
#' @param surv_dev_nta The survival column in the reassessed trait axis.
#' @param obs_dev_nta The observation status column in the reassessed trait
#' axis.
#' @param size_dev_nta The primary size column in the reassessed trait axis.
#' @param sizeb_dev_nta The secondary size column in the reassessed trait axis.
#' @param sizec_dev_nta The tertiary size column in the reassessed trait axis.
#' @param repst_dev_nta The reproductive status column in the reassessed trait
#' axis.
#' @param fec_dev_nta The fecundity column in the reassessed trait axis.
#' @param jsurv_dev_nta The juvenile survival column in the reassessed trait
#' axis.
#' @param jobs_dev_nta The juvenile observation status column in the reassessed
#' trait axis.
#' @param jsize_dev_nta The juvenile primary size column in the reassessed
#' trait axis.
#' @param jsizeb_dev_nta The juvenile secondary size column in the reassessed
#' trait axis.
#' @param jsizec_dev_nta The juvenile tertiary size column in the reassessed
#' trait axis.
#' @param jrepst_dev_nta The juvenile reproductive status column in the
#' reassessed trait axis.
#' @param jmatst_dev_nta The juvenile maturity status column in the reassessed
#' trait axis.
#' @param indcova_nta The individual covariate a column in the reassessed
#' trait axis.
#' @param indcovb_nta The individual covariate b column in the reassessed
#' trait axis.
#' @param indcovc_nta The individual covariate c column in the reassessed
#' trait axis.
#' @param variant_nta The variant column in the reassessed 995 trait axis.
#' @param surv_dev_nta_995 The survival column in the reassessed 995 trait
#' axis.
#' @param obs_dev_nta_995 The observation status column in the reassessed 995
#' trait axis.
#' @param size_dev_nta_995 The primary size column in the reassessed 995 trait
#' axis.
#' @param sizeb_dev_nta_995 The secondary size column in the reassessed 995
#' trait axis.
#' @param sizec_dev_nta_995 The tertiary size column in the reassessed 995
#' trait axis.
#' @param repst_dev_nta_995 The reproductive status column in the reassessed
#' 995 trait axis.
#' @param fec_dev_nta_995 The fecundity column in the reassessed 995 trait
#' axis.
#' @param jsurv_dev_nta_995 The juvenile survival column in the reassessed 995
#' trait axis.
#' @param jobs_dev_nta_995 The juvenile observation status column in the
#' reassessed 995 trait axis.
#' @param jsize_dev_nta_995 The juvenile primary size column in the reassessed
#' 995 trait axis.
#' @param jsizeb_dev_nta_995 The juvenile secondary size column in the
#' reassessed 995 trait axis.
#' @param jsizec_dev_nta_995 The juvenile tertiary size column in the
#' reassessed 995 trait axis.
#' @param jrepst_dev_nta_995 The juvenile reproductive status column in the
#' reassessed 995 trait axis.
#' @param jmatst_dev_nta_995 The juvenile maturity status column in the
#' reassessed 995 trait axis.
#' @param indcova_nta_995 The individual covariate a column in the reassessed
#' 995 trait axis.
#' @param indcovb_nta_995 The individual covariate b column in the reassessed
#' 995 trait axis.
#' @param indcovc_nta_995 The individual covariate c column in the reassessed
#' 995 trait axis.
#' @param variant_nta_995 The variant column in the reassessed 995 trait axis.
#' @param N_out_pre The main list of final population sizes, supplied as a
#' reference and altered by this function.
#' @param comm_out_pre The main list of full projection results for the community,
#' supplied as a pointer and altered by this function.
#' @param new_stageexpansion_list A list with stage expansions for all
#' variant data used in ESS evaluation. This list includes an extra layer of
#' list elements, corresponding to the optim_ta and optim_ta_995 data.
#' @param errcheck_mpm_reps An optional list of all MPMs post-processing. Only
#' output if \code{err_check = "extreme"}.
#' @param errcheck_mpmout_reps An optional list of all mpm_out matrices from MPM
#' processing. Only output if \code{err_check = "extreme"}.
#' @param mdtl The modified dev terms list.
#' @param used_times A list of year numbers for each time per run.
#' @param allmodels_all A list of extracted vrm inputs for all MPMs.
#' @param vrm_list A list of \code{vrm_input} objects.
#' @param allstages_all The allstages indexing data frame used to produce MPMs.
#' @param dev_terms_list List of deviations for vital rate models.
#' @param ind_terms_num_list List of data frames giving values of numeric
#' individual covariates.
#' @param ind_terms_cat_list List of data frames giving values of factor
#' individual covariates.
#' @param stageexpansion_ta_devterms_by_variant A list giving trait axis info
#' by variant, with each variant given a list element.
#' @param sp_density_list A list of values of spatial density for all MPMs.
#' @param start_list A list of starting information, supplied in \code{lefkoSV}
#' format.
#' @param equivalence_list A list giving the effect of each individual in each
#' stage relative to a reference individual.
#' @param density_vr_list Data frame of \code{lefkoDensVR} objects holding
#' density relationships for all 14 vital rate models.
#' @param current_stageframe The main stageframe, including extra stages.
#' @param current_supplement A supplement in \code{lefkoSD} format.
#' @param density_df A data frame of class \code{lefkoDens}.
#' @param dens_index_df A data frame giving indices for density dependent
#' transitions.
#' @param entry_time_vec An IntegerVector containing the entry time of each
#' mutant, population, or species, as given by each MPM.
#' @param sp_density_num_vec A vector giving the number of spatial density
#' terms.
#' @param inda_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate a.
#' @param indb_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate b.
#' @param indc_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate c.
#' @param inda_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate a.
#' @param indb_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate b.
#' @param indc_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate c.
#' @param dens_vr_yn_vec A vector stating whether density dependence is used,
#' given through \code{lefkoDensVR} objects.
#' @param fecmod_vec A numeric vector giving the fecmod values.
#' @param year_vec A vector giving the main years used.
#' @param patch_vec A vector giving the name of each patch used in projection.
#' @param var_per_run An integer giving the number of variants per run.
#' @param times An integer giving the number of occasions to project.
#' @param var_mat_length An integer giving the number of rows in the variant
#' matrix.
#' @param format_int An integer giving the MPM format.
#' @param current_rep The integer giving the current replicate.
#' @param firstage_int An integer giving the first age in a Leslie or
#' age-by-stage MPM.
#' @param finalage_int  An integer giving the final age in a Leslie or
#' age-by-stage MPM.
#' @param dev_terms_times_int A vector giving the number of occasions over
#' which vital rate y-intercept deviations cycle.
#' @param substoch An integer giving the level of sustochasticity to enforce.
#' @param opt_res If evaluating optima, then this integer gives the number
#' of variants to create between each minimum and maximum for each trait found
#' to be variable in the input trait axis. Note that the version used in this
#' function is actually equivalent to \code{opt_res_true}.
#' @param opt_res_orig The original value of \code{opt_res}, prior to the
#' determination of the number of variable traits. Equal to \code{opt_res} if
#' the number of variable traits is 1, and to the square root of \code{opt_res}
#' if the number of variable traits is 2.
#' @param year_counter An integer for year counts during projection.
#' @param exp_tol The maximum tolerated exponent.
#' @param theta_tol The maximum tolerated limit for theta, in non-linear
#' models such as those using the negative binomial.
#' @param threshold The lower limit for the absolute value of fitness, below
#' which fitness is rounded to 0. Defaults to 0.00000001.
#' @param err_check A logical value indicating whether to include an extra list
#' of output objects for error checking.
#' @param err_check_extreme A logical value indicating whether to include an
#' extra list of all matrices projected in the \code{err_check} object.
#' @param sparse_bool A Boolean value indiating whether the MPM is in sparse
#' matrix format.
#' @param A_only A Boolean value indicating whether to export U and F matrices
#' for alteration, or only A matrices.
#' @param stages_not_equal A Boolean value indicating whether equivalence
#' info is supplied suggesting even stages within MPMs are not equal.
#' @param integeronly A Boolean value indicating whether to allow only whole
#' values of individuals or not.
#' @param dens_yn_bool A Boolean value stating whether density dependence is
#' used, given through \code{lefkoDens} objects.
#' @param benchmark_bool A Boolean value indicating whether to issue benchmark
#' statements on progress through the projection.
#' 
#' @return The first four arguments are directly manipulated without any
#' values returned.
#' 
#' @keywords internal
#' @noRd
NULL

#' Set-Up Function Running Invasion Analyses of Function-based MPMs
#' 
#' Function \code{invade3_fb_core} is the main function running invasion
#' analyses in which matrices must be created at each time step.
#' 
#' @name invade3_fb_core
#' 
#' @param Lyapunov The main data frame giving the Lyapunov coefficients
#' estimated, as well as the circumstances resulting in them.
#' @param Lyapunov_optim Main data frame giving Lyapunov coefficients for all
#' trait combinations developed for the ESS optima table. Holds elasticity
#' fitness values.
#' @param ESS_Lyapunov A data frame provided by reference that will hold the
#' ESS optima.
#' @param var_run_mat A matrix giving the the variants to be run in each
#' projection, with rows giving the projections and columns giving the
#' variants.
#' @param N_out The main list of final population sizes, supplied as a
#' reference and altered by this function.
#' @param comm_out The main list of full projection results for the community,
#' supplied as a pointer and altered by this function.
#' @param N_out_optim The main list of final population sizes from ESS
#' optimization, supplied as a reference and altered by this function.
#' @param comm_out_optim The main list of full projection results for the
#' community resulting from ESS optimization, supplied as a pointer and altered
#' by this function.
#' @param zero_stage_vec_list A list of vectors giving zero stage vectors for
#' each MPM, if entry times are staggered.
#' @param trait_axis A data frame of class \code{adaptAxis} holding the trait
#' data to test.
#' @param new_trait_axis A data frame giving trait axis data post-processing
#' with function \code{ta_reassess()}.
#' @param optim_trait_axis A data frame giving trait axis data processed for
#' ESS optimization.
#' @param optim_trait_axis_995 A data frame giving trait axis data processed
#' for ESS optimization for variants 99.5% the values of the core frame.
#' @param new_stageexpansion_list A list with stage expansions for all trait
#' axis data leading to matrix element changes with each list element
#' corresponding to each respective variant.
#' @param new_stageexpansion_list_optim A list with stage expansions for all
#' variant data used in ESS evaluation.
#' @param modified_dev_terms_list An optional list giving the vital rate
#' y-intercept deviations by variant once data from the \code{trait_axis} data
#' frame has been allocated.
#' @param errcheck_mpms An optional list of all MPMs post-processing. Only
#' output if \code{err_check = "extreme"}.
#' @param errcheck_mpms_optima An optional list of all MPMs used in the first
#' stage of ESS trait evaluation. Only output if \code{err_check = "extreme"}.
#' @param errcheck_mpm_ESS An optional list of all MPMs used in the second
#' stage of ESS trait evaluation. Only output if \code{err_check = "extreme"}.
#' @param errcheck_mpmouts An optional list of all mpm_out matrices from MPM
#' processing. Only output if \code{err_check = "extreme"}.
#' @param errcheck_mpmouts_optima An optional list of all mpm_out matrices from
#' the first stage of ESS trait evaluation. Only output if
#' \code{err_check = "extreme"}.
#' @param errcheck_mpmout_ESS An optional list of all mpm_out matrices from the
#' second stage of ESS trait evaluation. Only output if
#' \code{err_check = "extreme"}.
#' @param tweights_list The tweights vector or matrix covering the MPM.
#' @param start_list A list of starting information, supplied in \code{lefkoSV}
#' format.
#' @param vrm_list A list of \code{vrm_input} objects.
#' @param current_stageframe The main stageframe, including extra stages.
#' @param allmodels_all A list of extracted vrm inputs for all MPMs.
#' @param allstages_all The allstages indexing data frame used to produce MPMs.
#' @param current_supplement A supplement in \code{lefkoSD} format.
#' @param year_vec A vector giving the main years used.
#' @param ind_terms_num_list List of data frames giving values of numeric
#' individual covariates.
#' @param ind_terms_cat_list List of data frames giving values of factor
#' individual covariates.
#' @param dev_terms_list List of deviations for vital rate models.
#' @param density_vr_list Data frame of \code{lefkoDensVR} objects holding
#' density relationships for all 14 vital rate models.
#' @param sp_density_list A list of values of spatial density for all MPMs.
#' @param density_df A data frame of class \code{lefkoDens}.
#' @param dens_index_df A data frame giving indices for density dependent
#' transitions.
#' @param equivalence_list A list giving the effect of each individual in each
#' stage relative to a reference individual.
#' @param sp_density_num_vec A vector giving the number of spatial density
#' terms.
#' @param entry_time_vec An IntegerVector containing the entry time of each
#' mutant, population, or species, as given by each MPM.
#' @param inda_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate a.
#' @param indb_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate b.
#' @param indc_terms_num_vec A vector giving the number of numeric terms given
#' in individual covariate c.
#' @param inda_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate a.
#' @param indb_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate b.
#' @param indc_terms_cat_vec A vector giving the number of factor terms given
#' in individual covariate c.
#' @param dens_vr_yn_vec A vector stating whether density dependence is used,
#' given through \code{lefkoDensVR} objects.
#' @param tweights_type_vec A vector giving the style of \code{tweights} used
#' in each MPM.
#' @param fecmod_vec A numeric vector giving the fecmod values.
#' @param patch_vec A vector giving the name of each patch used in projection.
#' @param variant_count An integer giving the number of variants to run in
#' invasion analysis.
#' @param var_per_run The number of variants to run in each projection.
#' @param nreps An integer giving the number of replicates to perform.
#' @param times An integer giving the amount of time steps to run the
#' projection for.
#' @param fitness_times An integer giving how many time steps at the end of
#' each run to use to estimate fitness.
#' @param stagecounts Integer denoting the number of stages in the MPM.
#' @param substoch An integer giving the level of sustochasticity to enforce.
#' @param format_int An integer giving the MPM format.
#' @param firstage_int An integer giving the first age in a Leslie or
#' age-by-stage MPM.
#' @param finalage_int  An integer giving the final age in a Leslie or
#' age-by-stage MPM.
#' @param dev_terms_times_int A vector giving the number of occasions over
#' which vital rate y-intercept deviations cycle.
#' @param main_optim_res An integer giving the number of variants being tested.
#' @param opt_res If evaluating optima, then this integer gives the number
#' of variants to create between each minimum and maximum for each trait found
#' to be variable in the input trait axis.
#' @param exp_tol The maximum tolerated exponent.
#' @param theta_tol The maximum tolerated limit for theta, in non-linear
#' models such as those using the negative binomial.
#' @param loop_max An integer value denoting the number of search cycles
#' allowed per ESS during ESS optimization. Defaults to 150.
#' @param integeronly A Boolean value indicating whether to allow only whole
#' values of individuals or not.
#' @param stochastic A Boolean value indicating to perform a temporally
#' stochastic projection.
#' @param dens_yn_bool A Boolean value stating whether density dependence is
#' used, given through \code{lefkoDens} objects.
#' @param stages_not_equal A Boolean value indicating whether equivalence
#' info is supplied suggesting even stages within MPMs are not equal.
#' @param sparse_bool A Boolean value indiating whether the MPM is in sparse
#' matrix format.
#' @param historical A Boolean value indicating whether the MPM is historical.
#' @param pure_leslie A Boolean value indicating whether the MPM is Leslie.
#' @param A_only A Boolean value indicating whether to export U and F matrices
#' for alteration, or only A matrices.
#' @param err_check A logical value indicating whether to include an extra list
#' of output objects for error checking.
#' @param err_check_extreme A logical value indicating whether to include an
#' extra list of all matrices projected in the \code{err_check} object.
#' @param threshold The lower limit for the absolute value of fitness, below
#' which fitness is rounded to 0. Defaults to 0.00000001.
#' @param fitness_table A Boolean value dictating whether to include a data
#' frame giving Lyapunov coefficients for all combinations of variants tested.
#' Necessary for the creation of pairwise invasibility plots (PIPs). Defaults
#' to \code{TRUE}.
#' @param ESS_optima A logical value indicating whether to assess the values of
#' ESSoptima for traits that vary among variants in the given \code{adaptAxis}
#' table. Defaults to \code{TRUE}.
#' @param elast_mult A multiplier for traits to assess the elasticity of
#' fitness in trait optimization. Defaults to 0.995.
#' @param zap_min A Boolean value describing whether to round fitness values
#' below the value given in \code{threshold}.
#' @param benchmark_bool A Boolean value indicating whether to issue benchmark
#' statements on progress through the projection.
#' 
#' @return The first four arguments are directly manipulated without any
#' values returned.
#' 
#' @keywords internal
#' @noRd
NULL

#' Project Multiple MPMs With or Without Density Dependence
#' 
#' Function \code{project3} uses pre-existing or function-based MPMs to run
#' community projection simulations, in which different populations are run as
#' separate MPMs. Density dependence can be used with individual equivalence
#' vectors specifying Lotka-Volterra coefficients to adjust overall population
#' sizes to make them comparable.
#' 
#' @name project3
#' 
#' @param mpms An optional list of MPMs. Each MPM must be of class
#' \code{lefkoMat}.
#' @param vrms An optional list of \code{vrm_input} objects, each corresponding
#' to a distinct MPM that will be created during projection. Each
#' \code{vrm_input} object requires its own stageframe, entered in the same
#' order via argument \code{stageframes}.
#' @param stageframes An optional list of stageframes, corresponding in number
#' and order to the MPMs in argument \code{vrms}. Each stageframe must be of
#' class \code{stageframe}.
#' @param supplements An optional list of data frames of class \code{lefkoSD}
#' that provide supplemental data that should be incorporated into MPMs. If
#' used, then should have the same number of elements as the number of MPMs
#' provided in the list for argument \code{vrms}, with MPMs that do not need
#' supplemental data entered as \code{NULL} elements in this list. See
#' \code{\link[lefko3]{supplemental}()} for details of how these data frames
#' are used in function-based MPM construction.
#' @param equivalence An optional numeric vector, list of numeric vectors,
#' data frame of class \code{adaptEq} or class \code{lefkoEq}, or a list of such
#' data frames. If a numeric vector, then must have the same number of elements
#' as the number of MPMs, with each element giving the effect of an individual
#' of each MPM relative to a reference individual. If a list of vectors, then
#' the list should be composed of as many numeric vectors as MPMs, or as a two-
#' layered list of such vectors for each annual matrix per MPM, with each
#' vector giving the effect of each individual in each stage relative to a
#' reference individual. Data frames of class \code{adaptEq}, and lists of such
#' data frames, can be made with function \code{\link{equiv_input}()}. Numeric
#' entries used in these vectors can be thought of as Lotka-Volterra
#' competition terms, such as are used in multiple species competition models.
#' @param starts An optional list of \code{lefkoSV} objects, which are data
#' frames providing the starting numbers of individuals of each stage. If
#' provided, then one is needed per MPM. If not provided, then all projections
#' start with a single individual of each stage per MPM.
#' @param years An optional term corresponding either to a single integer vector
#' of time \code{t} values, if all MPMs will use the same time \code{t} or set
#' of time \code{t}'s, or a list of such vectors with each vector corresponding
#' to each MPM in order. In the latter case, a vector composed of a single
#' \code{NA} value is interpreted to mean that all time \code{t} values in the
#' MPM should be utilized. If a vector shorter than \code{times} is supplied,
#' then this vector will be cycled.
#' @param patches An optional string vector with length equal to the number of
#' MPMs, detailing the name of each patch to project for each MPM, in order.
#' Only a single pop-patch may be projected for each MPM given. A value of
#' \code{NA} can be supplied to indicate that the population-level matrices
#' should be projected (if argument \code{mpms} is used and a population-level
#' set of matrices exist), or that the first patch noted should be used.
#' Defaults to the population-level set or the first patch, depending on
#' whether the former exists.
#' @param tweights An optional list composed of numeric vectors or matrices
#' denoting the probabilities of choosing each matrix in each MPM in a
#' stochastic projection. If an element of the list is a matrix, then a
#' first-order Markovian environment is assumed, in which the probability of
#' choosing a specific annual matrix depends on which annual matrix is
#' currently chosen. If an element of the list is a vector, then the choice of
#' annual matrix is assumed to be independent of the current matrix. Defaults
#' to equal weighting among matrices. If used, then one element per MPM is
#' required, with equal weighting assumed for any element set to \code{NULL}.
#' @param format An optional integer vector indicating the kind of
#' function-based MPM to create for each \code{vrm_input} object entered in
#' argument \code{vrms}. Possible choices include: \code{1}, Ehrlen-format
#' historical MPM; \code{2}, deVries-format historical MPM; \code{3},
#' ahistorical MPM (default); \code{4}, age-by-stage MPM; and \code{5}, Leslie
#' (age-based) MPM.
#' @param entry_time An optional integer vector giving the entry time for each
#' MPM into the projection. Defaults to a zero vector with the length of the
#' number of MPMs, as given either by argument \code{mpms} or \code{vrms}.
#' @param sp_density An optional argument for use with \code{vrm_input} objects
#' that specifies the spatial density to be used in each time step. If used,
#' may either be a numeric vector giving a single spatial density for each
#' \code{vrm_input} object entered in argument \code{vrms} (in this case, the
#' value of spatial density given for each \code{vrm_input} object will be held
#' constant through the projection), or a list of as many numeric vectors as
#' \code{vrm_input} objects, with the length of each vector giving the spatial
#' density at each time step. If vectors are shorter than specified in 
#' \code{times}, then these values will be cycled.
#' @param ind_terms An optional argument providing values of individual or
#' environmental covariate values for \code{vrm_input} objects used in
#' function-based projection. Can be set either to a single data frame with 3
#' columns giving values for up to 3 covariates across time (rows give the time
#' order of these values), or a list of as many such data frames as
#' \code{vrm_input} objects. In the latter case, \code{vrm_input} objects that
#' do not use such covariates should have the associated element set to
#' \code{NULL}. Unused terms within each data frame must be set to \code{0}
#' (use of \code{NA} will produce errors.) If the number of rows is less than
#' \code{times}, then these values will be cycled.
#' @param dev_terms An optional list of data frames, one for each
#' \code{vrm_input} object. Each should include either 14 or 17 columns, and up
#' to \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. In addition, users may supply 3 more columns
#' designating additive deviations to: 15: individual covariate a,
#' 16: individual covariate b, and 17: individual covariate c. Unused terms
#' must be set to \code{0} (use of \code{NA} will produce errors). Single or
#' small numbers of values per vital rate model are also allowed, and if the
#' number of rows is less than \code{times}, then the terms will be cycled.
#' @param fb_sparse A logical vector indicating whether function-based MPMs
#' should be produced in sparse matrix format. Defaults to \code{FALSE} for
#' each MPM.
#' @param firstage An optional integer vector used for function-based Leslie
#' and age-by-stage MPMs giving the starting ages in such MPMs. Use only if at
#' least one MPM is both function-based and has age structure. Typically,
#' the starting age in such MPMs should be set to \code{0} if post-breeding and
#' \code{1} if pre-breeding. All other MPMs should be set to \code{0}. Do not
#' use if no MPM has age structure. Defaults to \code{1} in Leslie and
#' age-by-stage MPMs.
#' @param finalage An optional integer vector used for function-based Leslie
#' and age-by-stage MPMs giving the final ages in such MPMs. Use only if at
#' least one MPM is both function-based and has age structure. Do not use if no
#' MPM has age structure.
#' @param fecage_min An optional integer vector used for function-based Leslie
#' MPMs giving the first age at which organisms can be reproductive in such
#' MPMs. Use only if at least one MPM is a function-based Leslie MPM. Defaults
#' to the values given in \code{firstage}.
#' @param fecage_max An optional integer vector used for function-based Leslie
#' MPMs giving the final age at which organisms can be reproductive in such
#' MPMs. Use only if at least one MPM is a function-based Leslie MPM. Defaults
#' to the values given in \code{finalage}.
#' @param cont An optional vector used for function-based Leslie and
#' age-by-stage MPMs stating whether the MPM should should include a stasis
#' transition within the final age. This should be used only when an organism
#' can maintain the demographic characteristics of the final described age
#' after reaching that age. Can be entered as a logical vector or an integer
#' vector. MPMs without age structure should be entered as \code{0} or
#' \code{FALSE}. Do not use if no MPM has age structure.
#' @param fecmod An optional vector used for function-based MPMs giving scalar
#' multipliers for fecundity terms, when two fecundity variables are used for a
#' collective fecundity per individual. Each entry refers to each 
#' \code{vrm_input} object in argument \code{vrms}, in the same order.
#' @param density An optional list of data frames of class \code{lefkoDens},
#' which provide details for density dependence in MPM elements and have been
#' created with function \code{\link[lefko3]{density_input}()}, or a two-
#' layered list of such data frames, with a data frame per annual matrix per
#' MPM.
#' @param density_vr An optional list of data frames of class
#' \code{lefkoDensVR}, which provide details for density dependence in vital
#' rate models and have been created with function
#' \code{link[lefko3]{density_vr}()}. If used, then one such data frame per MPM
#' is required. MPMs to be run without vital describing density dependence
#' relationships in vital rates should be set to \code{NULL}. Can only be used
#' with function-based projections.
#' @param err_check A logical value indicating whether to include an extra list
#' of output objects for error checking. Can also be set to the text value
#' \code{"extreme"}, in which case all \code{err_check} output plus a multiple
#' level list with each MPM used in each time step will be output.
#' @param benchmark A logical value indicating whether to issue messages during
#' projection indicating progress. Defaults to \code{FALSE}.
#' @param stochastic A logical value indicating whether the projection will be
#' run as a temporally stochastic projection. Defaults to \code{FALSE}.
#' @param integeronly A logical value indicating whether to round the number of
#' individuals projected in each stage at each occasion in each MPM 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 nreps The number of replicate projections. Defaults to \code{1}.
#' @param times Number of occasions to iterate per replicate. Defaults to
#' \code{10000}.
#' @param prep_mats An integer value for use when creating function-based MPM
#' projections. If using \code{vrms} input instead of \code{mpms} input, then
#' this argument determines how many matrices should be used as a limit to
#' develop matrices prior to running the projection. See \code{Notes} for
#' further details.
#' @param force_fb A logical value indicating whether to force function-based
#' MPMs to be developed at each time step even if fewer than \code{prep_mats}.
#' 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}.
#' @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.
#' 
#' @return A list of class \code{adaptProj}, with the following elements:
#' \item{agg_density}{A numeric matrix giving the aggregate community density
#' by time (column) and replicate (row). Here, the aggregate density is
#' calculated using any stage weights supplied, and is exactly equal to the
#' aggegate density used in density dependence calculations by this function.}
#' \item{N_out}{A list with the number of elements equal to the number of
#' replicates. Each element within this list is a numeric matrix showing the number
#' of individuals of each species or genotype alive at each time. The number of
#' rows are equal to the number of MPMs used, and the columns correspond to the
#' time steps.}
#' \item{structure}{A two-level list with the top level list having number of
#' elements equal to the number of replicates, and the lower level
#' corresponding to the number of MPMs. Each element of the lower level list is
#' a numeric matrix showing the number of individuals in each stage at each
#' time. Rows and columns in the data frames correspond to stages and time
#' steps, respectively.}
#' \item{stageframe_list}{A list in which each element is the stageframe for
#' each MPM used.}
#' \item{hstages_list}{A list giving the used \code{hstages} data frames, which
#' identify the correct stage pairing for each row / column in each
#' historical MPM utilized.}
#' \item{agestages_list}{A list giving the used \code{agestages} data frames,
#' which identify the correct age-stage pairing for each row / column in each
#' age-by-stage MPM utilized.}
#' \item{labels}{A small data frame giving the the population and patch
#' identities for each MPM entered.}
#' \item{err_check}{An optional list composed of six additional lists, each
#' of which has the number of elements equal to the number of MPMs utilized.
#' List output include \code{allstages_all}, which gives the indices of
#' estimated transitions in MPMs constructed by function \code{project3()} from
#' input vital rate models; \code{allmodels_all}, which provides all vital rate
#' models as decomposed and interpreted by function \code{project3()};
#' \code{equivalence_list}, which gives the stage equivalence for density
#' calculations across MPMs; \code{density_list}, which gives the
#' \code{density} inputs utilized; \code{dens_index_list}, which provides
#' indices used to identify matrix elements for density dependence; and
#' \code{density_vr_list}, which gives the \code{density_vr} inputs utilized.}
#' 
#' @section Notes:
#' 
#' This function has been optimized in the function-based approach such that
#' if there are relatively few matrices required per MPM to run the projection
#' forward, then these matrices will be made prior to running the projection.
#' This approach saves time, but only if there are relatively few unique
#' matrices required for each MPM. If many or only unique MPMs are required at
#' each time step, then the matrices will be made on the fly during the
#' projection itself. Such a situation will most likely occur if each time
#' step requires a new matrix resulting from a unique individual covariate
#' value, or if the \code{density_vr} argument is used. The key argument
#' determining this behavior is \code{prep_mats}, which provides the maximum
#' limit for the number of matrices required per MPM in order to create
#' matrices prior to projection.
#' 
#' Please note that function-based Leslie MPMs cannot be forced through
#' Lefkovitch-style MPM processing via the \code{format} argument. Attempting
#' to do so will yield NA values within the projected matrices, which may then
#' propagate further NA values in other matrices via density dependence
#' functions. Always use \code{format = 5} for Leslie MPMs.
#' 
#' @examples
#' library(lefko3)
#' data(cypdata)
#' 
#' data(cypa_data)
#' 
#' 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)
#' 
#' cycaraw_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)
#'   
#' cyparaw_v1 <- verticalize3(data = cypa_data, noyears = 18, firstyear = 1994,
#'   individcol = "plant_id", blocksize = 2, sizeacol = "Inf.94",
#'   sizebcol = "Veg.94", repstracol = "Inf.94", fecacol = "Inf.94",
#'   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)
#' cyp_supp_list1 <- list(cypsupp2r, cypsupp2r)
#' 
#' cycamatrix2r <- rlefko2(data = cycaraw_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")
#' 
#' cypamatrix2r <- rlefko2(data = cyparaw_v1, stageframe = cypframe_raw, 
#'   year = "all", stages = c("stage3", "stage2", "stage1"),
#'   size = c("size3added", "size2added"), supplement = cypsupp2r,
#'   yearcol = "year2", patchcol = "patchid", indivcol = "individ")
#' 
#' cyp_mpm_list <- list(cycamatrix2r, cypamatrix2r)
#' 
#' cyca2_start <- start_input(cycamatrix2r, stage2 = c("SD", "P1", "P2"),
#'   value = c(500, 100, 200))
#' cypa2_start <- start_input(cypamatrix2r, stage2 = c("SD", "P1", "P2"),
#'   value = c(5000, 1000, 2000))
#' cyp_start_list <- list(cyca2_start, cypa2_start)
#' 
#' cyp2_dv <- density_input(cypamatrix2r, stage3 = c("SD", "P1"),
#'   stage2 = c("rep", "rep"), style = c(1, 1), alpha = c(0.5, 1.2),
#'   beta = c(1.0, 2.0), type = c(2, 1))
#' cyp_dv_list <- list(cyp2_dv, cyp2_dv)
#' 
#' cyp_comm_proj <- project3(mpms = cyp_mpm_list, starts = cyp_start_list,
#'   density = cyp_dv_list, times = 10)
#'   
#' summary(cyp_comm_proj)
#' 
#' @export project3
project3 <- function(mpms = NULL, vrms = NULL, stageframes = NULL, supplements = NULL, equivalence = NULL, starts = NULL, years = NULL, patches = NULL, tweights = NULL, format = NULL, entry_time = NULL, sp_density = NULL, ind_terms = NULL, dev_terms = NULL, fb_sparse = NULL, firstage = NULL, finalage = NULL, fecage_min = NULL, fecage_max = NULL, cont = NULL, fecmod = NULL, density = NULL, density_vr = NULL, err_check = NULL, benchmark = NULL, stochastic = FALSE, integeronly = FALSE, substoch = 0L, nreps = 1L, times = 10000L, prep_mats = 20L, force_fb = FALSE, exp_tol = 700.0, theta_tol = 100000000.0) {
    .Call('_adapt3_project3', PACKAGE = 'adapt3', mpms, vrms, stageframes, supplements, equivalence, starts, years, patches, tweights, format, entry_time, sp_density, ind_terms, dev_terms, fb_sparse, firstage, finalage, fecage_min, fecage_max, cont, fecmod, density, density_vr, err_check, benchmark, stochastic, integeronly, substoch, nreps, times, prep_mats, force_fb, exp_tol, theta_tol)
}

#' Project Multiple MPMs In Batches With Varying Starting Conditions
#' 
#' Function \code{batch_project3} runs function \code{project3()} across series
#' of differing beginning conditions. Currently used to run sensitivity
#' analyses.
#' 
#' @name batch_project3
#' 
#' @param used_mpms An integer vector detailing the MPMs entered in argument
#' \code{mpms} to run the batch projection on. Although all MPMs entered in
#' argument \code{mpms} will be projected, the alterations given in
#' \code{givenrate}, \code{offset}, or \code{multiplier} will only be performed
#' with those specified here. Defaults to \code{"all"}, which is equivalent to
#' an integer vector holding the sequence of 1 through the number of MPMs
#' entered.
#' @param givenrate A numeric vector giving values to replace targeted matrix
#' elements with. If used, then arguments \code{offset} and \code{multiplier}
#' cannot be used. Defaults to \code{NULL}.
#' @param offset A numeric vector giving the values to offset matrix elements
#' by. If used, then arguments \code{givenrate} and \code{multiplier} cannot be
#' used. Defaults to \code{c(0.005, 0.010, 0.015, 0.020, 0.025)}.
#' @param multiplier A numeric vector giving values to multiply targeted matrix
#' elements by. If used, then arguments \code{givenrate} and \code{offset}
#' cannot be used. Defaults to \code{NULL}.
#' @param all_elems A logical value indicating whether to use the alterations
#' specified in argument \code{givenrate}, \code{offset}, or \code{multiplier}
#' on all matrix elements. Defaults to \code{FALSE}.
#' @param mpms An optional list of MPMs. Each MPM must be of class
#' \code{lefkoMat}.
#' @param vrms An optional list of \code{vrm_input} objects, each corresponding
#' to a distinct MPM that will be created during projection. Each
#' \code{vrm_input} object requires its own stageframe, entered in the same
#' order via argument \code{stageframes}.
#' @param stageframes An optional list of stageframes, corresponding in number
#' and order to the MPMs in argument \code{vrms}. Each stageframe must be of
#' class \code{stageframe}.
#' @param supplements An optional list of data frames of class \code{lefkoSD}
#' that provide supplemental data that should be incorporated into MPMs. If
#' used, then should have the same number of elements as the number of MPMs
#' provided in the list for argument \code{vrms}, with MPMs that do not need
#' supplemental data entered as \code{NULL} elements in this list. See
#' \code{\link[lefko3]{supplemental}()} for details of how these data frames
#' are used in function-based MPM construction.
#' @param equivalence An optional numeric vector, list of numeric vectors,
#' data frame of class \code{adaptEq} or class \code{lefkoEq}, or a list of such
#' data frames. If a numeric vector, then must have the same number of elements
#' as the number of MPMs, with each element giving the effect of an individual
#' of each MPM relative to a reference individual. If a list of vectors, then
#' the list should be composed of as many numeric vectors as MPMs, or as a two-
#' layered list of such vectors for each annual matrix per MPM, with each
#' vector giving the effect of each individual in each stage relative to a
#' reference individual. Data frames of class \code{adaptEq}, and lists of such
#' data frames, can be made with function \code{\link{equiv_input}()}. Numeric
#' entries used in these vectors can be thought of as Lotka-Volterra
#' competition terms, such as are used in multiple species competition models.
#' @param starts An optional list of \code{lefkoSV} objects, which are data
#' frames providing the starting numbers of individuals of each stage. If
#' provided, then one is needed per MPM. If not provided, then all projections
#' start with a single individual of each stage per MPM.
#' @param years An optional term corresponding either to a single integer vector
#' of time \code{t} values, if all MPMs will use the same time \code{t} or set
#' of time \code{t}'s, or a list of such vectors with each vector corresponding
#' to each MPM in order. In the latter case, a vector composed of a single
#' \code{NA} value is interpreted to mean that all time \code{t} values in the
#' MPM should be utilized. If a vector shorter than \code{times} is supplied,
#' then this vector will be cycled.
#' @param patches An optional string vector with length equal to the number of
#' MPMs, detailing the name of each patch to project for each MPM, in order.
#' Only a single pop-patch may be projected for each MPM given. A value of
#' \code{NA} can be supplied to indicate that the population-level matrices
#' should be projected (if argument \code{mpms} is used and a population-level
#' set of matrices exist), or that the first patch noted should be used.
#' Defaults to the population-level set or the first patch, depending on
#' whether the former exists.
#' @param tweights An optional list composed of numeric vectors or matrices
#' denoting the probabilities of choosing each matrix in each MPM in a
#' stochastic projection. If an element of the list is a matrix, then a
#' first-order Markovian environment is assumed, in which the probability of
#' choosing a specific annual matrix depends on which annual matrix is
#' currently chosen. If an element of the list is a vector, then the choice of
#' annual matrix is assumed to be independent of the current matrix. Defaults
#' to equal weighting among matrices. If used, then one element per MPM is
#' required, with equal weighting assumed for any element set to \code{NULL}.
#' @param format An optional integer vector indicating the kind of
#' function-based MPM to create for each \code{vrm_input} object entered in
#' argument \code{vrms}. Possible choices include: \code{1}, Ehrlen-format
#' historical MPM; \code{2}, deVries-format historical MPM; \code{3},
#' ahistorical MPM (default); \code{4}, age-by-stage MPM; and \code{5}, Leslie
#' (age-based) MPM.
#' @param entry_time An optional integer vector giving the entry time for each
#' MPM into the projection. Defaults to a zero vector with the length of the
#' number of MPMs, as given either by argument \code{mpms} or \code{vrms}.
#' @param sp_density An optional argument for use with \code{vrm_input} objects
#' that specifies the spatial density to be used in each time step. If used,
#' may either be a numeric vector giving a single spatial density for each
#' \code{vrm_input} object entered in argument \code{vrms} (in this case, the
#' value of spatial density given for each \code{vrm_input} object will be held
#' constant through the projection), or a list of as many numeric vectors as
#' \code{vrm_input} objects, with the length of each vector giving the spatial
#' density at each time step. If vectors are shorter than specified in 
#' \code{times}, then these values will be cycled.
#' @param ind_terms An optional argument providing values of individual or
#' environmental covariate values for \code{vrm_input} objects used in
#' function-based projection. Can be set either to a single data frame with 3
#' columns giving values for up to 3 covariates across time (rows give the time
#' order of these values), or a list of as many such data frames as
#' \code{vrm_input} objects. In the latter case, \code{vrm_input} objects that
#' do not use such covariates should have the associated element set to
#' \code{NULL}. Unused terms within each data frame must be set to \code{0}
#' (use of \code{NA} will produce errors.) If the number of rows is less than
#' \code{times}, then these values will be cycled.
#' @param dev_terms An optional list of data frames, one for each
#' \code{vrm_input} object. Each should include either 14 or 17 columns, and up
#' to \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. In addition, users may supply 3 more columns
#' designating additive deviations to: 15: individual covariate a,
#' 16: individual covariate b, and 17: individual covariate c. Unused terms
#' must be set to \code{0} (use of \code{NA} will produce errors). Single or
#' small numbers of values per vital rate model are also allowed, and if the
#' number of rows is less than \code{times}, then the terms will be cycled.
#' @param fb_sparse A logical vector indicating whether function-based MPMs
#' should be produced in sparse matrix format. Defaults to \code{FALSE} for
#' each MPM.
#' @param firstage An optional integer vector used for function-based Leslie
#' and age-by-stage MPMs giving the starting ages in such MPMs. Use only if at
#' least one MPM is both function-based and has age structure. Typically,
#' the starting age in such MPMs should be set to \code{0} if post-breeding and
#' \code{1} if pre-breeding. All other MPMs should be set to \code{0}. Do not
#' use if no MPM has age structure. Defaults to \code{1} in Leslie and
#' age-by-stage MPMs.
#' @param finalage An optional integer vector used for function-based Leslie
#' and age-by-stage MPMs giving the final ages in such MPMs. Use only if at
#' least one MPM is both function-based and has age structure. Do not use if no
#' MPM has age structure.
#' @param fecage_min An optional integer vector used for function-based Leslie
#' MPMs giving the first age at which organisms can be reproductive in such
#' MPMs. Use only if at least one MPM is a function-based Leslie MPM. Defaults
#' to the values given in \code{firstage}.
#' @param fecage_max An optional integer vector used for function-based Leslie
#' MPMs giving the final age at which organisms can be reproductive in such
#' MPMs. Use only if at least one MPM is a function-based Leslie MPM. Defaults
#' to the values given in \code{finalage}.
#' @param cont An optional vector used for function-based Leslie and
#' age-by-stage MPMs stating whether the MPM should should include a stasis
#' transition within the final age. This should be used only when an organism
#' can maintain the demographic characteristics of the final described age
#' after reaching that age. Can be entered as a logical vector or an integer
#' vector. MPMs without age structure should be entered as \code{0} or
#' \code{FALSE}. Do not use if no MPM has age structure.
#' @param fecmod An optional vector used for function-based MPMs giving scalar
#' multipliers for fecundity terms, when two fecundity variables are used for a
#' collective fecundity per individual. Each entry refers to each 
#' \code{vrm_input} object in argument \code{vrms}, in the same order.
#' @param density An optional list of data frames of class \code{lefkoDens},
#' which provide details for density dependence in MPM elements and have been
#' created with function \code{\link[lefko3]{density_input}()}, or a two-
#' layered list of such data frames, with a data frame per annual matrix per
#' MPM.
#' @param density_vr An optional list of data frames of class
#' \code{lefkoDensVR}, which provide details for density dependence in vital
#' rate models and have been created with function
#' \code{link[lefko3]{density_vr}()}. If used, then one such data frame per MPM
#' is required. MPMs to be run without vital describing density dependence
#' relationships in vital rates should be set to \code{NULL}. Can only be used
#' with function-based projections.
#' @param err_check A logical value indicating whether to include an extra list
#' of output objects for error checking with each projection. Can also be set
#' to the text value \code{"extreme"}, in which case all \code{err_check}
#' output plus a multiple level list with each MPM used in each time step will
#' be output.
#' @param benchmark A logical value indicating whether to issue messages during
#' projection indicating progress. Defaults to \code{FALSE}.
#' @param stochastic A logical value indicating whether the projection will be
#' run as a temporally stochastic projection. Defaults to \code{FALSE}.
#' @param integeronly A logical value indicating whether to round the number of
#' individuals projected in each stage at each occasion in each MPM 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 nreps The number of replicate projections. Defaults to \code{1}.
#' @param times Number of occasions to iterate per replicate. Defaults to
#' \code{10000}.
#' @param prep_mats An integer value for use when creating function-based MPM
#' projections. If using \code{vrms} input instead of \code{mpms} input, then
#' this argument determines how many matrices should be used as a limit to
#' develop matrices prior to running the projection. See \code{Notes} for
#' further details.
#' @param force_fb A logical value indicating whether to force function-based
#' MPMs to be developed at each time step even if fewer than \code{prep_mats}.
#' 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}.
#' @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.
#' 
#' @return A list of class \code{adaptProjBatch}, which is composed of three
#' elements:
#' \item{proj_out}{A multi-layered list, with the top number of elements equal
#' to the number of \code{used_mpms}. Each element is a list, with the number
#' of elements equal to the number of alterations tried. Each of these elements
#' is, in turn, an \code{adaptProj} object.}
#' \item{ref}{A list with the same structure as \code{proj_out}. This list is
#' composed of supplements (\code{lefkoSD} objects) giving the exact
#' alterations performed in the associated MCM.}
#' \item{control}{An integer vector giving the identities of the MPM altered
#' in each top list.}
#' 
#' @section Notes:
#' 
#' This function is currently used to run sensitivity analyses, in which the
#' slope of the final population size is regressed against the the starting
#' offset values for each element. Each regression is run on the offset values
#' within each element.
#' 
#' The only arguments unique to this function are arguments \code{used_mpms},
#' \code{givenrate}, \code{offset}, \code{multiplier}, and \code{all_elems}.
#' All others are passed to function \code{project3}.
#' 
#' Setting \code{all_elems = TRUE} will lead to very time-intensive analysis.
#' We encourage users to break down their analyses into smaller batches, in 
#' order to make them more tractable.
#' 
#' @examples
#' \donttest{
#' library(lefko3)
#' 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)
#' 
#' sizevector <- c(0, 0, 3.0, 15)
#' stagevector <- c("P1", "D", "Sm", "Lg")
#' repvector <- c(0, 0, 1, 1)
#' obsvector <- c(0, 0, 1, 1)
#' matvector <- c(0, 1, 1, 1)
#' immvector <- c(1, 0, 0, 0)
#' indataset <- c(0, 1, 1, 1)
#' binvec <- c(0, 0.5, 2.5, 9.5)
#' 
#' cypframe_small_raw <- sf_create(sizes = sizevector, stagenames = stagevector,
#'   repstatus = repvector, obsstatus = obsvector, matstatus = matvector,
#'   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)
#' 
#' cypraw_v2 <- 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_small_raw, stagesize = "sizeadded", NAas0 = TRUE,
#'   NRasRep = TRUE)
#' 
#' cypraw_v3 <- 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",
#'   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, 1500, 500),
#'   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")
#' cypmean <- lmean(cypmatrix2r)
#' 
#' cypsupp2r_small <- supplemental(stage3 = c("D", "Sm", "Lg", "P1"),
#'   stage2 = c("P1", "P1", "P1", "rep"), eststage3 = c(NA, "Sm", "Lg", NA),
#'   eststage2 = c(NA, "D", "D", NA), givenrate = c(0.05, NA, NA, NA),
#'   offset = c(NA, NA, -0.1, NA), multiplier = c(NA, NA, NA, 0.5),
#'   type =c(1, 1, 1, 3), stageframe = cypframe_small_raw, historical = FALSE)
#' cypmatrix2r_small <- rlefko2(data = cypraw_v2, stageframe = cypframe_small_raw, 
#'   year = "all", patch = "all", stages = c("stage3", "stage2", "stage1"),
#'   size = c("size3added", "size2added"), supplement = cypsupp2r_small,
#'   yearcol = "year2", patchcol = "patchid", indivcol = "individ")
#' cypmean_small <- lmean(cypmatrix2r_small)
#' 
#' cypmatrixL_small <- rleslie(data = cypraw_v3, start_age = 1, last_age = 4,
#'   continue = TRUE, fecage_min = 3, year = "all", pop = NA, patch = "all",
#'   yearcol = "year2", patchcol = "patchid", indivcol = "individ")
#' 
#' cyp_mpms1 <- list(cypmatrix2r, cypmatrix2r_small, cypmatrixL_small)
#' 
#' c2d_4 <- density_input(cypmean, stage3 = c("P1", "P1"), stage2= c("SD", "rep"),
#'   style = 1, time_delay = 1, alpha = 1, beta = 0.0005, type = c(2, 2))
#' c2d_4a <- density_input(cypmean_small, stage3 = c("P1", "P1"), stage2= c("P1", "rep"),
#'   style = 1, time_delay = 1, alpha = 1, beta = 0.0005, type = c(2, 2))
#' cypL_dv <- density_input(cypmatrixL_small, stage3 = c("Age1"), stage2 = c("rep"),
#'   style = c(1), alpha = c(0.5), beta = c(1.0), type = c(2))
#' cyp_density <- list(c2d_4, c2d_4a, cypL_dv)
#' 
#' cyp_start1 <- start_input(cypmatrix2r, stage2 = c("SD", "P1", "D"),
#'   value = c(100, 200, 4))
#' cyp_start2 <- start_input(cypmatrix2r_small, stage2 = c("P1", "D"),
#'   value = c(10, 2000))
#' cypL_start_1 <- start_input(cypmatrixL_small, stage2 = c("Age1"),
#'   value = c(200))
#' cyp_start <- list(cyp_start1, cyp_start2, cypL_start_1)
#' 
#' new_supplement_cyp2_small <- sup_skeleton(2)
#' new_supplement_cyp2_small$stage3 <- c("D", "Sm")
#' new_supplement_cyp2_small$stage2 <- c("Lg", "Lg")
#' new_supplement_cyp2_small$convtype <- c(1, 1)
#' used_supplements <- list(new_supplement_cyp2_small,
#'   new_supplement_cyp2_small, NULL)
#' 
#' aaa1_prj_batch2 <- batch_project3(used_mpms = "all", all_elems = FALSE,
#'   mpms =  cyp_mpms1, entry_time = c(0, 5, 8), times = 15, nreps = 3,
#'   supplement = used_supplements, integeronly = TRUE, density = cyp_density)
#' }
#' 
#' @export batch_project3
batch_project3 <- function(used_mpms = NULL, givenrate = NULL, offset = NULL, multiplier = NULL, all_elems = NULL, mpms = NULL, vrms = NULL, stageframes = NULL, supplements = NULL, equivalence = NULL, starts = NULL, years = NULL, patches = NULL, tweights = NULL, format = NULL, entry_time = NULL, sp_density = NULL, ind_terms = NULL, dev_terms = NULL, fb_sparse = NULL, firstage = NULL, finalage = NULL, fecage_min = NULL, fecage_max = NULL, cont = NULL, fecmod = NULL, density = NULL, density_vr = NULL, err_check = NULL, benchmark = NULL, stochastic = FALSE, integeronly = FALSE, substoch = 0L, nreps = 1L, times = 10000L, prep_mats = 20L, force_fb = FALSE, exp_tol = 700.0, theta_tol = 100000000.0) {
    .Call('_adapt3_batch_project3', PACKAGE = 'adapt3', used_mpms, givenrate, offset, multiplier, all_elems, mpms, vrms, stageframes, supplements, equivalence, starts, years, patches, tweights, format, entry_time, sp_density, ind_terms, dev_terms, fb_sparse, firstage, finalage, fecage_min, fecage_max, cont, fecmod, density, density_vr, err_check, benchmark, stochastic, integeronly, substoch, nreps, times, prep_mats, force_fb, exp_tol, theta_tol)
}

#' Run Pairwise and Multiple Invasibility Analysis
#' 
#' Function \code{invade3} runs pairwise and multiple invasisibility analyses,
#' and provides output to analyze all aspects of the dynamics of generic
#' variants. The output includes invasion fitness for all variants included, as
#' well as resident fitness in all simulations run. Forms the core data plotted
#' by the \code{\link{plot.adaptInv}()} function to plot pairwise
#' invasibility plots (PIPs) and elasticity plots. Also estimates trait optima,
#' if any occur.
#' 
#' @name invade3
#' 
#' @param axis The \code{adaptAxis} object detailing all variant
#' characteristics. Essentially, a data frame giving the values of all changes
#' to vital rates and transition elements to test, where each value is change
#' is given by row.
#' @param mpm An MPM of class \code{lefkoMat}, for use if using existing MPMs.
#' @param vrm A \code{vrm_input} object corresponding to a distinct MPM that
#' will be created during analysis. Requires a stageframe, entered in argument
#' \code{stageframe}.
#' @param stageframe A stageframe defining stages and the life cycle for the
#' entered object in argument \code{vrms}. Must be of class \code{stageframe}.
#' @param supplement An optional data frame of class \code{lefkoSD} providing
#' supplemental data that should be incorporated into function-based MPMs. See
#' \code{\link[lefko3]{supplemental}()} for details. Use only with argument
#' \code{vrm}.
#' @param equivalence An optional object of class \code{adaptEq} giving the
#' degree to which individuals in each stage are equivalent to one another.
#' May also be a numeric vector, in which case the vector must have the same
#' number of elements as the number of rows in the associated MPM, with each
#' element giving the effect of an individual of that age, stage, age-stage, or
#' stage-pair, depending on whether the MPM is age-based, ahistorical
#' stage-based, age-by-stage, or historical stage-based, respectively. Numeric
#' entries used in these vectors can be thought of as Lotka-Volterra
#' competition terms, such as are used in multiple species competition models.
#' @param starts An optional \code{lefkoSV} object, which is a data frame
#' providing the starting numbers of individuals of each stage. If not
#' provided, then all projections start with a single individual per stage.
#' @param years An optional term corresponding to a single integer vector of
#' time \code{t} values. If a vector shorter than \code{times} is supplied,
#' then this vector will be cycled. Defaults to a vector of all detected
#' years in argument \code{mpm} or argument \code{vrm}.
#' @param patches An optional single string giving a single pop-patch to be
#' used during invasion analysis. Defaults to the population-level set or the
#' first patch, depending on whether the former exists.
#' @param tweights An optional numeric vector or matrix denoting the
#' probabilities of choosing each matrix in each MPM in a stochastic
#' projection. If a matrix, then a first-order Markovian environment is
#' assumed, in which the probability of choosing a specific annual matrix
#' depends on which annual matrix is currently chosen. If an element of the
#' list is a vector, then the choice of annual matrix is assumed to be
#' independent of the current matrix. Defaults to equal weighting among
#' matrices.
#' @param format An optional integer indicating the kind of function-based MPM
#' to create, if argument \code{vrm} is provided. Possible choices include:
#' \code{1}, Ehrlen-format historical MPM; \code{2}, deVries-format historical
#' MPM; \code{3}, ahistorical MPM (default); \code{4}, age-by-stage MPM; and
#' \code{5}, Leslie (age-based) MPM. Defaults to \code{3}.
#' @param entry_time An optional integer vector giving the entry time for each
#' variant into each simulation. Defaults to a zero vector with length equal to
#' the number of variants to run concurrently in each simulation, as given by
#' argument \code{var_per_run}. Note that if two variants are to be run at a
#' time, as in a pairwise invasion analysis, then the length of the vector
#' should be equal to 2.
#' @param sp_density An optional argument for use with argument \code{vrm} that
#' specifies the spatial density to be used in each time step. If used, then
#' may either be a numeric vector giving a single spatial density for each
#' time step. If vectors are shorter than specified in \code{times}, then these
#' values will be cycled.
#' @param ind_terms An optional argument providing values of individual or
#' environmental covariate values for argument \code{vrm}. Should be set to a
#' single data frame with 3 columns giving values for up to 3 covariates across
#' time (rows give the time order of these values). Unused terms within the
#' data frame must be set to \code{0} (use of \code{NA} will produce errors).
#' If the number of rows is less than \code{times}, then these values will be
#' cycled.
#' @param dev_terms An optional data frame including 14 or 17 columns and up to
#' \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. Optionally, the user may add three columns designating
#' additive deviations to: 15: individual covariate a, 16: individual covariate
#' b, and 17: individual covariate c. Unused terms must be set to \code{0} (use
#' of \code{NA} will produce errors). Single or small numbers of values per
#' vital rate model are also allowed, and if the number of rows is less than
#' \code{times}, then the terms will be cycled.
#' @param fb_sparse A logical value indicating whether function-based MPMs
#' should be produced in sparse matrix format. Defaults to \code{FALSE}.
#' @param firstage An optional integer vector used for function-based Leslie
#' and age-by-stage MPMs giving the starting ages in such MPMs. Use only if at
#' least one MPM is both function-based and has age structure. Typically,
#' the starting age in such MPMs should be set to \code{0} if post-breeding and
#' \code{1} if pre-breeding. All other MPMs should be set to \code{0}. Do not
#' use if no MPM has age structure. Defaults to \code{1} in Leslie and
#' age-by-stage MPMs.
#' @param finalage An optional integer used for function-based Leslie and
#' age-by-stage MPMs giving the final age in such MPMs. Use only if the MPM is
#' both function-based and has age structure.
#' @param fecage_min An optional integer used for function-based Leslie MPMs
#' giving the first age at which organisms can reproduce. Use only if the MPM
#' is both function-based and has age structure. Defaults to the value given in
#' \code{firstage}.
#' @param fecage_max An optional integer used for function-based Leslie MPMs
#' giving the final age at which organisms can reproduce. Use only if the MPM
#' is both function-based and has age structure. Defaults to the value given in
#' \code{finalage}.
#' @param cont An optional logical value for function-based Leslie and
#' age-by-stage MPMs stating whether the MPM should should include a stasis
#' transition within the final age. This should be used only when an organism
#' can maintain the demographic characteristics of the final described age
#' after reaching that age.
#' @param prebreeding An optional logical value indicating whether the life
#' cycle is prebreeding (\code{TRUE}) or postbreeding (\code{FALSE}). Defaults 
#' to \code{TRUE}.
#' @param fecmod An optional numeric value for function-based MPMs giving
#' scalar multipliers for fecundity terms, when two fecundity variables are
#' used for a collective fecundity per individual.
#' @param density An optional data frames of class \code{lefkoDens}, which
#' provides details for density dependence in MPM elements and is created with
#' function \code{\link[lefko3]{density_input}()}. Defaults to \code{NULL}, in
#' which case no density dependence is built into matrix elements.
#' @param density_vr An optional data frame of class \code{lefkoDensVR}, which
#' provides details for density dependence in vital rate models and has been
#' created with function \code{link[lefko3]{density_vr}()}. Can only be used
#' with function-based projections. Defaults to \code{NULL}, in which case no
#' density dependence is built into vital rates.
#' @param stochastic A logical value indicating whether the projection will be
#' run as a temporally stochastic projection. Defaults to \code{FALSE}.
#' @param A_only A logical value indicating whether to alter survival and
#' fecundity matrix elements separately prior to creating the overall \code{A}
#' matrix, or whether to alter elements directly on \code{A} matrices. Defaults
#' to \code{TRUE}, and should be kept to that setting unless some matrix
#' elements to be altered are sums of survival and fecundity transitions.
#' @param integeronly A logical value indicating whether to round the number of
#' individuals projected in each stage at each occasion down to the next lower
#' integer. Defaults to \code{FALSE}.
#' @param fitness_table A logical value dictating whether to include a data
#' frame giving Lyapunov coefficients for all combinations of variants tested.
#' Necessary for the creation of pairwise invasibility plots (PIPs). Defaults
#' to \code{TRUE}.
#' @param trait_optima A logical value indicating whether to assess the optimal
#' values of traits, generally as kinds of evolutionary stage equilibrium (ESS)
#' points. Trait optimization is conducted via elasticity analysis of traits
#' that are variable within the \code{trait_axis} table. Defaults to
#' \code{FALSE}.
#' @param zap_min A logical value indicating whether to treat traits and
#' fitness as 0 when their absolute values are less than the value given in
#' argument \code{threshold}.
#' @param converged_only A logical value indicating whether to show predicted
#' trait optima only in cases where the elasticity analysis has converged.
#' Defaults to \code{FALSE}.
#' @param err_check A logical value indicating whether to include an extra list
#' of output objects for error checking. Can also be set to the text value
#' \code{"extreme"}, in which case all \code{err_check} output plus a multiple
#' level list with each MPM used in each time step will be output.
#' @param benchmark A logical value indicating whether to issue messages during
#' projection indicating progress. Defaults to \code{FALSE}.
#' @param var_per_run The number of variants to run in each simulation.
#' Defaults to \code{2}, resulting in pairwise invasibility analysis. See
#' \code{Notes} for details.
#' @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}, while setting \code{0} does not alter fecundity.
#' @param elast_mult A multiplier for traits to assess the elasticity of
#' fitness in trait optimization. Defaults to \code{0.995}.
#' @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 fitness_times An integer giving the number of time steps at the end
#' of each run to use to estimate the fitness of the respective genotype.
#' Defaults to \code{100}, but if \code{times < 100}, then is set equal to
#' \code{times}.
#' @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 threshold The lower limit for the absolute value of fitness, below
#' which fitness is rounded to 0. Defaults to 0.00000001.
#' @param loop_max An integer value denoting the number of search cycles
#' allowed per ESS during ESS optimization. Defaults to 150.
#' 
#' @return A list of class \code{adaptInv}, with the following elements:
#' \item{fitness}{A data frame giving the resident and invasion fitness
#' estimated for each variant, per replicate. In typical cases, the user will
#' be interested in the invasion fitness, which corresponds to the Lyapunov
#' coefficient of the invader in invasibility analysis.}
#' \item{variants_out}{A two-level list with the top level list having number of
#' elements equal to the number of variants, and the lower level corresponding
#' to the number of replicates. Each element of the lower level list is a
#' matrix showing the number of individuals in each stage (row) at each time
#' (column).}
#' \item{N_out}{A list with the number of elements equal to the number of
#' replicates. Each element within this list is data frame showing the number
#' of individuals of each species or genotype alive at each time. The number of
#' rows are equal to the number of MPMs used, and the columns correspond to the
#' time steps.}
#' \item{trait_axis}{An edited version of the input trait axis.}
#' \item{stageframe_list}{A list in which each element is the stageframe for
#' each MPM used.}
#' \item{hstages_list}{A list giving the used \code{hstages} data frames, which
#' identify the correct stage pairing for each row / column in each historical
#' MPM utilized.}
#' \item{agestages_list}{A list giving the used \code{agestages} data frames,
#' which identify the correct age-stage pairing for each row / column in each
#' age-by-stage MPM utilized.}
#' \item{labels}{A small data frame giving the the population and patch
#' identities for each MPM entered.}
#' \item{err_check}{An optional list composed of an additional six lists, each
#' of which has the number of elements equal to the number of MPMs utilized.
#' List output include \code{allstages_all}, which gives the indices of
#' estimated transitions in MPMs constructed by function \code{invade3()} from
#' input vital rate models; \code{allmodels_all}, which provides all vital rate
#' models as decomposed and interpreted by function \code{invade3()};
#' \code{equivalence_list}, which gives the stage equivalence for density
#' calculations across MPMs; \code{density_list}, which gives the
#' \code{density} inputs utilized; \code{dens_index_list}, which provides
#' indices used to identify matrix elements for density dependence; and
#' \code{density_vr_list}, which gives the \code{density_vr} inputs utilized.}
#' 
#' @section Notes:
#' The argument \code{var_per_run} establishes the style of simulation to run.
#' Entering \code{var_per_run = 1} runs each variant singly. Entering
#' \code{var_per_run = 2} runs pairwise invasibility analysis, trying each pair
#' permutation of variants. Greater values will lead to multiple invasibility
#' analysis with different permutations of groups. For example,
#' \code{var_per_run = 3} runs each permutation of groups of three. The integer
#' set must be positive, and must not be larger than the number of variants.
#' 
#' When \code{optima = TRUE}, ESS values for traits that vary in the input
#' \code{adaptAxis} data frame are evaluated. The methodology is that
#' originally developed in Benton and Grant (1999, Evolution 53:677-688), as
#' communicated in Roff (2010, Modeling evolution: an introduction to numerical
#' methods, Oxford University Press). In essence, function \code{invade3}
#' determines which traits vary among all traits noted in the input trait axis.
#' A new trait axis is then created with values of variable traits multiplied
#' by \code{0.995}, although this can be reset with argument \code{elast_mult}.
#' This new trait axis is composed entirely of invaders that will be paired
#' against each respective row in the original trait axis. These two trait axis
#' frames are then used to conduct pairwise invasibility elasticity analyses,
#' particularly noting where fitness values and trends invert. Elasticity plots
#' show the results of these elasticity simulations, using R's line segment
#' default in the \code{plot.default()} function. Results are then used to
#' determine golden sections for further evaluation, within which the bounded
#' Nelder-Mead algorithm is used to determine the optimum value. Note that this
#' optimization approach typically works properly with only one variable trait.
#' Also note that if a trait spans both negative and positive values, then
#' elasticity calculation is altered such that invader values for negative
#' values are calculated as the sum of the old trait value and the difference
#' between that value and the value when multiplied by the elasticity value.
#' This is done to ensure that all elasticity values are consistently lower
#' than the original values.
#' 
#' @examples
#' \donttest{
#' library(lefko3)
#' data(cypdata)
#' 
#' sizevector <- c(0, 0, 0, 0, 1, 2.5, 4.5, 8, 17.5)
#' stagevector <- c("SD", "P1", "SL", "D", "XSm", "Sm", "Md", "Lg", "XLg")
#' repvector <- c(0, 0, 0, 0, 1, 1, 1, 1, 1)
#' obsvector <- c(0, 0, 0, 0, 1, 1, 1, 1, 1)
#' matvector <- c(0, 0, 0, 1, 1, 1, 1, 1, 1)
#' immvector <- c(0, 1, 1, 0, 0, 0, 0, 0, 0)
#' propvector <- c(1, 0, 0, 0, 0, 0, 0, 0, 0)
#' indataset <- c(0, 0, 0, 1, 1, 1, 1, 1, 1)
#' binvec <- c(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", "SL", "D", 
#'     "XSm", "Sm", "SD", "P1"),
#'   stage2 = c("SD", "SD", "P1", "SL", "SL", "SL", "rep",
#'     "rep"),
#'   eststage3 = c(NA, NA, NA, "D", "XSm", "Sm", NA, NA),
#'   eststage2 = c(NA, NA, NA, "XSm", "XSm", "XSm", NA, NA),
#'   givenrate = c(0.10, 0.40, 0.25, NA, NA, NA, NA, NA),
#'   multiplier = c(NA, NA, NA, NA, NA, NA, 1000, 1000),
#'   type =c(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")
#' cypmean <- lmean(cypmatrix2r)
#' 
#' cyp_start <- start_input(cypmean, stage2 = c("SD", "P1", "D"),
#'   value = c(1000, 200, 4))
#' 
#' c2d_4 <- density_input(cypmean, stage3 = c("P1", "P1"), stage2= c("SD", "rep"),
#'   style = 2, time_delay = 1, alpha = 0.005, beta = 0.000005, type = c(2, 2))
#' 
#' # A simple projection allows us to find a combination of density dependence
#' # and running time that produces a stable quasi-equilibrium
#' cyp_proj <- projection3(cypmean, times = 250, start_frame = cyp_start,
#'   density = c2d_4, integeronly = TRUE)
#' plot(cyp_proj)
#' 
#' cyp_ta <- trait_axis(stageframe = cypframe_raw,
#'   stage3 = rep("P1", 15),
#'   stage2 = rep("rep", 15),
#'   multiplier = seq(from = 0.1, to = 10.0, length.out = 15),
#'   type = rep(2, 15))
#' 
#' cyp_inv <- invade3(axis = cyp_ta, mpm = cypmean, density = c2d_4, times = 350,
#'   starts = cyp_start, entry_time = c(0, 250), fitness_times = 30,
#'   var_per_run = 2)
#' plot(cyp_inv)
#' }
#' 
#' @export invade3
invade3 <- function(axis = NULL, mpm = NULL, vrm = NULL, stageframe = NULL, supplement = NULL, equivalence = NULL, starts = NULL, years = NULL, patches = NULL, tweights = NULL, format = NULL, entry_time = NULL, sp_density = NULL, ind_terms = NULL, dev_terms = NULL, fb_sparse = NULL, firstage = NULL, finalage = NULL, fecage_min = NULL, fecage_max = NULL, cont = NULL, prebreeding = NULL, fecmod = NULL, density = NULL, density_vr = NULL, stochastic = NULL, A_only = NULL, integeronly = NULL, fitness_table = NULL, trait_optima = NULL, zap_min = NULL, converged_only = NULL, err_check = NULL, benchmark = NULL, var_per_run = 2L, substoch = 0L, elast_mult = 0.995, nreps = 1L, times = 10000L, fitness_times = 100L, exp_tol = 700.0, theta_tol = 100000000.0, threshold = 0.00000001, loop_max = 150L) {
    .Call('_adapt3_invade3', PACKAGE = 'adapt3', axis, mpm, vrm, stageframe, supplement, equivalence, starts, years, patches, tweights, format, entry_time, sp_density, ind_terms, dev_terms, fb_sparse, firstage, finalage, fecage_min, fecage_max, cont, prebreeding, fecmod, density, density_vr, stochastic, A_only, integeronly, fitness_table, trait_optima, zap_min, converged_only, err_check, benchmark, var_per_run, substoch, elast_mult, nreps, times, fitness_times, exp_tol, theta_tol, threshold, loop_max)
}

#' Create Skeleton Data Frame for Trait Variation for Invasion Analysis
#' 
#' Function \code{ta_skeleton()} creates a core data frame that can be modified
#' by users to provide the core variation in transition elements and vital
#' rates to use in invasion analysis. The resulting data frame should be used
#' as input in the \code{axis} argument in function \code{\link{invade3}()}.
#' 
#' @name ta_skeleton
#' 
#' @param rows The number of rows needed in the data frame. Defaults to 10.
#' 
#' @return A data frame of class \code{adaptAxis}, with the following columns:
#' \item{variant}{Denotes each variant in order, with each row corresponding to
#' a novel variant.}
#' \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{age3}{Age 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{estage3}{Age at occasion \emph{t}+1 in the transition to replace the
#' transition designated by \code{age2}.}
#' \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{offset}{A constant value to be added to the transition or proxy
#' 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).}
#' \item{surv_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for survival probability.}
#' \item{obs_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for observation probability.}
#' \item{size_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for primary size transition.}
#' \item{sizeb_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for secondary size transition.}
#' \item{sizec_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for tertiary size transition.}
#' \item{repst_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for reproduction probability.}
#' \item{fec_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for fecundity.}
#' \item{jsurv_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for juvenile survival probability.}
#' \item{jobs_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for juvenile observation probability.}
#' \item{jsize_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for juvenile primary size transition.}
#' \item{jsizeb_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for juvenile secondary size transition.}
#' \item{jsizec_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for juvenile tertiary size transition.}
#' \item{jrepst_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for juvenile reproduction probability.}
#' \item{jmatst_dev}{A numeric vector giving the deviations to the y-intercept of
#' the vital rate model for maturity status.}
#' \item{indcova}{Numeric values of individual covariate a used in creating new
#' variants.}
#' \item{indcovb}{Numeric values of individual covariate b used in creating new
#' variants.}
#' \item{indcovc}{Numeric values of individual covariate c used in creating new
#' variants.}
#' 
#' @examples
#' 
#' current_traits <- ta_skeleton(4)
#' current_traits$stage3 <- c("Dorm", "Dorm", "Sdl1", NA)
#' current_traits$stage2 <- c("cut", "V0r", "rep", NA)
#' current_traits$convtype <- c(1, 1, 2, NA)
#' current_traits$offset <- c(0.1, 0.2, 0.3, NA)
#' current_traits$surv_dev <- c(NA, NA, NA, 0.1)
#' 
#' @export ta_skeleton
ta_skeleton <- function(rows = 10L) {
    .Call('_adapt3_ta_skeleton', PACKAGE = 'adapt3', rows)
}

#' Create a Data Frame of Trait Data for Invasion Analysis
#' 
#' Function \code{trait_axis()} provides all necessary data for invasion
#' analysis. It lists the specific variations to MPMs for each variant run.
#' Variants can be given via overwritten matrix elements, proxy matrix
#' elements, additive offsets on matrix elements, matrix element multipliers,
#' additive offsets to y-intercepts in vital rate models, or specific values
#' of individual covariates to vary by matrix.
#' 
#' @name trait_axis
#' 
#' @param historical A single logical value indicating whether the MPMs
#' intended will be historical or ahistorical. Defaults to \code{TRUE}.
#' @param stagebased A single logical value indicating whether the MPM will be
#' stage-based or age-by-stage. Defaults to \code{TRUE}.
#' @param agebased A single 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 String vector of stage names in occasion \emph{t}+1 in the
#' transition to be affected. Abbreviations for groups of stages are also
#' usable (see \code{Notes}). Required in all stage-based and age-by-stage
#' MPMs.
#' @param stage2 String vector of stage names in occasion \emph{t} in the
#' transition to be affected. Abbreviations for groups of stages are also
#' usable (see \code{Notes}). Required in all stage-based and age-by-stage
#' MPMs.
#' @param stage1 String vector of stage names in occasion \emph{t}-1 in the
#' transition to be affected. 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 age3 An integer vector of the ages in occasion \emph{t}+1 to use in
#' transitions to be affected. Required for all age- and age-by-stage MPMs.
#' @param age2 An integer vector of the ages in occasion \emph{t} to use in
#' transitions to be affected. Required for all age- and age-by-stage MPMs.
#' @param eststage3 String vector of stage names 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 String vector of stage names 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 String vector of stage names 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 estage3 Integer vector of age at time \emph{t}+1 to replace
#' \code{age3} 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 estage2 Integer vector of 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 numeric vector of fixed rates or probabilities to replace
#' for the transition described by \code{stage3}, \code{stage2}, \code{stage1},
#' and/or \code{age2}.
#' @param offset A numeric vector of fixed numeric values to add to the
#' transitions described by \code{stage3}, \code{stage2}, \code{stage1}, and/or
#' \code{age2}.
#' @param multiplier A numeric vector of multipliers for the transition
#' described by \code{stage3}, \code{stage2}, \code{stage1}, and/or
#' \code{age2}, or for the proxy transitions described by \code{eststage3},
#' \code{eststage2}, \code{eststage1}, and/or \code{estage2}. Defaults to
#' \code{1}.
#' @param type Integer 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 integer 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.
#' @param surv_dev An optional vector of numeric deviations to the y-intercept
#' of the survival model used in function-based MPM creation. Defaults to
#' \code{NA} for all values.
#' @param obs_dev An optional vector of numeric deviations to the y-intercept
#' of the observation model used in function-based MPM creation. Defaults to
#' \code{NA} for all values.
#' @param size_dev An optional vector of numeric deviations to the y-intercept
#' of the primary size model used in function-based MPM creation. Defaults to
#' \code{NA} for all values.
#' @param sizeb_dev An optional vector of numeric deviations to the y-intercept
#' of the secondary size model used in function-based MPM creation. Defaults to
#' \code{NA} for all values.
#' @param sizec_dev An optional vector of numeric deviations to the y-intercept
#' of the tertiary size model used in function-based MPM creation. Defaults to
#' \code{NA} for all values.
#' @param repst_dev An optional vector of numeric deviations to the y-intercept
#' of the reproduction model used in function-based MPM creation. Defaults to
#' \code{NA} for all values.
#' @param fec_dev An optional vector of numeric deviations to the y-intercept
#' of the fecundity model used in function-based MPM creation. Defaults to
#' \code{NA} for all values.
#' @param jsurv_dev An optional vector of numeric deviations to the y-intercept
#' of the juvenile survival model used in function-based MPM creation. Defaults
#' to \code{NA} for all values.
#' @param jobs_dev An optional vector of numeric deviations to the y-intercept
#' of the juvenile observation model used in function-based MPM creation.
#' Defaults to \code{NA} for all values.
#' @param jsize_dev An optional vector of numeric deviations to the y-intercept
#' of the juvenile primary size model used in function-based MPM creation.
#' Defaults to \code{NA} for all values.
#' @param jsizeb_dev An optional vector of numeric deviations to the y-intercept
#' of the juvenile secondary size model used in function-based MPM creation.
#' Defaults to \code{NA} for all values.
#' @param jsizec_dev An optional vector of numeric deviations to the y-intercept
#' of the juvenile tertiary size model used in function-based MPM creation.
#' Defaults to \code{NA} for all values.
#' @param jrepst_dev An optional vector of numeric deviations to the y-intercept
#' of the juvenile reproduction model used in function-based MPM creation.
#' Defaults to \code{NA} for all values.
#' @param jmatst_dev An optional vector of numeric deviations to the y-intercept
#' of the juvenile maturity model used in function-based MPM creation.
#' Defaults to \code{NA} for all values.
#' @param indcova An optional vector of numeric values for a quantitative
#' individual covariate used in MPM creation. Should be identified as
#' individual covariate a in any other modeling. Defaults to \code{NA} for all
#' values.
#' @param indcovb An optional vector of numeric values for a quantitative
#' individual covariate used in MPM creation. Should be identified as
#' individual covariate b in any other modeling. Defaults to \code{NA} for all
#' values.
#' @param indcovc An optional vector of numeric values for a quantitative
#' individual covariate used in MPM creation. Should be identified as
#' individual covariate c in any other modeling. Defaults to \code{NA} for all
#' values.
#' 
#' @return A data frame of class \code{adaptAxis}. This object can be used as
#' input in function \code{invade3()}.
#' 
#' Variables in this object include the following:
#' \item{variant}{Denotes each variant in order, with each row corresponding to
#' a novel variant.}
#' \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{age3}{Age 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{estage3}{Age at occasion \emph{t}+1 in the transition to replace the
#' transition designated by \code{age3}.}
#' \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{offset}{A constant value to be added to the transition or proxy
#' 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).}
#' \item{surv_dev}{Numeric deviations to the y-intercept of the vital rate
#' model of survival.}
#' \item{obs_dev}{Numeric deviations to the y-intercept of the vital rate model
#' of observation.}
#' \item{size_dev}{Numeric deviations to the y-intercept of the vital rate
#' model of primary size.}
#' \item{sizeb_dev}{Numeric deviations to the y-intercept of the vital rate
#' model of secondary size.}
#' \item{sizec_dev}{Numeric deviations to the y-intercept of the vital rate
#' model of tertiary size.}
#' \item{repst_dev}{Numeric deviations to the y-intercept of the vital rate
#' model of reproduction.}
#' \item{fec_dev}{Numeric deviations to the y-intercept of the vital rate model
#' of fecundity.}
#' \item{jsurv_dev}{Numeric deviations to the y-intercept of the vital rate
#' model of juvenile survival.}
#' \item{jobs_dev}{Numeric deviations to the y-intercept of the vital rate
#' model of juvenile observation.}
#' \item{jsize_dev}{Numeric deviations to the y-intercept of the vital rate
#' model of juvenile primary size.}
#' \item{jsizeb_dev}{Numeric deviations to the y-intercept of the vital rate
#' model of juvenile secondary size.}
#' \item{jsizec_dev}{Numeric deviations to the y-intercept of the vital rate
#' model of juvenile tertiary size.}
#' \item{jrepst_dev}{Numeric deviations to the y-intercept of the vital rate
#' model of juvenile reproduction.}
#' \item{jmatst_dev}{Numeric deviations to the y-intercept of the vital rate
#' model of juvenile maturity.}
#' \item{indcova}{Numeric values of individual covariate a used in creating new
#' variants.}
#' \item{indcovb}{Numeric values of individual covariate b used in creating new
#' variants.}
#' \item{indcovc}{Numeric values of individual covariate c used in creating new
#' variants.}
#' 
#' @section Notes:
#' Negative values are not allowed in \code{givenrate} and \code{multiplier}
#' input, but are allowed in \code{offset}, if values are to be subtracted from
#' specific estimated transitions. Stage entries should not be used for purely
#' age-based MPMs, and age entries should not be used for purely stage-based
#' MPMs.
#' 
#' 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)}.
#' 
#' Several operations may be included per transition. Operations on the same
#' row of the resulting data frame are generally handled with given rate
#' substitutions first, then with proxy transitions, then by additive offsets,
#' and finally by multipliers. This order can be manipulated by ordering
#' operations across rows, with higher numbered rows in the data frame being
#' performed later.
#' 
#' @seealso \code{\link{ta_skeleton}()}
#' 
#' @examples
#' library(lefko3)
#' 
#' data(cypa_data)
#' 
#' 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 = cypa_data, noyears = 18, firstyear = 1994,
#'   individcol = "plant_id", blocksize = 2, sizeacol = "Inf.94",
#'   sizebcol = "Veg.94", repstracol = "Inf.94", fecacol = "Inf.94",
#'   stageassign = cypframe_raw, stagesize = "sizeadded", NAas0 = TRUE,
#'   NRasRep = TRUE)
#' 
#' cypa_ta <- trait_axis(stageframe = cypframe_raw,
#'   stage3 = c("P1", "P1", "P1", NA, NA, NA),
#'   stage2 = c("rep", "rep", "rep", NA, NA, NA),
#'   multiplier = c(0.5, 2.0, 10., NA, NA, NA), type = c(2, 2, 2, NA, NA, NA),
#'   obs_dev = c(NA, NA, NA, 0.5, 2.0, 50), fec_dev = c(NA, NA, NA, -1000, 0, 1000))
#' 
#' @export trait_axis
trait_axis <- function(historical = NULL, stagebased = NULL, agebased = NULL, stageframe = NULL, stage3 = NULL, stage2 = NULL, stage1 = NULL, age3 = NULL, age2 = NULL, eststage3 = NULL, eststage2 = NULL, eststage1 = NULL, estage3 = NULL, estage2 = NULL, givenrate = NULL, offset = NULL, multiplier = NULL, type = NULL, type_t12 = NULL, surv_dev = NULL, obs_dev = NULL, size_dev = NULL, sizeb_dev = NULL, sizec_dev = NULL, repst_dev = NULL, fec_dev = NULL, jsurv_dev = NULL, jobs_dev = NULL, jsize_dev = NULL, jsizeb_dev = NULL, jsizec_dev = NULL, jrepst_dev = NULL, jmatst_dev = NULL, indcova = NULL, indcovb = NULL, indcovc = NULL) {
    .Call('_adapt3_trait_axis', PACKAGE = 'adapt3', historical, stagebased, agebased, stageframe, stage3, stage2, stage1, age3, age2, eststage3, eststage2, eststage1, estage3, estage2, givenrate, offset, multiplier, type, type_t12, surv_dev, obs_dev, size_dev, sizeb_dev, sizec_dev, repst_dev, fec_dev, jsurv_dev, jobs_dev, jsize_dev, jsizeb_dev, jsizec_dev, jrepst_dev, jmatst_dev, indcova, indcovb, indcovc)
}

Try the adapt3 package in your browser

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

adapt3 documentation built on June 7, 2026, 9:08 a.m.