---
license: cc-by-4.0
pretty_name: lifefrom-units
language:
- en
tags:
- clinical-chemistry
- laboratory-medicine
- units-of-measure
- ucum
- omop
- fhir
- unit-conversion
size_categories:
- n<1K
---

# lifefrom-units

Interactive version: https://lifefrom.ai/research/open-data/lab-units

lifefrom-units normalises the units printed on clinical lab results and converts lab values between them.

- Every factor that depends on the analyte has a cited source.
- Conversions that must never be done are refused, with a reason.
- Values like `<5` or `5,4 H` keep their qualifier through a conversion.

The project ships as:

- one JSON specification, `data/units.json`;
- a Python package: distribution `lifefrom-units`, import `lifefrom_units`;
- a TypeScript package, `@lifefrom/units`.

Both packages read the same JSON and pass the same 1,501 test vectors, with bit-identical results.

Version 1.0.0, released 2026-11-25, by LifeFrom (https://lifefrom.ai).

Scope: lifefrom-units converts units only. It does not interpret results or compare them with reference intervals.

## How it was built and checked

Every analyte-specific number was taken from a source fetched during the build and is cited per value:

- PubChem molar masses;
- CIAAW atomic weights;
- CDC NHANES published factors;
- the NGSP HbA1c equation;
- the papers cited in `data/units.json`.

How it was checked:

- **Rebuild from raw sources.** `build.py` checks that every published factor and the NGSP equation appear in the fetched pages.
- **Formula cross-check.** Each PubChem molar mass was recomputed from its formula, using CIAAW atomic weights.
- **Published tables.** 20 factors were compared with NHANES and IOM published values. All agree within the rounding of those tables (METHODS.md §6).
- **Test vectors.** The 1,501 vectors are generated by a script that does not import the library.
- **UCUM codes.** All 143 codes were validated by our own grammar check and by the NLM's `ucum-lhc` 8.0.1.

## Who it is for

- **Researchers** who harmonise lab values from hospital records: OHDSI/OMOP, i2b2, UK Biobank, N3C-style pooled data.
- **Lab interface teams** who map instrument and LIS unit strings.
- **App developers** who read lab reports.

## What it handles

| Problem | Example | What lifefrom-units does |
|---|---|---|
| One unit, many spellings | `µg/L`, `ug/L`, `mcg/L`, `μg/l`, `UG/L` | `normalize_unit` returns `µg/L` |
| Counts written five ways | `×10⁹/L`, `10^9/L`, `x10E9/L`, `G/L`, `10*9/L` | all become `10^9/L`; `same_unit("K/µL", "/nL")` is True |
| mg/dL vs mmol/L | glucose, cholesterol, creatinine | factor from the molar mass; `explain()` names the reference compound and its PubChem CID |
| mEq/L vs mmol/L | sodium (z = 1), calcium and magnesium (z = 2) | uses the ion charge; needs the analyte |
| Enzyme activity | `U/L`, `IU/L`, `µkat/L` | `1 U = 1 µmol/min = 1/60 µkat`, only for enzyme analytes, with a warning that unit conversion does not make methods comparable |
| HbA1c | NGSP % vs IFCC mmol/mol | the IFCC–NGSP master equation, not a factor |
| Vitamin D IU | 1 µg = 40 IU (doses only) | allowed for `vitamin-d-dose`; refused for serum 25-hydroxyvitamin D |
| Never convert by default | Lp(a) mg/dL vs nmol/L; insulin µIU/mL vs pmol/L; AMH ng/mL vs pmol/L; S/CO vs index | raises `ForbiddenConversionError` with the reason and a source |
| Your own factor | insulin with your assay's factor; TSH mU/L → mIU/L; IgE kU/L → IU/mL | `factor=` (never a default); `explain()` records it and what it overrode |
| Censored and flagged values | `<5`, `>1000`, `5.4 H`, `5,4 L` | `parse_result` / `convert_result` keep the comparator and flag; plain `convert` refuses them rather than drop them |
| Decimal commas | `"5,4"`, `"1.234,5"` | parsed; `"1,234"` is ambiguous and raises |

## Install

Nothing is published to PyPI or npm yet. Build locally:

```bash
cd python && pip install .               # Python >= 3.9, no runtime dependencies
cd ts && npm install && npm run build    # ESM, no runtime dependencies
```

## Quickstart: Python

```python
from lifefrom_units import (convert, convert_result, normalize_unit, same_unit, explain,
                            ForbiddenConversionError)

normalize_unit("mcg/l")                              # 'µg/L'
normalize_unit("x10E3/uL")                           # '10^3/µL'
same_unit("µg/L", "ng/mL")                           # True
same_unit("mEq/L", "mmol/L", analyte="sodium")       # True

convert("5,4", "mmol/L", "mg/dL", analyte="glucose")        # 97.2864
convert(1.1, "mg/dL", "µmol/L", analyte="creatinine-serum") # 97.24  (marker slugs work too)
convert(48, "mmol/mol", "%", analyte="hba1c")               # 6.54304  (master equation)

convert_result("<5", "mg/dL", "mmol/L", analyte="glucose")
# {'value': 0.2775..., 'comparator': '<', 'flag': None, 'unit': 'mmol/L', 'text': '<0.277531'}
convert_result("5,4 H", "mmol/L", "mg/dL", analyte="glucose")["text"]   # '97.2864 H' (+ flag_note)

try:
    convert(10, "µIU/mL", "pmol/L", analyte="insulin")
except ForbiddenConversionError as e:
    print(e.details["reason"])
convert(10, "µIU/mL", "pmol/L", analyte="insulin", factor=6)     # 60.0, your assay's factor
explain("µIU/mL", "pmol/L", analyte="insulin", factor=6)["warnings"]
# ['Factor 6 supplied by the caller; lifefrom-units has not checked it.', 'Overrides lifefrom-units (forbidden): ...']

e = explain("ng/mL", "nmol/L", analyte="vitamin-d-25-oh")
e["reference_compounds"][0]["name"], e["reference_compounds"][0]["pubchem_cid"]   # ('25-Hydroxyvitamin D3', 5283731)
e["warnings"]   # ['Reference compound: 25-hydroxyvitamin D3 (PubChem CID 5283731, 400.6 g/mol). ...']
```

Command line:

```bash
lifefrom-units convert 5,4 mmol/L mg/dL --analyte glucose        # 97.2864
lifefrom-units convert "<5" mg/dL mmol/L -a glucose              # <0.277531
lifefrom-units convert 10 µIU/mL pmol/L -a insulin --factor 6    # 60 (note on stderr)
lifefrom-units normalize "×10⁹/L" "K/uL" "μmol/l"
lifefrom-units explain U/L µkat/L -a alt                         # factor, sources, warnings
lifefrom-units convert 50 mg/dL nmol/L -a lipoprotein-a          # exit code 2, reason on stderr
```

## Quickstart: TypeScript

```ts
import { convert, convertResult, normalizeUnit, sameUnit, explain, LifeFromUnitsError } from '@lifefrom/units';

normalizeUnit('mcg/l');                                     // 'µg/L'
sameUnit('K/µL', '10^9/L');                                 // true
convert('5,4', 'mmol/L', 'mg/dL', 'glucose');               // 97.2864
convertResult('>1000', 'mg/dL', 'g/L').text;                // '>10'
explain('%', 'mmol/mol', 'hba1c').equation?.text;           // 'mmol/mol = 10.9314 × % - 23.5243'
convert(2.5, 'mU/L', 'mIU/L', 'tsh', 1);                    // 2.5, factor supplied by you

try {
  convert(2, 'ng/mL', 'pmol/L', 'amh');
} catch (e) {
  if (e instanceof LifeFromUnitsError) console.log(e.code); // 'forbidden'
}
```

TypeScript functions are camelCase, with snake_case aliases matching Python.

## API

| Function | Returns | Raises (error `code`) |
|---|---|---|
| `normalize_unit(unit)` | canonical spelling | `unknown_unit` |
| `convert(value, from_unit, to_unit, analyte=None, factor=None)` | number | `incompatible_units` (needs an analyte), `forbidden`, `no_sourced_conversion`, `unknown_unit`, `unknown_analyte`, `invalid_value`, `qualified_value`, `ambiguous_value` |
| `convert_result(value, from_unit, to_unit, analyte=None, factor=None)` | `{value, comparator, flag, unit, text, flag_note?}` | as `convert`, except `qualified_value` |
| `parse_result(value)` | `{value, comparator, flag, text}` | `invalid_value`, `ambiguous_value` |
| `parse_value(value)` | number | `invalid_value`, `qualified_value`, `ambiguous_value` |
| `same_unit(a, b, analyte=None)` | bool | `unknown_unit`, `unknown_analyte` |
| `explain(from_unit, to_unit, analyte=None, value=None, factor=None)` | kind, factor or equation, steps, sources, `reference_compounds`, `warnings`, `user_factor` | same as `convert` |
| `unit_info(unit)` | canonical spelling, dimension, scale, UCUM code | `unknown_unit` |
| `analytes()` | analytes and their marker slugs | |

**`analyte`** takes a lifefrom-units analyte id (`glucose`, `calcium`, `hba1c`, ...) or a LifeFrom marker slug (`glucose-fasting`, `calcium-ionized`, ...).

**`factor`** is a caller-supplied multiplier: `value_to = value_from × factor`.

- It is never applied unless you pass it.
- It replaces whatever the library would have done, including a refusal.
- `explain()` records it under `kind: "user_factor"` and `user_factor: {value, overrides, library_kind, library_factor}`.
- It also adds warnings: that the factor is unchecked, which rule it overrides, or how far it differs from the library's own factor.

**Comparators and flags.**

| | Accepted |
|---|---|
| Comparators | `<`, `>`, `<=`, `>=`, `≤`, `≥`, `=<`, `=>` |
| Flags | `H`, `L`, `HH`, `LL`, `A`, `AA` (also in `()` or `[]`), `↑`, `↓`, `*`, `!` |

- The comparator is kept through a conversion, because every conversion is increasing.
- The flag is copied unchanged, with a `flag_note`: the flag refers to the original lab's reference interval.

**`explain(...)["kind"]`** is one of:

- `identity`;
- `unit_arithmetic`: derived from unit prefixes;
- `label_equivalence`: IU/L read as U/L for an enzyme;
- `analyte_factor`: molar mass, ion charge, published factor or dose equivalence;
- `equation`: HbA1c;
- `user_factor`.

## Files

| Path | What it is |
|---|---|
| `data/units.json` | Canonical specification: normalisation rules, 158 units in 42 dimensions, lookup tables, 60 analytes with conversions, 6 forbidden rules, 61 cited sources. |
| `data/analyte_factors.csv` | One row per analyte conversion in conventional units, with source and published cross-check. |
| `data/release1_comparison.csv` | Every non-preferred unit in LifeFrom release 1, with release 1's factor next to this release's result. |
| `web/lifefrom-units.json` | Compact data for the lifefrom.ai live converter (schema below). |
| `tests/vectors.json` | 1,501 shared test vectors. |
| `python/` | Python package (distribution `lifefrom-units`, import `lifefrom_units`, CLI `lifefrom-units`). |
| `ts/` | TypeScript package `@lifefrom/units` (CLI `lifefrom-units`). |
| `scripts/` | `build_all.sh` rebuilds everything; `fetch_sources.sh` downloads the raw sources. |

### `data/units.json`, main keys

- **`normalization.rules`**: ordered regular expressions (`pattern`, `replacement` with `$1` groups, `note`). They behave the same in Python and JavaScript.
- **`units[]`**: one record per canonical unit.
  - `unit`, `dimension`, `ucum`.
  - `scale`: multiply by this to get the dimension's base unit.
  - `aliases`.
  - `case_sensitive_aliases`: `G/L`, `M/µL`, `nM`.
- **`lookup.exact`, `lookup.casefold`**: normalised key → canonical unit.
- **`lookup.analytes`**: analyte id or marker slug → analyte id.
- **`analytes[]`**: `id`, `name`, `marker_slugs`, `molar_mass`, `charge`, `bridges[]`, `note`, `caveats[]`.
  - Each bridge gives the `from` and `to` dimensions and an affine map on base units: `base_to = a × base_from + b`.
  - It also gives `kind`, `basis` and `sources`. Molar-mass bridges add `reference_compound`.
- **`forbidden[]`**: `analyte` (null means "applies to all analytes"), the dimension pair `a`/`b`, optional unit lists, `reason`, `sources`.
- **`sources{}`**: label, URL, DOI, location in the source, kind, access date. PubChem entries add CID, formula and molecular weight.

### `web/lifefrom-units.json`

```
{ name, version,
  units:     [{unit, normalized, dimension}],                       // 452 spellings
  analytes:  [{slug, analyte, name, conversions:[{from, to, factor | equation, source_label, source_url,
                                                  reference_compound?, warnings?}]}],
  forbidden: [{slug, a, b, reason}] }
```

- `slug` is the LifeFrom `marker_slug`. `vitamin-d-dose` has no marker, so it uses its own id.
- A forbidden entry with `slug: null` applies to every analyte (% vs mmol/mol).
- `warnings` ship with the factor and should be shown next to it: enzyme comparability, and the reference compounds for 25-OH-D and folate.

## UCUM codes

- 143 of the 158 units carry a UCUM code. These are the codes OMOP and FHIR use.
- Every code was validated by our UCUM grammar check, using `ucum-essence.xml` 2.2, and by `@lhncbc/ucum-lhc` 8.0.1.
- UCUM is © Regenstrief Institute, Inc., and is used under the UCUM License (https://ucum.org/license). The UCUM tables are not redistributed.
- The mapping from lab spellings to UCUM codes is our own work. It is not part of UCUM and not a units standard.

Deliberate difference from strict UCUM:

- `mIU/mL` equals `IU/L` here, because we scale prefixes within the same international unit. UCUM §25 and ucum-lhc refuse these conversions.
- IU never converts to mass or moles without a sourced analyte rule.

## Limitations

- **Coverage.** 60 analytes have conversions, covering 83 LifeFrom markers.
  - Proteins and peptides (PTH, ACTH, ferritin, IGF-1, C-peptide, AMH) have no default mass↔molar factor.
  - Nor do haemoglobin in mmol/L, ammonia, and vitamins B1, B2 and B6.
  - You can pass your own `factor=` for any of these.
- **Precision.** PubChem molecular weights have 4–5 significant figures, so factors are good to about 1 part in 10⁴.
- **Conventions.** Some factors rest on a chosen reference compound or convention. `explain()` reports the reference compound, and the warnings state the alternatives:
  - 25-OH-D: D3, not D2 (about 3% apart);
  - folate: folic acid, not 5-methyltetrahydrofolate (about 4% apart);
  - B12: cyanocobalamin;
  - phosphorus: as P;
  - BUN: as nitrogen.
- **Enzymes.** Converting U/L to µkat/L does not make results from different methods or reaction temperatures comparable.
- **Context.** The library does not know the specimen, method or assay. If you pass the wrong analyte, you get the wrong molar mass.
- **Labels we won't equate.** We found no source for treating `mU/L` as `mIU/L` (TSH), `kU/L` as `IU/mL` (IgE), or `U/mL` as `IU/mL` (autoantibodies). They are not equated by default.
- **No reference intervals.** None are converted or included.

## Related tools

- [nerdocs/labunits](https://github.com/nerdocs/labunits) is an unrelated Python package published on PyPI as `labunits`. The packages here are named `lifefrom-units` to avoid a name clash.
- [ucum-lhc](https://github.com/lhncbc/ucum-lhc) is the US National Library of Medicine's JavaScript library for validating and converting UCUM expressions. It was used here as an independent check of the UCUM codes (METHODS.md §9). It follows strict UCUM and so refuses the IU prefix conversions that lifefrom-units allows.
- [pint](https://github.com/hgrecco/pint) is a general Python library for physical quantities and unit arithmetic. It does not carry analyte-specific, sourced conversion factors or refusal rules for lab results.

## How to cite

LifeFrom and Julian Caraulani (2026). *lifefrom-units: lab unit normalisation and sourced conversion* (version 1.0.0). https://github.com/caraulani/lifefrom-units. See `CITATION.cff`.

When you use a specific factor, also cite its source. `explain()` returns it.

## Licence

- Code: MIT.
- Data (`data/`, `web/`, `tests/vectors.json`): CC BY 4.0.
- UCUM code strings are used under the UCUM License.

See `LICENSE`.
