Transformed Parameters API Reference¶
Parameter transformation components for SciStanPy models.
This module provides a comprehensive library of mathematical transformations that can be applied to model parameters. These transformations enable complex model construction through composition of simple mathematical operations while maintaining automatic differentiation capabilities and Stan code generation.
The transformation system supports the following classes of operations:
- Basic Arithmetic via Python Operators
Addition (
+
) viaAddParameter
Subtraction (
-
) viaSubtractParameter
Multiplication (
*
) viaMultiplyParameter
Division (
/
) viaDivideParameter
Power (
**
) viaPowerParameter
Negation (Unary
-
) viaNegateParameter
- Standard Mathematical Functions
Absolute Value via
AbsParameter
Natural Logarithm via
LogParameter
Exponential via
ExpParameter
Sigmoid via
SigmoidParameter
Log Sigmoid via
LogSigmoidParameter
\(\log{1 + \exp{x}}\) via
Log1pExpParameter
- Normalization Operations
Normalization (sum to 1) via
NormalizeParameter
Log-Space Normalization (sum of exponents to 1) via
NormalizeLogParameter
- Reduction Operations
Sum Reduction via
SumParameter
Log-Sum-Exp via
LogSumExpParameter
- Growth Models
Exponential Growth via
ExponentialGrowth
orBinaryExponentialGrowth
Log Exponential Growth via
LogExponentialGrowth
orBinaryLogExponentialGrowth
Sigmoid Growth via
SigmoidGrowth
orSigmoidGrowthInitParametrization
Log Sigmoid Growth via
LogSigmoidGrowth
orLogSigmoidGrowthInitParametrization
- Special Functions
Sequence Convolution via
ConvolveSequence
- Indexing and Array Operations
Indexing and slicing via
IndexParameter
Note that none of these classes will typically be instantiated directly. Instead, end users will access them either via Python’s inbuilt operators between other model components or else use SciStanPy’s operations
submodule.
Base Classes¶
Transformed parameters are composed using a hierarchy of base classes that define their behavior and interfaces. The main base classes are:
TransformableParameter
, which activates operator overloading for mathematical expressions. Note that, in addition toTransformedParameter
subclasses, allContinuousDistribution
subclasses also inherit from this class. Classes that inherit from this base are, as the name suggests, transformable via any Python operators or functions defined in theoperations
module.
Transformation
, which is the abstract base class for all transformations (i.e., bothTransformedParameter
andTransformedData
). This class defines the core interface and behavior for all transformed parameters, including methods for drawing samples, generating Stan code, and managing parent components.
TransformedParameter
, which is the base class for all SciStanPy transformed parameters.
UnaryTransformedParameter
, which is a convenience base class for transformations that take a single input parameter.
BinaryTransformedParameter
, which is a convenience base class for transformations that take two input parameters.
Documentation for each of these base classes is provided below:
- class scistanpy.model.components.transformations.transformed_parameters.TransformableParameter[source]¶
Bases:
object
Mixin class enabling mathematical operator overloading for parameters.
This mixin class provides Python operator overloading capabilities that allow parameters to be combined using natural mathematical syntax. Each operator creates an appropriate TransformedParameter instance that represents the mathematical operation.
- The mixin supports the following Python arithmetic operators:
Addition (
+
), subtraction (-
)Multiplication (
*
), division (/
)Exponentiation (
**
)Unary negation (
-
)
Each operation supports both left and right operand positioning, enabling flexible mathematical expressions with mixed parameter and constant types.
- Example:
>>> param1 = Normal(mu=0, sigma=1) >>> param2 = Normal(mu=1, sigma=0.5) >>> # All of these create TransformedParameter instances >>> sum_param = param1 + param2 >>> scaled_param = 2 * param1 >>> ratio_param = param1 / param2 >>> power_param = param1 ** 2 >>> negated_param = -param1
- __add__(other: custom_types.CombinableParameterType)[source]¶
See
AddParameter
.
- __mul__(other: custom_types.CombinableParameterType)[source]¶
See
MultiplyParameter
.
- __neg__()[source]¶
See
NegateParameter
.
- __pow__(other: custom_types.CombinableParameterType)[source]¶
See
PowerParameter
.
- __radd__(other: custom_types.CombinableParameterType)[source]¶
See
AddParameter
.
- __rmul__(other: custom_types.CombinableParameterType)[source]¶
See
MultiplyParameter
.
- __rpow__(other: custom_types.CombinableParameterType)[source]¶
See
PowerParameter
.
- __rsub__(other: custom_types.CombinableParameterType)[source]¶
See
SubtractParameter
.
- __rtruediv__(other: custom_types.CombinableParameterType)[source]¶
See
DivideParameter
.
- __sub__(other: custom_types.CombinableParameterType)[source]¶
See
SubtractParameter
.
- __truediv__(other: custom_types.CombinableParameterType)[source]¶
See
DivideParameter
.
- class scistanpy.model.components.transformations.transformed_parameters.Transformation(
- *,
- shape: tuple['custom_types.Integer', ...] | 'custom_types.Integer' = (),
- **model_params: custom_types.CombinableParameterType,
Bases:
AbstractModelComponent
Base class for all parameter transformations in SciStanPy.
This abstract base class provides the foundational infrastructure for creating transformations that can be used in both the transformed parameters and transformed data blocks of Stan models. It handles the common aspects of transformation operations including shape validation and Stan code generation.
- Variables:
SHAPE_CHECK – Whether to perform automatic shape checking. Defaults to True.
- Key Responsibilities:
Coordinate transformation assignment code generation
Manage shape validation for transformation outputs
Provide abstract interface for Stan operation writing
Handle index options and assignment formatting
The class provides methods for generating Stan code assignments and manages the interaction between transformation inputs and outputs. Subclasses must implement the
write_stan_operation
method to define their specific mathematical operations.Shape handling can be disabled for transformations that perform reductions or other operations that fundamentally change dimensionality.
- SHAPE_CHECK: bool = True¶
- 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,
Generate right-hand side of transformation assignment.
- Parameters:
index_opts (Optional[tuple[str, ...]]) – Index options for multi-dimensional operations
start_dims (Optional[dict[str, custom_types.Integer]]) – First indexable dimension of parent parameters. Defaults to None.
end_dims (Optional[dict[str, custom_types.Integer]]) – Last indexable dimension of parent parameters. Defaults to None.
offset_adjustment (int) – Index offset adjustment. Defaults to 0.
- Returns:
Stan code for the right-hand side of the assignment
- Return type:
str
This method coordinates the formatting of parent parameters and applies the transformation operation. It automatically adds parentheses around operations when the transformation is not named.
- class scistanpy.model.components.transformations.transformed_parameters.TransformedParameter(
- *,
- shape: tuple['custom_types.Integer', ...] | 'custom_types.Integer' = (),
- **model_params: custom_types.CombinableParameterType,
Bases:
Transformation
,TransformableParameter
Base class for transformed parameters that can be used in parameter blocks.
This class provides the foundation for parameters that result from mathematical operations on other parameters. It handles both the computational aspects (sampling, PyTorch operations) and code generation aspects (Stan assignments).
- Transformed parameters support:
Sampling through parent parameter sampling and operation application
PyTorch operations with automatic differentiation
Stan code generation for transformed parameters block
Further transformation through operator overloading
The class provides the infrastructure for creating complex mathematical expressions while maintaining compatibility with all SciStanPy backends.
- Subclasses must implement:
run_np_torch_op: The core mathematical operation
write_stan_operation: Stan code generation for the operation
- Example Usage:
TransformedParameter subclasses are typically created through operator overloading or the operations submodule rather than direct instantiation, but can be used directly for custom operations.
- STAN_OPERATOR: str = ''¶
Stan operator string or function name for simple operations
This operator is used in the Stan code generation for the transformation. Subclasses should define this variable to specify the appropriate operator or function for their specific transformation.
- __call__(*args, **kwargs)[source]¶
Enable calling transformed parameters as functions.
- Parameters:
args – Positional arguments passed to run_np_torch_op
kwargs – Keyword arguments passed to run_np_torch_op
- Returns:
Result of the operation
This allows transformed parameters to be used as callable functions, providing a convenient interface for applying operations directly.
- get_transformation_assignment(
- index_opts: tuple[str, ...] | None,
- assignment_kwargs: dict | None = None,
- right_side_kwargs: dict | None = None,
Generate complete transformation assignment code.
- Parameters:
index_opts (Optional[tuple[str, ...]]) – Index variable names for multi-dimensional operations
assignment_kwargs (Optional[dict]) – Keyword arguments for assignment formatting. Defaults to None.
right_side_kwargs (Optional[dict]) – Keyword arguments for right-side formatting. Defaults to None.
- Returns:
Complete Stan assignment statement
- Return type:
str
This method combines the left-hand side variable name with the right-hand side operation to create a complete Stan assignment statement suitable for use in transformed parameters or transformed data blocks.
- abstractmethod run_np_torch_op(**draws: torch.Tensor) torch.Tensor [source]¶
- abstractmethod run_np_torch_op(
- **draws: custom_types.SampleType,
Execute the mathematical operation using NumPy or PyTorch.
- Parameters:
draws (Union[torch.Tensor, custom_types.SampleType]) – Input values for the operation
- Returns:
Result of the mathematical operation
- Return type:
Union[torch.Tensor, npt.NDArray]
This abstract method defines the core computational logic for the transformation. It must handle both NumPy and PyTorch inputs appropriately to maintain backend compatibility.
- property torch_parametrization: torch.Tensor¶
Get PyTorch representation with transformations applied.
- Returns:
PyTorch tensor with operation applied to parent tensors
- Return type:
torch.Tensor
This property applies the transformation operation to the PyTorch parameterizations of all parent parameters, maintaining gradient flow for optimization.
- abstractmethod write_stan_operation(**to_format: str) str [source]¶
Generate Stan code for the transformation operation.
- Parameters:
to_format (str) – Formatted parameter strings
- Returns:
Stan code for the operation
- Return type:
str
- Raises:
NotImplementedError – If
STAN_OPERATOR
is not defined for simple operations
This method must be implemented to provide appropriate Stan code for the mathematical operation represented by this transformation.
- class scistanpy.model.components.transformations.transformed_parameters.UnaryTransformedParameter(dist1: custom_types.CombinableParameterType, **kwargs)[source]¶
Bases:
TransformedParameter
Base class for transformations involving exactly one parameter.
This class provides a specialized interface for unary mathematical operations such as negation, absolute value, logarithms, and exponentials. It enforces the single-parameter constraint and provides appropriate method signatures.
- Parameters:
dist1 (custom_types.CombinableParameterType) – Parameter for the operation
kwargs – Additional arguments passed to parent class
Unary operations are essential for mathematical transformations and provide common functions needed in statistical modeling and parameter reparameterization.
Subclasses must implement
run_np_torch_op
with the single-parameter signature and can optionally overridewrite_stan_operation
for custom Stan formatting.- abstractmethod run_np_torch_op(dist1: torch.Tensor) torch.Tensor [source]¶
- abstractmethod run_np_torch_op(
- dist1: custom_types.SampleType,
Execute unary operation on single input.
- Parameters:
dist1 – Input operand
- Returns:
Result of unary operation
This method implements the core unary mathematical operation for both NumPy and PyTorch backends.
- write_stan_operation(dist1: str) str [source]¶
Generate Stan code for unary operations using STAN_OPERATOR.
- Parameters:
dist1 (str) – Formatted string for the parameter
- Returns:
Stan code with prefix operator
- Return type:
str
Generates Stan code in the format
"OPERATOR dist1"
for standard unary operations.
- class scistanpy.model.components.transformations.transformed_parameters.BinaryTransformedParameter(
- dist1: custom_types.CombinableParameterType,
- dist2: custom_types.CombinableParameterType,
- **kwargs,
Bases:
TransformedParameter
Base class for transformations involving exactly two parameters.
This class provides a specialized interface for binary mathematical operations such as addition, subtraction, multiplication, and division. It enforces the two-parameter constraint and provides appropriate method signatures.
- Parameters:
dist1 (custom_types.CombinableParameterType) – First parameter for the operation
dist2 (custom_types.CombinableParameterType) – Second parameter for the operation
kwargs – Additional arguments passed to parent class
Binary operations are the foundation for arithmetic expressions and provide the building blocks for more complex mathematical relationships between parameters.
Subclasses must implement
run_np_torch_op
with the (dist1, dist2
) signature and can optionally overridewrite_stan_operation
for custom Stan formatting.- abstractmethod run_np_torch_op(dist1: torch.Tensor, dist2: torch.Tensor) torch.Tensor [source]¶
- abstractmethod run_np_torch_op(
- dist1: custom_types.SampleType,
- dist2: custom_types.SampleType,
Execute binary operation on two inputs.
- Parameters:
dist1 – First operand
dist2 – Second operand
- Returns:
Result of binary operation
This method implements the core binary mathematical operation for both NumPy and PyTorch backends.
- write_stan_operation(dist1: str, dist2: str) str [source]¶
Generate Stan code for binary operations using STAN_OPERATOR.
- Parameters:
dist1 (str) – Formatted string for first parameter
dist2 (str) – Formatted string for second parameter
- Returns:
Stan code with infix operator
- Return type:
str
Generates Stan code in the format
"dist1 OPERATOR dist2"
for standard binary operations.
Basic Arithmetic Operations¶
- class scistanpy.model.components.transformations.transformed_parameters.AddParameter(
- dist1: custom_types.CombinableParameterType,
- dist2: custom_types.CombinableParameterType,
- **kwargs,
Bases:
BinaryTransformedParameter
Addition transformation for two parameters.
Implements element-wise addition of two parameters:
result = dist1 + dist2
- Example:
# Binary operations automatically handle broadcasting x = ssp.parameters.Normal(mu=0, sigma=1, shape=(5,)) y = ssp.parameters.Normal(mu=0, sigma=1, shape=(3, 1)) # Result has shape (3, 5) through broadcasting combined = x + y
- STAN_OPERATOR: str = '+'¶
Stan operator string or function name for simple operations
This operator is used in the Stan code generation for the transformation. Subclasses should define this variable to specify the appropriate operator or function for their specific transformation.
- class scistanpy.model.components.transformations.transformed_parameters.SubtractParameter(
- dist1: custom_types.CombinableParameterType,
- dist2: custom_types.CombinableParameterType,
- **kwargs,
Bases:
BinaryTransformedParameter
Subtraction transformation for two parameters.
Implements element-wise subtraction of two parameters:
result = dist1 - dist2
- Example:
# Binary operations automatically handle broadcasting x = ssp.parameters.Normal(mu=0, sigma=1, shape=(5,)) y = ssp.parameters.Normal(mu=0, sigma=1, shape=(3, 1)) # Result has shape (3, 5) through broadcasting difference = x - y
- STAN_OPERATOR: str = '-'¶
Stan operator string or function name for simple operations
This operator is used in the Stan code generation for the transformation. Subclasses should define this variable to specify the appropriate operator or function for their specific transformation.
- class scistanpy.model.components.transformations.transformed_parameters.MultiplyParameter(
- dist1: custom_types.CombinableParameterType,
- dist2: custom_types.CombinableParameterType,
- **kwargs,
Bases:
BinaryTransformedParameter
Element-wise multiplication transformation for two parameters.
Implements element-wise multiplication of two parameters:
result = dist1 * dist2
This transformation is fundamental for scaling, interaction effects, and product relationships between parameters.
- Example:
# Binary operations automatically handle broadcasting x = ssp.parameters.Normal(mu=0, sigma=1, shape=(5,)) y = ssp.parameters.Normal(mu=0, sigma=1, shape=(3, 1)) # Result has shape (3, 5) through broadcasting product = x * y
- STAN_OPERATOR: str = '.*'¶
Stan operator string or function name for simple operations
This operator is used in the Stan code generation for the transformation. Subclasses should define this variable to specify the appropriate operator or function for their specific transformation.
- class scistanpy.model.components.transformations.transformed_parameters.DivideParameter(
- dist1: custom_types.CombinableParameterType,
- dist2: custom_types.CombinableParameterType,
- **kwargs,
Bases:
BinaryTransformedParameter
Element-wise division transformation for two parameters.
Implements element-wise division of two parameters:
result = dist1 / dist2
This transformation is used for ratios, rates, normalized quantities, and relative measures. Care must be taken to avoid division by zero.
- Example:
# Binary operations automatically handle broadcasting x = ssp.parameters.Normal(mu=0, sigma=1, shape=(5,)) y = ssp.parameters.Normal(mu=1, sigma=0.5, shape=(3, 1)) # Result has shape (3, 5) through broadcasting ratio = x / y
- STAN_OPERATOR: str = './'¶
Stan operator string or function name for simple operations
This operator is used in the Stan code generation for the transformation. Subclasses should define this variable to specify the appropriate operator or function for their specific transformation.
- class scistanpy.model.components.transformations.transformed_parameters.PowerParameter(
- dist1: custom_types.CombinableParameterType,
- dist2: custom_types.CombinableParameterType,
- **kwargs,
Bases:
BinaryTransformedParameter
Element-wise exponentiation transformation for two parameters.
Implements element-wise exponentiation:
result = dist1 ^ dist2
This transformation is used for power relationships, polynomial terms, and exponential scaling effects.
- Example:
# Binary operations automatically handle broadcasting x = ssp.parameters.Normal(mu=2, sigma=1, shape=(5,)) y = ssp.parameters.Normal(mu=3, sigma=0.5, shape=(3, 1)) # Result has shape (3, 5) through broadcasting exponentiated = x ** y
- STAN_OPERATOR: str = '.^'¶
Stan operator string or function name for simple operations
This operator is used in the Stan code generation for the transformation. Subclasses should define this variable to specify the appropriate operator or function for their specific transformation.
- class scistanpy.model.components.transformations.transformed_parameters.NegateParameter(dist1: custom_types.CombinableParameterType, **kwargs)[source]¶
Bases:
UnaryTransformedParameter
Unary negation transformation for parameters.
Implements element-wise negation of a parameter:
result = -dist1
- Example:
x = ssp.parameters.Normal(mu=0, sigma=1, shape=(5,)) negated = -x
- STAN_OPERATOR: str = '-'¶
Stan operator string or function name for simple operations
This operator is used in the Stan code generation for the transformation. Subclasses should define this variable to specify the appropriate operator or function for their specific transformation.
Standard Mathematical Functions¶
- class scistanpy.model.components.transformations.transformed_parameters.AbsParameter(dist1: custom_types.CombinableParameterType, **kwargs)[source]¶
Bases:
UnaryTransformedParameter
Absolute value transformation for parameters.
Implements element-wise absolute value:
result = \|dist1\|
This transformation ensures non-negative values and is commonly used for magnitudes, distances, and ensuring positive parameters.
This transformation is accessed through the
abs_()
function.- Example:
x = ssp.parameters.Normal(mu=0, sigma=1, shape=(5,)) abs_x = ssp.operations.abs_(x) # Effectively half-normal distribution
- LOWER_BOUND: custom_types.Float = 0.0¶
Class variable giving the lower bound constraint for component values. None if unbounded.
- class scistanpy.model.components.transformations.transformed_parameters.ExpParameter(dist1: custom_types.CombinableParameterType, **kwargs)[source]¶
Bases:
UnaryTransformedParameter
Exponential transformation for parameters.
Implements element-wise exponential function:
result = exp(dist1)
This transformation is used for ensuring positive values, exponential growth models, and converting from log-scale to natural scale.
This transformation is accessed through the
exp()
function.- Example:
x = ssp.parameters.Normal(mu=0, sigma=1, shape=(5,)) exp_x = ssp.operations.exp(x) # Log-normally distributed
- LOWER_BOUND: custom_types.Float = 0.0¶
Class variable giving the lower bound constraint for component values. None if unbounded.
- class scistanpy.model.components.transformations.transformed_parameters.LogParameter(dist1: custom_types.CombinableParameterType, **kwargs)[source]¶
Bases:
UnaryTransformedParameter
Natural logarithm transformation for parameters.
Implements element-wise natural logarithm:
result = ln(dist1)
This transformation is fundamental for log-scale modeling, multiplicative effects on additive scales, and ensuring positive-valued parameters.
This transformation is accessed through the
log()
function.- Example:
x = ssp.parameters.LogNormal(mu=0, sigma=1, shape=(5,)) log_x = ssp.operations.log(x) # Normally distributed
- POSITIVE_PARAMS: set[str] = {'dist1'}¶
Class variable giving the set of parent parameter names that must be positive.
- class scistanpy.model.components.transformations.transformed_parameters.SigmoidParameter(dist1: custom_types.CombinableParameterType, **kwargs)[source]¶
Bases:
UnaryTransformedParameter
Sigmoid (logistic) transformation for parameters.
Implements the sigmoid function: \(result = \frac{1}{1 + \exp(-dist1)}\)
- The sigmoid function is essential for:
Converting unbounded values to probabilities
Logistic regression and classification
Smooth transitions between bounds
Activation functions in neural networks
This implementation uses numerically stable computation methods to avoid overflow/underflow issues.
This is accessed through the
sigmoid()
function.Warning
It is easy to define a model that is not identifiable when using the sigmoid transformation. Make sure that there are sufficient constraints on the input parameter to ensure a well-defined posterior distribution.
- Example:
>>> logits = Normal(mu=0, sigma=1) >>> probabilities = SigmoidParameter(logits)
- LOWER_BOUND: custom_types.Float = 0.0¶
Class variable giving the lower bound constraint for component values. None if unbounded.
- UPPER_BOUND: custom_types.Float = 1.0¶
Class variable giving the upper bound constraint for component values. None if unbounded.
- class scistanpy.model.components.transformations.transformed_parameters.LogSigmoidParameter(dist1: custom_types.CombinableParameterType, **kwargs)[source]¶
Bases:
UnaryTransformedParameter
Performs the sigmoid transformation followed by the natural logarithm in a numerically stable manner: \(\log(\text{sigmoid}(x)) = -\log(1 + \exp(-x))\).
This transformation is useful for converting unbounded values to log-probabilities in the range (-∞, 0). It is commonly used in logistic regression, binary classification, and scenarios where log-probabilities are required.
This transformation is accessed through the
logsigmoid()
function.- UPPER_BOUND: custom_types.Float = 0.0¶
Class variable giving the upper bound constraint for component values. None if unbounded.
- class scistanpy.model.components.transformations.transformed_parameters.Log1pExpParameter(dist1: custom_types.CombinableParameterType, **kwargs)[source]¶
Bases:
UnaryTransformedParameter
Calculates \(\log(1 + \exp(x))\) transformation in a numerically stable way.
This transformation is accessed through the
log1p_exp()
function.
Normalization Transformations¶
- class scistanpy.model.components.transformations.transformed_parameters.NormalizeParameter(dist1: custom_types.CombinableParameterType, **kwargs)[source]¶
Bases:
UnaryTransformedParameter
Normalization transformation that scales values to sum to 1 in the last dimension of the input.
Implements element-wise normalization where each vector is divided by its sum, creating probability vectors or normalized weights that sum to unity.
This transformation is essential for creating probability vectors from non-negative weights.
This transformation is accessed through the
normalize()
function.Important
The normalization is applied along the last dimension only. This cannot be changed to other dimensions in the current implementation.
- Example:
x = ssp.parameters.Exponential(rate=1.0, shape=(4, 5)) # Normalize along last dimension (size 5) normalized_x = ssp.operations.normalize(x) # Each of the 4 vectors of length 5 sums to 1
- LOWER_BOUND: custom_types.Float = 0.0¶
Class variable giving the lower bound constraint for component values. None if unbounded.
- UPPER_BOUND: custom_types.Float = 1.0¶
Class variable giving the upper bound constraint for component values. None if unbounded.
- class scistanpy.model.components.transformations.transformed_parameters.NormalizeLogParameter(dist1: custom_types.CombinableParameterType, **kwargs)[source]¶
Bases:
UnaryTransformedParameter
Log-space normalization transformation for log-probability vectors over the last dimension of the input.
Implements normalization in log-space where log-probabilities are adjusted so that their exponentiated values sum to 1. This is equivalent to subtracting the log-sum-exp from each element.
- This transformation is crucial for:
Normalizing log-probabilities without exponentiation
Stable computation with very small probabilities
Log-space categorical distributions
The log-sum-exp operation provides numerical stability by avoiding overflow/underflow issues common with direct exponentiation.
This transformation is accessed through the
normalize_log()
function.Important
As with
NormalizeParameter
, this is performed over the last dimension only.- Example:
x = ssp.parameters.Normal(mu=0, sigma=1, shape=(4, 5)) log_probs = ssp.operations.normalize_log(x) # Each of the exponentials of the 4 vectors of length 5 sums to 1 in # probability space
- UPPER_BOUND: custom_types.Float = 0.0¶
Class variable giving the upper bound constraint for component values. None if unbounded.
Reduction Operations¶
Reductions are built from an additional intermediate base class, Reduction
, which provides shared functionality for all reduction operations. It is documented below followed by the specific reduction transformations.
- class scistanpy.model.components.transformations.transformed_parameters.Reduction(dist1: custom_types.CombinableParameterType, keepdims: bool = False, **kwargs)[source]¶
Bases:
UnaryTransformedParameter
Base class for operations that reduce dimensionality.
This abstract base class provides infrastructure for transformations that reduce the size of the last dimension through operations like
sum
orlog-sum-exp
. It handles shape management and provides specialized indexing behavior for reductions.- Parameters:
dist1 (custom_types.CombinableParameterType) – Parameter to reduce
keepdims (bool) – Whether to keep the reduced dimension as size 1. Defaults to False.
kwargs – Additional arguments passed to parent class
Important
Currently, all reductions in SciStanPy are performed along the last dimension of the input parameter. This cannot be changed to other dimensions in the current implementation.
- NP_FUNC: Callable[[npt.NDArray], npt.NDArray]¶
The NumPy function to use for the reduction operation.
- SHAPE_CHECK: bool = False¶
- TORCH_FUNC: Callable[[npt.NDArray], npt.NDArray]¶
The PyTorch function to use for the reduction operation.
- get_assign_depth() int [source]¶
Reductions require one additional level of loop nesting to properly iterate over the dimension being reduced. Thus, the assignment depth is always one greater than the parent class.
- get_index_offset(
- query: str | AbstractModelComponent,
- offset_adjustment: int = 0,
Return zero offset for all reduction operations.
- Parameters:
query – Component or parameter name (ignored)
offset_adjustment – Offset adjustment (ignored)
- Returns:
Always returns 0
- Return type:
int
Reductions always return zero offset because they operate on the last dimension and don’t require complex indexing adjustments.
- class scistanpy.model.components.transformations.transformed_parameters.SumParameter(dist1: custom_types.CombinableParameterType, keepdims: bool = False, **kwargs)[source]¶
Bases:
Reduction
Sum reduction transformation.
Computes the sum of values along the last dimension. This is accessed through the
sum()
function.- Example:
rates = ssp.parameters.Exponential(rate=1.0, shape=(10, 5)) summed = ssp.operations.sum(rates, keepdims=False) # Shape (10,) summed2 = ssp.operations.sum(rates, keepdims=True) # Shape (10, 1)
- class scistanpy.model.components.transformations.transformed_parameters.LogSumExpParameter(dist1: custom_types.CombinableParameterType, keepdims: bool = False, **kwargs)[source]¶
Bases:
Reduction
Log-sum-exp reduction transformation.
Computes the logarithm of the sum of exponentials along the last dimension.
- This transformation is fundamental for:
Normalizing log-probabilities
Computing partition functions
Stable softmax computations
Log-space mixture models
This transformation is accessed through the
logsumexp()
function.Important
The log-sum-exp is performed over the last dimension only. This cannot be changed to other dimensions in the current implementation.
- Example:
weights = ssp.parameters.Exponential(rate=1.0, shape=(10, 5)) log_weights = ssp.operations.log(weights) # Log-space weights log_partition = ssp.operations.logsumexp(log_weights) # Shape (10,) log_partition2 = ssp.operations.logsumexp(log_weights, keepdims=True) # Shape (10, 1)
Growth Model Transformations¶
SciStanPy has been thoroughly applied to modeling biological growth processes, particularly in the context of deep mutational scanning experiments. The following transformations provide a suite of growth model operations that can be used to define complex growth dynamics in a probabilistic framework. Note that all of these transformations could also be implemented using the basic arithmetic and mathematical functions provided above, but these classes provide a more convenient interface and better integration with SciStanPy’s model component system. If there are other compound functions that would be useful to include in SciStanPy (whether growth-related or not), please consider raising an issue on the SciStanPy GitHub repository or contributing a custom transformation.
- class scistanpy.model.components.transformations.transformed_parameters.ExponentialGrowth(
- *,
- t: custom_types.CombinableParameterType,
- A: custom_types.CombinableParameterType,
- r: custom_types.CombinableParameterType,
- **kwargs,
Bases:
ExpParameter
A transformed parameter that models exponential growth. Specifically, parameters
t
,A
, andr
are used to calculate the exponential growth model as follows:\[x = A \text{e}^{rt}\]This transformation is accessed through the
exponential_growth()
function.- Example:
>>> time = np.array([[0], [1], [2], [3], [4]]) # Shape (5, 1) >>> baseline = Dirichlet(alpha = 1.0, shape = (10,)) >>> rate = Exponential(beta = 1.0) >>> growth = ssp.operations.exponential_growth(t=time, A=baseline, r=rate)
- class scistanpy.model.components.transformations.transformed_parameters.LogExponentialGrowth(
- *,
- t: custom_types.CombinableParameterType,
- log_A: custom_types.CombinableParameterType,
- r: custom_types.CombinableParameterType,
- **kwargs,
Bases:
TransformedParameter
Log-scale exponential growth model transformation.
Implements the logarithm of exponential growth:
\[\log(x) = logA + r * t\]- Parameters:
t (custom_types.CombinableParameterType) – Time parameter
log_A (custom_types.CombinableParameterType) – Log-amplitude parameter (log of initial value)
r (custom_types.CombinableParameterType) – Growth rate parameter
kwargs – Additional arguments passed to parent class
- This transformation is particularly useful for:
Population modeling where values must be positive
Multiplicative growth processes
Log-scale regression models
Ensuring positive-valued outcomes
The log-scale parameterization avoids issues with negative values and provides numerical stability for extreme growth rates.
This transformation is accessed through the
log_exponential_growth()
function.
- class scistanpy.model.components.transformations.transformed_parameters.BinaryExponentialGrowth(
- A: custom_types.CombinableParameterType,
- r: custom_types.CombinableParameterType,
- **kwargs,
Bases:
ExpParameter
Binary exponential growth for two time points, which is a special case of exponential growth for modeling with only two time points assuming \(t_0 = 0\) and \(t_1 = 1\). This reduces to
\[x = A\text{e}^r\]This transformation is accessed through the
binary_exponential_growth()
function.
- class scistanpy.model.components.transformations.transformed_parameters.BinaryLogExponentialGrowth(
- log_A: custom_types.CombinableParameterType,
- r: custom_types.CombinableParameterType,
- **kwargs,
Bases:
TransformedParameter
Binary log-exponential growth for two time points.
This is identical to
BinaryExponentialGrowth
, but operates in log-space. Mathematically,\[\log(x) = logA + r\]- Parameters:
log_A (custom_types.CombinableParameterType) – Log-amplitude parameter (log of initial value)
r (custom_types.CombinableParameterType) – Growth rate parameter
kwargs – Additional arguments passed to parent class
- This transformation is useful for:
Modeling growth between two time points
Ensuring positive-valued outcomes
Log-scale regression models
Multiplicative growth processes
The log-scale parameterization avoids issues with negative values and provides numerical stability for extreme growth rates.
This transformation is accessed through the
binary_log_exponential_growth()
function.
- class scistanpy.model.components.transformations.transformed_parameters.SigmoidGrowth(
- *,
- t: custom_types.CombinableParameterType,
- A: custom_types.CombinableParameterType,
- r: custom_types.CombinableParameterType,
- c: custom_types.CombinableParameterType,
- **kwargs,
Bases:
SigmoidParameter
Sigmoid growth model transformation.
Implements sigmoid growth:
\[x = \frac{A}{1 + \exp(-r(t - c))}\]- Parameters:
t (custom_types.CombinableParameterType) – Time parameter
A (custom_types.CombinableParameterType) – Amplitude parameter (carrying capacity)
r (custom_types.CombinableParameterType) – Growth rate parameter
c (custom_types.CombinableParameterType) – Inflection point parameter (time of fastest growth)
kwargs – Additional arguments passed to parent class
- This transformation is essential for:
Population growth with carrying capacity
Any growth process with saturation
This transformation is accessed through the
sigmoid_growth()
function.- LOWER_BOUND: custom_types.Float = 0.0¶
Class variable giving the lower bound constraint for component values. None if unbounded.
- UPPER_BOUND: None = None¶
Class variable giving the upper bound constraint for component values. None if unbounded.
- class scistanpy.model.components.transformations.transformed_parameters.LogSigmoidGrowth(
- *,
- t: custom_types.CombinableParameterType,
- log_A: custom_types.CombinableParameterType,
- r: custom_types.CombinableParameterType,
- c: custom_types.CombinableParameterType,
- **kwargs,
Bases:
LogSigmoidParameter
Log-scale sigmoid growth model transformation.
- Implements the logarithm of sigmoid growth:
- \[\log(x) = logA - \log(1 + \exp(-r(t - c)))\]
Under the hood, this uses the numerically stable log-sigmoid to calculate the
1 + exp(-...)
term.- Parameters:
t (custom_types.CombinableParameterType) – Time parameter
log_A (custom_types.CombinableParameterType) – Log-amplitude parameter (log of carrying capacity)
r (custom_types.CombinableParameterType) – Growth rate parameter
c (custom_types.CombinableParameterType) – Inflection point parameter
kwargs – Additional arguments passed to parent class
- This parameterization is ideal for:
Extreme parameter regimes
Log-scale statistical modeling
When initial conditions are naturally in log-space
Maximum numerical precision requirements
This transformation is accessed through the
log_sigmoid_growth()
function.- LOWER_BOUND: None = None¶
Class variable giving the lower bound constraint for component values. None if unbounded.
- UPPER_BOUND: None = None¶
Class variable giving the upper bound constraint for component values. None if unbounded.
- class scistanpy.model.components.transformations.transformed_parameters.SigmoidGrowthInitParametrization(
- *,
- t: custom_types.CombinableParameterType,
- x0: custom_types.CombinableParameterType,
- r: custom_types.CombinableParameterType,
- c: custom_types.CombinableParameterType,
- **kwargs,
Bases:
TransformedParameter
Sigmoid growth with initial value parameterization.
Alternative parameterization of sigmoid growth in terms of initial abundances rather than carrying capacity.
- Parameters:
t (custom_types.CombinableParameterType) – Time parameter
x0 (custom_types.CombinableParameterType) – Initial abundance parameter
r (custom_types.CombinableParameterType) – Growth rate parameter
c (custom_types.CombinableParameterType) – Offset parameter (related to carrying capacity)
kwargs – Additional arguments passed to parent class
- Mathematical Properties:
Parameterizes sigmoid growth by initial value x0
Uses log-add-exp trick for numerical stability
Avoids direct computation of large exponentials
Maintains sigmoid growth dynamics
- This parameterization is useful when:
Initial conditions are better known than carrying capacity (e.g., biological systems)
Numerical stability is crucial
Working with extreme parameter values
Modeling relative growth from baseline
This transformation is accessed through the
sigmoid_growth_init_param()
function.- LOWER_BOUND: custom_types.Float = 0.0¶
Class variable giving the lower bound constraint for component values. None if unbounded.
- UPPER_BOUND: None = None¶
Class variable giving the upper bound constraint for component values. None if unbounded.
- class scistanpy.model.components.transformations.transformed_parameters.LogSigmoidGrowthInitParametrization(
- *,
- t: custom_types.CombinableParameterType,
- log_x0: custom_types.CombinableParameterType,
- r: custom_types.CombinableParameterType,
- c: custom_types.CombinableParameterType,
- **kwargs,
Bases:
TransformedParameter
Log-scale sigmoid growth with initial value parameterization.
Log-space version of sigmoid growth parameterized by initial values, providing numerical stability and guaranteed positive outputs.
- Parameters:
t (custom_types.CombinableParameterType) – Time parameter
log_x0 (custom_types.CombinableParameterType) – Log of initial abundance parameter
r (custom_types.CombinableParameterType) – Growth rate parameter
c (custom_types.CombinableParameterType) – Offset parameter
kwargs – Additional arguments passed to parent class
- Mathematical Properties:
Fully operates in log-space for numerical stability
Parameterized by log of initial conditions
Maintains sigmoid growth dynamics
- This parameterization is ideal for:
Extreme parameter regimes
Log-scale statistical modeling
When initial conditions are naturally in log-space
Maximum numerical precision requirements
- LOWER_BOUND: None = None¶
Class variable giving the lower bound constraint for component values. None if unbounded.
- UPPER_BOUND: None = None¶
Class variable giving the upper bound constraint for component values. None if unbounded.
Special Functions¶
- class scistanpy.model.components.transformations.transformed_parameters.ConvolveSequence(
- *,
- weights: custom_types.CombinableParameterType,
- ordinals: custom_types.CombinableParameterType,
- **kwargs,
Bases:
TransformedParameter
Sequence convolution transformation using weight matrices.
Performs convolution operation on ordinally-encoded sequences using provided weight matrices. This is commonly used for sequence modeling and pattern recognition in biological sequences or text data.
- Parameters:
weights (custom_types.CombinableParameterType) – Weight matrix for convolution (at least 2D)
ordinals (custom_types.CombinableParameterType) – Ordinally-encoded sequence array (at least 1D)
kwargs – Additional arguments passed to parent class
- Raises:
ValueError – If weights is not at least 2D
ValueError – If ordinals is not at least 1D
ValueError – If shapes are incompatible for broadcasting
- Shape Requirements:
Weights: (…, kernel_size, alphabet_size)
Ordinals: (…, sequence_length)
Output: (…, sequence_length - kernel_size + 1)
- The transformation applies convolution by:
Sliding a kernel of size kernel_size over the sequence
Using ordinal values to index into the weight matrix
Summing weighted values for each position
- This is commonly used for:
DNA/RNA sequence analysis
Protein sequence modeling
Text processing with character-level models
Pattern recognition in discrete sequences
This transformation is accessed through the
convolve_sequence()
function.- Example:
>>> # DNA sequence convolution >>> weights = Normal(mu=0, sigma=1, shape=(motif_length, 4)) # 4 nucleotides >>> dna_sequence = Constant(encoded_dna) # 0,1,2,3 for A,C,G,T >>> motif_scores = ConvolveSequence(weights=weights, ordinals=dna_sequence)
- FORCE_LOOP_RESET: bool = True¶
Class variable noting whether to force loop reset in Stan code. This is useful where this parameter’s shape makes it appear nestable with another inside the same loop, but it actually is not.
- FORCE_PARENT_NAME: bool = True¶
Class variable noting whether to force naming of parent variables in Stan code. If
True
and not provided by the user, parent parameters will be assigned names automatically in the Stan code.
- SHAPE_CHECK: bool = False¶
Indexing and Array Operations¶
- class scistanpy.model.components.transformations.transformed_parameters.IndexParameter(dist: custom_types.CombinableParameterType, *indices: custom_types.IndexType)[source]¶
Bases:
TransformedParameter
Array indexing transformation with NumPy-compatible semantics.
Creates indexed subsets of parameters using slicing, scalar indexing, and array indexing. Follows NumPy indexing conventions rather than Stan conventions for consistency with Python data manipulation.
- Parameters:
dist (custom_types.CombinableParameterType) – Parameter to index
indices (custom_types.IndexType) – Indexing specifications (slices, integers, arrays)
- Supported Index Types:
slice: Standard Python slicing with start:stop (step=1 only)
int: Single element selection
np.ndarray: Advanced indexing with integer arrays. 1D only. Follows numpy convention.
Ellipsis: Automatic dimension filling
None: New axis insertion
- Important Differences from Stan:
Uses 0-based indexing (Python convention)
Advanced indexing follows NumPy broadcasting rules, not Stan rules
Negative indices are supported and converted appropriately
This transformation is never applied directly. Instead index a parameter as in normal Python/NumPy:
- Example:
# Define any parameter param = Normal(mu=0, sigma=1, shape=(10, 5)) # Standard indexing (last element of first dimension) last_elem = param[-1] # Slice first 5 rows subset = param[:5] # Select specific elements with NumPy-style advanced indexing selected = param[np.array([0, 2, 4])] # Use Ellipsis to fill in dimensions first_col = param[..., 0] # All leading dimensions, first of last # Insert new axis new_axis = param[:, None, :]
- FORCE_PARENT_NAME: bool = True¶
Class variable noting whether to force naming of parent variables in Stan code. If
True
and not provided by the user, parent parameters will be assigned names automatically in the Stan code.
- SHAPE_CHECK: bool = False¶
- property force_name: bool¶
Force explicit naming for indexed parameters.
- Returns:
Always True
- Return type:
bool
Indexed parameters must be explicitly named in Stan code to enable proper variable reference and assignment.
- neg_to_pos(
- neg_ind: custom_types.Integer,
- dim: custom_types.Integer,
- neg_to_pos(
- neg_ind: ndarray[tuple[int, ...], dtype[int64]],
- dim: custom_types.Integer,
Convert negative indices to positive indices.
- Parameters:
neg_ind – Negative index or array of indices
dim – Dimension size for conversion
- Returns:
Positive indices
- Raises:
ValueError – If indices are out of bounds
Handles both scalar and array indices, performing bounds checking and conversion from Python’s negative indexing convention.