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_pathparameter)) - ✅ 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
EWSScorerclass - ✅ 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).
💻 Installation
pip install earlywarn
uv add earlywarn
poetry add earlywarn
🚀 Quick Start
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:
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
avpuandgcsto 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 rawgcsof3then sits next to a scoredavpuof3.0and looks deceptively like a second score. Drop the unused column beforehand, or passkeep_only_scored_columns=Trueto omit it from the output. Useearlywarn.rulesets.NEWS2_gcs.get_parameters()to see exactly what a variant expects.
Example: Splitting a cohort across two variants
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:
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:
# 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:
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
Metadata
Release files for earlywarn 0.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| earlywarn-0.4.0.tar.gz | 52.3 kB | Without provenance | Details for earlywarn-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| earlywarn-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for earlywarn-0.4.0-py3-none-any.whl |
Total release size: 89.2 kB
Release files / earlywarn-0.4.0.tar.gz
| Download URL | earlywarn-0.4.0.tar.gz |
|---|---|
| Size | 52.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
fbf606fae5aaadec58e4f6a01be1e3f517eb7e6652583aab95afd1aade612fb0
|
|
BLAKE2b-256 checksum How to use checksums |
960f1860dacf318ff139ede563648a1df735e33f4da80ae0486d5e1454dd3b53
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.7.6
|
Release files / earlywarn-0.4.0-py3-none-any.whl
| Download URL | earlywarn-0.4.0-py3-none-any.whl |
|---|---|
| Size | 36.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
36e17c5bec7691f0477c2a67e8a3ffcc8d50e0452960e01026892e91e190d8ee
|
|
BLAKE2b-256 checksum How to use checksums |
61b30df75a5bea1dbd767216a97763ffb0851d048c7053f136472eefb3fdd591
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.7.6
|
Security for earlywarn 0.4.0
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.