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}_observedwherenameis 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
constraintfield
- Parameters:
- 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
- Parameters:
data (
Any)
Fields¶ Field
Type
Required
Default
Yes
Literal[‘full’, ‘lite’]No
'lite'Yes
Yes
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
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.
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.
Identity of this distribution's expression, independent of its name.
to_hist()Convert HistFactory channel to hist.Hist with categorical process axis.
Per-bin parameters whose bin has a positive yield and zero uncertainty.
Attributes
Dictionary of PyTensor constants generated from numeric field values.
Return all parameters used by this HistFactory distribution.
Whether two distributions of this class that are equal in every field except
namemay share one built expression (seestructural_key()).
- HistFactoryDistChannel.constraint_specs()[source]¶
Yield
(dedup_key, modifier, sample_data)for each constraint modifier.dedup_keyis 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_keyisNone— these constraints are channel-local by workspace validation and are always emitted as-is.In BB-lite mode,
StatErrorModifierspecs are skipped entirely: theirdataisNoneby design (per-bin errors come from sample data instead), somodifier.make_constraint()would raise. The corresponding constraint is channel-level, not modifier-level — callers get it from_make_barlow_beeston_lite_constraintinstead.- 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 forcontextlike the likelihood terms, so calling this afterlog_likelihood()with the same context reuses its subgraph.
- 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-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.
- HistFactoryDistChannel.extended_likelihood(context, _data=None)[source]¶
Build constraint product for this channel.
Constraints are deduped by parameter — multiple
ParameterModifierinstances sharing one nuisance parameter (e.g., twonormsyson different samples both pointing atalpha_lumi) emit a single constraint factor, not one per modifier.ParametersModifierconstraints (shapesys,staterror) carry per-bin nominal yields and are always emitted per-modifier.
- 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.
- 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:
- 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']
- 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().
- 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 takinglogof the probability-spacelikelihood()/extended_likelihood()product. This keeps the result finite where the probability-space product would underflow to0.0.
- 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’slog_constraint(...)term (deduped by parameter exactly as inextended_likelihood()) instead of the product ofmake_constraint(...)terms.log_constraintevaluates the same constraint distribution(s) via their analytic log-space form, so this never takespt.logof a probability-space value that can underflow to 0.0.
- 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 thelog(prod(exp(log_probs)))round-trip, whose intermediate product underflows float64 to0.0for channels with many bins or large expected counts (turninglog_probinto-inf).
- HistFactoryDistChannel.log_prob_terms(_expressions, log_expressions, _distributions)¶
Structured contributions of this distribution to the joint log-likelihood.
Called by
pyhs3.Model.log_probfor 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 (extendedMixtureDist) 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:
- 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.
- 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).
- 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:
- 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)
- 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:
- 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]
- 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:
- 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)
- Histogram with shape
- Return type:
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 beconst.
- 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.
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.
- HistFactoryDistChannel.type¶
- HistFactoryDistChannel.axes¶
- HistFactoryDistChannel.samples¶
- HistFactoryDistChannel.barlow_beeston_method¶
- HistFactoryDistChannel.name¶