"""
Composite distribution implementations.
Provides classes for handling composite probability distributions that combine
multiple other distributions, including mixtures and products of distributions.
"""
from __future__ import annotations
from collections.abc import Callable, Mapping, Sequence
from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast
import pytensor.tensor as pt
from pydantic import (
Field,
PrivateAttr,
ValidationInfo,
field_serializer,
field_validator,
model_serializer,
)
from pyhs3.base import balanced_sum
from pyhs3.context import Context
from pyhs3.distributions.core import Distribution, LogProbTerms
from pyhs3.typing.aliases import TensorVar
if TYPE_CHECKING:
from pyhs3.distributions import Distributions
def _stable_logsumexp(
x: TensorVar, axis: int, weights: TensorVar | None = None
) -> TensorVar:
"""Numerically stable log-sum-exp, built explicitly instead of via ``pt.logsumexp``.
``pt.logsumexp`` lowers to the literal ``log(sum(exp(x)))`` graph; the
protection against overflow/underflow is not part of that graph but is
instead an emergent property of the ``local_log_sum_exp`` graph rewrite,
which only runs in the stabilize/specialize passes under ``FAST_RUN``.
Any mode that skips those passes (e.g. ``FAST_COMPILE``, which
``Model``/``Workspace.model()`` expose to callers via ``mode=``) silently
loses the protection. Building the max-shifted form here makes the
stability structural rather than rewrite-dependent. See
https://github.com/scipp-atlas/pyhs3/issues/277 for the failure mode and
https://github.com/pymc-devs/pytensor/issues/2288 for the tracked
upstream request for a stable-by-construction ``logsumexp``.
With ``weights``, the reduction is log(sum(weights * exp(x))): each term
enters the sum multiplied by the corresponding entry of ``weights``, which
may be negative or zero. This is how :class:`MixtureDist` evaluates
log(sum_i c_i f_i) with ``x = log f`` and ``weights = c``. The max shift
uses ``x`` only, so every exp(x - m) stays <= 1 and the result is stable
in the same regimes, while the weights enter linearly: the derivative
with respect to a weight is exp(x - m) / sum, finite even where the
weight is exactly zero (unlike writing the term as log|w| + x, whose
derivative 1/w is infinite there). A negative total gives NaN (log of a
negative number), surfacing a density that is negative somewhere; a total
of exactly zero gives -inf. When positive and negative terms nearly
cancel, the relative precision of the total is limited by that
cancellation, as it is for the probability-space sum.
Args:
x: Tensor to reduce.
axis: Axis to reduce over.
weights: Optional tensor broadcastable to ``x`` holding each term's
weight. ``None`` means every weight is one.
Returns:
log(sum(exp(x), axis=axis)), stable against underflow (large
negative x, the case relevant to :class:`MixtureDist`) and overflow
(large positive x). Reduces to -inf (not NaN) when every entry along
axis is -inf: the ``pt.isinf`` guard below substitutes 0.0 for the
max in that slice so the subsequent subtraction is ``-inf - 0.0``
rather than ``-inf - -inf`` (NaN). The *value* is finite there, but
its gradient is not: d/ds log(s) diverges as s = sum(exp(x - safe_m))
approaches 0, so the gradient at an all-(-inf) point is NaN. That is
a genuine singularity of log at its domain boundary -- present in
any logsumexp implementation, not an artifact of the guard above
(whose own gradient contribution stays finite; see the
``_stable_logsumexp`` tests in ``tests/test_distributions.py``).
"""
m = pt.max(x, axis=axis, keepdims=True) # type: ignore[no-untyped-call]
safe_m = pt.switch(pt.isinf(m), 0.0, m)
shifted = pt.exp(x - safe_m)
if weights is not None:
shifted = weights * shifted
result = safe_m + pt.log(
pt.sum(shifted, axis=axis, keepdims=True) # type: ignore[no-untyped-call]
)
return cast(TensorVar, pt.squeeze(result, axis=axis)) # type: ignore[no-untyped-call]
def _weighted_logsumexp(
log_terms: Sequence[TensorVar], weights: Sequence[TensorVar]
) -> TensorVar:
"""log(Σᵢ wᵢ·exp(log_termsᵢ)) via :func:`_stable_logsumexp`, term by term.
``log_terms[i]`` and ``weights[i]`` belong to the same summand. The log
terms share a shape (e.g. ``(N, M)`` per event, ``(N, 1)`` for an
observable with scalar parameters, or a scalar); terms of different
types are first broadcast against each other. Each weight is a scalar
or a parameter batch (``(M,)`` or a ``(1, M)`` view). The weights are
padded with leading broadcastable axes to the terms' rank, (1, 1) or
(1, M), and given a common shape among themselves only, so that their
stack ``(n_summands, 1, 1 or M)`` broadcasts against the stacked terms
``(n_summands, N, M)``; the reduction over the stacking axis gives the
terms' shape back. Broadcasting each weight to its term's full shape
would need that term's symbolic shape, which is slow to build for large
expressions.
"""
if len({term.type for term in log_terms}) > 1:
log_terms = list(pt.broadcast_arrays(*log_terms))
ndim = max(term.ndim for term in log_terms)
padded = [
weight.dimshuffle(("x",) * (ndim - weight.ndim) + tuple(range(weight.ndim))) # type: ignore[no-untyped-call]
if weight.ndim < ndim
else weight
for weight in weights
]
if len({weight.type for weight in padded}) > 1:
padded = list(pt.broadcast_arrays(*padded))
return _stable_logsumexp(
pt.stack(log_terms, axis=0), axis=0, weights=pt.stack(padded, axis=0)
)
[docs]
class MixtureDist(Distribution):
r"""
Mixture of probability distributions.
Implements a weighted combination of multiple distributions following ROOT's RooAddPdf.
Supports both N and N-1 coefficient configurations where :math:`N` represents number of distributions (`summands`):
**N-1 coefficients:**
.. math::
f(x) = \sum_{i=1}^{n-1} c_i \cdot f_i(x) + (1 - \sum_{i=1}^{n-1} c_i) \cdot f_n(x)
**N coefficients:**
.. math::
f(x) = \frac{\sum_{i=1}^{n} c_i \cdot f_i(x)}{\sum_{i=1}^{n} c_i}
**N coefficients with `ref_coef_norm`:**
.. math::
f(x) = \frac{\sum_{i=1}^{n} c_i \cdot f_i(x)}{\sum_{j \in \text{ref\_coef\_norm}} c_j}
Both log-space paths build log(Σcᵢfᵢ) via logsumexp over each summand's
own log-space expression rather than pt.log of the probability-space
sum, so they stay finite even when every component underflows to 0.0:
:meth:`log_prob_terms` for an extended mixture in the joint likelihood,
and :meth:`log_likelihood` (behind
:meth:`~pyhs3.distributions.Distribution.log_expression`, used for
non-extended mixtures and standalone evaluation), which reads the
summands' log-space tensors from the context (see
https://github.com/scipp-atlas/pyhs3/issues/282).
Parameters:
coefficients (list[str]): Names of coefficient parameters.
summands (list[str]): Names of component distributions.
extended (bool): Whether the mixture is extended (affects normalization).
Must be True for N coefficients, False for N-1 coefficients.
ref_coef_norm (list[str] | None): Optional list of coefficient names for custom normalization.
Only valid when using N coefficients (extended=True).
ROOT Reference:
:root:`RooAddPdf`
"""
type: Literal["mixture_dist"] = "mixture_dist"
summands: list[str]
coefficients: list[str]
extended: bool = False
ref_coef_norm: list[str] | None = Field(
default=None, json_schema_extra={"preprocess": False}
)
# PyTensor nodes built by the most recent likelihood() call, reused by
# unnormalized_expression() and expected_yield() so that model.log_prob
# shares the same subgraphs instead of building duplicates the compiler
# then has to merge (a measurable compile-time cost on large workspaces).
# Components are already-normalized densities; re-normalizing over the
# observables they depend on would add a redundant integral.
_normalizable: bool = PrivateAttr(default=False)
_cached_unnorm_expr: TensorVar | None = PrivateAttr(default=None)
_cached_nu_expr: TensorVar | None = PrivateAttr(default=None)
# Per-summand coefficient nodes (context[coeff] for each entry in
# self.coefficients, N==N case only), cached alongside _cached_unnorm_expr
# so that log_prob_terms can build the log-space logsumexp directly from
# the same coefficient tensors used in the probability-space sum, rather
# than re-resolving them from a context it is not given.
_cached_coeffs: list[TensorVar] | None = PrivateAttr(default=None)
# The caches above are set by this object's own likelihood() call and read
# by its log_prob_terms(); an alias sharing another mixture's expression
# would never set them.
share_identical_expressions: ClassVar[bool] = False
[docs]
@model_serializer(mode="wrap")
def serialize_model(self, handler: Callable[[Any], Any]) -> Any:
"""Do not serialize ref_coef_norm if it is unspecified (None)."""
data = handler(self)
if self.ref_coef_norm is None:
# exclude_none / exclude may already have dropped the key.
data.pop("ref_coef_norm", None)
return data
[docs]
@field_validator("ref_coef_norm", mode="before")
@classmethod
def split_comma_separated_ref_coef_norm(cls, v: object) -> object:
"""Convert comma-separated string to list for ref_coef_norm."""
if isinstance(v, str):
v = v.strip()
return None if v == "" else v.split(",")
return v
[docs]
@field_validator("ref_coef_norm", mode="after")
@classmethod
def validate_ref_coef_norm_usage(
cls, ref_coef_norm: list[str] | None, info: ValidationInfo
) -> list[str] | None:
"""Validate that ref_coef_norm is only used with N=N coefficient case."""
if ref_coef_norm is not None:
# Get summands and coefficients from the values being validated
summands = info.data.get("summands", [])
coefficients = info.data.get("coefficients", [])
n_coeffs = len(coefficients)
n_summands = len(summands)
if n_coeffs != n_summands:
msg = (
f"ref_coef_norm can only be used with N coefficients and N summands "
f"(N={n_summands}), but got {n_coeffs} coefficients."
)
raise ValueError(msg)
return ref_coef_norm
[docs]
@field_serializer("ref_coef_norm")
def serialize_ref_coef_norm(self, ref_coef_norm: list[str] | None) -> str | None:
"""Convert list back to comma-separated string for serialization."""
if ref_coef_norm is None:
return None
return ",".join(ref_coef_norm)
[docs]
@field_validator("coefficients", mode="after")
@classmethod
def validate_coefficient_count(
cls, coefficients: list[str], info: ValidationInfo
) -> list[str]:
"""Validate that coefficient count matches summand count appropriately."""
# Get summands from the values being validated
summands = info.data.get("summands", [])
n_coeffs = len(coefficients)
n_summands = len(summands)
if n_coeffs not in (n_summands, n_summands - 1):
msg = (
f"Invalid coefficient configuration: {n_coeffs} coefficients "
f"for {n_summands} summands. Must have N ({n_summands}) or "
f"N-1 ({n_summands - 1}) coefficients."
)
raise ValueError(msg)
return coefficients
[docs]
@field_validator("extended", mode="after")
@classmethod
def validate_extended_matches_coefficients(
cls, extended: bool, info: ValidationInfo
) -> bool:
"""Validate that extended matches coefficient configuration."""
# Get summands and coefficients from the values being validated
summands = info.data.get("summands", [])
coefficients = info.data.get("coefficients", [])
n_coeffs = len(coefficients)
n_summands = len(summands)
# Validate extended matches coefficient configuration
if n_coeffs == n_summands:
if not extended:
msg = (
f"extended must be True when N coefficients = N summands "
f"({n_coeffs} coefficients, {n_summands} summands)."
)
raise ValueError(msg)
elif extended:
msg = (
f"extended must be False when N-1 coefficients with N summands "
f"({n_coeffs} coefficients, {n_summands} summands)."
)
raise ValueError(msg)
return extended
[docs]
def likelihood(self, context: Context) -> TensorVar:
"""
Builds a symbolic expression for the mixture distribution.
Handles both N and N-1 coefficient cases:
- N-1 coefficients: Traditional approach with automatic normalization
- N coefficients: Direct summation with optional custom normalization
Args:
context (dict): Mapping of names to pytensor variables.
Returns:
pytensor.tensor.variable.TensorVariable: Symbolic representation of the mixture PDF.
"""
n_coeffs = len(self.coefficients)
n_summands = len(self.summands)
if n_coeffs == n_summands:
# N coefficients case: direct summation with normalization
# Calculate the mixture sum (unnormalized: Σ cᵢ fᵢ)
coeff_tensors = [context[coeff] for coeff in self.coefficients]
mixture_terms = [
coeff_tensor * context[summand]
for coeff_tensor, summand in zip(
coeff_tensors, self.summands, strict=True
)
]
mixturesum = balanced_sum(mixture_terms, pt.constant(0.0))
# Cache the unnormalized Σcᵢfᵢ so that model.log_prob can build
# the extended log-likelihood as Σⱼ log(Σcᵢfᵢ(xⱼ)) - nu without
# introducing a separate pt.log(nu) node that triggers costly
# optimizer rewrites when combined with log(Σcᵢfᵢ/nu).
self._cached_unnorm_expr = mixturesum
# Cache the per-summand coefficient nodes (same order as
# self.summands) so log_prob_terms can build the log-space
# equivalent Σᵢ cᵢfᵢ = logsumexp(log cᵢ + log fᵢ) directly, which
# stays finite where the probability-space fᵢ underflow to 0.0.
self._cached_coeffs = coeff_tensors
# Handle normalization
if self.ref_coef_norm is not None:
# Custom normalization using specified coefficients
norm_sum = balanced_sum(
[context[norm_coeff] for norm_coeff in self.ref_coef_norm],
pt.constant(0.0),
)
# Cache the normalisation sum so expected_yield() can reuse
# the same PyTensor node rather than building a duplicate
# summation subgraph that the compiler then has to merge.
self._cached_nu_expr = norm_sum
mixturesum = mixturesum / norm_sum
else:
# Standard normalization: divide by sum of all coefficients
coeffsum = balanced_sum(
[context[coeff] for coeff in self.coefficients],
pt.constant(0.0),
)
# Cache so expected_yield() reuses this node.
self._cached_nu_expr = coeffsum
mixturesum = mixturesum / coeffsum
else:
# N-1 coefficients case: traditional approach with automatic last term
coeffsum = balanced_sum(
[context[coeff] for coeff in self.coefficients], pt.constant(0.0)
)
# First N-1 terms
mixture_terms = [
context[coeff] * context[self.summands[i]]
for i, coeff in enumerate(self.coefficients)
]
# Add the last term with remaining coefficient
last_index = len(self.summands) - 1
f_last = context[self.summands[last_index]]
mixture_terms.append((1 - coeffsum) * f_last)
mixturesum = balanced_sum(mixture_terms, pt.constant(0.0))
return mixturesum
[docs]
def log_likelihood(self, context: Context) -> TensorVar:
"""
Log-space mixture density built from the summands' log-densities.
Evaluates log(Σᵢ wᵢ·fᵢ) as a weighted logsumexp over each summand's
log-space tensor (``context.log_density(summand)``) rather than
``pt.log`` of the probability-space sum, so it stays finite where
every fᵢ underflows to 0.0. The weights are the same as in
:meth:`likelihood`:
- N coefficients: wᵢ = cᵢ / Σⱼcⱼ, or cᵢ / Σ_{j ∈ ref_coef_norm} cⱼ.
- N-1 coefficients: wᵢ = cᵢ for the first N-1 summands and
w_N = 1 - Σᵢcᵢ for the last.
The weights enter linearly (see ``_stable_logsumexp``), so negative
weights are allowed: the result is NaN exactly where the mixture
density itself is negative.
Args:
context: Mapping of names to pytensor variables, with the
summands' log-space tensors registered by the model builder.
Returns:
TensorVar: Log of the mixture PDF, with the summands' shape.
"""
log_terms = [context.log_density(summand) for summand in self.summands]
if len(self.coefficients) == len(self.summands):
# likelihood() fills the coefficient and yield caches that
# log_prob_terms() and expected_yield() read; reuse its nodes.
self.likelihood(context)
coeffs = cast(list[TensorVar], self._cached_coeffs)
nu = cast(TensorVar, self._cached_nu_expr)
weights = [coeff / nu for coeff in coeffs]
else:
coeffs = [context[coeff] for coeff in self.coefficients]
last = 1 - balanced_sum(coeffs, pt.constant(0.0))
weights = [*coeffs, cast(TensorVar, last)]
return _weighted_logsumexp(log_terms, weights)
[docs]
def expected_yield(self, context: Context) -> TensorVar:
"""
Compute the total expected yield nu in the extended case.
- N coefficients case: nu = sum(coefficients) or sum(ref_coef_norm) if specified
- N-1 coefficients case: not defined (extended=False always)
Args:
context: Mapping of names to pytensor variables
Returns:
Expected yield (nu) for extended likelihood
Raises:
RuntimeError: If called on non-extended PDF
"""
if not self.extended:
msg = "expected_yield only valid for extended PDFs"
raise RuntimeError(msg)
# Reuse the normalisation sum cached by likelihood() to avoid building
# a duplicate PyTensor summation subgraph (which would slow compilation).
if self._cached_nu_expr is not None:
return self._cached_nu_expr
# Fallback: likelihood() hasn't been called yet, compute fresh.
coeff_names = (
self.ref_coef_norm if self.ref_coef_norm is not None else self.coefficients
)
return balanced_sum([context[coeff] for coeff in coeff_names], pt.constant(0.0))
[docs]
def unnormalized_expression(self, context: Context) -> TensorVar:
"""Return the unnormalized mixture Σcᵢfᵢ (before dividing by Σcᵢ).
After :meth:`likelihood` has been called this just returns the cached
intermediate result. This is a probability-space quantity: for the
per-event log-likelihood, :meth:`log_prob_terms` builds
log(Σcᵢfᵢ(xⱼ)) directly from each summand's own log-space expression
via logsumexp instead of taking ``pt.log`` of this sum, so that the
result stays finite where the probability-space fᵢ(xⱼ) underflow to
0.0. This method remains available for callers wanting the raw
probability-space value itself.
The Poisson yield term enters the likelihood once per channel and
involves the observed event count, so it is assembled by
:meth:`pyhs3.Model.log_prob` (which owns the channel-dataset
pairing) rather than via :meth:`extended_likelihood` (whose result is
multiplied into the per-event density and would be overcounted when
summing over events).
"""
if self._cached_unnorm_expr is not None:
return self._cached_unnorm_expr
# Fallback: recompute (likelihood() hasn't been called yet).
unnorm_terms = [
context[coeff] * context[self.summands[i]]
for i, coeff in enumerate(self.coefficients)
]
return balanced_sum(unnorm_terms, pt.constant(0.0))
[docs]
def log_prob_terms( # pylint: disable=redefined-outer-name
self,
expressions: Mapping[str, TensorVar],
log_expressions: Mapping[str, TensorVar],
distributions: Distributions,
) -> LogProbTerms:
"""
Extended-likelihood contributions for the mixture.
For an extended mixture the per-channel log-likelihood is built from
the unnormalized mixture and the expected yield:
Σⱼ log(Σᵢcᵢfᵢ(xⱼ)) - nu
which simplifies from Σⱼ log(Σᵢcᵢfᵢ(xⱼ)/nu) + N·log(nu) - nu (the
log(nu) terms cancel). This is algebraically identical to the full
extended likelihood but avoids introducing pt.log(nu) into the graph,
preventing costly optimizer rewrite cascades triggered by
log(a/b) + N·log(b). For weighted data this form also reproduces
RooFit's sum-of-weights convention: weighting the log(Σᵢcᵢfᵢ) term
gives Σⱼwⱼ·log(PDF) + (Σwⱼ)·log(nu) - nu.
log(Σᵢcᵢfᵢ(xⱼ)) is evaluated as logsumexp(log cᵢ + log fᵢ(xⱼ)) using
each summand's own log-space expression (``log_expressions``) rather
than ``pt.log`` of the probability-space sum
(``_cached_unnorm_expr``). fᵢ(xⱼ) can underflow to 0.0 in
float64 for xⱼ far in a component's tail, which would make every
cᵢfᵢ(xⱼ) — and hence their sum — exactly 0.0 and ``pt.log`` of it
``-inf``, even though log fᵢ(xⱼ) itself is finite. Building the sum
in log space keeps it finite in that regime. The log cᵢ + log fᵢ(xⱼ)
terms are stacked on a new leading axis (shape ``(n_summands, N, M)``
for ``N`` events and parameter-batch size ``M``, matching the
per-event shape documented on :class:`LogProbTerms`) and reduced with
``_stable_logsumexp`` over that axis, giving the ``(N, M)``
per-event term. ``_stable_logsumexp`` is used instead of
``pt.logsumexp`` because the latter's stability is an emergent
property of a graph rewrite that only runs under ``FAST_RUN`` (see
``_stable_logsumexp``'s docstring and
https://github.com/scipp-atlas/pyhs3/issues/277).
Coefficients may be negative: HS3 defines the mixture as Σᵢcᵢfᵢ
without restricting the sign of cᵢ (and c_n = 1 - Σcᵢ can be negative
by construction), and RooFit's RooAddPdf accepts it. The terms are
therefore log fᵢ(xⱼ), reduced with the cᵢ as linear weights, so the
result equals log(Σᵢcᵢfᵢ(xⱼ)) whenever that sum is positive and is NaN
where it is negative (see
https://github.com/scipp-atlas/pyhs3/issues/348). Keeping cᵢ linear
also keeps the gradient with respect to cᵢ finite at cᵢ = 0, the
usual starting point of e.g. a spurious-signal yield.
The data-only -log(N!) constant is omitted and N_eff = Σwⱼ is used
for weighted data; both are RooFit conventions adopted because HS3
does not specify the extended term exactly. See
https://github.com/hep-statistics-serialization-standard/hep-statistics-serialization-standard/issues/91
and https://github.com/scipp-atlas/pyhs3/issues/241.
Non-extended mixtures contribute the default per-event log(PDF).
"""
if not self.extended:
return super().log_prob_terms(expressions, log_expressions, distributions)
if (
self._cached_unnorm_expr is None
or self._cached_nu_expr is None
or self._cached_coeffs is None
):
msg = (
f"log_prob_terms for extended mixture '{self.name}' requires "
f"likelihood() to have been called (the model graph build does "
f"this) so the unnormalized mixture and yield nodes exist."
)
raise RuntimeError(msg)
# Each log f_i has the per-event shape (N, M); each coefficient is a
# scalar or a (M,) batch. The weighted reduction over the summands
# gives the (N, M) per-event term.
per_event_term = _weighted_logsumexp(
[log_expressions[summand] for summand in self.summands],
self._cached_coeffs,
)
return LogProbTerms(
per_event=[per_event_term],
channel=[-self._cached_nu_expr],
)
[docs]
class ProductDist(Distribution):
r"""
Product distribution implementation.
Implements a product of PDFs as defined in ROOT's RooProdPdf.
The probability density function is defined as:
.. math::
f(x, \ldots) = \prod_{i=1}^{N} \text{PDF}_i(x, \ldots)
where each PDF_i is a component distribution that may share observables.
Parameters:
factors: List of component distribution names to multiply together
Note:
In the context of pytensor variables/tensors, this is implemented as
an elementwise product of all factor distributions.
"""
type: Literal["product_dist"] = "product_dist"
factors: list[str]
# Factors are already-normalized densities, each over its own observables.
_normalizable: bool = PrivateAttr(default=False)
[docs]
def likelihood(self, context: Context) -> TensorVar:
"""
Evaluate the product distribution.
Args:
context: Mapping of names to pytensor variables
Returns:
Symbolic representation of the product PDF
"""
if not self.factors:
return cast(TensorVar, pt.constant(1.0))
vals = [context[factor] for factor in self.factors]
return cast(TensorVar, pt.mul(*vals))
[docs]
def log_likelihood(self, context: Context) -> TensorVar:
"""
Log-space product density: the sum of the factors' log-densities.
Sums each factor's log-space tensor (``context.log_density(factor)``)
rather than taking ``pt.log`` of the probability-space product, so
the result stays finite where a factor underflows to 0.0. The
factors broadcast against each other as in :meth:`likelihood`.
Args:
context: Mapping of names to pytensor variables, with the
factors' log-space tensors registered by the model builder.
Returns:
TensorVar: Log of the product PDF.
"""
if not self.factors:
return cast(TensorVar, pt.constant(0.0))
log_vals = [context.log_density(factor) for factor in self.factors]
return cast(TensorVar, pt.add(*log_vals))
[docs]
def log_prob_terms( # pylint: disable=redefined-outer-name
self,
expressions: Mapping[str, TensorVar],
log_expressions: Mapping[str, TensorVar],
distributions: Distributions,
) -> LogProbTerms:
"""
Split factors into per-event shape terms and per-channel constraints.
Factors that depend on an observable delegate to their own
log_prob_terms, so e.g. an extended mixture inside a product
contributes its yield term correctly. Such a factor carries the
event axis: observables enter as ``(N, 1)`` views, so its expression
has a leading axis that is not length-1. Batched parameters enter as
``(1, M)`` views, so a factor of parameters alone is a scalar or has
a length-1 leading axis.
Factors that depend only on nuisance parameters (scalar or batched)
are constraint PDFs and are returned as named constraints for the
model to add once globally. This prevents the N-fold overcounting that occurs when
naively summing log(shape x Π_j constr_j) over N events, which
multiplies each constr_j term by N rather than counting it once.
The shape-vs-constraint classification is structural inference
(matching RooProdPdf), not HS3 spec semantics — nothing in an HS3
file marks a factor as a constraint. If the spec adopts explicit
constraint encoding, this inference can be removed; see
https://github.com/hep-statistics-serialization-standard/hep-statistics-serialization-standard/issues/90
and https://github.com/scipp-atlas/pyhs3/issues/240.
"""
terms = LogProbTerms()
for factor_name in self.factors:
factor_expr = expressions[factor_name]
# Observable-dependent factors carry the event axis (axis 0); a
# batched parameter's (1, M) view only adds a length-1 axis 0.
is_shape = factor_expr.ndim >= 1 and not factor_expr.type.broadcastable[0]
if is_shape:
factor_terms = distributions[factor_name].log_prob_terms(
expressions, log_expressions, distributions
)
terms.per_event.extend(factor_terms.per_event)
terms.channel.extend(factor_terms.channel)
terms.constraints.update(factor_terms.constraints)
else:
terms.constraints[factor_name] = log_expressions[factor_name]
return terms
# Registry of composite distributions
distributions: dict[str, type[Distribution]] = {
"mixture_dist": MixtureDist,
"product_dist": ProductDist,
}
# Define what should be exported from this module
__all__ = [
"MixtureDist",
"ProductDist",
"distributions",
]