pyhs3.Model

class pyhs3.Model(*, context, distributions, functions, progress=True, mode='CVM', observables=None, likelihood=None)[source]

Probabilistic model with compiled tensor operations.

A model represents a specific instantiation of a workspace with concrete parameter values and domain constraints. It builds symbolic computation graphs for distributions and functions, with optional compilation for performance optimization.

The model handles dependency resolution between parameters, functions, and distributions, ensuring proper evaluation order through topological sorting of the computation graph.

Single log-space pipeline. Every distribution node is built exactly once, in log space, as self.log_distributions[name]; the probability-space counterpart self.distributions[name] is always derived as pt.exp(self.log_distributions[name]) rather than built independently, so the two can never disagree on normalization or on their free inputs – pars() is therefore valid for both pdf() and logpdf() by construction.

HFDC constraint storage. For HistFactoryDistChannel distributions, self.log_distributions[name] stores the full per-channel log expression (summed Poisson log-pmf plus summed log-constraints) so that logpdf(name, **params) matches pyhf/cabinetry semantics for callers asking about a single channel’s probability; self.distributions[name] is pt.exp of that. self._hfdc_log_poisson[name] stores only the log-space Poisson term; log_prob uses it to assemble the joint NLL without double-counting constraint factors when multiple channels share a nuisance parameter. Log-space constraint expressions are appended to self._hfdc_log_constraints exactly once per unique dedup key across all channels: single-parameter modifiers (normsys, histosys) are deduped by parameter name using self._hfdc_constraint_params_seen; multi-parameter modifiers (shapesys, staterror) are channel-local by workspace validation and always emitted as-is. log_prob sums self._hfdc_log_constraints directly, so it stays finite where a probability-space constraint would underflow to 0.0.

HS3 Reference

Models are computational representations of HS3 workspaces.

Parameters:
__init__(*, context, distributions, functions, progress=True, mode='CVM', observables=None, likelihood=None)[source]

Represents a probabilistic model composed of parameters, domains, distributions, and functions.

Parameters:
  • context (ParameterContext) – The parameter context: starting values, const parameters (baked into the graph as constants), domain bounds and parameters of interest. Use pyhs3.Workspace.parameter_context() to derive it from an analysis. The bounds are not applied in the graph; they are passed to the minimizer through pyhs3.compiled.CompiledNLL.bounds.

  • distributions (Distributions) – Set of distributions to include.

  • functions (Functions) – Set of functions that compute parameter values.

  • progress (bool) – Whether to show progress bar during dependency graph construction.

  • mode (str) – PyTensor compilation mode. Defaults to “CVM”. Options: “CVM” (apply all rewrites, use C implementations), “FAST_RUN” (all rewrites; with PyTensor’s config.linker “auto” (the default) or “numba” it compiles with Numba, which does not finish compiling large workspaces, and with “cvm” it is “CVM”), “FAST_COMPILE” (few rewrites, Python implementations), “NUMBA” (compile using Numba), “JAX” (compile using JAX), “PYTORCH” (compile using PyTorch), “DebugMode” (debugging), “NanGuardMode” (NaN detection).

  • observables (dict[str, tuple[float, float]] | None) – Dictionary mapping observable names to (lower, upper) bounds.

  • likelihood (Likelihood | None)

Variables:

Methods

__init__(*, context, distributions, functions)

Represents a probabilistic model composed of parameters, domains, distributions, and functions.

compile_nll(*[, gradient, backend, fuse, ...])

Compile the negative log-likelihood for a minimizer.

entity_type(name)

Get the kind of entity a name refers to.

expected_data(**parametervalues)

Expected Poisson mean of every bin of each HistFactory channel.

graph_summary(name)

Get a summary of the computation graph structure.

logpdf(name, **parametervalues)

Evaluates the natural logarithm of the PDF.

logpdf_unsafe(name, **parametervalues)

Evaluates the log PDF with automatic type conversion (convenience method).

pars(name)

Get the ordered list of input parameter names for a distribution.

parsort(name, names)

Similar to numpy's argsort, returns the indices that would sort the parameters.

pdf(name, **parametervalues)

Evaluates the probability density function of the specified distribution.

pdf_unsafe(name, **parametervalues)

Evaluates the PDF with automatic type conversion (convenience method).

sample_data(n, *, rng[, include_auxdata])

Toy datasets: Poisson draws around expected_data(), and optionally auxiliary data.

visualize_graph(name[, fmt, outfile, path, ...])

Visualize the computation graph for a distribution.

Attributes

auxdata

Observed global observables of the constraint terms, keyed by constraint name.

data

Observed data arrays from the workspace, keyed by observable name.

free_params

Non-constant parameter values from the parameter context.

log_prob

Symbolic joint log-probability expression for the full likelihood.

nominal_params

Default parameter values from the parameter context.

observed_data

Observed bin counts of each HistFactory channel, keyed by channel name.

Model.compile_nll(*, gradient=True, backend='c', fuse=False, mode=None, cache=None, batched=False, data_inputs=False, auxdata_inputs=False, fixed=None)[source]

Compile the negative log-likelihood for a minimizer.

Returns a CompiledNLL: -sum(log_prob) and, by default, its gradient, compiled once as a function of a single 1-D vector of the free parameters (ordered as parameter_names). Every const parameter, the observed data unless data_inputs=True, and the auxiliary data unless auxdata_inputs=True, are baked into the compiled function, so each call passes only the free parameters. The result also carries the starting point (free_params), the domain bounds of each parameter, ready for SciPy or iminuit, and the positions of the analysis parameters of interest (poi_indices). Its Hessian (hessian()) is compiled at the first call, with the same backend, mode and cache.

This is the recommended way to evaluate a likelihood repeatedly; see Fit a Model with Optimistix.

Parameters:
  • gradient (bool) – Also compile the gradient with respect to the free parameters. The value and gradient then come from one compiled function.

  • backend (Literal['c', 'jax']) – "c" (default) compiles with PyTensor’s C linker. "jax" transpiles the graph to JAX and compiles it with XLA, which needs the optional JAX dependency (pip install pyhs3[jax]) and enables JAX’s float64 mode (a process-wide JAX setting). On large workspaces it compiles faster than the C backend and evaluates the value and gradient several times faster.

  • fuse (bool) – Keep PyTensor’s elemwise-fusion rewrites (C backend only). Fused kernels evaluate faster but make the first compile of a large workspace several times slower; see default_nll_mode(). Use fuse=True for long fitting campaigns, ideally with cache=True.

  • mode (Mode | str | None) – PyTensor compile mode, replacing the default default_nll_mode(fuse=fuse); e.g. "CVM" (C backend only). Cannot be combined with fuse=True. With mode=None, the C backend uses the mode the model was built with if that is not the default "CVM" and fuse is False; otherwise it uses default_nll_mode(fuse=fuse). The JAX backend ignores the model’s mode.

  • cache (bool | str | PathLike[str] | None) – Cache the compiled function on disk and reuse it when the same likelihood is compiled again with the same options, pyhs3 and PyTensor versions. True uses $XDG_CACHE_HOME/pyhs3 (~/.cache/pyhs3); a path uses that directory; None or False disables caching. The cached file refers to PyTensor’s compiled C modules, so it is only valid on the machine (and PyTensor compile directory) that wrote it. With backend="jax" the cache holds a serialized jax.export module, whose loading skips the PyTensor-to-JAX transpilation, and JAX’s persistent compilation cache in its xla subdirectory holds the XLA executable. JAX’s cache directory is a process-wide setting: pyhs3 sets jax_compilation_cache_dir only if it is unset, so a directory you configured yourself is kept.

  • batched (bool) – Evaluate many parameter vectors per call (backend="jax" only). Returns a BatchedCompiledNLL, whose methods take a (K, P) array with one parameter vector per row and return values (K,) and gradients (K, P); XLA compiles once per batch size K, at the first call with that size.

  • data_inputs (bool) – Make the binned observed counts of the HistFactory channels inputs of the compiled function instead of constants, so that one compiled likelihood evaluates on other datasets (toys, Asimov data) without recompiling: its value, grad and value_and_grad then take a data mapping keyed and shaped like observed_data, which is the default. The data of channels that are not HistFactory channels (unbinned data) stay baked in, and so do the constraint centres (auxiliary data) unless auxdata_inputs=True. Off by default, since data-dependent terms such as log(n!) are then computed on each call instead of folded once at compile time.

  • auxdata_inputs (bool) – Make the global observables of the constraint terms (auxdata) inputs of the compiled function instead of constants, so that one compiled likelihood evaluates on toys that randomize them: the data mapping then also takes them, keyed and shaped like auxdata, which is the default. With data_inputs=True as well, one mapping holds the observed counts and the auxiliary data, as sample_data(include_auxdata=True) returns them. Constraint terms with no entry in auxdata stay baked in. A separate flag from data_inputs, so that a likelihood compiled for swapped counts alone keeps folding its constraint terms at compile time, and its data keeps one key per channel.

  • fixed (Mapping[str, float] | None) – Free parameters to hold at the given values, keyed by name, e.g. {"mu": 0.0} for a fixed-POI or profile fit. Each is baked into the compiled function like a const parameter, without rebuilding the model, and left out of parameter_names, the starting point and the bounds. A fixed parameter of interest is left out of parameters_of_interest and poi_indices, as a const one is. A value outside the parameter’s domain warns, as for const. Each distinct set of values compiles anew.

Returns:

The compiled likelihood.

Return type:

CompiledNLL

Raises:
  • RuntimeError – If the model was built without a likelihood.

  • ValueError – If a free parameter has no starting value in the parameter set (the message lists every such name). Also if a free parameter is batched (kind=pt.vector); the parameter vector has one entry per scalar parameter. Also for an unknown backend, for fuse=True combined with mode=, for fuse/mode with backend="jax", and for batched=True without backend="jax", for data_inputs=True when the likelihood has no binned HistFactory channel, and for auxdata_inputs=True when it has no auxiliary data. Also if fixed names a const parameter, or a name that is not a free parameter of the likelihood.

  • ImportError – If backend="jax" and JAX is not installed.

Model.entity_type(name)[source]

Get the kind of entity a name refers to.

Parameters:

name (str) – Name of a distribution, function, parameter, constant, or HistFactory modifier in the model.

Returns:

One of "distribution", "function", "parameter", "constant", or "modifier".

Return type:

EntityType

Raises:

ValueError – If the model has no entity with this name.

Examples

>>> import pyhs3
>>> ws = pyhs3.Workspace(
...     metadata={"hs3_version": "0.2"},
...     distributions=[
...         {
...             "name": "gauss",
...             "type": "gaussian_dist",
...             "x": "x",
...             "mean": "mu",
...             "sigma": 1.0,
...         }
...     ],
...     parameter_points=[
...         {
...             "name": "default_values",
...             "parameters": [
...                 {"name": "x", "value": 0.0},
...                 {"name": "mu", "value": 0.0},
...             ],
...         }
...     ],
... )
>>> model = ws.model(0, progress=False)
>>> model.entity_type("gauss")
'distribution'
>>> model.entity_type("mu")
'parameter'
Model.expected_data(**parametervalues)[source]

Expected Poisson mean of every bin of each HistFactory channel.

These are the rates the main Poisson terms of log_prob compare the observed bin counts with, evaluated at the given parameter values: the Asimov data of the main measurement. Every const parameter is baked in at its parameter-set value.

The result covers only the main measurement. It holds no auxiliary data (the Asimov values of the constraint terms’ global observables, see auxdata). Channels other than HistFactory channels have no expected bin counts and are left out.

The first call compiles one function for all channels, which later calls reuse.

Parameters:

**parametervalues (float | ndarray[tuple[Any, ...], dtype[float64]]) – Scalar value of each free parameter, keyed by name. Names the channels do not depend on are ignored, so a full parameter point, such as free_params or dict(zip(nll.parameter_names, x)) for a CompiledNLL nll, can be passed as is.

Returns:

For each HistFactory channel built in the model, keyed by distribution name in the order of the workspace’s distributions, a float64 array of shape (B,), B the channel’s total number of bins.

Return type:

dict[str, numpy.ndarray]

Raises:

ValueError – If the model has no HistFactory channel, or if a free parameter a channel depends on has no value (the message lists every such name).

Examples

>>> import pyhs3
>>> ws = pyhs3.from_hifa(
...     {
...         "channels": [
...             {
...                 "name": "SR",
...                 "samples": [
...                     {
...                         "name": "signal",
...                         "data": [5.0, 10.0],
...                         "modifiers": [
...                             {"name": "mu", "type": "normfactor", "data": None}
...                         ],
...                     },
...                     {"name": "background", "data": [50.0, 60.0], "modifiers": []},
...                 ],
...             }
...         ],
...         "observations": [{"name": "SR", "data": [52.0, 75.0]}],
...         "measurements": [{"name": "meas", "config": {"poi": "mu", "parameters": []}}],
...         "version": "1.0.0",
...     }
... )
>>> model = ws.model(ws.analyses["meas"], progress=False)
>>> model.expected_data(mu=2.0)["model_SR"]  # shape (2,): one mean per bin
array([60., 80.])
Model.graph_summary(name)[source]

Get a summary of the computation graph structure.

Parameters:

name (str) – Distribution name.

Returns:

Summary of the graph structure.

Return type:

str

Model.logpdf(name, **parametervalues)[source]

Evaluates the natural logarithm of the PDF.

This method requires all parameter values to be numpy arrays with dtype float64. For automatic type conversion, use logpdf_unsafe() instead.

The logarithm is evaluated in log space via a compiled log-PDF function (log(prod(exp(...))) stays collapsed), so the result remains finite for HistFactory channels where the probability-space pdf underflows to 0.0.

Parameters:
Returns:

The log of the PDF.

Return type:

npt.NDArray[np.float64]

Raises:
  • TypeError – If any parameter value is not a numpy array of the compiled input’s dtype (float64).

  • ValueError – If an array’s dimensionality differs from its compiled input’s (e.g. a vector passed for a scalar parameter).

See also

logpdf_unsafe(): Convenience version with automatic type conversion pdf(): PDF with strict type checking

Example

>>> import numpy as np
>>> model.logpdf("gauss", x=np.array(1.5), mu=np.array(0.0), sigma=np.array(1.0))
Model.logpdf_unsafe(name, **parametervalues)[source]

Evaluates the log PDF with automatic type conversion (convenience method).

This method automatically converts parameter values to numpy arrays before evaluation and, unlike logpdf(), does not check that each array has the dimensionality of its compiled input. An array passed for a scalar parameter is then not rejected: the default C backend reads only its first element. Use this for convenience in testing or interactive use.

Parameters:
Returns:

The log of the PDF.

Return type:

npt.NDArray[np.float64]

See also

logpdf(): Type-safe version requiring numpy arrays pdf_unsafe(): PDF with automatic type conversion

Example

>>> model.logpdf_unsafe("gauss", x=1.5, mu=0.0, sigma=1.0)  # floats ok
Model.pars(name)[source]

Get the ordered list of input parameter names for a distribution.

This method returns the parameter names in the exact order expected by the compiled PDF function. Since the probability- and log-space expressions for a distribution share identical free inputs by construction (pdf() evaluates pt.exp() of exactly what logpdf() evaluates), this same ordering is valid for both pdf() and logpdf().

Parameters:

name (str) – Distribution name

Return type:

list[str]

Returns:

List of parameter names in the order expected by pdf() and logpdf()

Example

>>> model.pars("model_singlechannel")
['uncorr_bkguncrt_1', 'uncorr_bkguncrt_0', 'model_singlechannel_observed', 'mu', 'Lumi']
Model.parsort(name, names)[source]

Similar to numpy’s argsort, returns the indices that would sort the parameters.

Parameters:
  • name (str) – Distribution name

  • names (list[str]) – Parameter names to sort

Return type:

list[int]

Returns:

List of indices that would sort the parameters

Example

>>> model.parsort("model_singlechannel", ["mu", "Lumi", "uncorr_bkguncrt_0", "uncorr_bkguncrt_1", "model_singlechannel_observed"])
[3, 2, 4, 0, 1]
Model.pdf(name, **parametervalues)[source]

Evaluates the probability density function of the specified distribution.

This method requires all parameter values to be numpy arrays with dtype float64. For automatic type conversion, use pdf_unsafe() instead.

Parameters:
Returns:

The evaluated PDF value.

Return type:

npt.NDArray[np.float64]

Raises:
  • TypeError – If any parameter value is not a numpy array of the compiled input’s dtype (float64).

  • ValueError – If an array’s dimensionality differs from its compiled input’s (e.g. a vector passed for a scalar parameter).

See also

pdf_unsafe(): Convenience version with automatic type conversion logpdf(): Log PDF with strict type checking

Example

>>> import numpy as np
>>> model.pdf("gauss", x=np.array(1.5), mu=np.array(0.0), sigma=np.array(1.0))
Model.pdf_unsafe(name, **parametervalues)[source]

Evaluates the PDF with automatic type conversion (convenience method).

This method automatically converts parameter values to numpy arrays before evaluation and, unlike pdf(), does not check that each array has the dimensionality of its compiled input. An array passed for a scalar parameter is then not rejected: the default C backend reads only its first element. Use this for convenience in testing or interactive use.

Parameters:
Returns:

The evaluated PDF value.

Return type:

npt.NDArray[np.float64]

See also

pdf(): Type-safe version requiring numpy arrays logpdf_unsafe(): Log PDF with automatic type conversion

Example

>>> model.pdf_unsafe("gauss", x=1.5, mu=0.0, sigma=1.0)  # floats ok
>>> model.pdf_unsafe("gauss", x=[1.5], mu=0.0, sigma=1.0)  # lists ok
Model.sample_data(n, *, rng, include_auxdata=False, **parametervalues)[source]

Toy datasets: Poisson draws around expected_data(), and optionally auxiliary data.

Each bin of each HistFactory channel is drawn independently from a Poisson distribution whose mean is the bin’s expected_data() at the given parameter values. Row i of every array together is one toy dataset, keyed like observed_data, so it can be passed as the data of a likelihood compiled with compile_nll(data_inputs=True):

nll.value(x, data={name: counts[i] for name, counts in toys.items()})

By default only the main measurement is randomized, and the auxiliary data (the global observables of the constraint terms) stay at their observed values: toys conditional on the observed auxiliary data, whose test statistic distribution leaves out the fluctuations of the auxiliary measurements. With include_auxdata=True, each global observable of auxdata is also drawn from its constraint distribution at the given parameter values, as pyhf’s make_pdf(pars).sample does: Gauss(alpha, 1) for a Gauss single-parameter constraint, Poisson(gamma * tau) for a Poisson per-bin one, and so on. These fully frequentist toys feed a likelihood compiled with compile_nll(data_inputs=True, auxdata_inputs=True). The counts are drawn first, so a full toy has the counts of a main-measurement toy drawn with the same seed.

Parameters:
  • n (int) – Number of toy datasets.

  • rng (Generator) – Source of the random draws; the draws advance its state. Seed it, e.g. numpy.random.default_rng(0), for reproducible toys.

  • include_auxdata (bool) – Also draw the auxiliary data.

  • **parametervalues (float | ndarray[tuple[Any, ...], dtype[float64]]) – Scalar value of each free parameter, as for expected_data().

Returns:

For each HistFactory channel, keyed as expected_data(), a float64 array of whole-number counts of shape (n, B), B the channel’s total number of bins. With include_auxdata=True, also a float64 array per entry of auxdata, keyed alike, of shape (n,) for a scalar global observable and (n, B') for a per-bin one.

Return type:

dict[str, numpy.ndarray]

Raises:
  • ValueError – As for expected_data(), or if an expected bin count is negative or NaN, which no Poisson distribution has as its mean. With include_auxdata=True, also if a constraint distribution’s parameters are not finite or outside its domain (a negative Poisson rate, say).

  • NotImplementedError – With include_auxdata=True, if a constraint term of the likelihood has no global observable pyhs3 can draw: a distribution other than a Gaussian, Poisson or log-normal one, or one whose global observable is not a constant (a number or const parameter), or is held by another term. The message names every such term.

Examples

For the model of expected_data(), three toys at mu = 2:

>>> import numpy as np
>>> import pyhs3
>>> ws = pyhs3.from_hifa(
...     {
...         "channels": [
...             {
...                 "name": "SR",
...                 "samples": [
...                     {
...                         "name": "signal",
...                         "data": [5.0, 10.0],
...                         "modifiers": [
...                             {"name": "mu", "type": "normfactor", "data": None}
...                         ],
...                     },
...                     {"name": "background", "data": [50.0, 60.0], "modifiers": []},
...                 ],
...             }
...         ],
...         "observations": [{"name": "SR", "data": [52.0, 75.0]}],
...         "measurements": [{"name": "meas", "config": {"poi": "mu", "parameters": []}}],
...         "version": "1.0.0",
...     }
... )
>>> model = ws.model(ws.analyses["meas"], progress=False)
>>> toys = model.sample_data(3, rng=np.random.default_rng(0), mu=2.0)
>>> toys["model_SR"].shape  # (n, B): 3 toys of 2 bins
(3, 2)
Model.visualize_graph(name, fmt='svg', outfile=None, path=None, *, op_params=mappingproxy({'ExpandDims': 'elide', 'DimShuffle': 'elide'}), show_id=False, show_dtype=False, show_shape=False, const_arrays='elide', const_array_threshold=8)[source]

Visualize the computation graph for a distribution.

The defaults favor a figure that’s readable at a glance over one that exposes every implementation detail: dtype/shape annotations and toposort-index ids are hidden, single-input broadcasting plumbing ops (ExpandDims, DimShuffle) are spliced out of the drawing, and constant arrays larger than const_array_threshold collapse to a const[shape] placeholder. Pass the corresponding kwarg to bring any of that detail back.

Parameters:
  • name (str) – Distribution name.

  • fmt (str) – Output format (‘svg’, ‘png’, ‘pdf’). Defaults to ‘svg’.

  • outfile (str | None) – Output filename. If None, uses ‘{name}_graph.{fmt}’.

  • path (str | None) – Directory path for output. If None, uses current working directory.

  • op_params (Literal['orig', 'elide', 'none'] | Mapping[str, Literal['orig', 'elide', 'none']]) – Per-op-name display mode, or one mode applied to every op. "orig" keeps the op’s full label (e.g. Sum{axis=0}); "none" drops the parameter block (Sum); "elide" removes the node from the drawing entirely, rewiring its consumers to its own (sole) input - only sound for single-input ops. Op names absent from a mapping default to "orig". Defaults to eliding ExpandDims/DimShuffle only.

  • show_id (bool) – Append each op’s toposort index to its label (e.g. Add id=9). Defaults to False.

  • show_dtype (bool) – Keep the dtype portion of PyTensor’s type annotations (e.g. Matrix(float32)). Defaults to False.

  • show_shape (bool) – Keep the shape portion of PyTensor’s type annotations (e.g. Matrix(shape=(1, 1))). Defaults to False.

  • const_arrays (Literal['orig', 'truncate', 'elide']) – How to render constant arrays larger than const_array_threshold elements. "orig" leaves pydotprint’s own (possibly mid-token-truncated) value dump untouched; "truncate" shows a deliberate [v0, v1, v2, ...] (shape) preview; "elide" collapses it to const[shape]. Defaults to "elide".

  • const_array_threshold (int) – Element count above which const_arrays applies. Defaults to 8.

Returns:

Path to the generated visualization file.

Return type:

str

Raises:

ImportError – If pydot is not installed.

Model.auxdata

Observed global observables of the constraint terms, keyed by constraint name.

Each constraint term of the likelihood measures its parameters through a global observable (auxiliary datum), a constant of log_prob:

  • a HistFactory modifier’s constraint, keyed constraint_{modifier} (constraint_bblite_{channel} for a channel’s Barlow-Beeston-lite staterror group): 0 for a Gauss and 1 for a Poisson or LogNormal single-parameter constraint (normsys, histosys), of shape (); for a per-bin constraint (shapesys, staterror) an array of shape (B',), B' the number of constrained bins, of tau = 1 / sigma_rel**2 (Poisson) or 1 (Gauss, LogNormal). A name a workspace distribution or an earlier constraint already has gets a suffix _1, _2, …

  • an auxiliary distribution of the likelihood, or a constraint factor of a ProductDist channel, keyed by its name: its x, if that is a number or a const parameter, else, for a Gaussian, its mean (ROOT writes Gauss(alpha | nom_alpha, 1)), of shape (). Terms with neither, or of another distribution type than Gaussian, Poisson or log-normal, have no entry.

These are the values log_prob bakes in, the default auxiliary data of a likelihood compiled with compile_nll(auxdata_inputs=True), and what sample_data(include_auxdata=True) draws. The arrays are float64 copies, in the order the terms enter log_prob.

Raises:

RuntimeError – If the model was built without a likelihood.

Model.data

Observed data arrays from the workspace, keyed by observable name.

Only available when the model was built via ws.model(analysis) or ws.model(likelihood). Raises RuntimeError otherwise.

Returns a dict suitable for passing directly to a compiled or JAX function alongside free_params:

jg = pyhs3.jaxify(model.log_prob)
jg(**model.data, **model.free_params)
Model.free_params

Non-constant parameter values from the parameter context.

Like nominal_params but excludes parameters whose ParameterPoint.const flag is True and observables (whose values come from data). These are the parameters that remain as free symbolic inputs after model construction, making this dict the correct one to pass to a jaxified callable:

jg = pyhs3.jaxify(model.log_prob)
jg(**model.data, **model.free_params)
Model.log_prob[source]

Symbolic joint log-probability expression for the full likelihood.

A 0-d PyTensor TensorVar when every parameter is a scalar, and a 1-D one of shape (M,) when parameters are batched over M points (e.g. a profile scan with a pt.vector parameter; see Broadcasting with Vector Parameters). Observable data and parameters listed in free_params are symbolic free inputs; parameters with const=True are baked as compile-time constants and do not appear as free inputs. The expression is suitable for JAX transpilation, gradient computation, or direct PyTensor compilation.

Normalization denominators are fixed constants (axis bounds baked at Model construction time). For unweighted data, the same compiled/JAX function can be evaluated against different event arrays. Weighted UnbinnedData entries bake the weights as constants at construction time; to use different weights, a new Model must be built.

The workspace defaults for evaluation are available via data and free_params.

Only available when the model was built via ws.model(analysis) or ws.model(likelihood). Raises RuntimeError otherwise.

Example:

model = ws.model(ws.analyses["CombinedPdf_combData"])
nll = -2 * model.log_prob
jg = pyhs3.jaxify(nll)
val = jg(**model.data, **model.free_params)
Model.nominal_params

Default parameter values from the parameter context.

Returns all parameters, including those marked const=True (which are baked as pytensor.tensor.constant in the symbolic graph and are therefore not free inputs to a jaxified expression).

Use free_params when passing parameters to a jaxified callable to avoid supplying spurious keyword arguments.

Model.observed_data

Observed bin counts of each HistFactory channel, keyed by channel name.

Unlike data, which holds unbinned events keyed by observable, this holds the binned data each HistFactory channel of the likelihood is paired with: for each channel, keyed by distribution name in the order of the workspace’s distributions, a float64 array of shape (B,), B the channel’s total number of bins. These are the counts log_prob bakes in as constants, and the default data of a likelihood compiled with compile_nll(data_inputs=True), whose data argument takes a mapping of the same keys and shapes. The arrays are copies. The mapping is empty if the likelihood has no binned channel.

Raises:

RuntimeError – If the model was built without a likelihood.