C API#


Installation#

Please follow the Getting Started guide to install TinyStan’s pre-requisites and downloaded a copy of the TinyStan source code.

This API is implemented in C++ and exposed to C using the extern "C" directive. It is used to implement all the other high-level interfaces. It can also be used for its own purposes, such as compiling to WebAssembly.

API Reference#

The following are the C functions exposed by the TinyStan library in tinystan.h. These are wrapped in the various high-level interfaces.

Functions

void tinystan_api_version(int *major, int *minor, int *patch)#

Get the version of the library.

Parameters:
  • major[out] The major version number.

  • minor[out] The minor version number.

  • patch[out] The patch version number.

void tinystan_stan_version(int *major, int *minor, int *patch)#

Get the version of Stan this library is built against.

Parameters:
  • major[out] The major version number.

  • minor[out] The minor version number.

  • patch[out] The patch version number

TinyStanModel *tinystan_create_model(const char *data, unsigned int seed, TinyStanError **err)#

Instantiate a model from JSON-encoded data.

Besides being an argument to the algorithm functions, the model can be used to query the names of the parameters and the number of free parameters. This is essential for constructing output buffers of appropriate size.

Parameters:
  • data[in] A path to a JSON file or a string containing JSON-encoded data. Can be NULL or an empty string if the model does not require data.

  • seed[in] Random seed.

  • err[out] Error information. Can be NULL.

Returns:

A pointer to the model. Must later be freed with tinystan_destroy_model(). Returns NULL on error.

void tinystan_destroy_model(TinyStanModel *model)#

Deallocate a model.

Parameters:

model[in] The model to deallocate.

const char *tinystan_model_param_names(const TinyStanModel *model)#

Get the names of the parameters.

Parameters:

model[in] The model.

Returns:

A string containing the names of the parameters, comma separated. Multidimensional parameters are flattened, e.g. “foo[2,3]” becomes 6 strings, starting with “foo.1.1”.

size_t tinystan_model_num_free_params(const TinyStanModel *model)#

Get the number of free parameters, i.e., those declared in the parameters block, not transformed parameters or generated quantities.

Parameters:

model[in] The model.

Returns:

The number of free parameters.

char tinystan_separator_char()#

Returns the separator character which must be used to provide multiple initialization files or json strings.

Currently, this is ASCII 0x1C, the file separator character.

int tinystan_sample(const TinyStanModel *model, size_t num_chains, const char *inits, unsigned int seed, unsigned int chain_id, double init_radius, int num_warmup, int num_samples, TinyStanMetric metric_choice, const double *init_inv_metric, bool adapt, double delta, double gamma, double kappa, double t0, unsigned int init_buffer, unsigned int term_buffer, unsigned int window, bool save_warmup, double stepsize, double stepsize_jitter, int max_depth, int refresh, int num_threads, double *out, size_t out_size, double *metric_out, TinyStanError **err)#

Run Stan’s No-U-Turn Sampler (NUTS) to sample from the posterior.

A wrapper around several functions in the stan::services::sample namespace. Same-named arguments should be interpreted as having the same meaning as in the Stan documentation.

Parameters:
  • model[in] The TinyStanModel to use for the sampling.

  • num_chains[in] The number of chains to run.

  • inits[in] Initial parameter values. This should be a path to a JSON file or a JSON string. If num_chains is greater than 1, this can be a list of paths or JSON strings separated by the separator character returned by tinystan_separator_char().

  • seed[in] The seed to use for the random number generator.

  • chain_id[in] Chain ID for the first chain.

  • init_radius[in] Radius to initialize unspecified parameters within.

  • num_warmup[in] Number of warmup iterations to run.

  • num_samples[in] Number of samples to draw after warmup.

  • metric_choice[in] The type of mass matrix to use in the sampler.

  • init_inv_metric[in] Initial value for the mass matrix used by the sampler. Depending on metric_choice, this should be a flattened matrix for a dense metric, or a vector for a diagonal one. If NULL, the sampler will use the identity matrix.

  • adapt[in] Whether the sampler should adapt the step size and metric.

  • delta[in] Target average acceptance probability.

  • gamma[in] Adaptation regularization scale.

  • kappa[in] Adaptation relaxation exponent.

  • t0[in] Adaptation iteration offset.

  • init_buffer[in] Number of warmup samples to use for initial step size adaptation.

  • term_buffer[in] Number of warmup samples to use for step size adaptation after the metric is adapted.

  • window[in] Initial number of iterations to use for metric adaptation.

  • save_warmup[in] Whether to save the warmup samples.

  • stepsize[in] Initial step size for the sampler.

  • stepsize_jitter[in] Amount of random jitter to add to the step size.

  • max_depth[in] Maximum tree depth for the sampler.

  • refresh[in] Number of iterations between progress messages.

  • num_threads[in] Number of threads to use for sampling.

  • out[out] Buffer to store the samples. The buffer should be large enough to store num_chains * (num_samples + save_warmup * num_warmup) * num_params doubles.

  • out_size[in] Size of the buffer in doubles. Used for bounds checking unless TINYSTAN_NO_BOUNDS_CHECK is defined, in which case it is ignored.

  • metric_out[out] Buffer to store the metric. Can be NULL. If non-NULL, the buffer should be large enough to store tinystan_model_num_free_params() doubles if using a diagonal matrix, and the free parameters squared if using a dense one.

  • err[out] Error information. Can be NULL.

Returns:

Zero on success, non-zero on error. If an error occurs, err will be set to a non-NULL value which must be freed with tinystan_destroy_error().

int tinystan_pathfinder(const TinyStanModel *model, size_t num_paths, const char *inits, unsigned int seed, unsigned int id, double init_radius, int num_draws, int max_history_size, double init_alpha, double tol_obj, double tol_rel_obj, double tol_grad, double tol_rel_grad, double tol_param, int num_iterations, int num_elbo_draws, int num_multi_draws, bool calculate_lp, bool psis_resample, int refresh, int num_threads, double *out, size_t out_size, TinyStanError **err)#

Run the Pathfinder algorithm to approximate the posterior.

A wrapper around the functions in the stan::services::pathfinder namespace. Same-named arguments should be interpreted as having the same meaning as in the Stan documentation.

Parameters:
  • model[in] The TinyStanModel to use for the sampling.

  • num_paths[in] The number of individual runs of the algorithm to run in parallel.

  • inits[in] Initial parameter values. This should be a path to a JSON file or a JSON string. If num_paths is greater than 1, this can be a list of paths or JSON strings separated by the separator character returned by tinystan_separator_char().

  • seed[in] The seed to use for the random number generator.

  • id[in] ID for the first path.

  • init_radius[in] Radius to initialize unspecified parameters within.

  • num_draws[in] Number of approximate draws drawn from each of the num_paths Pathfinders.

  • max_history_size[in] History size used by the internal L-BFGS algorithm to approximate the Hessian.

  • init_alpha[in] Initial step size for the internal L-BFGS algorithm.

  • tol_obj[in] Convergence tolerance for the objective function for the internal L-BFGS algorithm.

  • tol_rel_obj[in] Relative convergence tolerance for the objective function for the internal L-BFGS algorithm.

  • tol_grad[in] Convergence tolerance for the gradient norm for the internal L-BFGS algorithm.

  • tol_rel_grad[in] Relative convergence tolerance for the gradient norm for the internal L-BFGS algorithm.

  • tol_param[in] Convergence tolerance for the changes in parameters for the internal L-BFGS algorithm.

  • num_iterations[in] Maximum number of iterations for the internal L-BFGS algorithm.

  • num_elbo_draws[in] Number of Monte Carlo draws used to estimate the ELBO.

  • num_multi_draws[in] Number of draws returned by Multi-Pathfinder.

  • calculate_lp[in] Whether to calculate the log probability of the approximate draws.

  • psis_resample[in] Whether to use Pareto smoothed importance sampling on the approximate draws.

  • refresh[in] Number of iterations between progress messages.

  • num_threads[in] Number of threads to use for Pathfinder.

  • out[out] Buffer to store the samples. The buffer should be large enough to store num_multi_draws doubles if psis_resample is true, or num_paths * num_draws doubles otherwise.

  • out_size[in] Size of the buffer in doubles. Used for bounds checking unless TINYSTAN_NO_BOUNDS_CHECK is defined, in which case it is ignored.

  • err[out] Error information. Can be NULL.

Returns:

Zero on success, non-zero on error. If an error occurs, err will be set to a non-NULL value which must be freed with tinystan_destroy_error().

int tinystan_optimize(const TinyStanModel *model, const char *init, unsigned int seed, unsigned int id, double init_radius, TinyStanOptimizationAlgorithm algorithm, int num_iterations, bool jacobian, int max_history_size, double init_alpha, double tol_obj, double tol_rel_obj, double tol_grad, double tol_rel_grad, double tol_param, int refresh, int num_threads, double *out, size_t out_size, TinyStanError **err)#

Optimize the model parameters using the specified algorithm.

A wrapper around the functions in the stan::services::optimize namespace. Same-named arguments should be interpreted as having the same meaning as in the Stan documentation.

Parameters:
  • model[in] The TinyStanModel to use for the optimization.

  • init[in] Initial parameter values. This should be a path to a JSON file or a JSON string.

  • seed[in] The seed to use for the random number generator.

  • id[in] ID used to offset the random number generator.

  • init_radius[in] Radius to initialize unspecified parameters within.

  • algorithm[in] Which optimization algorithm to use. Some of the following arguments may be ignored depending on the algorithm.

  • num_iterations[in] Maximum number of iterations to run the optimization.

  • jacobian[in] Whether to apply the Jacobian change of variables to the log density. If False, the algorithm will find the MLE. If True, the algorithm will find the MAP estimate.

  • max_history_size[in] History size used to approximate the Hessian.

  • init_alpha[in] Initial step size.

  • tol_obj[in] Convergence tolerance for the objective function.

  • tol_rel_obj[in] Relative convergence tolerance for the objective function.

  • tol_grad[in] Convergence tolerance for the gradient norm.

  • tol_rel_grad[in] Relative convergence tolerance for the gradient norm.

  • tol_param[in] Convergence tolerance for the changes in parameters.

  • refresh[in] Number of iterations between progress messages.

  • num_threads[in] Number of threads to use for log density evaluations.

  • out[out] Buffer to store the samples. The buffer should be large enough to store num_params doubles.

  • out_size[in] Size of the buffer in doubles. Used for bounds checking unless TINYSTAN_NO_BOUNDS_CHECK is defined, in which case it is ignored.

  • err[out] Error information. Can be NULL.

Returns:

Zero on success, non-zero on error. If an error occurs, err will be set to a non-NULL value which must be freed with tinystan_destroy_error().

int tinystan_laplace_sample(const TinyStanModel *tmodel, const double *theta_hat_constr, const char *theta_hat_json, unsigned int seed, int num_draws, bool jacobian, bool calculate_lp, int refresh, int num_threads, double *out, size_t out_size, double *hessian_out, TinyStanError **err)#

Sample from the Laplace approximation of the posterior centered at the provided mode.

A wrapper around the functions in the stan::services::laplace_sample namespace.

Parameters:
  • tmodel[in] The TinyStanModel to use for the sampling.

  • theta_hat_constr[in] The mode to center the Laplace approximation on. This should be a pointer to an array of doubles on the constrained scale, like the one returned by tinystan_optimize(). At most one of theta_hat_constr and theta_hat_json should be non-NULL.

  • theta_hat_json[in] A path to a JSON file or JSON string representing the mode on the constrained scale. At most one of theta_hat_constr and theta_hat_json should be non-NULL.

  • seed[in] The seed to use for the random number generator.

  • num_draws[in] Number of draws.

  • jacobian[in] Whether to apply the Jacobian change of variables to the log density. Note: This should match the value used when the mode was calculated.

  • calculate_lp[in] Whether to calculate the log probability of the samples.

  • refresh[in] Number of iterations between progress messages.

  • num_threads[in] Number of threads to use for log density evaluations.

  • out[out] Buffer to store the samples. The buffer should be large enough to store num_draws * num_params doubles.

  • out_size[in] Size of the buffer in doubles. Used for bounds checking unless TINYSTAN_NO_BOUNDS_CHECK is defined, in which case it is ignored.

  • hessian_out[out] Buffer to store the Hessian matrix calculated at the mode. Can be NULL.

  • err[out] Error information. Can be NULL.

Returns:

Zero on success, non-zero on error. If an error occurs, err will be set to a non-NULL value which must be freed with tinystan_destroy_error().

const char *tinystan_get_error_message(const TinyStanError *err)#

Get the error message from an error object.

Parameters:

err[in] The error object.

Returns:

The error message. Will be freed when the error object is freed, so copy it if you need it later.

TinyStanErrorType tinystan_get_error_type(const TinyStanError *err)#

Get the type of error.

Parameters:

err[in] The error object.

Returns:

The type of error. This is intended to provide more information about the kind of error, allowing for more specific handling. For example, the interrupt value can be used to distinguish between a user interrupt and a generic error.

void tinystan_destroy_error(TinyStanError *err)#

Free the error object.

Note

This will invalidate any pointers returned by tinystan_get_error_message().

Parameters:

err[in] The error object.

void tinystan_set_print_callback(TINYSTAN_PRINT_CALLBACK print)#

Set the callback function for printing messages. If this is not set, messages will be printed to stdout.

Parameters:

print[in] The callback function.

Typedefs

typedef struct TinyStanError TinyStanError#

Opaque type for errors.

Functions in TinyStan that can fail will accept a nullable TinyStanError** argument as their last parameter.

In addition to returning an integer status code (most functions), or NULL (allocation functions), they can also set this argument to a new error object if it itself was not NULL. This must be freed with tinystan_destroy_error() when no longer needed. The error object contains a message describing the error which can be retrieved with tinystan_get_error_message(), and and a type field that can be used to distinguish between different kinds of errors which can be retrieved with tinystan_get_error_type()

typedef struct TinyStanModel TinyStanModel#

Opaque type for models.

typedef void (*TINYSTAN_PRINT_CALLBACK)(const char *msg, size_t len, bool bad)#

Callback used for printing.

Param msg:

[in] The message to print.

Param len:

[in] The length of the message.

Param bad:

[in] Whether the message is an error message or not

Enums

enum TinyStanMetric#

Choice of metric for HMC.

Values:

enumerator unit#
enumerator dense#
enumerator diagonal#
enum TinyStanOptimizationAlgorithm#

Choice of optimization algorithm.

Values:

enumerator newton#
enumerator bfgs#
enumerator lbfgs#
enum TinyStanErrorType#

An enum representing different kinds of errors TinyStan can generate.

Values:

enumerator generic#

A generic runtime error from Stan.

enumerator config#

An invalid configuration for the algorithm.

enumerator interrupt#

The user interrupted the algorithm with Ctrl+C.