pyhs3.base.Evaluable

class pyhs3.base.Evaluable(**data)[source]

Base class for HS3 distributions and functions with automatic parameter preprocessing.

This class provides automatic parameter processing that eliminates the need for manual @model_validator methods in subclasses. It automatically converts field values into parameter names and generates constants for numeric values.

The class automatically processes all field annotations during initialization:

  • String fields (str) → Direct parameter mapping

  • Numeric fields (float, int) → Generate unique constant names

  • Union fields (str | float, int | str, etc.) → Runtime type detection

  • List fields (list[str], list[str | float]) → Indexed parameter mapping

  • Boolean fields (bool) → Automatically excluded from processing

  • Excluded fields → Fields marked with json_schema_extra={"preprocess": False}

Examples

Basic usage with string and numeric parameters:

from typing import Literal

class MyDistribution(Evaluable):
    type: Literal["gaussian"] = "gaussian"
    mean: str | float  # Can be parameter name or numeric value
    sigma: str | float

# With parameter references
dist1 = MyDistribution(name="gauss1", mean="mu_param", sigma="sigma_param")
print(dist1.parameters)  # {'mu_param', 'sigma_param'}
print(dist1.constants)   # {}

# With numeric values - constants are generated automatically
dist2 = MyDistribution(name="gauss2", mean=1.5, sigma=0.5)
print(dist2.parameters)  # {'constant_gauss2_mean', 'constant_gauss2_sigma'}
print(list(dist2.constants.keys()))  # ['constant_gauss2_mean', 'constant_gauss2_sigma']

List parameter processing:

class ProductFunction(Evaluable):
    type: Literal["product"] = "product"
    factors: list[str | float]  # Mixed list of names and values

func = ProductFunction(name="prod", factors=["param1", 2.0, "param2", 1.5])
print(sorted(func.parameters))
# ['constant_prod_factors[1]', 'constant_prod_factors[3]', 'param1', 'param2']

# Reconstruct parameter list in context
context = {
    "param1": "tensor1",
    "constant_prod_factors[1]": "tensor2",
    "param2": "tensor3",
    "constant_prod_factors[3]": "tensor4"
}
func.get_parameter_list(context, "factors")  # ['tensor1', 'tensor2', 'tensor3', 'tensor4']

Excluding fields from preprocessing:

from pydantic import Field

class ConfigurableDistribution(Evaluable):
    type: Literal["configurable"] = "configurable"
    param: str | float                    # Will be processed
    enabled: bool                         # Automatically excluded
    config_val: float = Field(           # Explicitly excluded
        default=1.0,
        json_schema_extra={"preprocess": False}
    )

dist = ConfigurableDistribution(name="test", param="alpha", enabled=True, config_val=2.0)
print(dist.parameters)  # {'alpha'} - Only param is processed

Note

If you need custom parameter processing, set _parameters manually before the auto-processing runs, or provide a custom @model_validator.

Unsupported field types raise RuntimeError with helpful guidance about using json_schema_extra={"preprocess": False} for non-parameter fields.

Variables:
  • name (str) – Name of the component.

  • type (str) – Type identifier for the component.

  • parameters (set[str]) – Set of parameter names this component depends on.

  • constants (dict[str, TensorVar]) – Generated PyTensor constants for numeric values.

Parameters:

data (Any)

Fields

Field

Type

Required

Default

name

str

Yes

type

str

Yes

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Parameters:

data (Any)

Methods

expression(context)

Evaluate and return a named PyTensor expression.

get_parameter_list(context, param_key)

Reconstruct a parameter list from flattened indexed keys.

model_post_init(context, /)

This function is meant to behave like a BaseModel method to initialise private attributes.

process_parameter(param_key)

Process a single parameter that can be either a string reference or numeric value.

process_parameter_list(param_key)

Process a list parameter containing mixed string references and numeric values.

Attributes

constants

Dictionary of PyTensor constants generated from numeric field values.

parameters

Set of parameter names this component depends on.

name

type

Evaluable.expression(context)[source]

Evaluate and return a named PyTensor expression.

This is a template method that calls _expression() to get the result, then names the result before returning.

_expression() may return a tensor it does not own — for example a single-summand SumFunction or a single-factor ProductFunction returns context[param] directly, which is the same tensor object stored in model.parameters. Renaming such a shared tensor in place would silently corrupt the parameter it borrows (e.g. model.parameters['mu'] would be renamed to the function’s name). To avoid this, a result that already carries a different name is wrapped in a fresh identity copy before being renamed; freshly built (unnamed) expressions are named in place as before so that compilation and graph_summary keep working.

Parameters:

context (Context) – Mapping of names to PyTensor variables

Return type:

TensorVar

Returns:

Named PyTensor expression representing the component

Evaluable.get_parameter_list(context, param_key)[source]

Reconstruct a parameter list from flattened indexed keys.

Used to recover the original list structure from the indexed parameter mapping created by process_parameter_list().

Parameters:
  • context (Context) – The context containing parameter values mapped by name.

  • param_key (str) – The base parameter key (e.g., “factors”).

Return type:

list[TensorVar]

Returns:

List of parameter values in original order.

Example

>>> from typing import Literal
>>> class TestEvaluable(Evaluable):
...     type: Literal["test"] = "test"
...     factors: list[str | float]
...     def _expression(self, _: Context) -> TensorVar:
...         return None
>>>
>>> eval1 = TestEvaluable(name="test", factors=["a", 1.0, "b"])
>>> context = {
...     "a": "tensor_a",
...     "constant_test_factors[1]": "tensor_1",
...     "b": "tensor_b"
... }
>>> eval1.get_parameter_list(context, "factors")
['tensor_a', 'tensor_1', 'tensor_b']
Evaluable.model_post_init(context, /)

This function is meant to behave like a BaseModel method to initialise private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self (BaseModel) – The BaseModel instance.

  • context (Any) – The context.

Return type:

None

Evaluable.process_parameter(param_key)[source]

Process a single parameter that can be either a string reference or numeric value.

For numeric values, generates a unique constant name. For string values, returns the value as-is.

Parameters:

param_key (str) – The parameter field name to process (e.g., “mean”, “sigma”).

Return type:

tuple[str, float | int | None]

Returns:

(processed_name, numeric_value). processed_name is either the original string value or a generated constant name; numeric_value is the numeric value if the input was numeric, None otherwise.

Example

>>> from typing import Literal
>>> class TestEvaluable(Evaluable):
...     type: Literal["test"] = "test"
...     some_param: str | float
...     def _expression(self, _: Context) -> TensorVar:
...         return None
>>>
>>> # String parameter
>>> eval1 = TestEvaluable(name="test1", some_param="alpha")
>>> eval1.process_parameter("some_param")
('alpha', None)
>>> # Numeric parameter
>>> eval2 = TestEvaluable(name="test2", some_param=1.5)
>>> eval2.process_parameter("some_param")
('constant_test2_some_param', 1.5)
Evaluable.process_parameter_list(param_key)[source]

Process a list parameter containing mixed string references and numeric values.

For numeric values, generates indexed unique names and stores the values. For string values, returns the values as-is. Also updates internal parameter mapping with indexed keys.

Parameters:

param_key (str) – The parameter field name to process (e.g., “factors”, “coefficients”).

Return type:

tuple[list[str], list[float | int | None]]

Returns:

(processed_names, numeric_values). processed_names lists the parameter names (original strings or generated constant names); numeric_values lists the numeric values (None for string entries).

Example

>>> from typing import Literal
>>> class TestEvaluable(Evaluable):
...     type: Literal["test"] = "test"
...     factors: list[str | float]
...     def _expression(self, _: Context) -> TensorVar:
...         return None
>>>
>>> eval1 = TestEvaluable(name="test", factors=["param1", 2.0, "param2"])
>>> names, values = eval1.process_parameter_list("factors")
>>> names
['param1', 'constant_test_factors[1]', 'param2']
>>> values
[None, 2.0, None]
Evaluable.constants

Dictionary of PyTensor constants generated from numeric field values.

Returns:

Mapping from generated constant names to PyTensor constant tensors. Empty if all fields are string references.

Evaluable.parameters

Set of parameter names this component depends on.

Returns:

Set of parameter names, including both string references and generated constant names for numeric values.

Evaluable.name
Evaluable.type