pyhs3.distributions.MixtureDist¶
- class pyhs3.distributions.MixtureDist(*, name, type='mixture_dist', summands, coefficients, extended=False, ref_coef_norm=None)[source]¶
Mixture of probability distributions.
Implements a weighted combination of multiple distributions following ROOT’s RooAddPdf. Supports both N and N-1 coefficient configurations where \(N\) represents number of distributions (summands):
N-1 coefficients:
\[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:
\[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`:
\[f(x) = \frac{\sum_{i=1}^{n} c_i \cdot f_i(x)}{\sum_{j \in \text{ref\_coef\_norm}} c_j}\]log_prob_terms()is the log-space-safe path for an extended mixture: it builds log(Σcᵢfᵢ) via logsumexp over each summand’s own log-space expression rather than pt.log of the probability-space sum, so it stays finite even when every component underflows to 0.0. The base-classlog_expression()(used for non-extended mixtures and standalone evaluation) still round-trips through probability-space component tensors and cannot be converted until composite distributions receive log-space component context (see https://github.com/scipp-atlas/pyhs3/issues/254, phase 4).- Parameters:
name (
str)type (
Literal['mixture_dist'])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
RooAddPdf
Fields¶ Field
Type
Required
Default
Yes
No
FalseYes
No
NoneYes
Literal[‘mixture_dist’]No
'mixture_dist'Validators¶ Validator
Mode
Fields
before
after
after
after
- __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
expected_yield(context)Compute the total expected yield nu in the extended case.
expression(context)Evaluate and return a named PyTensor expression.
extended_likelihood(_context[, _data])Extended likelihood contribution in normal space.
get_parameter_list(context, param_key)Reconstruct a parameter list from flattened indexed keys.
likelihood(context)Builds a symbolic expression for the mixture distribution.
log_expression(context)Log-probability combining main likelihood with extended terms.
log_likelihood(context)Log-space counterpart of
likelihood().log_prob_terms(expressions, log_expressions, ...)Extended-likelihood contributions for the mixture.
model_post_init(context, /)This function is meant to behave like a BaseModel method to initialize private attributes.
normalization_expression(_context, ...)Return the antiderivative expression, or None for numerical fallback.
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.
serialize_model(handler)Do not serialize ref_coef_norm if it is unspecified (None).
serialize_ref_coef_norm(ref_coef_norm)Convert list back to comma-separated string for serialization.
Convert comma-separated string to list for ref_coef_norm.
Identity of this distribution's expression, independent of its name.
unnormalized_expression(context)Return the unnormalized mixture Σcᵢfᵢ (before dividing by Σcᵢ).
validate_coefficient_count(coefficients, info)Validate that coefficient count matches summand count appropriately.
Validate that extended matches coefficient configuration.
validate_ref_coef_norm_usage(ref_coef_norm, info)Validate that ref_coef_norm is only used with N=N coefficient case.
Attributes
Dictionary of PyTensor constants generated from numeric field values.
Set of parameter names this component depends on.
Whether two distributions of this class that are equal in every field except
namemay share one built expression (seestructural_key()).
- MixtureDist.expected_yield(context)[source]¶
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)
- Parameters:
context (
Context) – Mapping of names to pytensor variables- Return type:
- Returns:
Expected yield (nu) for extended likelihood
- Raises:
RuntimeError – If called on non-extended PDF
- MixtureDist.expression(context)¶
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-summandSumFunctionor a single-factorProductFunctionreturnscontext[param]directly, which is the same tensor object stored inmodel.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 andgraph_summarykeep working.
- MixtureDist.extended_likelihood(_context, _data=None)¶
Extended likelihood contribution in normal space.
Returns additional likelihood terms for extended ML fitting. Override only when the extended terms belong in the distribution’s per-event density, like constraint terms (HistFactory). Terms that enter the likelihood once per channel (e.g. the Poisson yield term of an extended MixtureDist, which involves the observed event count) must not use this hook:
_expression()multiplies the result into the density, soModel.log_probwould count it once per event when summing over data. Such terms are assembled once per channel byModel.log_prob, which owns the channel-dataset pairing.Default: no contribution (returns 1.0 in normal space).
- MixtureDist.get_parameter_list(context, param_key)¶
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:
- Return type:
- 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']
- MixtureDist.likelihood(context)[source]¶
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
- MixtureDist.log_expression(context)¶
Log-probability combining main likelihood with extended terms.
Returns log_likelihood() plus log(extended_likelihood()), minus the log of the normalization integral where normalization applies. This is mathematically equivalent to log(likelihood * extended_likelihood) but starts from log_likelihood() so that a distribution’s analytic log form (e.g. Gaussian, Poisson, LogNormal) is used directly instead of round- tripping through a probability value that can underflow to 0.0.
Normalization itself stays probability-space: the normalization integral (whether analytic or Gauss-Legendre quadrature) is a sum of positive terms and is far less underflow-prone than the raw density, so log(integral) is subtracted rather than computed as its own analytic log form.
All distributions are automatically normalized over observables present in the context, unless explicitly opted out via _normalizable = False.
PyTensor handles optimization and simplification automatically.
- MixtureDist.log_likelihood(context)¶
Log-space counterpart of
likelihood().Default implementation takes the log of the probability-space likelihood. Override with an analytic log-space form wherever one exists (e.g. Gaussian, Poisson, LogNormal): the default round-trips through a probability value that can underflow to 0.0 for parameter points far from the mode, at which point
pt.log(0.0)is-infeven though the true log-density is finite.
- MixtureDist.log_prob_terms(expressions, log_expressions, distributions)[source]¶
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 thanpt.logof 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 andpt.logof 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)forNevents and parameter-batch sizeM, matching the per-event shape documented onLogProbTerms) and reduced with_stable_logsumexpover that axis, giving the(N, M)per-event term._stable_logsumexpis used instead ofpt.logsumexpbecause the latter’s stability is an emergent property of a graph rewrite that only runs underFAST_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).
- Parameters:
- Return type:
- MixtureDist.model_post_init(context, /)¶
This function is meant to behave like a BaseModel method to initialize private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- MixtureDist.normalization_expression(_context, _observable_name)¶
Return the antiderivative expression, or None for numerical fallback.
Override in subclasses to provide analytical normalization. The returned expression should be the antiderivative F(x) such that the integral ∫f(x)dx from a to b equals F(b) - F(a).
- MixtureDist.process_parameter(param_key)¶
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:
- Returns:
(processed_name, numeric_value).processed_nameis either the original string value or a generated constant name;numeric_valueis the numeric value if the input was numeric,Noneotherwise.
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)
- MixtureDist.process_parameter_list(param_key)¶
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:
- Returns:
(processed_names, numeric_values).processed_nameslists the parameter names (original strings or generated constant names);numeric_valueslists the numeric values (Nonefor 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]
- MixtureDist.serialize_model(handler)[source]¶
Do not serialize ref_coef_norm if it is unspecified (None).
- MixtureDist.serialize_ref_coef_norm(ref_coef_norm)[source]¶
Convert list back to comma-separated string for serialization.
- classmethod MixtureDist.split_comma_separated_ref_coef_norm(v)[source]¶
Convert comma-separated string to list for ref_coef_norm.
- MixtureDist.structural_key()¶
Identity of this distribution’s expression, independent of its name.
Two distributions with the same key reference the same parameters, functions and constants in the same fields, so in one model they build identical expressions. The key is the class name plus the JSON dump of every field except
name.Examples
Equal fields under different names give the same key:
>>> from pyhs3.distributions import GaussianDist >>> a = GaussianDist(name="sig", x="m", mean="mu", sigma=1.0) >>> b = GaussianDist(name="bkg", x="m", mean="mu", sigma=1.0) >>> a.structural_key() == b.structural_key() True
A different value, or a constant in place of a parameter reference, gives a different key:
>>> c = GaussianDist(name="bkg", x="m", mean="mu", sigma=2.0) >>> d = GaussianDist(name="bkg", x="m", mean=0.0, sigma=1.0) >>> a.structural_key() in {c.structural_key(), d.structural_key()} False
- Returns:
The structural key.
- Return type:
- MixtureDist.unnormalized_expression(context)[source]¶
Return the unnormalized mixture Σcᵢfᵢ (before dividing by Σcᵢ).
After
likelihood()has been called this just returns the cached intermediate result. This is a probability-space quantity: for the per-event log-likelihood,log_prob_terms()builds log(Σcᵢfᵢ(xⱼ)) directly from each summand’s own log-space expression via logsumexp instead of takingpt.logof 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
pyhs3.Model.log_prob()(which owns the channel-dataset pairing) rather than viaextended_likelihood()(whose result is multiplied into the per-event density and would be overcounted when summing over events).
- classmethod MixtureDist.validate_coefficient_count(coefficients, info)[source]¶
Validate that coefficient count matches summand count appropriately.
- Parameters:
info (
ValidationInfo)
- Return type:
- classmethod MixtureDist.validate_extended_matches_coefficients(extended, info)[source]¶
Validate that extended matches coefficient configuration.
- Parameters:
extended (
bool)info (
ValidationInfo)
- Return type:
- classmethod MixtureDist.validate_ref_coef_norm_usage(ref_coef_norm, info)[source]¶
Validate that ref_coef_norm is only used with N=N coefficient case.
- MixtureDist.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.
- MixtureDist.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.
Whether two distributions of this class that are equal in every field except
namemay share one built expression (seestructural_key()). Classes that keep per-object state while their expression is built must set this toFalse: an alias reuses the first object’s tensors and never builds, so its own state would be missing.
- MixtureDist.type¶
- MixtureDist.summands¶
- MixtureDist.coefficients¶
- MixtureDist.extended¶
- MixtureDist.ref_coef_norm¶
- MixtureDist.name¶