Constants API Reference

Constant value components for SciStanPy models.

This module provides the Constant class for representing fixed values in SciStanPy models. Constants serve as the foundational building blocks for model hierarchies, providing fixed hyperparameters, unmodeled data values, and other numerical components that don’t change during inference.

The Constant class integrates with SciStanPy’s model component hierarchy while providing specialized functionality for fixed-value components. It is particularly important for interactive model manipulation during prior predictive checks.

Basic Usage:

import scistanpy as ssp
import numpy as np

# Scalar constants
learning_rate = ssp.constants.Constant(0.01)
n_samples = ssp.constants.Constant(100)

# Array constants
design_matrix = ssp.constants.Constant(X_data)
time_points = ssp.constants.Constant(np.linspace(0, 10, 11))

# Constants with bounds
probability = ssp.constants.Constant(0.5, lower_bound=0.0, upper_bound=1.0)

# Force constant to NOT be modifiable in interactive contexts
temperature = ssp.constants.Constant(
    300.0,
    lower_bound=250.0,
    upper_bound=350.0,
    togglable=False
)

As of now, there is a single class in this module:

class scistanpy.model.components.constants.Constant(
value: 'custom_types.Integer' | 'custom_types.Float' | npt.NDArray | np.integer | np.floating,
*,
lower_bound: 'custom_types.Float' | None = None,
upper_bound: 'custom_types.Float' | None = None,
togglable: bool | None = None,
enforce_uniformity: bool = False,
**kwargs,
)[source]

Bases: AbstractModelComponent

Represents a constant value component in SciStanPy models.

This class wraps fixed numerical values to integrate them into the SciStanPy model component hierarchy. Constants provide the foundation for model construction by supplying fixed hyperparameters, unmodeled data, and other numerical values that remain unchanged during inference.

Parameters:
  • value (Union[custom_types.Integer, custom_types.Float, npt.NDArray, np.integer, np.floating]) – The constant value to wrap

  • lower_bound (Optional[custom_types.Float]) – Optional lower bound for value validation. Defaults to None.

  • upper_bound (Optional[custom_types.Float]) – Optional upper bound for value validation. Defaults to None.

  • togglable (Optional[bool]) – Whether value can be toggled in interactive interfaces. Auto-detected if None. Defaults to None.

  • enforce_uniformity (bool) – Whether to require all array elements to be identical. Defaults to False.

  • kwargs – Additional keyword arguments passed to parent class

Variables:
  • value – The stored constant value as a NumPy array

  • BASE_STAN_DTYPE – Stan data type (“real” or “int”) inferred from value

  • LOWER_BOUND – Lower bound constraint (if specified)

  • UPPER_BOUND – Upper bound constraint (if specified)

  • is_togglable – Whether the constant can be modified in interactive contexts

Raises:
  • ValueError – If value violates specified bounds

  • ValueError – If enforce_uniformity=True but array has non-uniform values

Key Features:
  • Automatic Type Inference: Determines appropriate Stan data types

  • Bound Checking: Validates values against optional constraints

  • Interactive Support: Configures sliders for model exploration

The class automatically handles:
  • Conversion of Python scalars to NumPy arrays

  • Shape inference from array inputs

  • Data type detection for Stan code generation

  • Bound validation at initialization

Hint

Under the hood, the Model.prior_predictive() method parses the model components to identify constants. Any identified constant with is_togglable=True is represented as an interactive slider in the generated interface. Updating slider values updates the underlying constant value used in the model.

Important

By default, constants with floating-point values are considered togglable=True, allowing interactive modification. Integer-valued constants are togglable=False by default to prevent invalid states. As a result, it is important to specify true data types when defining constants to ensure desired behavior. For example,

>>> n = ssp.Constant(100)  # n is not togglable
>>> n = ssp.Constant(100.0)  # n is togglable

This is also important when defining parameters, as raw Python integers and floats are converted to constants interally. For example,

>>> mean = ssp.Normal(mu = 0, sigma = 1)  # Neither mu nor sigma are togglable
>>> mean = ssp.Normal(mu = 0.0, sigma = 1.0)  # Both mu and sigma are togglable
property enforce_uniformity: bool

Check if uniformity enforcement is enabled.

Returns:

True if uniformity is enforced

Return type:

bool

Raises:

ValueError – If uniformity is enforced but value is not uniform

When enabled, this property ensures that all elements of array-valued constants have the same value, which is useful for symmetric priors and other modeling contexts requiring uniform parameters.

get_right_side(
index_opts: tuple[str, ...] | None,
start_dims: dict[str, 'custom_types.Integer'] | None = None,
end_dims: dict[str, 'custom_types.Integer'] | None = None,
offset_adjustment: int = 0,
) str[source]

Return Stan code for right-hand side (empty for constants).

Parameters:
  • index_opts (Optional[tuple[str, ...]]) – Indexing options (unused for constants)

  • start_dims (Optional[dict[str, custom_types.Integer]]) – Starting dimensions (unused for constants)

  • end_dims (Optional[dict[str, custom_types.Integer]]) – Ending dimensions (unused for constants)

  • offset_adjustment (int) – Index offset (unused for constants)

Returns:

Empty string (constants don’t have right-hand side expressions)

Return type:

str

There is no right-hand side expression for constants, as they represent fixed values rather than derived quantities. Thus, this method returns an empty string.

property slider_end: custom_types.Float

Get ending value for interactive sliders when constant is used for interactive prior predictive checks.

Returns:

Appropriate ending value for sliders

Return type:

custom_types.Float

Returns the upper bound if specified, otherwise calculates a reasonable upper limit based on the value’s order of magnitude.

property slider_start: custom_types.Float

Get starting value for interactive sliders when constant is used for interactive prior predictive checks.

Returns:

Appropriate starting value for sliders

Return type:

custom_types.Float

Returns the lower bound if specified, otherwise calculates a reasonable lower limit based on the value’s order of magnitude.

property slider_step_size: custom_types.Float

Get step size for interactive sliders when constant is used for interactive prior predictive checks.

Returns:

Appropriate step size for sliders

Return type:

custom_types.Float

Calculates a step size that provides approximately 100 steps between the slider start and end values, enabling fine-grained control.

property torch_parametrization: torch.Tensor

Get PyTorch tensor representation of the constant.

Returns:

PyTorch tensor containing the constant value

Return type:

torch.Tensor

Provides a tensor representation for PyTorch-based computations, enabling integration with gradient-based operations.