Stan Model API Reference

Stan probabilistic programming language integration and code generation.

This module provides the core functionality for translating SciStanPy models into Stan probabilistic programming language code and managing the complete Stan compilation and execution workflow. It handles automatic code generation, compilation management, and provides enhanced interfaces to Stan’s sampling algorithms.

The module implements a code generation system that organizes SciStanPy model components into proper Stan program structure, including automatic handling of dependency relationships, loop optimization, and efficient Stan code patterns.

Users will not normally interact with this module directly. Instead, they will either (1) use the Model.to_stan() method to convert a SciStanPy model to a StanModel instance or (2) use this module implicitly when fitting a SciStanPy model via the Model.mcmc() method.

Stan code generation is supported by four main classes, each described below. Users of SciStanPy will primarily interact with the StanModel class–the others classes are used internally to generate the Stan code.

Quickly navigate to a section:

Abstract Base for Stan Code Components

class scistanpy.model.stan.stan_model.StanCodeBase(parent_loop: StanCodeBase | None)[source]

Bases: ABC, list

Abstract base class for Stan code organization and generation.

This class provides the foundational infrastructure for organizing and generating Stan code from SciStanPy model components. It implements a hierarchical structure that mirrors the nested scope organization required by Stan programs.

Parameters:

parent_loop (Optional[StanCodeBase]) – Parent code block in the hierarchy, or None for root

Variables:

parent_loop – Reference to parent code block for hierarchical organization

The class serves as both a container for model components and for-loop constructs, and as a code generator that can produce appropriate Stan syntax for different program blocks (model, transformed parameters, etc.).

Key Features:
  • Hierarchical organization of code blocks and loops

  • Automatic Stan syntax generation for different program sections

  • Component filtering and organization based on block requirements

  • Proper indentation and formatting management

  • Loop optimization and combination capabilities

abstract property allowed_index_names: tuple[str, ...]
combine_lines(
lines: list[str],
indentation_level: custom_types.Integer | None = None,
) str[source]

Combine multiple Stan code lines with proper formatting.

Parameters:
  • lines (list[str]) – List of code lines to combine

  • indentation_level (Optional[custom_types.Integer]) – Indentation level for all lines. Defaults to None.

Returns:

Combined and formatted Stan code block

Return type:

str

Applies consistent formatting and indentation to all provided lines, creating a properly structured Stan code block.

abstract property depth: custom_types.Integer

Get the nesting depth of this code block.

Returns:

Depth level in the code hierarchy

Return type:

custom_types.Integer

finalize_line(
text: str,
indendation_level: custom_types.Integer | None = None,
) str[source]

Apply proper indentation and Stan syntax formatting to code lines.

Parameters:
  • text (str) – Raw code text to format

  • indendation_level (Optional[custom_types.Integer]) – Indentation level (uses current depth if None). Defaults to None.

Returns:

Properly formatted Stan code line

Return type:

str

This method handles:
  • Consistent indentation based on scope depth

  • Automatic semicolon insertion for statements

  • Proper formatting for control structures and comments

abstract property generated_quantities_prefix: str
get_generated_quantities(declarations: str | tuple[str, ...]) str[source]

Generate Stan code for generated quantities block.

Parameters:

declarations (Union[str, tuple[str, ...]]) – Variable declarations for the block

Returns:

Stan code for generated quantities block

Return type:

str

Creates the generated quantities block for posterior predictive sampling and derived quantity computation.

abstractmethod get_parent_loop(n: custom_types.Integer) StanCodeBase[source]
get_target_incrementation(_dummy: tuple[str, ...] | None = None) str[source]

Generate Stan code for model block target variable incrementation.

Parameters:

_dummy (Optional[tuple[str, ...]]) – Unused parameter for interface compatibility. Defaults to None.

Returns:

Stan code for model block.

Return type:

str

This method generates the model block containing all log-probability (target) increment statements for parameters and observables.

get_transformation_assignment(declarations: str | tuple[str, ...]) str[source]

Generate Stan code for transformed parameters block.

Parameters:

declarations (Union[str, tuple[str, ...]]) – Variable declarations for the block

Returns:

Stan code for transformed parameters block

Return type:

str

Creates the transformed parameters block containing all deterministic transformations.

get_transformed_data_assignment(declarations: str | tuple[str, ...]) str[source]

Generate Stan code for transformed data block.

Parameters:

declarations (Union[str, tuple[str, ...]]) – Variable declarations for the block

Returns:

Stan code for transformed data block

Return type:

str

Creates the transformed data block for preprocessing and deterministic data transformations.

property model_components: list[AbstractModelComponent]

Get all model components at this level.

Returns:

List of direct child model components

Return type:

list[AbstractModelComponent]

property nested_loops

Get all nested for-loops at this level.

Returns:

List of direct child for-loops

Return type:

list[StanForLoop]

recurse_for_loops(
yield_self: bool = True,
) Generator[StanForLoop, None, None][source]

Generate all for-loops in the program hierarchy.

This method recursively traverses the code structure to yield all for-loop constructs, enabling comprehensive analysis and optimization of the loop structure.

Parameters:

yield_self (bool) – Whether to include this loop in the output. Defaults to True.

Yields:

All StanForLoop instances in the hierarchy

Return type:

Generator[StanForLoop, None, None]

The traversal follows a depth-first pattern, yielding the current level before recursing into nested loops, ensuring proper processing order for loop optimization procedures.

recurse_model_components() Generator[AbstractModelComponent, None, None][source]

Recursively generate all model components in the program.

This method traverses the code structure to yield all SciStanPy model components.

Yields:

All model components in the code hierarchy

Return type:

Generator[AbstractModelComponent, None, None]

This is essential for global analysis of model structure, dependency validation, and code generation across all program blocks.

abstract property target_inc_prefix: str
abstract property transformation_assi_prefix: str
abstract property transformed_data_prefix: str

For Loop Representation in Stan Code

class scistanpy.model.stan.stan_model.StanForLoop(
parent_loop: StanCodeBase,
record_in_parent: bool = True,
)[source]

Bases: StanCodeBase

Represents a Stan for-loop construct with optimization capabilities.

This class manages individual for-loop constructs in Stan code, including automatic loop range determination, optimization through combination with compatible loops, and proper nesting within the code hierarchy.

Parameters:
  • parent_loop (StanCodeBase) – Parent code block containing this loop

  • record_in_parent (bool) – Whether to automatically add this loop to parent. Defaults to True.

Variables:

parent_loop – Reference to parent code block

Key Features:
  • Automatic loop range calculation based on component dimensions

  • Loop combination optimization for compatible adjacent loops

  • Singleton loop detection and elimination

  • Proper index variable management and scope resolution

  • Hierarchical ancestry tracking for scope navigation

The class automatically determines loop ranges by analyzing the dimensions of nested model components and provides optimization features like loop combination to generate efficient Stan code.

property allowed_index_names: tuple[str, ...]

Get allowed index variable names from the root program.

Returns:

Tuple of allowed index variable names

Return type:

tuple[str, …]

property ancestry

Get the complete ancestry chain of this loop.

Returns:

List of ancestor code blocks from root to immediate parent

Return type:

list[StanCodeBase]

append(
component: StanForLoop | AbstractModelComponent,
) None[source]

Add a component to this loop with depth validation.

Parameters:

component (Union[StanForLoop, AbstractModelComponent]) – Component to add to the loop

Raises:

AssertionError – If component depth doesn’t match loop depth

Ensures that only components with appropriate nesting depth are added to maintain proper Stan code structure.

copy(record_in_parent: bool = False) StanForLoop[source]

Create a shallow copy of this loop.

Parameters:

record_in_parent (bool) – Whether to register copy with parent. Defaults to False.

Returns:

New loop instance with same contents

Return type:

StanForLoop

Creates a copy with the same parent loop and components, useful for loop combination and optimization operations.

property depth: custom_types.Integer

Get the nesting depth of this loop. This is equivalent to the number of ancestor loops.

Returns:

Depth level based on number of ancestors

Return type:

custom_types.Integer

property end: custom_types.Integer

Calculate the end value (iteration count) for this loop.

Returns:

Number of iterations for this loop

Return type:

custom_types.Integer

Raises:

ValueError – If components have incompatible dimension sizes

Automatically determines loop range by analyzing the dimensions of all nested model components at the appropriate depth level. Handles dimension compatibility checking and singleton dimension filtering.

property generated_quantities_prefix: str

Get Stan code prefix for generated quantities block loops.

Returns:

Stan for-loop syntax for generated quantities block

Return type:

str

get_parent_loop(n: custom_types.Integer) StanCodeBase[source]

Get ancestor loop at specified level in the hierarchy.

Parameters:

n (custom_types.Integer) – Ancestry level to retrieve (clipped to available range). For example, 0 returns the root loop; -1 returns this loop.

Returns:

Ancestor loop at the specified level

Return type:

StanCodeBase

property loop_index: str

Get the index variable name for this loop (e.g., ‘i’ if loop construct is written as for (i in 1:10) {).

Returns:

Index variable name based on depth

Return type:

str

property program: StanProgram

Get the root Stan program containing this loop.

Returns:

Root StanProgram instance

Return type:

StanProgram

squash() None[source]

Remove singleton loops by moving contents to parent.

This optimization method detects when a loop has only one iteration (singleton) and eliminates the unnecessary loop construct by moving its contents directly to the parent scope.

property target_inc_prefix: str

Get Stan code prefix for model block loops.

Returns:

Stan for-loop syntax for model block

Return type:

str

property transformation_assi_prefix: str

Get Stan code prefix for transformed parameters block loops.

Returns:

Stan for-loop syntax for transformed parameters block

Return type:

str

property transformed_data_prefix: str

Get Stan code prefix for transformed data block loops.

Returns:

Stan for-loop syntax for transformed data block

Return type:

str

Base Stan Program Structure

class scistanpy.model.stan.stan_model.StanProgram(model: Model)[source]

Bases: StanCodeBase

Complete Stan program generation and management.

This class orchestrates the generation of complete Stan programs from SciStanPy models, handling dependency analysis, component organization, and the generation of all required Stan program blocks.

Parameters:

model (scistanpy.Model) – SciStanPy model to convert to Stan

Variables:
  • model – Reference to the source SciStanPy model

  • node_to_depth – Mapping from components to their hierarchy depth

  • all_varnames – Set of all variable names in the program

  • all_paramnames – Set of all parameter names

  • autogathered_varnames – Set of variables whose data will be automatically gathered from the SciStanPy model.

  • user_provided_varnames – Set of variables whose data the user must provide (i.e., the names of observable parameters).

The class performs comprehensive analysis of the SciStanPy model to:
  • Build dependency graphs and determine component ordering

  • Generate appropriate variable names avoiding conflicts

  • Organize components into proper Stan program structure

  • Create optimized loop constructs for multi-dimensional components

  • Generate all required Stan program blocks with proper syntax

The code is generated following the below procedure:
  1. Dependency Analysis: Build component dependency graph

  2. Depth Assignment: Determine nesting levels for components

  3. Loop Organization: Create optimized for-loop structures

  4. Block Generation: Generate all Stan program blocks

  5. Code Formatting: Apply Stan canonical formatting

property allowed_index_names: tuple[str, ...]

Get allowed index variable names avoiding conflicts.

Returns:

Tuple of allowed index variable names

Return type:

tuple[str, …]

append(
component: StanForLoop | AbstractModelComponent,
) None[source]

Add component to program with depth validation.

Parameters:

component (Union[StanForLoop, AbstractModelComponent]) – Component to add to the program

Raises:

AssertionError – If component depth is not 0 (root level)

Ensures only root-level components are added directly to the program.

build_node_to_depth() dict[AbstractModelComponent, int][source]

Build mapping from model components to their maximum hierarchy depth.

Returns:

Dictionary mapping components to their depth levels

Return type:

dict[AbstractModelComponent, int]

This method analyzes the SciStanPy model’s dependency graph to determine the maximum depth of each component relative to the root constants. This information is crucial for proper code ordering and loop organization.

property code: str

Generate complete Stan program code.

Returns:

Complete Stan program as formatted string

Return type:

str

Assembles all program blocks into a complete Stan program with proper formatting and structure.

compile() None[source]

Organize model components into proper Stan program structure.

This method performs the core compilation process:
  1. Determines topological ordering of components based on dependencies

  2. Organizes components into appropriate loop structures

  3. Creates and optimizes for-loop constructs

  4. Eliminates singleton loops for efficiency

The compilation process ensures that all dependencies are satisfied and that the resulting Stan code is properly structured and efficient.

property data_block: str

Generate Stan data block with observable and constant declarations.

Returns:

Stan data block code

Return type:

str

Creates the data block containing declarations for all observables (user-provided data) and constants (auto-gathered from model).

property depth: custom_types.Integer

Get the depth of the program (always 0 for root).

Returns:

Depth level (always 0)

Return type:

custom_types.Integer

property functions_block: str

Generate Stan functions block with custom function includes.

Returns:

Stan functions block code or empty string if no functions needed

Return type:

str

Automatically determines required supporting functions from model components and generates appropriate include statements and function definitions for the Stan functions block.

property generated_quantities_block: str

Generate Stan generated quantities block.

Returns:

Stan generated quantities block code

Return type:

str

Creates the generated quantities block for posterior predictive sampling and derived quantity computation.

property generated_quantities_prefix: str

Get prefix for generated quantities block.

Returns:

Stan generated quantities block opening syntax

Return type:

str

get_parent_loop(n: custom_types.Integer) StanCodeBase[source]

Get parent loop (only self is available for root program).

Parameters:

n (custom_types.Integer) – Must be -1 or 0 for root program

Returns:

Self (root program)

Return type:

StanCodeBase

Raises:

AssertionError – If n is not -1 or 0

get_varnames() tuple[set[str], set[str], set[str], set[str]][source]

Extract and categorize all variable names from the model.

Returns:

Tuple of (all_varnames, all_paramnames, autogathered_varnames, user_provided_varnames)

Return type:

tuple[set[str], set[str], set[str], set[str]]

Raises:

ValueError – If variable name collisions are detected

Analyzes the model to categorize variables into:
  • All variable names (for conflict detection)

  • Parameter names (for Stan parameters block)

  • Auto-gathered names (constants from model)

  • User-provided names (observables requiring external data)

property model_block: str

Generate Stan model block with log-probability statements.

Returns:

Stan model block code

Return type:

str

Creates the model block containing all target increment statements for priors and likelihoods.

property parameters_block: str

Generate Stan parameters block with parameter declarations.

Returns:

Stan parameters block code

Return type:

str

Creates the parameters block containing all model parameters that will be sampled during MCMC.

recurse_for_loops() Generator[StanForLoop, None, None][source]

Generate all for-loops in the program (excluding self).

Yields:

All StanForLoop instances in the program

Return type:

Generator[StanForLoop, None, None]

This method yields only the nested for-loops, not the program itself, which is different from the StanForLoop sibling class.

property target_inc_prefix: str

Get prefix for model block.

Returns:

Stan model block opening syntax

Return type:

str

property transformation_assi_prefix: str

Get prefix for transformed parameters block.

Returns:

Stan transformed parameters block opening syntax

Return type:

str

property transformed_data_block: str

Generate Stan transformed data block.

Returns:

Stan transformed data block code or empty string if not needed

Return type:

str

Creates the transformed data block for any deterministic data transformations required by the model.

property transformed_data_prefix: str

Get prefix for transformed data block.

Returns:

Stan transformed data block opening syntax

Return type:

str

property transformed_parameters_block: str

Generate Stan transformed parameters block.

Returns:

Stan transformed parameters block code

Return type:

str

Creates the transformed parameters block for deterministic parameter transformations and derived quantities.

Stan Model Representation

class scistanpy.model.stan.stan_model.StanModel(
model: Model,
output_dir: str,
force_compile: bool = False,
stanc_options: dict[str, Any] | None = None,
cpp_options: dict[str, Any] | None = None,
user_header: str | None = None,
model_name: str = 'model',
)[source]

Bases: CmdStanModel

Enhanced CmdStanModel with SciStanPy integration.

This class extends CmdStanPy’s CmdStanModel to provide integration with SciStanPy models, including automatic Stan code generation, enhanced sampling interfaces, and comprehensive result processing.

Parameters:
  • model (scistanpy.Model) – SciStanPy model to compile to Stan

  • output_dir (str) – Directory for Stan files and compilation.

  • force_compile (bool) – Whether to force recompilation. Defaults to False.

  • stanc_options (Optional[dict[str, Any]]) – Options for Stan compiler. Defaults to None (uses defaults).

  • cpp_options (Optional[dict[str, Any]]) – Options for C++ compilation. Defaults to None (uses defaults).

  • user_header (Optional[str]) – Custom C++ header code. Defaults to None.

  • model_name (str) – Name for compiled model. Defaults to ‘model’.

Variables:
  • model – Reference to source SciStanPy model

  • program – Generated StanProgram instance

  • output_dir – Directory containing Stan files

  • stan_executable_path – Path to compiled Stan executable

Key Features:
  • Automatic Stan code generation from SciStanPy models

  • Enhanced sampling with prior initialization and validation

  • Automatic data gathering for observables and constants

  • Comprehensive result processing and structuring

  • Integration with ArviZ for Bayesian workflow support

The class handles the complete workflow from SciStanPy model to Stan execution, providing an interface that abstracts away the complexities of Stan code generation and compilation management.

property all_varnames: set[str]

Get all variable names with Stan-compatible formatting.

Returns:

Set of all variable names (dots replaced with double underscores)

Return type:

set[str]

property autogathered_data: dict[str, ndarray[tuple[int, ...], dtype[_ScalarType_co]]]

Get automatically gathered data from model constants.

Returns:

Dictionary of constant values from SciStanPy model

Return type:

dict[str, npt.NDArray]

code() str[source]

Get the complete Stan program code.

Returns:

Stan program code as formatted string

Return type:

str

Returns the complete, formatted Stan program generated from the SciStanPy model for inspection or external use.

gather_inputs(
**observables: custom_types.SampleType,
) dict[str, 'custom_types.SampleType'][source]

Gather complete input data for Stan sampling.

Parameters:

observables (dict[str, custom_types.SampleType]) – User-provided data for observable parameters

Returns:

Complete data dictionary for Stan sampling

Return type:

dict[str, custom_types.SampleType]

Raises:
  • ValueError – If required observables are missing or extra observables provided

  • ValueError – If observable shapes don’t match model specifications

This method combines user-provided observable data with automatically gathered constants and hyperparameters to create the complete data input required for Stan sampling.

Data Processing:
  • Validates all required observables are provided

  • Checks shape compatibility between data and model specifications

  • Automatically gathers constants and hyperparameters from model

  • Handles variable name transformation (dots to double underscores)

generate_quantities(
data: Mapping[str, Any] | str | PathLike | None = None,
previous_fit: Fit | List[str] | None = None,
seed: int | None = None,
gq_output_dir: str | PathLike | None = None,
sig_figs: int | None = None,
show_console: bool = False,
refresh: int | None = None,
time_fmt: str = '%Y%m%d%H%M%S',
timeout: float | None = None,
*,
mcmc_sample: CmdStanMCMC | List[str] | None = None,
) CmdStanGQ[Fit]

Enhanced generate_quantities with automatic data gathering.

Automatically gathers required data from SciStanPy model. Experimental feature.

Warning:

This method is experimental and not thoroughly tested.

get_varnames_to_dimnames() dict[str, list[str]][source]

Create mapping from variable names to dimension names for ArviZ.

Returns:

Dictionary mapping variable names to their dimension names

Return type:

dict[str, list[str]]

This mapping is essential for creating properly structured ArviZ InferenceData objects with appropriate coordinate information.

laplace_sample(
data: Mapping[str, Any] | str | PathLike | None = None,
mode: CmdStanMLE | str | PathLike | None = None,
draws: int | None = None,
*,
jacobian: bool = True,
seed: int | None = None,
output_dir: str | PathLike | None = None,
sig_figs: int | None = None,
save_profile: bool = False,
show_console: bool = False,
refresh: int | None = None,
time_fmt: str = '%Y%m%d%H%M%S',
timeout: float | None = None,
opt_args: Dict[str, Any] | None = None,
) CmdStanLaplace

Enhanced laplace_sample with automatic data gathering.

Automatically gathers required data from SciStanPy model. Experimental feature.

Warning:

This method is experimental and not thoroughly tested.

log_prob(
params: Dict[str, Any] | str | PathLike,
data: Mapping[str, Any] | str | PathLike | None = None,
*,
jacobian: bool = True,
sig_figs: int | None = None,
) DataFrame

Enhanced log_prob with automatic data gathering.

Automatically gathers required data from SciStanPy model. Experimental feature.

Warning:

This method is experimental and not thoroughly tested.

optimize(
data: Mapping[str, Any] | str | PathLike | None = None,
seed: int | None = None,
inits: Mapping[str, Any] | float | str | PathLike | None = None,
output_dir: str | PathLike | None = None,
sig_figs: int | None = None,
save_profile: bool = False,
algorithm: str | None = None,
init_alpha: float | None = None,
tol_obj: float | None = None,
tol_rel_obj: float | None = None,
tol_grad: float | None = None,
tol_rel_grad: float | None = None,
tol_param: float | None = None,
history_size: int | None = None,
iter: int | None = None,
save_iterations: bool = False,
require_converged: bool = True,
show_console: bool = False,
refresh: int | None = None,
time_fmt: str = '%Y%m%d%H%M%S',
timeout: float | None = None,
jacobian: bool = False,
) CmdStanMLE

Enhanced optimize with automatic data gathering.

Automatically gathers required data from SciStanPy model. Experimental feature.

Warning:

This method is experimental and not thoroughly tested.

pathfinder(
data: Mapping[str, Any] | str | PathLike | None = None,
*,
init_alpha: float | None = None,
tol_obj: float | None = None,
tol_rel_obj: float | None = None,
tol_grad: float | None = None,
tol_rel_grad: float | None = None,
tol_param: float | None = None,
history_size: int | None = None,
num_paths: int | None = None,
max_lbfgs_iters: int | None = None,
draws: int | None = None,
num_single_draws: int | None = None,
num_elbo_draws: int | None = None,
psis_resample: bool = True,
calculate_lp: bool = True,
seed: int | None = None,
inits: Dict[str, float] | float | str | PathLike | None = None,
output_dir: str | PathLike | None = None,
sig_figs: int | None = None,
save_profile: bool = False,
show_console: bool = False,
refresh: int | None = None,
time_fmt: str = '%Y%m%d%H%M%S',
timeout: float | None = None,
num_threads: int | None = None,
) CmdStanPathfinder

Enhanced pathfinder with automatic data gathering.

Automatically gathers required data from SciStanPy model. Experimental feature.

Warning:

This method is experimental and not thoroughly tested.

sample(
*args,
precision: Literal['double', 'single', 'half'] = 'single',
mib_per_chunk: custom_types.Integer | None = None,
use_dask: bool = False,
**kwargs,
) results.SampleResults[source]

Execute MCMC sampling with enhanced SciStanPy integration.

Parameters:
  • args – Positional arguments passed to CmdStanModel.sample

  • precision (Literal["double", "single", "half"]) – Numerical precision for result arrays. Defaults to ‘single’.

  • mib_per_chunk (Optional[custom_types.Integer]) – When using dask, memory limit per chunk for large arrays. Defaults to None (uses Dask default).

  • use_dask (bool) – Whether to use Dask for large array processing. Defaults to False.

  • kwargs – Keyword arguments passed to CmdStanModel.sample

Returns:

Comprehensive sampling results with SciStanPy integration

Return type:

results.SampleResults

Enhanced Features:
  • Automatic data gathering from SciStanPy model

  • Prior-based initialization when requested

  • Result processing and structuring

  • Memory-efficient handling of large result arrays

  • Integration with SciStanPy’s result analysis tools

The method provides an interface that handles all the complexities of data preparation and result processing while maintaining full compatibility with CmdStanPy’s sampling options.

property stan_program_path: str

Get path to the generated Stan program file.

Returns:

Full path to .stan file

Return type:

str

variational(
data: Mapping[str, Any] | str | PathLike | None = None,
seed: int | None = None,
inits: float | None = None,
output_dir: str | PathLike | None = None,
sig_figs: int | None = None,
save_latent_dynamics: bool = False,
save_profile: bool = False,
algorithm: str | None = None,
iter: int | None = None,
grad_samples: int | None = None,
elbo_samples: int | None = None,
eta: float | None = None,
adapt_engaged: bool = True,
adapt_iter: int | None = None,
tol_rel_obj: float | None = None,
eval_elbo: int | None = None,
draws: int | None = None,
require_converged: bool = True,
show_console: bool = False,
refresh: int | None = None,
time_fmt: str = '%Y%m%d%H%M%S',
timeout: float | None = None,
*,
output_samples: int | None = None,
) CmdStanVB

Enhanced variational with automatic data gathering.

Automatically gathers required data from SciStanPy model. Experimental feature.

Warning:

This method is experimental and not thoroughly tested.

write_stan_program() None[source]

Write and format the generated Stan program to disk.

This method writes the Stan program code to a .stan file in the output directory and applies Stan’s canonical formatting for consistency and readability.

The written file can be inspected, modified, or used independently of SciStanPy for debugging or optimization purposes.