Architecture Overview¶
This guide gives contributors a map of the pyhs3 codebase: what each part is responsible for and where to look for it. It deliberately stays at the level of modules and concepts. For the individual classes, parameters and supported types, see Python API, which is generated from the docstrings and so stays current.
Project Goals¶
pyhs3 is a pure-Python implementation of the HS3 (HEP Statistics Serialization Standard) specification that:
Deserializes HS3 JSON to Python objects
Builds computational graphs using PyTensor for automatic differentiation
Evaluates statistical models efficiently with tensor operations
Supports complex statistical models from particle physics (e.g., HistFactory)
Core Concepts¶
The architecture follows the HS3 specification structure.
Workspace¶
The Workspace (src/pyhs3/workspace.py) is the top-level container that
holds all components of a statistical analysis: metadata, distributions,
functions, domains, parameter points, data, likelihoods and analyses. Each
component kind has its own module or package under src/pyhs3/ (for example
domains.py, parameter_points.py, data.py, likelihoods.py,
analyses.py).
Model¶
The Model (src/pyhs3/model.py) is built from a Workspace for a
given analysis or likelihood and holds the PyTensor graph of the model. It
evaluates individual distributions, builds the joint log-probability of a
likelihood, and compiles the negative log-likelihood for minimizers
(src/pyhs3/compiled.py).
Distributions¶
Distributions represent probability densities. The abstract base classes live
in src/pyhs3/distributions/core.py; concrete types are grouped by theme in
the other modules of src/pyhs3/distributions/, with HistFactory in its own
subpackage. Defining Custom Functions and Distributions describes the methods a distribution
implements and how they combine into the main and extended likelihood terms.
Functions¶
Functions provide parameterized transformations and calculations. The base
classes live in src/pyhs3/functions/core.py and the concrete types in the
other modules of src/pyhs3/functions/.
Project Structure¶
pyhs3/
├── src/pyhs3/ # Source code; one module or package per HS3 component
│ ├── distributions/
│ ├── functions/
│ ├── hifa/ # pyhf (HiFa) JSON conversion
│ ├── cli/ # The pyhs3 command-line interface
│ └── typing/ # Shared type aliases
├── tests/ # Test suite and test workspaces
├── docs/ # This documentation (Sphinx)
├── pyproject.toml # Package metadata, dependencies, tool configuration
└── pixi.toml # Development environments and tasks
The dependencies are declared in pyproject.toml; Development Workflow
describes the development environments.
Data Flow¶
The typical flow through pyhs3:
Deserialization
import pyhs3 # HS3 JSON → Pydantic models ws = pyhs3.Workspace(**json_data)
Validation
Pydantic validates structure and types
Custom validators check constraints
References between components are resolved
Graph Construction
# Build the computational graph for an analysis model = ws.model(ws.analyses["my_analysis"])
Components are linked through a dependency graph
Distributions and functions are converted to PyTensor ops in dependency order
Evaluation
# Evaluate one distribution result = model.logpdf("dist_name", **parameters) # Or compile the negative log-likelihood for a minimizer nll = model.compile_nll()
PyTensor compiles optimized computation
Automatic differentiation available
Batch evaluation supported via broadcasting
How pyhs3 Builds a Model explains these steps from the user’s side.
Computational Graph¶
Graph Construction¶
src/pyhs3/networks.py and Model._build_dependency_graph in
src/pyhs3/model.py build the graph:
Collect all components (distributions, functions, parameters)
Build a dependency graph with rustworkx
Group instances of batchable types into families (see Building many functions or distributions of one type as a family)
Topologically sort to determine evaluation order, keeping only the nodes the likelihood needs when the model has one
Convert each node to PyTensor ops in that order
Compile for efficient evaluation
The docstrings of these functions describe the invariants each step relies on.
Expression Parsing¶
src/pyhs3/generic_parse.py turns the expression strings of generic
functions and distributions into PyTensor ops. This allows users to specify
custom mathematical expressions in HS3 JSON.
HistFactory Support¶
HistFactory is a major use case, with dedicated support in
src/pyhs3/distributions/histfactory/: the channel distribution, its
samples, the modifiers and their interpolation codes.
Modifier Naming in Dependency Graph:
Modifiers themselves have simple names (e.g., "lumi"), but when incorporated into the dependency graph by histfactory_dist, they are given unique identifiers by prepending the full context path. This design distinguishes individual modifier instances while allowing parameters to indicate correlation:
Modifier names in JSON/specification: Simple names like
"lumi"Internal graph node names: Full path like
"{dist_name}/{sample_name}/{modifier_type}/{modifier_name}"Parameter names: Indicate correlation - modifiers sharing the same parameter name are correlated
# Example: Two modifiers with the same name "lumi" in different samples
{
"name": "lumi", # Simple modifier name
"parameter": "lumi", # Shared parameter = correlated
"type": "normsys",
# ...
}
# Internally becomes node: "SR/signal/normsys/lumi" in the dependency graph
{
"name": "lumi", # Same modifier name (different sample)
"parameter": "lumi", # Same parameter = correlated
"type": "normsys",
# ...
}
# Internally becomes node: "CR/background/normsys/lumi" in the dependency graph
This design allows:
Each modifier instance to be uniquely identified in the dependency graph
Correlations to be expressed naturally through shared parameter names
Clear separation between modifier identity and parameter correlation structure
Error Handling¶
pyhs3’s exceptions live in src/pyhs3/exceptions.py and all derive from
HS3Exception, so callers can catch every pyhs3 error with one except.
Extension Points¶
To extend pyhs3:
Adding New Distributions¶
Create class inheriting from
Distributionin appropriate fileImplement the
likelihood()method (required)Optionally override
extended_likelihood()for constraint/extended termsAdd to distribution registry dictionary
Write unit tests
Update documentation
Example skeleton:
>>> from __future__ import annotations
>>> from typing import Literal, cast
>>> import pytensor.tensor as pt
>>> from pyhs3.distributions.core import Distribution
>>> from pyhs3.context import Context
>>> from pyhs3.typing.aliases import TensorVar
>>>
>>> class MyDistribution(Distribution):
... """My custom distribution."""
... type: Literal["my_dist"] = "my_dist"
... param1: str | float # Parameter name or numeric value
... param2: str | float # Parameter name or numeric value
... def likelihood(self, context: Context) -> TensorVar:
... """Main probability model implementation."""
... # Get processed parameters from context
... p1 = context[self._parameters["param1"]]
... p2 = context[self._parameters["param2"]]
... # Implement your PDF/PMF here
... # Example: return some_probability_expression
... return cast(TensorVar, pt.constant(1.0)) # Replace with actual implementation
...
Adding New Functions¶
Create class inheriting from
Function, or fromBatchableFunctionif many instances can be evaluated together (see Defining Custom Functions and Distributions)Implement the
_expressionmethod (andbatch_expressionsfor a batchable type)Add the class to its module’s
functionsregistry. Workspaces look each entry’stypeup inregistered_functionsinsrc/pyhs3/functions/__init__.py, which merges only the modules it imports, so for a new module also import it there and merge itsfunctionsintoregistered_functionsWrite unit tests
Update documentation
Broadcasting¶
See Broadcasting with Vector Parameters for details on batch dimension handling.
Testing Strategy¶
See Testing Guide for comprehensive testing guide.
Test Categories¶
Unit tests: Individual component testing
Integration tests: Component interaction testing
End-to-end tests: Real-world workspace loading and evaluation
Doctests: Documentation examples validation
Performance Considerations¶
Compile time grows with the size of the PyTensor graph, so the first evaluation of a large model is dominated by compilation
Evaluate many points at once through broadcasting rather than in a Python loop (see Broadcasting with Vector Parameters)
Building many functions or distributions of one type as a family and Duplicate Subexpressions in the Model Graph explain how pyhs3 keeps large graphs small
Best Practices for Contributors¶
Code Organization¶
Keep related functionality together
Use clear, descriptive names
Minimize inter-module dependencies
Follow existing patterns
Type Hints¶
Use
from __future__ import annotationsProvide complete type hints
Use
typingmodule types appropriatelyDocument complex types in docstrings
Documentation¶
Write numpy-style docstrings
Include examples in docstrings
Update relevant documentation files
Add doctests for public APIs
Testing¶
Write tests before implementation (TDD)
Test edge cases and error conditions
Use parametrized tests for multiple cases
Keep tests focused and readable
Resources¶
External Documentation¶
Internal Documentation¶
Contributing to pyhs3 - Contributor guide
Testing Guide - Testing guide
Development Workflow - Development workflow
Python API - API reference
How pyhs3 Builds a Model - How pyhs3 builds a model
Getting Help¶
If you need architectural guidance:
Open a discussion on GitHub
Review existing code for patterns
Check HS3 specification for requirements
Ask specific questions with context