CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pystan

Python interface to Stan, a package for Bayesian inference

Pending
Overview
Eval results
Files

model-building.mddocs/

Model Building

Core functionality for building Stan models from program code, including data handling, caching, and compilation management. This module provides the primary entry point for creating executable Bayesian models from Stan probabilistic programming language code.

Capabilities

Model Compilation

Build and compile Stan programs into executable models with automatic caching and data integration.

def build(program_code: str, data: Data = frozendict(), random_seed: Optional[int] = None) -> Model:
    """
    Build (compile) a Stan program.

    Arguments:
        program_code: Stan program code describing a Stan model
        data: A Python dictionary or mapping providing data for the model.
              Variable names are keys and values are their associated values.
              Default is an empty dictionary, suitable for Stan programs with no data block.
        random_seed: Random seed, a positive integer for random number generation.
                    Used to make sure that results can be reproduced.

    Returns:
        Model: An instance of Model ready for sampling

    Raises:
        ValueError: If Stan code contains syntax or semantic errors
        
    Notes:
        - C++ reserved words and Stan reserved words may not be used for variable names
        - See the Stan User's Guide for a complete list of reserved words
        - Models are automatically cached based on program code hash
        - Data must be JSON-serializable
    """

Model Data Structure

The Model class encapsulates all information about a compiled Stan model.

@dataclass(frozen=True)
class Model:
    """
    Stores data associated with and proxies calls to a Stan model.
    
    Users will not instantiate this class directly. Use stan.build() instead.
    """
    model_name: str  # Unique identifier for the compiled model
    program_code: str  # Original Stan program code  
    data: Data  # Data dictionary used for the model
    param_names: Tuple[str, ...]  # Names of model parameters
    constrained_param_names: Tuple[str, ...]  # Names of all constrained parameters
    dims: Tuple[Tuple[int, ...]]  # Dimensions of parameters
    random_seed: Optional[int]  # Random seed used

Data Handling

Data structures and utilities for managing model data.

# Type alias for model data
Data = Dict[str, Union[int, float, Sequence[Union[int, float]]]]

class frozendict(dict):
    """
    Immutable dictionary implementation for default parameters.
    
    Raises:
        TypeError: When attempting to modify after creation
    """
    def __setitem__(self, key, value):
        raise TypeError("'frozendict' object is immutable.")

class DataJSONEncoder(json.JSONEncoder):
    """
    JSON encoder with numpy array support for model data serialization.
    
    Handles:
        - numpy.ndarray: Converted to nested lists
        - numpy integer types: Converted to Python int
    """
    def default(self, obj): ...

Usage Examples

Basic Model Building

import stan

# Simple normal model
program_code = """
parameters {
    real mu;
    real<lower=0> sigma;
}
model {
    mu ~ normal(0, 1);
    sigma ~ exponential(1);
}
"""

model = stan.build(program_code)
print(f"Model name: {model.model_name}")
print(f"Parameters: {model.param_names}")

Model with Data

import stan
import numpy as np

# Linear regression model
program_code = """
data {
    int<lower=0> N;
    vector[N] x;
    vector[N] y;
}
parameters {
    real alpha;
    real beta;
    real<lower=0> sigma;
}
model {
    y ~ normal(alpha + beta * x, sigma);
}
"""

# Prepare data
N = 100
x = np.random.normal(0, 1, N)
y = 2 + 3 * x + np.random.normal(0, 0.5, N)

data = {
    'N': N,
    'x': x.tolist(),
    'y': y.tolist()
}

model = stan.build(program_code, data=data, random_seed=123)

Error Handling

import stan

# Invalid Stan code
try:
    program_code = """
    parameters {
        real z
        real y
    }
    model {
        z ~ no_such_distribution();
    }
    """
    model = stan.build(program_code)
except ValueError as e:
    print(f"Stan compilation error: {e}")

Install with Tessl CLI

npx tessl i tessl/pypi-pystan

docs

bayesian-sampling.md

index.md

model-building.md

parameter-operations.md

results-analysis.md

tile.json