fit_model: Fit a mark-recapture model

View source: R/fit_model.R

fit_modelR Documentation

Fit a mark-recapture model

Description

Fits the multistate mark recapture model using cmdstanr. Most of the arguments to this function are inherited from the 'sample()' method in cmdstanr, providing fine-tuned control over the posterior sampling.

Usage

fit_model(
  data,
  seed = NULL,
  refresh = NULL,
  init = NULL,
  save_latent_dynamics = FALSE,
  output_dir = NULL,
  output_basename = NULL,
  sig_figs = NULL,
  chains = 4,
  parallel_chains = getOption("mc.cores", 1),
  chain_ids = seq_len(chains),
  threads_per_chain = NULL,
  opencl_ids = NULL,
  iter_warmup = 1000,
  iter_sampling = 1000,
  save_warmup = FALSE,
  thin = NULL,
  max_treedepth = NULL,
  adapt_engaged = TRUE,
  adapt_delta = NULL,
  step_size = NULL,
  metric = NULL,
  metric_file = NULL,
  inv_metric = NULL,
  init_buffer = NULL,
  term_buffer = NULL,
  window = NULL,
  fixed_param = FALSE,
  show_messages = TRUE,
  compile = TRUE,
  ...
)

Arguments

data

A list of data generated by the function mrmr::clean_data().

seed

(positive integer(s)) A seed for the (P)RNG to pass to CmdStan. In the case of multi-chain sampling the single seed will automatically be augmented by the the run (chain) ID so that each chain uses a different seed. The exception is the transformed data block, which defaults to using same seed for all chains so that the same data is generated for all chains if RNG functions are used. The only time seed should be specified as a vector (one element per chain) is if RNG functions are used in transformed data and the goal is to generate different data for each chain.

refresh

(non-negative integer) The number of iterations between printed screen updates. If refresh = 0, only error messages will be printed.

init

(multiple options) The initialization method to use for the variables declared in the parameters block of the Stan program. One of the following:

  • A real number x>0. This initializes all parameters randomly between ⁠[-x,x]⁠ on the unconstrained parameter space.;

  • The number 0. This initializes all parameters to 0;

  • A character vector of paths (one per chain) to JSON or Rdump files containing initial values for all or some parameters. See write_stan_json() to write R objects to JSON files compatible with CmdStan.

  • A list of lists containing initial values for all or some parameters. For MCMC the list should contain a sublist for each chain. For optimization and variational inference there should be just one sublist. The sublists should have named elements corresponding to the parameters for which you are specifying initial values. See Examples.

  • A function that returns a single list with names corresponding to the parameters for which you are specifying initial values. The function can take no arguments or a single argument chain_id. For MCMC, if the function has argument chain_id it will be supplied with the chain id (from 1 to number of chains) when called to generate the initial values. See Examples.

save_latent_dynamics

(logical) Should auxiliary diagnostic information about the latent dynamics be written to temporary diagnostic CSV files? This argument replaces CmdStan's diagnostic_file argument and the content written to CSV is controlled by the user's CmdStan installation and not CmdStanR (for some algorithms no content may be written). The default is FALSE, which is appropriate for almost every use case. To save the temporary files created when save_latent_dynamics=TRUE see the $save_latent_dynamics_files() method.

output_dir

(string) A path to a directory where CmdStan should write its output CSV files. For interactive use this can typically be left at NULL (temporary directory) since CmdStanR makes the CmdStan output (posterior draws and diagnostics) available in R via methods of the fitted model objects. The behavior of output_dir is as follows:

  • If NULL (the default), then the CSV files are written to a temporary directory and only saved permanently if the user calls one of the ⁠$save_*⁠ methods of the fitted model object (e.g., $save_output_files()). These temporary files are removed when the fitted model object is garbage collected (manually or automatically).

  • If a path, then the files are created in output_dir with names corresponding to the defaults used by ⁠$save_output_files()⁠.

output_basename

(string) A string to use as a prefix for the names of the output CSV files of CmdStan. If NULL (the default), the basename of the output CSV files will be comprised from the model name, timestamp, and 5 random characters.

sig_figs

(positive integer) The number of significant figures used when storing the output values. By default, CmdStan represent the output values with 6 significant figures. The upper limit for sig_figs is 18. Increasing this value will result in larger output CSV files and thus an increased usage of disk space.

chains

(positive integer) The number of Markov chains to run. The default is 4.

parallel_chains

(positive integer) The maximum number of MCMC chains to run in parallel. If parallel_chains is not specified then the default is to look for the option "mc.cores", which can be set for an entire R session by options(mc.cores=value). If the "mc.cores" option has not been set then the default is 1.

chain_ids

(integer vector) A vector of chain IDs. Must contain as many unique positive integers as the number of chains. If not set, the default chain IDs are used (integers starting from 1).

threads_per_chain

(positive integer) If the model was compiled with threading support, the number of threads to use in parallelized sections within an MCMC chain (e.g., when using the Stan functions reduce_sum() or map_rect()). This is in contrast with parallel_chains, which specifies the number of chains to run in parallel. The actual number of CPU cores used is parallel_chains*threads_per_chain. For an example of using threading see the Stan case study Reduce Sum: A Minimal Example.

opencl_ids

(integer vector of length 2) The platform and device IDs of the OpenCL device to use for fitting. The model must be compiled with cpp_options = list(stan_opencl = TRUE) for this argument to have an effect.

iter_warmup

(positive integer) The number of warmup iterations to run per chain. Note: in the CmdStan User's Guide this is referred to as num_warmup.

iter_sampling

(positive integer) The number of post-warmup iterations to run per chain. Note: in the CmdStan User's Guide this is referred to as num_samples.

save_warmup

(logical) Should warmup iterations be saved? The default is FALSE.

thin

(positive integer) The period between saved samples. This should typically be left at its default (no thinning) unless memory is a problem.

max_treedepth

(positive integer) The maximum allowed tree depth for the NUTS engine. See the Tree Depth section of the CmdStan User's Guide for more details.

adapt_engaged

(logical) Do warmup adaptation? The default is TRUE. If a precomputed inverse metric is specified via the inv_metric argument (or metric_file) then, if adapt_engaged=TRUE, Stan will use the provided inverse metric just as an initial guess during adaptation. To turn off adaptation when using a precomputed inverse metric set adapt_engaged=FALSE.

adapt_delta

(real in ⁠(0,1)⁠) The adaptation target acceptance statistic.

step_size

(positive real) The initial step size for the discrete approximation to continuous Hamiltonian dynamics. This is further tuned during warmup.

metric

(string) One of "diag_e", "dense_e", or "unit_e", specifying the geometry of the base manifold. See the Euclidean Metric section of the CmdStan User's Guide for more details. To specify a precomputed (inverse) metric, see the inv_metric argument below.

metric_file

(character vector) The paths to JSON or Rdump files (one per chain) compatible with CmdStan that contain precomputed inverse metrics. The metric_file argument is inherited from CmdStan but is confusing in that the entry in JSON or Rdump file(s) must be named inv_metric, referring to the inverse metric. We recommend instead using CmdStanR's inv_metric argument (see below) to specify an inverse metric directly using a vector or matrix from your R session.

inv_metric

(vector, matrix) A vector (if metric='diag_e') or a matrix (if metric='dense_e') for initializing the inverse metric. This can be used as an alternative to the metric_file argument. A vector is interpreted as a diagonal metric. The inverse metric is usually set to an estimate of the posterior covariance. See the adapt_engaged argument above for details about (and control over) how specifying a precomputed inverse metric interacts with adaptation.

init_buffer

(nonnegative integer) Width of initial fast timestep adaptation interval during warmup.

term_buffer

(nonnegative integer) Width of final fast timestep adaptation interval during warmup.

window

(nonnegative integer) Initial width of slow timestep/metric adaptation interval.

fixed_param

(logical) When TRUE, call CmdStan with argument "algorithm=fixed_param". The default is FALSE. The fixed parameter sampler generates a new sample without changing the current state of the Markov chain; only generated quantities may change. This can be useful when, for example, trying to generate pseudo-data using the generated quantities block. If the parameters block is empty then using fixed_param=TRUE is mandatory. When fixed_param=TRUE the chains and parallel_chains arguments will be set to 1.

show_messages

(logical) When TRUE (the default), prints all output during the sampling process, such as iteration numbers and elapsed times. If the output is silenced then the $output() method of the resulting fit object can be used to display the silenced messages.

compile

(logical) Do compilation? The default is TRUE. If FALSE compilation can be done later via the $compile() method.

...

Optionally, additional arguments to pass to the $compile() method if compile=TRUE. These options include specifying the directory for saving the executable, turning on pedantic mode, specifying include paths, configuring C++ options, and more. See $compile() for details.

Details

To use within-chain parallelization, provide the following arguments:

1. 'cpp_options = list(stan_threads = TRUE)' to compile with threading

2. 'threads_per_chain' set to some integer value > 1.

Value

A list containing the model object, extracted posterior draws, and input data.

Examples

## Not run: 
captures <- system.file("extdata", "capture-example.csv", package = "mrmr") %>%
  readr::read_csv()
translocations <- system.file("extdata", "translocation-example.csv",
                              package = "mrmr") %>%
  readr::read_csv()
surveys <- system.file("extdata", "survey-example.csv", package = "mrmr") %>%
  readr::read_csv()
out <- clean_data(captures, surveys, translocations)

# fit a model with 4 chains, 2 threads per chain (to use 8 physical cores)
fit_model(
  data = out,
  chains = 4,
  parallel_chains = 4,
  cpp_options = list(stan_threads = TRUE),
  threads_per_chain = 2
)

## End(Not run)

SNARL1/mrmr documentation built on Nov. 23, 2023, 7:04 a.m.