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,735 @@
|
|
|
1
|
+
"""The clinical use cases: match protocols, calculate a new perfusor, check a running one.
|
|
2
|
+
|
|
3
|
+
Nothing here logs, stores or caches a weight, dose, rate or result (BE-03).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass, replace
|
|
9
|
+
from decimal import Decimal
|
|
10
|
+
from typing import cast
|
|
11
|
+
|
|
12
|
+
from doseframe.calculation import (
|
|
13
|
+
CalculationStrategy,
|
|
14
|
+
Derivation,
|
|
15
|
+
StructuralError,
|
|
16
|
+
deviation_pct,
|
|
17
|
+
estimate_infused,
|
|
18
|
+
neighbouring_steps,
|
|
19
|
+
)
|
|
20
|
+
from doseframe.checks import CheckChain, CheckContext, CheckMode
|
|
21
|
+
from doseframe.findings import INCOMPATIBLE_UNIT, UNIT_ROLE, Finding, Severity
|
|
22
|
+
from doseframe.protocols import (
|
|
23
|
+
DeviceProfile,
|
|
24
|
+
InfusionScheme,
|
|
25
|
+
Medication,
|
|
26
|
+
ProtocolVersion,
|
|
27
|
+
SingleDoseOutcome,
|
|
28
|
+
SingleDoseScheme,
|
|
29
|
+
SingleDoseSetup,
|
|
30
|
+
StockSolution,
|
|
31
|
+
VersionContent,
|
|
32
|
+
Workflow,
|
|
33
|
+
evaluate_single_dose,
|
|
34
|
+
title_of,
|
|
35
|
+
usual_range,
|
|
36
|
+
)
|
|
37
|
+
from doseframe.rounding import RoundingPolicyRegistry, UnknownRoundingPolicyError
|
|
38
|
+
from doseframe.units import (
|
|
39
|
+
IncompatibleUnitError,
|
|
40
|
+
Quantity,
|
|
41
|
+
Role,
|
|
42
|
+
Unit,
|
|
43
|
+
UnitError,
|
|
44
|
+
UnitRoleError,
|
|
45
|
+
is_allowed,
|
|
46
|
+
result_units,
|
|
47
|
+
unit,
|
|
48
|
+
)
|
|
49
|
+
from doseframe.use_cases.gate import (
|
|
50
|
+
AvailabilityGate,
|
|
51
|
+
VersionUnusableError,
|
|
52
|
+
activate,
|
|
53
|
+
require_workflow,
|
|
54
|
+
)
|
|
55
|
+
from doseframe.use_cases.ports import Clock, ProtocolRepository
|
|
56
|
+
from doseframe.use_cases.results import (
|
|
57
|
+
CalculationResult,
|
|
58
|
+
ConcentrationSource,
|
|
59
|
+
ProtocolMatch,
|
|
60
|
+
ReverseCheckResult,
|
|
61
|
+
SettingStep,
|
|
62
|
+
SingleDoseResult,
|
|
63
|
+
Unavailable,
|
|
64
|
+
VersionRef,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def version_ref(repo: ProtocolRepository, version: ProtocolVersion, clock: Clock) -> VersionRef:
|
|
69
|
+
protocol = repo.get_protocol(version.protocol_id)
|
|
70
|
+
medication = repo.get_medication(protocol.medication_id)
|
|
71
|
+
content = version.content
|
|
72
|
+
device = device_of(repo, version)
|
|
73
|
+
title = title_of(medication.name, content.scheme, content.weight_scope, device, protocol.name)
|
|
74
|
+
return VersionRef(
|
|
75
|
+
version_id=version.id,
|
|
76
|
+
protocol_id=protocol.id,
|
|
77
|
+
protocol_name=title.text(),
|
|
78
|
+
medication_name=medication.name,
|
|
79
|
+
number=version.number,
|
|
80
|
+
scheme_kind=content.scheme.key,
|
|
81
|
+
workflow=content.scheme.workflow,
|
|
82
|
+
dose_unit=content.dose_unit,
|
|
83
|
+
usual_dose_units=content.usual_dose_units,
|
|
84
|
+
weight_scope=content.weight_scope,
|
|
85
|
+
stock_solutions=content.scheme.stock_solutions,
|
|
86
|
+
notes=content.notes,
|
|
87
|
+
fictitious=content.fictitious,
|
|
88
|
+
review_overdue=version.is_review_overdue(clock.today()),
|
|
89
|
+
device_name=device.name if device else None,
|
|
90
|
+
title=title,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def device_of(repo: ProtocolRepository, version: ProtocolVersion) -> DeviceProfile | None:
|
|
95
|
+
"""The pump profile a version names, if any."""
|
|
96
|
+
profile_id = version.content.device_profile_id
|
|
97
|
+
return repo.get_device_profile(profile_id) if profile_id else None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def to_protocol_unit(dose: Quantity, expected: Unit) -> Quantity:
|
|
101
|
+
"""The dose in the protocol's unit (V2-02). A dose of another kind stays as typed, so the
|
|
102
|
+
unit check blocks it and nothing is guessed."""
|
|
103
|
+
return dose.to(expected) if dose.unit.is_compatible(expected) else dose
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def views(value: Quantity | None, content: VersionContent) -> tuple[Quantity, ...]:
|
|
107
|
+
"""A result in the protocol's unit and in each usual unit; nothing else is offered."""
|
|
108
|
+
if value is None:
|
|
109
|
+
return ()
|
|
110
|
+
return tuple(value.to(u) for u in result_units(content.dose_unit, content.usual_dose_units))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def problem(exc: Exception) -> Finding:
|
|
114
|
+
"""Turn an error from the calculation into a BLOCK finding the checks will report."""
|
|
115
|
+
match exc:
|
|
116
|
+
case StructuralError():
|
|
117
|
+
return Finding(exc.code, Severity.BLOCK, str(exc))
|
|
118
|
+
case UnitRoleError():
|
|
119
|
+
return Finding(UNIT_ROLE, Severity.BLOCK, str(exc))
|
|
120
|
+
case IncompatibleUnitError():
|
|
121
|
+
return Finding(INCOMPATIBLE_UNIT, Severity.BLOCK, str(exc))
|
|
122
|
+
case _:
|
|
123
|
+
return Finding("invalid_input", Severity.BLOCK, str(exc))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class MatchProtocolsUseCase:
|
|
127
|
+
"""Published versions whose weight range contains the weight. It never chooses (ST-03)."""
|
|
128
|
+
|
|
129
|
+
def __init__(self, repo: ProtocolRepository, clock: Clock) -> None:
|
|
130
|
+
self._repo = repo
|
|
131
|
+
self._clock = clock
|
|
132
|
+
|
|
133
|
+
def medications_in_use(self) -> list[Medication]:
|
|
134
|
+
"""Medications with at least one published version, for the first screen."""
|
|
135
|
+
result: list[Medication] = []
|
|
136
|
+
with self._repo.transaction():
|
|
137
|
+
for medication in self._repo.list_medications():
|
|
138
|
+
protocols = self._repo.list_protocols(medication.id)
|
|
139
|
+
if any(
|
|
140
|
+
v.is_usable()
|
|
141
|
+
for p in protocols
|
|
142
|
+
for v in activate(self._repo, p.id, self._clock)
|
|
143
|
+
):
|
|
144
|
+
result.append(medication)
|
|
145
|
+
return sorted(result, key=lambda m: m.name)
|
|
146
|
+
|
|
147
|
+
def execute(self, medication_id: str, weight: Quantity) -> list[ProtocolMatch]:
|
|
148
|
+
if not is_allowed(weight.unit, Role.WEIGHT) or not weight.is_positive():
|
|
149
|
+
return []
|
|
150
|
+
matches: list[ProtocolMatch] = []
|
|
151
|
+
with self._repo.transaction():
|
|
152
|
+
for protocol in self._repo.list_protocols(medication_id):
|
|
153
|
+
for version in activate(self._repo, protocol.id, self._clock):
|
|
154
|
+
content = version.content
|
|
155
|
+
if version.is_usable() and content.weight_scope.contains(weight):
|
|
156
|
+
matches.append(self._match(version, weight))
|
|
157
|
+
return sorted(matches, key=lambda m: (m.version.protocol_name, m.version.number))
|
|
158
|
+
|
|
159
|
+
def label_required(self, medication_id: str, weight: Quantity) -> bool:
|
|
160
|
+
"""True when published infusion protocols for this drug differ in concentration.
|
|
161
|
+
|
|
162
|
+
All weight bands count: a running syringe may still hold a preparation from the band the
|
|
163
|
+
patient has just left, so the protocol chosen today cannot tell which strength it is. A
|
|
164
|
+
concentration that cannot be worked out counts as different (fail closed).
|
|
165
|
+
"""
|
|
166
|
+
if not is_allowed(weight.unit, Role.WEIGHT) or not weight.is_positive():
|
|
167
|
+
return False
|
|
168
|
+
concentrations: list[Quantity | None] = []
|
|
169
|
+
with self._repo.transaction():
|
|
170
|
+
for protocol in self._repo.list_protocols(medication_id):
|
|
171
|
+
for version in activate(self._repo, protocol.id, self._clock):
|
|
172
|
+
scheme = version.content.scheme
|
|
173
|
+
if not version.is_usable() or scheme.workflow is not Workflow.INFUSION:
|
|
174
|
+
continue
|
|
175
|
+
try:
|
|
176
|
+
strategy = cast(InfusionScheme, scheme).create_strategy()
|
|
177
|
+
concentrations.append(strategy.concentration_for(weight).value)
|
|
178
|
+
except (UnitError, StructuralError):
|
|
179
|
+
concentrations.append(None)
|
|
180
|
+
if None in concentrations:
|
|
181
|
+
return len(concentrations) > 1
|
|
182
|
+
return any(c != concentrations[0] for c in concentrations[1:])
|
|
183
|
+
|
|
184
|
+
def _match(self, version: ProtocolVersion, weight: Quantity) -> ProtocolMatch:
|
|
185
|
+
ref = version_ref(self._repo, version, self._clock)
|
|
186
|
+
if version.content.scheme.workflow is not Workflow.INFUSION:
|
|
187
|
+
return ProtocolMatch(ref, None, None) # a single dose has no syringe concentration
|
|
188
|
+
scheme = cast(InfusionScheme, version.content.scheme)
|
|
189
|
+
try:
|
|
190
|
+
concentration: Quantity | None = scheme.shown(
|
|
191
|
+
scheme.create_strategy().concentration_for(weight).value
|
|
192
|
+
)
|
|
193
|
+
except (UnitError, StructuralError):
|
|
194
|
+
concentration = None
|
|
195
|
+
reference = scheme.reference_dose()
|
|
196
|
+
if reference is not None and reference.unit.is_compatible(version.content.dose_unit):
|
|
197
|
+
reference = reference.to(version.content.dose_unit)
|
|
198
|
+
return ProtocolMatch(ref, concentration, reference)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
@dataclass(frozen=True, slots=True)
|
|
202
|
+
class CalculationRequest:
|
|
203
|
+
version_id: str
|
|
204
|
+
weight: Quantity
|
|
205
|
+
dose: Quantity
|
|
206
|
+
stock_label: str | None = None
|
|
207
|
+
setting: Quantity | None = None
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class CalculateRateUseCase:
|
|
211
|
+
"""Facade: the one call that runs a calculation on a confirmed protocol version.
|
|
212
|
+
|
|
213
|
+
Order: availability gate, preparation, exact rate, rounding rule, dose at the setting,
|
|
214
|
+
deviation, check chain. It does no arithmetic itself.
|
|
215
|
+
"""
|
|
216
|
+
|
|
217
|
+
def __init__(
|
|
218
|
+
self,
|
|
219
|
+
repo: ProtocolRepository,
|
|
220
|
+
gate: AvailabilityGate,
|
|
221
|
+
registry: RoundingPolicyRegistry,
|
|
222
|
+
chain: CheckChain,
|
|
223
|
+
clock: Clock,
|
|
224
|
+
) -> None:
|
|
225
|
+
self._repo = repo
|
|
226
|
+
self._gate = gate
|
|
227
|
+
self._registry = registry
|
|
228
|
+
self._chain = chain
|
|
229
|
+
self._clock = clock
|
|
230
|
+
|
|
231
|
+
def execute(self, request: CalculationRequest) -> CalculationResult | Unavailable:
|
|
232
|
+
try:
|
|
233
|
+
version = self._gate.ensure_usable(request.version_id)
|
|
234
|
+
except VersionUnusableError as exc:
|
|
235
|
+
return exc.unavailable
|
|
236
|
+
wrong = require_workflow(version, Workflow.INFUSION, self._gate.fallback_note)
|
|
237
|
+
if wrong:
|
|
238
|
+
return wrong
|
|
239
|
+
content = version.content
|
|
240
|
+
scheme = cast(InfusionScheme, content.scheme)
|
|
241
|
+
problems: list[Finding] = []
|
|
242
|
+
weight, entered = request.weight, request.dose
|
|
243
|
+
dose = to_protocol_unit(entered, content.dose_unit)
|
|
244
|
+
|
|
245
|
+
stock = _choose_stock(scheme.stock_solutions, request.stock_label, problems)
|
|
246
|
+
preparation = None
|
|
247
|
+
if stock is not None:
|
|
248
|
+
try:
|
|
249
|
+
preparation = scheme.prepare(weight, stock)
|
|
250
|
+
except (StructuralError, UnitError) as exc:
|
|
251
|
+
problems.append(problem(exc))
|
|
252
|
+
|
|
253
|
+
strategy = scheme.create_strategy()
|
|
254
|
+
concentration = exact = None
|
|
255
|
+
if dose.unit == content.dose_unit: # another kind: UnitCheck blocks
|
|
256
|
+
try:
|
|
257
|
+
concentration = strategy.concentration_for(weight)
|
|
258
|
+
exact = strategy.dose_to_rate(dose, weight)
|
|
259
|
+
except (StructuralError, UnitError) as exc:
|
|
260
|
+
problems.append(problem(exc))
|
|
261
|
+
|
|
262
|
+
device = device_of(self._repo, version)
|
|
263
|
+
suggested = None
|
|
264
|
+
if exact is not None:
|
|
265
|
+
try:
|
|
266
|
+
policy = self._registry.get(content.rounding_policy_key)
|
|
267
|
+
suggested = policy.round(exact.value, device)
|
|
268
|
+
except UnknownRoundingPolicyError as exc:
|
|
269
|
+
problems.append(Finding("unknown_rounding_policy", Severity.BLOCK, str(exc)))
|
|
270
|
+
|
|
271
|
+
dose_at_setting: Derivation | None = None
|
|
272
|
+
deviation: Decimal | None = None
|
|
273
|
+
if request.setting is not None and exact is not None:
|
|
274
|
+
try:
|
|
275
|
+
dose_at_setting = strategy.rate_to_dose(request.setting, weight, content.dose_unit)
|
|
276
|
+
deviation = deviation_pct(dose_at_setting.value, dose)
|
|
277
|
+
except (StructuralError, UnitError) as exc:
|
|
278
|
+
problems.append(problem(exc))
|
|
279
|
+
|
|
280
|
+
ctx = CheckContext(
|
|
281
|
+
mode=CheckMode.CALCULATION,
|
|
282
|
+
today=self._clock.today(),
|
|
283
|
+
expected_dose_unit=content.dose_unit,
|
|
284
|
+
weight_scope=content.weight_scope,
|
|
285
|
+
weight=weight,
|
|
286
|
+
dose=dose,
|
|
287
|
+
rate=exact.value if exact else None,
|
|
288
|
+
setting=request.setting if dose_at_setting else None,
|
|
289
|
+
delivered_dose=dose_at_setting.value if dose_at_setting else None,
|
|
290
|
+
withdrawal_volume=preparation.drawn_volume if preparation else None,
|
|
291
|
+
limits=content.limits,
|
|
292
|
+
device=device,
|
|
293
|
+
review_due=content.review_due,
|
|
294
|
+
problems=tuple(problems),
|
|
295
|
+
)
|
|
296
|
+
suggested, suggested_dose, suggested_deviation, findings = self._check_suggestion(
|
|
297
|
+
ctx, suggested, strategy
|
|
298
|
+
)
|
|
299
|
+
if ctx.setting is not None:
|
|
300
|
+
# A typed setting is what the pump will run, so it passes the same checks as a
|
|
301
|
+
# pump-step button: a step the button refuses cannot be typed in instead.
|
|
302
|
+
intended = self._evaluate_setting(ctx, ctx.setting, strategy)
|
|
303
|
+
findings += [f for f in intended.findings if f.blocks and f not in findings]
|
|
304
|
+
setting_steps = ()
|
|
305
|
+
step = device.step_size if device is not None else None
|
|
306
|
+
if (
|
|
307
|
+
suggested is None
|
|
308
|
+
and exact is not None
|
|
309
|
+
and step is not None
|
|
310
|
+
and step.unit.is_compatible(exact.value.unit)
|
|
311
|
+
and step.is_positive()
|
|
312
|
+
and not any(f.blocks for f in findings)
|
|
313
|
+
):
|
|
314
|
+
setting_steps = tuple(
|
|
315
|
+
self._evaluate_setting(ctx, candidate, strategy)
|
|
316
|
+
for candidate in neighbouring_steps(exact.value, step)
|
|
317
|
+
if candidate.is_positive()
|
|
318
|
+
)
|
|
319
|
+
return CalculationResult(
|
|
320
|
+
version=version_ref(self._repo, version, self._clock),
|
|
321
|
+
weight=weight,
|
|
322
|
+
dose=dose,
|
|
323
|
+
dose_entered=entered,
|
|
324
|
+
stock=stock,
|
|
325
|
+
preparation=preparation,
|
|
326
|
+
concentration=concentration,
|
|
327
|
+
exact_rate=exact,
|
|
328
|
+
suggested_setting=suggested,
|
|
329
|
+
suggested_dose=suggested_dose,
|
|
330
|
+
suggested_deviation_pct=suggested_deviation,
|
|
331
|
+
setting=request.setting,
|
|
332
|
+
dose_at_setting=dose_at_setting,
|
|
333
|
+
deviation_pct=deviation,
|
|
334
|
+
usual_range=usual_range(content.limits),
|
|
335
|
+
dose_views=views(dose_at_setting.value if dose_at_setting else None, content),
|
|
336
|
+
findings=tuple(findings),
|
|
337
|
+
setting_steps=setting_steps,
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
def _check_suggestion(
|
|
341
|
+
self, ctx: CheckContext, suggested: Quantity | None, strategy: CalculationStrategy
|
|
342
|
+
) -> tuple[Quantity | None, Quantity | None, Decimal | None, list[Finding]]:
|
|
343
|
+
"""A suggestion must pass the same checks as a setting entered by the clinician."""
|
|
344
|
+
findings = self._chain.run(ctx)
|
|
345
|
+
if suggested is None:
|
|
346
|
+
return None, None, None, findings
|
|
347
|
+
step = self._evaluate_setting(ctx, suggested, strategy)
|
|
348
|
+
if any(f.blocks for f in step.findings):
|
|
349
|
+
return None, None, None, [*findings, _suggestion_unavailable()]
|
|
350
|
+
findings += [f for f in step.findings if f not in findings]
|
|
351
|
+
return step.setting, step.delivered_dose, step.deviation_pct, findings
|
|
352
|
+
|
|
353
|
+
def _evaluate_setting(
|
|
354
|
+
self, ctx: CheckContext, setting: Quantity, strategy: CalculationStrategy
|
|
355
|
+
) -> SettingStep:
|
|
356
|
+
assert ctx.dose is not None
|
|
357
|
+
try:
|
|
358
|
+
dose, deviation = _dose_and_deviation(
|
|
359
|
+
strategy.rate_to_dose(setting, ctx.weight, ctx.expected_dose_unit).value, ctx.dose
|
|
360
|
+
)
|
|
361
|
+
findings = self._chain.run(
|
|
362
|
+
replace(ctx, rate=setting, setting=setting, delivered_dose=dose)
|
|
363
|
+
)
|
|
364
|
+
except (StructuralError, UnitError) as exc:
|
|
365
|
+
return SettingStep(setting, None, None, (problem(exc),))
|
|
366
|
+
return SettingStep(setting, dose, deviation, tuple(findings))
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
@dataclass(frozen=True, slots=True)
|
|
370
|
+
class SingleDoseRequest:
|
|
371
|
+
version_id: str
|
|
372
|
+
weight: Quantity
|
|
373
|
+
daily_dose: Quantity
|
|
374
|
+
stock_label: str | None = None
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
class CalculateSingleDoseUseCase:
|
|
378
|
+
"""Facade for a divided daily dose: gate, workflow, conversion, shared evaluation, checks."""
|
|
379
|
+
|
|
380
|
+
def __init__(
|
|
381
|
+
self,
|
|
382
|
+
repo: ProtocolRepository,
|
|
383
|
+
gate: AvailabilityGate,
|
|
384
|
+
registry: RoundingPolicyRegistry,
|
|
385
|
+
chain: CheckChain,
|
|
386
|
+
clock: Clock,
|
|
387
|
+
) -> None:
|
|
388
|
+
self._repo = repo
|
|
389
|
+
self._gate = gate
|
|
390
|
+
self._registry = registry
|
|
391
|
+
self._chain = chain
|
|
392
|
+
self._clock = clock
|
|
393
|
+
|
|
394
|
+
def execute(self, request: SingleDoseRequest) -> SingleDoseResult | Unavailable:
|
|
395
|
+
try:
|
|
396
|
+
version = self._gate.ensure_usable(request.version_id)
|
|
397
|
+
except VersionUnusableError as exc:
|
|
398
|
+
return exc.unavailable
|
|
399
|
+
wrong = require_workflow(version, Workflow.SINGLE_DOSE, self._gate.fallback_note)
|
|
400
|
+
if wrong:
|
|
401
|
+
return wrong
|
|
402
|
+
content = version.content
|
|
403
|
+
scheme = cast(SingleDoseScheme, content.scheme)
|
|
404
|
+
problems: list[Finding] = []
|
|
405
|
+
weight, entered = request.weight, request.daily_dose
|
|
406
|
+
daily = to_protocol_unit(entered, content.dose_unit)
|
|
407
|
+
stock = _choose_stock(scheme.stock_solutions, request.stock_label, problems)
|
|
408
|
+
outcome: SingleDoseOutcome | None = None
|
|
409
|
+
if stock is not None and daily.unit == content.dose_unit:
|
|
410
|
+
outcome = evaluate_single_dose(
|
|
411
|
+
scheme,
|
|
412
|
+
stock,
|
|
413
|
+
daily,
|
|
414
|
+
weight,
|
|
415
|
+
self._setup(content),
|
|
416
|
+
content.max_rounding_deviation_pct,
|
|
417
|
+
)
|
|
418
|
+
problems += outcome.findings
|
|
419
|
+
ctx = CheckContext(
|
|
420
|
+
mode=CheckMode.CALCULATION,
|
|
421
|
+
today=self._clock.today(),
|
|
422
|
+
expected_dose_unit=content.dose_unit,
|
|
423
|
+
weight_scope=content.weight_scope,
|
|
424
|
+
weight=weight,
|
|
425
|
+
dose=daily,
|
|
426
|
+
limits=content.limits,
|
|
427
|
+
device=None, # the syringe was checked by evaluate_single_dose; there is no pump rate
|
|
428
|
+
review_due=content.review_due,
|
|
429
|
+
problems=tuple(problems),
|
|
430
|
+
)
|
|
431
|
+
offers_choice = outcome is not None and outcome.offers_choice
|
|
432
|
+
only = outcome.options[0] if outcome is not None and outcome.options else None
|
|
433
|
+
if not offers_choice and only is not None and only.amount is not None:
|
|
434
|
+
# One rounded amount: the checks see it as before V3, with the delivered dose and the
|
|
435
|
+
# withdrawal volume filled in. Only a choice runs them once without, then per option.
|
|
436
|
+
ctx = replace(
|
|
437
|
+
ctx, delivered_dose=only.delivered_daily_dose, withdrawal_volume=only.volume
|
|
438
|
+
)
|
|
439
|
+
findings = tuple(f for f in self._chain.run(ctx) if f.code != "device_not_on_file")
|
|
440
|
+
options = ()
|
|
441
|
+
if outcome is not None:
|
|
442
|
+
options = tuple(
|
|
443
|
+
replace(
|
|
444
|
+
option,
|
|
445
|
+
findings=option.findings
|
|
446
|
+
+ tuple(
|
|
447
|
+
f
|
|
448
|
+
for f in self._chain.run(
|
|
449
|
+
replace(
|
|
450
|
+
ctx,
|
|
451
|
+
delivered_dose=option.delivered_daily_dose,
|
|
452
|
+
withdrawal_volume=option.volume
|
|
453
|
+
if option.amount is not None
|
|
454
|
+
else None,
|
|
455
|
+
)
|
|
456
|
+
)
|
|
457
|
+
if f not in findings and f.code != "device_not_on_file"
|
|
458
|
+
),
|
|
459
|
+
)
|
|
460
|
+
for option in outcome.options
|
|
461
|
+
)
|
|
462
|
+
if not offers_choice and options:
|
|
463
|
+
findings += tuple(f for f in options[0].findings if f not in findings)
|
|
464
|
+
return SingleDoseResult(
|
|
465
|
+
version=version_ref(self._repo, version, self._clock),
|
|
466
|
+
weight=weight,
|
|
467
|
+
daily_dose_entered=entered,
|
|
468
|
+
daily_dose=daily,
|
|
469
|
+
stock=stock,
|
|
470
|
+
exact=outcome.exact if outcome is not None else None,
|
|
471
|
+
exact_volume=outcome.exact_volume if outcome is not None else None,
|
|
472
|
+
options=options,
|
|
473
|
+
offers_choice=offers_choice,
|
|
474
|
+
doses_per_day=scheme.doses_per_day,
|
|
475
|
+
usual_range=usual_range(content.limits),
|
|
476
|
+
fallback_note=self._gate.fallback_note,
|
|
477
|
+
findings=findings,
|
|
478
|
+
)
|
|
479
|
+
|
|
480
|
+
def _setup(self, content: VersionContent) -> SingleDoseSetup | None:
|
|
481
|
+
try:
|
|
482
|
+
rounding = self._registry.get(content.rounding_policy_key)
|
|
483
|
+
except UnknownRoundingPolicyError:
|
|
484
|
+
return None
|
|
485
|
+
device = (
|
|
486
|
+
self._repo.get_device_profile(content.device_profile_id)
|
|
487
|
+
if content.device_profile_id
|
|
488
|
+
else None
|
|
489
|
+
)
|
|
490
|
+
return SingleDoseSetup(rounding, device)
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
@dataclass(frozen=True, slots=True)
|
|
494
|
+
class ReverseCheckRequest:
|
|
495
|
+
version_id: str
|
|
496
|
+
weight: Quantity
|
|
497
|
+
rate: Quantity
|
|
498
|
+
label_drug_amount: Quantity | None = None
|
|
499
|
+
label_final_volume: Quantity | None = None
|
|
500
|
+
prescribed_dose: Quantity | None = None
|
|
501
|
+
running_for: Quantity | None = None
|
|
502
|
+
comparison_rate: Quantity | None = None
|
|
503
|
+
require_label_if_ambiguous: bool = False
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
class CheckRunningPerfusorUseCase:
|
|
507
|
+
"""The dose a running pump delivers, from the rate on the pump and the syringe label."""
|
|
508
|
+
|
|
509
|
+
def __init__(
|
|
510
|
+
self, repo: ProtocolRepository, gate: AvailabilityGate, chain: CheckChain, clock: Clock
|
|
511
|
+
) -> None:
|
|
512
|
+
self._repo = repo
|
|
513
|
+
self._gate = gate
|
|
514
|
+
self._chain = chain
|
|
515
|
+
self._clock = clock
|
|
516
|
+
|
|
517
|
+
def execute(self, request: ReverseCheckRequest) -> ReverseCheckResult | Unavailable:
|
|
518
|
+
try:
|
|
519
|
+
version = self._gate.ensure_usable(request.version_id)
|
|
520
|
+
except VersionUnusableError as exc:
|
|
521
|
+
return exc.unavailable
|
|
522
|
+
wrong = require_workflow(version, Workflow.INFUSION, self._gate.fallback_note)
|
|
523
|
+
if wrong:
|
|
524
|
+
return wrong
|
|
525
|
+
content = version.content
|
|
526
|
+
scheme = cast(InfusionScheme, content.scheme)
|
|
527
|
+
strategy = scheme.create_strategy()
|
|
528
|
+
problems: list[Finding] = []
|
|
529
|
+
weight, rate = request.weight, request.rate
|
|
530
|
+
|
|
531
|
+
protocol_concentration = None
|
|
532
|
+
try:
|
|
533
|
+
protocol_concentration = scheme.shown(strategy.concentration_for(weight).value)
|
|
534
|
+
except (StructuralError, UnitError) as exc:
|
|
535
|
+
problems.append(problem(exc))
|
|
536
|
+
|
|
537
|
+
label = self._read_label(version, request, problems)
|
|
538
|
+
implied_weight = None
|
|
539
|
+
if label is not None and request.label_drug_amount is not None:
|
|
540
|
+
try:
|
|
541
|
+
implied_weight = scheme.implied_preparation_weight(request.label_drug_amount)
|
|
542
|
+
except UnitError as exc:
|
|
543
|
+
problems.append(problem(exc))
|
|
544
|
+
notices = _label_notices(label, protocol_concentration, implied_weight, weight)
|
|
545
|
+
|
|
546
|
+
used = label if label is not None else protocol_concentration
|
|
547
|
+
source = ConcentrationSource.LABEL if label is not None else ConcentrationSource.PROTOCOL
|
|
548
|
+
delivered: Derivation | None = None
|
|
549
|
+
if used is not None and not problems:
|
|
550
|
+
try:
|
|
551
|
+
delivered = strategy.rate_to_dose(rate, weight, content.dose_unit, used)
|
|
552
|
+
except (StructuralError, UnitError) as exc:
|
|
553
|
+
problems.append(problem(exc))
|
|
554
|
+
|
|
555
|
+
infused = None
|
|
556
|
+
if request.running_for is not None and used is not None and delivered is not None:
|
|
557
|
+
try:
|
|
558
|
+
infused = estimate_infused(rate, request.running_for, used)
|
|
559
|
+
except (StructuralError, UnitError) as exc:
|
|
560
|
+
problems.append(problem(exc))
|
|
561
|
+
|
|
562
|
+
prescribed = (
|
|
563
|
+
to_protocol_unit(request.prescribed_dose, content.dose_unit)
|
|
564
|
+
if request.prescribed_dose is not None
|
|
565
|
+
else None
|
|
566
|
+
)
|
|
567
|
+
deviation = None
|
|
568
|
+
if (
|
|
569
|
+
delivered is not None
|
|
570
|
+
and prescribed is not None
|
|
571
|
+
and prescribed.unit == content.dose_unit
|
|
572
|
+
):
|
|
573
|
+
try:
|
|
574
|
+
deviation = deviation_pct(delivered.value, prescribed)
|
|
575
|
+
except StructuralError as exc:
|
|
576
|
+
problems.append(problem(exc))
|
|
577
|
+
|
|
578
|
+
ctx = CheckContext(
|
|
579
|
+
mode=CheckMode.REVERSE_CHECK,
|
|
580
|
+
today=self._clock.today(),
|
|
581
|
+
expected_dose_unit=content.dose_unit,
|
|
582
|
+
weight_scope=content.weight_scope,
|
|
583
|
+
weight=weight,
|
|
584
|
+
dose=prescribed,
|
|
585
|
+
rate=rate if is_allowed(rate.unit, Role.RATE) else None,
|
|
586
|
+
delivered_dose=delivered.value if delivered else None,
|
|
587
|
+
limits=content.limits,
|
|
588
|
+
device=device_of(self._repo, version),
|
|
589
|
+
review_due=content.review_due,
|
|
590
|
+
problems=tuple(problems),
|
|
591
|
+
)
|
|
592
|
+
findings = tuple(notices + self._chain.run(ctx))
|
|
593
|
+
return ReverseCheckResult(
|
|
594
|
+
version=version_ref(self._repo, version, self._clock),
|
|
595
|
+
weight=weight,
|
|
596
|
+
rate=rate,
|
|
597
|
+
concentration=used,
|
|
598
|
+
concentration_source=source,
|
|
599
|
+
protocol_concentration=protocol_concentration,
|
|
600
|
+
implied_preparation_weight=implied_weight,
|
|
601
|
+
delivered_dose=delivered,
|
|
602
|
+
prescribed_dose=prescribed,
|
|
603
|
+
deviation_pct=deviation,
|
|
604
|
+
findings=findings,
|
|
605
|
+
dose_views=views(delivered.value if delivered else None, content),
|
|
606
|
+
usual_range=usual_range(content.limits),
|
|
607
|
+
infused=infused,
|
|
608
|
+
rate_difference=rate - request.comparison_rate
|
|
609
|
+
if request.comparison_rate is not None
|
|
610
|
+
and delivered is not None
|
|
611
|
+
and rate.unit.is_compatible(request.comparison_rate.unit)
|
|
612
|
+
else None,
|
|
613
|
+
)
|
|
614
|
+
|
|
615
|
+
def _read_label(
|
|
616
|
+
self,
|
|
617
|
+
version: ProtocolVersion,
|
|
618
|
+
request: ReverseCheckRequest,
|
|
619
|
+
problems: list[Finding],
|
|
620
|
+
) -> Quantity | None:
|
|
621
|
+
if (
|
|
622
|
+
request.require_label_if_ambiguous
|
|
623
|
+
and request.label_drug_amount is None
|
|
624
|
+
and request.label_final_volume is None
|
|
625
|
+
):
|
|
626
|
+
matcher = MatchProtocolsUseCase(self._repo, self._clock)
|
|
627
|
+
medication_id = self._repo.get_protocol(version.protocol_id).medication_id
|
|
628
|
+
if matcher.label_required(medication_id, request.weight):
|
|
629
|
+
problems.append(
|
|
630
|
+
Finding(
|
|
631
|
+
"label_concentration_required",
|
|
632
|
+
Severity.BLOCK,
|
|
633
|
+
"enter the syringe label when approved concentrations differ",
|
|
634
|
+
)
|
|
635
|
+
)
|
|
636
|
+
return _label_concentration(request, problems)
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
# --- helpers ----------------------------------------------------------------------------------
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def _choose_stock(
|
|
643
|
+
stocks: tuple[StockSolution, ...], label: str | None, problems: list[Finding]
|
|
644
|
+
) -> StockSolution | None:
|
|
645
|
+
if label is None:
|
|
646
|
+
if not stocks:
|
|
647
|
+
problems.append(
|
|
648
|
+
Finding(
|
|
649
|
+
"no_stock_solution",
|
|
650
|
+
Severity.BLOCK,
|
|
651
|
+
"the protocol has no approved stock solution",
|
|
652
|
+
)
|
|
653
|
+
)
|
|
654
|
+
return stocks[0] if stocks else None
|
|
655
|
+
for stock in stocks:
|
|
656
|
+
if stock.label == label:
|
|
657
|
+
return stock
|
|
658
|
+
problems.append(
|
|
659
|
+
Finding(
|
|
660
|
+
"unknown_stock",
|
|
661
|
+
Severity.BLOCK,
|
|
662
|
+
f"{label!r} is not an approved stock solution",
|
|
663
|
+
{"stock": label},
|
|
664
|
+
)
|
|
665
|
+
)
|
|
666
|
+
return None
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def _suggestion_unavailable() -> Finding:
|
|
670
|
+
return Finding(
|
|
671
|
+
"suggestion_unavailable",
|
|
672
|
+
Severity.WARN,
|
|
673
|
+
"the rounded pump suggestion violates a protocol or device limit",
|
|
674
|
+
)
|
|
675
|
+
|
|
676
|
+
|
|
677
|
+
def _dose_and_deviation(dose_at: Quantity, prescribed: Quantity) -> tuple[Quantity, Decimal]:
|
|
678
|
+
return dose_at, deviation_pct(dose_at, prescribed)
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def _label_concentration(request: ReverseCheckRequest, problems: list[Finding]) -> Quantity | None:
|
|
682
|
+
amount, volume = request.label_drug_amount, request.label_final_volume
|
|
683
|
+
if amount is None and volume is None:
|
|
684
|
+
return None
|
|
685
|
+
if amount is None or volume is None:
|
|
686
|
+
problems.append(
|
|
687
|
+
Finding("label_incomplete", Severity.BLOCK, "drug amount and final volume are needed")
|
|
688
|
+
)
|
|
689
|
+
return None
|
|
690
|
+
if not (is_allowed(amount.unit, Role.DRUG_AMOUNT) and is_allowed(volume.unit, Role.VOLUME)):
|
|
691
|
+
problems.append(Finding(UNIT_ROLE, Severity.BLOCK, "label values need mg/IU and ml"))
|
|
692
|
+
return None
|
|
693
|
+
if not (amount.is_positive() and volume.is_positive()):
|
|
694
|
+
problems.append(Finding("not_positive", Severity.BLOCK, "label values must be positive"))
|
|
695
|
+
return None
|
|
696
|
+
# The label keeps the unit the nurse entered; the concentration needs a strength unit the
|
|
697
|
+
# catalogue accepts, so a mass in g (g/ml is no strength unit) is expressed in mg first.
|
|
698
|
+
if not is_allowed(
|
|
699
|
+
unit(f"{amount.unit.symbol}/ml"), Role.CONCENTRATION
|
|
700
|
+
) and amount.unit.is_compatible(unit("mg")):
|
|
701
|
+
amount = amount.to("mg")
|
|
702
|
+
concentration = amount / volume
|
|
703
|
+
return concentration.to(f"{amount.unit.symbol}/ml")
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def _label_notices(
|
|
707
|
+
label: Quantity | None,
|
|
708
|
+
protocol: Quantity | None,
|
|
709
|
+
implied_weight: Quantity | None,
|
|
710
|
+
weight: Quantity,
|
|
711
|
+
) -> list[Finding]:
|
|
712
|
+
"""Compare the label with the protocol: a factor of ten shows here (RP-02, AT-06)."""
|
|
713
|
+
if label is None or protocol is None or not label.unit.is_compatible(protocol.unit):
|
|
714
|
+
return []
|
|
715
|
+
findings: list[Finding] = []
|
|
716
|
+
if implied_weight is not None and implied_weight != weight:
|
|
717
|
+
findings.append(
|
|
718
|
+
Finding(
|
|
719
|
+
"prepared_for_other_weight",
|
|
720
|
+
Severity.WARN,
|
|
721
|
+
f"the syringe was prepared for {implied_weight}, the patient weighs {weight}",
|
|
722
|
+
{"implied_weight": str(implied_weight), "weight": str(weight)},
|
|
723
|
+
)
|
|
724
|
+
)
|
|
725
|
+
if label == protocol:
|
|
726
|
+
return findings
|
|
727
|
+
findings.append(
|
|
728
|
+
Finding(
|
|
729
|
+
"label_concentration_differs",
|
|
730
|
+
Severity.WARN,
|
|
731
|
+
f"label {label.to(protocol.unit)} differs from the protocol's {protocol}",
|
|
732
|
+
{"label": str(label.to(protocol.unit)), "protocol": str(protocol)},
|
|
733
|
+
)
|
|
734
|
+
)
|
|
735
|
+
return findings
|