Defining Custom Functions and Distributions

This guide shows how to create custom Functions and Distributions for use with pyhs3. These custom components should follow the HS3 specification for distributions and functions. Both Functions and Distributions inherit from the Evaluable base class, which provides automatic parameter preprocessing to eliminate boilerplate validation code.

Quick Start

Creating a custom distribution or function requires:

  1. Inherit from Distribution or Function

  2. Define fields with appropriate type annotations

  3. Implement the likelihood() method (distributions) or expression() method (functions)

  4. Register your component (optional)

The Evaluable base class automatically handles parameter processing based on your field type annotations.

Basic Distribution Example

Here’s a simple custom Gaussian distribution:

from typing import Literal
import pytensor.tensor as pt
from pyhs3.distributions.core import Distribution
from pyhs3.context import Context
from pyhs3.typing.aliases import TensorVar


class CustomGaussianDist(Distribution):
    """Custom Gaussian distribution implementation."""

    type: Literal["custom_gaussian"] = "custom_gaussian"
    mean: str | float  # Parameter name or numeric value
    sigma: str | float  # Parameter name or numeric value

    def likelihood(self, context: Context) -> TensorVar:
        """Evaluate the Gaussian PDF (main probability model)."""
        # Get processed parameters from context
        mean_val = context[self._parameters["mean"]]
        sigma_val = context[self._parameters["sigma"]]

        # Assume 'x' is the observable variable
        x = context["x"]  # Would come from domain/data definition

        # Gaussian PDF formula
        norm = 1.0 / (sigma_val * pt.sqrt(2 * pt.pi))
        exp_term = pt.exp(-0.5 * ((x - mean_val) / sigma_val) ** 2)
        return norm * exp_term

What happens automatically:

  • If mean="mu_param", then self._parameters["mean"] == "mu_param"

  • If mean=1.5, then self._parameters["mean"] == "constant_myname_mean" and a constant is created

  • The parameters property returns all parameter names this distribution depends on

  • The constants property provides PyTensor constants for numeric values

Basic Function Example

Here’s a custom product function:

from typing import Literal
import pytensor.tensor as pt
from pyhs3.functions.core import Function
from pyhs3.context import Context
from pyhs3.typing.aliases import TensorVar


class WeightedProductFunction(Function):
    """Product function with weights."""

    type: Literal["weighted_product"] = "weighted_product"
    factors: list[str | float]  # Mix of parameter names and values
    weights: list[str | float]  # Corresponding weights

    def expression(self, context: Context) -> TensorVar:
        """Evaluate weighted product: prod(factor[i] ** weight[i])."""
        # Get parameter lists in original order
        factor_vals = self.get_parameter_list(context, "factors")
        weight_vals = self.get_parameter_list(context, "weights")

        result = pt.constant(1.0)
        for factor, weight in zip(factor_vals, weight_vals, strict=True):
            result = result * (factor**weight)
        return result

What happens automatically:

  • factors=["param1", 2.0, "param2"] creates indexed parameters: factors[0], factors[1], factors[2]

  • get_parameter_list(context, "factors") reconstructs the original list from context

  • Constants are generated for numeric values: constant_myname_factors[1] for 2.0

Automatic Parameter Processing

The Evaluable base class automatically processes field annotations:

Supported Field Types:

class MyComponent(Evaluable):
    # String fields -> direct parameter mapping
    param_name: str  # -> self._parameters["param_name"] = field_value

    # Numeric fields -> generate constants
    numeric_val: (
        float  # -> self._parameters["numeric_val"] = "constant_name_numeric_val"
    )

    # Union types -> runtime detection
    mixed_param: str | float  # -> string or constant depending on value
    flexible: str | int | float  # -> handles any combination

    # Lists -> indexed processing
    string_list: list[str]  # -> param_name[0], param_name[1], ...
    mixed_list: list[str | float]  # -> mix of strings and generated constants

    # Excluded fields
    config_flag: bool  # -> automatically excluded
    internal_val: float = Field(  # -> explicitly excluded
        default=1.0, json_schema_extra={"preprocess": False}
    )

Exclusion Rules:

  • Boolean fields are automatically excluded (not parameters)

  • Fields marked with json_schema_extra={"preprocess": False} are excluded

  • Base class fields (name, type) are excluded

  • None values are skipped

Advanced Examples

Complex Distribution with Mixed Parameters:

from pydantic import Field


class FlexibleDist(Distribution):
    type: Literal["flexible"] = "flexible"

    # Core parameters (will be processed)
    location: str | float
    scale: str | float
    coefficients: list[str | float]

    # Configuration (excluded from processing)
    use_log_scale: bool = False
    tolerance: float = Field(default=1e-6, json_schema_extra={"preprocess": False})

    def likelihood(self, context: Context) -> TensorVar:
        loc = context[self._parameters["location"]]
        scale = context[self._parameters["scale"]]

        # Get coefficient list
        coeffs = self.get_parameter_list(context, "coefficients")

        # Use configuration values directly
        if self.use_log_scale:
            scale = pt.exp(scale)

        # ... implementation
        return result

Function with Validation:

from pydantic import model_validator


class ValidatedFunction(Function):
    type: Literal["validated"] = "validated"
    inputs: list[str]
    weights: list[float] = Field(json_schema_extra={"preprocess": False})

    @model_validator(mode="after")
    def validate_lengths(self) -> "ValidatedFunction":
        """Custom validation after auto-processing."""
        if len(self.inputs) != len(self.weights):
            raise ValueError("inputs and weights must have same length")
        return self

    def expression(self, context: Context) -> TensorVar:
        # inputs were auto-processed into indexed parameters
        input_vals = self.get_parameter_list(context, "inputs")

        result = pt.constant(0.0)
        for inp, weight in zip(input_vals, self.weights, strict=True):
            result = result + inp * weight
        return result

Registration and Discovery

Option 1: Manual Registration

Add your components to the appropriate registry, keyed by the value of the class’s type field: pyhs3.functions.registered_functions for functions, pyhs3.distributions.registered_distributions for distributions. A workspace that names that type then loads your class:

>>> from typing import Literal
>>> import pyhs3
>>> from pyhs3.functions import Function, registered_functions
>>> class DoubledFunction(Function):
...     type: Literal["doubled"] = "doubled"
...     x: str
...     def _expression(self, context):
...         return 2.0 * context[self.x]
...
>>> registered_functions["doubled"] = DoubledFunction
>>> ws = pyhs3.Workspace(
...     metadata={"hs3_version": "0.2"},
...     functions=[{"name": "twice_mu", "type": "doubled", "x": "mu"}],
... )
>>> type(ws.functions["twice_mu"]).__name__
'DoubledFunction'

A workspace looks each entry’s type up in these registries when it validates, so register your classes before you load a workspace that uses them. An unregistered type fails validation with a message that lists the registered types. Instances you construct in Python skip the lookup, so Distributions([CustomGaussianDist(...)]) works without registering.

Option 2: Plugin System (if available)

Check if pyhs3 supports a plugin entry point system for automatic discovery.

Usage in Workspaces

Once defined, your custom components work like built-in ones:

# In JSON/YAML workspace definition
{
    "distributions": [
        {
            "name": "signal_pdf",
            "type": "custom_gaussian",
            "mean": "mu_signal",  # Parameter reference
            "sigma": 0.1,  # Numeric constant
        }
    ],
    "functions": [
        {
            "name": "weighted_norm",
            "type": "weighted_product",
            "factors": ["norm1", "norm2", 1.5],  # Mixed types
            "weights": [2.0, 1.0, 0.5],  # Config values
        }
    ],
}

# In Python
workspace = Workspace.load("my_workspace.json")
model = workspace.model(0)

# Your components are automatically instantiated and available

Error Handling and Debugging

Common Issues:

  1. Unsupported field type:

    class BadDist(Distribution):
        type: Literal["bad"] = "bad"
        complex_field: dict  # Not supported!
    

    Fix: Add json_schema_extra={"preprocess": False} or use supported types.

  2. Missing implementation:

    dist = MyDist(name="test", param="value")
    # TypeError: Can't instantiate abstract class MyDist without an implementation for abstract method 'likelihood'
    

    Fix: Implement the likelihood() method for distributions or expression() method for functions.

  3. Context key errors:

    def expression(self, context):
        return context["missing_param"]  # KeyError!
    

    Fix: Use self._parameters or self.get_parameter_list() to get correct keys.

Debugging Tips:

# Inspect what was auto-processed
dist = MyDist(name="test", param1="alpha", param2=1.5)
print("Parameters:", dist.parameters)  # All parameter names
# Parameters: ...
print("Internal mapping:", dist._parameters)  # Field -> parameter mapping
# Internal mapping: ...
print("Constants:", list(dist.constants.keys()))  # Generated constant names
# Constants: ...
print("Constant values:", dist._constants_values)  # Stored numeric values
# Constant values: ...

Distribution Architecture: likelihood() vs extended_likelihood()

Distributions in pyhs3 separate the main probability model from extended likelihood terms through a clear three-method architecture:

Three Methods:

  1. likelihood(context): Main probability model (abstract - must implement)

    def likelihood(self, context: Context) -> TensorVar:
        """Main probability density function."""
        # Implement your PDF here
        # Example: Gaussian PDF, Poisson PMF, etc.
    
  2. extended_likelihood(context, data): Additional constraint/extended terms (optional - override when needed)

    def extended_likelihood(
        self, context: Context, data: TensorVar | None = None
    ) -> TensorVar:
        """Extended likelihood contribution in normal space.
    
        Default: returns 1.0 (no additional terms).
        Override for: constraint terms (HistFactory), extended ML terms (MixtureDist).
        """
        return pt.constant(1.0)  # Default behavior
    
  3. expression(context): Complete probability (concrete - do not override)

    def expression(self, context: Context) -> TensorVar:
        """Complete probability = likelihood() * extended_likelihood()."""
        return self.likelihood(context) * self.extended_likelihood(context)
    

When to Override extended_likelihood():

Override extended_likelihood() only when your distribution needs additional terms beyond the main PDF that are computable from the context alone:

  • HistFactory distributions: Constraint terms for nuisance parameters (Gaussian/Poisson constraints)

  • Most distributions: Do not override (use default 1.0)

Dataset-level terms cannot use this hook, for two reasons. First, expression() multiplies extended_likelihood() into the per-event density, so a term meant to enter the likelihood once per channel — like the extended Poisson yield term, which involves the observed event count — would be counted once per event when Model.log_prob sums over the data. Second, while the observable tensors are present in the Context, a MixtureDist cannot identify them: its declared dependencies are its coefficients and summand distributions, not the random variable. Such terms are instead declared via log_prob_terms() (below) and assembled by Model.log_prob, which owns the channel-dataset pairing.

Structured log-likelihood contributions: log_prob_terms()

Not every term a distribution contributes to the joint log-likelihood is a per-event log-density. Distribution.log_prob_terms(expressions, distributions) lets a distribution describe its contributions structurally, returning a LogProbTerms with three kinds of terms:

  • per_event: log-density terms summed over events (with per-event weights applied when present)

  • channel: scalar terms added once per channel (e.g. the -nu yield term of an extended MixtureDist)

  • constraints: log-terms keyed by factor name, added exactly once globally so constraints shared across channels are not double-counted

The default implementation returns a single per-event log(PDF) term, which is correct for most distributions. ProductDist overrides it to split its factors into observable-dependent shape factors (delegating to each factor’s own log_prob_terms, so composition nests) and scalar-only constraint factors. MixtureDist overrides it to contribute the extended yield term. Model.log_prob calls this hook for each channel and owns the assembly — event weighting, summing, and global constraint deduplication — so new distribution types with channel-level terms only need to override log_prob_terms(), never Model.log_prob itself.

Example with Extended Likelihood:

class HistFactoryDistChannel(Distribution):
    type: Literal["histfactory_dist"] = "histfactory_dist"
    # ... fields ...

    def likelihood(self, context: Context) -> TensorVar:
        """Main Poisson likelihood for observed bin counts."""
        # Poisson probability for data
        return poisson_prob(observed_data, expected_rates)

    def extended_likelihood(
        self, context: Context, data: TensorVar | None = None
    ) -> TensorVar:
        """Constraint terms for nuisance parameters."""
        constraint_probs = []
        for modifier in self.modifiers:
            if hasattr(modifier, "make_constraint"):
                constraint_probs.append(modifier.make_constraint(context))
        return (
            pt.prod(pt.stack(constraint_probs))
            if constraint_probs
            else pt.constant(1.0)
        )

Key Points:

  • Distributions automatically combine likelihood() * extended_likelihood() via expression()

  • Tests and direct usage get the complete probability automatically

  • Extended likelihood terms are in normal space (not log space)

  • log_expression() handles the conversion: log(likelihood()) + log(extended_likelihood())

  • Most distributions only need to implement likelihood()

Distribution Normalization

All continuous distributions in pyhs3 are automatically normalized over the domain of their observables. This ensures that probability density functions (PDFs) integrate to 1.0 over the specified observable range.

When normalization applies:

  • With observables: When a model specifies observable bounds (e.g., observables={"x": (0, 10)}), distributions are normalized over that domain

  • Without observables: Distributions remain unnormalized (raw likelihood)

  • HistFactory: Explicitly opts out via _normalizable = False (already normalized by design)

Example:

from pyhs3.distributions.basic import GaussianDist

# Define distribution
gauss = GaussianDist(name="signal", mean="mu", sigma="sigma", x="x")

# With observables: normalized over [100, 160]
model = Model(
    distributions=[gauss],
    observables={"x": (100.0, 160.0)},
    # ... other fields
)
# The distribution will integrate to 1.0 over [100, 160]

Providing analytical normalization:

Override normalization_expression() to return the antiderivative for efficient analytical integration:

class LinearDist(Distribution):
    def likelihood(self, context: Context) -> TensorVar:
        return context["x"]  # f(x) = x

    def normalization_expression(
        self, context: Context, observable_name: str
    ) -> TensorVar:
        observable = context[observable_name]
        return observable**2 / 2.0  # F(x) = x²/2

Without an analytical expression, pyhs3 uses 64-point Gauss-Legendre quadrature for numerical integration.

For complete details, see PDF Normalization.

Batching Many Instances of a Component

A workspace can hold hundreds of instances of one function or distribution type, such as one InterpolationFunction per sample and systematic, or one Gaussian constraint per nuisance parameter. A type that inherits BatchableFunction or BatchableDistribution lets the model build all instances that feed one likelihood channel with a single vectorised expression, which pyhs3 calls a family, so that compile time does not grow with their number. Building many functions or distributions of one type as a family explains the design.

The model finds batchable types by inheritance, wherever their instances appear among a model’s functions or distributions, and needs no other registration. It groups the instances of each class that feed one root distribution into one family; a group needs at least two members, and an instance that depends on another member of its group is built on its own. To see which instances were built on their own instead of in a family, and why, enable debug logging for pyhs3:

import logging

logging.basicConfig()
logging.getLogger("pyhs3").setLevel(logging.DEBUG)

Functions

Besides _expression, a batchable type implements the classmethod batch_expressions(). It receives:

  • members: the instances of exactly this class in one family, in a fixed order;

  • context: a built tensor for every name the members’ parameter fields reference;

  • functions: the model’s function definitions (Function objects, not tensors) by name, for a member whose inputs are themselves functions and whose structure you want to inspect.

It returns a dict with one entry per member name, each an expression with the same shape as that member’s own expression(context). Here each member is a scalar:

>>> from typing import Literal
>>> import numpy as np
>>> import pytensor
>>> import pytensor.tensor as pt
>>> from pyhs3.functions import BatchableFunction
>>> class ScaledFunction(BatchableFunction):
...     type: Literal["scaled"] = "scaled"
...     x: str
...     factor: float
...     def _expression(self, context):
...         return context[self.x] * self.factor
...     @classmethod
...     def batch_expressions(cls, members, context, functions):
...         # Stack the inputs into one (F,) vector, scale by a constant (F,)
...         # table, and split back into one scalar per member.
...         x = pt.stack([context[m.x] for m in members])
...         scaled = x * np.array([m.factor for m in members])
...         pieces = pt.split(scaled, [1] * len(members), n_splits=len(members))
...         return {m.name: p.reshape(()) for m, p in zip(members, pieces)}
...
>>> members = [
...     ScaledFunction(name="a", x="u", factor=2.0),
...     ScaledFunction(name="b", x="v", factor=3.0),
... ]
>>> u, v = pt.dscalar("u"), pt.dscalar("v")
>>> context = {"u": u, "v": v}
>>> outputs = ScaledFunction.batch_expressions(members, context, {})
>>> f = pytensor.function([u, v], [outputs["a"], outputs["b"]], mode="FAST_COMPILE")
>>> [float(y) for y in f(1.5, 4.0)]
[3.0, 12.0]

Nothing checks at run time that the batched outputs equal each member’s own expression, so compare them yourself, as here and in your tests:

>>> g = pytensor.function(
...     [u, v], [m.expression(context) for m in members], mode="FAST_COMPILE"
... )
>>> [float(y) for y in g(1.5, 4.0)]
[3.0, 12.0]

The contract and the graph rules that keep a family fast:

  • Equal results: each returned expression has the value of the member’s own expression(context). For a member you cannot batch (for example one with a non-scalar input), return its own expression(context) and log the reason at debug level.

  • Every member: return an entry for every member; the model raises a RuntimeError naming any member that is missing.

  • Fixed graph size: build a fixed number of operations however many members there are. Build per-member constant tables as one numpy array from Python values, rather than stacking many scalar constant tensors.

  • One Split for the outputs: read the per-member outputs with a single pt.split, not by indexing result[i] per member; see Building many functions or distributions of one type as a family for why.

Distributions

A distribution type whose math is elementwise in every parameter needs no batching code of its own: inheriting BatchableDistribution is a promise that likelihood, log_likelihood and normalization_expression (if defined) still compute the right values when each parameter is replaced by a tensor of several members’ values, broadcast against the observable. The inherited batch_log_expressions() then evaluates the class’s own log_expression once for the whole family, normalization included, and splits the result back into one log density per member, of shape (N, 1) for an observable with N events, or a scalar for a distribution of parameters only (a constraint).

Formulas built from elementwise PyTensor operations (+, *, pt.exp, pt.switch, and so on) keep that promise. A formula that reduces over an axis, indexes or reshapes its inputs, or depends on Python-level control flow on parameter values does not, and its type should not inherit BatchableDistribution. Members are batched together when their fields name the same non-scalar inputs, such as one observable, and differ only in scalar parameters; a type used both as a shape and as a constraint forms one batch of each, and a member that matches no other is built on its own, logged at debug level. Because a member is one row of its batch, pdf() of that member takes the inputs of every member batched with it.

No built-in distribution opts in. On large workspaces, batching its crystal-ball shapes made the JAX compile faster but the cold C compile slower, and batching its Gaussian constraints slowed C evaluation without any gain; Building many functions or distributions of one type as a family gives the measurements and the reason. Before opting in a type of your own, measure the cold compile and the evaluation time with both backends on your workspaces.

For example, an exponential decay with an analytic normalization:

>>> from pyhs3.context import Context
>>> from pyhs3.distributions import BatchableDistribution
>>> class DecayDist(BatchableDistribution):
...     type: Literal["decay"] = "decay"
...     x: str
...     rate: str
...     def likelihood(self, context):
...         return pt.exp(-context[self.rate] * context[self.x])
...     def log_likelihood(self, context):
...         return -context[self.rate] * context[self.x]
...     def normalization_expression(self, context, observable_name):
...         rate = context[self.rate]
...         return -pt.exp(-rate * context[observable_name]) / rate
...
>>> x = pt.dvector("x")
>>> rates = {"r0": pt.dscalar("r0"), "r1": pt.dscalar("r1")}
>>> context = Context(
...     parameters={"x": x, **rates},
...     observables={"x": (pt.constant(0.0), pt.constant(10.0))},
...     views={"x": x[:, None]},  # observables enter as (N, 1) views
... )
>>> decays = [DecayDist(name=f"d{k}", x="x", rate=f"r{k}") for k in range(2)]
>>> batched = DecayDist.batch_log_expressions(decays, context)
>>> f = pytensor.function(
...     [x, *rates.values()],
...     [batched["d0"], batched["d1"], *(d.log_expression(context) for d in decays)],
...     mode="FAST_COMPILE",
... )
>>> b0, b1, own0, own1 = f(np.array([0.5, 2.0, 4.0]), 0.3, 1.2)
>>> b0.shape
(3, 1)
>>> bool(np.allclose(b0, own0) and np.allclose(b1, own1))
True

As for functions, compare the batched log densities with each member’s own log_expression in your tests, as above: nothing checks the elementwise promise at run time.

Best Practices

  1. Use descriptive type literals for easy identification

  2. Document your components with clear docstrings and examples

  3. Handle edge cases in your expression() method

  4. Test thoroughly with different parameter combinations

  5. Consider performance - PyTensor operations should be efficient

  6. Follow naming conventions - use clear, descriptive field names

  7. Validate inputs when auto-processing isn’t sufficient

The automatic parameter processing handles most common cases, letting you focus on the mathematical implementation rather than parameter management boilerplate.