Metadata-Version: 2.4
Name: ALOTT-MEDS
Version: 0.2.0
Summary: An ETL pipeline to extract the ALOTT (Carescape) EMR data into the MEDS format.
Author-email: Robin van de Water <rpv2114@cumc.columbia.edu>
Project-URL: Homepage, https://github.com/rvandewater/ALOTT_MEDS
Project-URL: Issues, https://github.com/rvandewater/ALOTT_MEDS/issues
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: <3.14,>=3.11.4
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: meds-extract[download]<0.10,>=0.9.2
Requires-Dist: sumeds<0.7,>=0.6.11
Dynamic: license-file

# ALOTT-MEDS

<!-- Placeholders until available: the PyPI badges resolve once ALOTT-MEDS is published; replace
CODECOV_TOKEN_PLACEHOLDER with the repo's Codecov badge token and zenodo.XXXXXXX with its Zenodo DOI. -->

[![PyPI - Version](https://img.shields.io/pypi/v/ALOTT-MEDS)](https://pypi.org/project/ALOTT-MEDS/)
[![codecov](https://codecov.io/gh/rvandewater/ALOTT_MEDS/graph/badge.svg?token=CODECOV_TOKEN_PLACEHOLDER)](https://codecov.io/gh/rvandewater/ALOTT_MEDS)
[![tests](https://github.com/rvandewater/ALOTT_MEDS/actions/workflows/synthetic-etl.yaml/badge.svg)](https://github.com/rvandewater/ALOTT_MEDS/actions/workflows/synthetic-etl.yaml)
[![code-quality](https://github.com/rvandewater/ALOTT_MEDS/actions/workflows/code-quality-main.yaml/badge.svg)](https://github.com/rvandewater/ALOTT_MEDS/actions/workflows/code-quality-main.yaml)
![python](https://img.shields.io/badge/python-%3E%3D3.11.4%2C%20%3C3.14-blue?logo=python&logoColor=white)
![Static Badge](https://img.shields.io/badge/MEDS-0.4.1-blue)
[![license](https://img.shields.io/badge/License-MIT-green.svg?labelColor=gray)](https://github.com/rvandewater/ALOTT_MEDS#license)
[![PRs](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/rvandewater/ALOTT_MEDS/pulls)
[![contributors](https://img.shields.io/github/contributors/rvandewater/ALOTT_MEDS.svg)](https://github.com/rvandewater/ALOTT_MEDS/graphs/contributors)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.23698073.svg)](https://doi.org/10.5281/zenodo.23698073)

ALOTT (ALarms, Outcomes Telemetry with Timing) is a pilot bedside-EMR database from two
hospitals, collected to support algorithms that predict emergency response team events. It
pairs bedside telemetry from 270 beds (alarms, monitor measurements and waveforms) with
electronic medical record data: admissions, diagnoses, ICU stays and bed moves, labs,
orders, medications and nursing flowsheets.
This pipeline extracts the EMR tables of ALOTT (from PhysioNet,
https://physionet.org/content/alott/) into the
[MEDS](https://github.com/Medical-Event-Data-Standard/meds) format. It is built the same way
as [MIMIC_IV_MEDS](https://github.com/Medical-Event-Data-Standard/MIMIC_IV_MEDS): one
declarative [MEDS-Extract](https://github.com/mmcdermott/MEDS_extract) spec, whose medication codes
end in their dose unit so that each code has a single `unit` String, and suMEDS's post-stages that
link and normalise those units (see [Codes](#codes) and [Code metadata](#code-metadata)).

## Usage:

```bash
pip install git+https://github.com/rvandewater/ALOTT_MEDS
export DATASET_DOWNLOAD_USERNAME=$PHYSIONET_USERNAME
export DATASET_DOWNLOAD_PASSWORD=$PHYSIONET_PASSWORD

meds-extract-run spec=ALOTT output_dir=$MEDS_OUTPUT_DIR
```

This one command runs the ETL and then enriches its code metadata with
[suMEDS](https://github.com/rvandewater/SumMEDS) (installed with this package): the spec ends with
suMEDS's `sumeds_enrich` stage, which fills the official ICD-10-CM titles and parents of the
diagnosis codes into `metadata/codes.parquet`. If it cannot (no internet, say), the ETL still
succeeds, unenriched, and `suMEDS-enrich $MEDS_OUTPUT_DIR` finishes it later. Add
`skip_stages=[sumeds_enrich]` for the plain ETL. See
[Enriching code metadata with suMEDS](#enriching-code-metadata-with-sumeds).

The run downloads only the `emr-datasets/` folder of the ALOTT 1.0.0 release (the telemetry is
skipped) into `$MEDS_OUTPUT_DIR/.meds_extract_run/raw_input` and runs the full MEDS-Extract
pipeline, writing `data/` and `metadata/` to `$MEDS_OUTPUT_DIR`. Files that already exist and
verify against PhysioNet's checksums are skipped, so an interrupted download resumes. Pass
`download_dest_dir=$RAW_INPUT_DIR` to keep the raw data somewhere durable.

ALOTT is a credentialed release: the PhysioNet account must have signed the ALOTT data use
agreement.

To reuse a download you already have, point `input_dir` at the directory that *contains*
`emr-datasets/`:

```bash
meds-extract-run spec=ALOTT output_dir=$MEDS_OUTPUT_DIR do_download=false input_dir=$RAW_INPUT_DIR
```

> [!NOTE]
> The folder the EMR CSVs sit in on PhysioNet, assumed to be `emr-datasets/`, has not been
> checked against a download. If your copy is a flat folder of the ten CSVs
> (`admission.csv`, `labs.csv`, ...), point `input_dir` at a directory holding an
> `emr-datasets` link to it.

Run `meds-extract-run --help` and `suMEDS-enrich --help` for the full set of arguments.

Intermediate stage outputs are deleted after a successful run, by default: the spec sets
MEDS-Extract's `etl.cleanup_intermediates: true`, so a finished `$MEDS_OUTPUT_DIR` holds only `data/`,
`metadata/`, `.logs/` and `.meds_extract_run/`. A failed run keeps them, so the same command resumes
where it stopped, and the same command on a finished output still does nothing. To keep them (to look
at a stage's output; `$MEDS_OUTPUT_DIR/.logs/pipeline.log` keeps the stage logs either way), add
`"overrides=['cleanup_intermediates=false']"`. Cleanup never deletes raw data: a download into the
default `$MEDS_OUTPUT_DIR/.meds_extract_run/raw_input` stays, and `download_dest_dir=` elsewhere lets other
output directories reuse it.

## Configuration

The whole pipeline is one file,
[`src/ALOTT_MEDS/event_configs.yaml`](https://github.com/rvandewater/ALOTT_MEDS/blob/main/src/ALOTT_MEDS/event_configs.yaml), written in MESSY
(MEDS-Extract Specification Syntax YAML) and registered under the `MEDS_extract.pipelines`
entry-point group as `ALOTT`. That registration is what makes `spec=ALOTT` work from anywhere
and what stamps the output's `metadata/dataset.json` with
`<ALOTT release>:<this package's version>`. The file holds:

- a `sources:` block pointing at the PhysioNet release, restricted to `emr-datasets/*`;
- an `etl:` block with the run's few knobs, what `metadata/dataset.json` says about the
    dataset, and the suMEDS enrichment stage that runs after the ETL;
- one block per raw EMR table describing the events extracted from it.

`metadata/dataset.json` gives the release's `license` and PhysioNet page (`description_uri`), and
lists `hadm_id`, the encounter key, under `raw_source_id_columns`. MEDS-Extract lists every other
extension column (`diagnosis_rank`, `flow_type`, `dose_unit`, ...) under `other_extension_columns`.

A second entry point registers
[`src/ALOTT_MEDS/sumeds_rules.yaml`](src/ALOTT_MEDS/sumeds_rules.yaml) with suMEDS under the same
name, which is how the spec's enrichment stage finds them (see
[Enriching code metadata with suMEDS](#enriching-code-metadata-with-sumeds)).

### Timestamps

ALOTT shifts each patient's dates by a random -180..180 days but keeps the time of day. Most
tables store each timestamp as one shifted `%Y-%m-%d %H:%M:%S` column. Labs and orders carry
only a shifted **date**, and medication start and end times are always `00:00:00`, i.e. dates
too. Those events are placed at the **end of that day (23:59:59)**: midnight would make a
result or a new medication visible before it existed, which leaks the future into any
prediction made later that day. Same-day lab orders and results therefore share a time.
Medication administrations keep their recorded time of day. A row with a null timestamp
produces no event.

Absolute dates are shifted per patient, so only differences *within* a subject are
meaningful.

### IDs

`aMRN` is the MEDS `subject_id`; the encounter key `aCSN` is carried as `hadm_id`. Lab and
order results use the resulting encounter, and orders the ordering one. The release
writes the string `nan` for an unresulted encounter; it is cast leniently, so it becomes a
null and `hadm_id` stays `Int64`.

### Codes

Every code is `FAMILY//...`, from general to specific, so a prefix selects a group (all
labs, one lab panel, one drug). Where a table records both an order and its outcome, the
second component says which: `ORDERED` or `RESULT`, `START` or `END`, or `MAR`
(Medication Administration Record: the bedside log of each dose given, held or refused).
`UNK` stands for a null component that must not drop the row (see
[Null handling](#null-handling)).

A code has one unit. Start and administration codes always end in the dose unit as recorded
(`HV_DISCRET_DOSE_UNIT`, `MAR_DOSE_UNIT`): `MEDICATION//START//<drug>//<dose unit>` and
`MEDICATION//MAR//<drug>//<action>//<dose unit>`. The unit is stripped of surrounding whitespace, and
a row that records none or a blank one gets `UNK`, as `UNK` marks a missing component everywhere else
in this ETL; this matches how MEDS-Extract compares units when it writes `unit` (stripped, blanks
dropped), so ` mg` and `mg` give one code. The action is kept as recorded. A code then has one unit by construction,
whatever units a drug is ordered or given in, and the spec needs no stage of its own to find the
drugs that mix units. Where a drug's starts (or its administrations with one action) are recorded
in several units, or also without one, the code without the unit stays in `metadata/codes.parquet`,
without events, as the parent of its per-unit codes (see [Code metadata](#code-metadata)); it stands
for the drug in any unit. `MEDICATION//END` codes have no dose and do not end in a unit.

| Code                                             | Table        | Time                  | Value and extra columns                                                                |
| ------------------------------------------------ | ------------ | --------------------- | -------------------------------------------------------------------------------------- |
| `HOSPITAL_ADMISSION//<admission type>//<source>` | admission    | admission             | reason for visit in `text_value`                                                       |
| `HOSPITAL_DISCHARGE//<destination>`              | admission    | discharge             |                                                                                        |
| `DIAGNOSIS//ICD//10CM//<ICD-10-CM code>`         | admission    | discharge             | diagnosis text; `diagnosis_rank` `PRIMARY` or `SECONDARY`                              |
| `<FIELD>//<value>`                               | demographics | static                | `FIELD` is `GENDER`, `MARITAL_STATUS`, `RACE`, `ETHNICITY`, `LANGUAGE` or `BLOOD_TYPE` |
| `ALLERGY//<allergen>`                            | allergy      | static                | reaction in `text_value`                                                               |
| `FLOWSHEET//<FLO_MEAS_ID>`                       | flowsheet    | recorded              | reading or score; `flow_type`                                                          |
| `ICU_ADMISSION`, `ICU_DISCHARGE`                 | icu          | start, end            |                                                                                        |
| `TRANSFER`                                       | location     | start                 |                                                                                        |
| `MEDICATION//START//<drug>//<dose unit>`         | medications  | start date, 23:59:59  | ordered dose (raw text if a range); `dose_unit`, `frequency`                           |
| `MEDICATION//END//<drug>`                        | medications  | end date, 23:59:59    |                                                                                        |
| `MEDICATION//MAR//<drug>//<action>//<dose unit>` | medications  | administration        | given dose; `dose_unit`, `route`                                                       |
| `LAB//ORDERED//<PROC_ID>`                        | labs         | order date, 23:59:59  |                                                                                        |
| `LAB//RESULT//<PROC_ID>//<component>`            | labs         | result date, 23:59:59 | result; `order_status`                                                                 |
| `ORDER//ORDERED//<order type>//<PROC_ID>`        | orders       | order date, 23:59:59  | `order_status`                                                                         |
| `ORDER//RESULT//<order type>//<PROC_ID>`         | orders       | result date, 23:59:59 | result; `order_status`                                                                 |

### Code metadata

`metadata/codes.parquet` gives every code a `description`, except diagnoses (see
[Diagnoses](#diagnoses)), which suMEDS describes (see
[Enriching code metadata with suMEDS](#enriching-code-metadata-with-sumeds)). All of them come
from `_metadata: _self:` blocks in the spec, evaluated on the extracted rows:

| Codes                                                                                             | Description                                                                                                                              |
| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `FLOWSHEET//...`, `LAB//...`, `ORDER//...`                                                        | the release's own display names: `disp_name` (else `flo_meas_name`) for flowsheets; `DESCRIPTION`, plus `COMPONENT_NAME` for lab results |
| `HOSPITAL_ADMISSION`, `HOSPITAL_DISCHARGE`, the six demographic families, `ALLERGY`, `MEDICATION` | the code's own components, each named with the column it comes from, e.g. `Patient sex/gender: M (ALOTT demographics.Gender)`            |
| `ICU_ADMISSION`, `ICU_DISCHARGE`, `TRANSFER`                                                      | a fixed text saying what the event marks and that the release records no unit, room or bed                                               |

`unit` is a String: the unit of the code's numeric values, one per code (null where there is none),
written in [UCUM](https://ucum.org/) by suMEDS's `sumeds_normalize_units` post-stage (`units` becomes
`{units}`). The spelling as the release records it stays in `unit_source_value`, a spelling suMEDS
does not know is kept as it is, and the codes keep their names (`MEDICATION//START//<drug>//units`
stays). Medication codes carry it from
`HV_DISCRET_DOSE_UNIT` (`MEDICATION//START`) and `MAR_DOSE_UNIT` (`MEDICATION//MAR`), which is also
the code's last component, so that downstream tools read a code's unit from
one place; the
`dose_unit` column keeps the per-event value as recorded. The release records no unit for flowsheets, labs or
orders, and its documentation states none, so those codes have a null `unit`. Their descriptions
(the release's display names) do not state units in a form that can be read off either: on the
1.0.0 release, 5 of the 9,356 flowsheet, lab and order codes end in a bracketed token that is a
known unit, 3 of those are single letters or on codes without values, so none is taken.

MEDS-Extract (0.9 and later) writes `unit` as one String per code: blanks are stripped and empty
entries dropped, units are otherwise kept as recorded, and the run fails, naming the codes, if a code
has more than one unit. The spec's first post-stage, suMEDS's
[`sumeds_link_unit_siblings`](https://github.com/rvandewater/suMEDS/blob/main/docs/unit_siblings.md)
then links unit siblings, codes that differ only in their last
component, which is their `unit` (one drug given in `mg` and in `g`): each gets the code without the
unit (its stem) in `parent_codes`, and the stem gets a row of its own with the siblings' shared
description (or the same one but for the unit each states, which is left out), the parents they all
share and no `unit`. A stem has no events. In this ETL the siblings are the start (administration)
codes of one drug (and action) in different units (above), and a code of the same item whose unit
was not recorded (`…//UNK`) joins them. With `link_single_units: true` and
`unknown_unit_prefixes: [MEDICATION//START//, MEDICATION//MAR//]`, a code ending in its unit gets its
stem also when its drug has a single unit, and so does a start or MAR code without a recorded dose
unit (`MEDICATION//START//{drug}//UNK`), so every start pairs with its `MEDICATION//END//{drug}` by
stem. It runs before `sumeds_normalize_units`. This shared stage replaced the package's own `alott_unit_metadata`
(suMEDS 0.6.6); `suMEDS-link-unit-siblings $MEDS_OUTPUT_DIR` runs the same step on an existing build.

What each column means follows the table descriptions on the
[ALOTT 1.0.0 PhysioNet page](https://physionet.org/content/alott/1.0.0/) and the column names
in the authors' release code ([Carescape](https://github.com/johnclawrence/Carescape), MIT);
the descriptions paraphrase them and copy no text.

The three constant codes (`ICU_ADMISSION`, `ICU_DISCHARGE`, `TRANSFER`) are plain literals:
MEDS-Extract 0.8.1 and later attach `_self` metadata to literal codes
([MEDS_extract#166](https://github.com/mmcdermott/MEDS_extract/issues/166)), and a row whose
time is null yields no event.

Apart from unit-sibling stems, the ETL writes no `parent_codes`. The only standard vocabulary in the EMR tables is
ICD-10-CM, and diagnoses cannot carry metadata (below), so their ICD-10-CM parents come from
suMEDS. Labs and orders are keyed by Epic procedure IDs,
flowsheets by Epic flowsheet IDs and medications by name; the release has no LOINC, RxNorm or
NDC column.

### Null handling

A null component of a composite code drops the row under MEDS-Extract 0.8. Components are
therefore coalesced with `?? 'UNK'` wherever a null must not drop the row (admission type and
source, discharge destination, lab component, order type, medication administration action).

The rest are deliberately left uncoalesced. In the release, the code columns of
flowsheets, labs, orders and allergies are never null, and `MEDICATION` is null in 10 of
12,698,867 rows, so a coalesce would add nothing. A missing ICD-10 code or demographic
produces no event rather than an `UNK` category, because a missing value is not an observed
one.

### Diagnoses

The primary and secondary ICD-10 codes on each visit become `DIAGNOSIS//ICD//10CM//<code>`
events at discharge time, with `diagnosis_rank` set to `PRIMARY` or `SECONDARY`. About 4% of
cells list up to four codes separated by a comma and a space; each code becomes its own event, carrying the
cell's full diagnosis text. No `_metadata` is attached, so diagnosis codes have neither a
`description` nor `parent_codes`: each list position of each column is its own code template,
one code occurs under several of them (as primary and as secondary, at different positions),
and MEDS-Extract 0.8 rejects a code produced by two metadata-carrying code templates.
The codes are dotted ICD-10-CM codes, so `DIAGNOSIS//ICD//10CM//<code>` maps to
`ICD10CM//<code>` directly, and suMEDS adds their titles and parents (below).

### Enriching code metadata with suMEDS

Vocabulary work is maintained once, in [suMEDS](https://github.com/rvandewater/SumMEDS), rather
than in every ETL. This package ships the rules for it,
[`src/ALOTT_MEDS/sumeds_rules.yaml`](src/ALOTT_MEDS/sumeds_rules.yaml), registered in suMEDS's
`sumeds.rules` entry-point group under the same name as the MEDS-Extract spec, `ALOTT`, so
`--rules ALOTT` works for any suMEDS command. The spec runs them as its last stage, after suMEDS's
`sumeds_link_unit_siblings` and `sumeds_normalize_units`, so that suMEDS sees the final table (and a later `suMEDS-enrich` gives the
same result):

```yaml
etl:
  post_stages:
    - sumeds_link_unit_siblings:
        link_single_units: true
        unknown_unit_prefixes: [MEDICATION//START//, MEDICATION//MAR//]
    - sumeds_normalize_units
    - sumeds_enrich: {rules: ALOTT}
```

suMEDS keeps existing `parent_codes`, including the in-dataset unit-sibling stems: it reads each
entry as a possible `VOCABULARY//CODE` reference, finds no pack or Athena vocabulary named
`MEDICATION` and leaves the entry as it is.

The stage replaces `metadata/codes.parquet` only once the enriched table is complete, and it stays
valid MEDS code metadata. By default the ICD-10-CM data comes from suMEDS's ontology packs, fetched
from GitHub on first use and cached; no Athena download is needed.

`metadata/dataset.json` says whether a build is enriched: `sumeds_enrichment.enriched` is `true`
(with the rules, pack source and coverage) or `false` (with the error and the `retry` command).

```bash
jq .sumeds_enrichment.enriched $MEDS_OUTPUT_DIR/metadata/dataset.json
```

Enrichment soft-fails: if it cannot run (a server without internet, for example), the ETL still
succeeds with `metadata/codes.parquet` left as the ETL wrote it, and `dataset.json`
records `"enriched": false`. The warning, with the command that finishes the enrichment, is in
`$MEDS_OUTPUT_DIR/.logs/pipeline.log`, not on the console. MEDS-Extract marks the stage done either
way, so running `meds-extract-run` again does not retry it. Enrich the build afterwards, with the
rules and options of the failed run:

```bash
suMEDS-enrich $MEDS_OUTPUT_DIR
# Air-gapped: from a copy of the sumeds-ontologies packs directory
suMEDS-enrich $MEDS_OUTPUT_DIR --ontology-source /path/to/sumeds-ontologies/ontologies --offline
```

For the plain, unenriched ETL, leave the stage out with `skip_stages=[sumeds_enrich]`:

```bash
meds-extract-run spec=ALOTT output_dir=$MEDS_OUTPUT_DIR skip_stages=[sumeds_enrich]
```

The stage takes the `suMEDS-enrich` options, spelled with underscores. Set them for one run with
`overrides=`, as `++stage_cfg.<option>` (the override reaches every stage of the pipeline, and only
this one declares the option, hence the `++`):

```bash
# Make a failed enrichment fail the run (exit code 1):
meds-extract-run spec=ALOTT output_dir=$MEDS_OUTPUT_DIR "overrides=['++stage_cfg.strict=true']"
# Also look codes up in your own OHDSI Athena download:
meds-extract-run spec=ALOTT output_dir=$MEDS_OUTPUT_DIR "overrides=['++stage_cfg.athena_csv=/path/to/athena']"
# Read the packs from a local copy (or set SUMEDS_ONTOLOGY_SOURCE=/path/to/ontologies):
meds-extract-run spec=ALOTT output_dir=$MEDS_OUTPUT_DIR "overrides=['++stage_cfg.ontology_source=/path/to/ontologies']"
```

On a cluster whose compute nodes have no internet access, fill a cache on shared storage once from
a login node, then run with `offline`, so nothing tries the network:

```bash
export XDG_CACHE_HOME=/shared/project/cache # on the login node and the compute nodes
suMEDS-enrich --prefetch --rules ALOTT      # login node: the pinned pack release, about 30 MB
meds-extract-run spec=ALOTT output_dir=$MEDS_OUTPUT_DIR "overrides=['++stage_cfg.offline=true']"
```

Diagnosis codes are validated against suMEDS's versioned ontology data (sumeds-ontologies,
pinned release), built from the CDC/NCHS ICD-10-CM files. The rules add:

- `alott-icd10cm-diagnoses`: each `DIAGNOSIS//ICD//10CM//<code>` with the dotted ICD-10-CM shape
    that is a valid ICD-10-CM code gets the official title as its `description`, and
    `ICD10CM//<code>` followed by its ICD-10-CM ancestors as `parent_codes`, with the title of
    each in `parent_names`.
- `alott-diagnosis-parents-in-dataset`: same-dataset parents. A diagnosis code also gets the
    nearest ICD-10-CM ancestor that is itself an ALOTT diagnosis code, e.g.
    `DIAGNOSIS//ICD//10CM//I50.2` for `DIAGNOSIS//ICD//10CM//I50.23`.

suMEDS fills only missing descriptions, never removes or rewrites existing metadata, and writes
parents as `VOCABULARY//CODE`. The other code families keep the descriptions the spec gives them
and get no parents: none of them is a standard vocabulary. `parent_names` is a map from each parent
code to its name (suMEDS 0.6 and later), stored in Parquet as `map<string, string>`, which Polars 2
reads as `pl.Map` and Polars 1 as a list of `key`/`value` structs. The plain ETL
(`skip_stages=[sumeds_enrich]`) emits no diagnosis descriptions or parent codes. The same rules work with
`suMEDS … --rules ALOTT` to build a privacy-masked code catalog of the output.

### Other tables

- **ICU stays and bed moves** carry only their start and end times in the release (no unit,
    room or bed), so they become bare `ICU_ADMISSION`, `ICU_DISCHARGE` and `TRANSFER`
    events.
- **Demographics and allergies** carry no time in the release and are static events.
- **Flowsheet, lab and order-result values** are free text. The numeric reading is kept where
    it parses; scored flowsheet items charted as `<score>--><label>` (e.g. `-1-->Drowsy`) keep
    their score. The raw string goes to `text_value` unless it is just the number. Epic's
    nonnumeric sentinel `9999999` never becomes a numeric value.
- **Medications:** each row of the release is one administration and repeats its order's
    start and end, so an order yields one `START`, one `END` and one `MAR` event per
    administration.
- **Orders** hold every order type except labs; roughly half carry a single result.
- **Birth and death:** the release has no birth date, age or death time, so there are no
    `MEDS_BIRTH` or `MEDS_DEATH` events.
- **Not extracted:** the telemetry (alarms, 2-second measurements, waveforms; per-admission
    files keyed by file name, far larger than the EMR), `social_hx` (no event times and
    unlabeled Epic category codes), and the medication order date.

### Validation against the release

The spec was first written from the authors' release code
([Carescape](https://github.com/johnclawrence/Carescape)) and did not run on the published
files. Profiling the 1.0.0 EMR CSVs (value *shapes* and null counts only, never values)
showed what had to change:

- Tables are lowercase (`admission`, `labs`, ...) rather than `Patient`, `Labs`, ...; the
    keys are `aMRN` and `aCSN`, not `csID` and `CS_PAT_ENC_CSN_ID`.
- Each timestamp is one already-shifted column rather than a date plus an `HH:MM:SS`
    column. Labs and orders keep only the date (see [Timestamps](#timestamps)).
- `icu` and `location` have no department, event type, room or bed columns.
- `resulting_aCSN` holds the string `nan` for unresulted rows.
- 1,536 ICD-10 codes occur as both primary and secondary diagnoses, and some cells list
    several codes (see [Diagnoses](#diagnoses)). The synthetic test covers both.
- Medication start and end times are always midnight, and `orders` carries results of its
    own (it holds no lab orders).

All ten CSVs are valid UTF-8, which is what MEDS-Extract 0.8's default encoding detection
(`etl.encoding: auto`) reads them as. On the full 1.0.0 EMR tables (6.3 GB of CSVs read),
`meds-extract-run` with MEDS-Extract 0.7.1 finishes in about 90 seconds on a laptop with about
6.5 GB peak memory, producing 52.6M events for 18,472 subjects. Fewer lab, order and
medication start/stop events come out than raw rows because identical events are merged: lab
and order times have day resolution, and the medication table repeats an order's start and
end on every administration row.

## MEDS-transforms settings

If you want to convert a large dataset, you can parallelize the MEDS-transforms stages
(the MEDS-transformation step that takes the longest).

Using local parallelization with the `hydra-joblib-launcher` package:

```bash
pip install hydra-joblib-launcher --upgrade
```

Then write a stage-runner file and pass it to the run:

```yaml
# runner.yaml
parallelize:
  n_workers: 8
  launcher: joblib
```

```bash
meds-extract-run spec=ALOTT output_dir=$MEDS_OUTPUT_DIR stage_runner_fp=runner.yaml
```

The number of subjects per shard is `n_subjects_per_shard` in the spec's `etl:` block
(1000 by default); raise it to cut the parallelization overhead.

## Summary statistics

[`tests/regression/full_summary_stats.json`](tests/regression/full_summary_stats.json) is a
[meds_summary_stats](https://github.com/Medical-Event-Data-Standard/meds_summary_stats) fingerprint of
the MEDS dataset this ETL builds from the full ALOTT 1.0.0 release with `meds-extract-run spec=ALOTT`,
so its code-metadata coverage includes the suMEDS enrichment. It covers subject, event and measurement
counts, digests of the code vocabulary, per-subject, value and time distributions, code-metadata
coverage, the splits and the schema. It names no code and reports no cell of fewer than 20 subjects and
no minimum or maximum, which is what makes it safe to publish. Because it is committed next to the ETL,
its diff shows what an ETL change did to the output, and two ETL versions can be compared without
access to the data.

Regenerate it in every pull request that changes the output, from a build of that branch:

```bash
# Build the release with this checkout, then summarize it
scripts/summary_stats.sh full --input-dir $RAW_INPUT_DIR
# Or summarize a build of this checkout you already have
scripts/summary_stats.sh full --meds-dir $MEDS_OUTPUT_DIR
```

Both print how the statistics changed against the committed baseline before overwriting it, and
refuse a build whose enrichment failed (finish it with `suMEDS-enrich` first). Add
`--compare` to check a build without writing anything; it exits 1 when
[`tests/regression/policy.yaml`](tests/regression/policy.yaml) flags an error. Rebuilding the same
commit reproduces the baseline exactly, so any finding is a change in the output. CI cannot rebuild the
credentialed release, so the [Summary stats workflow](.github/workflows/summary-stats.yaml) only warns
when a pull request changes `src/` (the spec or the suMEDS rules) without regenerating the baseline. A
MEDS-Extract, suMEDS or polars upgrade can also move the output, so check it with `--compare`.

## Development

```bash
uv sync --group dev
uv run pytest tests/ src/ --doctest-modules
uv run pre-commit run --all-files
```

A release bumps the version in `pyproject.toml` with `uv version --bump`, commits it and pushes
a tag of that exact version, which publishes to PyPI and creates the GitHub release. See [`RELEASING.md`](https://github.com/rvandewater/ALOTT_MEDS/blob/main/RELEASING.md) for choosing the
version, the one-time PyPI setup and recovering from a failed release.

ALOTT has no open demo, so CI runs the spec end to end over a small **synthetic** input
generated in [`tests/e2e_synthetic_test.py`](https://github.com/rvandewater/ALOTT_MEDS/blob/main/tests/e2e_synthetic_test.py), and
[`tests/test_run_with_enrichment.py`](tests/test_run_with_enrichment.py) runs
`meds-extract-run spec=ALOTT` over the same input with its enrichment stage against a tiny synthetic
ontology pack, offline, and without the stage (`skip_stages`), and against an empty pack source, to
check the soft failure, its `suMEDS-enrich` retry and `strict`.
[`tests/test_sumeds_rules.py`](tests/test_sumeds_rules.py) checks that the rules are registered as
`ALOTT` and match the diagnosis codes the spec writes. Both build on suMEDS's shared contract tests
(`sumeds.testing.contracts`, see suMEDS's
[Testing an ETL](https://github.com/rvandewater/suMEDS/blob/main/docs/testing.md)), so they only state
what is ALOTT's own: the synthetic packs and the codes and parents it expects. These check the spec's
mechanics, not its agreement with the real release. Never commit raw ALOTT data or MEDS output derived
from it.

## Breaking changes

### 0.2.0 (2026-11-20)

- Rebuilt on the full release; `tests/regression/full_summary_stats.json` regenerated.

- **`unit` in `metadata/codes.parquet` is written in UCUM**, by suMEDS's `sumeds_normalize_units`
    post-stage (`units` becomes `{units}`), and the new column `unit_source_value` keeps the spelling
    the release records. A spelling suMEDS does not know is kept as it is. Codes, events and the
    per-event `dose_unit` are unchanged; only the `unit` column of `codes.parquet` changes. To
    migrate, read `unit_source_value` where you read `unit` before.

- **Intermediate stage outputs are no longer kept.** Up to 0.1.0, a run left each stage's output in
    `<output_dir>/<stage>/` (`convert_to_parquet/`, `convert_to_MEDS_events/`, `alott_unit_keys/`, `sumeds_enrich/`, …). The spec now sets MEDS-Extract's
    `etl.cleanup_intermediates: true`, so a successful run deletes those directories and keeps only
    `data/`, `metadata/`, `.logs/` and `.meds_extract_run/`. The MEDS data and metadata are
    unchanged. To migrate, add `"overrides=['cleanup_intermediates=false']"` to `meds-extract-run`
    wherever you read a stage directory after the run.

- **`codes.parquet` gains unit-free stem rows and stem parents for single-unit codes**
    ([#20](https://github.com/rvandewater/ALOTT_MEDS/pull/20)). suMEDS's `sumeds_link_unit_siblings` now runs with `link_single_units: true`:
    every code that ends in its unit gets the code without the unit (its stem) as its last
    `parent_codes` entry, and the stem gets a row of its own (no unit, no events), also when the
    item has a single unit (`MEDICATION//START//{drug}//{unit}` gets `MEDICATION//START//{drug}`, `MEDICATION//MAR//{drug}//{action}//{unit}` gets `MEDICATION//MAR//{drug}//{action}`). Before, only items recorded in two or more units did. A start or MAR code without a recorded dose unit (`…//UNK`) gets its stem too (`unknown_unit_prefixes`).
    Events are unchanged. On a synthetic (MESSY-synth) build, 51 codes gain a stem parent and 51 stem rows are added (48 `MEDICATION//MAR`, 3 `MEDICATION//START`), and all 13 starts pair with their end by stem (10 before). To migrate, nothing is needed unless a tool expects every
    `codes.parquet` row to have events: drop the stem rows (no `code_template`, no `unit`), or
    ignore a parent that is the code without its last `//` component.

- **Every start and administration code ends in its dose unit**: `MEDICATION//START//<drug>//<dose unit>`
    and `MEDICATION//MAR//<drug>//<action>//<dose unit>`, with the unit stripped of surrounding whitespace
    and `//UNK` for a row that records no unit or a blank one.
    Before, only the codes whose rows recorded more than one unit ended in it, which took a package
    pre-stage (`alott_unit_keys`, now removed) and two side tables to decide; now every code has one
    unit by construction, and suMEDS's `sumeds_link_unit_siblings` still gives the code without the
    unit as a parent where a drug (and action) has several units or also rows without one. On the 1.0.0
    release, the 24,340 of the 25,606 start and administration codes that did not end in a unit gain one
    (the exact new counts need a credentialed rebuild); the 1,266 codes split by unit before, now the
    per-unit codes' parents, keep that role. On a synthetic MESSY-synth build, 147 of 292 codes change
    name (75 of 146 starts, 72 of 146 administrations) and become 154: a code whose rows mix one unit
    with none becomes `…//<unit>` and `…//UNK` (7 codes), with the old code as their parent. Events,
    values, times and each code's `unit`, `unit_source_value`, description and other parents are
    unchanged; `MEDICATION//END` codes are unchanged.

    | Old                                    | New                                                               |
    | -------------------------------------- | ----------------------------------------------------------------- |
    | `MEDICATION//START//<drug>`            | `MEDICATION//START//<drug>//<dose unit>`, or `…//UNK` without one |
    | `MEDICATION//MAR//<drug>//<action>`    | `MEDICATION//MAR//<drug>//<action>//<dose unit>`, or `…//UNK`     |
    | `…//<dose unit>` (codes split by unit) | unchanged                                                         |

    The unit cannot be derived from the old code, so migrate by comparing without it: strip the last
    component (`^(MEDICATION//(START|MAR)//.*)//.*$` → `\1`, the greedy group ending at the last `//`)
    to compare with an old single-unit code, or match all codes of a drug in both spellings with
    `^MEDICATION//START//<drug>(//.*)?$`. Code lists that named a code without a unit either add the
    units it is recorded in or name the stem and follow `parent_codes`.

- **Order end codes use `END`, not `STOP`** ([alignEHR#53](https://github.com/rvandewater/alignEHR/issues/53)):
    `MEDICATION//STOP//<drug>` is now `MEDICATION//END//<drug>`, the spelling all MEDS ETLs move to for the
    two ends of an interval, `<FAMILY>//START//…` and `<FAMILY>//END//…`. Start codes, events and code
    metadata are otherwise unchanged. A start code ends in its dose unit (see [Codes](#codes)); to pair a
    start with its end, drop that unit and swap `START` for `END`.

    | Old                        | New                       |
    | -------------------------- | ------------------------- |
    | `MEDICATION//STOP//<drug>` | `MEDICATION//END//<drug>` |

    To migrate, rewrite old codes with the regex `^MEDICATION//STOP//` → `MEDICATION//END//`.

- **ICD codes name the vocabulary and its edition apart, `ICD//<edition>//<code>`.** Diagnoses
    `DIAGNOSIS//ICD//10//<code>` are now `DIAGNOSIS//ICD//10CM//<code>`, the layout every MEDS ETL of
    this family uses for ICD (`ICD//10CM`, `ICD//9CM`, `ICD//10PCS`, `ICD//10GM`, `ICD//10CN`). The code
    after the edition is unchanged (dotted, as ALOTT records it), and so is its `ICD10CM//<code>` parent.
    To migrate, rename codes with the regex `^DIAGNOSIS//ICD//10//` → `DIAGNOSIS//ICD//10CM//`.

## Citation

Please cite the following original dataset when using ALOTT:

```bibtex
@article{PhysioNet-alott-1.0.0,
  author = {Lawrence, John and Rayo, Mike and Huerta, Timothy},
  title = {{ALarms, Outcomes Telemetry with Timing (ALOTT): a Bedside-EMR Database}},
  journal = {{PhysioNet}},
  year = {2025},
  month = mar,
  note = {Version 1.0.0},
  doi = {10.13026/sbq5-dy17},
  url = {https://doi.org/10.13026/sbq5-dy17}
}
```

Also cite the ETL framework used to extract the dataset:

```bibtex
@software{van_de_water_2026_alott_meds,
  author       = {van de Water, Robin},
  title        = {ALOTT MEDS ETL},
  version      = {0.1.0},
  month        = nov,
  year         = 2026,
  publisher    = {Zenodo},
  doi          = {10.5281/zenodo.23698073},
  url          = {https://doi.org/10.5281/zenodo.23698073},
}
```

(also check the "Cite this repository" link on this repo's main page for the latest version)

For citing MEDS in general:

```bibtex
@article{mcdermott2026meds,
  title={MEDS—An Emerging Data Standard and Ecosystem for Health AI Research},
  author={McDermott, Matthew BA and Steinberg, Ethan and Fries, Jason A and van de Water, Robin P and Pang, Chao and Rockenschaub, Patrick and Renc, Pawel and Oh, Jungwoo and Stankevi{\v{c}}i{\=u}t{\.e}, Kamil{\.e} and Xu, Justin and others},
  journal={NEJM AI},
  volume={3},
  number={6},
  pages={AIra2501253},
  year={2026},
  publisher={Massachusetts Medical Society}
}
```
