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 counterpartself.distributions[name]is always derived aspt.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 bothpdf()andlogpdf()by construction.HFDC constraint storage. For
HistFactoryDistChanneldistributions,self.log_distributions[name]stores the full per-channel log expression (summed Poisson log-pmf plus summed log-constraints) so thatlogpdf(name, **params)matches pyhf/cabinetry semantics for callers asking about a single channel’s probability;self.distributions[name]ispt.expof that.self._hfdc_log_poisson[name]stores only the log-space Poisson term;log_probuses it to assemble the joint NLL without double-counting constraint factors when multiple channels share a nuisance parameter. Log-space constraint expressions are appended toself._hfdc_log_constraintsexactly once per unique dedup key across all channels: single-parameter modifiers (normsys,histosys) are deduped by parameter name usingself._hfdc_constraint_params_seen; multi-parameter modifiers (shapesys,staterror) are channel-local by workspace validation and always emitted as-is.log_probsumsself._hfdc_log_constraintsdirectly, so it stays finite where a probability-space constraint would underflow to 0.0.HS3 Reference
Models are computational representations of HS3 workspaces.
- Parameters:
context (
ParameterContext)distributions (
Distributions)functions (
Functions)progress (
bool)mode (
str)likelihood (
Likelihood|None)
- __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,
constparameters (baked into the graph as constants), domain bounds and parameters of interest. Usepyhs3.Workspace.parameter_context()to derive it from an analysis. The bounds are not applied in the graph; they are passed to the minimizer throughpyhs3.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:
context (ParameterContext) – The parameter context the model was built from.
distributions (dict[str, pytensor.tensor.variable.TensorVariable]) – Symbolic distribution expressions.
parameters (dict[str, pytensor.tensor.variable.TensorVariable]) – Symbolic parameter variables.
functions (dict[str, pytensor.tensor.variable.TensorVariable]) – Computed function values.
modifiers (dict[str, pytensor.tensor.variable.TensorVariable]) – HistFactory modifier terms (normalization factors, shape systematics, and similar) discovered while building the graph.
log_distributions (dict[str, pytensor.tensor.variable.TensorVariable]) – Log-space expression for each distribution, keyed by name; what
logpdf()/logpdf_unsafe()evaluate.mode (str) – PyTensor compilation mode.
_compiled_functions (dict[str, Callable[..., npt.NDArray[np.float64]]]) – Cache of compiled PyTensor functions.
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
Observed global observables of the constraint terms, keyed by constraint name.
Observed data arrays from the workspace, keyed by observable name.
Non-constant parameter values from the parameter context.
Symbolic joint log-probability expression for the full likelihood.
Default parameter values from the parameter context.
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 asparameter_names). Everyconstparameter, the observed data unlessdata_inputs=True, and the auxiliary data unlessauxdata_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; seedefault_nll_mode(). Usefuse=Truefor long fitting campaigns, ideally withcache=True.mode (
Mode|str|None) – PyTensor compile mode, replacing the defaultdefault_nll_mode(fuse=fuse); e.g."CVM"(C backend only). Cannot be combined withfuse=True. Withmode=None, the C backend uses themodethe model was built with if that is not the default"CVM"andfuseisFalse; otherwise it usesdefault_nll_mode(fuse=fuse). The JAX backend ignores the model’smode.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.Trueuses$XDG_CACHE_HOME/pyhs3(~/.cache/pyhs3); a path uses that directory;NoneorFalsedisables 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. Withbackend="jax"the cache holds a serializedjax.exportmodule, whose loading skips the PyTensor-to-JAX transpilation, and JAX’s persistent compilation cache in itsxlasubdirectory holds the XLA executable. JAX’s cache directory is a process-wide setting: pyhs3 setsjax_compilation_cache_dironly if it is unset, so a directory you configured yourself is kept.batched (
bool) – Evaluate many parameter vectors per call (backend="jax"only). Returns aBatchedCompiledNLL, 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 sizeK, 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: itsvalue,gradandvalue_and_gradthen take adatamapping keyed and shaped likeobserved_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) unlessauxdata_inputs=True. Off by default, since data-dependent terms such aslog(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: thedatamapping then also takes them, keyed and shaped likeauxdata, which is the default. Withdata_inputs=Trueas well, one mapping holds the observed counts and the auxiliary data, assample_data(include_auxdata=True)returns them. Constraint terms with no entry inauxdatastay baked in. A separate flag fromdata_inputs, so that a likelihood compiled for swapped counts alone keeps folding its constraint terms at compile time, and itsdatakeeps 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 aconstparameter, without rebuilding the model, and left out ofparameter_names, the starting point and the bounds. A fixed parameter of interest is left out ofparameters_of_interestandpoi_indices, as aconstone is. A value outside the parameter’s domain warns, as forconst. Each distinct set of values compiles anew.
- Returns:
The compiled likelihood.
- Return type:
- 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, forfuse=Truecombined withmode=, forfuse/modewithbackend="jax", and forbatched=Truewithoutbackend="jax", fordata_inputs=Truewhen the likelihood has no binned HistFactory channel, and forauxdata_inputs=Truewhen it has no auxiliary data. Also iffixednames aconstparameter, 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:
- 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_probcompare the observed bin counts with, evaluated at the given parameter values: the Asimov data of the main measurement. Everyconstparameter 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 asfree_paramsordict(zip(nll.parameter_names, x))for aCompiledNLLnll, 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,),Bthe channel’s total number of bins.- Return type:
- 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.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-spacepdfunderflows to0.0.- Parameters:
- Returns:
The log of the PDF.
- Return type:
- 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 conversionpdf(): PDF with strict type checkingExample
>>> 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:
See also
logpdf(): Type-safe version requiring numpy arrayspdf_unsafe(): PDF with automatic type conversionExample
>>> 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()evaluatespt.exp()of exactly whatlogpdf()evaluates), this same ordering is valid for bothpdf()andlogpdf().- Parameters:
name (
str) – Distribution name- Return type:
- 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:
- Return type:
- 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:
- 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 conversionlogpdf(): Log PDF with strict type checkingExample
>>> 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:
See also
pdf(): Type-safe version requiring numpy arrayslogpdf_unsafe(): Log PDF with automatic type conversionExample
>>> 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. Rowiof every array together is one toy dataset, keyed likeobserved_data, so it can be passed as thedataof a likelihood compiled withcompile_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 ofauxdatais also drawn from its constraint distribution at the given parameter values, as pyhf’smake_pdf(pars).sampledoes: Gauss(alpha, 1) for aGausssingle-parameter constraint, Poisson(gamma * tau) for aPoissonper-bin one, and so on. These fully frequentist toys feed a likelihood compiled withcompile_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 forexpected_data().
- Returns:
For each HistFactory channel, keyed as
expected_data(), a float64 array of whole-number counts of shape(n, B),Bthe channel’s total number of bins. Withinclude_auxdata=True, also a float64 array per entry ofauxdata, keyed alike, of shape(n,)for a scalar global observable and(n, B')for a per-bin one.- Return type:
- Raises:
ValueError – As for
expected_data(), or if an expected bin count is negative or NaN, which no Poisson distribution has as its mean. Withinclude_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 orconstparameter), or is held by another term. The message names every such term.
Examples
For the model of
expected_data(), three toys atmu = 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 thanconst_array_thresholdcollapse to aconst[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 elidingExpandDims/DimShuffleonly.show_id (
bool) – Append each op’s toposort index to its label (e.g.Add id=9). Defaults toFalse.show_dtype (
bool) – Keep the dtype portion of PyTensor’s type annotations (e.g.Matrix(float32)). Defaults toFalse.show_shape (
bool) – Keep the shape portion of PyTensor’s type annotations (e.g.Matrix(shape=(1, 1))). Defaults toFalse.const_arrays (
Literal['orig','truncate','elide']) – How to render constant arrays larger thanconst_array_thresholdelements."orig"leaves pydotprint’s own (possibly mid-token-truncated) value dump untouched;"truncate"shows a deliberate[v0, v1, v2, ...] (shape)preview;"elide"collapses it toconst[shape]. Defaults to"elide".const_array_threshold (
int) – Element count above whichconst_arraysapplies. Defaults to 8.
- Returns:
Path to the generated visualization file.
- Return type:
- 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-litestaterrorgroup): 0 for aGaussand 1 for aPoissonorLogNormalsingle-parameter constraint (normsys,histosys), of shape(); for a per-bin constraint (shapesys,staterror) an array of shape(B',),B'the number of constrained bins, oftau = 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
ProductDistchannel, keyed by its name: itsx, if that is a number or aconstparameter, else, for a Gaussian, itsmean(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_probbakes in, the default auxiliary data of a likelihood compiled withcompile_nll(auxdata_inputs=True), and whatsample_data(include_auxdata=True)draws. The arrays are float64 copies, in the order the terms enterlog_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)orws.model(likelihood). RaisesRuntimeErrorotherwise.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_paramsbut excludes parameters whoseParameterPoint.constflag isTrueand observables (whose values come fromdata). 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
TensorVarwhen every parameter is a scalar, and a 1-D one of shape(M,)when parameters are batched overMpoints (e.g. a profile scan with apt.vectorparameter; see Broadcasting with Vector Parameters). Observable data and parameters listed infree_paramsare symbolic free inputs; parameters withconst=Trueare 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
Modelconstruction time). For unweighted data, the same compiled/JAX function can be evaluated against different event arrays. WeightedUnbinnedDataentries bake the weights as constants at construction time; to use different weights, a newModelmust be built.The workspace defaults for evaluation are available via
dataandfree_params.Only available when the model was built via
ws.model(analysis)orws.model(likelihood). RaisesRuntimeErrorotherwise.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 aspytensor.tensor.constantin the symbolic graph and are therefore not free inputs to a jaxified expression).Use
free_paramswhen 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,),Bthe channel’s total number of bins. These are the countslog_probbakes in as constants, and the defaultdataof a likelihood compiled withcompile_nll(data_inputs=True), whosedataargument 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.