Julia Interface#


Installation#

From JuliaRegistries#

BridgeStan is registered on JuliaRegistries each release.

] add BridgeStan

The first time you compile a model, the BridgeStan source code for your current version will be downloaded to a hidden directory in the users HOME directory. If you prefer to use a source distribution of BridgeStan, consult the following section.

Note that the system pre-requisites from the Getting Started guide are still required and will not be automatically installed by this method.

From Source#

This section assumes you have followed the Getting Started guide to install BridgeStan’s pre-requisites and downloaded a copy of the BridgeStan source code.

To install the Julia interface, you can either install it directly from Github by running the following inside a Julia REPL

] add https://github.com/roualdes/bridgestan.git:julia

Or, since you have already downloaded the repository, you can run

] dev julia/

from the BridgeStan folder.

To use the BridgeStan source you’ve manually downloaded instead of one the package will download for you, you must use set_bridgestan_path() or the $BRIDGESTAN environment variable.

Note that the Julia package depends on Julia 1.6+ and the Inflate package.

Example Program#

An example program is provided alongside the Julia interface code in example.jl:

Show example.jl
using BridgeStan

const BS = BridgeStan

# These paths are what they are because this example lives in a subfolder
# of the BridgeStan repository. If you're running this on your own, you
# will most likely want to delete the next line (to have BridgeStan
# download its sources for you) and change the paths on the following two
BS.set_bridgestan_path!("../")

bernoulli_stan = joinpath(@__DIR__, "../test_models/bernoulli/bernoulli.stan")
bernoulli_data = joinpath(@__DIR__, "../test_models/bernoulli/bernoulli.data.json")

smb = BS.StanModel(bernoulli_stan, bernoulli_data);

println("This model's name is $(BS.name(smb)).")
println("It has $(BS.param_num(smb)) parameters.")

x = rand(BS.param_unc_num(smb));
q = @. log(x / (1 - x)); # unconstrained scale

lp, grad = BS.log_density_gradient(smb, q, jacobian = false)

println("log_density and gradient of Bernoulli model: $((lp, grad))")

API Reference#

StanModel interface#

# BridgeStan.StanModelType.

StanModel(lib, data="", seed=204; stanc_args=[], make_args=[], warn=true)

A StanModel instance encapsulates a Stan model instantiated with data.

Construct a Stan model from the supplied library file path and data. If lib is a path to a file ending in .stan, this will first compile the model. Compilation occurs if no shared object file exists for the supplied Stan file or if a shared object file exists and the Stan file has changed since last compilation. This is equivalent to calling compile_model and then the constructor of StanModel. If warn is false, the warning about re-loading the same shared objects is suppressed.

Data should either be a string containing a JSON string literal, a path to a data file ending in .json, or the empty string.

If seed is supplied, it is used to initialize the RNG used by the model’s constructor.

source

# BridgeStan.log_densityFunction.

log_density(sm, q; propto=true, jacobian=true)

Return the log density of the specified unconstrained parameters.

This calculation drops constant terms that do not depend on the parameters if propto is true and includes change of variables terms for constrained parameters if jacobian is true.

source

# BridgeStan.log_density_gradientFunction.

log_density_gradient(sm, q; propto=true, jacobian=true)

Returns a tuple of the log density and gradient of the specified unconstrained parameters.

This calculation drops constant terms that do not depend on the parameters if propto is true and includes change of variables terms for constrained parameters if jacobian is true.

This allocates new memory for the gradient output each call. See log_density_gradient! for a version which allows re-using existing memory.

source

# BridgeStan.log_density_hessianFunction.

log_density_hessian(sm, q; propto=true, jacobian=true)

Returns a tuple of the log density, gradient, and Hessian of the specified unconstrained parameters.

This calculation drops constant terms that do not depend on the parameters if propto is true and includes change of variables terms for constrained parameters if jacobian is true.

This allocates new memory for the gradient and Hessian output each call. See log_density_hessian! for a version which allows re-using existing memory.

source

# BridgeStan.log_density_hessian_vector_productFunction.

log_density_hessian_vector_product(sm, q, v; propto=true, jacobian=true)

Returns log density and the product of the Hessian of the log density with the vector v at the specified unconstrained parameters.

This calculation drops constant terms that do not depend on the parameters if propto is true and includes change of variables terms for constrained parameters if jacobian is true.

This allocates new memory for the output each call. See log_density_hessian_vector_product! for a version which allows re-using existing memory.

source

# BridgeStan.param_constrainFunction.

param_constrain(sm, theta_unc, out; include_tp=false, include_gq=false, rng=nothing)

Returns a vector constrained parameters given unconstrained parameters. Additionally (if include_tp and include_gq are set, respectively) returns transformed parameters and generated quantities.

If include_gq is true, then rng must be provided. See StanRNG for details on how to construct RNGs.

This allocates new memory for the output each call. See param_constrain! for a version which allows re-using existing memory.

This is the inverse of param_unconstrain.

source

# BridgeStan.param_unconstrainFunction.

param_unconstrain(sm, theta)

Returns a vector of unconstrained params give the constrained parameters.

It is assumed that these will be in the same order as internally represented by the model (e.g., in the same order as param_unc_names()). If structured input is needed, use param_unconstrain_json

This allocates new memory for the output each call. See param_unconstrain! for a version which allows re-using existing memory.

This is the inverse of param_constrain.

source

# BridgeStan.param_unconstrain_jsonFunction.

param_unconstrain_json(sm, theta)

This accepts a JSON string of constrained parameters and returns the unconstrained parameters.

The JSON is expected to be in the JSON Format for CmdStan.

This allocates new memory for the output each call. See param_unconstrain_json! for a version which allows re-using existing memory.

source

# BridgeStan.nameFunction.

name(sm)

Return the name of the model sm

source

# BridgeStan.model_infoFunction.

model_info(sm)

Return information about the model sm.

This includes the Stan version and important compiler flags.

source

# BridgeStan.param_numFunction.

param_num(sm; include_tp=false, include_gq=false)

Return the number of (constrained) parameters in the model.

This is the total of all the sizes of items declared in the parameters block of the model. If include_tp or include_gq are true, items declared in the transformed parameters and generate quantities blocks are included, respectively.

source

# BridgeStan.param_unc_numFunction.

param_unc_num(sm)

Return the number of unconstrained parameters in the model.

This function is mainly different from param_num when variables are declared with constraints. For example, simplex[5] has a constrained size of 5, but an unconstrained size of 4.

source

# BridgeStan.param_namesFunction.

param_names(sm; include_tp=false, include_gq=false)

Return the indexed names of the (constrained) parameters, including transformed parameters and/or generated quantities as indicated.

For containers, indexes are separated by periods (.).

For example, the scalar a has indexed name "a", the vector entry a[1] has indexed name "a.1" and the matrix entry a[2, 3] has indexed names "a.2.3". Parameter order of the output is column major and more generally last-index major for containers.

source

# BridgeStan.param_unc_namesFunction.

param_unc_names(sm)

Return the indexed names of the unconstrained parameters.

For example, a scalar unconstrained parameter b has indexed name b and a vector entry b[3] has indexed name b.3.

source

# BridgeStan.log_density_gradient!Function.

log_density_gradient!(sm, q, out; propto=true, jacobian=true)

Returns a tuple of the log density and gradient of the specified unconstrained parameters.

This calculation drops constant terms that do not depend on the parameters if propto is true and includes change of variables terms for constrained parameters if jacobian is true.

The gradient is stored in the vector out, and a reference is returned. See log_density_gradient for a version which allocates fresh memory.

source

# BridgeStan.log_density_hessian!Function.

log_density_hessian!(sm, q, out_grad, out_hess; propto=true, jacobian=true)

Returns a tuple of the log density, gradient, and Hessian of the specified unconstrained parameters.

This calculation drops constant terms that do not depend on the parameters if propto is true and includes change of variables terms for constrained parameters if jacobian is true.

The gradient is stored in the vector out_grad and the Hessian is stored in out_hess and references are returned. See log_density_hessian for a version which allocates fresh memory.

source

# BridgeStan.log_density_hessian_vector_product!Function.

log_density_hessian_vector_product!(sm, q, v, out; propto=true, jacobian=true)

Returns log density and the product of the Hessian of the log density with the vector v at the specified unconstrained parameters.

This calculation drops constant terms that do not depend on the parameters if propto is true and includes change of variables terms for constrained parameters if jacobian is true.

The product is stored in the vector out and a reference is returned. See log_density_hessian_vector_product for a version which allocates fresh memory.

source

# BridgeStan.param_constrain!Function.

param_constrain!(sm, theta_unc, out; include_tp=false, include_gq=false, rng=nothing)

Returns a vector constrained parameters given unconstrained parameters. Additionally (if include_tp and include_gq are set, respectively) returns transformed parameters and generated quantities.

If include_gq is true, then rng must be provided. See StanRNG for details on how to construct RNGs.

The result is stored in the vector out, and a reference is returned. See param_constrain for a version which allocates fresh memory.

This is the inverse of param_unconstrain!.

source

# BridgeStan.param_unconstrain!Function.

param_unconstrain!(sm, theta, out)

Returns a vector of unconstrained params give the constrained parameters.

It is assumed that these will be in the same order as internally represented by the model (e.g., in the same order as param_names()). If structured input is needed, use param_unconstrain_json!

The result is stored in the vector out, and a reference is returned. See param_unconstrain for a version which allocates fresh memory.

This is the inverse of param_constrain!.

source

# BridgeStan.param_unconstrain_json!Function.

param_unconstrain_json!(sm, theta, out)

This accepts a JSON string of constrained parameters and returns the unconstrained parameters.

The JSON is expected to be in the JSON Format for CmdStan.

The result is stored in the vector out, and a reference is returned. See param_unconstrain_json for a version which allocates fresh memory.

source

# BridgeStan.StanRNGType.

StanRNG(sm::StanModel, seed)

Construct a StanRNG instance from a StanModel instance and a seed.

This can be used in the param_constrain and param_constrain! methods when using the generated quantities block.

This object is not thread-safe, one should be created per thread.

source

# BridgeStan.new_rngFunction.

new_rng(sm::StanModel, seed)

Construct a StanRNG instance from a StanModel instance and a seed. This function is a wrapper around the constructor StanRNG.

This can be used in the param_constrain and param_constrain! methods when using the generated quantities block.

The StanRNG object created is not thread-safe, one should be created per thread.

source

Compilation utilities#

# BridgeStan.compile_modelFunction.

compile_model(stan_file; stanc_args=[], make_args=[])

Run BridgeStan’s Makefile on a .stan file, creating the .so used by StanModel and return a path to the compiled library. Arguments to stanc3 can be passed as a vector, for example ["--O1"] enables level 1 compiler optimizations. Additional arguments to make can be passed as a vector, for example ["STAN_THREADS=true"] enables the model’s threading capabilities. If the same flags are defined in make/local, the versions passed here will take precedent.

This function checks that the path to BridgeStan is valid and will error if it is not. This can be set with set_bridgestan_path!().

source

# BridgeStan.get_bridgestan_pathFunction.

get_bridgestan_path() -> String

Return the path the the BridgeStan directory.

If the environment variable BRIDGESTAN is set, this will be returned. Otherwise, this function downloads a matching version of BridgeStan under a folder called .bridgestan in the user’s home directory.

See set_bridgestan_path!() to set the path from within Julia.

source

# BridgeStan.set_bridgestan_path!Function.

set_bridgestan_path!(path)

Set the path BridgeStan.

source