Internal API Reference

The following documents the internal API of CmdStanPy. No guarantees are made about backwards compatibility between minor versions and refactors are expected. If you find yourself needing something exposed here, please open an issue requesting it be added to the public API.

Classes

InferenceMetadata

class cmdstanpy.stanfit.InferenceMetadata(config)[source]

CmdStan configuration and contents of output file parsed out of the Stan CSV file header comments and column headers. Assumes valid CSV files.

Parameters:

config (Dict[str, Any]) –

property cmdstan_config: Dict[str, Any]

Returns a dictionary containing a set of name, value pairs parsed out of the Stan CSV file header. These include the command configuration and the CSV file header row information. Uses deepcopy for immutability.

property method_vars: Dict[str, Variable]

Method variable names always end in __, e.g. lp__.

property stan_vars: Dict[str, Variable]

These are the user-defined variables in the Stan program.

RunSet

class cmdstanpy.stanfit.RunSet(args, chains=1, *, chain_ids=None, time_fmt='%Y%m%d%H%M%S', one_process_per_chain=True)[source]

Encapsulates the configuration and results of a call to any CmdStan inference method. Records the method return code and locations of all console, error, and output files.

RunSet objects are instantiated by the CmdStanModel class inference methods which validate all inputs, therefore “__init__” method skips input checks.

Parameters:
cmd(idx)[source]

Assemble CmdStan invocation. When running parallel chains from single process (2.28 and up), specify CmdStan arg num_chains and leave chain idx off CSV files.

Parameters:

idx (int) –

Return type:

List[str]

get_err_msgs()[source]

Checks console messages for each CmdStan run.

Return type:

str

save_csvfiles(dir=None)[source]

Moves CSV files to specified directory.

Parameters:

dir (Optional[str]) – directory path

Return type:

None

property chain_ids: List[int]

Chain ids.

property chains: int

Number of chains.

property csv_files: List[str]

List of paths to CmdStan output files.

property diagnostic_files: List[str]

List of paths to CmdStan hamiltonian diagnostic files.

property method: Method

CmdStan method used to generate this fit.

property model: str

Stan model name.

property num_procs: int

Number of processes run.

property one_process_per_chain: bool

When True, for each chain, call CmdStan in its own subprocess. When False, use CmdStan’s num_chains arg to run parallel chains. Always True if CmdStan < 2.28. For CmdStan 2.28 and up, sample method determines value.

property profile_files: List[str]

List of paths to CmdStan profiler files.

property stdout_files: List[str]

List of paths to transcript of CmdStan messages sent to the console. Transcripts include config information, progress, and error messages.

CompilerOptions

class cmdstanpy.compilation.CompilerOptions(*, stanc_options=None, cpp_options=None, user_header=None)[source]

User-specified flags for stanc and C++ compiler.

Parameters:
stanc_options - stanc compiler flags, options
cpp_options - makefile options
Type:

NAME=value

user_header - path to a user .hpp file to include during compilation
add(new_opts)[source]

Adds options to existing set of compiler options.

Parameters:

new_opts (CompilerOptions) –

Return type:

None

add_include_path(path)[source]

Adds include path to existing set of compiler options.

Parameters:

path (str) –

Return type:

None

compose(filename_in_msg=None)[source]

Format makefile options as list of strings.

Parameters:

filename_in_msg (str, optional) – filename to be displayed in stanc3 error messages (if different from actual filename on disk), by default None

Return type:

List[str]

is_empty()[source]

True if no options specified.

Return type:

bool

validate()[source]

Check compiler args. Raise ValueError if invalid options are found.

Return type:

None

validate_cpp_opts()[source]

Check cpp compiler args. Raise ValueError if bad config is found.

Return type:

None

validate_stanc_opts()[source]

Check stanc compiler args and consistency between stanc and C++ options. Raise ValueError if bad config is found.

Return type:

None

validate_user_header()[source]

User header exists. Raise ValueError if bad config is found.

Return type:

None

property cpp_options: Dict[str, Union[bool, int]]

C++ compiler options.

property stanc_options: Dict[str, Union[bool, int, str, Iterable[str]]]

Stanc compiler options.

property user_header: str

user header.

CmdStanArgs

class cmdstanpy.cmdstan_args.CmdStanArgs(model_name, model_exe, chain_ids, method_args, data=None, seed=None, inits=None, output_dir=None, sig_figs=None, save_latent_dynamics=False, save_profile=False, refresh=None)[source]

Container for CmdStan command line arguments. Consists of arguments common to all methods and and an object which contains the method-specific arguments.

Parameters:
compose_command(idx, csv_file, *, diagnostic_file=None, profile_file=None)[source]

Compose CmdStan command for non-default arguments.

Parameters:
Return type:

List[str]

validate()[source]

Check arguments correctness and consistency.

  • input files must exist

  • output files must be in a writeable directory

  • if no seed specified, set random seed.

  • length of per-chain lists equals specified # of chains

Return type:

None

SamplerArgs

class cmdstanpy.cmdstan_args.SamplerArgs(iter_warmup=None, iter_sampling=None, save_warmup=False, thin=None, max_treedepth=None, metric=None, step_size=None, adapt_engaged=True, adapt_delta=None, adapt_init_phase=None, adapt_metric_window=None, adapt_step_size=None, fixed_param=False, num_chains=1)[source]

Arguments for the NUTS adaptive sampler.

Parameters:
compose(idx, cmd)[source]

Compose CmdStan command for method-specific non-default arguments.

Parameters:
Return type:

List[str]

validate(chains)[source]

Check arguments correctness and consistency.

  • adaptation and warmup args are consistent

  • if file(s) for metric are supplied, check contents.

  • length of per-chain lists equals specified # of chains

Parameters:

chains (Optional[int]) –

Return type:

None

OptimizeArgs

class cmdstanpy.cmdstan_args.OptimizeArgs(algorithm=None, init_alpha=None, iter=None, save_iterations=False, tol_obj=None, tol_rel_obj=None, tol_grad=None, tol_rel_grad=None, tol_param=None, history_size=None, jacobian=False)[source]

Container for arguments for the optimizer.

Parameters:
compose(_idx, cmd)[source]

compose command string for CmdStan for non-default arg values.

Parameters:
Return type:

List[str]

validate(_chains=None)[source]

Check arguments correctness and consistency.

Parameters:

_chains (Optional[int]) –

Return type:

None

LaplaceArgs

class cmdstanpy.cmdstan_args.LaplaceArgs(mode, draws=None, jacobian=True)[source]

Arguments needed for laplace method.

Parameters:
compose(_idx, cmd)[source]

compose command string for CmdStan for non-default arg values.

Parameters:
Return type:

List[str]

validate(_chains=None)[source]

Check arguments correctness and consistency.

Parameters:

_chains (Optional[int]) –

Return type:

None

PathfinderArgs

class cmdstanpy.cmdstan_args.PathfinderArgs(init_alpha=None, tol_obj=None, tol_rel_obj=None, tol_grad=None, tol_rel_grad=None, tol_param=None, history_size=None, num_psis_draws=None, num_paths=None, max_lbfgs_iters=None, num_draws=None, num_elbo_draws=None, save_single_paths=False, psis_resample=True, calculate_lp=True)[source]

Container for arguments for Pathfinder.

Parameters:
compose(_idx, cmd)[source]

compose command string for CmdStan for non-default arg values.

Parameters:
Return type:

List[str]

validate(_chains=None)[source]

Check arguments correctness and consistency.

Parameters:

_chains (Optional[int]) –

Return type:

None

VariationalArgs

class cmdstanpy.cmdstan_args.VariationalArgs(algorithm=None, iter=None, grad_samples=None, elbo_samples=None, eta=None, adapt_iter=None, adapt_engaged=True, tol_rel_obj=None, eval_elbo=None, output_samples=None)[source]

Arguments needed for variational method.

Parameters:
compose(idx, cmd)[source]

Compose CmdStan command for method-specific non-default arguments.

Parameters:
Return type:

List[str]

validate(chains=None)[source]

Check arguments correctness and consistency.

Parameters:

chains (Optional[int]) –

Return type:

None