Skip to main content

Logo do pacote heimdall dalheimdall

Python versions License: MIT

Python port of the R heimdall package — Drift Adaptable Models.

dalheimdall is a tool designed for concept drift detection in continuous data streams. When analyzing time series data, it is possible to observe significant changes in the data distribution or in the accuracy of predictive models during the forecasting process. These changes are known as concept drift.

The goal of dalheimdall is to detect when concept drift occurs, enabling the detection and adaptation of models in non-stationary contexts. Extending the DAL Experiment Line (pydaltoolbox) to streaming data, the package provides a unified API for concept drift detection (both real concept drift and virtual concept drift), reactive retraining, recurrent concept pools, and controlled drift benchmarking, with reproducible examples designed to help users move quickly from theory to a working streaming implementation.


Implemented detectors

The tables below list every drift detector in the package: the article that proposed it, how the implementation was validated (against the reference publications and in R–Python parity tests), how it works, and the kind of drift it detects. Virtual drift is a change in the input distribution $P(X)$, seen by detectors that monitor the features. Real drift is a change in $P(y \mid X)$, seen by detectors that monitor the error stream of a model. Detectors marked "Virtual / Real" detect either one, depending on whether they are given a feature or an error stream.

The reproductions of the recent detectors (scripts, logs and result tables) are in heimdall/development/validation/, one folder per detector, and dalheimdall mirrors each detector with unit and parity tests under tests/.

Classic detectors

Detector Proposed in Validation How it works Drift
DfrAdwin() Bifet & Gavaldà (2007), SIAM SDM Unit tests: the change of the scikit-multiflow example, quiet on stationary data, consistent window, serialization. Its row of Table IV of the FEDD paper is reproduced (F1 0.38) Adaptive window kept as an exponential histogram; cut when two subwindows have significantly different means Virtual / Real
DfrPageHinkley() Page (1954), Biometrika Unit tests (direction, reset, false alarms). FEDD Table IV reproduced (F1 0.46) Cumulative deviation from the running mean; alarm when it departs from its running minimum by more than a threshold Virtual / Real
DfrCusum() Muthukrishnan, Berg & Wu (2007), ICDMW Unit tests: detects a moderate rise of the error rate, rare false alarms Accumulates deviations of the error signal; alarm when the sum exceeds a threshold Real
DfrDdm() Gama et al. (2004), SBIA Unit tests of the error-based detectors Monitors the online error rate $p$ and its standard deviation $s$; warning and drift when $p + s$ rises well above its minimum Real
DfrEddm() Baena-García et al. (2006), IWKDDS Unit tests of the error-based detectors Monitors the distance between consecutive errors, which makes it more sensitive to gradual drift Real
DfrEcdd() Ross et al. (2012), Pattern Recognition Letters Unit tests (a longer ARL gives fewer false alarms) EWMA control chart on the error stream Real
DfrHddm() Frías-Blanco et al. (2015), IEEE TKDE Unit tests of the error-based detectors $\text{HDDM}_A$: Hoeffding bound on an increase of the mean error Real
DfrKswin() Raab, Heusinger & Schleif (2020), Neurocomputing Unit tests. FEDD Table IV reproduced (F1 0.41 against 0.38) Kolmogorov-Smirnov test between the recent window and a sample of older observations Virtual
DfrKldist() Kullback & Leibler (1951), Ann. Math. Stat. Unit tests (stationary data, mean shift, multivariate). FEDD Table IV reproduced (F1 0.45) Symmetrised KL (Jeffreys) divergence between the binned reference and recent windows Virtual
DfrMcdd() Giusti et al. (2021), Evolving Systems Unit tests. FEDD Table IV reproduced (F1 0.42 against 0.41) Test of the central tendency of the reference against the recent window Virtual
DfrLbdd() Giusti et al. (2021), Evolving Systems Unit tests of the window detectors Levene's variance test between the reference and the recent window Virtual
DfrAedd() Kaminskyi, Li & Müller (2022), ICDMW Unit tests (contract, windows, criteria). FEDD Table IV reproduced (F1 0.40) Autoencoder trained on a reference window; drift when the reconstruction error of recent windows differs Virtual

Recent detectors

Detector Proposed in Validation How it works Drift
DfrEnsemble() (CEDD / FEDD) Giusti Tavares et al. (2025), IJCNN The published member detections on 3W are combined: the crisp ensembles match the reference files exactly (28 of 28 examples), and Table IV is reproduced within 0.01 Members vote with the EFER, majority or threshold rule; FEDD gives each detection a triangular fuzzy score over a tolerance $k$ Depends on the members
DfrMmqt() Stucchi et al. (2023), IEEE TNNLS QuantTree port identical to the reference code; MMQT written from the paper (not in the reference repository). FPR kept at 5% on synthetic data; CWRU bearing results of Table VI reproduced Batch-wise test with one QuantTree histogram per modality (found by k-means); each batch is tested against its closest modality Virtual
DfrEikmeans() Liu, Lu & Zhang (2021), IEEE Trans. Cybernetics Equivalent to the reference code (16,000 of 16,000 decisions identical); Tables III-V and X-XI reproduced Equal-intensity k-means partition of the training data; chi-square test on the bin counts of each window Virtual
DfrMcd() (MCD-DD) Wan, Liang & Yoon (2024), KDD Step-by-step trace against the reference within 1e-14 (encoder, gradients, Adam, decisions); Table 2 matches the reference on 6 of 7 synthetic data sets Contrastive encoder of sample sets of sub-windows; drift when the discrepancy between consecutive sub-window concepts exceeds a learned quantile Virtual
DfrPsi() Kurian & Allali (2024), J. Data, Inf. & Mgmt. Data re-simulated from the SAS code (20 seeds); total PSI of Tables 4-6 within 0.0007 when conditioned on the paper's draw Population Stability Index per feature over the decile bins of a baseline Virtual
DfrOnlinebcp() Yigiter et al. (2015); Xu, Yigiter & Chen (2022), SoftwareX Equivalent to the onlineBcp package (within 1e-13) on aCGH, cnv and COVID; printed outputs of the paper reproduced; an overflow of the reference fixed with log-scale numerics Posterior of the location of the last change point (normal model, normal-inverse-gamma prior, geometric prior on segment lengths) Virtual
DfrIndid() Romanenkova et al. (2022), ACM Multimedia Losses, gradients and Adam steps match the reference within 1e-15; SyntheticNormal Table 2 within the spread between seeds LSTM sequence-to-sequence model trained with the InDiD (or BCE) loss to output the probability of change at each step Virtual
DfrLlr2() Sojo, Bielza & Larrañaga (2027), Expert Systems with Applications No public detector code; compared with the authors' result files on 16 synthetic streams and 18 configurations: no missed drift, detection times at the paper's level, slightly more false alarms on sudden drifts Semiparametric Bayesian network fitted on a baseline; chi-square test on the per-node log-likelihood ratio between a sliding and a reference window, optionally with the Benjamini-Hochberg correction Virtual
DfrCosine() Nigenda et al. (2022), KDD (SageMaker Model Monitor) Matches the AWS reference code within 3e-6 on BERT embeddings of CoLA; the paper gives no numbers, so the behaviour was checked on in-domain and out-of-domain sets Average cosine similarity of each embedding to the baseline embeddings, averaged over a window; alarm below a threshold Virtual
DfrPadd() Komorniczak & Ksieniewicz (2024), arXiv:2404.07776 Step-by-step identical to the reference with the same random draws (p-values within 6e-14, same detections); D1, D2 and R of experiment 2 (240 streams) reproduced Chunks are passed through a random, untrained neural network; repeated t-tests compare the output activations with those stored since the last drift Virtual
DfrStudd() Cerqueira et al. (2023), Machine Learning Step-by-step equivalent to the reference (same fits, errors, alarms and kappa); on real data, kappa and label ratios do not differ from the reference ($p \ge 0.2$) A student model mimics a teacher; Page-Hinkley on the disagreement stream, so labels are needed only after an alarm Virtual
DfrWwAggr() Stepikin, Romanenkova & Zaytsev (2025), ICDM Components match the reference (aggregations within 1e-14, networks within 1e-7); ensembles on HAR reach the reference F1 (mean difference 1e-4). The paper's own data sets are not reproduced Ensemble of deep change point models (BCE, InDiD, TS-CP2, TS2Vec); window Wasserstein aggregation of the members' scores, then a threshold Virtual
DfrFastlr() Tatti (2019), ECML PKDD Reference code unreachable, implemented from the paper; unit tests against the brute-force optimum; the synthetic results (Step, Slope, Hill) reproduced Best two-segment Bernoulli split of the error sequence over the border indices, with a $(1 - \varepsilon)$ guarantee; change when the likelihood ratio exceeds $\tau + \log n$ Real
DfrGreedyks() Cardoso & Galeno (2023), J. Computational Science Statistic identical to the reference within 1e-16; error and effectiveness experiments statistically equal; call-center Table 6 reproduced exactly One-sample Kolmogorov-Smirnov test against a reference distribution with the constant-memory GreedyKS sketch Virtual / Real
DfrIks() dos Reis et al. (2016), KDD KS and Kuiper statistics of the treap identical to the reference over 800 operations; in Tables 2-3 the detector beats both baselines in 18 of 18 settings Incremental two-sample Kolmogorov-Smirnov test per feature on a treap, between a reference sample and a sliding window Virtual
DfrQts() Ramos et al. (2024), ESANN Occupancy curve and detections identical to the reference on 4 data sets; Table 1 exact on RBF and close on Toy Recent observations are mapped onto a quadtree; drift when its occupancy (occupied leaves) shifts or its derivative changes Virtual
DfrDde() Szűcs & Németh (2025), Knowledge and Information Systems Reference repository unavailable, implemented from the paper; Table 3 reproduced exactly; on Covertype (Insects is not available) F1 0.64 against 0.55 in the paper Monitors a subset of the features; a correlation-based "domino" curve estimates the drift probability of the unmonitored ones Virtual
DfrProton() Das et al. (2026), arXiv:2606.20913 No reference code, implemented from the paper; on the FLAIR fundus benchmark the far-OOD gain is reproduced (+8.8 against +8.1), but not the covariate-shift gain (-11.0 against +23.9) Test-time OOD score for a frozen vision-language model: cosine distance to class prototypes from a confidence-gated bank, fused with the MCM score through a variance-driven weight Virtual

Drifter outputs

Besides the drift decision, every drifter exposes the statistic it monitors. After fit(), obj.drifter_output is a DataFrame with one row per observation, and obj.last_drifter_output holds the value for the last observation processed by update_state(). Rows are NaN when the detector reported nothing for that observation, for example while its window is still filling or when it skipped a missing value.

AdpRetrain() exposes the output of its drifter in obj.drifter_output as well, with one row per row of x across every call to fit(). Rows are NaN while the drifter is not monitoring (during the warmup, or after a drift until the model is retrained).

Drifter Type drifter_output columns
DfrDdm() error-based miss_prob: running error rate
DfrEddm() error-based mean_distance: mean distance between two consecutive errors
DfrHddm() error-based estimation: running error rate
DfrEcdd() error-based Z: exponentially weighted moving average of the errors
DfrCusum() error-based g: cumulative sum compared with lambda_
DfrFastlr() error-based score, change_point: Bernoulli likelihood-ratio score and estimated change point
DfrAdwin() univariate width: current length of the adaptive window
DfrGreedyks() univariate statistic, p_value, drift: online one-sample KS statistic, p-value and alarm
DfrPageHinkley() univariate ph_statistic: Page-Hinkley statistic compared with threshold (the larger of the two directions when direction="both")
DfrKswin() univariate D: Kolmogorov-Smirnov statistic; p: its p-value
DfrLbdd() univariate levene_p: p-value of Levene's test
DfrMcdd() univariate old_shapiro_p, new_shapiro_p: normality p-values of the reference and recent halves; comparison_p: p-value of the t-test or Wilcoxon test
DfrOnlinebcp() univariate prob, changepoint: posterior probability and estimated change-point location
DfrKldist() multivariate divergence: divergence between the reference and recent halves, compared with threshold
DfrAedd() multivariate one column per feature: reconstruction error of the most recent row (encoder-decoder), or its encoding (encoder only)
DfrCosine() multivariate score, window_score: per-observation and window cosine similarity against the baseline
DfrDde() multivariate per-feature monitoring and domino drift scores
DfrEikmeans() multivariate statistic, df, p_value: chi-square test over equal-intensity k-means bins
DfrIks() multivariate statistic, drift: incremental two-sample KS statistic and alarm
DfrLlr2() multivariate per-node log-likelihood ratio p-values and drift indicator
DfrMcd() multivariate mcd, threshold: Maximum Concept Discrepancy and learned quantile threshold
DfrMmqt() multivariate statistic, threshold, modality: QuantTree batch statistic, threshold and matched modality
DfrPadd() multivariate significant: fraction of random-network activations with significant t-tests
DfrPsi() multivariate psi_<feature>: Population Stability Index per monitored feature
DfrQts() multivariate occupancy, derivative: quadtree leaf occupancy and its change
DfrIndid() deep / sequence probability: step-by-step change probability from the InDiD LSTM
DfrProton() OOD / VLM score, base_score, proto_score, alpha, variance, calibrated, class, enqueued
DfrStudd() student-teacher teacher, student, error, statistic, drift: predictions, mimicking error and detector output
DfrWwAggr() deep ensemble score, drift: aggregated Wasserstein/MMD score across ensemble members
DfrEnsemble() combined member detections and crisp/fuzzy ensemble vote
DfrMultiCriteria() combined one boolean column per drifter in drifter_list, with its decision on that observation
DfrInactive(), DfrPassive() baseline no columns: they monitor nothing

Choosing what a detector monitors

Every distribution-based detector selects its input through target_feat:

  • univariate detectors (DfrAdwin(), DfrGreedyks(), DfrPageHinkley(), DfrKswin(), DfrLbdd(), DfrMcdd(), DfrOnlinebcp()) take a single column name;
  • multivariate detectors (DfrKldist(), DfrAedd(), DfrCosine(), DfrDde(), DfrEikmeans(), DfrIks(), DfrLlr2(), DfrMcd(), DfrMmqt(), DfrPadd(), DfrPsi(), DfrQts()) take one or more column names, and monitor every numeric column when target_feat=None.

Inside AdpRetrain() and DfrMultiCriteria(), a univariate detector without a target_feat receives the mean of each row. In AdpRetrain(), column names refer to the one-hot encoded, normalized columns, so numeric columns keep their names.


What each detector cannot see

Each detector is blind to some kinds of change. Combine detectors with DfrMultiCriteria() when several kinds of change matter.

Drifter Reacts to Does not see
DfrDdm(), DfrHddm() increases of the error rate decreases of the error rate, and any change that leaves the error rate unchanged
DfrEddm() errors becoming closer together changes that do not affect the distance between errors
DfrEcdd(), DfrCusum() increases of the error rate decreases of the error rate
DfrPageHinkley() increases of the mean (decreases or both with direction) changes of spread or shape with the same mean
DfrAdwin() changes of the mean changes of spread or shape with the same mean
DfrMcdd() changes of location (mean or median) changes of spread with the same centre
DfrLbdd() changes of spread shifts of the mean with the same spread
DfrKswin() any change of the distribution of one feature changes in the relation between features
DfrKldist() changes of the marginal distribution of each feature; with the default 100-row window, shifts of about two standard deviations small shifts (below about one standard deviation with the default window) and changes in the relation between features
DfrAedd() changes of the joint distribution, through the reconstruction error changes that the autoencoder reconstructs equally well

Distribution-based detectors only see virtual concept drift (changes in the inputs); error-based detectors only see real concept drift that degrades the predictions.


Long streams

  • The window-based detectors (DfrKswin(), DfrLbdd(), DfrMcdd(), DfrKldist(), DfrAedd()) run a statistical test or a comparison at every evaluation. monitoring_step is the main speed control: with monitoring_step=10, the test runs once every ten observations.
  • AdpRetrain(history_size=...) bounds the rows kept in drifter_output and drifter_input.
  • NrmMemory(max_size=...) bounds the history used to estimate the normalization.

Installation

pip install dalheimdall

For local development:

pip install -e ".[dev]"

Quickstart

1. Concept Drift Detection

import dalheimdall as ph

data = ph.datasets.st_drift_examples()
stream = data["multivariate"]

detector = ph.DfrAdwin(target_feat="x1", delta=0.002)
detector.fit(stream)

print("Drift detected:", detector.drifted)
print(detector.drifter_output.tail())

2. Reactive Retraining (AdpRetrain)

import numpy as np
import pandas as pd
import pydaltoolbox as dal
import dalheimdall as ph

rng = np.random.default_rng(42)
x = rng.normal(0, 1, size=(200, 2))
y = (x[:, 0] > 0).astype(int)
y[100:] = (x[100:, 0] <= 0).astype(int)  # abrupt concept flip
df = pd.DataFrame({"x1": x[:, 0], "x2": x[:, 1], "y": y.astype(str)})

workflow = ph.AdpRetrain(
    model=dal.ClaDtree("y", slevels=["0", "1"], random_state=42),
    drift_method=ph.DfrDdm(min_instances=20),
    warmup_size=40,
)
for start in range(0, len(df), 40):
    batch = df.iloc[start : start + 40]
    workflow.fit(batch[["x1", "x2"]], batch[["y"]])

print("Drift detected on last batch:", workflow.drifted)

3. Recurrent Concept Pools (AdpRecurrent)

import pydaltoolbox as dal
import dalheimdall as ph

workflow = ph.recurrent_ensemble(
    method=dal.ClaDtree("y", slevels=["0", "1"], random_state=42),
    train_size=40,
    numerical_cols=["x1", "x2"],
    detector=ph.DfrAdwin(target_feat="x1"),
    memory=ph.MemoryBasic(),
)

What's Included

Every detector inherits from Drifter (ErrorBased, DistBased, or MvDistBased), supporting streaming update_state(value) -> bool, batch fit(data) -> self (populating drifter_output), and reset_state().

Group Classes & Functions
Core & Infrastructure Drifter, Dummy, DfrInactive, DfrPassive, ErrorBased, DistBased, MvDistBased, DfrMultiCriteria, DriftWorkflow, drift_step, OneHot, TransPipeline, NrmBase, NrmMemory, MemoryManager, MemoryBasic, MemoryOversampling, MemoryUndersampling
Metrics Metric, MtAccuracy, MtPrecision, MtRecall, MtFscore, MtRocauc, cm_metrics, f1_aggregate
Error-Based Detectors DfrDdm, DfrEddm, DfrHddm, DfrEcdd, DfrCusum
Univariate Distribution Detectors DfrAdwin, DfrPageHinkley, DfrKswin, DfrLbdd, DfrMcdd, DfrPsi, DfrOnlinebcp, DfrFastlr, DfrGreedyks, DfrIks, DfrQts, psi, online_bcp, fastlr_split, ks_sf, GreedyKS, iks_ca, IKS
Multivariate & Structural Detectors DfrKldist, DfrAedd, DfrCosine, DfrEikmeans, DfrMmqt, DfrDde, DfrLlr2, cosine_score, eikmeans, eikmeans_test, mmqt, mmqt_test, dde_curve, dde_score, dde_feature_drift, spbn, spbn_loglik
Ensemble, OOD & Student-Teacher DfrStudd, DfrProton, DfrEnsemble, ensemble_vote
Neural & Deep CPD Detectors DfrPadd, DfrMcd, DfrIndid, DfrWwAggr, indid, indid_predict, tscp2, ts2vec, cpd_scores, cpd_calibrate, cpd_ensemble, cpd_ensemble_fit, wwaggr
Adaptive Workflows AdpRetrain, AdpRecurrent, adapt_static, adapt_retrain, adapt_incremental, adapt_reset, recurrent_ensemble, recurrent_incremental, Concept, ConceptPool, ConceptPoolInactive, TrainStatic, TrainRetrain, TrainIncremental, SlctInactive, SlctPsi, SlctErrorMetrics, SlctPsiThenBest, SlctPsiThenError, SlctAe, EvtLeastUsed, EvtRedundant, RankRatio, RankPsi, RareKeep, RareDrop, RecAlways, RecStable, LearnedLimit
Benchmarks & Datasets datasets.st_drift_examples(), dsg_source, dsg_take, dsg_drift, dsg_stream, dsg_mmd_test, dsg_source_data, dsg_source_regions, dsg_sea, dsg_sine, dsg_mixed, dsg_agrawal

Examples

Rendered examples live in examples/README.md and are generated from executable Markdown notebooks under notebooks/ via:

python notebooks/conversor.py

License

MIT

Metadata

Release files for dalheimdall 1.0.727

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dalheimdall 1.0.727
File Size Uploaded Provenance Actions
dalheimdall-1.0.727.tar.gz 139.2 kB Without provenance Details for dalheimdall-1.0.727.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for dalheimdall 1.0.727
File Interpreter ABI Platform Actions
dalheimdall-1.0.727-py3-none-any.whl Python 3 none any Details for dalheimdall-1.0.727-py3-none-any.whl

Total release size: 295.2 kB

Release files / dalheimdall-1.0.727.tar.gz

Download URL dalheimdall-1.0.727.tar.gz
Size 139.2 kB
Tags Source
SHA-256 checksum
How to use checksums
696db02f92b635573922ccc3d13a1703eb55517f0206438541669ab1c9ccc692
BLAKE2b-256 checksum
How to use checksums
a265c88f526e347c5f8baf73a4cee4b38a5a4d4ebde5884fbbbfca1f7ced8d82
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.0

Release files / dalheimdall-1.0.727-py3-none-any.whl

Download URL dalheimdall-1.0.727-py3-none-any.whl
Size 156.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6e1e7c569aee435486a1da685ceec6bf6919715757c36a2889594194e7f01d72
BLAKE2b-256 checksum
How to use checksums
43915ec9727ad589442d21d463c51ffb2912ef4f4953634c535e216529a980eb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.0

Security for dalheimdall 1.0.727

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page