homepy is a Python package for building and fitting Bayesian hierarchical time-series models to large longitudinal datasets. It was designed for the analysis of home-cage monitoring studies, where activity is recorded continuously over days and the recording is repeated over many weeks, but it can be used with any dataset that has nested, ragged hierarchies and effects that act on several time scales.
Models are put together from reusable building blocks (baselines, long-term trends, hierarchical Gaussian processes, likelihoods) and fitted with PyMC. Sampling can optionally run on the GPU through JAX and NumPyro.
- Key Features
- Why homepy?
- The Statistical Model
- Installation
- Quick Start
- Documentation
- Package Overview
- License
| Multi-scale time series | Model short-scale (within-day) and long-scale (across-week) dynamics together in one model |
| Ragged hierarchies | Efficiently handle nested structures such as groups → cages → individuals, where each level can have a different number of children |
| Hierarchical Gaussian processes | Flexible, non-parametric daily activity patterns that are partially pooled across levels of the hierarchy |
| Correlated features | Learn correlations between several observed features through LKJ priors |
| Composable model blocks | Build models from configurable ModelBlocks, or write your own custom blocks |
| Count likelihoods | Negative Binomial, Zero-Inflated Negative Binomial, Poisson, Generalized Poisson and Normal likelihoods |
| Effect sizes and model comparison | Time-resolved effect sizes, posterior predictive checks, and BIC, DIC and ECDF-CRPS scores |
| GPU acceleration | Sample on the GPU through JAX and NumPyro |
The goal of homepy is to make it easy to model large, hierarchically structured longitudinal datasets that are ragged and that can contain effects at different temporal resolutions (for example within a day and across several weeks).
Longitudinal studies are only useful if you can describe how observations change over time. The main strength of homepy here is that it can model several time scales at once. The cartoon below shows the idea:
In this study, recordings were made over several weeks (the long time scale), and in each recording week activity was measured throughout the day (the short time scale). Both scales show structure:
- Short time scale: activity starts near zero, peaks in the middle of the recording and then falls again.
- Long time scale: overall activity drops over the weeks, and the amplitude of the daily modulation shrinks.
A model that only looks at the long time scale ignores the daily modulation. A model that only looks at the short time scale misses the long-term effect. homepy models both together.
For this, homepy provides flexible Gaussian process models for the short time scale (e.g. recordings over several days) and simple linear or quadratic models for the long time scale (e.g. the effect of the passing weeks). You can also write custom model blocks for your own needs.
Collected data often has a hierarchical structure. For example, you might collect data from several groups, where each group is made up of many individuals who are housed in small collectives (in animal experiments, individuals that share a cage). The observations depend on this structure:
To draw sound conclusions from such data, the model must account for how the data was collected. homepy makes it easy to build models that reflect even complex hierarchical structures.
Many packages can model hierarchical data, but homepy was built specifically for ragged hierarchies. A hierarchy can be viewed as a tree with many branches:
Moving down the tree, each node can branch into several descendants. In a ragged hierarchy, nodes at the same depth do not have the same number of descendants. homepy walks through such hierarchies efficiently and builds models that make full use of the nested structure.
The models implemented in homepy form a family of semi-parametric Bayesian generalized additive models (GAMs). This section gives a short summary. For the full details, see the documentation notebooks.
Let
The standard components are:
-
Baseline activity
$\phi_{i,f,\text{base}}$ , which is constant in time. -
Long-term trend, for example linear,
$\phi_{i,f,\text{long}}(t) = m_{i,f}, t$ , or quadratic. -
Daily modulation
$\phi_{i,f,\text{daily}}(t)$ , a function drawn from a Gaussian process that captures short time scale activity patterns.
Every component can follow the data hierarchy. Each unit's parameters are centred on those of its parent level, and so on up to the root of the hierarchy:
Centered, non-centered and zero-sum parametrizations are all available.
Daily activity patterns are modeled as deviations from the parent level's function. Correlations between features can optionally be included:
Each level
Exact GPs scale as homepy instead uses a truncated Karhunen–Loève (spectral) expansion of the covariance kernel:
Here
With the posterior distribution, homepy computes time-resolved effect sizes: the expected difference in activity between conditions (e.g. disease vs. control), where the random effects are marginalized given the fixed effects. This quantifies when during the day groups differ, and comes with full uncertainty estimates and no multiple-comparison corrections.
You can do a basic install of homepy with pip:
pip install git+https://github.com/Roche/homepy.gitTip
To get the most out of the package, we strongly recommend that you also install jax and dask. The repository includes a conda environment file that installs all optional dependencies and prepares the package for sampling on GPUs.
-
Clone the repository (skip this step if you have already cloned it)
git clone git@github.com:Roche/homepy.git
-
Go to the repository directory
cd homepyIf you cloned the repository a while ago, update it with:
git pull
-
Create the conda environment (or update it if it already exists)
conda env create --file environment.yml
To update the existing environment instead of recreating it, run:
conda env update --file environment.yml --prune
-
Activate the environment
conda activate homepy
-
Install homepy
python -m pip install --editable .
homepy can run inference on the GPU using JAX. To check whether your GPU can be used for sampling, run:
import jax
from jax.lib import xla_bridge
print(jax.devices())
assert xla_bridge.get_backend().platform == "gpu"If jax.devices() does not list a GpuDevice, or the assertion fails, you may need to install a jax and jaxlib version built for your GPU. For example, with CUDA 11.0 and CuDNN 8.2 you would run:
pip install "jax[cuda11_cudnn82]" -f \
https://storage.googleapis.com/jax-releases/jax_cuda_releases.html \
cuda versionSee the JAX documentation for more information.
Once the check above passes, test that homepy can access the GPU:
from homepy.tests.test_gpu_sampling import test_gpu_sampling
test_gpu_sampling()✅ If this runs without errors, you are ready to run inference on your GPU!
A homepy model is defined by two things: a mapping from block names to ModelBlock classes, and a configuration dictionary for each block. The example below uses the synthetic dataset from the docs. It models activity counts with a hierarchical baseline, a linear long-term trend, a periodic daily Gaussian process and a Negative Binomial likelihood:
import numpy as np
import pandas as pd
import homepy
df = pd.read_csv("docs/data/docs_synthetic_dataset.csv")
coords = {"observation": df.index, "feature": ["activity"]}
config = {
"hierarchies": dict(
nested_hierarchies=["group", "individual"], time_columns=["week", "bins"],
),
"intercept": dict(
nested_hierarchies=["group"],
name_prefix="intercept",
parametrization="non-centered",
coef_dims=["feature"],
prior_mu=np.log(300),
prior_mu_sigma=0.3,
level_scale_kwargs={1: {"prior_kwargs": {"sigma": 0.3}}},
),
"long_term_trend": dict(
nested_hierarchies=["group"],
name_prefix="long_term_slope",
parametrization="non-centered",
coef_dims=["feature"],
time_column="time_in_weeks",
prior_mu=0,
prior_mu_sigma=0.02,
level_scale_kwargs={1: {"prior_kwargs": {"sigma": 0.02}}},
),
"gp": dict(
nested_hierarchies=[],
name_prefix="gp",
level_kernel_kwargs={0: {"kernel": "0.1 * Periodic(1, period=1, ls=0.3)"}},
time_column="bins",
coef_dims=["feature"],
),
"observed": dict(
link_function="exp",
concentration_dist="Exponential",
concentration_name="concentration",
concentration_prior=[2],
rv_name="y",
observed_features=coords["feature"],
observed_dims=["observation", "feature"],
),
}
model = homepy.models.Model(
blocks_config={
"hierarchies": homepy.blocks.SortNestedHierarchies,
"intercept": homepy.blocks.BaselineActivity,
"long_term_trend": homepy.blocks.LinearLongTermTrend,
"gp": homepy.blocks.WithinBlockGP,
"observed": homepy.blocks.NegBinLikelihood,
},
data=df,
config=config,
coords=coords,
)
idata = model.fit(target_accept=0.9, random_seed=42) # add sample_gpu=True to sample on the GPU
model.plot_predictions(idata, depth=2)See docs/02_modeling.ipynb for a step-by-step walkthrough, including prior predictive checks, hierarchical GPs and model comparison.
The docs/ folder contains a series of tutorial notebooks:
| Notebook | Description |
|---|---|
| 01 · Introduction | Motivation and overview of the package |
| 02 · Modeling | Building models from ModelBlocks, prior/posterior predictive checks, hierarchical GPs, model comparison |
| 03 · Parametrization | Centered, non-centered and zero-sum hierarchical parametrizations |
| 04 · Customizing | Writing custom blocks, summaries and plots, and working with the NestedHierarchy helpers |
| 05 · Predicting | Prior/posterior predictive sampling and out-of-sample prediction |
| 06 · Effect size | Defining and computing time-resolved effect sizes |
| 08 · GP refresher | A Gaussian process cheatsheet: kernels, spectral decomposition, combining kernels |
homepy/
├── blocks/ # Composable model building blocks
│ ├── base.py # ModelBlock base class, SortNestedHierarchies
│ ├── linear.py # BaselineActivity, Linear/QuadraticLongTermTrend
│ ├── gp.py # WithinBlockGP, (LKJ-)correlated hierarchical GPs
│ ├── likelihoods.py # NegBin, ZeroInfNegBin, Poisson, GeneralizedPoisson, Normal
│ └── distributions.py # Custom distributions
├── models/ # Model class and ready-made model configurations
├── nested_hierarchy_rvs.py # Hierarchical random variables over ragged trees
├── nested_hierarchy_utils.py
├── model_comparison.py # BIC, DIC and ECDF-CRPS model comparison
├── jax_utils.py # JAX / GPU sampling helpers
└── tests/
Copyright 2026 F. Hoffmann-La Roche Ltd and PyMC Labs.
This project is licensed under the Apache License 2.0.
The code was written in collaboration with PyMC Labs. Notable contributors were:
With additional contribution from the Roche internships for Scientific Exchange (RiSE) Programme by:
While we do not accept external code contributions or pull requests, we welcome bug reports, feature requests, suggestions, and community discussions.
Please use GitHub Issues or GitHub Discussions to share your feedback.



