labunits 0.1.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
+ # The MIT License (MIT)
2
+
3
+ Copyright © 2025 <Christian González>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: labunits
3
+ Version: 0.1.0
4
+ Summary: Convert laboratory units between mmol/l und mg/dl based on the molar mass of the unit.
5
+ Author-email: Christian Gonzalez <office@nerdocs.at>
6
+ Project-URL: Homepage, https://github.com/nerdocs/labunits
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE.md
10
+ Dynamic: license-file
11
+
12
+ # Labunits
13
+
14
+
15
+ This is a simple python library for laboratory units, and to convert between them.
16
+
17
+
18
+ ### Why another library with this content?
19
+
20
+ Oh - just because - there IS NONE. I couldn't believe that.
21
+
22
+
23
+ ### License
24
+
25
+ MIT. Just use it in your project and give credits.
@@ -0,0 +1,14 @@
1
+ # Labunits
2
+
3
+
4
+ This is a simple python library for laboratory units, and to convert between them.
5
+
6
+
7
+ ### Why another library with this content?
8
+
9
+ Oh - just because - there IS NONE. I couldn't believe that.
10
+
11
+
12
+ ### License
13
+
14
+ MIT. Just use it in your project and give credits.
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "labunits"
7
+ version = "0.1.0"
8
+ description = "Convert laboratory units between mmol/l und mg/dl based on the molar mass of the unit."
9
+ authors = [
10
+ { name="Christian Gonzalez", email="office@nerdocs.at" }
11
+ ]
12
+ readme = "README.md"
13
+ license-files = ["LICENSE.md"]
14
+ requires-python = ">=3.10"
15
+
16
+ [project.urls]
17
+ Homepage = "https://github.com/nerdocs/labunits"
18
+
19
+ [dependencies]
20
+
21
+
22
+ [dependency-groups]
23
+ test = ["pytest", "ruff"]
24
+ dev = ["beautifulsoup4","build", "thefuzz", "pydantic", "ruff", "black"]
25
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,116 @@
1
+ import json
2
+ import math
3
+ from pathlib import Path
4
+
5
+ _analytes_data = {}
6
+
7
+ type LoincNum = str
8
+
9
+
10
+ def _load_data() -> dict:
11
+ """
12
+ Load data from the 'data' directory.
13
+
14
+ Returns:
15
+ dict: Data in the format {'analyte': {'value': float, 'units': str}}
16
+ """
17
+ global _analytes_data
18
+ # check if data is already loaded
19
+ if _analytes_data:
20
+ return _analytes_data
21
+
22
+ # get data dir of labunits package using Pathlib
23
+ data_dir = Path(__file__).parent / "data"
24
+
25
+ with Path.open(data_dir / "analytes.json", "r") as file:
26
+ _analytes_data = json.load(file)
27
+
28
+ return _analytes_data
29
+
30
+
31
+ def _resolve_analyte_identifier(identifier: str) -> LoincNum:
32
+ """Resolve various identifiers to LOINC code."""
33
+ data = _load_data()
34
+
35
+ # Direct LOINC lookup
36
+ if identifier in data:
37
+ return identifier
38
+
39
+ # Search by abbreviation or name
40
+ for loinc, info in data.items():
41
+ if ( # FIXME
42
+ info.get("abbreviation", "").lower() == identifier.lower()
43
+ or info.get("name", "").lower() == identifier.lower()
44
+ ):
45
+ return loinc
46
+
47
+ raise ValueError(f"Unknown analyte identifier: {identifier}")
48
+
49
+
50
+ def si_unit(analyte: LoincNum | str) -> str:
51
+ """Returns the SI unit for the given analyte.
52
+
53
+ Examples:
54
+ "mmol/L"
55
+ "µmol/L"
56
+ """
57
+ loinc = _resolve_analyte_identifier(analyte)
58
+ return _analytes_data[loinc]["si_units"]
59
+
60
+
61
+ def traditional_unit(analyte: LoincNum | str) -> str:
62
+ """Returns the traditional unit for the given analyte."""
63
+ loinc = _resolve_analyte_identifier(analyte)
64
+ return _analytes_data[loinc]["traditional_units"]
65
+
66
+
67
+ def conversion_factor(analyte: LoincNum | str) -> float:
68
+ """Returns the conversion factor for the given analyte.
69
+
70
+ Multiply with the factor to convert from traditional to SI, divide by it the
71
+ other way round.
72
+
73
+ Returns:
74
+ float: Conversion factor
75
+ """
76
+ loinc = _resolve_analyte_identifier(analyte)
77
+ return float(_analytes_data[loinc]["conversion_factor"])
78
+
79
+
80
+ def to_si_unit(analyte: LoincNum | str, value: float) -> float:
81
+ """
82
+ Convert value to SI unit.
83
+
84
+ Args:
85
+ analyte: LOINC code (preferred), abbreviation, or full name
86
+ value (float): Concentration in traditional units
87
+ Returns:
88
+ float: value in SI units
89
+ """
90
+ # Normalize to LOINC internally
91
+ loinc = _resolve_analyte_identifier(analyte)
92
+ data = _load_data()
93
+ factor = float(data[loinc]["conversion_factor"])
94
+
95
+ if math.isinf(value) or math.isnan(value):
96
+ return value
97
+ return value * factor
98
+
99
+
100
+ def to_traditional_unit(analyte: str, value: float) -> float:
101
+ """
102
+ Convert SI to value unit.
103
+
104
+ Args:
105
+ analyte: LOINC code (preferred), abbreviation, or full name
106
+ value (float): Concentration in SI units
107
+ Returns:
108
+ float: value in traditional units
109
+ """
110
+ loinc = _resolve_analyte_identifier(analyte)
111
+ data = _load_data()
112
+ factor = float(data[loinc]["conversion_factor"])
113
+
114
+ if math.isinf(value) or math.isnan(value):
115
+ return value
116
+ return value / factor
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: labunits
3
+ Version: 0.1.0
4
+ Summary: Convert laboratory units between mmol/l und mg/dl based on the molar mass of the unit.
5
+ Author-email: Christian Gonzalez <office@nerdocs.at>
6
+ Project-URL: Homepage, https://github.com/nerdocs/labunits
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE.md
10
+ Dynamic: license-file
11
+
12
+ # Labunits
13
+
14
+
15
+ This is a simple python library for laboratory units, and to convert between them.
16
+
17
+
18
+ ### Why another library with this content?
19
+
20
+ Oh - just because - there IS NONE. I couldn't believe that.
21
+
22
+
23
+ ### License
24
+
25
+ MIT. Just use it in your project and give credits.
@@ -0,0 +1,11 @@
1
+ LICENSE.md
2
+ README.md
3
+ pyproject.toml
4
+ src/labunits/__init__.py
5
+ src/labunits/converters.py
6
+ src/labunits.egg-info/PKG-INFO
7
+ src/labunits.egg-info/SOURCES.txt
8
+ src/labunits.egg-info/dependency_links.txt
9
+ src/labunits.egg-info/top_level.txt
10
+ tests/test_converters.py
11
+ tests/test_data_integration.py
@@ -0,0 +1 @@
1
+ labunits
@@ -0,0 +1,131 @@
1
+ """Tests for ``labunits.converters``.
2
+
3
+ Function-style tests, no classes. The autouse fixture in ``conftest.py``
4
+ injects ``SAMPLE_ANALYTES`` into the module-level cache so the real JSON
5
+ file is irrelevant here.
6
+ """
7
+
8
+ import math
9
+
10
+ import pytest
11
+
12
+ from labunits.converters import (
13
+ conversion_factor,
14
+ si_unit,
15
+ to_si_unit,
16
+ to_traditional_unit,
17
+ traditional_unit,
18
+ )
19
+
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Lookup helpers
23
+ # ---------------------------------------------------------------------------
24
+
25
+
26
+ def test_si_unit_by_loinc():
27
+ assert si_unit("109547-0") == "mmol/L"
28
+
29
+
30
+ def test_traditional_unit_by_loinc():
31
+ assert traditional_unit("109547-0") == "mg/dL"
32
+
33
+
34
+ def test_lookup_by_exact_name():
35
+ assert si_unit("Acetone") == "mmol/L"
36
+
37
+
38
+ def test_lookup_by_lowercase_name():
39
+ assert si_unit("acetone") == "mmol/L"
40
+
41
+
42
+ def test_lookup_by_uppercase_name():
43
+ assert si_unit("ACETONE") == "mmol/L"
44
+
45
+
46
+ def test_unknown_identifier_raises_value_error():
47
+ with pytest.raises(ValueError, match="Unknown analyte identifier"):
48
+ si_unit("definitely-not-a-real-analyte")
49
+
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # conversion_factor
53
+ # ---------------------------------------------------------------------------
54
+
55
+
56
+ def test_conversion_factor_returns_float():
57
+ factor = conversion_factor("109547-0")
58
+ assert isinstance(factor, float)
59
+ assert factor == pytest.approx(0.172)
60
+
61
+
62
+ def test_conversion_factor_for_albumin():
63
+ assert conversion_factor("100158-5") == pytest.approx(10.0)
64
+
65
+
66
+ # ---------------------------------------------------------------------------
67
+ # to_si_unit / to_traditional_unit
68
+ # ---------------------------------------------------------------------------
69
+
70
+
71
+ def test_to_si_unit_acetone():
72
+ # 1.0 mg/dL * 0.172 == 0.172 mmol/L
73
+ assert to_si_unit("109547-0", 1.0) == pytest.approx(0.172)
74
+
75
+
76
+ def test_to_si_unit_albumin():
77
+ # 4.0 g/dL * 10 == 40 g/L
78
+ assert to_si_unit("100158-5", 4.0) == pytest.approx(40.0)
79
+
80
+
81
+ def test_to_traditional_unit_acetone():
82
+ # 0.172 mmol/L / 0.172 == 1.0 mg/dL
83
+ assert to_traditional_unit("109547-0", 0.172) == pytest.approx(1.0)
84
+
85
+
86
+ def test_to_traditional_unit_albumin():
87
+ # 40 g/L / 10 == 4.0 g/dL
88
+ assert to_traditional_unit("100158-5", 40.0) == pytest.approx(4.0)
89
+
90
+
91
+ def test_round_trip_traditional_to_si_to_traditional():
92
+ original = 2.5
93
+ si = to_si_unit("100158-5", original)
94
+ back = to_traditional_unit("100158-5", si)
95
+ assert back == pytest.approx(original)
96
+
97
+
98
+ def test_zero_value_passes_through():
99
+ assert to_si_unit("109547-0", 0.0) == 0.0
100
+ assert to_traditional_unit("109547-0", 0.0) == 0.0
101
+
102
+
103
+ def test_negative_value_is_converted():
104
+ assert to_si_unit("100158-5", -3.0) == pytest.approx(-30.0)
105
+
106
+
107
+ def test_to_si_unit_returns_float():
108
+ assert isinstance(to_si_unit("109547-0", 1.0), float)
109
+
110
+
111
+ # ---------------------------------------------------------------------------
112
+ # Special float values
113
+ # ---------------------------------------------------------------------------
114
+
115
+
116
+ def test_positive_infinity_passes_through():
117
+ assert to_si_unit("109547-0", float("inf")) == float("inf")
118
+ assert to_traditional_unit("109547-0", float("inf")) == float("inf")
119
+
120
+
121
+ def test_negative_infinity_passes_through():
122
+ assert to_si_unit("109547-0", float("-inf")) == float("-inf")
123
+ assert to_traditional_unit("109547-0", float("-inf")) == float("-inf")
124
+
125
+
126
+ def test_nan_passes_through():
127
+ # NaN must propagate, not raise. The current implementation uses
128
+ # ``value in [..., float("nan")]`` which is always False because
129
+ # NaN never compares equal to itself — this test exposes that bug.
130
+ assert math.isnan(to_si_unit("109547-0", float("nan")))
131
+ assert math.isnan(to_traditional_unit("109547-0", float("nan")))
@@ -0,0 +1,81 @@
1
+ """Integration tests against the real shipped ``analytes.json``.
2
+
3
+ These tests bypass the autouse fixture from ``conftest.py`` so they hit
4
+ the actual data file as the published library would.
5
+ """
6
+
7
+ import json
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ from labunits import converters
13
+ from labunits.converters import (
14
+ conversion_factor,
15
+ si_unit,
16
+ to_si_unit,
17
+ to_traditional_unit,
18
+ traditional_unit,
19
+ )
20
+
21
+
22
+ @pytest.fixture
23
+ def real_data(monkeypatch):
24
+ """Reset the module cache and force a real load from the shipped JSON."""
25
+ monkeypatch.setattr(converters, "_analytes_data", {})
26
+ yield converters._load_data()
27
+
28
+
29
+ def test_shipped_json_is_valid():
30
+ data_file = Path(converters.__file__).parent / "data" / "analytes.json"
31
+ with data_file.open("r", encoding="utf-8") as f:
32
+ data = json.load(f)
33
+ assert isinstance(data, dict)
34
+ assert len(data) > 0
35
+
36
+
37
+ def test_shipped_entries_have_required_keys(real_data):
38
+ required = {"name", "traditional_units", "si_units", "conversion_factor"}
39
+ missing = [
40
+ loinc for loinc, entry in real_data.items() if not required <= entry.keys()
41
+ ]
42
+ assert missing == []
43
+
44
+
45
+ # A few upstream entries (AccessMedicine HTML) ship without a numeric
46
+ # conversion factor — typically when the units are dimensionless or
47
+ # percentage-based and no factor is published. Track them explicitly
48
+ # so genuine regressions stand out.
49
+ KNOWN_NON_NUMERIC_FACTORS = {"27345-8"} # Hemoglobin A2 (% total Hb <-> fraction)
50
+
51
+
52
+ def test_shipped_conversion_factors_are_numeric_when_present(real_data):
53
+ bad = set()
54
+ for loinc, entry in real_data.items():
55
+ factor = entry["conversion_factor"]
56
+ if factor == "":
57
+ continue
58
+ try:
59
+ float(factor)
60
+ except (TypeError, ValueError):
61
+ bad.add(loinc)
62
+ assert bad == set(), f"Non-numeric conversion factors: {bad}"
63
+
64
+
65
+ def test_known_non_numeric_factor_entries_are_still_in_data(real_data):
66
+ # Documents the upstream gap so it's visible. If the source data
67
+ # gets fixed and a factor is added, this test will fail and prompt
68
+ # us to drop the entry from KNOWN_NON_NUMERIC_FACTORS.
69
+ for loinc in KNOWN_NON_NUMERIC_FACTORS:
70
+ assert loinc in real_data
71
+ assert real_data[loinc]["conversion_factor"] == ""
72
+
73
+
74
+ def test_acetone_round_trip_against_real_data(real_data):
75
+ # Acetone (LOINC 109547-0): 1 mg/dL -> 0.172 mmol/L
76
+ assert "109547-0" in real_data
77
+ assert si_unit("109547-0") == "mmol/L"
78
+ assert traditional_unit("109547-0") == "mg/dL"
79
+ assert conversion_factor("109547-0") == pytest.approx(0.172)
80
+ assert to_si_unit("109547-0", 1.0) == pytest.approx(0.172)
81
+ assert to_traditional_unit("109547-0", 0.172) == pytest.approx(1.0)