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.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]) –

Return type

None

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_cols: Dict[str, Tuple[int, ...]]

Returns a map from a Stan inference method variable to a tuple of column indices in inference engine’s output array. Method variable names always end in __, e.g. lp__. Uses deepcopy for immutability.

property stan_vars_cols: Dict[str, Tuple[int, ...]]

Returns a map from a Stan program variable name to a tuple of the column indices in the vector or matrix of estimates produced by a CmdStan inference method. Uses deepcopy for immutability.

property stan_vars_dims: Dict[str, Tuple[int, ...]]

Returns map from Stan program variable names to variable dimensions. Scalar types are mapped to the empty tuple, e.g., program variable int foo has dimension () and program variable vector[10] bar has single dimension (10). Uses deepcopy for immutability.

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
Return type

None

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: cmdstanpy.cmdstan_args.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.compiler_opts.CompilerOptions(*, stanc_options=None, cpp_options=None, user_header=None)[source]

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

Parameters
  • stanc_options (Optional[Dict[str, Any]]) –

  • cpp_options (Optional[Dict[str, Any]]) –

  • user_header (Optional[str]) –

Return type

None

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 (cmdstanpy.compiler_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()[source]

Format makefile options as list of strings.

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]]

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
Return type

None

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

Compose CmdStan command for non-default arguments.

Parameters
  • idx (int) –

  • csv_file (str) –

  • diagnostic_file (Optional[str]) –

  • profile_file (Optional[str]) –

  • num_chains (Optional[int]) –

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)[source]

Arguments for the NUTS adaptive sampler.

Parameters
  • iter_warmup (Optional[int]) –

  • iter_sampling (Optional[int]) –

  • save_warmup (bool) –

  • thin (Optional[int]) –

  • max_treedepth (Optional[int]) –

  • metric (Optional[Union[str, Dict[str, Any], List[str], List[Dict[str, Any]]]]) –

  • step_size (Optional[Union[float, List[float]]]) –

  • adapt_engaged (bool) –

  • adapt_delta (Optional[float]) –

  • adapt_init_phase (Optional[int]) –

  • adapt_metric_window (Optional[int]) –

  • adapt_step_size (Optional[int]) –

  • fixed_param (bool) –

Return type

None

compose(idx, cmd)[source]

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

Parameters
  • idx (int) –

  • cmd (List[str]) –

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)[source]

Container for arguments for the optimizer.

Parameters
  • algorithm (Optional[str]) –

  • init_alpha (Optional[float]) –

  • iter (Optional[int]) –

  • save_iterations (bool) –

  • tol_obj (Optional[float]) –

  • tol_rel_obj (Optional[float]) –

  • tol_grad (Optional[float]) –

  • tol_rel_grad (Optional[float]) –

  • tol_param (Optional[float]) –

  • history_size (Optional[int]) –

Return type

None

compose(idx, cmd)[source]

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

Parameters
  • idx (int) –

  • cmd (List[str]) –

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
  • algorithm (Optional[str]) –

  • iter (Optional[int]) –

  • grad_samples (Optional[int]) –

  • elbo_samples (Optional[int]) –

  • eta (Optional[float]) –

  • adapt_iter (Optional[int]) –

  • adapt_engaged (bool) –

  • tol_rel_obj (Optional[float]) –

  • eval_elbo (Optional[int]) –

  • output_samples (Optional[int]) –

Return type

None

compose(idx, cmd)[source]

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

Parameters
  • idx (int) –

  • cmd (List[str]) –

Return type

List[str]

validate(chains=None)[source]

Check arguments correctness and consistency.

Parameters

chains (Optional[int]) –

Return type

None