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.
Files changed (46) hide show
  1. doseframe/__init__.py +252 -0
  2. doseframe/calculation/__init__.py +34 -0
  3. doseframe/calculation/derivation.py +30 -0
  4. doseframe/calculation/errors.py +16 -0
  5. doseframe/calculation/infusion.py +27 -0
  6. doseframe/calculation/relation.py +129 -0
  7. doseframe/calculation/single_dose.py +54 -0
  8. doseframe/calculation/steps.py +20 -0
  9. doseframe/calculation/strategies.py +105 -0
  10. doseframe/calculation/strategy.py +37 -0
  11. doseframe/checks/__init__.py +20 -0
  12. doseframe/checks/chain.py +212 -0
  13. doseframe/checks/context.py +43 -0
  14. doseframe/findings/__init__.py +58 -0
  15. doseframe/protocols/__init__.py +103 -0
  16. doseframe/protocols/activation.py +51 -0
  17. doseframe/protocols/device.py +51 -0
  18. doseframe/protocols/diff.py +70 -0
  19. doseframe/protocols/errors.py +26 -0
  20. doseframe/protocols/limits.py +74 -0
  21. doseframe/protocols/model.py +40 -0
  22. doseframe/protocols/naming.py +126 -0
  23. doseframe/protocols/reference.py +163 -0
  24. doseframe/protocols/schemes.py +598 -0
  25. doseframe/protocols/single_dose.py +253 -0
  26. doseframe/protocols/version.py +690 -0
  27. doseframe/py.typed +0 -0
  28. doseframe/rounding/__init__.py +23 -0
  29. doseframe/rounding/policy.py +108 -0
  30. doseframe/units/__init__.py +49 -0
  31. doseframe/units/catalog.py +155 -0
  32. doseframe/units/decimal_context.py +17 -0
  33. doseframe/units/errors.py +27 -0
  34. doseframe/units/options.py +52 -0
  35. doseframe/units/quantity.py +144 -0
  36. doseframe/units/unit.py +137 -0
  37. doseframe/use_cases/__init__.py +73 -0
  38. doseframe/use_cases/clinical.py +735 -0
  39. doseframe/use_cases/gate.py +85 -0
  40. doseframe/use_cases/governance.py +460 -0
  41. doseframe/use_cases/ports.py +73 -0
  42. doseframe/use_cases/results.py +182 -0
  43. doseframe-0.2.0.dist-info/METADATA +79 -0
  44. doseframe-0.2.0.dist-info/RECORD +46 -0
  45. doseframe-0.2.0.dist-info/WHEEL +4 -0
  46. doseframe-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,74 @@
1
+ """Weight ranges and limits: approved protocol data, never developer decisions (PR-02)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterable
6
+ from dataclasses import dataclass
7
+ from enum import StrEnum
8
+
9
+ from doseframe.findings import Severity
10
+ from doseframe.protocols.device import Range
11
+ from doseframe.units import Quantity
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class WeightScope:
16
+ """A half-open weight range: lower ≤ weight < upper.
17
+
18
+ The lower limit is included and the upper limit excluded, so a child of exactly 10.0 kg uses
19
+ the protocol "from 10 kg" (confirmed by the senior physician). Either bound may be open.
20
+ """
21
+
22
+ lower: Quantity | None = None
23
+ upper: Quantity | None = None
24
+
25
+ def contains(self, weight: Quantity) -> bool:
26
+ if self.lower is not None and weight < self.lower:
27
+ return False
28
+ return not (self.upper is not None and weight >= self.upper)
29
+
30
+ def describe(self) -> str:
31
+ low = str(self.lower) if self.lower is not None else "0 kg"
32
+ high = str(self.upper) if self.upper is not None else "∞"
33
+ return f"[{low}, {high})"
34
+
35
+
36
+ class LimitTarget(StrEnum):
37
+ DOSE = "dose"
38
+ RATE = "rate"
39
+ WITHDRAWAL_VOLUME = "withdrawal_volume"
40
+ SETTING = "setting"
41
+
42
+
43
+ @dataclass(frozen=True, slots=True)
44
+ class Limit:
45
+ """A warning or hard limit on one value, with its written justification.
46
+
47
+ A value below `lower` or above `upper` gives a finding with this limit's severity.
48
+ """
49
+
50
+ target: LimitTarget
51
+ severity: Severity
52
+ justification: str
53
+ lower: Quantity | None = None
54
+ upper: Quantity | None = None
55
+
56
+ def violated_by(self, value: Quantity) -> Quantity | None:
57
+ """The bound the value crosses, or None."""
58
+ if self.lower is not None and value < self.lower:
59
+ return self.lower
60
+ if self.upper is not None and value > self.upper:
61
+ return self.upper
62
+ return None
63
+
64
+
65
+ def usual_range(limits: Iterable[Limit]) -> Range | None:
66
+ """The usual dose range: the bounds of the one WARN dose limit, if exactly one exists."""
67
+ warn = [
68
+ limit
69
+ for limit in limits
70
+ if limit.target is LimitTarget.DOSE and limit.severity is Severity.WARN
71
+ ]
72
+ if len(warn) != 1:
73
+ return None
74
+ return Range(warn[0].lower, warn[0].upper)
@@ -0,0 +1,40 @@
1
+ """Medications, protocols, and the people who act on them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from enum import StrEnum
7
+
8
+
9
+ @dataclass(frozen=True, slots=True)
10
+ class Medication:
11
+ id: str
12
+ name: str
13
+ active_ingredient: str
14
+ trade_names: tuple[str, ...] = ()
15
+
16
+
17
+ @dataclass(frozen=True, slots=True)
18
+ class Protocol:
19
+ """The identity of a protocol: one medication, one named rule. Its content is versioned."""
20
+
21
+ id: str
22
+ medication_id: str
23
+ name: str
24
+
25
+
26
+ class UserRole(StrEnum):
27
+ EDITOR = "editor" # drafts and submits protocol versions
28
+ APPROVER = "approver" # reviews, approves and withdraws (a physician in this hospital)
29
+ ADMIN = "admin" # manages accounts; grants no right over medical content
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class Actor:
34
+ """A person acting in the protocol office, with the roles the user directory gives them."""
35
+
36
+ user_id: str
37
+ roles: frozenset[UserRole] = field(default_factory=frozenset)
38
+
39
+ def has(self, role: UserRole) -> bool:
40
+ return role in self.roles
@@ -0,0 +1,126 @@
1
+ """The standard protocol name, built from the version's content (V3-12).
2
+
3
+ A name is never typed. It is drug, final strength, carrier (or, for a single dose, the syringe)
4
+ and weight range in a fixed order, always with all parts:
5
+
6
+ Adrenalin 30 µg/ml · G 5 % · < 10 kg
7
+ Insulin 0.1 IU/kg/ml · NaCl 0.9 % · alle Gewichte
8
+ Ampicillin 100 mg/ml · 1-ml-Spritze · < 1 kg
9
+
10
+ An optional addition typed in the office ("Arterienperfusor") follows the generated part and
11
+ never replaces it. The parts that tell two protocols apart (`identity`) may not change once a
12
+ protocol has an approved version: a different strength, carrier, syringe or weight range is a
13
+ new protocol, so a syringe made up from an older version always matches its name.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass, replace
19
+
20
+ from doseframe.protocols.device import DeviceProfile
21
+ from doseframe.protocols.limits import WeightScope
22
+ from doseframe.protocols.schemes import PreparationScheme
23
+ from doseframe.units import Quantity
24
+ from doseframe.units.unit import Dimension
25
+
26
+ SEPARATOR = " · "
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class ProtocolTitle:
31
+ """The parts of a standard protocol name. A part the content does not define is None."""
32
+
33
+ drug: str
34
+ strength: Quantity | None
35
+ carrier: str | None
36
+ syringe: Quantity | None
37
+ weight: WeightScope
38
+ addition: str = ""
39
+
40
+ @property
41
+ def identity(self) -> tuple[object, ...]:
42
+ """What tells this protocol apart from its siblings; fixed after the first approval."""
43
+ return (self.strength, self.carrier, self.syringe, self.weight)
44
+
45
+ def shown_with(self, plausible: WeightScope | None) -> ProtocolTitle:
46
+ """The title with bounds that equal the plausible weight range shown as open.
47
+
48
+ The stored bounds stay in the protocol (they keep an implausible weight out); only the
49
+ name drops them, so "0.3 to < 10 kg" reads "< 10 kg".
50
+ """
51
+ if plausible is None:
52
+ return self
53
+ lower = None if _same(self.weight.lower, plausible.lower) else self.weight.lower
54
+ upper = None if _same(self.weight.upper, plausible.upper) else self.weight.upper
55
+ return replace(self, weight=WeightScope(lower, upper))
56
+
57
+ def text(self) -> str:
58
+ """The canonical German text; the web renders the same parts per language."""
59
+ head = self.drug if self.strength is None else f"{self.drug} {_de(self.strength)}"
60
+ parts = [head]
61
+ if self.carrier:
62
+ parts.append(self.carrier)
63
+ if self.syringe is not None:
64
+ parts.append(f"{_de_number(self.syringe)}-{self.syringe.unit.symbol}-Spritze")
65
+ parts.append(describe_weight(self.weight))
66
+ name = SEPARATOR.join(parts)
67
+ return f"{name}{SEPARATOR}{self.addition}" if self.addition else name
68
+
69
+
70
+ def title_of(
71
+ drug: str,
72
+ scheme: PreparationScheme,
73
+ weight: WeightScope,
74
+ device: DeviceProfile | None,
75
+ addition: str = "",
76
+ ) -> ProtocolTitle:
77
+ """The title of a version from its scheme, weight range and pump or syringe profile."""
78
+ return ProtocolTitle(
79
+ drug=drug,
80
+ strength=scheme.named_strength(),
81
+ carrier=scheme.named_carrier(),
82
+ syringe=_syringe_volume(device) if scheme.names_syringe else None,
83
+ weight=weight,
84
+ addition=addition.strip(),
85
+ )
86
+
87
+
88
+ def describe_weight(weight: WeightScope) -> str:
89
+ """The half-open range in words: lower included, upper excluded (`WeightScope`)."""
90
+ lower, upper = weight.lower, weight.upper
91
+ if lower is None and upper is None:
92
+ return "alle Gewichte"
93
+ if lower is None:
94
+ assert upper is not None
95
+ return f"< {_de(upper)}"
96
+ if upper is None:
97
+ return f"≥ {_de(lower)}"
98
+ if lower.unit == upper.unit:
99
+ return f"{_de_number(lower)} bis < {_de(upper)}"
100
+ return f"{_de(lower)} bis < {_de(upper)}"
101
+
102
+
103
+ def _syringe_volume(device: DeviceProfile | None) -> Quantity | None:
104
+ """The syringe's capacity: the most its profile lets one draw."""
105
+ if device is None:
106
+ return None
107
+ ranges = (device.settable_range, device.approved_range)
108
+ upper = next((r.upper for r in ranges if r is not None and r.upper is not None), None)
109
+ if upper is None or dict(upper.unit.dimensions) != {Dimension.VOLUME: 1}:
110
+ return None
111
+ return upper
112
+
113
+
114
+ def _same(a: Quantity | None, b: Quantity | None) -> bool:
115
+ if a is None or b is None:
116
+ return a is b
117
+ return a.unit.is_compatible(b.unit) and a == b
118
+
119
+
120
+ def _de_number(q: Quantity) -> str:
121
+ text = format(q.value.normalize(), "f")
122
+ return text.replace(".", ",")
123
+
124
+
125
+ def _de(q: Quantity) -> str:
126
+ return f"{_de_number(q)} {q.unit.symbol}"
@@ -0,0 +1,163 @@
1
+ """Reference cases: worked examples with known results that a version must reproduce."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from decimal import Decimal
7
+ from enum import StrEnum
8
+ from typing import cast
9
+
10
+ from doseframe.findings import Severity, blocking
11
+ from doseframe.protocols.limits import Limit, LimitTarget
12
+ from doseframe.protocols.schemes import (
13
+ InfusionScheme,
14
+ PreparationScheme,
15
+ SingleDoseScheme,
16
+ Workflow,
17
+ )
18
+ from doseframe.protocols.single_dose import (
19
+ SingleDoseSetup,
20
+ evaluate_single_dose,
21
+ )
22
+ from doseframe.units import DoseframeError, Quantity, Role, Unit, is_allowed, unit
23
+
24
+
25
+ class CaseDirection(StrEnum):
26
+ DOSE_TO_RATE = "dose_to_rate"
27
+ RATE_TO_DOSE = "rate_to_dose"
28
+ DAILY_DOSE_TO_ADMINISTRATION = "daily_dose_to_administration"
29
+
30
+ @property
31
+ def workflow(self) -> Workflow:
32
+ return (
33
+ Workflow.SINGLE_DOSE
34
+ if self is CaseDirection.DAILY_DOSE_TO_ADMINISTRATION
35
+ else Workflow.INFUSION
36
+ )
37
+
38
+
39
+ @dataclass(frozen=True, slots=True)
40
+ class ReferenceCase:
41
+ """A worked example: for this weight and input, the protocol must give `expected`.
42
+
43
+ `expected` is written with the precision the clinician checked, and a computed value passes
44
+ when it equals `expected` rounded to that many decimal places (0.020833 matches 0.0208333…).
45
+ A single-dose case also names its `stock_label` and the `expected_volume` to draw.
46
+ """
47
+
48
+ direction: CaseDirection
49
+ weight: Quantity
50
+ input: Quantity
51
+ expected: Quantity
52
+ stock_label: str | None = None
53
+ expected_volume: Quantity | None = None
54
+
55
+ def evaluate(
56
+ self,
57
+ scheme: PreparationScheme,
58
+ dose_unit: Unit,
59
+ setup: SingleDoseSetup | None = None,
60
+ limits: tuple[Limit, ...] = (),
61
+ max_deviation: Decimal | None = None,
62
+ ) -> CaseResult:
63
+ if scheme.workflow is not self.direction.workflow:
64
+ return CaseResult(self, None, passed=False, error="case does not fit the workflow")
65
+ if self.direction is CaseDirection.DAILY_DOSE_TO_ADMINISTRATION:
66
+ return self._evaluate_single_dose(
67
+ cast(SingleDoseScheme, scheme), dose_unit, setup, limits, max_deviation
68
+ )
69
+ strategy = cast(InfusionScheme, scheme).create_strategy() # only infusion has rates
70
+ try:
71
+ if self.direction is CaseDirection.DOSE_TO_RATE:
72
+ computed = strategy.dose_to_rate(self.input, self.weight).value
73
+ else:
74
+ computed = strategy.rate_to_dose(self.input, self.weight, dose_unit).value
75
+ computed = computed.to(self.expected.unit)
76
+ except DoseframeError as exc:
77
+ return CaseResult(self, None, passed=False, error=str(exc))
78
+ return CaseResult(self, computed, passed=_matches(computed, self.expected))
79
+
80
+ def _evaluate_single_dose( # noqa: PLR0911
81
+ self,
82
+ scheme: SingleDoseScheme,
83
+ dose_unit: Unit,
84
+ setup: SingleDoseSetup | None,
85
+ limits: tuple[Limit, ...],
86
+ max_deviation: Decimal | None,
87
+ ) -> CaseResult:
88
+ if self.expected_volume is None:
89
+ return CaseResult(self, None, passed=False, error="expected_volume is required")
90
+ if not scheme.stock_solutions:
91
+ return CaseResult(self, None, passed=False, error="no stock solution")
92
+ try:
93
+ stock = scheme.stock(self.stock_label or scheme.stock_solutions[0].label)
94
+ outcome = evaluate_single_dose(
95
+ scheme, stock, self.input, self.weight, setup, max_deviation
96
+ )
97
+ if blocking(outcome.findings):
98
+ codes = "; ".join(f.code for f in outcome.findings)
99
+ return CaseResult(self, outcome.rounded, passed=False, error=codes)
100
+ for option in outcome.options:
101
+ if option.amount is None or not option.is_usable():
102
+ continue
103
+ amount = option.amount.to(self.expected.unit)
104
+ if outcome.offers_choice:
105
+ matches = amount == self.expected and option.volume == self.expected_volume
106
+ else:
107
+ matches = _matches(amount, self.expected) and _matches(
108
+ option.volume, self.expected_volume
109
+ )
110
+ if not matches:
111
+ continue
112
+ assert option.delivered_daily_dose is not None
113
+ values = {
114
+ LimitTarget.DOSE: (self.input, option.delivered_daily_dose),
115
+ LimitTarget.WITHDRAWAL_VOLUME: (option.volume,),
116
+ }
117
+ outside = any(
118
+ limit.violated_by(value)
119
+ for limit in limits
120
+ if limit.severity is Severity.BLOCK
121
+ for value in values.get(limit.target, ())
122
+ )
123
+ if not outside:
124
+ return CaseResult(self, option.amount, passed=True)
125
+ return CaseResult(
126
+ self, option.amount, passed=False, error="outside a hard protocol limit"
127
+ )
128
+ except DoseframeError as exc:
129
+ return CaseResult(self, None, passed=False, error=str(exc))
130
+ if outcome.offers_choice:
131
+ return CaseResult(
132
+ self, None, passed=False, error="expected drawable option unavailable"
133
+ )
134
+ return CaseResult(self, outcome.rounded, passed=False)
135
+
136
+ def units_fit(self, dose_unit: Unit) -> bool:
137
+ if not is_allowed(self.weight.unit, Role.WEIGHT):
138
+ return False
139
+ if self.direction is CaseDirection.DAILY_DOSE_TO_ADMINISTRATION:
140
+ return (
141
+ self.input.unit == dose_unit
142
+ and is_allowed(self.expected.unit, Role.DRUG_AMOUNT)
143
+ and (self.expected_volume is None or self.expected_volume.unit == unit("ml"))
144
+ )
145
+ if self.direction is CaseDirection.DOSE_TO_RATE:
146
+ return self.input.unit == dose_unit and is_allowed(self.expected.unit, Role.RATE)
147
+ return is_allowed(self.input.unit, Role.RATE) and self.expected.unit == dose_unit
148
+
149
+
150
+ @dataclass(frozen=True, slots=True)
151
+ class CaseResult:
152
+ case: ReferenceCase
153
+ computed: Quantity | None
154
+ passed: bool
155
+ error: str | None = None
156
+
157
+
158
+ def _matches(computed: Quantity, expected: Quantity) -> bool:
159
+ """A computed value matches when it equals `expected` rounded to its decimal places."""
160
+ exponent = expected.value.as_tuple().exponent
161
+ if not isinstance(exponent, int):
162
+ return False
163
+ return computed.value.quantize(expected.value) == expected.value