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,37 @@
1
+ """Hot-spot 1: the calculation strategy (Strategy pattern)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Protocol, runtime_checkable
6
+
7
+ from doseframe.calculation.derivation import Derivation
8
+ from doseframe.units import Quantity, Unit
9
+
10
+
11
+ @runtime_checkable
12
+ class CalculationStrategy(Protocol):
13
+ """Converts between dose and pump rate for one preparation scheme.
14
+
15
+ Every implementation either returns a `Derivation` with a valid unit or raises a
16
+ `DoseframeError`. It never returns a bare number, None, or a value that is not positive.
17
+ """
18
+
19
+ def concentration_for(self, weight: Quantity) -> Derivation:
20
+ """The final concentration the protocol prescribes for this weight."""
21
+ ...
22
+
23
+ def dose_to_rate(
24
+ self, dose: Quantity, weight: Quantity, concentration: Quantity | None = None
25
+ ) -> Derivation:
26
+ """The pump rate in ml/h. `concentration` overrides the protocol's, for label checks."""
27
+ ...
28
+
29
+ def rate_to_dose(
30
+ self,
31
+ rate: Quantity,
32
+ weight: Quantity,
33
+ dose_unit: Unit,
34
+ concentration: Quantity | None = None,
35
+ ) -> Derivation:
36
+ """The dose a rate delivers, in `dose_unit`."""
37
+ ...
@@ -0,0 +1,20 @@
1
+ """Checks: the check interface (hot-spot 4), the chain, and the mandatory checks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from doseframe.checks.chain import UNIT_PROBLEM_CODES, Check, CheckChain, LimitCheck, UnitCheck
6
+ from doseframe.checks.context import CheckContext, CheckMode
7
+ from doseframe.findings import Finding, Severity, blocking
8
+
9
+ __all__ = [
10
+ "UNIT_PROBLEM_CODES",
11
+ "Check",
12
+ "CheckChain",
13
+ "CheckContext",
14
+ "CheckMode",
15
+ "Finding",
16
+ "LimitCheck",
17
+ "Severity",
18
+ "UnitCheck",
19
+ "blocking",
20
+ ]
@@ -0,0 +1,212 @@
1
+ """Hot-spot 4: the check chain (Chain of Responsibility) and the mandatory checks.
2
+
3
+ The chain holds its checks as a list instead of next-links, so the mandatory checks come first
4
+ and cannot be removed or reordered. A hospital can only append its own checks.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Protocol, runtime_checkable
10
+
11
+ from doseframe.checks.context import CheckContext, CheckMode
12
+ from doseframe.findings import DOSE_UNIT_MISMATCH, UNIT_PROBLEM_CODES, Finding, Severity
13
+ from doseframe.protocols.device import Range
14
+ from doseframe.protocols.limits import Limit, LimitTarget
15
+ from doseframe.units import IncompatibleUnitError, Quantity
16
+
17
+
18
+ @runtime_checkable
19
+ class Check(Protocol):
20
+ def check(self, ctx: CheckContext) -> list[Finding]: ...
21
+
22
+
23
+ class UnitCheck:
24
+ """Units must be exactly the ones the protocol expects; nothing is converted silently.
25
+
26
+ A dose of another kind (µg vs IU) is blocked. A dose of the same kind arrives here already
27
+ converted by the use case (V2-02).
28
+ """
29
+
30
+ def check(self, ctx: CheckContext) -> list[Finding]:
31
+ findings = [p for p in ctx.problems if p.code in UNIT_PROBLEM_CODES]
32
+ if ctx.dose is not None and ctx.dose.unit != ctx.expected_dose_unit:
33
+ findings.append(
34
+ Finding(
35
+ DOSE_UNIT_MISMATCH,
36
+ Severity.BLOCK,
37
+ f"dose entered in {ctx.dose.unit.symbol}, protocol expects "
38
+ f"{ctx.expected_dose_unit.symbol}",
39
+ {"entered": ctx.dose.unit.symbol, "expected": ctx.expected_dose_unit.symbol},
40
+ )
41
+ )
42
+ return _unique(findings)
43
+
44
+
45
+ class LimitCheck:
46
+ """Structural rules, the weight range, approved limits, the device profile, the review date."""
47
+
48
+ def check(self, ctx: CheckContext) -> list[Finding]:
49
+ findings = [p for p in ctx.problems if p.code not in UNIT_PROBLEM_CODES]
50
+ if not ctx.weight_scope.contains(ctx.weight):
51
+ findings.append(
52
+ Finding(
53
+ "weight_out_of_scope",
54
+ Severity.BLOCK,
55
+ f"{ctx.weight} is outside {ctx.weight_scope.describe()}",
56
+ {"weight": str(ctx.weight), "scope": ctx.weight_scope.describe()},
57
+ )
58
+ )
59
+ for limit in ctx.limits:
60
+ findings += _limit_findings(limit, ctx)
61
+ findings += _device_findings(ctx)
62
+ if ctx.review_due is not None and ctx.review_due < ctx.today:
63
+ findings.append(
64
+ Finding(
65
+ "review_overdue",
66
+ Severity.WARN,
67
+ f"review date {ctx.review_due.isoformat()} has passed",
68
+ {"review_due": ctx.review_due.isoformat()},
69
+ )
70
+ )
71
+ return findings
72
+
73
+
74
+ class CheckChain:
75
+ """Runs the mandatory checks, then the appended ones; stops after the first BLOCK."""
76
+
77
+ def __init__(self) -> None:
78
+ self._checks: list[Check] = [UnitCheck(), LimitCheck()]
79
+
80
+ def append(self, check: Check) -> None:
81
+ self._checks.append(check)
82
+
83
+ @property
84
+ def checks(self) -> tuple[Check, ...]:
85
+ return tuple(self._checks)
86
+
87
+ def run(self, ctx: CheckContext) -> list[Finding]:
88
+ findings: list[Finding] = []
89
+ for check in self._checks:
90
+ found = check.check(ctx)
91
+ findings += found
92
+ if any(f.blocks for f in found):
93
+ break
94
+ return findings
95
+
96
+
97
+ # --- limits and device ----------------------------------------------------------------------
98
+
99
+
100
+ def _targets(limit: Limit, ctx: CheckContext) -> list[tuple[str, Quantity]]:
101
+ match limit.target:
102
+ case LimitTarget.DOSE:
103
+ values = [("dose", ctx.dose), ("delivered_dose", ctx.delivered_dose)]
104
+ case LimitTarget.RATE:
105
+ values = [("rate", ctx.rate)]
106
+ case LimitTarget.SETTING:
107
+ values = [("setting", ctx.setting)]
108
+ case LimitTarget.WITHDRAWAL_VOLUME:
109
+ values = [("withdrawal_volume", ctx.withdrawal_volume)]
110
+ return [(name, value) for name, value in values if value is not None]
111
+
112
+
113
+ def _limit_findings(limit: Limit, ctx: CheckContext) -> list[Finding]:
114
+ severity = limit.severity
115
+ # In a reverse check the pump is already running: hiding what it delivers would hide the most
116
+ # important fact, so dose and rate limits warn and the numbers stay visible (spec S-1).
117
+ if ctx.mode is CheckMode.REVERSE_CHECK and limit.target in {LimitTarget.DOSE, LimitTarget.RATE}:
118
+ severity = min(severity, Severity.WARN)
119
+ findings: list[Finding] = []
120
+ for name, value in _targets(limit, ctx):
121
+ try:
122
+ bound = limit.violated_by(value)
123
+ except IncompatibleUnitError:
124
+ findings.append(
125
+ Finding(
126
+ "limit_unit_mismatch",
127
+ Severity.BLOCK,
128
+ f"limit on {limit.target} does not fit {value.unit.symbol}",
129
+ {"target": limit.target.value, "unit": value.unit.symbol},
130
+ )
131
+ )
132
+ continue
133
+ if bound is None:
134
+ continue
135
+ side = "above" if limit.upper is not None and bound is limit.upper else "below"
136
+ findings.append(
137
+ Finding(
138
+ f"{name}_{side}_limit",
139
+ severity,
140
+ f"{name} {value} is {side} the limit {bound}",
141
+ {"value": str(value), "limit": str(bound), "justification": limit.justification},
142
+ )
143
+ )
144
+ return findings
145
+
146
+
147
+ def _device_findings(ctx: CheckContext) -> list[Finding]:
148
+ device = ctx.device
149
+ if device is None:
150
+ return [Finding("device_not_on_file", Severity.INFO, "pump suitability not checked")]
151
+ findings: list[Finding] = []
152
+ if ctx.setting is not None:
153
+ findings += _setting_findings(ctx.setting, device.settable_range, device.step_size)
154
+ for name, value in (("rate", ctx.rate), ("setting", ctx.setting)):
155
+ if value is None:
156
+ continue
157
+ if device.approved_range is not None and not device.approved_range.contains(value):
158
+ findings.append(
159
+ Finding(
160
+ f"{name}_outside_approved_range",
161
+ Severity.WARN,
162
+ f"{name} {value} is outside the approved range of {device.name}",
163
+ {"value": str(value), "device": device.name},
164
+ )
165
+ )
166
+ threshold = device.low_rate_warning_below
167
+ if threshold is not None and value < threshold:
168
+ findings.append(
169
+ Finding(
170
+ f"{name}_below_low_rate_threshold",
171
+ Severity.WARN,
172
+ f"{name} {value} is below {threshold}",
173
+ {"value": str(value), "threshold": str(threshold), "device": device.name},
174
+ )
175
+ )
176
+ return findings
177
+
178
+
179
+ def _setting_findings(
180
+ setting: Quantity, settable: Range | None, step: Quantity | None
181
+ ) -> list[Finding]:
182
+ findings: list[Finding] = []
183
+ if settable is not None and not settable.contains(setting):
184
+ findings.append(
185
+ Finding(
186
+ "setting_not_settable",
187
+ Severity.BLOCK,
188
+ f"the pump cannot be set to {setting}",
189
+ {"value": str(setting)},
190
+ )
191
+ )
192
+ if step is not None and (setting.to(step.unit).value % step.value) != 0:
193
+ findings.append(
194
+ Finding(
195
+ "setting_not_a_step",
196
+ Severity.BLOCK,
197
+ f"{setting} is not a multiple of the pump step {step}",
198
+ {"value": str(setting), "step": str(step)},
199
+ )
200
+ )
201
+ return findings
202
+
203
+
204
+ def _unique(findings: list[Finding]) -> list[Finding]:
205
+ seen: set[tuple[str, str]] = set()
206
+ result: list[Finding] = []
207
+ for finding in findings:
208
+ key = (finding.code, finding.message)
209
+ if key not in seen:
210
+ seen.add(key)
211
+ result.append(finding)
212
+ return result
@@ -0,0 +1,43 @@
1
+ """What a check sees: the inputs, the computed values, and the approved protocol data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from datetime import date
7
+ from enum import StrEnum
8
+
9
+ from doseframe.findings import Finding
10
+ from doseframe.protocols.device import DeviceProfile
11
+ from doseframe.protocols.limits import Limit, WeightScope
12
+ from doseframe.units import Quantity, Unit
13
+
14
+
15
+ class CheckMode(StrEnum):
16
+ CALCULATION = "calculation" # a new perfusor: dose to rate
17
+ REVERSE_CHECK = "reverse_check" # a running perfusor: rate to dose
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class CheckContext:
22
+ """Everything the checks need, with no reference to how it was computed.
23
+
24
+ `problems` are findings the calculation itself produced, for example a structural rule or a
25
+ unit that does not fit. Computed values are None where the computation was impossible.
26
+ In a calculation, `rate` is the exact rate and `dose` the prescribed dose. In a reverse check,
27
+ `rate` is the rate read off the pump and `delivered_dose` what it delivers.
28
+ """
29
+
30
+ mode: CheckMode
31
+ today: date
32
+ expected_dose_unit: Unit
33
+ weight_scope: WeightScope
34
+ weight: Quantity
35
+ dose: Quantity | None = None
36
+ rate: Quantity | None = None
37
+ setting: Quantity | None = None
38
+ delivered_dose: Quantity | None = None
39
+ withdrawal_volume: Quantity | None = None
40
+ limits: tuple[Limit, ...] = ()
41
+ device: DeviceProfile | None = None
42
+ review_due: date | None = None
43
+ problems: tuple[Finding, ...] = ()
@@ -0,0 +1,58 @@
1
+ """Findings: what a check or a validation reports, with a severity.
2
+
3
+ A finding names its cause by a stable `code`. The interface translates the code into a sentence
4
+ that says what happened and what to check, so the library never holds display text. `params`
5
+ holds the values the sentence needs, already formatted with their units.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass, field
12
+ from enum import IntEnum
13
+ from types import MappingProxyType
14
+
15
+ # Codes of unit problems. They are raised in several modules but must all reach UnitCheck, so
16
+ # they are named once here instead of spelled out at each place.
17
+ UNIT_ROLE = "unit_role"
18
+ INCOMPATIBLE_UNIT = "incompatible_unit"
19
+ DOSE_UNIT_MISMATCH = "dose_unit_mismatch"
20
+ UNIT_PROBLEM_CODES = frozenset({UNIT_ROLE, INCOMPATIBLE_UNIT, DOSE_UNIT_MISMATCH})
21
+
22
+
23
+ class Severity(IntEnum):
24
+ """INFO is shown, WARN is shown next to the numbers, BLOCK suppresses all numbers."""
25
+
26
+ INFO = 1
27
+ WARN = 2
28
+ BLOCK = 3
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class Finding:
33
+ code: str
34
+ severity: Severity
35
+ message: str
36
+ params: Mapping[str, str] = field(default_factory=lambda: MappingProxyType({}))
37
+
38
+ def __post_init__(self) -> None:
39
+ object.__setattr__(self, "params", MappingProxyType(dict(self.params)))
40
+
41
+ @property
42
+ def blocks(self) -> bool:
43
+ return self.severity is Severity.BLOCK
44
+
45
+
46
+ def blocking(findings: list[Finding] | tuple[Finding, ...]) -> bool:
47
+ return any(f.blocks for f in findings)
48
+
49
+
50
+ __all__ = [
51
+ "DOSE_UNIT_MISMATCH",
52
+ "INCOMPATIBLE_UNIT",
53
+ "UNIT_PROBLEM_CODES",
54
+ "UNIT_ROLE",
55
+ "Finding",
56
+ "Severity",
57
+ "blocking",
58
+ ]
@@ -0,0 +1,103 @@
1
+ """Protocols: governed protocol versions and their content.
2
+
3
+ `ProtocolVersion` is the aggregate root: its preparation scheme (hot-spot 3), weight range,
4
+ limits, reference cases and lifecycle state change only through its operations.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from doseframe.protocols.activation import activate_due
10
+ from doseframe.protocols.device import DeviceProfile, DeviceProfileChange, Range
11
+ from doseframe.protocols.diff import FieldChange, diff_contents, flatten
12
+ from doseframe.protocols.errors import (
13
+ GovernanceError,
14
+ GuardFailedError,
15
+ IllegalTransitionError,
16
+ PermissionDeniedError,
17
+ )
18
+ from doseframe.protocols.limits import Limit, LimitTarget, WeightScope, usual_range
19
+ from doseframe.protocols.model import Actor, Medication, Protocol, UserRole
20
+ from doseframe.protocols.naming import ProtocolTitle, describe_weight, title_of
21
+ from doseframe.protocols.reference import CaseDirection, CaseResult, ReferenceCase
22
+ from doseframe.protocols.schemes import (
23
+ DosePreparation,
24
+ IndividualPreparationScheme,
25
+ InfusionScheme,
26
+ Preparation,
27
+ PreparationScheme,
28
+ PreparationStep,
29
+ SchemeRegistry,
30
+ SingleDoseScheme,
31
+ StandardConcentrationScheme,
32
+ StepKind,
33
+ StockSolution,
34
+ TwoStepPreparationScheme,
35
+ Workflow,
36
+ default_schemes,
37
+ )
38
+ from doseframe.protocols.single_dose import (
39
+ SingleDoseOutcome,
40
+ SingleDoseSetup,
41
+ evaluate_single_dose,
42
+ )
43
+ from doseframe.protocols.version import (
44
+ EventKind,
45
+ LifecycleEvent,
46
+ LifecycleState,
47
+ Operation,
48
+ ProtocolVersion,
49
+ StateName,
50
+ VersionContent,
51
+ )
52
+
53
+ __all__ = [
54
+ "Actor",
55
+ "CaseDirection",
56
+ "CaseResult",
57
+ "DeviceProfile",
58
+ "DeviceProfileChange",
59
+ "DosePreparation",
60
+ "EventKind",
61
+ "FieldChange",
62
+ "GovernanceError",
63
+ "GuardFailedError",
64
+ "IllegalTransitionError",
65
+ "IndividualPreparationScheme",
66
+ "InfusionScheme",
67
+ "LifecycleEvent",
68
+ "LifecycleState",
69
+ "Limit",
70
+ "LimitTarget",
71
+ "Medication",
72
+ "Operation",
73
+ "PermissionDeniedError",
74
+ "Preparation",
75
+ "PreparationScheme",
76
+ "PreparationStep",
77
+ "Protocol",
78
+ "ProtocolTitle",
79
+ "ProtocolVersion",
80
+ "Range",
81
+ "ReferenceCase",
82
+ "SchemeRegistry",
83
+ "SingleDoseOutcome",
84
+ "SingleDoseScheme",
85
+ "SingleDoseSetup",
86
+ "StandardConcentrationScheme",
87
+ "StateName",
88
+ "StepKind",
89
+ "StockSolution",
90
+ "TwoStepPreparationScheme",
91
+ "UserRole",
92
+ "VersionContent",
93
+ "WeightScope",
94
+ "Workflow",
95
+ "activate_due",
96
+ "default_schemes",
97
+ "describe_weight",
98
+ "diff_contents",
99
+ "evaluate_single_dose",
100
+ "flatten",
101
+ "title_of",
102
+ "usual_range",
103
+ ]
@@ -0,0 +1,51 @@
1
+ """Activation: an approved version comes into force on its start date (decision D-07).
2
+
3
+ There is no background job. Every read path runs activation first, so the state is correct
4
+ whenever anyone looks.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Iterable
10
+ from datetime import date, datetime
11
+
12
+ from doseframe.protocols.version import ProtocolVersion, StateName
13
+
14
+
15
+ def activate_due(
16
+ versions: Iterable[ProtocolVersion], *, today: date, at: datetime
17
+ ) -> list[ProtocolVersion]:
18
+ """Publish the newest approved version whose start date has come; return what changed.
19
+
20
+ The newest such version wins. The previously published version and every older approved
21
+ version are superseded, so an older approval with a later date can never come back.
22
+ """
23
+ all_versions = list(versions)
24
+ due = [
25
+ v
26
+ for v in all_versions
27
+ if v.state is StateName.APPROVED
28
+ and v.effective_from is not None
29
+ and v.effective_from <= today
30
+ ]
31
+ if not due:
32
+ return []
33
+ winner = max(due, key=lambda v: v.number)
34
+ published = [v for v in all_versions if v.state is StateName.PUBLISHED]
35
+ if any(p.number > winner.number for p in published):
36
+ return []
37
+ changed: list[ProtocolVersion] = []
38
+ for version in published:
39
+ version.supersede(at=at)
40
+ changed.append(version)
41
+ winner.publish(today=today, at=at)
42
+ changed.append(winner)
43
+ for version in all_versions:
44
+ if version.state is StateName.APPROVED and version.number < winner.number:
45
+ version.supersede(at=at)
46
+ changed.append(version)
47
+ return changed
48
+
49
+
50
+ def _due(version: ProtocolVersion, today: date) -> bool:
51
+ return version.effective_from is not None and version.effective_from <= today
@@ -0,0 +1,51 @@
1
+ """Device profiles and ranges: what is known about a pump and syringe combination."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from datetime import datetime
7
+
8
+ from doseframe.units import Quantity
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class Range:
13
+ """A closed range, lower ≤ value ≤ upper. Either bound may be open (None)."""
14
+
15
+ lower: Quantity | None = None
16
+ upper: Quantity | None = None
17
+
18
+ def contains(self, value: Quantity) -> bool:
19
+ if self.lower is not None and value < self.lower:
20
+ return False
21
+ return not (self.upper is not None and value > self.upper)
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class DeviceProfile:
26
+ """What is documented about a pump. Unknown properties are None: "not on file", never "fine".
27
+
28
+ `step_size` is the setting resolution, `settable_range` what the pump accepts at all,
29
+ `approved_range` the range the hospital approved for clinical use, and
30
+ `low_rate_warning_below` the rate under which a warning is shown (0.1 ml/h in this hospital).
31
+ """
32
+
33
+ id: str
34
+ name: str
35
+ step_size: Quantity | None = None
36
+ settable_range: Range | None = None
37
+ approved_range: Range | None = None
38
+ low_rate_warning_below: Quantity | None = None
39
+
40
+
41
+ @dataclass(frozen=True, slots=True)
42
+ class DeviceProfileChange:
43
+ """One saved state of an unused profile: who saved it and when.
44
+
45
+ The office makes a profile immutable once a protocol approval references it. New settings
46
+ require a new profile ID and protocol approval; the history records edits before first use.
47
+ """
48
+
49
+ profile: DeviceProfile
50
+ at: datetime
51
+ actor: str
@@ -0,0 +1,70 @@
1
+ """Field-by-field comparison of two versions' content, for the review screen."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ from dataclasses import dataclass
7
+ from datetime import date
8
+ from enum import Enum
9
+
10
+ from doseframe.protocols.schemes import PreparationScheme
11
+ from doseframe.protocols.version import VersionContent
12
+ from doseframe.units import Quantity, Unit
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class FieldChange:
17
+ path: str
18
+ before: str | None
19
+ after: str | None
20
+
21
+
22
+ def diff_contents(before: VersionContent | None, after: VersionContent) -> list[FieldChange]:
23
+ """Every field whose value differs; a field present on one side only has None on the other."""
24
+ old = flatten(before) if before is not None else {}
25
+ new = flatten(after)
26
+ paths = list(dict.fromkeys([*old, *new]))
27
+ return [
28
+ FieldChange(path, old.get(path), new.get(path))
29
+ for path in paths
30
+ if old.get(path) != new.get(path)
31
+ ]
32
+
33
+
34
+ def flatten(value: object, prefix: str = "") -> dict[str, str]: # noqa: PLR0911
35
+ """A flat mapping from field paths such as ``scheme.final_volume`` to display strings."""
36
+ match value:
37
+ case None:
38
+ return {prefix: "—"} if prefix else {}
39
+ case Quantity() | Unit() | Enum():
40
+ return {prefix: _text(value)}
41
+ case date():
42
+ return {prefix: value.isoformat()}
43
+ case bool() | int() | str():
44
+ return {prefix: str(value)}
45
+ case tuple() | list():
46
+ result: dict[str, str] = {}
47
+ for index, item in enumerate(value, start=1):
48
+ result |= flatten(item, f"{prefix}[{index}]")
49
+ return result or {prefix: "—"}
50
+ case _ if dataclasses.is_dataclass(value) and not isinstance(value, type):
51
+ result = {}
52
+ if isinstance(value, PreparationScheme):
53
+ result[_join(prefix, "kind")] = value.key
54
+ for f in dataclasses.fields(value):
55
+ result |= flatten(getattr(value, f.name), _join(prefix, f.name))
56
+ return result
57
+ case _:
58
+ return {prefix: str(value)}
59
+
60
+
61
+ def _text(value: Quantity | Unit | Enum) -> str:
62
+ if isinstance(value, Unit):
63
+ return value.symbol
64
+ if isinstance(value, Enum):
65
+ return str(value.value)
66
+ return str(value)
67
+
68
+
69
+ def _join(prefix: str, name: str) -> str:
70
+ return f"{prefix}.{name}" if prefix else name
@@ -0,0 +1,26 @@
1
+ """Errors of the protocol lifecycle."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from doseframe.findings import Finding
6
+ from doseframe.units import DoseframeError
7
+
8
+
9
+ class GovernanceError(DoseframeError):
10
+ """A protocol office action was refused."""
11
+
12
+
13
+ class IllegalTransitionError(GovernanceError):
14
+ """The operation is not allowed in the version's current state."""
15
+
16
+
17
+ class PermissionDeniedError(GovernanceError):
18
+ """The person lacks the role, or is the author where the four-eyes rule needs someone else."""
19
+
20
+
21
+ class GuardFailedError(GovernanceError):
22
+ """A guard of the lifecycle failed; `findings` say why."""
23
+
24
+ def __init__(self, message: str, findings: list[Finding] | None = None) -> None:
25
+ super().__init__(message)
26
+ self.findings = list(findings or [])