### Build and Run Example (Dynamic Linking) Source: https://github.com/roualdes/bridgestan/blob/main/c-example/README.md Compiles and runs a C example that dynamically links against a BridgeStan model. This is the default behavior when running 'make example'. ```shell make example ./example ``` -------------------------------- ### Install bridgestan from GitHub Source: https://github.com/roualdes/bridgestan/blob/main/R/README.md Install the bridgestan package directly from its GitHub repository. Ensure the 'remotes' package is installed. ```r remotes::install_github("https://github.com/roualdes/bridgestan", subdir="R") ``` -------------------------------- ### Install Bridgestan from Source Source: https://github.com/roualdes/bridgestan/blob/main/python/README.md Install bridgestan from a local clone of the repository. Ensure you have already cloned the repository before running these commands. ```shell cd python/ # this directory pip install -e . ``` -------------------------------- ### Install bridgestan from Local Repository Source: https://github.com/roualdes/bridgestan/blob/main/R/README.md Install the bridgestan package from a downloaded source repository. Navigate to the 'R/' directory before running the command. ```r # from folder R/ install.packages(getwd(), repos=NULL, type="source") ``` -------------------------------- ### Build and Run Static Linking Example Source: https://github.com/roualdes/bridgestan/blob/main/c-example/README.md Compiles and runs a C example that statically links against a BridgeStan model. This creates an executable independent of the model's shared library location. ```shell make example_static rm ../test_models/full/full_model.a # statically linked executable doesn't need library around ./example_static ``` -------------------------------- ### Install Bridgestan from PyPI Source: https://github.com/roualdes/bridgestan/blob/main/python/README.md Use this command to install the latest stable version of bridgestan from the Python Package Index. ```shell pip install bridgestan ``` -------------------------------- ### Build and Run Example with Specific Model (Dynamic Linking) Source: https://github.com/roualdes/bridgestan/blob/main/c-example/README.md Compiles and runs a C example dynamically linking against a specific BridgeStan model specified by the MODEL variable. It also shows how to pass a data file path to the model. ```shell make MODEL=multi example ./example ../test_models/multi/multi.data.json ``` -------------------------------- ### Example Program in Julia Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Demonstrates how to load a Stan model, set paths, and compute log density and gradient using the BridgeStan Julia interface. This example requires BridgeStan to be set up in the parent directory. ```julia 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))") ``` -------------------------------- ### Example Rust Program for BridgeStan Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/rust.md A complete example program demonstrating the usage of the BridgeStan Rust client. This program showcases how to compile and run models. ```Rust use std::error::Error; fn main() -> Result<(), Box> { // Example usage of the bridgestan crate // This is a placeholder and should be replaced with actual model compilation and execution logic. println!("BridgeStan Rust example running..."); // In a real scenario, you would: // 1. Define or load your Stan model. // 2. Compile the model using bridgestan::compile_model(...). // 3. Run the compiled model with data using bridgestan::run_model(...). Ok(()) } ``` -------------------------------- ### Build and Run Runtime Loading Example Source: https://github.com/roualdes/bridgestan/blob/main/c-example/README.md Compiles and runs a C example that loads a BridgeStan model at runtime using dynamic library loading functions (dlfcn.h on Unix, libloaderapi.h on Windows). This allows loading different models without recompiling. ```shell make example_runtime # unlike above, this did not automatically build a model, since it # was not needed to _build_, but we still need one to _run_ the program make ../test_models/full/full_model.so ./example_runtime ../test_models/full/full_model.so ``` -------------------------------- ### Install bridgestan from R-Multiverse Mirror Source: https://github.com/roualdes/bridgestan/blob/main/R/README.md Install the bridgestan package from the R-Multiverse mirror. This method ensures you get the latest community-maintained version. ```r install.packages( "bridgestan", repos = c("https://community.r-multiverse.org", getOption("repos")) ) ``` -------------------------------- ### Example Program for BridgeStan Julia Interface Source: https://github.com/roualdes/bridgestan/blob/main/julia/docs/src/julia.md This is an example program demonstrating the usage of the BridgeStan Julia interface. It showcases how to load and interact with a Stan model. ```julia using StanModel using BridgeStan # Load the Stan model stan_model = StanModel("example.stan") # Get model information println(model_info(stan_model)) # Get parameter names println(param_names(stan_model)) # Initialize parameters init_params = param_initialize(stan_model) println("Initial parameters: ", init_params) # Constrain parameters to the model's support constrained_params = param_constrain(stan_model, init_params) println("Constrained parameters: ", constrained_params) # Unconstrain parameters unconstrained_params = param_unconstrain(stan_model, constrained_params) println("Unconstrained parameters: ", unconstrained_params) # Calculate log density log_density_val = log_density(stan_model, unconstrained_params) println("Log density: ", log_density_val) # Calculate log density and gradient log_density_grad, grad = log_density_gradient(stan_model, unconstrained_params) println("Log density gradient: ", log_density_grad) println("Gradient: ", grad) # Calculate log density and Hessian log_density_hess, hess = log_density_hessian(stan_model, unconstrained_params) println("Log density Hessian: ", log_density_hess) println("Hessian: ", hess) # Calculate log density and Hessian-vector product vec = rand(param_unc_num(stan_model)) log_density_hv, hv = log_density_hessian_vector_product(stan_model, unconstrained_params, vec) println("Log density Hessian-vector product: ", log_density_hv) println("Hessian-vector product: ", hv) # Use a new random number generator stan_rng = StanRNG(stan_model) new_rng_val = new_rng(stan_rng) println("New RNG value: ", new_rng_val) # In-place operations (modify parameters directly) println("\n--- In-place operations ---") # Initialize parameters in-place param_initialize!(stan_model) println("Initialized parameters (in-place): ", stan_model.init_params) # Constrain parameters in-place param_constrain!(stan_model, stan_model.init_params) println("Constrained parameters (in-place): ", stan_model.init_params) # Unconstrain parameters in-place param_unconstrain!(stan_model, stan_model.init_params) println("Unconstrained parameters (in-place): ", stan_model.init_params) # Calculate log density and gradient in-place log_density_gradient!(stan_model, stan_model.init_params) println("Log density gradient (in-place): ", stan_model.log_density, " Gradient: ", stan_model.grad) # Calculate log density and Hessian in-place log_density_hessian!(stan_model, stan_model.init_params) println("Log density Hessian (in-place): ", stan_model.log_density, " Hessian: ", stan_model.hess) # Calculate log density and Hessian-vector product in-place param_unc_num_val = param_unc_num(stan_model) vec_inplace = rand(param_unc_num_val) log_density_hessian_vector_product!(stan_model, stan_model.init_params, vec_inplace) println("Log density Hessian-vector product (in-place): ", stan_model.log_density, " Hessian-vector product: ", stan_model.hess_vec) # Constrain parameters in-place (using a different set of parameters) new_params_to_constrain = param_initialize(stan_model) param_constrain!(stan_model, new_params_to_constrain) println("Constrained parameters (in-place, new set): ", new_params_to_constrain) # Unconstrain parameters in-place (using a different set of parameters) new_params_to_unconstrain = param_constrain(stan_model, init_params) param_unconstrain!(stan_model, new_params_to_unconstrain) println("Unconstrained parameters (in-place, new set): ", new_params_to_unconstrain) # Unconstrain parameters to JSON format in-place param_unconstrain_json!(stan_model, stan_model.init_params) println("Unconstrained parameters JSON (in-place): ", stan_model.init_params_json) # Initialize parameters in-place with a specific RNG stan_rng_init = StanRNG(stan_model) param_initialize!(stan_model, stan_rng_init) println("Initialized parameters with RNG (in-place): ", stan_model.init_params) ``` -------------------------------- ### Install BridgeStan from Local Source Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/python.md Install the BridgeStan Python package from a local source directory using pip in editable mode. This is useful after cloning the repository. ```shell pip install -e python/ ``` -------------------------------- ### Install BridgeStan from Source (GitHub) Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/python.md Install the BridgeStan Python package directly from its GitHub repository using pip. This is useful if you want the latest development version. ```shell pip install "git+https://github.com/roualdes/bridgestan.git#egg=bridgestan&subdirectory=python" ``` -------------------------------- ### Install BridgeStan R Package from Source Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/r.md Install the R package from local source code after downloading BridgeStan. This command should be run from within the BridgeStan source folder. ```R install.packages(file.path(getwd(),"R"), repos=NULL, type="source") ``` -------------------------------- ### Example C Program for Linking Models Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/c-api.rst This C code demonstrates how to link a specific Stan model directly into a program using the BridgeStan C API. It requires building the example program with the provided Makefile. ```c #include #include #include int main(int argc, char **argv) { // Initialize BridgeStan bs_init(); // Load the model (replace "model.stan" with your model file) bs_model_t *model = bs_model_load("model.stan"); if (!model) { fprintf(stderr, "Error loading model\n"); return 1; } // Create a new ODE solver (example) bs_ode_solver_t *solver = bs_ode_solver_create(model); if (!solver) { fprintf(stderr, "Error creating ODE solver\n"); bs_model_destroy(model); return 1; } // Example: Set parameters (replace with actual parameter values) double params[] = {1.0, 2.0, 3.0}; bs_set_param_array(model, params, 3); // Example: Set initial conditions (replace with actual initial conditions) double init[] = {0.1, 0.2}; bs_set_var_array(model, init, 2); // Example: Solve ODE (replace with actual time points) double t[] = {0.0, 1.0, 2.0}; double *ode_solution = bs_ode_solve(solver, t, 3); if (!ode_solution) { fprintf(stderr, "Error solving ODE\n"); bs_ode_solver_destroy(solver); bs_model_destroy(model); return 1; } // Process the solution (example: print first time point) printf("Solution at t=%.2f: ", t[0]); for (int i = 0; i < bs_num_vars(model); ++i) { printf("%.4f ", ode_solution[i]); } printf("\n"); // Clean up free(ode_solution); bs_ode_solver_destroy(solver); bs_model_destroy(model); bs_shutdown(); return 0; } ``` -------------------------------- ### Add BridgeStan from GitHub Source: https://github.com/roualdes/bridgestan/blob/main/julia/docs/src/julia.md Installs the BridgeStan package directly from its GitHub repository. Use this if you want to install a specific version or the development version. ```julia ] add https://github.com/roualdes/bridgestan.git:julia ``` -------------------------------- ### Install BridgeStan from General Registry Source: https://github.com/roualdes/bridgestan/blob/main/julia/README.md Use this command to add the BridgeStan package from the Julia General Registry. ```julia ] add BridgeStan ``` -------------------------------- ### Example BridgeStan Python Program Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/python.md An example Python script demonstrating how to use the BridgeStan library to compile a Stan model, set its path, and compute the log density and gradient. ```python import numpy as np import bridgestan as bs # 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(".." stan = "../test_models/bernoulli/bernoulli.stan" data = "../test_models/bernoulli/bernoulli.data.json" model = bs.StanModel(stan, data) print(f"This model's name is {model.name()}.") print(f"It has {model.param_num()} parameters.") x = np.random.random(model.param_unc_num()) q = np.log(x / (1 - x)) # unconstrained scale lp, grad = model.log_density_gradient(q, jacobian=False) print(f"log_density and gradient of Bernoulli model: {(lp, grad)}") ``` -------------------------------- ### Develop BridgeStan Julia Interface from Local Source Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Install the Julia interface using a local copy of the BridgeStan source code. This is useful if you have already cloned the repository and want to develop the Julia interface. ```julia ] dev julia/ ``` -------------------------------- ### Install BridgeStan from Local Repository Source: https://github.com/roualdes/bridgestan/blob/main/julia/README.md Use this command to develop the BridgeStan package locally from a cloned repository. Ensure you are in the 'julia/' directory of the cloned repository. ```julia # from folder julia/ ] dev . ``` -------------------------------- ### Example C Program for Runtime Model Loading Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/c-api.rst This C code demonstrates loading a Stan model at runtime using the BridgeStan C API. This approach is flexible as it does not require recompiling the program when the model changes. ```c #include #include #include int main(int argc, char **argv) { // Initialize BridgeStan bs_init(); // Load the model at runtime (replace "model.stan" with your model file) bs_model_t *model = bs_model_load("model.stan"); if (!model) { fprintf(stderr, "Error loading model\n"); return 1; } // Create a new ODE solver (example) bs_ode_solver_t *solver = bs_ode_solver_create(model); if (!solver) { fprintf(stderr, "Error creating ODE solver\n"); bs_model_destroy(model); return 1; } // Example: Set parameters (replace with actual parameter values) double params[] = {1.0, 2.0, 3.0}; bs_set_param_array(model, params, 3); // Example: Set initial conditions (replace with actual initial conditions) double init[] = {0.1, 0.2}; bs_set_var_array(model, init, 2); // Example: Solve ODE (replace with actual time points) double t[] = {0.0, 1.0, 2.0}; double *ode_solution = bs_ode_solve(solver, t, 3); if (!ode_solution) { fprintf(stderr, "Error solving ODE\n"); bs_ode_solver_destroy(solver); bs_model_destroy(model); return 1; } // Process the solution (example: print first time point) printf("Solution at t=%.2f: ", t[0]); for (int i = 0; i < bs_num_vars(model); ++i) { printf("%.4f ", ode_solution[i]); } printf("\n"); // Clean up free(ode_solution); bs_ode_solver_destroy(solver); bs_model_destroy(model); bs_shutdown(); return 0; } ``` -------------------------------- ### Set BridgeStan Installation Path Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/set_bridgestan_path.md Use this function to specify the directory where BridgeStan is installed. Ensure the path points to the top-level folder of the BridgeStan repository. ```r set_bridgestan_path(path) ``` -------------------------------- ### Add BridgeStan Package Source: https://github.com/roualdes/bridgestan/blob/main/julia/docs/src/julia.md Installs the BridgeStan package from JuliaRegistries. This is the recommended method for most users. ```julia ] add BridgeStan ``` -------------------------------- ### Develop BridgeStan from Local Source Source: https://github.com/roualdes/bridgestan/blob/main/julia/docs/src/julia.md Installs the BridgeStan package using a local source code checkout. This is useful if you have already downloaded the BridgeStan repository and want to develop or test it. ```julia ] dev julia/ ``` -------------------------------- ### Compile a Test Model with Make Source: https://github.com/roualdes/bridgestan/blob/main/docs/getting-started.md After cloning the repository, run this command to test your BridgeStan installation by compiling a sample Stan model. This requires internet access for the first run to download the Stan compiler. ```shell make test_models/multi/multi_model.so ``` -------------------------------- ### Add BridgeStan Julia Interface from GitHub Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Install the Julia interface directly from the BridgeStan GitHub repository. This method is useful if you want to use the latest development version. Ensure you have downloaded the BridgeStan source code first. ```julia ] add https://github.com/roualdes/bridgestan.git:julia ``` -------------------------------- ### BridgeStan.set_bridgestan_path! Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Sets the path for the BridgeStan installation. ```APIDOC ## `BridgeStan.set_bridgestan_path!` ### Description Set the path BridgeStan. ### Method ```julia set_bridgestan_path!(path) ``` ### Parameters #### Path Parameters - **path** (string) - Required - The path to set for BridgeStan. ``` -------------------------------- ### Clone BridgeStan Repository with Git Source: https://github.com/roualdes/bridgestan/blob/main/docs/getting-started.md Use this command to download the latest version of BridgeStan and its submodules if you have git installed. The shallow clone options reduce download size. ```shell git clone --recurse-submodules --shallow-submodules --depth=1 https://github.com/roualdes/bridgestan.git ``` -------------------------------- ### set_bridgestan_path() Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/set_bridgestan_path.md Sets the path to the BridgeStan installation directory. This path should point to the root folder of the BridgeStan repository. ```APIDOC ## set_bridgestan_path() ### Description Set the path to BridgeStan. ### Details This should point to the top-level folder of the repository. ### Parameters #### Path Parameters * **path** (string) - Required - The file path to the BridgeStan installation directory. ``` -------------------------------- ### Add BridgeStan Crate Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/rust.md Install the BridgeStan Rust client using Cargo. Ensure you have the BridgeStan C++ sources available, either by using the 'download-bridgestan-src' feature or by downloading them manually. ```shell cargo add bridgestan ``` -------------------------------- ### Get StanModel compile information Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Retrieves information about the compilation of the Stan model, including the Stan version and flags. ```R StanModel$model_info() ``` -------------------------------- ### Get Model Information Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Retrieves information about the Stan model, including the Stan version and compiler flags. ```julia model_info(sm) ``` -------------------------------- ### Get Indexed Names of Unconstrained Parameters Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Returns the indexed names of unconstrained parameters. For example, an unconstrained scalar 'b' has name 'b', and a vector entry 'b[3]' has name 'b.3'. ```julia param_unc_names(sm) ``` -------------------------------- ### Initialize Parameters Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Initializes parameters, allowing for incomplete specifications. Unspecified parameters are randomly selected within a given radius. The resulting point is checked for a finite log density. ```julia param_initialize(sm, rng, theta=""; init_radius=2.0, max_tries=100, jacobian=true) ``` -------------------------------- ### Initialize Parameters Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Initializes parameters, allowing for incomplete JSON specifications. Unspecified parameters are randomly sampled. The resulting point is checked for a finite log density, with retries up to a specified limit. ```julia param_initialize!(sm, rng, out, theta="{}"; init_radius=2.0, max_tries=100, jacobian=true) ``` -------------------------------- ### Instantiate and Use a StanModel in R Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/r.md Demonstrates how to load a Stan model, retrieve its properties, and calculate log density and gradient. Ensure you are in the 'bridgestan/R' directory before running. ```R # Before running this, make sure you are in the directory bridgestan/R library(bridgestan) model <- StanModel$new( "../test_models/bernoulli/bernoulli.stan", "../test_models/bernoulli/bernoulli.data.json", 1234 ) print(paste0("This model's name is ", model$name(), ".")) print(paste0("This model has ", model$param_num(), " parameters.")) x <- runif(model$param_unc_num()) q <- log(x / (1 - x)) res <- model$log_density_gradient(q, jacobian = FALSE) print(paste0( "log_density and gradient of Bernoulli model: ", res$val, ", ", res$gradient )) ``` -------------------------------- ### Get Model Name Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Retrieves the name of the Stan model. ```julia name(sm) ``` -------------------------------- ### Get the name of the StanModel Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Retrieves the name of the compiled Stan model. ```R StanModel$name() ``` -------------------------------- ### Initialize Model Parameters Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Initializes a point in the unconstrained parameter space. Parameters not specified in the JSON are randomized within [-init_radius, init_radius). Retries up to max_tries to find a point with finite log density. ```r StanModel$param_initialize( rng, json = "{}, init_radius = 2, max_tries = 100, jacobian = TRUE ) ``` -------------------------------- ### Get BridgeStan version used in the model Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Retrieves the version of BridgeStan that was used to compile the model. ```R StanModel$model_version() ``` -------------------------------- ### Run Julia Tests Source: https://github.com/roualdes/bridgestan/blob/main/docs/internals/testing.md Runs the Julia tests using the built-in unit testing library. This command should be executed from the project root. ```shell julia --project=./julia -t 2 -e "using Pkg; Pkg.test()" ``` -------------------------------- ### Get Reference to Stan Library Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_rust/bridgestan/lib.md Returns an immutable reference to the underlying Stan library associated with the model. ```rust pub fn ref_library(&self) -> &StanLibrary ``` -------------------------------- ### Initialize Parameters from JSON in R Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/r.md Sets an initial point in the unconstrained parameter space using values from a JSON string, randomizing unspecified parameters. It ensures the initialized point has a finite log density. ```r StanModel$param_initialize( rng, json = "{}", init_radius = 2, max_tries = 100, jacobian = TRUE ) ``` -------------------------------- ### Get Model Name Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_rust/bridgestan/lib.md Retrieves the name of the Stan model. Returns an error if UTF decoding fails. ```rust pub fn name(&self) -> Result<&str> ``` -------------------------------- ### Compile and Use a Stan Model in Rust Source: https://github.com/roualdes/bridgestan/blob/main/rust/README.md Demonstrates how to compile a Stan model using the `compile_model` function, load the compiled library, and then evaluate the log density and its gradient. Ensure the BridgeStan source path is correctly set or the `download-bridgestan-src` feature is enabled. ```rust use std::ffi::CString; use std::path::{Path, PathBuf}; use bridgestan::{BridgeStanError, Model, open_library, compile_model}; // The path to the Stan model let path = Path::new(env!["CARGO_MANIFEST_DIR"]) .parent() .unwrap() .join("test_models/simple/simple.stan"); // You can manually set the BridgeStan src path or // automatically download it (but remember to // enable the download-bridgestan-src feature first) let bs_path: PathBuf = "..".into(); // let bs_path = bridgestan::download_bridgestan_src().unwrap(); // The path to the compiled model let path = compile_model(&bs_path, &path, &[], &[]).expect("Could not compile Stan model."); println!("Compiled model: {:?}", path); let lib = open_library(path).expect("Could not load compiled Stan model."); // The dataset as json let data = r#"{"N": 7}"#; let data = CString::new(data.to_string().into_bytes()).unwrap(); // The seed is used in case the model contains a transformed data section // that uses rng functions. let seed = 42; let model = match Model::new(&lib, Some(data), seed) { Ok(model) => model, Err(BridgeStanError::ConstructFailed(msg)) => { panic!("Model initialization failed. Error message from Stan was {msg}") } Err(e) => { panic!("Unexpected error:\n{e}") } }; let n_dim = model.param_unc_num(); assert_eq!(n_dim, 7); let point = vec![1f64; n_dim]; let mut gradient_out = vec![0f64; n_dim]; let logp = model.log_density_gradient(&point[..], true, true, &mut gradient_out[..]) .expect("Stan failed to evaluate the logp function."); // gradient_out contains the gradient of the logp density ``` -------------------------------- ### Get indexed names of unconstrained parameters Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Returns the indexed names of unconstrained parameters. Parameter names are period-separated for containers. ```R StanModel$param_unc_names() ``` -------------------------------- ### Run R Tests Source: https://github.com/roualdes/bridgestan/blob/main/docs/internals/testing.md Navigates to the R directory and executes R tests using devtools::test(). This is a basic test suite compared to Python or Julia. ```shell cd R/ Rscript -e "devtools::test()" ``` -------------------------------- ### BridgeStan.param_initialize! Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Initializes parameters, allowing for incomplete specifications via JSON. Unspecified parameters are randomly sampled. The resulting point is checked for a finite log density. ```APIDOC ## `BridgeStan.param_initialize!` ### Description Similar to [`param_unconstrain_json!`](#BridgeStan.param_unconstrain_json!) but allows for incomplete specifications of the parameters. Any parameter not specified in the provided JSON will be randomly selected uniformly from `[-init_radius, init_radius)`. The resulting point will be checked for a finite log density value, and retried up to the specified number of times. If all such retries fail, an error is raised. The JSON is expected to be in the [JSON Format for CmdStan](https://mc-stan.org/docs/cmdstan-guide/json_apdx.html). The result is stored in the vector `out`, and a reference is returned. See [`param_initialize`](#BridgeStan.param_initialize) for a version which allocates fresh memory. ### Method Signature ```julia param_initialize!(sm, rng, out, theta="{}"; init_radius=2.0, max_tries=100, jacobian=true) ``` ### Parameters - `sm` (StanModel): The StanModel instance. - `rng` (StanRNG): A random number generator. - `out` (Vector): The vector to store the initialized parameters. - `theta` (String, optional): A JSON string specifying initial parameter values. Defaults to "{}". - `init_radius` (Float64, optional): The radius for random initialization. Defaults to 2.0. - `max_tries` (Int, optional): The maximum number of retries for finding a valid point. Defaults to 100. - `jacobian` (Bool, optional): Whether to compute the Jacobian. Defaults to true. ``` -------------------------------- ### Get Number of Unconstrained Parameters Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_rust/bridgestan/lib.md Returns the number of parameters on the unconstrained scale. This is the required size for slices used in log-density functions. ```rust pub fn param_unc_num(&self) -> usize ``` -------------------------------- ### StanModel$param_initialize() Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Initializes a point in the unconstrained space using provided JSON values and randomizing others. Retries up to max_tries if log density is not finite. ```APIDOC ## StanModel$param_initialize() ### Description Initialize a point in the unconstrained space, using the specified values from JSON and randomizing the others. ### Method StanModel$param_initialize( rng, json = "{}", init_radius = 2, max_tries = 100, jacobian = TRUE ) ### Parameters #### Path Parameters - **rng** (object) - Required - The source of randomness for the unspecified parameters. - **json** (string) - Optional - Character vector containing a string representation of JSON data. Defaults to "{}". - **init_radius** (numeric) - Optional - The parameters not provided will be drawn uniformly from `[-init_radius, init_radius)` on the unconstrained scale. Defaults to 2. - **max_tries** (integer) - Optional - Maximum number of random initializations considered to find a point with finite log density. Defaults to 100. - **jacobian** (boolean) - Optional - If `TRUE`, include change of variables terms for constrained parameters when checking the log density and gradient for finiteness. Defaults to TRUE. ### Returns The unconstrained parameters of the model. ``` -------------------------------- ### Get BridgeStan Path Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Retrieves the path to the BridgeStan directory. Optionally downloads BridgeStan source if not found and the download flag is true. ```julia get_bridgestan_path(;download=true) -> String ``` -------------------------------- ### Get the number of constrained parameters Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Returns the total count of constrained parameters in the model. Can optionally include transformed parameters and generated quantities. ```R StanModel$param_num(include_tp = FALSE, include_gq = FALSE) ``` -------------------------------- ### Model::param_initialize Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_rust/bridgestan/lib.md Initializes a point in the unconstrained parameter space using provided JSON values and randomizing others. It ensures the resulting parameters have a finite log density and gradient. ```APIDOC ## Model::param_initialize ### Description Initializes a point in the unconstrained parameter space using JSON values and randomizing the rest. Checks for finite log density and gradient. ### Method (Implicitly a method call on a `Model` object) ### Parameters - **rng** (&mut Rng) - Required - A mutable reference to a random number generator. - **json** (S: AsRef) - Required - JSON data in the format for CmdStan. - **init_radius** (f64) - Required - The radius for initialization. - **max_tries** (i32) - Required - The maximum number of tries for initialization. - **jacobian** (bool) - Required - Whether to compute the Jacobian. - **theta_unc** (&mut [f64]) - Required - The buffer to store the unconstrained parameters. ### Returns - Result<(), _> - Ok(()) on success, or an error if initialization fails. ``` -------------------------------- ### Get Number of Parameters (Constrained) Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_rust/bridgestan/lib.md Retrieves the total number of parameters in the model on the constrained scale. Optionally includes transformed parameters and generated quantities. ```rust pub fn param_num(&self, include_tp: bool, include_gq: bool) -> usize ``` -------------------------------- ### Run Rust Tests Source: https://github.com/roualdes/bridgestan/blob/main/docs/internals/testing.md Navigates to the Rust directory and runs tests using cargo test. This command executes the Rust test suite. ```shell cd rust/ cargo test ``` -------------------------------- ### Get Number of Unconstrained Parameters Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Returns the number of unconstrained parameters in the Stan model. This differs from param_num when parameters have constraints, affecting their unconstrained representation. ```julia param_unc_num(sm) ``` -------------------------------- ### Get the number of unconstrained parameters Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Returns the total count of unconstrained parameters. This count may differ from `param_num` for constrained variables (e.g., simplex). ```R StanModel$param_unc_num() ``` -------------------------------- ### StanModel.from_stan_file (classmethod) Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/python.md Construct a StanModel instance from a `.stan` file, compiling if necessary. This method is deprecated; use the constructor on a `.stan` file instead. ```APIDOC ## classmethod bridgestan.StanModel.from_stan_file ### Description Construct a StanModel instance from a `.stan` file, compiling if necessary. ### Parameters * **stan_file** (str) – A path to a Stan model file. * **model_data** (str | None) – A path to data in JSON format. * **stanc_args** (List[str]) – A list of arguments to pass to stanc3. For example, `["--O1"]` will enable compiler optimization level 1. * **make_args** (List[str]) – A list of additional arguments to pass to Make. For example, `["STAN_THREADS=True"]` will enable threading for the compiled model. If the same flags are defined in `make/local`, the versions passed here will take precedent. * **seed** (int) – A pseudo random number generator seed, used for RNG functions in the `transformed data` block. Defaults to 1234. * **capture_stan_prints** (bool) – If `True`, capture all `print` statements from the Stan model and print them from Python. This has no effect if the model does not contain any `print` statements, but may have a performance impact if it does. If `False`, `print` statements from the Stan model will be sent to `cout` and will not be seen in Jupyter or capturable with `contextlib.redirect_stdout`. Defaults to `True`. ### Raises * **FileNotFoundError** **or** **PermissionError** – If `stan_file` does not exist or is not readable. * **ValueError** – If BridgeStan cannot be located. * **RuntimeError** – If compilation fails. ``` -------------------------------- ### bridgestan::Model::param_unc_names Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_rust/bridgestan/lib.md Returns a comma-separated sequence of unconstrained parameter names. Parameters are indexed starting from 1, and multivariate parameters are in column-major order. ```APIDOC ## bridgestan::Model::param_unc_names ### Description Return a comma-separated sequence of unconstrained parameters. Only parameters are unconstrained, so there are no unconstrained transformed parameters or generated quantities. The parameters are returned in the order they are declared. Multivariate parameters are return in column-major (more generally last-index major) order. Parameter indices are separated with periods (`.`). For example, `a[3]` is written `a.3` and `b[2, 3]` as `b.2.3`. The numbering follows Stan and is indexed from 1. ### Method `pub fn param_unc_names(&self) -> &str` ### Returns `&str` - A comma-separated string of unconstrained parameter names. ``` -------------------------------- ### Create a StanModel instance Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Initializes a StanModel object. Requires a path to a compiled Stan model or a .stan file, data in JSON format, and an RNG seed. Optional arguments for stanc and make can be provided. ```R StanModel$new( lib, data, seed, stanc_args = NULL, make_args = NULL, warn = TRUE ) ``` -------------------------------- ### Calculate Log Density and Gradient Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Computes the log density and its gradient for a given vector of unconstrained parameters. Options for 'propto' and 'jacobian' are available. ```r StanModel$log_density_gradient(theta_unc, propto = TRUE, jacobian = TRUE) ``` -------------------------------- ### Calculate Log Density, Gradient, and Hessian Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Computes the log density, gradient, and Hessian for a given vector of unconstrained parameters. Supports 'propto' and 'jacobian' options. ```r StanModel$log_density_hessian(theta_unc, propto = TRUE, jacobian = TRUE) ``` -------------------------------- ### Calculate Log Density and Hessian-Vector Product Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Computes the log density and the product of the Hessian with a given vector 'v'. Supports proportional calculations and Jacobian terms for constrained parameters. ```julia log_density_hessian_vector_product!(sm, q, v, out; propto=true, jacobian=true) ``` -------------------------------- ### Calculate Log Density and Hessian-Vector Product Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Computes the log density and the product of the Hessian with a specified vector for a given vector of unconstrained parameters. Includes 'propto' and 'jacobian' options. ```r StanModel$log_density_hessian_vector_product( theta_unc, v, propto = TRUE, jacobian = TRUE ) ``` -------------------------------- ### Get Unconstrained Parameter Names Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_rust/bridgestan/lib.md Returns a comma-separated string of unconstrained parameter names. Parameters are ordered as declared, with multivariate parameters in column-major order. Indices are 1-based and period-separated. ```rust pub fn param_unc_names(&self) -> &str ``` -------------------------------- ### Get indexed names of constrained parameters Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Returns the indexed names of constrained parameters. Supports including transformed parameters and generated quantities. Parameter names are period-separated for containers. ```R StanModel$param_names(include_tp = FALSE, include_gq = FALSE) ``` -------------------------------- ### StanModel$param_initialize() Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/r.md Initializes a point in the unconstrained parameter space, using provided JSON values and randomizing others within a specified radius. ```APIDOC ## StanModel$param_initialize() ### Description Initialize a point in the unconstrained space, using the specified values from JSON and randomizing the others. Any parameter not specified in the provided JSON will be randomly selected uniformly from `[-init_radius, init_radius)`. The resulting point will be checked for a finite log density value, and retried up to the specified number of times. If all such retries fail, an error is raised. The JSON is expected to be in the [JSON Format for CmdStan](https://mc-stan.org/docs/cmdstan-guide/json_apdx.html). ### Method `StanModel$param_initialize(rng, json = "{}", init_radius = 2, max_tries = 100, jacobian = TRUE)` ### Parameters #### Arguments - **`rng`** (object) - The source of randomness for the unspecified parameters. - **`json`** (character) - Character vector containing a string representation of JSON data. Defaults to "{}". - **`init_radius`** (numeric) - The parameters not provided will be drawn uniformly from `[-init_radius, init_radius)` on the unconstrained scale. Defaults to 2. - **`max_tries`** (numeric) - Maximum number of random initializations considered to find a point with finite log density. Defaults to 100. - **`jacobian`** (boolean) - If `TRUE`, include change of variables terms for constrained parameters when checking the log density and gradient for finiteness. Defaults to TRUE. ### Returns The unconstrained parameters of the model. ``` -------------------------------- ### Get Number of Constrained Parameters Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Returns the total number of parameters declared in the 'parameters' block of the Stan model. Optionally includes parameters from 'transformed parameters' and 'generate quantities' blocks. ```julia param_num(sm; include_tp=false, include_gq=false) ``` -------------------------------- ### BridgeStan.param_initialize Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Initializes parameters, allowing for incomplete specifications. Unspecified parameters are randomly selected. The function attempts to find a point with a finite log density, retrying up to a specified limit. ```APIDOC ## `BridgeStan.param_initialize` ### Description Similar to [`param_unconstrain_json`](#BridgeStan.param_unconstrain_json) but allows for incomplete specifications of the parameters. Any parameter not specified in the provided JSON will be randomly selected uniformly from `[-init_radius, init_radius)`. The resulting point will be checked for a finite log density value, and retried up to the specified number of times. If all such retries fail, an error is raised. The JSON is expected to be in the [JSON Format for CmdStan](https://mc-stan.org/docs/cmdstan-guide/json_apdx.html). This allocates new memory for the output each call. See [`param_initialize!`](#BridgeStan.param_initialize!) for a version which allows reusing existing memory. ### Function Signature ```julia param_initialize(sm, rng, theta="{}"; init_radius=2.0, max_tries=100, jacobian=true) ``` ``` -------------------------------- ### download_bridgestan_src Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_rust/bridgestan/lib.md Downloads and unzips the BridgeStan source distribution for the current version to the default user directory. Requires the 'download-bridgestan-src' feature to be enabled. ```APIDOC ## fn download_bridgestan_src ### Description Download and unzip the BridgeStan source distribution for this version to `~/.bridgestan/bridgestan-$VERSION`. Requires feature `download-bridgestan-src`. ### Signature ```rust pub fn download_bridgestan_src() -> Result ``` ### Returns Result: A `Result` that is `Ok` containing the path to the downloaded sources if successful, or `Err` if the download or extraction fails. ``` -------------------------------- ### Get Indexed Names of Constrained Parameters Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Retrieves the indexed names of constrained parameters, optionally including transformed parameters and generated quantities. Container elements are indexed with periods (e.g., 'a.1', 'a.2.3'). ```julia param_names(sm; include_tp=false, include_gq=false) ``` -------------------------------- ### open_library Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_rust/bridgestan/lib.md Opens a compiled Stan library. The library must have been compiled with the same version of BridgeStan as the Rust library. ```APIDOC ## fn open_library> ### Description Open a compiled Stan library. The library should have been compiled with BridgeStan, with the same version as the Rust library. ### Signature ```rust pub fn open_library>(path: P) -> Result ``` ### Parameters * `path` (P): A type that can be referenced as an `OsStr`, representing the path to the compiled Stan library. ### Returns Result: A `Result` that is `Ok` containing a `StanLibrary` object if the library was opened successfully, or `Err` if the library could not be opened. ``` -------------------------------- ### StanModel$new() Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/_r/StanModel.md Creates a new StanModel instance. This can be used to load a pre-compiled shared object or compile a .stan file. ```APIDOC ## StanModel$new() ### Description Create a Stan Model instance. ### Method StanModel$new() ### Parameters #### Arguments - **`lib`** (string) - Required - A path to a compiled BridgeStan Shared Object file or a .stan file (will be compiled). - **`data`** (string) - Required - Either a JSON string literal, a path to a data file in JSON format ending in ".json", or the empty string. - **`seed`** (numeric) - Required - Seed for the RNG used in constructing the model. - **`stanc_args`** (list) - Optional - A list of arguments to pass to stanc3 if the model is not already compiled. - **`make_args`** (list) - Optional - A list of additional arguments to pass to Make if the model is not already compiled. - **`warn`** (boolean) - Optional - If false, the warning about re-loading the same shared object is suppressed. ### Returns A new StanModel. ``` -------------------------------- ### Calculate Log Density, Gradient, and Hessian Source: https://github.com/roualdes/bridgestan/blob/main/docs/languages/julia.md Computes the log density, gradient, and Hessian of the unconstrained parameters. Similar to log_density_gradient!, it supports proportional calculations and Jacobian terms. Gradient and Hessian are stored in 'out_grad' and 'out_hess' respectively. ```julia log_density_hessian!(sm, q, out_grad, out_hess; propto=true, jacobian=true) ``` -------------------------------- ### Clone BridgeStan Repository Source: https://github.com/roualdes/bridgestan/blob/main/README.md Use this command to download the latest development version of BridgeStan, ensuring all submodules are included. ```shell git clone --recurse-submodules https://github.com/roualdes/bridgestan.git ```