Skip to main content

Mixed-effects models in Python: LMM, GLMM, CLMM, and Cox frailty with crossed random effects, validated against R

Project description

interlace

interlace

Documentation

Pure-Python mixed-effects modelling library — linear (LMM), generalised (GLMM), ordinal (CLMM), and survival (Cox frailty) — validated against R's lme4, glmer, ordinal, and coxme.

Designed as a drop-in replacement for statsmodels.MixedLM in diagnostics pipelines that require crossed grouping factors (e.g. (1|worker) + (1|company)), which statsmodels does not support.

Installation

pip install interlace-lme

Requires Python ≥ 3.10.

For materially faster random-slopes LMM and GLMM fits (~3-10x), install the [fast] extra to pull in scikit-sparse (CHOLMOD):

pip install 'interlace-lme[fast]'

CHOLMOD requires SuiteSparse system libraries (libsuitesparse-dev on Debian/Ubuntu, brew install suite-sparse on macOS). Without [fast], fits fall back to SuperLU and you'll see a one-shot warning at fit time on the slow path.

Quick start

import pandas as pd
from interlace import fit

result = fit(
    formula="score ~ hours_studied + prior_gpa",
    data=df,
    groups=["student_id", "school_id"],   # crossed random intercepts
)

print(result.fe_params)          # fixed-effect coefficients
print(result.variance_components) # per-factor variance components
print(result.scale)              # residual variance σ²

groups accepts a single string (one random intercept) or a list (crossed intercepts). The first entry is the primary grouping factor.

Model types

Linear mixed models (LMM)

from interlace import fit

result = fit(
    formula="score ~ hours_studied + prior_gpa",
    data=df,
    groups=["student_id", "school_id"],
    method="REML",           # or "ML" for likelihood-ratio tests
    df_method="satterthwaite", # or "kenward-roger"
)

Supports crossed and nested random intercepts, random slopes ((1 + x | g)), observation-level weights, AR(1) and compound-symmetry residual correlation structures, and Satterthwaite or Kenward-Roger denominator degrees of freedom.

Generalised linear mixed models (GLMM)

from interlace import glmer

result = glmer(
    formula="incidence / size ~ period",
    data=df,
    family="binomial",       # or "poisson", "gaussian", "negativebinomial"
    groups="herd",
    weights=df["size"].values,
)

Families: binomial, Poisson, Gaussian, NB1, NB2, Beta, Gamma, zero-inflated Poisson/NB2, hurdle Poisson, zero-one-inflated Beta. Supports Laplace approximation and adaptive Gauss-Hermite quadrature.

Cumulative link mixed models (CLMM)

from interlace import clmm

result = clmm(
    formula="rating ~ condition",
    data=df,
    groups="subject",
)

Ordinal regression with random effects, matching R's ordinal::clmm().

Cox frailty models

from interlace import coxme

result = coxme(
    formula="Surv(time, event) ~ treatment + age",
    data=df,
    groups="centre",
)

Cox proportional hazards with Gaussian frailty, matching R's coxme::coxme().

Diagnostics

from interlace import hlm_resid, leverage, hlm_influence, hlm_augment

resid_df = hlm_resid(result, type="conditional")  # or "marginal"
lev = leverage(result)                              # hat-matrix diagonal
infl = hlm_influence(result, level=1)               # Cook's D, MDFFITS, etc.
aug = hlm_augment(result)                           # data + residuals + influence

# Plotting (all return plotnine.ggplot objects)
from interlace import plot_resid, plot_influence, dotplot_diag

plot_resid(resid_df, type="resid_vs_fitted")
plot_influence(infl, measure="cooks_d")
dotplot_diag(infl, variable="cooks_d", cutoff="internal")

statsmodels compatibility

CrossedLMEResult exposes the same interface as statsmodels.MixedLMResults so it can be used as a drop-in in downstream code that accesses fe_params, resid, scale, fittedvalues, random_effects, predict(), and model.exog / model.groups / model.data.frame.

hlm_resid, hlm_influence, and hlm_augment all accept either a CrossedLMEResult or a statsmodels MixedLMResults object.

Parity with R

Results are validated against R reference implementations to the following tolerances:

Model type R reference Fixed effects Variance components
LMM lme4::lmer() abs diff < 1e-4 rel diff < 5%
GLMM lme4::glmer() abs diff < 1e-3 rel diff < 5%
CLMM ordinal::clmm() abs diff < 1e-3 rel diff < 5%
Cox frailty coxme::coxme() abs diff < 1e-3 rel diff < 10%
AR(1) / CS nlme::lme() abs diff < 1e-3 rel diff < 5%

Contributing

Bug reports, documentation fixes, and new features are welcome — see CONTRIBUTING.md for how to get started. To open an issue or ask a question, use the GitHub issue tracker.

Attribution

  • lme4 — the reference implementation for mixed-effects models in R; interlace targets parity with lme4::lmer() and lme4::glmer().
  • ordinal — R package for cumulative link models; interlace's clmm() targets parity with ordinal::clmm().
  • coxme — R package for Cox models with random effects; interlace's coxme() targets parity with coxme::coxme().
  • nlme — R package for linear mixed models with correlation structures; AR(1) and CS validation benchmarks.
  • HLMdiag — the R package whose diagnostics API (hlm_resid, hlm_influence, hlm_augment, dotplot_diag) interlace replicates in Python.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

interlace_lme-0.3.1.tar.gz (12.4 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

interlace_lme-0.3.1-py3-none-any.whl (170.9 kB view details)

Uploaded Python 3

File details

Details for the file interlace_lme-0.3.1.tar.gz.

File metadata

  • Download URL: interlace_lme-0.3.1.tar.gz
  • Upload date:
  • Size: 12.4 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for interlace_lme-0.3.1.tar.gz
Algorithm Hash digest
SHA256 73e7134a0fa1fa04cdbcd28c5c740d7e34f48640a8b79d629e5af4d133581f7e
MD5 8adca1f5d6f322f5d185ba6c059f6639
BLAKE2b-256 9c17118c27c02a25ba359b1ca850bb358a1646e6b9a9de0ed5ae3a1962e9d9ff

See more details on using hashes here.

Provenance

The following attestation bundles were made for interlace_lme-0.3.1.tar.gz:

Publisher: publish.yml on heliopais/interlace

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file interlace_lme-0.3.1-py3-none-any.whl.

File metadata

  • Download URL: interlace_lme-0.3.1-py3-none-any.whl
  • Upload date:
  • Size: 170.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for interlace_lme-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 1413e547157539b8af53596cb9581900fbf4a266a478ce17c3953c1e34e86b4e
MD5 aa1162e7a22f86ff547723aa6eb9a9af
BLAKE2b-256 21f176311993fdb4c52aafaa1fc8ab8b0f5710b66a7895b616c58d03060b2a74

See more details on using hashes here.

Provenance

The following attestation bundles were made for interlace_lme-0.3.1-py3-none-any.whl:

Publisher: publish.yml on heliopais/interlace

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page