Metadata-Version: 2.5
Name: paneldx
Version: 0.6.0
Summary: Validate that a longitudinal dataset is what it claims to be, before you model it.
Project-URL: Homepage, https://github.com/stemmatics/paneldx
Project-URL: Repository, https://github.com/stemmatics/paneldx
Project-URL: Issues, https://github.com/stemmatics/paneldx/issues
Author: Muhammad Umer Imran
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: data leakage,data validation,entity resolution,longitudinal,machine learning,panel data,reproducibility
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.11
Requires-Dist: numpy>=1.23.2
Requires-Dist: pandas>=1.5
Provides-Extra: dev
Requires-Dist: build; extra == 'dev'
Requires-Dist: mypy<2,>=1.11; extra == 'dev'
Requires-Dist: pandas-stubs; extra == 'dev'
Requires-Dist: pip-audit; extra == 'dev'
Requires-Dist: pre-commit; extra == 'dev'
Requires-Dist: pytest-cov; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff==0.9.4; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Provides-Extra: excel
Requires-Dist: openpyxl; extra == 'excel'
Provides-Extra: full
Requires-Dist: openpyxl; extra == 'full'
Requires-Dist: pyarrow>=23.0.1; extra == 'full'
Requires-Dist: scikit-learn<2,>=1.9; extra == 'full'
Provides-Extra: ml
Requires-Dist: scikit-learn<2,>=1.9; extra == 'ml'
Provides-Extra: parquet
Requires-Dist: pyarrow>=23.0.1; extra == 'parquet'
Description-Content-Type: text/markdown

# paneldx

[![CI](https://github.com/stemmatics/paneldx/actions/workflows/ci.yml/badge.svg)](https://github.com/stemmatics/paneldx/actions/workflows/ci.yml)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](https://www.python.org/downloads/)
[![PyPI](https://img.shields.io/pypi/v/paneldx)](https://pypi.org/project/paneldx/)
[![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-green)](https://github.com/stemmatics/paneldx/blob/v0.6.0/LICENSE)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.22339487.svg)](https://doi.org/10.5281/zenodo.22339487)

**Check that your longitudinal dataset is what it claims to be, before you model it.**

```bash
pip install paneldx
paneldx audit data.csv --time quarter --target risk_score --html report.html
```

## What it does, plainly

Imagine a class attendance sheet where you assume "student #3" is the same child
every week. But the sheet is re-sorted by test score each week, so student #3 is
a different child every time. Now compute "student #3's progress over the term".
You get a number. It means nothing.

Data that tracks the same patients, customers or providers across time has this
failure mode constantly, and nothing warns you. Lags, differences, trajectories,
sequence models and grouped cross-validation all silently assume the identifier
points at one entity. When it does not, nothing errors. The numbers just stop
meaning anything.

`paneldx` tests that assumption against the data itself, and tells you when it
fails. It also catches three related problems that make a model look better than
it is.

## When you would use this

- **Before training on any panel dataset**, especially one assembled from
  exports, joins, or de-identification passes, where re-sorting can sever an ID
  from the entity it names.
- **When results look too good.** An R² of 0.95 on time-series data is more often
  a warning than an achievement. `paneldx` tells you what a naive baseline scores
  so you know whether your model beat anything.
- **When inheriting someone else's data** and the entity column arrived without
  documentation.
- **As a CI gate.** The command exits non-zero on a disqualifying defect, and
  also when there is too little evidence to judge, so a pipeline can refuse to
  train on a broken or unverifiable panel.
- **When reviewing a paper or a colleague's analysis** and you want to check the
  panel is sound before reading the results.

Not useful for cross-sectional data with no time dimension, or for panels of
fewer than two periods.

---

## The bug this was built from

An earlier physician-analytics pipeline of ours built its entity ID from row
position:

```python
physician_id = ((serial_number - 1) % rows_per_quarter) + 1
```

Each quarter was sorted by platform rank before this ran, so position *i* was a
different doctor every quarter. That ID then fed momentum features, a GRU over
"trajectories", and the grouped CV splits. Two related defects sat alongside
it: a target reconstructible from its own features at R² 0.923, and a
carry-forward baseline that beat the model by 2.9x once the key was fixed.

The audit, the numbers and the reasoning are in
[case_studies/popnet_reanalysis](https://github.com/stemmatics/paneldx/blob/v0.6.0/case_studies/popnet_reanalysis/README.md).
The checks were carried out after the PopNet paper was published in 2025. They
were not included in the paper and are not corrected PopNet results.

---

## Install

```bash
pip install paneldx
```

Python 3.11+, `numpy` and `pandas`. Nothing else: no modelling framework, no
template engine. `paneldx` is run before a modelling stack is chosen, so the
base install does not drag one in.

Optional extras:

```bash
pip install "paneldx[excel,parquet]"   # more input formats
pip install "paneldx[ml]"              # scikit-learn; no 0.6.0 check uses it yet
pip install "paneldx[full]"            # all of the above
```

Reading a format whose extra is missing stops with the install command, and
`import paneldx` never fails because an extra is absent. The `ml` extra is
declared for the non-linear target reconstruction planned for 0.7.0.

---

## Usage

```python
from paneldx import audit, to_html
from paneldx import validate_key, discover_keys
from paneldx import detect_counters, target_leakage, persistence_baseline

# Is the entity key supported by the data?
print(validate_key(df, "patient_id", time_col="quarter"))
# ...and rule it out outright when you know something about the panel
print(validate_key(df, "patient_id", "quarter", invariant_cols=["birth_date"]))
print(discover_keys(df, time_col="quarter")[0])  # no hints needed

# Are the numbers about to fool you?
print(detect_counters(df, "patient_id", "quarter"))  # lifetime totals
print(target_leakage(df, target="risk_score"))  # is y inside X?
print(
    persistence_baseline(df, "patient_id", "quarter", "risk_score", period_step="QS")
)  # declare the cadence

# Or all of it at once
result = audit(df, "quarter", key="patient_id", target="risk_score")
open("report.html", "w").write(to_html(result))
```

The CLI reads CSV, TSV, Excel and JSON. Parquet and Feather support requires
`pip install "paneldx[parquet]"`:

```bash
paneldx audit panel.xlsx --time t --key site_id patient_id --target outcome
```

---

## The three traps

**Cumulative features.** Lifetime totals barely move between periods, so a target
built from them is near-perfectly autocorrelated. Models trained on them report
excellent R² for restating what they were handed. Difference them into
per-period flows.

**Target composition.** When the target is computed from columns that are also
features, the model is not predicting, it is recovering arithmetic. The metrics
look superb and mean nothing. `target_leakage` fits a deliberately *linear*
model: the point is not to predict the target well, but to show no prediction was
ever required.

**Missing naive baseline.** On autocorrelated panels, carrying the last value
forward is often unbeatable. A model reported without it may be losing to a
one-line rule, and no reader could tell.

---

## How key validation works

A useful entity key should reveal consistent patterns across periods.

**Invariants.** Some attributes should not change for the same entity, such as
a birth date or account opening date. Under a valid entity key, these values
should normally remain stable. Under a broken key, they may change between
periods.

**Counters.** Some values only increase over time. Under a valid entity key,
their within-entity changes should normally be non-negative. Under a broken
key, they may move in both directions.

**Persistence.** Most columns are neither constant nor only rising. They still
say something: under a valid key a value stays closer to the same entity's
previous value than to another entity's. This is what lets the check work on a
panel where nothing is invariant, which is most panels.

paneldx compares each column against the same reference: entity labels shuffled
within each period, over 199 permutations, with a Benjamini-Hochberg correction
across the panel's columns. A column supports the key when it beats that
reference.

The verdict uses the **share** of columns supporting the key, not only the
count. A key created from row order may pick up a few columns because those
columns were used for sorting; a real key should be supported more broadly.

| Supported share | Verdict |
|---|---|
| ≥ 0.40, at least 2 columns, and one of them an invariant or counter | `pass` — supported by the data |
| ≥ 0.40 on persistence alone | `warn` — reason `persistence_only` |
| 0.15 to 0.40 | `warn` — weak, inspect the listed columns by hand |
| < 0.15, or fewer than 3 usable columns | `inconclusive` — too little to judge |

Persistence alone stops at `warn` because it cannot separate a correct key from
a partly corrupted one: both beat the shuffled reference easily, since that
reference only asks whether *any* linkage exists. An invariant or a counter can
be **broken**, and a corrupted key breaks it — which is why one of those is what
lifts a key to `pass`.

A low share is not a rejection. It says the panel gave the key little to
explain, which happens to correct keys as readily as to broken ones: Produc, a
clean panel of 48 named US states over 17 years, has exactly one column that is
constant within a state.

## Declaring what you know

`fail` means the data, or a source you consulted, **contradicts** the key:
duplicate or merge-shaped entity-period rows, a column you declared invariant
that changes, a column you declared monotone that falls, a key recognised as a
row numbering, a mislinked share that rose above a reference, or anchor
lookups (below). The two declared ones are domain knowledge, and they are what
turns "cannot tell" into a definite answer:

```python
validate_key(
    df, "patient_id", "quarter",
    invariant_cols=["birth_date", "enrolled_on"],   # must never change
    monotone_cols=["total_visits"],                 # must never fall
)
```

```bash
paneldx audit data.csv --time quarter --key patient_id \
  --invariant birth_date enrolled_on --monotone total_visits
```

Every report also carries a `reason` (such as `supported`, `persistence_only`,
`positional_key_detected` or `anchor_mislinked`) and a `verification` saying
what the verdict was checked against. A pass with nothing independent behind it
is **`not verified`**.

### Checking the key against the system that issued it

Nothing in a file can rule out a key that was wrong from its first period. The
system that issued the IDs can. Measure your source first, then look up about
thirty IDs:

```bash
# 1. measure e: look up 50-100 IDs whose key you trust; 0 disagreements of 50 -> e = 0.06
paneldx anchor data.csv --key patient_id --time quarter --budget 30 --source-error 0.06
# 2. answer same / different / blank for each ID in data.csv.paneldx-anchor.csv
paneldx audit  data.csv --key patient_id --time quarter --anchor data.csv.paneldx-anchor.json
```

The answers can fail the key (`anchor_mislinked`) or verify that under 10% of
its IDs are mislinked (`anchor_verified`). A correct key fails at most 5% of
the time **if the source errs at most e**, even when the lookups were aimed at
the IDs the source happens to dispute. The "if" is yours to establish: use the
95% upper bound on the disagreement rate you measured, not a figure from the
source's documentation. In this project's final test two of three official
sources disagreed with a correct key more often than documented (7.8% against
a stated 5%, 21% against 10%), and on those two the bound did not hold. See
[how it works](https://github.com/stemmatics/paneldx/blob/v0.6.0/docs/how-it-works.md).

### When the data cannot decide, a person can

`paneldx review data.csv --key id --time t` shows twenty entities' least
convincing pair of adjacent rows and asks whether each pair is the same
entity. The answers are saved beside the data and re-read by
`paneldx audit ... --review`. A `different` answer warns; a `same` answer
covers those two rows only.

### Keys made from row order

A key built by sorting each period and numbering the rows — the defect this
package was built from — is caught without being declared anything. paneldx
reports `positional_key_detected` and **names the column it was sorted on**:

```
Entity key is a row numbering (physician_id)
  Each period was sorted on 'total_spend' and the rows numbered, so
  physician_id links a different entity every period.
```

Persistence alone cannot catch this: sorting on a slowly drifting column keeps
ranks nearly stable, so the manufactured key inherits real persistence and can
look supported. What gives it away is that the key *is* the rank — in every
period, ordering the rows by that column reproduces the key exactly.

---

## Limitations

- **Near-valid keys are hard to separate from perfect ones.** The tolerances
  exist because genuinely valid keys contain a few violations of their own, so
  a key that merges a small number of entities can score like a clean one. Ties
  break toward the finer partition, which mitigates but does not eliminate this.
- **Leakage detection is linear.** A target computed from its features by some
  non-linear rule can slip past `target_leakage`. A high score is strong
  evidence; a low one is not a clearance.
- **Two-column search is O(n²)** in columns. On a 24k x 31 table the full pair
  search takes about 23 seconds. Pass `--key` when you already know it.
- **A pass is `not verified` unless something independent was checked against.**
  Every check compares an entity with its own past, so a key that was already
  wrong when the file began agrees with itself and passes. The headline says
  *"no contradiction was found, but nothing here can rule out damage that was
  present from the first period"* — never fine, valid or correct. That blind
  spot was measured three ways with preregistered thresholds, and the last
  attempt to close it automatically failed two of its eight gates; the
  conclusion recorded in the protocol is that the current method cannot detect
  day-one damage universally from the file alone. Anchor lookups, or about
  twenty entity histories you have confirmed, give it something to check
  against.
- **Human review finds damage the model cannot; it does not teach the model.**
  On damaged files the model missed, a person answering twenty tool-chosen
  pair questions found a broken pair 54% of the time. A `same` answer covers
  those two rows only, never the whole history; a `different` answer is a
  warning from your review, not a contradiction the tool established. Model
  detection after review is 0.0% by design, and the two numbers are always
  reported apart.
- **Anchor lookups are only as good as the stated source error.** The error
  bound assumes the source errs at most e, and that IDs err independently
  of one another. A source whose errors move together (a definitional
  difference that recurs for the same entities) is outside it. Measure e; do
  not take it from documentation.
- **`inconclusive` still happens.** Four of the thirteen development panels
  abstain on their documented key, all because they hold fewer than the twenty
  entities any rate needs, and a fully shuffled key reads `inconclusive`
  rather than `fail`. Declaring an invariant or a counter is how a caller
  gets a definite answer on a panel that cannot supply one.
- **Partial key corruption is the hard case.** A key with a fraction of its
  labels wrong still shows plenty of persistence, so persistence cannot reject
  it. That is why persistence alone never reaches `pass`, and why declaring an
  invariant or a counter is what turns "cannot tell" into an answer.
- **The benchmark is published failing.** Gate A is not green on any split,
  and every rate is printed beside its abstention rate:

  | Split | Panels | Correct keys rejected | Broken keys accepted | Inconclusive |
  |---|---|---|---|---|
  | development (`v0.6.0-final`) | 13 | 0 of 13 | 0.287 [0.181, 0.385] | 0.280 |
  | held-out (3.30.4) | 7 | 0 of 7 | 0.456 [0.424, 0.494] | 0.160 |
  | locked final test, file only (3.33.1) | 3 | 0 of 568 cases | 0.139 | 0.572 |

  Renumbered keys were caught wherever one could be judged (the one miss was a
  held-out panel left with two entities). Partial damage from the first period
  is the case nothing in the file catches: on the held-out panels such a key was
  accepted 97% of the time, as `pass` or as a `warn` that names no damage. In a
  preregistered comparison on the development cases, Great Expectations and
  pandera caught duplicated and merged rows but no shuffle, rekey, partial or
  late-window damage, deepchecks flagged 62% of clean files, and paneldx claimed
  damage on no clean file. Eleven of the thirteen development panels are
  balanced academic data; the one customer-shaped panel is where every method
  fails.
  See [limitations](https://github.com/stemmatics/paneldx/blob/v0.6.0/docs/limitations.md) for what has and has not
  been measured, [REPRODUCE.md](https://github.com/stemmatics/paneldx/blob/v0.6.0/REPRODUCE.md) to rebuild it, and the
  [validation protocol](https://github.com/stemmatics/paneldx/blob/v0.6.0/validation/protocol/protocol.md) for every
  experiment, recorded before it ran. The full validation package (protocol,
  harnesses and recorded results) is in the GitHub repository and its Zenodo
  archive, not in the PyPI source distribution.
- **Scale is tested and sampled.** 41 million rows validate in 147 seconds at
  7.9 GB, but the statistical checks see a fixed 200,000-cell sample of any file
  that large; only the structural checks see every row.
- Needs at least two periods, and enough entities to measure a rate against.

---

## Roadmap

0.6.0 is the publication release: the method is frozen, and its benchmark is
published with its failures. 0.7.0 (no language models) adds curated domain
packs that declare invariants and counters, source cards that record a
source's measured error, a shape-aware lookup rule, a study of real documented
ID breaks, and a new locked test. 0.8.0 studies language models as dispute
judges and rule proposers. See the
[development roadmap](https://github.com/stemmatics/paneldx/blob/v0.6.0/ROADMAP.md).

---

## Documentation

- [Getting started](https://github.com/stemmatics/paneldx/blob/v0.6.0/docs/getting-started.md)
- [How it works](https://github.com/stemmatics/paneldx/blob/v0.6.0/docs/how-it-works.md)
- [Interpreting results](https://github.com/stemmatics/paneldx/blob/v0.6.0/docs/interpreting-results.md)
- [API reference](https://github.com/stemmatics/paneldx/blob/v0.6.0/docs/api.md)
- [Limitations](https://github.com/stemmatics/paneldx/blob/v0.6.0/docs/limitations.md)
- [Validation protocol](https://github.com/stemmatics/paneldx/blob/v0.6.0/validation/protocol/protocol.md)
- [Development roadmap](https://github.com/stemmatics/paneldx/blob/v0.6.0/ROADMAP.md)

## Contributing

See [CONTRIBUTING.md](https://github.com/stemmatics/paneldx/blob/v0.6.0/CONTRIBUTING.md). False positives are bugs: if `paneldx`
rejects a key you know is correct, that is worth an issue.

Release notes are in [CHANGELOG.md](https://github.com/stemmatics/paneldx/blob/v0.6.0/CHANGELOG.md).

## Citation

If you use `paneldx` in your research, please see [CITATION.cff](https://github.com/stemmatics/paneldx/blob/v0.6.0/CITATION.cff).

Releases are archived on Zenodo. The badge above is the **concept DOI**,
[10.5281/zenodo.22339487](https://doi.org/10.5281/zenodo.22339487), which always
resolves to the most recent archived release. Each release also receives its own
version DOI; cite that one when the exact version matters.

## License

Apache License 2.0. See [LICENSE](https://github.com/stemmatics/paneldx/blob/v0.6.0/LICENSE) and [NOTICE](https://github.com/stemmatics/paneldx/blob/v0.6.0/NOTICE).
