Skip to content
SlateGitOrgPublic

About

Finds lab results sent in the wrong unit by fitting each site against a reference shifted by known conversion factors, so a children's hospital with genuinely low creatinine is not flagged.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

unitslip

CI

unitslip

unitslip finds laboratory results that a site sent in the wrong unit. Instead of comparing each site's distribution with the rest and flagging whatever differs, it fits every site against a reference density shifted only by known conversion factors (glucose mg/dL to mmol/L, creatinine mg/dL to umol/L, and so on), so a children's hospital with genuinely low creatinine is not flagged. It reports which rows are affected, with a bootstrap interval per site and analyte, an onset date, and a corrected file with an audit trail. The data in this repository is synthetic.

The problem

Research networks and health information exchanges pool lab results from many hospitals. A site that sends glucose in mmol/L labelled mg/dL, hemoglobin in g/L labelled g/dL, or one analyzer that reports creatinine in umol/L silently corrupts every cohort built on the pool. Range checks catch some rows, but a whole site shifted by a factor still looks internally consistent, and naive distribution comparison flags sites whose patients genuinely differ, such as a children's hospital.

How it works

flowchart TD
    A[Lab results<br/>site, analyte, value, date] --> B[Pass 1: site median shift<br/>vs other sites' medians]
    B -->|"unit_shift: converted"| C[Reference density<br/>from rows believed canonical]
    B -->|consistent| C
    B -->|"unexplained_shift: never converted, left out of references"| X[Reported, not changed]
    C --> D[EM over the reference and<br/>the reference shifted by each factor]
    D --> E[Bootstrap 95% CI for pi<br/>per site-analyte]
    E --> F[Onset: least-squares<br/>changepoint on daily posterior]
    E --> G{Flagged rows<br/>changed?}
    G -->|yes, rebuild| C
    G -->|no| H[Fix: converted values<br/>with audit columns]
    F --> H
Loading
  1. Pass 1 compares each (site, analyte) log10 median with the median of the other sites' medians. A shift under 0.1 decades is consistent; a shift within 0.08 decades of +log10 of a known factor (the site's median sits above the others') is a unit_shift and the site is treated as converted; any other shift is unexplained_shift, which is never converted and is excluded from other sites' references. The rule is one-sided: a negative shift near -log10 of a factor (a site in the canonical unit while most other sites use the alternative) is also unexplained_shift.
  2. For each site and analyte, a leave-one-site-out reference density is built on log10 values from rows believed to be in the canonical unit (a 0.005-decade histogram smoothed with a Silverman-bandwidth Gaussian, interpolated linearly, with a density floor).
  3. EM fits mixing proportions over fixed components: the reference, and the reference shifted by each alternative factor. The components are not free, so the model can only explain mass sitting where a unit mistake would put it.
  4. Rows with a posterior of at least 0.9 are believed to be in the alternative unit. The reference is rebuilt with those rows converted and the fit repeated until the flagged rows stop changing (at most 5 iterations). --no-iterate stops after the first fit.
  5. A seeded bootstrap (200 resamples) gives a 95% interval for the alternative proportion; a site-analyte is flagged when the lower bound exceeds 0.01. The daily mean posterior of a flagged site-analyte gets one least-squares step function, which gives the onset date when the step is clear.
  6. fix converts flagged rows to the canonical unit. The output has three extra columns, original_value, original_unit_label and posterior. A row that was not converted keeps its original text as a prefix, followed by three empty fields. A converted row has value converted, unit_label set to the canonical unit, and the three columns filled in.

Verdicts in the scan table: consistent (not flagged), unit_shift (the whole site was a pass-1 unit shift and the fit confirms it), mixed_units (flagged by the bootstrap although pass 1 did not see a whole-site shift, so only some of the site's rows are in an alternative unit), unexplained_shift (never modelled) and insufficient_data.

Quick start

python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"

unitslip generate --seed 11 --out results.csv     # (git-ignored) also writes results.labels.csv (ground truth)
unitslip scan results.csv
unitslip explain results.csv --site S05 --analyte creatinine
unitslip fix results.csv --out corrected.csv
python scripts/demo.py                            # the whole flow, with the iterate comparison

scan, explain and fix accept --seed (bootstrap seed, default 11) and --no-iterate; scan --all also lists consistent site-analytes. Input columns: site_id, patient_id, analyte, value, unit_label, result_date, analyzer_id. The catalog is src/unitslip/analytes.yaml.

Example output

Output of python scripts/demo.py on the seeded synthetic data (8 sites, 5 analytes, 24,000 results, 2026-01-01 to 2026-04-30):

site  analyte     verdict            unit    median shift  pi-hat [95% CI]       onset
----  ----------  -----------------  ------  ------------  --------------------  ------------
S03   glucose     mixed_units        mmol/L        -0.051  0.342 [0.305, 0.377]  2026-03-21
S04   weight      mixed_units        lb            +0.065  0.346 [0.311, 0.388]  whole period
S05   creatinine  mixed_units        umol/L        +0.008  0.087 [0.068, 0.107]  whole period
S06   glucose     mixed_units        mmol/L        +0.008  0.108 [0.082, 0.135]  whole period
S07   hemoglobin  unit_shift         g/L           +1.005  1.000 [1.000, 1.000]  whole period
S08   creatinine  unexplained_shift  -             -0.318  -                     -
S08   weight      unexplained_shift  -             -0.554  -                     -

24000 rows, 40 site-analytes, 5 flagged, 1103 rows in an alternative unit
iterations: 3 (converged: yes)

S05 creatinine (mg/dL canonical), 600 rows
pass 1: log10 median -0.014 vs -0.022 for the other sites, shift +0.008 decades -> consistent
reference: 3600 rows from S01, S02, S03, S04, S06, S07 (bandwidth 0.0209 decades)
mixing proportions: canonical 0.913, umol/L 0.087
alternative proportion 0.087, 95% bootstrap interval [0.068, 0.107]
verdict: mixed_units (flagged)
rows converted (posterior >= 0.9): 52 of 600
converted rows by analyzer: S05-AZ2 52/52
onset: none detected (the mistake is spread over the whole period)

S06 glucose recall: 0.00 with --no-iterate, 1.00 with iteration (3 iterations)
fix: converted 1103 of 24000 rows

S08 is a children's hospital: its creatinine and weight shifts match no conversion factor, so they are reported as unexplained_shift and left alone. S02 is an endocrine clinic with 35% diabetic patients; its glucose is not flagged. S03's glucose median still looks consistent because only about a third of its rows are in mmol/L (from 2026-03-21), which is why a per-site median check alone misses it.

Design decisions

  • Fixed, shifted components instead of free ones. Each alternative component is the reference density moved by log10 of a known factor. A natural second mode (diabetic glucose) or a different population has no matching factor, so it cannot be absorbed as a unit mistake. The cost is that only mistakes in the catalog can be found.

  • Rebuild the reference from believed-canonical rows. A site left mislabelled in the pool hides the same mistake at other sites. In the demo, S03's mmol/L rows pollute the glucose reference so that a single pass recovers none of S06's mmol/L rows; iterating recovers all of them. The cost is several EM fits instead of one.

  • Unexplained sites stay out of every reference. A genuinely different population must not define normal for others, so unexplained_shift cells are never converted and never used. The cost is a smaller reference when many sites differ.

  • Log10 scale with a fixed 0.005-decade grid. Unit factors become additive shifts, and every reference shares a grid so shifting is an interpolation. Values must be positive; non-numeric or non-positive rows are ignored by the scan and left unchanged by fix.

  • Bootstrap for the flag, not a point estimate. A site-analyte is flagged only when the lower bound of its interval exceeds 0.01, which keeps a handful of tail rows from flagging a clean site. Resamples are seeded per site and analyte, so output is reproducible.

  • Single changepoint for onset. One step function is enough for a mistake that begins on a date, and it reports no onset when the series is flat (a mistake present all period). A mistake that switches on and off would need a richer model.

  • The unit_label column is not evidence. Detection looks only at values, so a row honestly labelled in an alternative unit is found only if its value looks shifted, and fix then sets its label to the canonical unit (the original is kept in original_unit_label). The synthetic data labels every row with the canonical unit.

Testing

pytest -q

63 tests pass. They cover conversion round trips for every pair, EM monotonicity and recovery of a known 70/30 mixture, the reference density, pass-1 classification, row-level precision and recall for each planted mistake, the interval per site, the S03 onset date, the contamination effect with and without iteration, determinism for a fixed seed, fix reversibility and the CLI.

Project layout

src/unitslip/
  catalog.py, analytes.yaml   analytes, canonical units, conversion factors
  data.py                     reading results CSV files
  generate.py                 seeded synthetic data with planted mistakes
  reference.py                binned, smoothed reference density
  sitescan.py                 pass 1 site median shifts
  mixture.py                  EM over fixed components
  iterate.py                  reference rebuild and fit loop, scan result
  bootstrap.py                bootstrap interval for the mixing proportion
  onset.py                    changepoint on the daily posterior
  fix.py                      conversion with audit columns
  report.py, cli.py           text tables and the command line
  __main__.py                 `python -m unitslip`
scripts/demo.py               full flow on synthetic data
tests/                        pytest suite

License

MIT, see LICENSE.

About

Finds lab results sent in the wrong unit by fitting each site against a reference shifted by known conversion factors, so a children's hospital with genuinely low creatinine is not flagged.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages