Skip to content
RochePublic

About

homepy makes it easy to model ragged, hierarchical longitudinal time series. It is designed in particular to model home cage monitoring (HCM) data recordings with effects unfolding across multiple time scales.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Bayesian Modeling of Hierarchical Time-series Data

homepy logo

License Python 3.12+ PyMC JAX


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.

Table of Contents

Key Features

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

Why homepy?

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

Modeling multiple time scales

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:

multi time scale image

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.

Modeling nested and ragged hierarchies

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:

groups -> cages -> individuals

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:

Ragged hierarchy

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 Statistical Model

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.

A generalized additive model

Let $y_{i,f}(t)$ be the observation of feature $f$ for individual $i$ at time $t$. Each observation follows an observational distribution $P_y$ with location $\mu_{i,f}(t)$ and scale parameters $\theta_f$. The location is a link function $g$ applied to a sum of components $c$:

$$ y_{i,f}(t) \sim P_y\big(\mu_{i,f}(t),, \theta_f\big), \qquad \mu_{i,f}(t) = g\Big(\sum_{c} \phi_{i,f,c}(t)\Big) $$

The standard components are:

  1. Baseline activity $\phi_{i,f,\text{base}}$, which is constant in time.
  2. Long-term trend, for example linear, $\phi_{i,f,\text{long}}(t) = m_{i,f}, t$, or quadratic.
  3. 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:

$$ \phi_{i,f} \sim \mathcal{N}\big(\phi_{\text{parent},f},, \sigma_{\text{parent},f}\big) $$

Centered, non-centered and zero-sum parametrizations are all available.

Hierarchical Gaussian processes

Daily activity patterns are modeled as deviations from the parent level's function. Correlations between features can optionally be included:

$$ \phi_{i,f,\text{daily}}(t) = \phi_{\text{parent},f,\text{daily}}(t) + \sigma_{\text{parent},f,\text{daily}} \sum_{f'} \rho_{ff'}, \Delta\phi_{i,f',\text{daily}}(t), \qquad \Delta\phi_{i,f,\text{daily}}(t) \sim \mathcal{GP}\big(0,, k_l(t, t')\big), \qquad \rho \sim \text{LKJ}(\eta) $$

Each level $l$ of the hierarchy can have its own covariance kernel, for example a periodic kernel with a 24-hour period at the group level and a squared exponential kernel at the individual level.

Scalable GP approximation

Exact GPs scale as $\mathcal{O}(N^3)$. homepy instead uses a truncated Karhunen–Loève (spectral) expansion of the covariance kernel:

$$ \Delta\phi(t) \approx \sum_{j=0}^{M} v_j, \lambda_j, \varphi_j(t), \qquad v_j \sim \mathcal{N}(0, 1) $$

Here $\varphi_j$ and $\lambda_j$ are the eigenfunctions and eigenvalues of the kernel. The series is truncated at the smallest $M$ that explains 95% of the process variance. Because the kernel hyperparameters are fixed, the eigenfunctions only have to be computed once. The cost then drops to $\mathcal{O}(NM)$, and the computation parallelizes well on GPUs.

Effect sizes

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.

Installation

Quick install with pip

You can do a basic install of homepy with pip:

pip install git+https://github.com/Roche/homepy.git

Tip

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.

Full install with conda

  1. Clone the repository (skip this step if you have already cloned it)

    git clone git@github.com:Roche/homepy.git
  2. Go to the repository directory

    cd homepy

    If you cloned the repository a while ago, update it with:

    git pull
  3. 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
  4. Activate the environment

    conda activate homepy
  5. Install homepy

    python -m pip install --editable .

Testing GPU support

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 version

See 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!

Quick Start

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.

Documentation

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

Package Overview

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/

License

Copyright 2026 F. Hoffmann-La Roche Ltd and PyMC Labs.

This project is licensed under the Apache License 2.0.

Authors

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:

Contributions and Community Feedback

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.

About

homepy makes it easy to model ragged, hierarchical longitudinal time series. It is designed in particular to model home cage monitoring (HCM) data recordings with effects unfolding across multiple time scales.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages