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

#' Scaled Inverse Chi Squared distribution
#'
#' @param n Number of random samples
#'
#' @param nu degrees of freedom of inverse chi square
#'
#' @param scale  Scale of inverse chi squared distribution
#'         (default is 1).
#'
#' @return a vector of inverse chi squared deviates.
#'
#' @examples
#' rinvchisq(3, 4, 1) ## Scale = 1, degrees of freedom = 4
#' rinvchisq(2, 4, 2) ## Scale = 2, degrees of freedom = 4
#' @export
rinvchisq <- function(n = 1L, nu = 1.0, scale = 1) {
    .Call(`_rxode2_rinvchisq`, n, nu, scale)
}

#' One correlation sample from the LKJ distribution
#'
#' @param d The dimension of the correlation matrix
#'
#' @param eta The scaling parameter of the LKJ distribution.
#'   Must be > 1.  Also related to the degrees of freedom nu.
#'   eta = (nu-1)/2.
#'
#' @param cholesky boolean; If `TRUE` return the cholesky
#'   decomposition.
#'
#' @return A correlation sample from the LKJ distribution
#'
#' @author Matthew Fidler (translated to RcppArmadillo) and Emma Schwager
#' @export
#' @keywords internal
rLKJ1 <- function(d, eta = 1.0, cholesky = FALSE) {
    .Call(`_rxode2_rLKJ1`, d, eta, cholesky)
}

rLKJcv1 <- function(sd, eta = 1.0) {
    .Call(`_rxode2_rLKJcv1`, sd, eta)
}

rLKJcvLsd1 <- function(logSd, logSdSD, eta = 1.0) {
    .Call(`_rxode2_rLKJcvLsd1`, logSd, logSdSD, eta)
}

#' One correlation sample from the Inverse Wishart distribution
#'
#' This correlation is constructed by transformation of the Inverse Wishart
#' random covariate to a correlation.
#'
#' @inheritParams rLKJ1
#'
#' @param nu Degrees of freedom of the Wishart distribution
#'
#' @inheritParams cvPost
#'
#' @return One correlation sample from the inverse wishart
#'
#' @author Matthew Fidler
#' @keywords internal
#' @export
invWR1d <- function(d, nu, omegaIsChol = FALSE) {
    .Call(`_rxode2_invWR1d`, d, nu, omegaIsChol)
}

rcvC1 <- function(sdEst, nu = 3.0, diagXformType = 1L, rType = 1L, returnChol = FALSE) {
    .Call(`_rxode2_rcvC1`, sdEst, nu, diagXformType, rType, returnChol)
}

cvPost_ <- function(nuS, omegaS, nS, omegaIsCholS, returnCholS, typeS, diagXformTypeS) {
    .Call(`_rxode2_cvPost_`, nuS, omegaS, nS, omegaIsCholS, returnCholS, typeS, diagXformTypeS)
}

expandTheta_ <- function(thetaS, thetaMatS, thetaLowerS, thetaUpperS, nStudS, nCoresRVS) {
    .Call(`_rxode2_expandTheta_`, thetaS, thetaMatS, thetaLowerS, thetaUpperS, nStudS, nCoresRVS)
}

expandPars_ <- function(objectS, paramsS, eventsS, controlS) {
    .Call(`_rxode2_expandPars_`, objectS, paramsS, eventsS, controlS)
}

nestingInfo_ <- function(omega, data) {
    .Call(`_rxode2_nestingInfo_`, omega, data)
}

swapMatListWithCube_ <- function(inO) {
    .Call(`_rxode2_swapMatListWithCube_`, inO)
}

omegaListRse <- function(omegaIn) {
    .Call(`_rxode2_omegaListRse`, omegaIn)
}

#' Set the CVODE linear solver
#'
#' @param type Integer: 1=dense (default), 2=band (currently aliases to dense),
#'   3=gmres, 4=bicgstab, 5=tfqmr
#' @return NULL (invisibly)
#' @export
#' @keywords internal
setCvodeLinearSolver <- function(type) {
    invisible(.Call(`_rxode2_setCvodeLinearSolver`, type))
}

#' Get the Linear Compartment Information based on the model variables
#'
#' @param obj The model variables object
#'
#' @return A named integer vector with the linear sensitivity compartments.
#'
#' @noRd
getLinInfo_ <- function(mv) {
    .Call(`_rxode2_getLinInfo_`, mv)
}

#' Get the real compartment number based on NONMEM-style compartment
#' adjusting for linear solved systems.
#'
#' This export is mostly for testing purposes.
#'
#' @param cmt The compartment number provided with traditional NONMEM numbering
#'
#' @param mv The model variables list
#'
#' @return An integer vector with the real compartment numbers
#'
#' @noRd
getCmtNum_ <- function(cmt, mv, sens = TRUE) {
    .Call(`_rxode2_getCmtNum_`, cmt, mv, sens)
}

#' Set Initial conditions to time zero instead of the first observed/dosed time
#'
#' @param ini0 When `TRUE` (default), set initial conditions to time
#'   zero. Otherwise the initial conditions are the first observed
#'   time.
#'
#' @return the boolean ini0, though this is called for its side effects
#'
#' @export
rxSetIni0 <- function(ini0 = TRUE) {
    .Call(`_rxode2_rxSetIni0`, ini0)
}

etTransEvidIsObs <- function(isObsSexp) {
    .Call(`_rxode2_etTransEvidIsObs`, isObsSexp)
}

#' See if the NONMEM compartment number supports infusion
#'
#' This export is mostly for testing purposes.
#'
#' @param cmt The compartment number provided with traditional NONMEM numbering
#'
#' @param mv The model variables list
#'
#' @return An integer vector with the real compartment numbers
#'
#' @noRd
cmtSupportsInfusion_ <- function(cmt, mv) {
    .Call(`_rxode2_cmtSupportsInfusion_`, cmt, mv)
}

#' See if the NONMEM compartment number supports infusion
#'
#' This export is mostly for testing purposes.
#'
#' @param cmt The compartment number provided with traditional NONMEM numbering
#'
#' @param mv The model variables list
#'
#' @return An integer vector with the real compartment numbers
#'
#' @noRd
cmtSupportsOff_ <- function(cmt, mv) {
    .Call(`_rxode2_cmtSupportsOff_`, cmt, mv)
}

#' Event translation for rxode2
#'
#' @param inData Data frame to translate
#'
#' @param obj object where model variables can be extracted from
#'
#' @param addCmt Add compartment to data frame (default `FALSE`).
#'
#' @param dropUnits Boolean to drop the units (default `FALSE`).
#'
#' @param allTimeVar Treat all covariates as if they were time-varying
#'
#' @param keepDosingOnly keep the individuals who only have dosing records and any
#'   trailing dosing records after the last observation.
#'
#' @param combineDvid is a boolean indicating if rxode2 will use `DVID` on observation
#'     records to change the `cmt` value; Useful for multiple-endpoint nlmixr models.  By default
#'     this is determined by `option("rxode2.combine.dvid")` and if the option has not been set,
#'     this is `TRUE`. This typically does not affect rxode2 simulations.
#'
#' @param keep This is a named vector of items you want to keep in the final rxode2 dataset.
#'     For added rxode2 event records (if seen), last observation carried forward will be used.
#'
#' @param addlKeepsCov This determines if the additional dosing items
#'   repeats the dose only (`FALSE`) or keeps the covariates at the
#'   record of the dose (`TRUE`)
#'
#' @param addlDropSs When there are steady state doses with an `addl`
#'   specification the steady state flag is dropped with repeated
#'   doses (when `TRUE`) or retained (when `FALSE`)
#'
#' @param ssAtDoseTime Boolean that when `TRUE` back calculates the
#'   steady concentration at the actual time of dose, otherwise when
#'   `FALSE` the doses are shifted
#'
#' @inheritParams rxSolve
#'
#' @return Object for solving in rxode2
#'
#' @keywords internal
#'
#' @export
etTrans <- function(inData, obj, addCmt = FALSE, dropUnits = FALSE, allTimeVar = FALSE, keepDosingOnly = FALSE, combineDvid = NULL, keep = character(0), addlKeepsCov = FALSE, addlDropSs = TRUE, ssAtDoseTime = TRUE, iCov = NULL) {
    .Call(`_rxode2_etTrans`, inData, obj, addCmt, dropUnits, allTimeVar, keepDosingOnly, combineDvid, keep, addlKeepsCov, addlDropSs, ssAtDoseTime, iCov)
}

rxEtTransAsDataFrame_ <- function(inData1) {
    .Call(`_rxode2_rxEtTransAsDataFrame_`, inData1)
}

#' Expand grid internal function
#'
#' @param c1 character vector of items to be expanded
#' @param c2 second character vector of items to be expanded
#' @param type 0 for a typical data frame, 1 for symengine sensitivity expansion
#' @return data frame (when type = 0) or symengine string (when type=1)
#' @export
#' @keywords internal
rxExpandGrid_ <- function(c1, c2, type) {
    .Call(`_rxode2_rxExpandGrid_`, c1, c2, type)
}

#' Expand sensitivity
#'
#' @param state is the state to expand
#' @param calcSens is the variables to calculate sensitivity
#' @keywords internal
#' @return symengine string for expanded sensitivity
#' @export
rxExpandSens_ <- function(state, calcSens) {
    .Call(`_rxode2_rxExpandSens_`, state, calcSens)
}

#' Expand second order sensitivity
#'
#' @param state is the state to expand
#' @param s1 is the variables to calculate sensitivity
#' @param s2 is the variables to calculate second order sensitivity
#' @keywords internal
#' @return string for symengine second order sensitivity
#' @export
rxExpandSens2_ <- function(state, s1, s2) {
    .Call(`_rxode2_rxExpandSens2_`, state, s1, s2)
}

#' Expand third order sensitivity
#'
#' Builds the symengine code for the third order forward sensitivity
#' d/dt(d^3 state / d s1 d s2 d s3) by total-differentiating the stored
#' second order sensitivity RHS (for the pair s2,s3) with respect to the
#' newly added variable s1.  Mirrors \code{rxExpandSens2_}; assumes the
#' first and second order sensitivities (and the Jacobian) are already
#' loaded in the symengine \code{model} environment.
#'
#' @param state is the state to expand
#' @param s1 is the newly added (outer) sensitivity variable
#' @param s2 is the second sensitivity variable
#' @param s3 is the third sensitivity variable
#' @keywords internal
#' @return data frame of symengine third order sensitivity code
#' @export
rxExpandSens3_ <- function(state, s1, s2, s3) {
    .Call(`_rxode2_rxExpandSens3_`, state, s1, s2, s3)
}

#' Expand d(f)/d(eta)
#'
#' @param state is the state to expand
#' @param neta is the number of etas
#' @param pred type of prediction
#' @param isTheta logical, is the expansion actually for thetas instead of etas
#' @keywords internal
#' @return String of symengine expressions to evaluate to calculate df/deta
#' @export
rxExpandFEta_ <- function(state, neta, pred, isTheta = FALSE) {
    .Call(`_rxode2_rxExpandFEta_`, state, neta, pred, isTheta)
}

#' Rep R0 for foce
#'
#' @param neta ETA to substitute
#'
#' @return Returns a string of R code to substitute the rx_r expression in the symengine environment .s
#'
#' @keywords internal
#'
#' @export
rxRepR0_ <- function(neta) {
    .Call(`_rxode2_rxRepR0_`, neta)
}

rxExpandNesting <- function(obj, nestingInfo, compile = FALSE) {
    .Call(`_rxode2_rxExpandNesting`, obj, nestingInfo, compile)
}

#' Inductive linearization solver
#'
#' @param cSub = Current subject number
#' @param op - rxode2 solving options
#' @param tp - Prior time point/time zero
#' @param yp - Prior state;  vector size = neq; Final state is updated here
#' @param tf - Final Time
#' @param InfusionRate = Rates of each compartment;  vector size = neq
#' @param on Indicator for if the compartment is "on"
#' @param cache
#'    0 = no Cache
#'    When doIndLin == 0, cache > 0 = nInf-1
#' @param ME the rxode2 matrix exponential function
#' @param IndF The rxode2 Inductive Linearization function F
#'
#' @return Returns a status for solving
#'
#'   1 = Successful solve
#'
#'   -1 = Maximum number of iterations reached when doing
#'        inductive linearization
#' @name rxIndLin_
#' @noRd
NULL

rxIndLin_ <- function(states) {
    .Call(`_rxode2_rxIndLin_`, states)
}

convertId_ <- function(x) {
    .Call(`_rxode2_convertId_`, x)
}

linCmtModelDouble <- function(dt, p1, v1, p2, p3, p4, p5, ka, alastNV, rateNV, ncmt, oral0, trans, deriv, type, tau, tinf, amt, bolusCmt, ndiff, sensType = 3L, sensH = 0.001) {
    .Call(`_rxode2_linCmtModelDouble`, dt, p1, v1, p2, p3, p4, p5, ka, alastNV, rateNV, ncmt, oral0, trans, deriv, type, tau, tinf, amt, bolusCmt, ndiff, sensType, sensH)
}

#' Variance-covariance (non-Cholesky) Omega parameterization derivatives (C++)
#'
#' C++/RcppArmadillo implementation of the non-Cholesky Omega derivatives used
#' to build a FOCEI/FOCE observed-information covariance over the natural
#' variance-covariance scale.  Returns \eqn{\Omega^{-1}}, \eqn{\log|\Omega|},
#' and their first (and optionally second) derivatives with respect to each free
#' lower-triangular variance-covariance element \eqn{\omega_{ab}}, using
#'
#' \deqn{\partial \Omega^{-1}/\partial \omega_{ab} = -\Omega^{-1} E_{ab} \Omega^{-1}}
#' \deqn{\partial \log|\Omega|/\partial \omega_{ab} = \mathrm{tr}(\Omega^{-1} E_{ab})}
#'
#' where \eqn{E_{ab}} is the symmetric single-entry basis matrix.
#'
#' @param omega symmetric positive-definite random-effects covariance matrix.
#' @param order integer; `1` for first derivatives only, `2` (default) to also
#'   return the second derivatives needed for the covariance Hessian.
#' @return a list with `omegaInv`, `logDet`, the free-element index matrix
#'   `elements` (each row `c(a, b)`, `a >= b`), first derivatives
#'   `dOmegaInv` / `dLogDet`, and (when `order = 2`) second derivatives
#'   `d2OmegaInv` / `d2LogDet`.
#' @author Hidde van de Beek
#' @keywords internal
#' @export
rxOmegaVarCovDeriv_ <- function(omega, order = 2L) {
    .Call(`_rxode2_rxOmegaVarCovDeriv_`, omega, order)
}

rxQs <- function(x) {
    .Call(`_rxode2_rxQs`, x)
}

rxQr <- function(y) {
    .Call(`_rxode2_rxQr`, y)
}

rxode2parseSetRstudio <- function(isRstudio = FALSE) {
    .Call(`_rxode2_rxode2parseSetRstudio`, isRstudio)
}

#' Silence some of rxode2's C/C++ messages
#'
#' @param silent can be 0L "noisy"  or 1L "silent"
#'
#' @keywords internal
#' @return TRUE; called for side effects
#' @export
rxParseSetSilentErr <- function(silent) {
    .Call(`_rxode2_rxParseSetSilentErr`, silent)
}

#' Get the serialization type from raw vector
#'
#' @param raw A raw vector
#'
#' @keywords internal
#'
#' @export
#'
#' @return a string indicating the serialization type:
#'    "qs2", "qdata", "qs", "bzip2", "xz",  "base", or "unknown"
rxGetSerialType_ <- function(raw) {
    .Call(`_rxode2_rxGetSerialType_`, raw)
}

#' This handles the drop list
#'
#' @param drop a character vector representing the list of items to
#'   drop from the output
#'
#' @param input The input data frame (technically a data.frame is a
#'   special list)
#'
#' @param warnDrop is a boolean that will determine if nonsense drops
#'   should be warned about in R.
#'
#' @return a data-frame with the requested items dropped.
#' @noRd
NULL

#' This gets the rxModels_ environment from the rxode2 namespace
#'
#' @return `rxModels_` environment
#' @noRd
NULL

#' This allows assignment inside the `rxModels_` environment
#'
#' @param string that should be assigned
#'
#' @param a R/S expression (SEXP) to assign in the `rxModels_`
#'   environment
#'
#' @return nothing, called for side effects
#'
#' @noRd
NULL

#' Returns (unsurprisingly) if the file exists
#'
#' @param file name
#'
#' @return boolean of if the file exists
#' @noRd
NULL

#' If nothing else works, try dispatching the `rxModelVarsS3`
#' dispatch
#'
#' @param obj is the R object trying to get the model variables from
#'
#' @return model variables (or error from `rxModelVarsS3` default method)
#' @noRd
NULL

#' Get the rxModelVars from an rxode2 object
#'
#' @param obj is the rxode2 object to get the model variables from
#'
#' @return model variables
#' @noRd
NULL

#' This gives a blank model variables object
#'
#' @return blank model variables object (though has same structure)
#'
#' @noRd
NULL

#' Get the model variables object from a character object
#'
#' @param obj character vector to convert to model variables object
#'
#' @return model variables
#'
#' @noRd
NULL

#' List to convert Model variables object into
#'
#' @param obj R list to extract model variable from.
#'
#' @return model variable object
#' @noRd
NULL

#' Check the type of an object using Rcpp
#'
#' @param obj Object to check
#'
#' @param cls Type of class.  Only s3 classes for lists/environments
#'   and primitive classes are checked.  For matrix types they are
#'   distinguished as `numeric.matrix`, `integer.matrix`,
#'   `logical.matrix`, and `character.matrix` as well as the
#'   traditional `matrix` class. Additionally checks for
#'   `event.data.frame` which is an `data.frame` object with `time`,
#'   `evid` and `amt`. (UPPER, lower or Title cases accepted)
#'
#'
#' @return A boolean indicating if the object is a member of the class.
#'
#' @keywords internal
#'
#' @author Matthew L. Fidler
#'
#' @export
#'
rxIs <- function(obj, cls) {
    .Call(`_rxode2_rxIs`, obj, cls)
}

dynLoad <- function(dll) {
    .Call(`_rxode2_dynLoad`, dll)
}

#' Get the model variables for an object
#'
#' @param obj the R object to try to extract the model variable object from.
#'
#' @return model variable object or error
#'
#' @noRd
rxModelVars_ <- function(obj) {
    .Call(`_rxode2_rxModelVars_`, obj)
}

#' State variables
#'
#' This returns the model's compartments or states.
#'
#' @inheritParams rxModelVars
#'
#' @param state is a string indicating the state or compartment that
#'     you would like to lookup.
#'
#' @return If state is missing, return a character vector of all the states.
#'
#' If state is a string, return the compartment number of the named state.
#'
#' @seealso [rxode2()]
#' @family Query model information
#' @author Matthew L.Fidler
#' @export
rxState <- function(obj = NULL, state = NULL) {
    .Call(`_rxode2_rxState`, obj, state)
}

rxParams_ <- function(obj) {
    .Call(`_rxode2_rxParams_`, obj)
}

#' Jacobian and parameter derivatives
#'
#' Return Jacobain and parameter derivatives
#'
#' @inheritParams rxModelVars
#'
#' @return A list of the jacobian parameters defined in this rxode2
#'     object.
#'
#' @author Matthew L. Fidler
#'
#' @family Query model information
#' @export
rxDfdy <- function(obj) {
    .Call(`_rxode2_rxDfdy`, obj)
}

#' Left handed Variables
#'
#' This returns the model calculated variables
#'
#' @inheritParams rxModelVars
#'
#' @return a character vector listing the calculated parameters
#' @seealso \code{\link{rxode2}}
#' @family Query model information
#' @author Matthew L.Fidler
#' @export
rxLhs <- function(obj) {
    .Call(`_rxode2_rxLhs`, obj)
}

#' Initial Values and State values for a rxode2 object
#'
#' Returns the initial values of the rxDll object
#'
#' @param obj rxDll, rxode2, or named vector representing default
#'     initial arguments
#'
#' @param vec If supplied, named vector for the model.
#'
#' @param req Required names, and the required order for the ODE solver
#'
#' @param defaultValue a number or NA representing the default value for
#'     parameters missing in `vec`, but required in `req`.
#'
#' @param noerror is a boolean specifying if an error should be thrown
#'     for missing parameter values when `default` = `NA`
#'
#' @return Initial values of the rxDll object
#'
#' @keywords internal
#' @family Query model information
#' @author Matthew L.Fidler
#' @export
rxInits <- function(obj, vec = NULL, req = NULL, defaultValue = 0, noerror = FALSE, noini = FALSE, rxLines = FALSE) {
    .Call(`_rxode2_rxInits`, obj, vec, req, defaultValue, noerror, noini, rxLines)
}

#' Setup the initial conditions.
#'
#' @param obj rxode2 object
#' @param inits A numeric vector of initial conditions.
#' @return initial conditions that were setup
#' @author Matthew L. Fidler
#' @keywords internal
#' @export
rxSetupIni <- function(obj, inits = NULL) {
    .Call(`_rxode2_rxSetupIni`, obj, inits)
}

#' Setup the initial conditions.
#'
#' @param obj rxode2 object
#'
#' @param scale A numeric vector scales
#'
#' @param extraArgs A list of extra args to parse for initial conditions.
#'
#' @author Matthew L. Fidler
#'
#' @keywords internal
#'
#' @return setup scale for changing compartment values
#'
#' @export
rxSetupScale <- function(obj, scale = NULL, extraArgs = NULL) {
    .Call(`_rxode2_rxSetupScale`, obj, scale, extraArgs)
}

atolRtolFactor_ <- function(factor) {
    invisible(.Call(`_rxode2_atolRtolFactor_`, factor))
}

#' Simulate Parameters from a Theta/Omega specification
#'
#' @param params Named Vector of rxode2 model parameters
#'
#' @param nObs Number of observations to simulate (with `sigma` matrix)
#'
#' @inheritParams rxSolve
#'
#' @param simSubjects boolean indicated rxode2 should simulate subjects in studies (`TRUE`,
#'         default) or studies (`FALSE`)
#'
#' @return a data frame with the simulated subjects
#'
#' @author Matthew L.Fidler
#'
#' @export
rxSimThetaOmega <- function(params = NULL, omega = NULL, omegaDf = NULL, omegaLower = as.numeric( c(R_NegInf)), omegaUpper = as.numeric( c(R_PosInf)), omegaIsChol = FALSE, omegaSeparation = "auto", omegaXform = 1L, nSub = 1L, thetaMat = NULL, thetaLower = as.numeric( c(R_NegInf)), thetaUpper = as.numeric( c(R_PosInf)), thetaDf = NULL, thetaIsChol = FALSE, nStud = 1L, sigma = NULL, sigmaLower = as.numeric( c(R_NegInf)), sigmaUpper = as.numeric( c(R_PosInf)), sigmaDf = NULL, sigmaIsChol = FALSE, sigmaSeparation = "auto", sigmaXform = 1L, nCoresRV = 1L, nObs = 1L, dfSub = 0, dfObs = 0, simSubjects = TRUE, simVariability = as.logical( c(NA_LOGICAL))) {
    .Call(`_rxode2_rxSimThetaOmega`, params, omega, omegaDf, omegaLower, omegaUpper, omegaIsChol, omegaSeparation, omegaXform, nSub, thetaMat, thetaLower, thetaUpper, thetaDf, thetaIsChol, nStud, sigma, sigmaLower, sigmaUpper, sigmaDf, sigmaIsChol, sigmaSeparation, sigmaXform, nCoresRV, nObs, dfSub, dfObs, simSubjects, simVariability)
}

rxSolveSetCurObj_ <- function(obj) {
    invisible(.Call(`_rxode2_rxSolveSetCurObj_`, obj))
}

#' Free the C solving/parsing information.
#'
#' Take the ODE C system and free it.
#'
#' @keywords internal
#' @return logical indicating if the memory was successfully freed
#' @export
rxSolveFree <- function() {
    .Call(`_rxode2_rxSolveFree`)
}

#' See if the memory is installed for a solve
#'
#' @return boolean saying if the memnory is currently free for rxode2
#' @keywords internal
#' @export
#' @author Matthew L. Fidler
rxSolveSetup <- function() {
    .Call(`_rxode2_rxSolveSetup`)
}

rxSolveFromRaw_ <- function(obj, rawObj, solveState, rxControl, specParams, extraArgs, params, events, inits) {
    .Call(`_rxode2_rxSolveFromRaw_`, obj, rawObj, solveState, rxControl, specParams, extraArgs, params, events, inits)
}

rxSolve_ <- function(obj, rxControl, specParams, extraArgs, params, events, inits, setupOnly) {
    .Call(`_rxode2_rxSolve_`, obj, rxControl, specParams, extraArgs, params, events, inits, setupOnly)
}

rxSolveDollarNames <- function(obj) {
    .Call(`_rxode2_rxSolveDollarNames`, obj)
}

rxSolveGet <- function(obj, arg, exact = TRUE) {
    .Call(`_rxode2_rxSolveGet`, obj, arg, exact)
}

rxSolveUpdate <- function(obj, arg = NULL, value = NULL) {
    .Call(`_rxode2_rxSolveUpdate`, obj, arg, value)
}

rxSolveSEXP <- function(objS, rxControlS, specParamsS, extraArgsS, paramsS, eventsS, initsS, setupOnlyS) {
    .Call(`_rxode2_rxSolveSEXP`, objS, rxControlS, specParamsS, extraArgsS, paramsS, eventsS, initsS, setupOnlyS)
}

rxRmModelLib_ <- function(str) {
    invisible(.Call(`_rxode2_rxRmModelLib_`, str))
}

#' Get rxode2 model from object
#' @param obj rxode2 family of objects
#' @return rxode2 model
#' @export
rxGetrxode2 <- function(obj) {
    .Call(`_rxode2_rxGetrxode2`, obj)
}

#' Checks if the rxode2 object was built with the current build
#'
#' @inheritParams rxModelVars
#'
#' @return boolean indicating if this was built with current rxode2
#'
#' @export
rxIsCurrent <- function(obj) {
    .Call(`_rxode2_rxIsCurrent`, obj)
}

#' Assign pointer based on model variables
#' @param object rxode2 family of objects
#' @return nothing, called for side effects
#' @export
rxAssignPtr <- function(object = NULL) {
    invisible(.Call(`_rxode2_rxAssignPtr`, object))
}

#' Return the DLL associated with the rxode2 object
#'
#' This will return the dynamic load library or shared object used to
#' run the C code for rxode2.
#'
#' @param obj A rxode2 family of objects or a character string of the
#'     model specification or location of a file with a model
#'     specification.
#'
#' @return a path of the library
#'
#' @keywords internal
#' @author Matthew L.Fidler
#' @export
rxDll <- function(obj) {
    .Call(`_rxode2_rxDll`, obj)
}

#' Return the C file associated with the rxode2 object
#'
#' This will return C code for generating the rxode2 DLL.
#'
#' @param obj A rxode2 family of objects or a character string of the
#'     model specification or location of a file with a model
#'     specification.
#'
#' @return a path of the library
#'
#' @keywords internal
#' @author Matthew L.Fidler
#' @export
rxC <- function(obj) {
    .Call(`_rxode2_rxC`, obj)
}

#' Determine if the DLL associated with the rxode2 object is loaded
#'
#' @param obj A rxode2 family of objects
#'
#' @return Boolean returning if the rxode2 library is loaded.
#'
#' @keywords internal
#' @author Matthew L.Fidler
#' @export
rxIsLoaded <- function(obj) {
    .Call(`_rxode2_rxIsLoaded`, obj)
}

#' Load rxode2 object
#'
#' @param obj A rxode2 family of objects
#'
#' @return Boolean returning if the rxode2 library is loaded.
#'
#' @keywords internal
#' @author Matthew L.Fidler
#' @export
rxDynLoad <- function(obj) {
    .Call(`_rxode2_rxDynLoad`, obj)
}

#' Lock/unlocking of rxode2 dll file
#'
#' @param obj A rxode2 family of objects
#'
#' @return nothing; called for side effects
#'
#' @export
rxLock <- function(obj) {
    .Call(`_rxode2_rxLock`, obj)
}

#' @rdname rxLock
#' @export
rxUnlock <- function(obj) {
    .Call(`_rxode2_rxUnlock`, obj)
}

#' Allow unloading of dlls
#'
#' @param allow boolean indicating if garbage collection will unload of rxode2 dlls.
#'
#' @return Boolean allow; called for side effects
#'
#' @examples
#'
#' # Garbage collection will not unload un-used rxode2 dlls
#' rxAllowUnload(FALSE);
#'
#' # Garbage collection will unload unused rxode2 dlls
#' rxAllowUnload(TRUE);
#' @export
#' @author Matthew Fidler
rxAllowUnload <- function(allow) {
    .Call(`_rxode2_rxAllowUnload`, allow)
}

rxUnloadAll_ <- function() {
    .Call(`_rxode2_rxUnloadAll_`)
}

#' Unload rxode2 object
#'
#' @param obj A rxode2 family of objects
#'
#' @return Boolean returning if the rxode2 library is loaded.
#'
#' @keywords internal
#' @author Matthew L.Fidler
#' @export
rxDynUnload <- function(obj) {
    .Call(`_rxode2_rxDynUnload`, obj)
}

#' Delete the DLL for the model
#'
#' This function deletes the DLL, but doesn't delete the model
#' information in the object.
#'
#' @param obj rxode2 family of objects
#'
#' @return A boolean stating if the operation was successful.
#'
#' @author Matthew L.Fidler
#' @export
rxDelete <- function(obj) {
    .Call(`_rxode2_rxDelete`, obj)
}

setRstudio <- function(isRstudio = FALSE) {
    .Call(`_rxode2_setRstudio`, isRstudio)
}

setProgSupported <- function(isSupported = 1L) {
    .Call(`_rxode2_setProgSupported`, isSupported)
}

getProgSupported <- function() {
    .Call(`_rxode2_getProgSupported`)
}

rxUpdateTrans_ <- function(ret, prefix, libName) {
    .Call(`_rxode2_rxUpdateTrans_`, ret, prefix, libName)
}

dropUnitsRxSolve <- function(x) {
    .Call(`_rxode2_dropUnitsRxSolve`, x)
}

#' Silence some of rxode2's C/C++ messages
#'
#' @param silent can be 0L "noisy"  or 1L "silent"
#'
#' @keywords internal
#' @return TRUE; called for side effects
#' @export
rxSetSilentErr <- function(silent) {
    .Call(`_rxode2_rxSetSilentErr`, silent)
}

#' Invert matrix using RcppArmadillo.
#'
#' @param matrix matrix to be inverted.
#'
#' @return inverse or pseudo inverse of matrix.
#'
#' @export
rxInv <- function(matrix) {
    .Call(`_rxode2_rxInv`, matrix)
}

#' Get Omega^-1 and derivatives
#'
#' @param invObjOrMatrix Object for inverse-type calculations.  If
#'   this is a matrix, setup the object for inversion
#'   [rxSymInvCholCreate()] with the default arguments and return a
#'   reactive s3 object.  Otherwise, use the inversion object to
#'   calculate the requested derivative/inverse.
#'
#' @param theta Thetas to be used for calculation.  If missing (`NULL`), a
#'     special s3 class is created and returned to access `Omega^1`
#'     objects as needed and cache them based on the theta that is
#'     used.
#'
#' @param type The type of object.  Currently the following types are
#'     supported:
#'
#' * `cholOmegaInv` gives the
#'     Cholesky decomposition of the Omega Inverse matrix.
#' * `omegaInv` gives the Omega Inverse matrix.
#' * `d(omegaInv)` gives the `d(Omega^-1)` withe respect to the
#'     theta parameter specified in `thetaNumber`.
#' * `d(D)` gives the `d(diagonal(Omega^-1))` with respect to
#'     the theta parameter specified in the `thetaNumber`
#'     parameter
#'
#' @param thetaNumber For types `d(omegaInv)` and `d(D)`,
#'     the theta number that the derivative is taken against.  This
#'     must be positive from 1 to the number of thetas defining the
#'     Omega matrix.
#'
#' @return Matrix based on parameters or environment with all the
#'     matrixes calculated in variables `omega`, `omegaInv`, `dOmega`,
#'     `dOmegaInv`.
#'
#' @author Matthew L. Fidler
#'
#' @export
rxSymInvChol <- function(invObjOrMatrix, theta = NULL, type = "cholOmegaInv", thetaNumber = 0L) {
    .Call(`_rxode2_rxSymInvChol`, invObjOrMatrix, theta, type, thetaNumber)
}

rxSymInvCholEnvCalculate <- function(obj, what, theta = NULL) {
    .Call(`_rxode2_rxSymInvCholEnvCalculate`, obj, what, theta)
}

#' Report the byte sizes of every rxode2 solver memory allocation
#'
#' Returns a named numeric vector of byte counts for every buffer rxode2
#' allocates during \code{rxSolve()}.  Values are computed with the same
#' formulas used by the actual allocator in \code{rxData.cpp} via the shared
#' \code{rxFillMemLayout()} function, so any change to the allocator
#' automatically changes the estimate.
#'
#' @param neq       Number of ODE states (\code{length(rxModelVars(model)$state)}).
#' @param stateSize Effective \code{state.size()} passed to the solver.
#'   For pure ODE models this equals \code{neq}; for linCmt-only models it
#'   may be 0.  Use \code{neq} when in doubt.
#' @param nlhs      Number of LHS (calculated) outputs.
#' @param npars     Number of model parameters (for \code{gpars} estimate).
#' @param neta      Number of random effects (etas).
#' @param neps      Number of residual-error levels (epsilons).
#' @param ncov      Number of time-varying covariates.
#' @param nsim      Number of simulations.
#' @param cores     Number of parallel OMP threads.
#' @param nMtime    Number of model measurement times.
#' @param extraCmt  Extra compartments (0, 1 = depot, 2 = depot+central).
#' @param linB      1 if using an analytical linear-compartment model, else 0.
#' @param nLlik     Number of log-likelihood terms (FOCEi).
#' @param nIndSim   Per-individual simulation count (typically \code{neta+neps}).
#' @param numLinSens Number of linear sensitivity parameters (FOCEi mixed models).
#' @param numLin    Number of linear compartment terms (FOCEi mixed models).
#' @param nsub      Number of subjects.
#' @param nallTotal Total events across all subjects (sum of obs + doses).
#' @param maxAllTimes Maximum events for any single subject.
#' @return Named numeric vector; each element is bytes for that allocation.
#'   Also includes \code{sizeofInd} (bytes per \code{rx_solving_options_ind}
#'   struct) and \code{rxLlikSaveSize} (the compile-time constant).
#' @noRd
rxMemoryComponents_ <- function(neq, stateSize, nlhs, npars, neta, neps, ncov, nsim, cores, nMtime, extraCmt, linB, nLlik, nIndSim, numLinSens, numLin, nsub, nallTotal, maxAllTimes) {
    .Call(`_rxode2_rxMemoryComponents_`, neq, stateSize, nlhs, npars, neta, neps, ncov, nsim, cores, nMtime, extraCmt, linB, nLlik, nIndSim, numLinSens, numLin, nsub, nallTotal, maxAllTimes)
}

rxOptRep_ <- function(input) {
    .Call(`_rxode2_rxOptRep_`, input)
}

#' Save the pre-integration rxode2 solver state to a binary file
#'
#' Called internally after event-table and parameter setup but before ODE
#' integration.  The file can later be restored with rxRestoreState_().
#'
#' @param path File path to write (created/overwritten).
#' @return Invisibly TRUE.
#' @noRd
rxSaveState_ <- function() {
    .Call(`_rxode2_rxSaveState_`)
}

#' Check whether a file was written by rxSaveState_
#' @noRd
rxIsSerializeFile_ <- function(rawSexp) {
    .Call(`_rxode2_rxIsSerializeFile_`, rawSexp)
}

#' Restore a pre-integration rxode2 solver state from binary file
#'
#' @param path File path written by rxSaveState_().
#' @return Invisibly TRUE.
#' @noRd
rxRestoreState_ <- function(rawSexp) {
    .Call(`_rxode2_rxRestoreState_`, rawSexp)
}

rxStack_ <- function(Data, vars = NULL) {
    .Call(`_rxode2_rxStack_`, Data, vars)
}

rxModelVarsStack <- function(x) {
    .Call(`_rxode2_rxModelVarsStack`, x)
}

rxRmvn_ <- function(A_, mu, sigma, ncores = 1L, isChol = FALSE) {
    .Call(`_rxode2_rxRmvn_`, A_, mu, sigma, ncores, isChol)
}

rxMvnrnd <- function(n, L, l, u, mu, a = 0.4, tol = 2.05) {
    .Call(`_rxode2_rxMvnrnd`, n, L, l, u, mu, a, tol)
}

rxCholperm <- function(Sig, l, u, eps = 1e-10) {
    .Call(`_rxode2_rxCholperm`, Sig, l, u, eps)
}

rxGradpsi <- function(y, L, l, u) {
    .Call(`_rxode2_rxGradpsi`, y, L, l, u)
}

rxNleq <- function(l, u, L) {
    .Call(`_rxode2_rxNleq`, l, u, L)
}

rxMvrandn_ <- function(A_, mu, sigma, lower, upper, ncores = 1L, a = 0.4, tol = 2.05, nlTol = 1e-10, nlMaxiter = 100L) {
    .Call(`_rxode2_rxMvrandn_`, A_, mu, sigma, lower, upper, ncores, a, tol, nlTol, nlMaxiter)
}

#' This seeds the engine based on the number of cores used in random number generation
#'
#' @param ncores is the number of cores to use.
#' @keywords internal
#' @return Nothing, called for side effects
#' @export
#' @examples
#' rxSeedEng()
rxSeedEng <- function(ncores = 1L) {
    .Call(`_rxode2_rxSeedEng`, ncores)
}

rxnbinomMu_ <- function(size, mu, n, ncores) {
    .Call(`_rxode2_rxnbinomMu_`, size, mu, n, ncores)
}

rxnbinom_ <- function(size, prob, n, ncores) {
    .Call(`_rxode2_rxnbinom_`, size, prob, n, ncores)
}

rxbinom_ <- function(n0, prob, n, ncores) {
    .Call(`_rxode2_rxbinom_`, n0, prob, n, ncores)
}

rxcauchy_ <- function(location, scale, n, ncores) {
    .Call(`_rxode2_rxcauchy_`, location, scale, n, ncores)
}

rxchisq_ <- function(df, n, ncores) {
    .Call(`_rxode2_rxchisq_`, df, n, ncores)
}

rxexp_ <- function(rate, n, ncores) {
    .Call(`_rxode2_rxexp_`, rate, n, ncores)
}

rxf_ <- function(df1, df2, n, ncores) {
    .Call(`_rxode2_rxf_`, df1, df2, n, ncores)
}

rxgamma_ <- function(shape, rate, n, ncores) {
    .Call(`_rxode2_rxgamma_`, shape, rate, n, ncores)
}

rxbeta_ <- function(shape1, shape2, n, ncores) {
    .Call(`_rxode2_rxbeta_`, shape1, shape2, n, ncores)
}

rxgeom_ <- function(prob, n, ncores) {
    .Call(`_rxode2_rxgeom_`, prob, n, ncores)
}

rxnorm_ <- function(mean, sd, n, ncores) {
    .Call(`_rxode2_rxnorm_`, mean, sd, n, ncores)
}

rxpois_ <- function(lambda, n, ncores) {
    .Call(`_rxode2_rxpois_`, lambda, n, ncores)
}

rxt__ <- function(df, n, ncores) {
    .Call(`_rxode2_rxt__`, df, n, ncores)
}

rxunif_ <- function(low, hi, n, ncores) {
    .Call(`_rxode2_rxunif_`, low, hi, n, ncores)
}

rxweibull_ <- function(shape, scale, n, ncores) {
    .Call(`_rxode2_rxweibull_`, shape, scale, n, ncores)
}

rxRmvn0 <- function(A_, mu, sigma, lower, upper, ncores = 1L, isChol = FALSE, a = 0.4, tol = 2.05, nlTol = 1e-10, nlMaxiter = 100L) {
    .Call(`_rxode2_rxRmvn0`, A_, mu, sigma, lower, upper, ncores, isChol, a, tol, nlTol, nlMaxiter)
}

rxRmvnSEXP <- function(nS, muS, sigmaS, lowerS, upperS, ncoresS, isCholS, keepNamesS, aS, tolS, nlTolS, nlMaxiterS) {
    .Call(`_rxode2_rxRmvnSEXP`, nS, muS, sigmaS, lowerS, upperS, ncoresS, isCholS, keepNamesS, aS, tolS, nlTolS, nlMaxiterS)
}

rpp_ <- function(nS, lambdaS, gammaS, probS, t0S, tmaxS, randomOrderS) {
    .Call(`_rxode2_rpp_`, nS, lambdaS, gammaS, probS, t0S, tmaxS, randomOrderS)
}

rxordSelect <- function(u, cs) {
    .Call(`_rxode2_rxordSelect`, u, cs)
}

isNullZero <- function(obj) {
    .Call(`_rxode2_isNullZero`, obj)
}

rxErf <- function(v) {
    .Call(`_rxode2_rxErf`, v)
}

binomProbsPredVec_ <- function(n, m, Y, M, doP = TRUE, tol = 1e-7) {
    .Call(`_rxode2_binomProbsPredVec_`, n, m, Y, M, doP, tol)
}

binomProbs_ <- function(x, probs, naRm, nIn, cont) {
    .Call(`_rxode2_binomProbs_`, x, probs, naRm, nIn, cont)
}

meanProbs_ <- function(x, probs, naRm, useT, pred, nIn) {
    .Call(`_rxode2_meanProbs_`, x, probs, naRm, useT, pred, nIn)
}

