pyhs3.distributions.HistFactoryDistChannel

class pyhs3.distributions.HistFactoryDistChannel(**data)[source]

HistFactory probability distribution for a single channel/region.

Implements binned statistical models consisting of histograms (step functions) with various modifiers as defined in the HS3 specification. Each HistFactoryDistChannel represents one independent measurement channel/region with its own observed data. Multiple channels can be combined in a workspace to form a complete HistFactory model.

The total likelihood consists of: 1. Main likelihood: Poisson likelihood for observed bin counts vs expected rates 2. Constraint likelihoods: Constraint terms for nuisance parameters

The prediction for a binned region is given as:

\[\lambda(x) = \sum_{s \in \text{samples}} \left[ \left( d_s(x) + \sum_{\delta \in M_\delta} \delta(x,\theta_\delta) \right) \prod_{\kappa \in M_\kappa} \kappa(x,\theta_\kappa) \right]\]
where:
  • \(d_s(x)\) is the nominal prediction for sample \(s\)

  • \(M_\delta\) are additive modifiers (histosys)

  • \(M_\kappa\) are multiplicative modifiers (normfactor, normsys, shapefactor, etc.)

Observed Data Convention:

Observed data must be provided in the context as {name}_observed where name is the HistFactory distribution name. This is required for likelihood evaluation.

Constraint Types:
  • Gaussian constraints (default): histosys, normsys, staterror

  • Poisson constraints (default): shapesys

  • All constraint types can be overridden via the constraint field

Parameters:
  • axes (list) – Array of axis definitions with binning information

  • samples (list) – Array of sample definitions with data and modifiers

Supported Modifiers:
  • normfactor: Multiplicative scaling by parameter value

  • normsys: Multiplicative systematic with hi/lo interpolation

  • histosys: Additive correlated shape systematic

  • shapefactor: Uncorrelated multiplicative bin-by-bin scaling

  • shapesys: Uncorrelated shape systematic with Poisson constraints

  • staterror: Statistical uncertainty via Barlow-Beeston method

Modifier Naming in Dependency Graph:

Modifiers have simple names (e.g., “lumi”) in the HS3 specification, but are given unique identifiers in the dependency graph by prepending the full context: {dist_name}/{sample_name}/{modifier_type}/{modifier_name}

This design distinguishes individual modifier instances while allowing parameters to indicate correlation - modifiers sharing the same parameter name are correlated.

Example: Two modifiers both named “lumi” in different samples will have unique graph nodes like “SR/signal/normsys/lumi” and “CR/background/normsys/lumi”, but if they share the same parameter name, they are correlated.

HS3 Reference

histfactory_dist

Parameters:

data (Any)

Fields

Field

Type

Required

Default

axes

BinnedAxes

Yes

barlow_beeston_method

Literal[‘full’, ‘lite’]

No

'lite'

name

str

Yes

samples

Samples

Yes

type

Literal[‘histfactory_dist’]

No

'histfactory_dist'

__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

constraint_specs()

Yield (dedup_key, modifier, sample_data) for each constraint modifier.

expected_rates(context)

Expected Poisson mean of each bin, all modifiers applied.

expression(context)

Evaluate and return a named PyTensor expression.

extended_likelihood(context[, _data])

Build constraint product for this channel.

get_internal_nodes()

Return all internal nodes that need to be in the dependency graph.

get_parameter_list(context, param_key)

Reconstruct a parameter list from flattened indexed keys.

likelihood(context)

Build the HistFactory main Poisson likelihood.

log_expression(context)

Log-probability for the channel: summed Poisson log-pmf + log-constraints.

log_extended_likelihood(context)

Log-space constraint sum for this channel.

log_likelihood(context)

Log-space main Poisson likelihood: sum of per-bin Poisson log-pmfs.

log_prob_terms(_expressions, ...)

Structured contributions of this distribution to the joint log-likelihood.

model_post_init(context, /)

This function is meant to behave like a BaseModel method to initialise 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.

structural_key()

Identity of this distribution's expression, independent of its name.

to_hist()

Convert HistFactory channel to hist.Hist with categorical process axis.

unconstrained_parameters()

Per-bin parameters whose bin has a positive yield and zero uncertainty.

Attributes

constants

Dictionary of PyTensor constants generated from numeric field values.

parameters

Return all parameters used by this HistFactory distribution.

share_identical_expressions

Whether two distributions of this class that are equal in every field except name may share one built expression (see structural_key()).

type

axes

samples

barlow_beeston_method

name

HistFactoryDistChannel.constraint_specs()[source]

Yield (dedup_key, modifier, sample_data) for each constraint modifier.

dedup_key is the modifier’s parameter name for single-parameter modifiers (normsys, histosys); callers may use it to dedup constraints when multiple modifier instances reference the same nuisance parameter — within a channel or across channels in a joint fit. For multi-parameter modifiers (shapesys, staterror) dedup_key is None — these constraints are channel-local by workspace validation and are always emitted as-is.

In BB-lite mode, StatErrorModifier specs are skipped entirely: their data is None by design (per-bin errors come from sample data instead), so modifier.make_constraint() would raise. The corresponding constraint is channel-level, not modifier-level — callers get it from _make_barlow_beeston_lite_constraint instead.

Return type:

Iterator[tuple[str | None, HasConstraint, SampleData]]

HistFactoryDistChannel.expected_rates(context)[source]

Expected Poisson mean of each bin, all modifiers applied.

This is \(\lambda(x)\) of the class docstring, the rate that log_likelihood() compares the observed counts with. The expression is cached for context like the likelihood terms, so calling this after log_likelihood() with the same context reuses its subgraph.

Parameters:

context (Context) – Mapping of parameter names to PyTensor variables

Return type:

TensorVar

Returns:

PyTensor expression of shape (B,), B the total number of bins over all axes, when every parameter is a scalar.

HistFactoryDistChannel.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-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

HistFactoryDistChannel.extended_likelihood(context, _data=None)[source]

Build constraint product for this channel.

Constraints are deduped by parameter — multiple ParameterModifier instances sharing one nuisance parameter (e.g., two normsys on different samples both pointing at alpha_lumi) emit a single constraint factor, not one per modifier. ParametersModifier constraints (shapesys, staterror) carry per-bin nominal yields and are always emitted per-modifier.

Parameters:
Return type:

TensorVar

HistFactoryDistChannel.get_internal_nodes()[source]

Return all internal nodes that need to be in the dependency graph.

Modifiers can have the same name across different samples/types (e.g., “Lumi” appearing in multiple places), but the dependency graph requires unique node identifiers. We create wrapper objects that provide unique names while delegating to the original modifier’s functionality.

Return type:

list[Any]

HistFactoryDistChannel.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:
  • 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']
HistFactoryDistChannel.likelihood(context)[source]

Build the HistFactory main Poisson likelihood.

Returns the Poisson probability for observed bin counts vs expected rates. Does NOT include constraint terms - those are added via extended_likelihood().

Parameters:

context (Context) – Mapping of parameter names to PyTensor variables

Return type:

TensorVar

Returns:

PyTensor expression for the main Poisson model probability

HistFactoryDistChannel.log_expression(context)[source]

Log-probability for the channel: summed Poisson log-pmf + log-constraints.

Overrides Distribution.log_expression() to assemble the channel log-probability directly in log space (sum of per-bin Poisson log-pmfs plus summed log-constraint terms), rather than taking log of the probability-space likelihood()/extended_likelihood() product. This keeps the result finite where the probability-space product would underflow to 0.0.

Parameters:

context (Context) – Mapping of parameter names to PyTensor variables

Return type:

TensorVar

Returns:

PyTensor expression for the channel log-probability.

HistFactoryDistChannel.log_extended_likelihood(context)[source]

Log-space constraint sum for this channel.

Log-space counterpart of extended_likelihood(): returns the sum of each modifier’s log_constraint(...) term (deduped by parameter exactly as in extended_likelihood()) instead of the product of make_constraint(...) terms. log_constraint evaluates the same constraint distribution(s) via their analytic log-space form, so this never takes pt.log of a probability-space value that can underflow to 0.0.

Parameters:

context (Context) – Mapping of parameter names to PyTensor variables

Return type:

TensorVar

Returns:

PyTensor expression for the summed log-constraint contribution.

HistFactoryDistChannel.log_likelihood(context)[source]

Log-space main Poisson likelihood: sum of per-bin Poisson log-pmfs.

This is the log-space counterpart of likelihood(). Returning the sum of per-bin log-probabilities directly avoids the log(prod(exp(log_probs))) round-trip, whose intermediate product underflows float64 to 0.0 for channels with many bins or large expected counts (turning log_prob into -inf).

Parameters:

context (Context) – Mapping of parameter names to PyTensor variables

Return type:

TensorVar

Returns:

PyTensor expression for the summed Poisson log-probability.

HistFactoryDistChannel.log_prob_terms(_expressions, log_expressions, _distributions)

Structured contributions of this distribution to the joint log-likelihood.

Called by pyhs3.Model.log_prob for each channel after the model graph is built. Override when the distribution’s terms do not all enter the likelihood as a per-event log-density — e.g. once-per- channel yield terms (extended MixtureDist) or globally-deduplicated constraint factors (ProductDist).

Default: a single per-event log(PDF) term sourced from the pre-built log-space expression so it stays finite where the probability-space PDF underflows.

Parameters:
  • _expressions (Mapping[str, TensorVar]) – Compiled symbolic expressions for all distributions, keyed by name (model.distributions). Unused in the base implementation; subclasses may reference it.

  • log_expressions (Mapping[str, TensorVar]) – Compiled log-space symbolic expressions for all distributions, keyed by name (model.log_distributions).

  • _distributions (Distributions) – Distribution objects keyed by name, so composite distributions can delegate to their components’ hooks.

Returns:

per-event, per-channel, and constraint contributions.

Return type:

LogProbTerms

HistFactoryDistChannel.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

HistFactoryDistChannel.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).

Parameters:
  • context – Mapping of names to pytensor variables

  • observable_name – Name of the observable to integrate over

  • _context (Context)

  • _observable_name (str)

Return type:

TensorVar | None

Returns:

Symbolic antiderivative expression, or None for numerical fallback.

HistFactoryDistChannel.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:

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)
HistFactoryDistChannel.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:

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]
HistFactoryDistChannel.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:

str

HistFactoryDistChannel.to_hist()[source]

Convert HistFactory channel to hist.Hist with categorical process axis.

Creates a single histogram combining all samples using a categorical axis. The first axis is a categorical axis with sample names (labeled “process”), followed by the original binning axes.

Returns:

Histogram with shape (n_samples, *binning_shape) where:
  • Axis 0: Categorical axis “process” with sample names

  • Remaining axes: Original binning axes from self.axes

  • Values: Sample contents (with errors as variances)

Return type:

hist.Hist

Examples

>>> channel = HistFactoryDistChannel(
...     name="SR",
...     axes=[{"name": "mass", "min": 100, "max": 150, "nbins": 5}],
...     samples=[
...         {"name": "signal", "data": {"contents": [105, 106, 107, 108, 109], "errors": [0.5, 0.6, 0.7, 0.8, 0.9]}},
...         {"name": "background", "data": {"contents": [110, 111, 112, 113, 114], "errors": [0.05, 0.06, 0.07, 0.08, 0.09]}}
...     ]
... )
>>> h = channel.to_hist()
>>> h
Hist(
  StrCategory(['signal', 'background'], name='process'),
  Regular(5, 100, 150, name='mass'),
  storage=Weight()) # Sum: WeightedSum(value=1095, variance=2.5755)
>>> h.axes[0]
StrCategory(['signal', 'background'], name='process')
>>> h["signal", :]  # Get all mass bins for signal sample
Hist(Regular(5, 100, 150, name='mass'), storage=Weight()) # Sum: WeightedSum(value=535, variance=2.55)
HistFactoryDistChannel.unconstrained_parameters()[source]

Per-bin parameters whose bin has a positive yield and zero uncertainty.

Such a bin gets no constraint term (see unconstrained_parameters()); pyhf and ROOT fix its parameter at 1, so it must be const.

Return type:

list[str]

HistFactoryDistChannel.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.

HistFactoryDistChannel.parameters

Return all parameters used by this HistFactory distribution.

HistFactoryDistChannel.share_identical_expressions

Whether two distributions of this class that are equal in every field except name may share one built expression (see structural_key()). Classes that keep per-object state while their expression is built must set this to False: an alias reuses the first object’s tensors and never builds, so its own state would be missing.

HistFactoryDistChannel.type
HistFactoryDistChannel.axes
HistFactoryDistChannel.samples
HistFactoryDistChannel.barlow_beeston_method
HistFactoryDistChannel.name