Metadata-Version: 2.4
Name: earlywarn
Version: 0.4.0
Summary: Computing clinical early warning scores (e.g. NEWS) on time‐series vital sign data
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=2.2.6
Requires-Dist: pandas>=2.2.3
Requires-Dist: polars>=1.30.0
Requires-Dist: scikit-learn>=1.5.0
Requires-Dist: pyarrow>=20.0.0
Requires-Dist: pyyaml>=6.0.2
Requires-Dist: rich>=14.0.0
Dynamic: license-file

# earlywarn – Early Warning Score Calculator

A Python library to compute Early Warning Scores (e.g. NEWS, MEWS, qSOFA) on tabular vital‐sign data, using Polars under the hood.

---

## 🌱 Features

**Core Scoring:**
- ✅ Accepts **Pandas** or **Polars** DataFrames, expected format is inspired by MIMIC datasets
- ✅ Pluggable rulesets (e.g. NEWS, custom YAML (`custom_ruleset_path` parameter))  
- ✅ Nullable‐aware scoring with configurable strictness  
- ✅ Returns per-parameter scores _and_ a combined `total_score`
- ✅ **Row-by-row scoring** capabilities for data streams with the stateful `EWSScorer` class
- ✅ **Score normalization** to 0-1 range based on available parameters
- ✅ **Imputation strategies** for missing values: forward-fill, mean, linear interpolation, MICE, KNN

**Feature Engineering:**
- ✅ **Rolling statistical features**: mean, std, variance, min, max, null counts/rates
- ✅ **Exponentially weighted moving averages** with configurable alpha
- ✅ **Trend analysis**: current difference to rolling mean, coefficient of variation
- ✅ **Threshold analysis**: counts above risk thresholds, mean crossings
- ✅ **Area Under Curve (AUC)** calculations with trapezoidal rule
- ✅ **Recovery time analysis**: average time to return below risk thresholds

Currently included rulesets: MEWS, ViEWS, NEWS, NEWS2, qSOFA, Worthing, GMEWS, CEWS, RAPS, SEWS —
plus GCS and SpO2-scale variants of MEWS, NEWS and NEWS2 (see [Ruleset Variants](#-ruleset-variants)).

---

## 💻 Installation

```bash
pip install earlywarn
```
```bash
uv add earlywarn
```
```bash
poetry add earlywarn
```

## 🚀 Quick Start

```python
from earlywarn.scoring.batch_score import score
import polars as pl 

# 1) Prepare your data:
df = pl.DataFrame({                         # Works just the same for pandas
    "id":                 [11, 12],         # Patient Encounter Ids
    "hr":                  [110, 120],      # Allows short names or long names (hr vs. heart_rate)
    "respiratory_rate":   [3,   None], 
    "temperature":        [37.5, 38.0],
    "systolic_bp":        [90,   80],
    "oxygen_saturation":  [95,   92],
    "avpu":               ["alert", "pain"],
    "clock":              [0,    1],        # time index if needed
})
┌─────┬─────┬──────────────────┬─────────────┬─────────────┬───────────────────┬───────┬───────┐
│ id  ┆ hr  ┆ respiratory_rate ┆ temperature ┆ systolic_bp ┆ oxygen_saturation ┆ avpu  ┆ clock │
│ --- ┆ --- ┆ ---              ┆ ---         ┆ ---         ┆ ---               ┆ ---   ┆ ---   │
│ i64 ┆ i64 ┆ i64              ┆ f64         ┆ i64         ┆ i64               ┆ str   ┆ i64   │
╞═════╪═════╪══════════════════╪═════════════╪═════════════╪═══════════════════╪═══════╪═══════╡
│ 11  ┆ 110 ┆ 3                ┆ 37.5        ┆ 90          ┆ 95                ┆ alert ┆ 0     │
│ 12  ┆ 120 ┆ null             ┆ 38.0        ┆ 80          ┆ 92                ┆ pain  ┆ 1     │
└─────┴─────┴──────────────────┴─────────────┴─────────────┴───────────────────┴───────┴───────┘

# 2) Compute scores:
scored = score(
    df, 
    ruleset_name="NEWS", 
    normalize=True,                 # Normalize the total score to a 0-1 range according to available parameters
    strict=False,                   # When strict=True, will error if any required column is missing
    aliases={"heart_rate":"hr"},    # Aliasing templates can be retrieved using earlywarn.rulesets.NEWS.get_alias_template()
    suppress_warnings=True
) 
┌─────┬───────┬─────┬───────────┬───────────┬───────────┬───────────┬──────┬───────────┬───────────┐
│ id  ┆ clock ┆ hr  ┆ respirato ┆ temperatu ┆ systolic_ ┆ oxygen_sa ┆ avpu ┆ NEWS_tota ┆ NEWS_tota │
│ --- ┆ ---   ┆ --- ┆ ry_rate   ┆ re        ┆ bp        ┆ turation  ┆ ---  ┆ l_score   ┆ l_score_n │
│ i64 ┆ i64   ┆ f64 ┆ ---       ┆ ---       ┆ ---       ┆ ---       ┆ f64  ┆ ---       ┆ ormalized │
│     ┆       ┆     ┆ f64       ┆ f64       ┆ f64       ┆ f64       ┆      ┆ f64       ┆ ---       │
│     ┆       ┆     ┆           ┆           ┆           ┆           ┆      ┆           ┆ f64       │
╞═════╪═══════╪═════╪═══════════╪═══════════╪═══════════╪═══════════╪══════╪═══════════╪═══════════╡
│ 11  ┆ 0     ┆ 1.0 ┆ 3.0       ┆ 0.0       ┆ 3.0       ┆ 1.0       ┆ 0.0  ┆ 8.0       ┆ 0.444444  │
│ 12  ┆ 1     ┆ 2.0 ┆ NaN       ┆ 0.0       ┆ 3.0       ┆ 2.0       ┆ 3.0  ┆ 10.0      ┆ 0.666667  │
└─────┴───────┴─────┴───────────┴───────────┴───────────┴───────────┴──────┴───────────┴───────────┘
```

### Alternatively use earlywarn's stateful scorer EWSScorer:

```python
from earlywarn.scoring.ews import EWSScorer

scorer = EWSScorer(
    ruleset_name="NEWS", # Optional, alternatively specify the used ruleset_name as a parameter in the score method to switch rulesets with ease
    aliases={
        "heart_rate": "hr",
    },
    normalize=True,  
    strict=False, 
    suppress_warnings=True,  
)

# Works the same as earlywarn.scoring.batch_score's score
res = scorer.score(df)
┌─────┬───────┬─────┬───────────┬───────────┬───────────┬───────────┬──────┬───────────┬───────────┐
│ id  ┆ clock ┆ hr  ┆ respirato ┆ temperatu ┆ systolic_ ┆ oxygen_sa ┆ avpu ┆ NEWS_tota ┆ NEWS_tota │
│ --- ┆ ---   ┆ --- ┆ ry_rate   ┆ re        ┆ bp        ┆ turation  ┆ ---  ┆ l_score   ┆ l_score_n │
│ i64 ┆ i64   ┆ f64 ┆ ---       ┆ ---       ┆ ---       ┆ ---       ┆ f64  ┆ ---       ┆ ormalized │
│     ┆       ┆     ┆ f64       ┆ f64       ┆ f64       ┆ f64       ┆      ┆ f64       ┆ ---       │
│     ┆       ┆     ┆           ┆           ┆           ┆           ┆      ┆           ┆ f64       │
╞═════╪═══════╪═════╪═══════════╪═══════════╪═══════════╪═══════════╪══════╪═══════════╪═══════════╡
│ 11  ┆ 0     ┆ 1.0 ┆ 3.0       ┆ 0.0       ┆ 3.0       ┆ 1.0       ┆ 0.0  ┆ 8.0       ┆ 0.444444  │
│ 12  ┆ 1     ┆ 2.0 ┆ NaN       ┆ 0.0       ┆ 3.0       ┆ 2.0       ┆ 3.0  ┆ 10.0      ┆ 0.666667  │
└─────┴───────┴─────┴───────────┴───────────┴───────────┴───────────┴──────┴───────────┴───────────┘
# Alternatively score row-by-row, eventually useful for datastreams:
scores = []
for row in df.iter_rows(named=True):
    scores.append(
        scorer.score_row(row)
    )
print(scores)

#[{'id': 11, 'clock': 0, 'hr': 1, 'respiratory_rate': 3, 'temperature': 0, 'systolic_bp': 3, 'oxygen_saturation': 1, 'avpu': 0, 'NEWS_total_score': 8, 'NEWS_total_score_normalized': 0.4444444444444444}, {'id': 12, 'clock': 1, 'hr': 2, 'respiratory_rate': nan, 'temperature': 0, 'systolic_bp': 3, 'oxygen_saturation': 2, 'avpu': 3, 'NEWS_total_score': 10, 'NEWS_total_score_normalized': 0.6666666666666666}]

scores_df = pl.DataFrame(scores)

┌─────┬───────┬─────┬───────────┬───────────┬───────────┬───────────┬──────┬───────────┬───────────┐
│ id  ┆ clock ┆ hr  ┆ respirato ┆ temperatu ┆ systolic_ ┆ oxygen_sa ┆ avpu ┆ NEWS_tota ┆ NEWS_tota │
│ --- ┆ ---   ┆ --- ┆ ry_rate   ┆ re        ┆ bp        ┆ turation  ┆ ---  ┆ l_score   ┆ l_score_n │
│ i64 ┆ i64   ┆ f64 ┆ ---       ┆ ---       ┆ ---       ┆ ---       ┆ f64  ┆ ---       ┆ ormalized │
│     ┆       ┆     ┆ f64       ┆ f64       ┆ f64       ┆ f64       ┆      ┆ f64       ┆ ---       │
│     ┆       ┆     ┆           ┆           ┆           ┆           ┆      ┆           ┆ f64       │
╞═════╪═══════╪═════╪═══════════╪═══════════╪═══════════╪═══════════╪══════╪═══════════╪═══════════╡
│ 11  ┆ 0     ┆ 1.0 ┆ 3.0       ┆ 0.0       ┆ 3.0       ┆ 1.0       ┆ 0.0  ┆ 8.0       ┆ 0.444444  │
│ 12  ┆ 1     ┆ 2.0 ┆ NaN       ┆ 0.0       ┆ 3.0       ┆ 2.0       ┆ 3.0  ┆ 10.0      ┆ 0.666667  │
└─────┴───────┴─────┴───────────┴───────────┴───────────┴───────────┴──────┴───────────┴───────────┘
```

## 🧭 Ruleset Variants

Some EWS define **alternative** ways of scoring the same thing. NEWS can take
consciousness from either AVPU or GCS, and NEWS2 defines two different SpO2 scales
depending on whether the patient has hypercapnic respiratory failure (e.g. COPD).

earlywarn models each combination as its **own ruleset** rather than putting conditional
logic inside one. Every ruleset therefore scores exactly one consciousness parameter and
exactly one oxygen scale -> nothing is ever counted twice, and the normalization
denominator is always correct. **You prefilter your cohort and score each group with the
matching variant.**

| Instrument | charts AVPU / ACVPU | charts GCS |
|---|---|---|
| MEWS | `MEWS` | `MEWS_gcs` |
| NEWS | `NEWS` | `NEWS_gcs` |
| NEWS2 — SpO₂ Scale 1 (most patients) | `NEWS2` | `NEWS2_gcs` |
| NEWS2 — SpO₂ Scale 2 (hypercapnic respiratory failure, target 88–92%) | `NEWS2_scale2` | `NEWS2_scale2_gcs` |

The remaining rulesets accept only one of the two and need no variant: `qSOFA`, `GMEWS`
and `RAPS` use GCS; `ViEWS`, `Worthing` and `SEWS` use AVPU.

> **Supply only the parameters your chosen variant defines.** If you pass both `avpu` and
> `gcs` to a ruleset that scores only one of them, the extra column is never added to the
> total — but it *is* passed through to the result **unscored**, as its raw value. A raw
> `gcs` of `3` then sits next to a scored `avpu` of `3.0` and looks deceptively like a
> second score. Drop the unused column beforehand, or pass
> `keep_only_scored_columns=True` to omit it from the output. Use
> `earlywarn.rulesets.NEWS2_gcs.get_parameters()` to see exactly what a variant expects.

### Example: Splitting a cohort across two variants

```python
import polars as pl
from earlywarn.scoring.batch_score import score

# Score COPD patients on Scale 2 and everyone else on Scale 1
scale1 = score(df.filter(~pl.col("has_copd")).drop("has_copd"),
               ruleset_name="NEWS2", normalize=True)
scale2 = score(df.filter(pl.col("has_copd")).drop("has_copd"),
               ruleset_name="NEWS2_scale2", normalize=True)
```

Score columns are named after the ruleset, so the two halves **do not share a schema** —
`scale1` has `NEWS2_total_score` while `scale2` has `NEWS2_scale2_total_score`, and a
naive `pl.concat` raises `ShapeError`. Rename before recombining:

```python
scale2 = scale2.rename({
    c: c.replace("NEWS2_scale2", "NEWS2") for c in scale2.columns if c.startswith("NEWS2_scale2")
})
combined = pl.concat([scale1, scale2]).sort("id", "clock")
```

The same pattern applies to AVPU vs GCS cohorts using `NEWS` and `NEWS_gcs`.

## 🧮 Continuous Scoring with Imputation

For real-time or sequential data processing, earlywarn provides stateful scoring with imputation strategies:

```python
# Continuous scoring with forward-fill imputation
continuous_scorer = EWSScorer(
    ruleset_name="NEWS",
    imputation_strategy="forward",  # Forward-fill missing values using last known values
    aliases={"heart_rate": "hr"},
    normalize=True
)

# Simulate a data stream - each data point processed sequentially
patient_stream = [
    {"id": 1, "clock": 0, "hr": 110, "respiratory_rate": None, "temperature": 37.5},
    {"id": 1, "clock": 1, "hr": None, "respiratory_rate": 20, "temperature": None},  # hr and temp will be forward-filled
    {"id": 1, "clock": 2, "hr": 105, "respiratory_rate": 18, "temperature": 38.0},
]

for data_point in patient_stream:
    score_result = continuous_scorer.score_row(data_point)
    print(f"Time {data_point['clock']}: Score = {score_result['NEWS_total_score']}")
    
# The scorer maintains state between calls, enabling proper imputation for missing values
```

## 📊 Feature Engineering

Earlywarn also provides advanced feature engineering capabilities for time-series analysis of vital signs and early warning scores:

```python
from earlywarn.features.features import rolling_features, rolling_area_under_the_curve, calculate_recovery_times

# Example time-series data
df_timeseries = pl.DataFrame({
    "id": [1, 1, 1, 1, 1, 2, 2, 2, 2],
    "clock": [0, 1, 2, 3, 4, 0, 1, 2, 3],
    "heart_rate": [80, 95, 105, 88, 75, 90, 110, 95, 85],
    "NEWS_total_score": [2, 4, 6, 3, 1, 3, 7, 4, 2] # Madeup for the purpose of this example
})

# Extract rolling statistical features
features_df = rolling_features(
    df_timeseries, 
    id_col="id", 
    clock_col="clock",
    cols=["NEWS_total_score"],
    rolling_window_size=3,
    risk_threshold=4  # Count scores above (>) 4 as "high risk"
)

# Calculate area under the curve for trending analysis
auc_df = rolling_area_under_the_curve(
    df_timeseries,
    id_col="id",
    clock_col="clock", 
    cols=["NEWS_total_score"]
)

# Analyze recovery patterns (time to return below threshold)
recovery_df = calculate_recovery_times(
    df_timeseries,
    id_col="id",
    clock_col="clock",
    cols=["NEWS_total_score"],
    risk_threshold=4
)
```

**Available feature types:**
- **Rolling statistics**: mean, std, variance, min, max across configurable windows
- **Exponentially weighted features**: trending with configurable decay
- **Threshold analysis**: counts above/below risk levels, duration analysis  
- **Trend detection**: mean crossings, coefficient of variation, current vs. baseline
- **Area Under Curve**: cumulative and rolling AUC calculations
- **Recovery metrics**: time to return to normal ranges, recovery frequency


## 🎯 Roadmap:

- Advanced Imputation Strategies
    - Tracability: include flagging for imputed values to signal which scores have been impacted by imputation
    - Paramter-specific imputation: Apply different imputation strategies for different vital parameters
- Visualization: 
    - Heatmap etc.
    - Gradio Dashboard
