# Typescript (JavaScript) Interface ## Targetting WASM with TinyStan This interface is intended to be used to access models built with [Emscripten](https://emscripten.org/), which compiles C++ code to [WebAssembly](https://webassembly.org/). This requires some extra configuration compared to normal builds. Examples of the build (and usage) can be found in the following projects: - [Stan Web Demo](https://github.com/WardBrian/stan-web-demo/) ([Emscripten config](https://github.com/WardBrian/stan-web-demo/blob/main/build/local.mk)) - [Stan Playground](https://github.com/flatironinstitute/stan-playground) ([Emscripten config](https://github.com/flatironinstitute/stan-playground/blob/main/backend/local.mk)) Note that, among other things, a more recent version of TBB must be used, as WebAssembly is not supported in the version Stan currently vendors. ## Installation The Typescript interface is [available on npm](https://www.npmjs.com/package/tinystan). To install it, run: ```shell npm install tinystan --save ``` or ```shell yarn add tinystan ``` [.sample(p)]:#stanmodel-sample-p [.pathfinder(p)]:#stanmodel-pathfinder-p [.stanVersion()]:#stanmodel-stanversion [.load(createModule, printCallback)]:#stanmodel-load-createmodule-printcallback ## API Reference ### Classes Name | Description ------ | ----------- [StanModel] |
StanModel is a class that wraps the WASM module and provides a higher-level interface to the Stan library, abstracting away things like memory management and error handling.
### Typedefs Name | Description ------ | ----------- [StanVariableInputs] |A type holding named inputs to a Stan model, e.g. the data or initial values.
[PrintCallback] |A callback for printing output from the Stan model.
[StanDraws] |A type holding the result of a Stan sampling run.
[SamplerParams] |Parameters for the HMC sampler.
[PathfinderParams] |Parameters for the Pathfinder algorithm.
### StanModelStanModel is a class that wraps the WASM module and provides a higher-level interface to the Stan library, abstracting away things like memory management and error handling.
**Kind**: global class * [StanModel] * _instance_ * [.sample(p)] * [.pathfinder(p)] * [.stanVersion()] * _static_ * [.load(createModule, printCallback)] #### stanModel.sample(p)Sample using NUTS-HMC.
**Kind**: instance method of [`StanModel`] **Returns**: [`StanDraws`] -A StanDraws object containing the parameter names and the draws
| Param | Type | Description | | --- | --- | --- | | p | [`SamplerParams`] |A (partially-specified) SamplerParams
object. If a property is not specified, the default value will be used.
Approximate the posterior using Pathfinder.
**Kind**: instance method of [`StanModel`] **Returns**: [`StanDraws`] -A StanDraws object containing the parameter names and the approximate draws
| Param | Type | Description | | --- | --- | --- | | p | [`PathfinderParams`] |A (partially-specified) PathfinderParams
object. If a property is not specified, the default value will be used.
Get the version of the Stan library being used.
**Kind**: instance method of [`StanModel`] **Returns**: `string` -The version of the Stan library being used, in the form "major.minor.patch"
#### StanModel.load(createModule, printCallback)Load a StanModel from a WASM module.
**Kind**: static method of [`StanModel`] **Returns**: `Promise.A promise that resolves to a StanModel
A function that resolves to a WASM module. This is much like the one Emscripten creates for you with -sMODULARIZE
.
A callback that will be called with any print statements from Stan. If null, this will default to console.log
.
The metric used for the HMC sampler.
**Kind**: global enum **Read only**: true **Properties** | Name | Type | Description | | --- | --- | --- | | UNIT | `0` |Unit metric.
| | DENSE | `1` |Dense metric.
| | DIAGONAL | `2` |Diagonal metric.
| ### StanVariableInputsA type holding named inputs to a Stan model, e.g. the data or initial values.
**Kind**: global typedef ### PrintCallbackA callback for printing output from the Stan model.
**Kind**: global typedef | Param | Type | Description | | --- | --- | --- | | s | `string` |The string to print.
| ### StanDrawsA type holding the result of a Stan sampling run.
**Kind**: global typedef **Properties** | Name | Type | Description | | --- | --- | --- | | paramNames | `Array.The names of the parameters in the model
| | draws | `Array.A 2D array of draws from the posterior. The first dimension is the number of samples, and the second dimension is the number of parameters.
| | metric | `Array.The metric used for the HMC sampler. If the metric is not saved, this field is not present.
| ### SamplerParamsParameters for the HMC sampler.
**Kind**: global typedef **Properties** | Name | Type | Default | Description | | --- | --- | --- | --- | | \[data\] | `string` \| [`StanVariableInputs`] | `'""'` |The data for the model
| | \[num_chains\] | `number` | `4` |The number of chains to run
| | \[inits\] | `string` \| [`StanVariableInputs`] \| `Array.The initial values for the sampler. If an array, must have length num_chains
.
The seed for the random number generator. If unspecified, a random seed will be generated.
| | \[id\] | `number` | `1` |The ID for the first chain
| | \[init_radius\] | `number` | `2.0` |Radius to initialize unspecified parameters within. The parameter values are drawn uniformly from the interval [-init_radius, init_radius]
on the unconstrained scale.
The number of warmup iterations to run
| | \[num_samples\] | `number` | `1000` |The number of samples to draw after warmup
| | \[metric\] | `HMCMetric` | `HMCMetric.DENSE` |The type of mass matrix to use in the sampler
| | \[save_metric\] | `boolean` | `false` |Whether to report the final mass matrix
| | \[init_inv_metric\] | `Array.The initial inverse metric to use. Currently, this argument is unused.
| | \[adapt\] | `boolean` | `true` |Whether the sampler should adapt the step size and metric
| | \[delta\] | `number` | `0.8` |Target acceptance rate
| | \[gamma\] | `number` | `0.05` |Adaptation regularization scale
| | \[kappa\] | `number` | `0.75` |Adaptation relaxation exponent
| | \[t0\] | `number` | `10.0` |Adaptation iteration offset
| | \[init_buffer\] | `number` | `75` |Number of warmup samples to use for initial step size adaptation.
| | \[term_buffer\] | `number` | `50` |Number of warmup samples to use for step size adaptation after the metric is adapted
| | \[window\] | `number` | `25` |Initial number of iterations to use for metric adaptation, which is doubled each time the adaptation window is hit
| | \[save_warmup\] | `boolean` | `false` |Whether to save the warmup draws
| | \[stepsize\] | `number` | `1.0` |Initial step size for the sampler
| | \[stepsize_jitter\] | `number` | `0.0` |Amount of random jitter to add to the step size
| | \[max_depth\] | `number` | `10` |Maximum tree depth for the NUTS sampler
| | \[refresh\] | `number` | `0` |Number of iterations between progress messages. If 0, no output is printed.
| | \[num_threads\] | `number` | `-1` |Number of threads to use for sampling. If -1, the number of threads is determined by the number of available CPU cores. May not be supported in all environments, and requires extra configuration during the Emscripten compilation.
| ### PathfinderParamsParameters for the Pathfinder algorithm.
**Kind**: global typedef **Properties** | Name | Type | Default | Description | | --- | --- | --- | --- | | \[data\] | `string` \| [`StanVariableInputs`][1] | `'""'` |The data for the model
| | \[num_paths\] | `number` | `4` |The number of individual paths to run
| | \[inits\] | `string` \| [`StanVariableInputs`] \| `Array.The initial values for the algorithm. If an array, must have length num_paths
.
The seed for the random number generator. If unspecified, a random seed will be generated.
| | \[id\] | `number` | `1` |The ID for the first path
| | \[init_radius\] | `number` | `2.0` |Radius to initialize unspecified parameters within. The parameter values are drawn uniformly from the interval [-init_radius, init_radius]
on the unconstrained scale.
The number of draws to take for each path
| | \[max_history_size\] | `number` | `5` |History size used by the internal L-BFGS algorithm to approximate the Hessian
| | \[init_alpha\] | `number` | `0.001` |Initial step size for the internal L-BFGS algorithm
| | \[tol_obj\] | `number` | `1e-12` |Convergence tolerance for the objective function
| | \[tol_rel_obj\] | `number` | `1e4` |Relative convergence tolerance for the objective function
| | \[tol_grad\] | `number` | `1e-8` |Convergence tolerance for the gradient norm
| | \[tol_rel_grad\] | `number` | `1e7` |Relative convergence tolerance for the gradient norm
| | \[tol_param\] | `number` | `1e-8` |Convergence tolerance for the changes in parameters
| | \[num_iterations\] | `number` | `1000` |Maximum number of iterations for the internal L-BFGS algorithm
| | \[num_elbo_draws\] | `number` | `25` |Number of Monte Carlo draws used to estimate the ELBO
| | \[num_multi_draws\] | `number` | `1000` |Number of draws returned by Multi-Pathfinder
| | \[calculate_lp\] | `boolean` | `true` |Whether to calculate the log probability of the approximate draws. If false, this also implies psis_resample=false
.
Whether to use Pareto smoothed importance sampling on the approximate draws. If false, all num_paths * num_draws
approximate samples will be returned.
Number of iterations between progress messages. If 0, no output is printed.
| | \[num_threads\] | `number` | `-1` |Number of threads to use for Pathfinder. If -1, the number of threads is determined by the number of available CPU cores. May not be supported in all environments, and requires extra configuration during the Emscripten compilation.
| [StanModel]:#stanmodel [StanVariableInputs]:#stanvariableinputs [PrintCallback]:#printcallback [StanDraws]:#standraws [SamplerParams]:#samplerparams [PathfinderParams]:#pathfinderparams [`StanModel`]:#stanmodel [`StanDraws`]:#standraws [`SamplerParams`]:#samplerparams [`PathfinderParams`]:#pathfinderparams [`PrintCallback`]:#printcallback [`StanVariableInputs`]:#stanvariableinputs [1]:#stanvariableinputs [.sample(p)]:#stanmodelsamplep [.pathfinder(p)]:#stanmodelpathfinderp [.stanVersion()]:#stanmodelstanversion [.load(createModule, printCallback)]:#stanmodelloadcreatemodule-printcallback