Stan.jl documentation

Programs

CMDSTAN_HOME

Stan.CMDSTAN_HOMEConstant.

The directory which contains the CmdStan executables such as bin/stanc and bin/stansummary. Inferred from Main.CMDSTAN_HOME or ENV["CMDSTAN_HOME"] when available. Use set_cmdstan_home! to modify.

setcmdstanhome!

Set the path for the CMDSTAN_HOME environment variable.

Example: set_cmdstan_home!(homedir() * "/Projects/Stan/cmdstan/")

stanmodel()

Stan.StanmodelType.

Method Stanmodel

Create a Stanmodel.

Constructors

Stanmodel(
  method=Sample();
  name="noname", 
  nchains=4,
  num_warmup=1000, 
  num_samples=1000,
  thin=1,
  model="",
  monitors=String[],
  data=DataDict[],
  random=Random(),
  init=DataDict[],
  output=Output(),
  pdir::String=pwd(),
  useMamba=true,
  mambaThinning=1
)

Required arguments

* `method::Method`            : See ?Method

Optional arguments

* `name::String`               : Name for the model
* `nchains::Int`               : Number of chains, if possible execute in parallel
* `num_warmup::Int`            : Number of samples used for num_warmupation 
* `num_samples::Int`           : Sample iterations
* `thin::Int`                  : Stan thinning factor
* `model::String`              : Stan program source
* `data::DataDict[]`           : Observed input data as an array of Dicts
* `random::Random`             : Random seed settings
* `init::DataDict[]`           : Initial values for parameters in parameter block
* `output::Output`             : File output options
* `pdir::String`               : Working directory
* `monitors::String[] `        : Filter for variables used in Mamba post-processing
* `useMamba::Bool`             : Use Mamba Chains for diagnostics and graphics
* `mambaThinning::Int`         : Additional thinning factor in Mamba Chains

Example

bernoullimodel = "
data { 
  int<lower=1> N; 
  int<lower=0,upper=1> y[N];
} 
parameters {
  real<lower=0,upper=1> theta;
} 
model {
  theta ~ beta(1,1);
  y ~ bernoulli(theta);
}
"

stanmodel = Stanmodel(num_samples=1200, thin=2, name="bernoulli", model=bernoullimodel);

Related help

?stan                          : Run a Stanmodel
?Sample                        : Sampling settings
?Method                       : List of available methods
?Output                        : Output file settings
?DataDict                      : Input data dictionaries, will be converted to R syntax

Method updatemodelfile

Update Stan language model file if necessary

Method

update_model_file(
  file::String, 
  str::String
)

Required arguments

* `file::String`                : File holding existing Stan model
* `str::String`                 : Stan model string

Related help

?Stan.Stanmodel                 : Create a StanModel

stan()

Stan.stanFunction.

stan

Execute a Stan model.

Method

rc, sim = stan(
  model::Stanmodel, 
  data=Nothing, 
  ProjDir=pwd();
  init=Nothing,
  summary=true, 
  diagnostics=false, 
  CmdStanDir=CMDSTAN_HOME
)

Required arguments

* `model::Stanmodel`              : See ?Method

Optional positional arguments

* `data=Nothing`                     : Observed input data dictionary 
* `ProjDir=pwd()`                 : Project working directory

Keyword arguments

* `init=Nothing`                     : Initial parameter value dictionary
* `summary=true`                  : Use CmdStan's stansummary to display results
* `diagnostics=false`             : Generate diagnostics file
* `CmdStanDir=CMDSTAN_HOME`       : Location of CmdStan directory

Return values

* `rc::Int`                       : Return code from stan(), rc == 0 if all is well
* `sim`                           : Chain results

Examples

# no data, use default ProjDir (pwd)
stan(mymodel)
# default ProjDir (pwd)
stan(mymodel, mydata)
# specify ProjDir
stan(mymodel, mydata, "~/myproject/")
# keyword arguments
stan(mymodel, mydata, "~/myproject/", diagnostics=true, summary=false)
# use default ProjDir (pwd), with keyword arguments
stan(mymodel, mydata, diagnostics=true, summary=false)

Related help

?Stanmodel                      : Create a StanModel
Stan.stan_summaryMethod.

Method stan_summary

Display CmdStan summary

Method

stan_summary(
  filecmd::Cmd; 
  CmdStanDir=CMDSTAN_HOME
)

Required arguments

* `filecmd::Cmd`                : Run command containing names of sample files

Optional arguments

* CmdStanDir=CMDSTAN_HOME       : CmdStan directory for stansummary program

Related help

?Stan.stan                      : Create a StanModel
Stan.stan_summaryMethod.

Method stan_summary

Display CmdStan summary

Method

stan_summary(
  file::String; 
  CmdStanDir=CMDSTAN_HOME
)

Required arguments

* `file::String`                : Name of file with samples

Optional arguments

* CmdStanDir=CMDSTAN_HOME       : CmdStan directory for stansummary program

Related help

?Stan.stan                      : Execute a StanModel

Types

Stan.MethodType.

Available top level Method

Method

*  Sample::Method             : Sampling
*  Optimize::Method           : Optimization
*  Diagnose::Method           : Diagnostics
*  Variational::Method        : Variational Bayes
Stan.SampleType.

Sample type and constructor

Settings for method=Sample() in Stanmodel.

Method

Sample(;
  num_samples=1000,
  num_warmup=1000,
  save_warmup=false,
  thin=1,
  adapt=Adapt(),
  algorithm=SamplingAlgorithm()
)

Optional arguments

* `num_samples::Int64`          : Number of sampling iterations ( >= 0 )
* `num_warmup::Int64`           : Number of warmup iterations ( >= 0 )
* `save_warmup::Bool`           : Include warmup samples in output
* `thin::Int64`                 : Period between saved samples
* `adapt::Adapt`                : Warmup adaptation settings
* `algorithm::SamplingAlgorithm`: Sampling algorithm

Related help

?Stanmodel                      : Create a StanModel
?Adapt
?SamplingAlgorithm
Stan.AdaptType.

Adapt type and constructor

Settings for adapt=Adapt() in Sample().

Method

Adapt(;
  engaged=true,
  gamma=0.05,
  delta=0.8,
  kappa=0.75,
  t0=10.0,
  init_buffer=75,
  term_buffer=50,
  window::25
)

Optional arguments

* `engaged::Bool`              : Adaptation engaged?
* `gamma::Float64`             : Adaptation regularization scale
* `delta::Float64`             : Adaptation target acceptance statistic
* `kappa::Float64`             : Adaptation relaxation exponent
* `t0::Float64`                : Adaptation iteration offset
* `init_buffer::Int64`         : Width of initial adaptation interval
* `term_buffer::Int64`         : Width of final fast adaptation interval
* `window::Int64`              : Initial width of slow adaptation interval

Related help

?Sample                        : Sampling settings

Available sampling algorithms

Currently limited to Hmc().

Stan.HmcType.

Hmc type and constructor

Settings for algorithm=Hmc() in Sample().

Method

Hmc(;
  engine=Nuts(),
  metric=Stan.diag_e,
  stepsize=1.0,
  stepsize_jitter=1.0
)

Optional arguments

* `engine::Engine`            : Engine for Hamiltonian Monte Carlo
* `metric::Metric`            : Geometry for base manifold
* `stepsize::Float64`         : Stepsize for discrete evolutions
* `stepsize_jitter::Float64`  : Uniform random jitter of the stepsize [%]

Related help

?Sample                        : Sampling settings
?Engine                        : Engine for Hamiltonian Monte Carlo
?Nuts                          : Settings for Nuts
?Static                        : Settings for Static
?Metric                        : Base manifold geometries
Stan.MetricType.

Metric types

Geometry of base manifold

Types defined

* unit_e::Metric      : Euclidean manifold with unit metric
* dense_e::Metric     : Euclidean manifold with dense netric
* diag_e::Metric      : Euclidean manifold with diag netric
Stan.EngineType.

Engine types

Engine for Hamiltonian Monte Carlo

Types defined

* Nuts       : No-U-Tyrn sampler
* Static     : Static integration time
Stan.NutsType.

Nuts type and constructor

Settings for engine=Nuts() in Hmc().

Method

Nuts(;max_depth=10)

Optional arguments

* `max_depth::Number`           : Maximum tree depth

Related help

?Sample                        : Sampling settings
?Engine                        : Engine for Hamiltonian Monte Carlo
Stan.StaticType.

Static type and constructor

Settings for engine=Static() in Hmc().

Method

Static(;int_time=2 * pi)

Optional arguments

* `;int_time::Number`          : Static integration time

Related help

?Sample                        : Sampling settings
?Engine                        : Engine for Hamiltonian Monte Carlo

Available method diagnostics

Currently limited to Gradient().

Stan.GradientType.

Gradient type and constructor

Settings for diagnostic=Gradient() in Diagnose().

Method

Gradient(;epsilon=1e-6, error=1e-6)

Optional arguments

* `epsilon::Float64`           : Finite difference step size
* `error::Float64`             : Error threshold

Related help

?Diagnose                      : Diagnostic method
Stan.DiagnoseType.

Diagnose type and constructor

Method

Diagnose(;d=Gradient())

Optional arguments

* `d::Diagnostics`            : Finite difference step size

Related help

```julia ?Diagnostics : Diagnostic methods ?Gradient : Currently sole diagnostic method

OptimizeAlgorithm types

Types defined

* Lbfgs::OptimizeAlgorithm   : Euclidean manifold with unit metric
* Bfgs::OptimizeAlgorithm    : Euclidean manifold with unit metric
* Newton::OptimizeAlgorithm  : Euclidean manifold with unit metric
Stan.OptimizeType.

Optimize type and constructor

Settings for Optimize top level method.

Method

Optimize(;
  method=Lbfgs(),
  iter=2000,
  save_iterations=false
)

Optional arguments

* `method::OptimizeMethod`      : Optimization algorithm
* `iter::Int`                   : Total number of iterations
* `save_iterations::Bool`       : Stream optimization progress to output

Related help

?Stanmodel                      : Create a StanModel
?OptimizeAlgorithm              : Available algorithms
Stan.LbfgsType.

Lbfgs type and constructor

Settings for method=Lbfgs() in Optimize().

Method

Lbfgs(;init_alpha=0.001, tol_obj=1e-8, tol_grad=1e-8, tol_param=1e-8, history_size=5)

Optional arguments

* `init_alpha::Float64`        : Linear search step size for first iteration
* `tol_obj::Float64`           : Convergence tolerance for objective function
* `tol_rel_obj::Float64`       : Relative change tolerance in objective function
* `tol_grad::Float64`          : Convergence tolerance on norm of gradient
* `tol_rel_grad::Float64`      : Relative change tolerance on norm of gradient
* `tol_param::Float64`         : Convergence tolerance on parameter values
* `history_size::Int`          : No of update vectors to use in Hessian approx

Related help

?OptimizeMethod               : List of available optimize methods
?Optimize                      : Optimize arguments
Stan.BfgsType.

Bfgs type and constructor

Settings for method=Bfgs() in Optimize().

Method

Bfgs(;init_alpha=0.001, tol_obj=1e-8, tol_rel_obj=1e4, 
  tol_grad=1e-8, tol_rel_grad=1e7, tol_param=1e-8)

Optional arguments

* `init_alpha::Float64`        : Linear search step size for first iteration
* `tol_obj::Float64`           : Convergence tolerance for objective function
* `tol_rel_obj::Float64`       : Relative change tolerance in objective function
* `tol_grad::Float64`          : Convergence tolerance on norm of gradient
* `tol_rel_grad::Float64`      : Relative change tolerance on norm of gradient
* `tol_param::Float64`         : Convergence tolerance on parameter values

Related help

?OptimizeMethod               : List of available optimize methods
?Optimize                      : Optimize arguments
Stan.NewtonType.

Newton type and constructor

Settings for method=Newton() in Optimize().

Method

Newton()

Related help

?OptimizeMethod               : List of available optimize methods
?Optimize                      : Optimize arguments

Variational type and constructor

Settings for method=Variational() in Stanmodel.

Method

Variational(;
  grad_samples=1,
  elbo_samples=100,
  eta_adagrad=0.1,
  iter=10000,
  tol_rel_obj=0.01,
  eval_elbo=100,
  algorithm=:meanfield,          
  output_samples=10000
)

Optional arguments

* `algorithm::Symbol`             : Variational inference algorithm
                                    :meanfiedl;
                                    :fullrank
* `iter::Int64`                   : Maximum number of iterations
* `grad_samples::Int`             : No of samples for MC estimate of gradients
* `elbo_samples::Int`             : No of samples for MC estimate of ELBO
* `eta::Float64`                  : Stepsize weighing parameter for adaptive sequence
* `adapt::Adapt`                  : Warmupadaptations
* `tol_rel_obj::Float64`          : Tolerance on the relative norm of objective
* `eval_elbo::Int`                : Tolerance on the relative norm of objective
* `output_samples::Int`           : Numberof posterior samples to draw and save

Related help

?Stanmodel                      : Create a StanModel
?Stan.Method                   : Available top level methods
?Stan.Adapt                     : Adaptation settings

Utilities

Stan.cmdlineFunction.

cmdline

Recursively parse the model to construct command line.

Method

cmdline(m)

Required arguments

* `m::Stanmodel`                : Stanmodel

Related help

?Stanmodel                      : Create a StanModel
Stan.check_dct_typeFunction.

checkdctmutable struct

Check if dct == Dict{String, Any}[] and has length > 0.

Method

check_dct_type(dct)

Required arguments

* `dct::Dict{String, Any}`      : Observed data or parameter init data
Stan.update_R_fileFunction.

updateRfile

Rewrite a dictionary of observed data or initial parameter values in R dump file format to a file.

Method

update_R_file{T<:Any}(file, dct)

Required arguments

* `file::String`                : R file name
* `dct::Dict{String, T}`        : Dictionary to format in R
Stan.parFunction.

par

Rewrite dct to R format in file.

Method

par(cmds)

Required arguments

* `cmds::Array{Base.AbstractCmd,1}`    : Multiple commands to concatenate

or

* `cmd::Base.AbstractCmd`              : Single command to be
* `n::Number`                            inserted n times into cmd


or
* `cmd::Array{String, 1}`              : Array of cmds as Strings
Stan.read_stanfitMethod.

read_stanfit

Rewrite dct to R format in file.

Method

par(cmds)

Required arguments

* `cmds::Array{Base.AbstractCmd,1}`    : Multiple commands to concatenate

or

* `cmd::Base.AbstractCmd`              : Single command to be
* `n::Number`                            inserted n times into cmd


or
* `cmd::Array{String, 1}`              : Array of cmds as Strings

Index