doseframe 0.2.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.
Files changed (46) hide show
  1. doseframe-0.2.0/LICENSE +21 -0
  2. doseframe-0.2.0/PKG-INFO +79 -0
  3. doseframe-0.2.0/README.md +66 -0
  4. doseframe-0.2.0/pyproject.toml +28 -0
  5. doseframe-0.2.0/src/doseframe/__init__.py +252 -0
  6. doseframe-0.2.0/src/doseframe/calculation/__init__.py +34 -0
  7. doseframe-0.2.0/src/doseframe/calculation/derivation.py +30 -0
  8. doseframe-0.2.0/src/doseframe/calculation/errors.py +16 -0
  9. doseframe-0.2.0/src/doseframe/calculation/infusion.py +27 -0
  10. doseframe-0.2.0/src/doseframe/calculation/relation.py +129 -0
  11. doseframe-0.2.0/src/doseframe/calculation/single_dose.py +54 -0
  12. doseframe-0.2.0/src/doseframe/calculation/steps.py +20 -0
  13. doseframe-0.2.0/src/doseframe/calculation/strategies.py +105 -0
  14. doseframe-0.2.0/src/doseframe/calculation/strategy.py +37 -0
  15. doseframe-0.2.0/src/doseframe/checks/__init__.py +20 -0
  16. doseframe-0.2.0/src/doseframe/checks/chain.py +212 -0
  17. doseframe-0.2.0/src/doseframe/checks/context.py +43 -0
  18. doseframe-0.2.0/src/doseframe/findings/__init__.py +58 -0
  19. doseframe-0.2.0/src/doseframe/protocols/__init__.py +103 -0
  20. doseframe-0.2.0/src/doseframe/protocols/activation.py +51 -0
  21. doseframe-0.2.0/src/doseframe/protocols/device.py +51 -0
  22. doseframe-0.2.0/src/doseframe/protocols/diff.py +70 -0
  23. doseframe-0.2.0/src/doseframe/protocols/errors.py +26 -0
  24. doseframe-0.2.0/src/doseframe/protocols/limits.py +74 -0
  25. doseframe-0.2.0/src/doseframe/protocols/model.py +40 -0
  26. doseframe-0.2.0/src/doseframe/protocols/naming.py +126 -0
  27. doseframe-0.2.0/src/doseframe/protocols/reference.py +163 -0
  28. doseframe-0.2.0/src/doseframe/protocols/schemes.py +598 -0
  29. doseframe-0.2.0/src/doseframe/protocols/single_dose.py +253 -0
  30. doseframe-0.2.0/src/doseframe/protocols/version.py +690 -0
  31. doseframe-0.2.0/src/doseframe/py.typed +0 -0
  32. doseframe-0.2.0/src/doseframe/rounding/__init__.py +23 -0
  33. doseframe-0.2.0/src/doseframe/rounding/policy.py +108 -0
  34. doseframe-0.2.0/src/doseframe/units/__init__.py +49 -0
  35. doseframe-0.2.0/src/doseframe/units/catalog.py +155 -0
  36. doseframe-0.2.0/src/doseframe/units/decimal_context.py +17 -0
  37. doseframe-0.2.0/src/doseframe/units/errors.py +27 -0
  38. doseframe-0.2.0/src/doseframe/units/options.py +52 -0
  39. doseframe-0.2.0/src/doseframe/units/quantity.py +144 -0
  40. doseframe-0.2.0/src/doseframe/units/unit.py +137 -0
  41. doseframe-0.2.0/src/doseframe/use_cases/__init__.py +73 -0
  42. doseframe-0.2.0/src/doseframe/use_cases/clinical.py +735 -0
  43. doseframe-0.2.0/src/doseframe/use_cases/gate.py +85 -0
  44. doseframe-0.2.0/src/doseframe/use_cases/governance.py +460 -0
  45. doseframe-0.2.0/src/doseframe/use_cases/ports.py +73 -0
  46. doseframe-0.2.0/src/doseframe/use_cases/results.py +182 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Simon Bernbeck
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.5
2
+ Name: doseframe
3
+ Version: 0.2.0
4
+ Summary: A transparent, unit-safe dose calculation framework for perfusors. Not a medical device.
5
+ Author: Simon Bernbeck
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Programming Language :: Python :: 3.13
10
+ Classifier: Typing :: Typed
11
+ Requires-Python: >=3.13
12
+ Description-Content-Type: text/markdown
13
+
14
+ # doseframe
15
+
16
+ A transparent, unit-safe framework for medication calculation and preparation across clinics,
17
+ including perfusors (syringe pumps) and divided daily doses.
18
+
19
+ The invariant kernel includes explicit units, governed protocol versions, approval and a mandatory
20
+ check prefix. Shipped preparation schemes, calculation strategies and rounding policies can be
21
+ selected or extended through their contracts. Every `CheckChain()` begins with `UnitCheck` then
22
+ `LimitCheck`; a clinic can append checks but cannot replace that prefix through the constructor.
23
+ A hospital supplies protocol data, storage and interface wiring.
24
+
25
+ What it ships:
26
+
27
+ - **Infusion schemes:** standard concentration, individual preparation and two-step preparation,
28
+ plus a reverse check of a running pump that changes one unit per step.
29
+ - **Single doses:** a divided daily dose, split into a fixed number of administrations.
30
+ - **Rounding policies:** `NoAutoRounding` (the default), `NearestStepRounding`, and `ChooseStep`,
31
+ which offers the neighbouring device or syringe steps and leaves the choice to a person.
32
+ - **Governance:** draft, review, approval and withdrawal, with four-eyes approval, reference
33
+ cases that must pass before approval, and versions that are never overwritten.
34
+ - **Standard protocol names:** `ProtocolTitle` builds a name from the content, in the order drug
35
+ and strength, carrier or syringe, weight range.
36
+
37
+ ## Installation
38
+
39
+ Doseframe requires Python 3.13 or newer and has no runtime dependencies.
40
+
41
+ ```sh
42
+ python -m pip install doseframe
43
+ ```
44
+
45
+ ## Quickstart
46
+
47
+ This fictitious example converts a weight-based rate to a volume per hour.
48
+
49
+ ```pycon
50
+ >>> from doseframe import Quantity, __version__
51
+ >>> __version__
52
+ '0.2.0'
53
+ >>> rate = (Quantity.of("0.02", "µg/kg/min") * Quantity.of("2.4", "kg")).to("µg/h")
54
+ >>> str(rate / Quantity.of("30", "µg/ml"))
55
+ '0.096 ml/h'
56
+
57
+ ```
58
+
59
+ A pump can only be set in steps. `ChooseStep` offers the two settable values next to the exact
60
+ rate and does not pick one:
61
+
62
+ ```pycon
63
+ >>> from doseframe import ChooseStep, DeviceProfile
64
+ >>> pump = DeviceProfile(id="demo", name="Demo pump", step_size=Quantity.of("0.01", "ml/h"))
65
+ >>> [str(q) for q in ChooseStep().candidates(Quantity.of("0.096", "ml/h"), pump)]
66
+ ['0.09 ml/h', '0.1 ml/h']
67
+
68
+ ```
69
+
70
+ ## Changes
71
+
72
+ - **0.2.0:** `ChooseStep` rounding with per-option findings for single doses; settable pump steps
73
+ next to the exact rate; one unit per step in the reverse calculation; a syringe label of any
74
+ compatible unit; `MatchProtocolsUseCase.label_required()`; generated protocol names
75
+ (`ProtocolTitle`); fields in the name fixed after approval.
76
+ - **0.1.x:** first package build (staged on TestPyPI only).
77
+
78
+ > **Not a medical device.** This library is a study project. It has no clinical validation
79
+ > or conformity assessment and must not be used to guide the treatment of a patient.
@@ -0,0 +1,66 @@
1
+ # doseframe
2
+
3
+ A transparent, unit-safe framework for medication calculation and preparation across clinics,
4
+ including perfusors (syringe pumps) and divided daily doses.
5
+
6
+ The invariant kernel includes explicit units, governed protocol versions, approval and a mandatory
7
+ check prefix. Shipped preparation schemes, calculation strategies and rounding policies can be
8
+ selected or extended through their contracts. Every `CheckChain()` begins with `UnitCheck` then
9
+ `LimitCheck`; a clinic can append checks but cannot replace that prefix through the constructor.
10
+ A hospital supplies protocol data, storage and interface wiring.
11
+
12
+ What it ships:
13
+
14
+ - **Infusion schemes:** standard concentration, individual preparation and two-step preparation,
15
+ plus a reverse check of a running pump that changes one unit per step.
16
+ - **Single doses:** a divided daily dose, split into a fixed number of administrations.
17
+ - **Rounding policies:** `NoAutoRounding` (the default), `NearestStepRounding`, and `ChooseStep`,
18
+ which offers the neighbouring device or syringe steps and leaves the choice to a person.
19
+ - **Governance:** draft, review, approval and withdrawal, with four-eyes approval, reference
20
+ cases that must pass before approval, and versions that are never overwritten.
21
+ - **Standard protocol names:** `ProtocolTitle` builds a name from the content, in the order drug
22
+ and strength, carrier or syringe, weight range.
23
+
24
+ ## Installation
25
+
26
+ Doseframe requires Python 3.13 or newer and has no runtime dependencies.
27
+
28
+ ```sh
29
+ python -m pip install doseframe
30
+ ```
31
+
32
+ ## Quickstart
33
+
34
+ This fictitious example converts a weight-based rate to a volume per hour.
35
+
36
+ ```pycon
37
+ >>> from doseframe import Quantity, __version__
38
+ >>> __version__
39
+ '0.2.0'
40
+ >>> rate = (Quantity.of("0.02", "µg/kg/min") * Quantity.of("2.4", "kg")).to("µg/h")
41
+ >>> str(rate / Quantity.of("30", "µg/ml"))
42
+ '0.096 ml/h'
43
+
44
+ ```
45
+
46
+ A pump can only be set in steps. `ChooseStep` offers the two settable values next to the exact
47
+ rate and does not pick one:
48
+
49
+ ```pycon
50
+ >>> from doseframe import ChooseStep, DeviceProfile
51
+ >>> pump = DeviceProfile(id="demo", name="Demo pump", step_size=Quantity.of("0.01", "ml/h"))
52
+ >>> [str(q) for q in ChooseStep().candidates(Quantity.of("0.096", "ml/h"), pump)]
53
+ ['0.09 ml/h', '0.1 ml/h']
54
+
55
+ ```
56
+
57
+ ## Changes
58
+
59
+ - **0.2.0:** `ChooseStep` rounding with per-option findings for single doses; settable pump steps
60
+ next to the exact rate; one unit per step in the reverse calculation; a syringe label of any
61
+ compatible unit; `MatchProtocolsUseCase.label_required()`; generated protocol names
62
+ (`ProtocolTitle`); fields in the name fixed after approval.
63
+ - **0.1.x:** first package build (staged on TestPyPI only).
64
+
65
+ > **Not a medical device.** This library is a study project. It has no clinical validation
66
+ > or conformity assessment and must not be used to guide the treatment of a patient.
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "doseframe"
3
+ version = "0.2.0"
4
+ description = "A transparent, unit-safe dose calculation framework for perfusors. Not a medical device."
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ dependencies = []
8
+ authors = [{name = "Simon Bernbeck"}]
9
+ license = "MIT"
10
+ license-files = ["LICENSE"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Programming Language :: Python :: 3.13",
14
+ "Typing :: Typed",
15
+ ]
16
+
17
+ [build-system]
18
+ requires = ["hatchling>=1.27"]
19
+ build-backend = "hatchling.build"
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/doseframe"]
23
+
24
+ [tool.hatch.build]
25
+ exclude = ["**/__pycache__", "**/*.py[co]"]
26
+
27
+ [tool.hatch.build.targets.sdist]
28
+ include = ["src/doseframe", "pyproject.toml", "README.md", "LICENSE"]
@@ -0,0 +1,252 @@
1
+ """doseframe: a transparent, unit-safe dose calculation framework for perfusors.
2
+
3
+ Not a medical device. The names exported here are the public API, versioned semantically:
4
+ a change to a frozen spot is a major version, a new default plug-in a minor version.
5
+
6
+ Hot-spots, where a hospital plugs in its own behaviour:
7
+ 1. `CalculationStrategy` how to calculate (Strategy)
8
+ 2. `RoundingPolicy` how to round (Strategy)
9
+ 3. `PreparationScheme` how the syringe is prepared (Factory Method)
10
+ 4. `Check` extra checks (Chain of Responsibility)
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from doseframe.calculation import (
16
+ CalculationStep,
17
+ CalculationStrategy,
18
+ Derivation,
19
+ DividedDailyDoseStrategy,
20
+ IndividualPreparationStrategy,
21
+ InfusedEstimate,
22
+ SingleDoseStrategy,
23
+ StandardConcentrationStrategy,
24
+ StructuralError,
25
+ TwoStepPreparationStrategy,
26
+ deviation_pct,
27
+ )
28
+ from doseframe.checks import Check, CheckChain, CheckContext, CheckMode, LimitCheck, UnitCheck
29
+ from doseframe.findings import Finding, Severity, blocking
30
+ from doseframe.protocols import (
31
+ Actor,
32
+ CaseDirection,
33
+ CaseResult,
34
+ DeviceProfile,
35
+ DeviceProfileChange,
36
+ DosePreparation,
37
+ EventKind,
38
+ FieldChange,
39
+ GovernanceError,
40
+ GuardFailedError,
41
+ IllegalTransitionError,
42
+ IndividualPreparationScheme,
43
+ InfusionScheme,
44
+ LifecycleEvent,
45
+ Limit,
46
+ LimitTarget,
47
+ Medication,
48
+ Operation,
49
+ PermissionDeniedError,
50
+ Preparation,
51
+ PreparationScheme,
52
+ PreparationStep,
53
+ Protocol,
54
+ ProtocolTitle,
55
+ ProtocolVersion,
56
+ Range,
57
+ ReferenceCase,
58
+ SchemeRegistry,
59
+ SingleDoseOutcome,
60
+ SingleDoseScheme,
61
+ SingleDoseSetup,
62
+ StandardConcentrationScheme,
63
+ StateName,
64
+ StepKind,
65
+ StockSolution,
66
+ TwoStepPreparationScheme,
67
+ UserRole,
68
+ VersionContent,
69
+ WeightScope,
70
+ Workflow,
71
+ default_schemes,
72
+ evaluate_single_dose,
73
+ usual_range,
74
+ )
75
+ from doseframe.protocols.single_dose import DoseOption
76
+ from doseframe.rounding import (
77
+ ChooseStep,
78
+ NearestStepRounding,
79
+ NoAutoRounding,
80
+ RoundingPolicy,
81
+ RoundingPolicyRegistry,
82
+ UnknownRoundingPolicyError,
83
+ default_registry,
84
+ )
85
+ from doseframe.units import (
86
+ DoseframeError,
87
+ IncompatibleUnitError,
88
+ Quantity,
89
+ Role,
90
+ Unit,
91
+ UnitError,
92
+ UnitOptions,
93
+ UnitRoleError,
94
+ UnknownUnitError,
95
+ dose_unit_options,
96
+ format_decimal,
97
+ is_allowed,
98
+ parse_unit,
99
+ require_role,
100
+ result_units,
101
+ unit,
102
+ )
103
+ from doseframe.use_cases import (
104
+ ApprovalReasons,
105
+ AvailabilityGate,
106
+ CalculateRateUseCase,
107
+ CalculateSingleDoseUseCase,
108
+ CalculationRequest,
109
+ CalculationResult,
110
+ CheckRunningPerfusorUseCase,
111
+ Clock,
112
+ ConcentrationSource,
113
+ Evaluation,
114
+ MatchProtocolsUseCase,
115
+ NotFoundError,
116
+ OpenChangeExistsError,
117
+ ProtocolMatch,
118
+ ProtocolOffice,
119
+ ProtocolOverview,
120
+ ProtocolRepository,
121
+ RepositoryUnavailableError,
122
+ ReverseCheckRequest,
123
+ ReverseCheckResult,
124
+ SingleDoseRequest,
125
+ SingleDoseResult,
126
+ Unavailable,
127
+ UnusableReason,
128
+ UserDirectory,
129
+ VersionDetail,
130
+ VersionOverview,
131
+ VersionRef,
132
+ )
133
+
134
+ __version__ = "0.2.0"
135
+
136
+ __all__ = [
137
+ "Actor",
138
+ "ApprovalReasons",
139
+ "AvailabilityGate",
140
+ "CalculateRateUseCase",
141
+ "CalculateSingleDoseUseCase",
142
+ "CalculationRequest",
143
+ "CalculationResult",
144
+ "CalculationStep",
145
+ "CalculationStrategy",
146
+ "CaseDirection",
147
+ "CaseResult",
148
+ "Check",
149
+ "CheckChain",
150
+ "CheckContext",
151
+ "CheckMode",
152
+ "CheckRunningPerfusorUseCase",
153
+ "ChooseStep",
154
+ "Clock",
155
+ "ConcentrationSource",
156
+ "Derivation",
157
+ "DeviceProfile",
158
+ "DeviceProfileChange",
159
+ "DividedDailyDoseStrategy",
160
+ "DoseOption",
161
+ "DosePreparation",
162
+ "DoseframeError",
163
+ "Evaluation",
164
+ "EventKind",
165
+ "FieldChange",
166
+ "Finding",
167
+ "GovernanceError",
168
+ "GuardFailedError",
169
+ "IllegalTransitionError",
170
+ "IncompatibleUnitError",
171
+ "IndividualPreparationScheme",
172
+ "IndividualPreparationStrategy",
173
+ "InfusedEstimate",
174
+ "InfusionScheme",
175
+ "LifecycleEvent",
176
+ "Limit",
177
+ "LimitCheck",
178
+ "LimitTarget",
179
+ "MatchProtocolsUseCase",
180
+ "Medication",
181
+ "NearestStepRounding",
182
+ "NoAutoRounding",
183
+ "NotFoundError",
184
+ "OpenChangeExistsError",
185
+ "Operation",
186
+ "PermissionDeniedError",
187
+ "Preparation",
188
+ "PreparationScheme",
189
+ "PreparationStep",
190
+ "Protocol",
191
+ "ProtocolMatch",
192
+ "ProtocolOffice",
193
+ "ProtocolOverview",
194
+ "ProtocolRepository",
195
+ "ProtocolTitle",
196
+ "ProtocolVersion",
197
+ "Quantity",
198
+ "Range",
199
+ "ReferenceCase",
200
+ "RepositoryUnavailableError",
201
+ "ReverseCheckRequest",
202
+ "ReverseCheckResult",
203
+ "Role",
204
+ "RoundingPolicy",
205
+ "RoundingPolicyRegistry",
206
+ "SchemeRegistry",
207
+ "Severity",
208
+ "SingleDoseOutcome",
209
+ "SingleDoseRequest",
210
+ "SingleDoseResult",
211
+ "SingleDoseScheme",
212
+ "SingleDoseSetup",
213
+ "SingleDoseStrategy",
214
+ "StandardConcentrationScheme",
215
+ "StandardConcentrationStrategy",
216
+ "StateName",
217
+ "StepKind",
218
+ "StockSolution",
219
+ "StructuralError",
220
+ "TwoStepPreparationScheme",
221
+ "TwoStepPreparationStrategy",
222
+ "Unavailable",
223
+ "Unit",
224
+ "UnitCheck",
225
+ "UnitError",
226
+ "UnitOptions",
227
+ "UnitRoleError",
228
+ "UnknownRoundingPolicyError",
229
+ "UnknownUnitError",
230
+ "UnusableReason",
231
+ "UserDirectory",
232
+ "UserRole",
233
+ "VersionContent",
234
+ "VersionDetail",
235
+ "VersionOverview",
236
+ "VersionRef",
237
+ "WeightScope",
238
+ "Workflow",
239
+ "blocking",
240
+ "default_registry",
241
+ "default_schemes",
242
+ "deviation_pct",
243
+ "dose_unit_options",
244
+ "evaluate_single_dose",
245
+ "format_decimal",
246
+ "is_allowed",
247
+ "parse_unit",
248
+ "require_role",
249
+ "result_units",
250
+ "unit",
251
+ "usual_range",
252
+ ]
@@ -0,0 +1,34 @@
1
+ """Calculation: the strategy interface (hot-spot 1), the default strategies, and their results."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from doseframe.calculation.derivation import CalculationStep, Derivation
6
+ from doseframe.calculation.errors import StructuralError
7
+ from doseframe.calculation.infusion import InfusedEstimate, estimate_infused
8
+ from doseframe.calculation.relation import deviation_pct, dose_to_rate, rate_to_dose
9
+ from doseframe.calculation.single_dose import DividedDailyDoseStrategy, SingleDoseStrategy
10
+ from doseframe.calculation.steps import neighbouring_steps
11
+ from doseframe.calculation.strategies import (
12
+ IndividualPreparationStrategy,
13
+ StandardConcentrationStrategy,
14
+ TwoStepPreparationStrategy,
15
+ )
16
+ from doseframe.calculation.strategy import CalculationStrategy
17
+
18
+ __all__ = [
19
+ "CalculationStep",
20
+ "CalculationStrategy",
21
+ "Derivation",
22
+ "DividedDailyDoseStrategy",
23
+ "IndividualPreparationStrategy",
24
+ "InfusedEstimate",
25
+ "SingleDoseStrategy",
26
+ "StandardConcentrationStrategy",
27
+ "StructuralError",
28
+ "TwoStepPreparationStrategy",
29
+ "deviation_pct",
30
+ "dose_to_rate",
31
+ "estimate_infused",
32
+ "neighbouring_steps",
33
+ "rate_to_dose",
34
+ ]
@@ -0,0 +1,30 @@
1
+ """A value together with the steps that produced it, for the visible calculation path."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from doseframe.units import Quantity
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class CalculationStep:
12
+ """One step of a calculation: ``operands[0] <operation> operands[1] = result``.
13
+
14
+ `key` names the step for the interface ("dose_for_weight", "per_hour", "to_volume", ...).
15
+ For a unit conversion, `operation` is ``"convert"`` and there is a single operand.
16
+ """
17
+
18
+ key: str
19
+ operation: str
20
+ operands: tuple[Quantity, ...]
21
+ result: Quantity
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class Derivation:
26
+ value: Quantity
27
+ steps: tuple[CalculationStep, ...] = ()
28
+
29
+ def then(self, step: CalculationStep) -> Derivation:
30
+ return Derivation(step.result, (*self.steps, step))
@@ -0,0 +1,16 @@
1
+ """Errors for inputs that cannot describe a real preparation or pump setting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from doseframe.units import DoseframeError
6
+
7
+
8
+ class StructuralError(DoseframeError):
9
+ """A rule that follows from arithmetic was broken. Always blocks, never configurable.
10
+
11
+ `code` is stable and becomes the code of the BLOCK finding shown to the user.
12
+ """
13
+
14
+ def __init__(self, code: str, message: str) -> None:
15
+ super().__init__(message)
16
+ self.code = code
@@ -0,0 +1,27 @@
1
+ """How much a running perfusor has delivered: an estimate at a constant rate (V2-05)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from doseframe.calculation.relation import require_positive
8
+ from doseframe.units import Quantity, Role
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class InfusedEstimate:
13
+ """Assumes the pump ran at this rate the whole time; it is not measured delivery."""
14
+
15
+ volume: Quantity
16
+ drug_amount: Quantity
17
+
18
+
19
+ def estimate_infused(
20
+ rate: Quantity, running_for: Quantity, concentration: Quantity
21
+ ) -> InfusedEstimate:
22
+ require_positive(rate, Role.RATE, "rate")
23
+ require_positive(running_for, Role.DURATION, "running_for")
24
+ require_positive(concentration, Role.CONCENTRATION, "concentration")
25
+ volume = (rate * running_for).to("ml")
26
+ amount = (volume * concentration).to(concentration.unit.terms[0][0].symbol)
27
+ return InfusedEstimate(volume, amount)
@@ -0,0 +1,129 @@
1
+ """The relation between dose and pump rate, shared by every preparation scheme.
2
+
3
+ weight-based dose: rate = dose × weight / concentration
4
+ absolute dose: rate = dose / concentration
5
+
6
+ Whether the weight enters follows from the dose unit (it has a "per kg"), never from a flag or a
7
+ medication name. Every step keeps its unit and is recorded for the calculation path.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from decimal import Decimal
13
+
14
+ from doseframe.calculation.derivation import CalculationStep, Derivation
15
+ from doseframe.calculation.errors import StructuralError
16
+ from doseframe.units import (
17
+ CONTEXT,
18
+ Dimension,
19
+ IncompatibleUnitError,
20
+ Quantity,
21
+ Role,
22
+ Unit,
23
+ is_weight_based_dose,
24
+ require_role,
25
+ unit,
26
+ )
27
+ from doseframe.units.catalog import H
28
+
29
+ ML_PER_H = unit("ml/h")
30
+
31
+
32
+ def dose_to_rate(dose: Quantity, weight: Quantity, concentration: Quantity) -> Derivation:
33
+ require_positive(dose, Role.DOSE, "dose")
34
+ require_positive(weight, Role.WEIGHT, "weight")
35
+ require_positive(concentration, Role.CONCENTRATION, "concentration")
36
+
37
+ derivation = Derivation(dose)
38
+ amount_per_time = dose
39
+ if is_weight_based_dose(dose.unit):
40
+ amount_per_time = dose * weight
41
+ derivation = derivation.then(
42
+ CalculationStep("dose_for_weight", "×", (dose, weight), amount_per_time)
43
+ )
44
+ per_hour_unit = Unit(((amount_per_time.unit.terms[0][0], 1), (H, -1)))
45
+ if amount_per_time.unit != per_hour_unit:
46
+ per_hour = amount_per_time.to(per_hour_unit)
47
+ derivation = derivation.then(
48
+ CalculationStep("per_hour", "convert", (amount_per_time,), per_hour)
49
+ )
50
+ amount_per_time = per_hour
51
+ rate = amount_per_time / concentration
52
+ if not rate.unit.is_compatible(ML_PER_H):
53
+ raise IncompatibleUnitError(
54
+ f"{dose.unit.symbol} and {concentration.unit.symbol} do not give a rate"
55
+ )
56
+ rate = rate.to(ML_PER_H)
57
+ return derivation.then(
58
+ CalculationStep("to_volume", "÷", (amount_per_time, concentration), rate)
59
+ )
60
+
61
+
62
+ def rate_to_dose(
63
+ rate: Quantity, weight: Quantity, concentration: Quantity, dose_unit: Unit
64
+ ) -> Derivation:
65
+ require_positive(rate, Role.RATE, "rate")
66
+ require_positive(weight, Role.WEIGHT, "weight")
67
+ require_positive(concentration, Role.CONCENTRATION, "concentration")
68
+ require_role(dose_unit, Role.DOSE)
69
+
70
+ amount_per_hour = rate * concentration
71
+ if not amount_per_hour.unit.is_compatible(Unit(((dose_unit.terms[0][0], 1), (H, -1)))):
72
+ raise IncompatibleUnitError(
73
+ f"{concentration.unit.symbol} does not give a dose in {dose_unit.symbol}"
74
+ )
75
+ derivation = Derivation(rate).then(
76
+ CalculationStep("to_amount", "×", (rate, concentration), amount_per_hour)
77
+ )
78
+ value = amount_per_hour
79
+ if is_weight_based_dose(dose_unit):
80
+ value = amount_per_hour / weight
81
+ derivation = derivation.then(
82
+ CalculationStep("per_weight", "÷", (amount_per_hour, weight), value)
83
+ )
84
+ dose = value.to(dose_unit)
85
+ if dose.unit == value.unit:
86
+ return derivation
87
+ # One unit per step (V3-02): time first, then body weight, then the drug amount. A single
88
+ # change keeps its one step, named for the prescribed unit as before.
89
+ target = {atom.dimension: (atom, exp) for atom, exp in dose_unit.terms}
90
+ terms = list(value.unit.terms)
91
+ changes = [
92
+ i
93
+ for i in reversed(range(len(terms)))
94
+ if target.get(terms[i][0].dimension, terms[i]) != terms[i]
95
+ ]
96
+ if len(changes) <= 1:
97
+ return derivation.then(CalculationStep("to_dose_unit", "convert", (value,), dose))
98
+ current = value
99
+ for i in changes:
100
+ terms[i] = target[terms[i][0].dimension]
101
+ following = current.to(Unit(tuple(terms)))
102
+ key = _CONVERSION_KEYS[terms[i][0].dimension]
103
+ derivation = derivation.then(CalculationStep(key, "convert", (current,), following))
104
+ current = following
105
+ return derivation
106
+
107
+
108
+ _CONVERSION_KEYS = {
109
+ Dimension.TIME: "to_time_unit",
110
+ Dimension.BODY_MASS: "to_weight_unit",
111
+ Dimension.DRUG_MASS: "to_amount_unit",
112
+ Dimension.DRUG_ACTIVITY: "to_amount_unit",
113
+ Dimension.VOLUME: "to_volume_unit",
114
+ }
115
+
116
+
117
+ def require_positive(q: Quantity, role: Role, name: str) -> None:
118
+ """The unit must fit the role, and the value must be greater than zero."""
119
+ require_role(q.unit, role)
120
+ if not q.is_positive():
121
+ raise StructuralError("not_positive", f"{name} must be greater than zero, got {q}")
122
+
123
+
124
+ def deviation_pct(actual: Quantity, target: Quantity) -> Decimal:
125
+ """(actual − target) / target × 100. Undefined for a target of zero, which is refused."""
126
+ if not target.is_positive():
127
+ raise StructuralError("not_positive", f"deviation needs a positive target, got {target}")
128
+ difference = (actual - target).value
129
+ return CONTEXT.multiply(CONTEXT.divide(difference, target.value), Decimal(100))