lifefrom-units 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ .pytest_cache/
5
+ .venv/
6
+ node_modules/
7
+ dist/
8
+ *.tgz
9
+ .DS_Store
@@ -0,0 +1,36 @@
1
+ lifefrom-units is released under two licences.
2
+
3
+ Code (python/, ts/, scripts/, tests/): MIT License
4
+ Data (data/, web/, tests/vectors.json, the units.json copies inside the packages): Creative Commons
5
+ Attribution 4.0 International (CC BY 4.0), https://creativecommons.org/licenses/by/4.0/
6
+
7
+ Third-party material:
8
+ - Molar masses are facts taken from PubChem (NCBI) and CIAAW; each is cited in data/units.json.
9
+ - UCUM code strings in data/units.json are expressions in the Unified Code for Units of Measure,
10
+ Copyright 1999-2024 Regenstrief Institute, Inc., used under the UCUM License, Version 1.1
11
+ (https://ucum.org/license). This repository does not include or redistribute the UCUM tables
12
+ (ucum-essence.xml). The mapping from lab spellings to UCUM codes is LifeFrom's work, is not part of
13
+ UCUM, and is not a units standard.
14
+
15
+ -------------------------------------------------------------------------------
16
+ MIT License
17
+
18
+ Copyright (c) 2026 LifeFrom (https://lifefrom.ai) and Julian Caraulani
19
+
20
+ Permission is hereby granted, free of charge, to any person obtaining a copy
21
+ of this software and associated documentation files (the "Software"), to deal
22
+ in the Software without restriction, including without limitation the rights
23
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
24
+ copies of the Software, and to permit persons to whom the Software is
25
+ furnished to do so, subject to the following conditions:
26
+
27
+ The above copyright notice and this permission notice shall be included in all
28
+ copies or substantial portions of the Software.
29
+
30
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
31
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
32
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
33
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
34
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
35
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
36
+ SOFTWARE.
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.5
2
+ Name: lifefrom-units
3
+ Version: 1.0.0
4
+ Summary: Normalise clinical lab unit spellings and convert lab values with sourced, analyte-specific factors.
5
+ Project-URL: Homepage, https://lifefrom.ai/research/open-data/lab-units
6
+ Project-URL: Repository, https://github.com/caraulani/lifefrom-units
7
+ Author: LifeFrom, Julian Caraulani
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: FHIR,OMOP,UCUM,clinical chemistry,laboratory,unit conversion,units
11
+ Classifier: Intended Audience :: Healthcare Industry
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+
19
+ # lifefrom-units (Python)
20
+
21
+ Normalise clinical lab unit spellings and convert lab values with sourced, analyte-specific factors. Zero runtime dependencies. Python 3.9 or newer. Distribution `lifefrom-units`, import `lifefrom_units`, CLI `lifefrom-units`.
22
+
23
+ ```python
24
+ from lifefrom_units import convert, convert_result, normalize_unit, same_unit, explain
25
+
26
+ normalize_unit("mcg/l") # 'µg/L'
27
+ convert("5,4", "mmol/L", "mg/dL", analyte="glucose") # 97.2864
28
+ convert_result("<5", "mg/dL", "mmol/L", analyte="glucose") # comparator '<' kept
29
+ same_unit("K/µL", "10^9/L") # True
30
+ convert(10, "µIU/mL", "pmol/L", analyte="insulin", factor=6) # your factor; recorded by explain()
31
+ explain("mg/dL", "nmol/L", analyte="lipoprotein-a") # raises ForbiddenConversionError
32
+ ```
33
+
34
+ Sources, checks and limitations are described in the repository README and METHODS: https://github.com/caraulani/lifefrom-units
@@ -0,0 +1,16 @@
1
+ # lifefrom-units (Python)
2
+
3
+ Normalise clinical lab unit spellings and convert lab values with sourced, analyte-specific factors. Zero runtime dependencies. Python 3.9 or newer. Distribution `lifefrom-units`, import `lifefrom_units`, CLI `lifefrom-units`.
4
+
5
+ ```python
6
+ from lifefrom_units import convert, convert_result, normalize_unit, same_unit, explain
7
+
8
+ normalize_unit("mcg/l") # 'µg/L'
9
+ convert("5,4", "mmol/L", "mg/dL", analyte="glucose") # 97.2864
10
+ convert_result("<5", "mg/dL", "mmol/L", analyte="glucose") # comparator '<' kept
11
+ same_unit("K/µL", "10^9/L") # True
12
+ convert(10, "µIU/mL", "pmol/L", analyte="insulin", factor=6) # your factor; recorded by explain()
13
+ explain("mg/dL", "nmol/L", analyte="lipoprotein-a") # raises ForbiddenConversionError
14
+ ```
15
+
16
+ Sources, checks and limitations are described in the repository README and METHODS: https://github.com/caraulani/lifefrom-units
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.18"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "lifefrom-units"
7
+ version = "1.0.0"
8
+ description = "Normalise clinical lab unit spellings and convert lab values with sourced, analyte-specific factors."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "LifeFrom" }, { name = "Julian Caraulani" }]
14
+ keywords = ["laboratory", "units", "UCUM", "unit conversion", "clinical chemistry", "OMOP", "FHIR"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Intended Audience :: Science/Research",
18
+ "Intended Audience :: Healthcare Industry",
19
+ "Topic :: Scientific/Engineering :: Medical Science Apps.",
20
+ "Typing :: Typed",
21
+ ]
22
+ dependencies = []
23
+
24
+ [project.urls]
25
+ Homepage = "https://lifefrom.ai/research/open-data/lab-units"
26
+ Repository = "https://github.com/caraulani/lifefrom-units"
27
+
28
+ [project.scripts]
29
+ lifefrom-units = "lifefrom_units.cli:main"
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["src/lifefrom_units"]
33
+
34
+ [tool.hatch.build.targets.sdist]
35
+ include = ["src/lifefrom_units", "tests", "README.md", "LICENSE", "pyproject.toml"]
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
39
+ addopts = "--doctest-modules src/lifefrom_units/core.py src/lifefrom_units/__init__.py tests"
@@ -0,0 +1,38 @@
1
+ """lifefrom_units: normalise clinical lab unit spellings and convert values with sourced factors.
2
+
3
+ >>> from lifefrom_units import convert, normalize_unit
4
+ >>> normalize_unit("mcg/l")
5
+ 'µg/L'
6
+ >>> round(convert(5.4, "mmol/L", "mg/dL", analyte="glucose"), 1)
7
+ 97.3
8
+ """
9
+ from .core import (
10
+ SPEC,
11
+ AmbiguousValueError,
12
+ ForbiddenConversionError,
13
+ IncompatibleUnitsError,
14
+ InvalidValueError,
15
+ LifeFromUnitsError,
16
+ NoSourcedConversionError,
17
+ QualifiedValueError,
18
+ UnknownAnalyteError,
19
+ UnknownUnitError,
20
+ analytes,
21
+ convert,
22
+ convert_result,
23
+ explain,
24
+ normalize_unit,
25
+ parse_result,
26
+ parse_value,
27
+ same_unit,
28
+ unit_info,
29
+ )
30
+ from . import core
31
+
32
+ __version__ = SPEC["version"]
33
+
34
+ __all__ = [
35
+ "AmbiguousValueError", "ForbiddenConversionError", "IncompatibleUnitsError", "InvalidValueError",
36
+ "LifeFromUnitsError", "NoSourcedConversionError", "QualifiedValueError", "UnknownAnalyteError", "UnknownUnitError", "analytes",
37
+ "convert", "convert_result", "core", "explain", "normalize_unit", "parse_result", "parse_value", "same_unit", "unit_info", "__version__",
38
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,24 @@
1
+ """Shared unit-spelling normalisation (no data). Used by the runtime and by scripts/build.py."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from typing import Dict, List, Sequence, Tuple
6
+
7
+ Rule = Tuple["re.Pattern[str]", str]
8
+
9
+
10
+ def compile_rules(rules: Sequence[Dict[str, str]]) -> List[Rule]:
11
+ """Compile rules whose replacements use JavaScript-style ``$1`` group references."""
12
+ out: List[Rule] = []
13
+ for r in rules:
14
+ repl = re.sub(r"\$(\d)", r"\\g<\1>", r["replacement"])
15
+ out.append((re.compile(r["pattern"]), repl))
16
+ return out
17
+
18
+
19
+ def unit_key(text: str, rules: Sequence[Rule]) -> str:
20
+ """Apply the rules in order, then drop all whitespace. This is the lookup key."""
21
+ s = text.strip()
22
+ for pat, repl in rules:
23
+ s = pat.sub(repl, s)
24
+ return re.sub(r"\s+", "", s)
@@ -0,0 +1,86 @@
1
+ """Command-line interface: ``lifefrom-units convert|normalize|same|explain|analytes``."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from typing import List, Optional
8
+
9
+ from . import __version__
10
+ from .core import LifeFromUnitsError, analytes, convert_result, explain, normalize_unit, same_unit
11
+
12
+
13
+ def _parser() -> argparse.ArgumentParser:
14
+ p = argparse.ArgumentParser(prog="lifefrom-units", description="Normalise lab units and convert lab values.")
15
+ p.add_argument("--version", action="version", version=f"lifefrom-units {__version__}")
16
+ sub = p.add_subparsers(dest="cmd", required=True)
17
+
18
+ c = sub.add_parser("convert", help="convert a value: lifefrom-units convert 5,4 mmol/L mg/dL --analyte glucose")
19
+ c.add_argument("value")
20
+ c.add_argument("from_unit")
21
+ c.add_argument("to_unit")
22
+ c.add_argument("--analyte", "-a")
23
+ c.add_argument("--factor", help="your own factor (value_to = value_from x factor); recorded, never a default")
24
+ c.add_argument("--json", action="store_true", help="print the result and full explanation as JSON")
25
+
26
+ n = sub.add_parser("normalize", help="print the canonical spelling of one or more units")
27
+ n.add_argument("units", nargs="+")
28
+
29
+ s = sub.add_parser("same", help="exit 0 if the two units are numerically the same, 1 if not")
30
+ s.add_argument("a")
31
+ s.add_argument("b")
32
+ s.add_argument("--analyte", "-a")
33
+
34
+ e = sub.add_parser("explain", help="show the factor or equation and its sources")
35
+ e.add_argument("from_unit")
36
+ e.add_argument("to_unit")
37
+ e.add_argument("--analyte", "-a")
38
+ e.add_argument("--factor")
39
+ e.add_argument("--json", action="store_true")
40
+
41
+ sub.add_parser("analytes", help="list analytes that have conversions")
42
+ return p
43
+
44
+
45
+ def main(argv: Optional[List[str]] = None) -> int:
46
+ args = _parser().parse_args(argv)
47
+ try:
48
+ if args.cmd == "convert":
49
+ r = convert_result(args.value, args.from_unit, args.to_unit, args.analyte, factor=args.factor)
50
+ if args.json:
51
+ print(json.dumps({"result": r, "explanation": explain(args.from_unit, args.to_unit, args.analyte,
52
+ factor=args.factor)},
53
+ ensure_ascii=False, indent=2))
54
+ else:
55
+ print(r["text"])
56
+ if args.factor is not None:
57
+ print("note: factor supplied by you; not checked by lifefrom-units", file=sys.stderr)
58
+ elif args.cmd == "normalize":
59
+ for u in args.units:
60
+ print(normalize_unit(u))
61
+ elif args.cmd == "same":
62
+ ok = same_unit(args.a, args.b, args.analyte)
63
+ print("same" if ok else "different")
64
+ return 0 if ok else 1
65
+ elif args.cmd == "explain":
66
+ ex = explain(args.from_unit, args.to_unit, args.analyte, factor=args.factor)
67
+ if args.json:
68
+ print(json.dumps(ex, ensure_ascii=False, indent=2))
69
+ else:
70
+ print(ex["text"])
71
+ for st in ex["steps"]:
72
+ print(f" - {st['description']}" + (f" [{st['basis']}]" if st.get("basis") else ""))
73
+ for src in ex["sources"]:
74
+ print(f" source: {src['label']} <{src['url']}>")
75
+ for w in ex["warnings"]:
76
+ print(f" warning: {w}")
77
+ if ex["derived"]:
78
+ print(" derived: unit arithmetic")
79
+ elif args.cmd == "analytes":
80
+ for a in analytes():
81
+ if a["has_conversions"]:
82
+ print(f"{a['id']}\t{a['name']}\t{', '.join(a['marker_slugs'])}")
83
+ except LifeFromUnitsError as ex:
84
+ print(f"lifefrom-units: {ex.code}: {ex}", file=sys.stderr)
85
+ return 2
86
+ return 0