doseframe 0.2.0__py3-none-any.whl
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.
- doseframe/__init__.py +252 -0
- doseframe/calculation/__init__.py +34 -0
- doseframe/calculation/derivation.py +30 -0
- doseframe/calculation/errors.py +16 -0
- doseframe/calculation/infusion.py +27 -0
- doseframe/calculation/relation.py +129 -0
- doseframe/calculation/single_dose.py +54 -0
- doseframe/calculation/steps.py +20 -0
- doseframe/calculation/strategies.py +105 -0
- doseframe/calculation/strategy.py +37 -0
- doseframe/checks/__init__.py +20 -0
- doseframe/checks/chain.py +212 -0
- doseframe/checks/context.py +43 -0
- doseframe/findings/__init__.py +58 -0
- doseframe/protocols/__init__.py +103 -0
- doseframe/protocols/activation.py +51 -0
- doseframe/protocols/device.py +51 -0
- doseframe/protocols/diff.py +70 -0
- doseframe/protocols/errors.py +26 -0
- doseframe/protocols/limits.py +74 -0
- doseframe/protocols/model.py +40 -0
- doseframe/protocols/naming.py +126 -0
- doseframe/protocols/reference.py +163 -0
- doseframe/protocols/schemes.py +598 -0
- doseframe/protocols/single_dose.py +253 -0
- doseframe/protocols/version.py +690 -0
- doseframe/py.typed +0 -0
- doseframe/rounding/__init__.py +23 -0
- doseframe/rounding/policy.py +108 -0
- doseframe/units/__init__.py +49 -0
- doseframe/units/catalog.py +155 -0
- doseframe/units/decimal_context.py +17 -0
- doseframe/units/errors.py +27 -0
- doseframe/units/options.py +52 -0
- doseframe/units/quantity.py +144 -0
- doseframe/units/unit.py +137 -0
- doseframe/use_cases/__init__.py +73 -0
- doseframe/use_cases/clinical.py +735 -0
- doseframe/use_cases/gate.py +85 -0
- doseframe/use_cases/governance.py +460 -0
- doseframe/use_cases/ports.py +73 -0
- doseframe/use_cases/results.py +182 -0
- doseframe-0.2.0.dist-info/METADATA +79 -0
- doseframe-0.2.0.dist-info/RECORD +46 -0
- doseframe-0.2.0.dist-info/WHEEL +4 -0
- doseframe-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Rounding: the rounding rule interface (hot-spot 2), the default rules, and their registry."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from doseframe.rounding.policy import (
|
|
6
|
+
ChooseStep,
|
|
7
|
+
NearestStepRounding,
|
|
8
|
+
NoAutoRounding,
|
|
9
|
+
RoundingPolicy,
|
|
10
|
+
RoundingPolicyRegistry,
|
|
11
|
+
UnknownRoundingPolicyError,
|
|
12
|
+
default_registry,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"ChooseStep",
|
|
17
|
+
"NearestStepRounding",
|
|
18
|
+
"NoAutoRounding",
|
|
19
|
+
"RoundingPolicy",
|
|
20
|
+
"RoundingPolicyRegistry",
|
|
21
|
+
"UnknownRoundingPolicyError",
|
|
22
|
+
"default_registry",
|
|
23
|
+
]
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Hot-spot 2: rounding rules (Strategy), the safe default (Null Object), and the registry."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from decimal import ROUND_HALF_EVEN, Decimal
|
|
6
|
+
from typing import Protocol, runtime_checkable
|
|
7
|
+
|
|
8
|
+
from doseframe.calculation import neighbouring_steps
|
|
9
|
+
from doseframe.protocols.device import DeviceProfile
|
|
10
|
+
from doseframe.units import CONTEXT, DoseframeError, Quantity
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@runtime_checkable
|
|
14
|
+
class RoundingPolicy(Protocol):
|
|
15
|
+
"""Turns an exact value into one that is actually given, or suggests nothing (None).
|
|
16
|
+
|
|
17
|
+
`value` is any quantity: a pump rate, or a single dose for a rule that rounds to vials.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def round(self, value: Quantity, device: DeviceProfile | None) -> Quantity | None: ...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class NoAutoRounding:
|
|
24
|
+
"""The framework default: never suggests a setting. No one approved a rounding decision."""
|
|
25
|
+
|
|
26
|
+
offers_choice = False
|
|
27
|
+
|
|
28
|
+
def round(self, value: Quantity, device: DeviceProfile | None) -> Quantity | None:
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
def candidates(self, value: Quantity, device: DeviceProfile | None) -> tuple[Quantity, ...]:
|
|
32
|
+
return ()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class NearestStepRounding:
|
|
36
|
+
"""The nearest multiple of the device's step: a pump's setting step or a syringe's scale.
|
|
37
|
+
|
|
38
|
+
`floor_one_step` keeps a running infusion from rounding to zero. Single doses switch it off,
|
|
39
|
+
so a dose too small to draw rounds to 0 ml and is blocked instead of multiplied (V2-18).
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
offers_choice = False
|
|
43
|
+
|
|
44
|
+
def __init__(self, floor_one_step: bool = True) -> None:
|
|
45
|
+
self._floor = floor_one_step
|
|
46
|
+
|
|
47
|
+
def round(self, value: Quantity, device: DeviceProfile | None) -> Quantity | None:
|
|
48
|
+
if device is None or device.step_size is None:
|
|
49
|
+
return None
|
|
50
|
+
step = device.step_size
|
|
51
|
+
in_steps = CONTEXT.divide(value.to(step.unit).value, step.value)
|
|
52
|
+
steps = in_steps.quantize(Decimal(1), rounding=ROUND_HALF_EVEN, context=CONTEXT)
|
|
53
|
+
if self._floor:
|
|
54
|
+
steps = max(steps, Decimal(1))
|
|
55
|
+
return Quantity(CONTEXT.multiply(steps, step.value), step.unit).to(value.unit)
|
|
56
|
+
|
|
57
|
+
def candidates(self, value: Quantity, device: DeviceProfile | None) -> tuple[Quantity, ...]:
|
|
58
|
+
rounded = self.round(value, device)
|
|
59
|
+
return () if rounded is None else (rounded,)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ChooseStep(NoAutoRounding):
|
|
63
|
+
"""Offer the adjacent device steps for a person to choose."""
|
|
64
|
+
|
|
65
|
+
offers_choice = True
|
|
66
|
+
|
|
67
|
+
def candidates(self, value: Quantity, device: DeviceProfile | None) -> tuple[Quantity, ...]:
|
|
68
|
+
if device is None or device.step_size is None:
|
|
69
|
+
return ()
|
|
70
|
+
return neighbouring_steps(value, device.step_size)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class UnknownRoundingPolicyError(DoseframeError):
|
|
74
|
+
"""A protocol names a rounding rule that no one registered."""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class RoundingPolicyRegistry:
|
|
78
|
+
"""Maps the `rounding_policy_key` of a protocol (approved data) to a registered rule."""
|
|
79
|
+
|
|
80
|
+
NONE = "none"
|
|
81
|
+
|
|
82
|
+
def __init__(self) -> None:
|
|
83
|
+
self._policies: dict[str, RoundingPolicy] = {self.NONE: NoAutoRounding()}
|
|
84
|
+
|
|
85
|
+
def register(self, key: str, policy: RoundingPolicy) -> None:
|
|
86
|
+
if not key.strip():
|
|
87
|
+
raise ValueError("a rounding policy key must not be empty")
|
|
88
|
+
if key in self._policies:
|
|
89
|
+
raise ValueError(f"rounding policy {key!r} is already registered")
|
|
90
|
+
self._policies[key] = policy
|
|
91
|
+
|
|
92
|
+
def get(self, key: str) -> RoundingPolicy:
|
|
93
|
+
try:
|
|
94
|
+
return self._policies[key]
|
|
95
|
+
except KeyError:
|
|
96
|
+
raise UnknownRoundingPolicyError(f"no rounding policy registered as {key!r}") from None
|
|
97
|
+
|
|
98
|
+
def keys(self) -> frozenset[str]:
|
|
99
|
+
return frozenset(self._policies)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def default_registry() -> RoundingPolicyRegistry:
|
|
103
|
+
"""The framework's rules: "none" (default), "nearest_pump_step" (floor), "nearest_step"."""
|
|
104
|
+
registry = RoundingPolicyRegistry()
|
|
105
|
+
registry.register("nearest_pump_step", NearestStepRounding(floor_one_step=True))
|
|
106
|
+
registry.register("nearest_step", NearestStepRounding(floor_one_step=False))
|
|
107
|
+
registry.register("choose_step", ChooseStep())
|
|
108
|
+
return registry
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Values with explicit units: `Quantity`, `Unit`, the unit catalog, and unit errors."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from doseframe.units.catalog import (
|
|
6
|
+
Role,
|
|
7
|
+
is_absolute_dose,
|
|
8
|
+
is_allowed,
|
|
9
|
+
is_weight_based_dose,
|
|
10
|
+
parse_unit,
|
|
11
|
+
require_role,
|
|
12
|
+
unit,
|
|
13
|
+
)
|
|
14
|
+
from doseframe.units.decimal_context import CONTEXT
|
|
15
|
+
from doseframe.units.errors import (
|
|
16
|
+
DoseframeError,
|
|
17
|
+
IncompatibleUnitError,
|
|
18
|
+
UnitError,
|
|
19
|
+
UnitRoleError,
|
|
20
|
+
UnknownUnitError,
|
|
21
|
+
)
|
|
22
|
+
from doseframe.units.options import UnitOptions, dose_unit_options, result_units
|
|
23
|
+
from doseframe.units.quantity import Quantity, format_decimal
|
|
24
|
+
from doseframe.units.unit import DIMENSIONLESS, Atom, Dimension, Unit
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"CONTEXT",
|
|
28
|
+
"DIMENSIONLESS",
|
|
29
|
+
"Atom",
|
|
30
|
+
"Dimension",
|
|
31
|
+
"DoseframeError",
|
|
32
|
+
"IncompatibleUnitError",
|
|
33
|
+
"Quantity",
|
|
34
|
+
"Role",
|
|
35
|
+
"Unit",
|
|
36
|
+
"UnitError",
|
|
37
|
+
"UnitOptions",
|
|
38
|
+
"UnitRoleError",
|
|
39
|
+
"UnknownUnitError",
|
|
40
|
+
"dose_unit_options",
|
|
41
|
+
"format_decimal",
|
|
42
|
+
"is_absolute_dose",
|
|
43
|
+
"is_allowed",
|
|
44
|
+
"is_weight_based_dose",
|
|
45
|
+
"parse_unit",
|
|
46
|
+
"require_role",
|
|
47
|
+
"result_units",
|
|
48
|
+
"unit",
|
|
49
|
+
]
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""The closed catalog of unit symbols, the parser, and the units allowed for each role.
|
|
2
|
+
|
|
3
|
+
Units are only ever parsed from this catalog, never from free text. `kg` always means the
|
|
4
|
+
patient's body mass; drug amounts are never written in kilograms.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from decimal import Decimal
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
from types import MappingProxyType
|
|
13
|
+
|
|
14
|
+
from doseframe.units.errors import UnitRoleError, UnknownUnitError
|
|
15
|
+
from doseframe.units.unit import Atom, Dimension, Unit
|
|
16
|
+
|
|
17
|
+
NG = Atom("ng", Dimension.DRUG_MASS, Decimal("1E-9"))
|
|
18
|
+
UG = Atom("µg", Dimension.DRUG_MASS, Decimal("1E-6"))
|
|
19
|
+
MG = Atom("mg", Dimension.DRUG_MASS, Decimal("1E-3"))
|
|
20
|
+
G = Atom("g", Dimension.DRUG_MASS, Decimal(1))
|
|
21
|
+
IU = Atom("IU", Dimension.DRUG_ACTIVITY, Decimal(1))
|
|
22
|
+
ML = Atom("ml", Dimension.VOLUME, Decimal(1))
|
|
23
|
+
KG = Atom("kg", Dimension.BODY_MASS, Decimal(1))
|
|
24
|
+
G_BODY = Atom("g", Dimension.BODY_MASS, Decimal("1E-3"))
|
|
25
|
+
"""Body mass in grams, for the weight field only (760 g). Drug grams stay `G`."""
|
|
26
|
+
MIN = Atom("min", Dimension.TIME, Decimal(1))
|
|
27
|
+
H = Atom("h", Dimension.TIME, Decimal(60))
|
|
28
|
+
D = Atom("d", Dimension.TIME, Decimal(1440))
|
|
29
|
+
|
|
30
|
+
_ATOMS: MappingProxyType[str, Atom] = MappingProxyType(
|
|
31
|
+
{
|
|
32
|
+
"ng": NG,
|
|
33
|
+
"µg": UG,
|
|
34
|
+
"μg": UG, # Greek small letter mu, which keyboards produce as often as the micro sign
|
|
35
|
+
"ug": UG,
|
|
36
|
+
"mcg": UG,
|
|
37
|
+
"mg": MG,
|
|
38
|
+
"g": G,
|
|
39
|
+
"IU": IU,
|
|
40
|
+
"IE": IU,
|
|
41
|
+
"I.E.": IU,
|
|
42
|
+
"ml": ML,
|
|
43
|
+
"mL": ML,
|
|
44
|
+
"kg": KG,
|
|
45
|
+
"min": MIN,
|
|
46
|
+
"h": H,
|
|
47
|
+
"d": D,
|
|
48
|
+
"Tag": D,
|
|
49
|
+
}
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
DRUG_AMOUNT_ATOMS = frozenset({NG, UG, MG, G, IU})
|
|
53
|
+
DOSE_AMOUNT_ATOMS = frozenset({NG, UG, MG, IU})
|
|
54
|
+
FACTOR_AMOUNT_ATOMS = frozenset({UG, MG, IU})
|
|
55
|
+
TIME_ATOMS = frozenset({MIN, H, D})
|
|
56
|
+
|
|
57
|
+
_WEIGHT_ATOMS: MappingProxyType[str, Atom] = MappingProxyType({"kg": KG, "g": G_BODY})
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def parse_unit(text: str, role: Role | None = None) -> Unit:
|
|
61
|
+
"""Parse a symbol such as ``µg/kg/min``. Every atom after a slash divides.
|
|
62
|
+
|
|
63
|
+
With `Role.WEIGHT` the symbol is a body mass: "g" means body grams, not drug grams.
|
|
64
|
+
"""
|
|
65
|
+
if role is Role.WEIGHT:
|
|
66
|
+
atom = _WEIGHT_ATOMS.get(text.strip())
|
|
67
|
+
if atom is None:
|
|
68
|
+
raise UnknownUnitError(f"{text!r} is not a weight unit")
|
|
69
|
+
return Unit(((atom, 1),))
|
|
70
|
+
parts = [part.strip() for part in text.strip().split("/")]
|
|
71
|
+
if not parts or any(not part for part in parts):
|
|
72
|
+
raise UnknownUnitError(f"not a unit: {text!r}")
|
|
73
|
+
atoms: list[Atom] = []
|
|
74
|
+
for part in parts:
|
|
75
|
+
atom = _ATOMS.get(part)
|
|
76
|
+
if atom is None:
|
|
77
|
+
raise UnknownUnitError(f"unknown unit symbol {part!r} in {text!r}")
|
|
78
|
+
atoms.append(atom)
|
|
79
|
+
seen = {atom.dimension for atom in atoms}
|
|
80
|
+
if len(seen) != len(atoms):
|
|
81
|
+
raise UnknownUnitError(f"a dimension appears twice in {text!r}")
|
|
82
|
+
head, *rest = atoms
|
|
83
|
+
return Unit(((head, 1), *((atom, -1) for atom in rest)))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def unit(text: str) -> Unit:
|
|
87
|
+
"""Shorthand for `parse_unit`, for code and tests that name a unit literally."""
|
|
88
|
+
return parse_unit(text)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class Role(StrEnum):
|
|
92
|
+
"""The part a value plays in a calculation. Each role allows a fixed set of units."""
|
|
93
|
+
|
|
94
|
+
WEIGHT = "weight"
|
|
95
|
+
DOSE = "dose"
|
|
96
|
+
CONCENTRATION = "concentration"
|
|
97
|
+
PREPARATION_FACTOR = "preparation_factor"
|
|
98
|
+
DRUG_AMOUNT = "drug_amount"
|
|
99
|
+
VOLUME = "volume"
|
|
100
|
+
RATE = "rate"
|
|
101
|
+
DURATION = "duration"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def is_allowed(u: Unit, role: Role) -> bool:
|
|
105
|
+
return _ROLE_RULES[role](u)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def is_weight_based_dose(u: Unit) -> bool:
|
|
109
|
+
terms = u.terms
|
|
110
|
+
return (
|
|
111
|
+
len(terms) == 3
|
|
112
|
+
and terms[0][0] in DOSE_AMOUNT_ATOMS
|
|
113
|
+
and terms[0][1] == 1
|
|
114
|
+
and terms[1] == (KG, -1)
|
|
115
|
+
and terms[2][0] in TIME_ATOMS
|
|
116
|
+
and terms[2][1] == -1
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def is_absolute_dose(u: Unit) -> bool:
|
|
121
|
+
terms = u.terms
|
|
122
|
+
return (
|
|
123
|
+
len(terms) == 2
|
|
124
|
+
and terms[0][0] in DOSE_AMOUNT_ATOMS
|
|
125
|
+
and terms[0][1] == 1
|
|
126
|
+
and terms[1][0] in TIME_ATOMS
|
|
127
|
+
and terms[1][1] == -1
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
_ROLE_RULES: MappingProxyType[Role, Callable[[Unit], bool]] = MappingProxyType(
|
|
132
|
+
{
|
|
133
|
+
Role.WEIGHT: lambda u: u.terms in (((KG, 1),), ((G_BODY, 1),)),
|
|
134
|
+
Role.DURATION: lambda u: u.terms in (((MIN, 1),), ((H, 1),)),
|
|
135
|
+
Role.VOLUME: lambda u: u.terms == ((ML, 1),),
|
|
136
|
+
Role.RATE: lambda u: u.terms == ((ML, 1), (H, -1)),
|
|
137
|
+
Role.DRUG_AMOUNT: lambda u: (
|
|
138
|
+
len(u.terms) == 1 and u.terms[0][1] == 1 and u.terms[0][0] in DRUG_AMOUNT_ATOMS
|
|
139
|
+
),
|
|
140
|
+
Role.CONCENTRATION: lambda u: _amount_per(u.terms, DOSE_AMOUNT_ATOMS, ML),
|
|
141
|
+
Role.PREPARATION_FACTOR: lambda u: _amount_per(u.terms, FACTOR_AMOUNT_ATOMS, KG),
|
|
142
|
+
Role.DOSE: lambda u: is_weight_based_dose(u) or is_absolute_dose(u),
|
|
143
|
+
}
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def require_role(u: Unit, role: Role) -> Unit:
|
|
148
|
+
"""Return the unit if it is allowed for the role, otherwise raise `UnitRoleError`."""
|
|
149
|
+
if not is_allowed(u, role):
|
|
150
|
+
raise UnitRoleError(f"{u.symbol} is not allowed as {role.value}")
|
|
151
|
+
return u
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _amount_per(terms: tuple[tuple[Atom, int], ...], amounts: frozenset[Atom], per: Atom) -> bool:
|
|
155
|
+
return len(terms) == 2 and terms[0][0] in amounts and terms[0][1] == 1 and terms[1] == (per, -1)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""The one decimal context used for all arithmetic.
|
|
2
|
+
|
|
3
|
+
34 significant digits (decimal128). Invalid operations, division by zero and overflow raise
|
|
4
|
+
instead of producing NaN or infinity, so no calculation can quietly return a non-number. The
|
|
5
|
+
context is used explicitly, never installed globally, so code that imports the library keeps its
|
|
6
|
+
own decimal settings.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from decimal import ROUND_HALF_EVEN, Context, DivisionByZero, InvalidOperation, Overflow
|
|
12
|
+
|
|
13
|
+
CONTEXT = Context(
|
|
14
|
+
prec=34,
|
|
15
|
+
rounding=ROUND_HALF_EVEN,
|
|
16
|
+
traps=[InvalidOperation, DivisionByZero, Overflow],
|
|
17
|
+
)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Errors raised by the framework.
|
|
2
|
+
|
|
3
|
+
`DoseframeError` is the base of every error the library raises on purpose. Code that calls the
|
|
4
|
+
library can rely on it: a calculation either returns a value with a unit or raises one of these.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class DoseframeError(Exception):
|
|
11
|
+
"""Base class for every error the framework raises on purpose."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class UnitError(DoseframeError):
|
|
15
|
+
"""A unit is unknown, used in the wrong place, or cannot be converted."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class UnknownUnitError(UnitError):
|
|
19
|
+
"""A unit symbol is not in the catalog."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class IncompatibleUnitError(UnitError):
|
|
23
|
+
"""Two quantities of different dimensions were combined or converted."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class UnitRoleError(UnitError):
|
|
27
|
+
"""A unit is valid but not allowed for the role a value plays, such as mg/kg as a dose."""
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Which dose units a person may pick, and in which units a result may be shown."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from doseframe.units.catalog import DOSE_AMOUNT_ATOMS, KG, TIME_ATOMS
|
|
9
|
+
from doseframe.units.unit import Atom, Unit
|
|
10
|
+
|
|
11
|
+
_AMOUNT_ORDER = ("ng", "µg", "mg", "IU")
|
|
12
|
+
_TIME_ORDER = ("min", "h", "d")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class UnitOptions:
|
|
17
|
+
default: Unit
|
|
18
|
+
usual: tuple[Unit, ...]
|
|
19
|
+
more: tuple[Unit, ...]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def dose_unit_options(default: Unit, usual: Sequence[Unit] = ()) -> UnitOptions:
|
|
23
|
+
"""Every catalog dose unit of the same kind as `default`, in reading order."""
|
|
24
|
+
taken = {default, *usual}
|
|
25
|
+
more = tuple(u for u in _all_dose_units() if u.is_compatible(default) and u not in taken)
|
|
26
|
+
return UnitOptions(default, tuple(usual), more)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def result_units(default: Unit, usual: Sequence[Unit]) -> tuple[Unit, ...]:
|
|
30
|
+
"""The units a result is offered in: the protocol's unit, then its usual units (V2-02)."""
|
|
31
|
+
seen: list[Unit] = [default]
|
|
32
|
+
for u in usual:
|
|
33
|
+
if u not in seen:
|
|
34
|
+
seen.append(u)
|
|
35
|
+
return tuple(seen)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _all_dose_units() -> list[Unit]:
|
|
39
|
+
amounts = sorted(DOSE_AMOUNT_ATOMS, key=lambda a: _AMOUNT_ORDER.index(a.symbol))
|
|
40
|
+
times = sorted(TIME_ATOMS, key=lambda a: _TIME_ORDER.index(a.symbol))
|
|
41
|
+
units: list[Unit] = []
|
|
42
|
+
for amount in amounts:
|
|
43
|
+
for time in times:
|
|
44
|
+
units.append(_unit(amount, KG, time))
|
|
45
|
+
units.append(_unit(amount, None, time))
|
|
46
|
+
return units
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _unit(amount: Atom, per_weight: Atom | None, time: Atom) -> Unit:
|
|
50
|
+
if per_weight is None:
|
|
51
|
+
return Unit(((amount, 1), (time, -1)))
|
|
52
|
+
return Unit(((amount, 1), (per_weight, -1), (time, -1)))
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""`Quantity`: a decimal value that always carries its unit."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from decimal import Decimal, InvalidOperation
|
|
7
|
+
from functools import total_ordering
|
|
8
|
+
|
|
9
|
+
from doseframe.units.catalog import Role, is_allowed, parse_unit, require_role
|
|
10
|
+
from doseframe.units.decimal_context import CONTEXT
|
|
11
|
+
from doseframe.units.errors import IncompatibleUnitError, UnitError
|
|
12
|
+
from doseframe.units.unit import Unit
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@total_ordering
|
|
16
|
+
@dataclass(frozen=True, slots=True, eq=False)
|
|
17
|
+
class Quantity:
|
|
18
|
+
"""An immutable value with a unit.
|
|
19
|
+
|
|
20
|
+
Values are `Decimal` only: a float would bring binary rounding into a dose, so it is refused.
|
|
21
|
+
Two quantities are equal when they describe the same physical amount, so 1 mg equals 1000 µg.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
value: Decimal
|
|
25
|
+
unit: Unit
|
|
26
|
+
|
|
27
|
+
def __post_init__(self) -> None:
|
|
28
|
+
if not isinstance(self.value, Decimal):
|
|
29
|
+
raise TypeError(
|
|
30
|
+
f"Quantity value must be a Decimal, got {type(self.value).__name__}; "
|
|
31
|
+
"use Quantity.of('0.096', 'ml/h')"
|
|
32
|
+
)
|
|
33
|
+
if not self.value.is_finite():
|
|
34
|
+
raise UnitError(f"Quantity value must be finite, got {self.value}")
|
|
35
|
+
if not isinstance(self.unit, Unit):
|
|
36
|
+
raise TypeError(f"Quantity unit must be a Unit, got {type(self.unit).__name__}")
|
|
37
|
+
|
|
38
|
+
@classmethod
|
|
39
|
+
def of(cls, value: str | Decimal | int, unit: str | Unit, role: Role | None = None) -> Quantity:
|
|
40
|
+
"""Build a quantity from a decimal string (or Decimal or int) and a unit symbol.
|
|
41
|
+
|
|
42
|
+
With `role`, the unit must be one of the units allowed for that role.
|
|
43
|
+
"""
|
|
44
|
+
if isinstance(value, bool) or not isinstance(value, (str, Decimal, int)):
|
|
45
|
+
raise TypeError(f"value must be a decimal string, Decimal or int, not {value!r}")
|
|
46
|
+
try:
|
|
47
|
+
number = Decimal(value) if not isinstance(value, Decimal) else value
|
|
48
|
+
except InvalidOperation as exc:
|
|
49
|
+
raise UnitError(f"not a decimal number: {value!r}") from exc
|
|
50
|
+
u = parse_unit(unit, role) if isinstance(unit, str) else unit
|
|
51
|
+
if role is not None:
|
|
52
|
+
require_role(u, role)
|
|
53
|
+
return cls(number, u)
|
|
54
|
+
|
|
55
|
+
# --- conversion -------------------------------------------------------------------------
|
|
56
|
+
|
|
57
|
+
def to(self, target: Unit | str) -> Quantity:
|
|
58
|
+
"""Convert exactly to another unit of the same dimension."""
|
|
59
|
+
u = parse_unit(target) if isinstance(target, str) else target
|
|
60
|
+
return Quantity(self.unit.convert(self.value, u), u)
|
|
61
|
+
|
|
62
|
+
def has_role(self, role: Role) -> bool:
|
|
63
|
+
return is_allowed(self.unit, role)
|
|
64
|
+
|
|
65
|
+
def is_positive(self) -> bool:
|
|
66
|
+
return self.value > 0
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def symbol(self) -> str:
|
|
70
|
+
return self.unit.symbol
|
|
71
|
+
|
|
72
|
+
# --- arithmetic -------------------------------------------------------------------------
|
|
73
|
+
|
|
74
|
+
def __mul__(self, other: Quantity | Decimal | int) -> Quantity:
|
|
75
|
+
if isinstance(other, Quantity):
|
|
76
|
+
product_unit, num, den = self.unit.multiply(other.unit)
|
|
77
|
+
top = CONTEXT.multiply(CONTEXT.multiply(self.value, other.value), num)
|
|
78
|
+
return Quantity(CONTEXT.divide(top, den), product_unit)
|
|
79
|
+
return Quantity(CONTEXT.multiply(self.value, _scalar(other)), self.unit)
|
|
80
|
+
|
|
81
|
+
__rmul__ = __mul__
|
|
82
|
+
|
|
83
|
+
def __truediv__(self, other: Quantity | Decimal | int) -> Quantity:
|
|
84
|
+
if isinstance(other, Quantity):
|
|
85
|
+
product_unit, num, den = self.unit.multiply(other.unit.inverse())
|
|
86
|
+
top = CONTEXT.multiply(self.value, num)
|
|
87
|
+
return Quantity(CONTEXT.divide(top, CONTEXT.multiply(other.value, den)), product_unit)
|
|
88
|
+
return Quantity(CONTEXT.divide(self.value, _scalar(other)), self.unit)
|
|
89
|
+
|
|
90
|
+
def __add__(self, other: Quantity) -> Quantity:
|
|
91
|
+
return Quantity(CONTEXT.add(self.value, self._aligned(other)), self.unit)
|
|
92
|
+
|
|
93
|
+
def __sub__(self, other: Quantity) -> Quantity:
|
|
94
|
+
return Quantity(CONTEXT.subtract(self.value, self._aligned(other)), self.unit)
|
|
95
|
+
|
|
96
|
+
# --- comparison -------------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
def __eq__(self, other: object) -> bool:
|
|
99
|
+
if not isinstance(other, Quantity):
|
|
100
|
+
return NotImplemented
|
|
101
|
+
if not self.unit.is_compatible(other.unit):
|
|
102
|
+
return False
|
|
103
|
+
return self.value == self._aligned(other)
|
|
104
|
+
|
|
105
|
+
def __lt__(self, other: Quantity) -> bool:
|
|
106
|
+
return self.value < self._aligned(other)
|
|
107
|
+
|
|
108
|
+
def __hash__(self) -> int:
|
|
109
|
+
num, den = self.unit.scale
|
|
110
|
+
base = CONTEXT.divide(CONTEXT.multiply(self.value, num), den).normalize(CONTEXT)
|
|
111
|
+
return hash((base, tuple(sorted(self.unit.dimensions.items()))))
|
|
112
|
+
|
|
113
|
+
def _aligned(self, other: Quantity) -> Decimal:
|
|
114
|
+
if not isinstance(other, Quantity):
|
|
115
|
+
raise TypeError(f"expected a Quantity, got {type(other).__name__}")
|
|
116
|
+
if not self.unit.is_compatible(other.unit):
|
|
117
|
+
raise IncompatibleUnitError(
|
|
118
|
+
f"cannot compare or combine {self.unit.symbol} with {other.unit.symbol}"
|
|
119
|
+
)
|
|
120
|
+
return other.unit.convert(other.value, self.unit)
|
|
121
|
+
|
|
122
|
+
# --- presentation -----------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
def plain(self) -> str:
|
|
125
|
+
"""The value as a plain decimal string without exponent and trailing zeros."""
|
|
126
|
+
return format_decimal(self.value)
|
|
127
|
+
|
|
128
|
+
def __str__(self) -> str:
|
|
129
|
+
return f"{self.plain()} {self.unit.symbol}"
|
|
130
|
+
|
|
131
|
+
def __repr__(self) -> str:
|
|
132
|
+
return f"Quantity.of({self.plain()!r}, {self.unit.symbol!r})"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def format_decimal(value: Decimal) -> str:
|
|
136
|
+
"""A plain decimal string: no exponent, no trailing zeros, always a leading zero."""
|
|
137
|
+
text = format(value.normalize(CONTEXT), "f")
|
|
138
|
+
return "0" if text in {"-0", ""} else text
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _scalar(value: Decimal | int) -> Decimal:
|
|
142
|
+
if isinstance(value, bool) or not isinstance(value, (Decimal, int)):
|
|
143
|
+
raise TypeError(f"a Quantity can only be scaled by a Decimal or int, not {value!r}")
|
|
144
|
+
return Decimal(value)
|