pyhs3.distributions.AsymmetricCrystalBallDist

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

Crystal Ball distribution implementation.

Implements the generalized asymmetrical double-sided Crystal Ball line shape as defined in ROOT’s RooCrystalBall.

The probability density function is defined as:

\[\begin{split}f(m; m_0, \sigma_L, \sigma_R, \alpha_L, \alpha_R, n_L, n_R) = \begin{cases} A_L \cdot \left(B_L - \frac{m - m_0}{\sigma_L}\right)^{-n_L}, & \text{for } \frac{m - m_0}{\sigma_L} < -\alpha_L \\ \exp\left(-\frac{1}{2} \cdot \left[\frac{m - m_0}{\sigma_L}\right]^2\right), & \text{for } \frac{m - m_0}{\sigma_L} \leq 0 \\ \exp\left(-\frac{1}{2} \cdot \left[\frac{m - m_0}{\sigma_R}\right]^2\right), & \text{for } \frac{m - m_0}{\sigma_R} \leq \alpha_R \\ A_R \cdot \left(B_R + \frac{m - m_0}{\sigma_R}\right)^{-n_R}, & \text{otherwise} \end{cases}\end{split}\]

where:

\[\begin{split}\begin{align} A_i &= \left(\frac{n_i}{\alpha_i}\right)^{n_i} \cdot \exp\left(-\frac{\alpha_i^2}{2}\right) \\ B_i &= \frac{n_i}{\alpha_i} - \alpha_i \end{align}\end{split}\]
Parameters:
  • m – Observable variable

  • m0 – Peak position (mean)

  • sigma_L – Left-side width parameter (must be > 0)

  • sigma_R – Right-side width parameter (must be > 0)

  • alpha_L – Left-side transition point (must be > 0)

  • alpha_R – Right-side transition point (must be > 0)

  • n_L – Left-side power law exponent (must be > 0)

  • n_R – Right-side power law exponent (must be > 0)

Note

All parameters except m and m0 must be positive. The distribution reduces to a single-sided Crystal Ball when one of the alpha parameters is set to zero.

HS3 Reference

Note: Asymmetric Crystal Ball distribution is not explicitly defined in the current HS3 specification.

Parameters:

data (Any)

Fields

Field

Type

Required

Default

alpha_L

str | float

Yes

alpha_R

str | float

Yes

m

str

Yes

m0

str | float

Yes

n_L

str | float

Yes

n_R

str | float

Yes

name

str

Yes

sigma_L

str | float

Yes

sigma_R

str | float

Yes

type

Literal[‘crystalball_doublesided_dist’]

No

'crystalball_doublesided_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

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)

Evaluate the Crystal Ball distribution.

log_expression(context)

Log-probability combining main likelihood with extended terms.

log_likelihood(context)

Builds a symbolic expression for the double-sided Crystal Ball log-PDF.

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

Analytic antiderivative of the double-sided Crystal Ball.

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.

unconstrained_parameters()

Parameters this distribution scales a positive yield with but does not constrain.

Attributes

constants

Dictionary of PyTensor constants generated from numeric field values.

parameters

Set of parameter names this component depends on.

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

alpha_L

alpha_R

m

m0

n_L

n_R

sigma_R

sigma_L

name

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

AsymmetricCrystalBallDist.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, so Model.log_prob would count it once per event when summing over data. Such terms are assembled once per channel by Model.log_prob, which owns the channel-dataset pairing.

Default: no contribution (returns 1.0 in normal space).

Parameters:
  • context – Mapping of names to pytensor variables

  • data – Optional data tensor for data-dependent terms

  • _context (Context)

  • _data (TensorVar | None)

Returns:

Likelihood contribution (default: 1.0 = no contribution)

Return type:

TensorVar

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

Evaluate the Crystal Ball distribution.

Implements the ROOT RooCrystalBall formula with proper parameter validation. All shape parameters (alpha, n, sigma) are assumed to be positive.

Parameters:

context (Context)

Return type:

TensorVar

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

Parameters:

context (Context) – Mapping of names to pytensor variables

Returns:

Log-probability density

Return type:

TensorVar

AsymmetricCrystalBallDist.log_likelihood(context)[source]

Builds a symbolic expression for the double-sided Crystal Ball log-PDF.

Analytic log form of likelihood(), piecewise over the same four regions (left tail, left core, right core, right tail):

\[\begin{split}\log f(m) = \begin{cases} \log A_L - n_L \log(B_L - t_L), & t_L < -\alpha_L \\ -\frac{1}{2} t_L^2, & -\alpha_L \leq t_L \leq 0 \\ -\frac{1}{2} t_R^2, & 0 < t_L,\ t_R \leq \alpha_R \\ \log A_R - n_R \log(B_R + t_R), & \text{otherwise} \end{cases}\end{split}\]

via _crystalball_log_tail for both tail branches (shared with CrystalBallDist, which uses the same power-law tail form on its single tail). Evaluating this directly (rather than pt.log(self.likelihood(...))) avoids computing each region’s probability-space value and re-logging it, which underflows to 0.0 (and then to -inf) far enough into either tail or core.

Parameters:

context (dict) – Mapping of names to pytensor variables.

Returns:

Symbolic representation of the double-sided Crystal Ball log-PDF.

Return type:

pytensor.tensor.variable.TensorVariable

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

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

AsymmetricCrystalBallDist.normalization_expression(context, observable_name)[source]

Analytic antiderivative of the double-sided Crystal Ball.

The DSCB is only piecewise-smooth (its second derivative is discontinuous at the core/tail junctions), which degrades the single-interval Gauss-Legendre fallback to ~1e-4..1e-3 relative error that shifts with the shape parameters. The antiderivative is exact: Gaussian error functions in the core and closed-form power-law integrals in the tails, with matching constants at the junctions so that F is continuous and F(b) - F(a) is the integral for any bounds. This matches ROOT’s RooCrystalBall::analyticalIntegral.

The n == 1 tails use the logarithmic antiderivative; the power form’s denominator is masked to 1 in that branch so the unused branch stays finite.

Parameters:
Return type:

TensorVar | None

AsymmetricCrystalBallDist.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)
AsymmetricCrystalBallDist.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]
AsymmetricCrystalBallDist.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

AsymmetricCrystalBallDist.unconstrained_parameters()

Parameters this distribution scales a positive yield with but does not constrain.

Such a parameter must be const in the parameter point an analysis uses, or it floats unconstrained. Only HistFactory channels have any (per-bin parameters of bins with zero uncertainty).

Return type:

list[str]

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

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

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

AsymmetricCrystalBallDist.type
AsymmetricCrystalBallDist.alpha_L
AsymmetricCrystalBallDist.alpha_R
AsymmetricCrystalBallDist.m
AsymmetricCrystalBallDist.m0
AsymmetricCrystalBallDist.n_L
AsymmetricCrystalBallDist.n_R
AsymmetricCrystalBallDist.sigma_R
AsymmetricCrystalBallDist.sigma_L
AsymmetricCrystalBallDist.name