forked from LoopKit/LoopAlgorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoopAlgorithm.swift
More file actions
818 lines (718 loc) · 38.1 KB
/
Copy pathLoopAlgorithm.swift
File metadata and controls
818 lines (718 loc) · 38.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//
// LoopAlgorithm.swift
//
// Created by Pete Schwamb on 6/30/23.
// Copyright © 2023 LoopKit Authors. All rights reserved.
//
import Foundation
public enum AlgorithmError: Error {
case missingGlucose
case glucoseTooOld
case basalTimelineIncomplete
case missingSuspendThreshold
case sensitivityTimelineStartsTooLate
case sensitivityTimelineEndsTooEarly
case futureBasalNotAllowed
}
public struct LoopAlgorithmEffects<CarbStatusType: CarbEntry> {
public var insulin: [GlucoseEffect]
public var carbs: [GlucoseEffect]
public var carbStatus: [CarbStatus<CarbStatusType>]
public var retrospectiveCorrection: [GlucoseEffect]
public var momentum: [GlucoseEffect]
public var insulinCounteraction: [GlucoseEffectVelocity]
public var retrospectiveGlucoseDiscrepancies: [GlucoseChange]
public var totalRetrospectiveCorrectionEffect: LoopQuantity?
public init(
insulin: [GlucoseEffect],
carbs: [GlucoseEffect],
carbStatus: [CarbStatus<CarbStatusType>],
retrospectiveCorrection: [GlucoseEffect],
momentum: [GlucoseEffect],
insulinCounteraction: [GlucoseEffectVelocity],
retrospectiveGlucoseDiscrepancies: [GlucoseChange],
totalRetrospectiveCorrectionEffect: LoopQuantity? = nil
) {
self.insulin = insulin
self.carbs = carbs
self.carbStatus = carbStatus
self.retrospectiveCorrection = retrospectiveCorrection
self.momentum = momentum
self.insulinCounteraction = insulinCounteraction
self.retrospectiveGlucoseDiscrepancies = retrospectiveGlucoseDiscrepancies
self.totalRetrospectiveCorrectionEffect = totalRetrospectiveCorrectionEffect
}
}
extension LoopAlgorithmEffects<FixtureCarbEntry>: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.insulin = try container.decode([GlucoseEffect].self, forKey: .insulin)
self.carbs = try container.decode([GlucoseEffect].self, forKey: .carbs)
self.carbStatus = try container.decode([CarbStatus<FixtureCarbEntry>].self, forKey: .carbStatus)
self.retrospectiveCorrection = try container.decode([GlucoseEffect].self, forKey: .retrospectiveCorrection)
self.momentum = try container.decode([GlucoseEffect].self, forKey: .momentum)
self.insulinCounteraction = try container.decode([GlucoseEffectVelocity].self, forKey: .insulinCounteraction)
self.retrospectiveGlucoseDiscrepancies = try container.decode([GlucoseChange].self, forKey: .retrospectiveGlucoseDiscrepancies)
if let totalRetrospectiveCorrectionEffectValue = try container.decodeIfPresent(Double.self, forKey: .totalRetrospectiveCorrectionEffect) {
self.totalRetrospectiveCorrectionEffect = LoopQuantity(
unit: .milligramsPerDeciliter,
doubleValue: totalRetrospectiveCorrectionEffectValue
)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(insulin, forKey: .insulin)
try container.encode(carbs, forKey: .carbs)
try container.encode(carbStatus, forKey: .carbStatus)
try container.encode(retrospectiveCorrection, forKey: .retrospectiveCorrection)
try container.encode(momentum, forKey: .momentum)
try container.encode(insulinCounteraction, forKey: .insulinCounteraction)
try container.encode(retrospectiveGlucoseDiscrepancies, forKey: .retrospectiveGlucoseDiscrepancies)
if let totalRetrospectiveCorrectionEffect {
try container.encode(
totalRetrospectiveCorrectionEffect.doubleValue(for: .milligramsPerDeciliter),
forKey: .totalRetrospectiveCorrectionEffect
)
}
}
private enum CodingKeys: String, CodingKey {
case insulin
case carbs
case carbStatus
case retrospectiveCorrection
case momentum
case insulinCounteraction
case retrospectiveGlucoseDiscrepancies
case totalRetrospectiveCorrectionEffect
}
}
public struct AlgorithmEffectsOptions: OptionSet, Sendable {
public let rawValue: UInt8
public static let carbs = AlgorithmEffectsOptions(rawValue: 1 << 0)
public static let insulin = AlgorithmEffectsOptions(rawValue: 1 << 1)
public static let momentum = AlgorithmEffectsOptions(rawValue: 1 << 2)
public static let retrospection = AlgorithmEffectsOptions(rawValue: 1 << 3)
public static let all: AlgorithmEffectsOptions = [.carbs, .insulin, .momentum, .retrospection]
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
}
public struct LoopPrediction<CarbStatusType: CarbEntry> {
public var glucose: [PredictedGlucoseValue]
public var effects: LoopAlgorithmEffects<CarbStatusType>
public var dosesRelativeToBasal: [BasalRelativeDose]
public var activeInsulin: Double?
public var activeCarbs: Double?
}
public struct LoopAlgorithm {
/// Percentage of recommended dose to apply as bolus when using automatic bolus dosing strategy
static public let defaultBolusPartialApplicationFactor = 0.4
/// The duration of recommended temp basals
static public let tempBasalDuration = TimeInterval(minutes: 30)
/// The amount of time since a given date that input data should be considered valid
public static let inputDataRecencyInterval = TimeInterval(minutes: 15)
/// Calculates the needed interval for insulin sensitivity to run the algorithm
/// - Parameters:
/// - doses: The active doses affecting the forecast
/// - glucoseHistoryStart: The start date of glucose history
/// - recommendationEffectInterval:The interval covering effects of a recommended dose
public static func timelineIntervalForSensitivity<DoseType: InsulinDose>(
doses: [DoseType],
glucoseHistoryStart: Date,
recommendationEffectInterval: DateInterval
) -> DateInterval {
return (doses.effectsInterval() ?? DateInterval(start: glucoseHistoryStart, end: glucoseHistoryStart))
.extendedToInclude(glucoseHistoryStart)
.extendedToInclude(recommendationEffectInterval)
.extendedForSimulation()
}
/// Generates a forecast predicting glucose.
/// Outputs may be incomplete, if there are issues with the provided data, but as many intermediate derived fields as can be computed, will be computed.
///
/// Returns nil if the normal scheduled basal, or active temporary basal, is sufficient.
///
///
/// - Parameters:
/// - start: The starting time of the glucose prediction.
/// - glucoseHistory: History of glucose values: t-10h to t. Must include at least one value.
/// - doses: History of insulin doses: t-16h to t
/// - carbEntries: History of carb entries: t-10h to t
/// - basal: Scheduled basal rate timeline: t-16h to t
/// - sensitivity: Insulin sensitivity timeline: t-16h to t (eventually with mid-absorption isf changes, it will be t-10h to t)
/// - carbRatio: Carb ratio timeline: t-10h to t+6h
/// - algorithmEffectsOptions: Which effects to include when combining effects to generate glucose prediction
/// - useIntegralRetrospectiveCorrection: If true, the prediction will use Integral Retrospection. If false, will use traditional Retrospective Correction
/// - includingPositiveVelocityAndRC: If false, only net negative momentum and RC effects will used.
/// - carbAbsorptionModel: A model conforming to CarbAbsorptionComputable that is used for computing carb absorption over time.
/// - Returns: A LoopPrediction struct containing the predicted glucose and the computed intermediate effects used to make the prediction
public static func generatePrediction<CarbType, GlucoseType, InsulinDoseType>(
start: Date,
glucoseHistory: [GlucoseType],
doses: [InsulinDoseType],
carbEntries: [CarbType],
basal: [AbsoluteScheduleValue<Double>],
sensitivity: [AbsoluteScheduleValue<LoopQuantity>],
carbRatio: [AbsoluteScheduleValue<Double>],
algorithmEffectsOptions: AlgorithmEffectsOptions = .all,
useIntegralRetrospectiveCorrection: Bool = false,
includingPositiveVelocityAndRC: Bool = true,
useMidAbsorptionISF: Bool = false,
carbAbsorptionModel: CarbAbsorptionComputable = PiecewiseLinearAbsorption(),
gradualTransitionsThreshold: Double? = 40.0,
momentumVelocityMaximum: LoopQuantity? = nil
) -> LoopPrediction<CarbType> where CarbType: CarbEntry, GlucoseType: GlucoseSampleValue, InsulinDoseType: InsulinDose {
var prediction: [PredictedGlucoseValue] = []
var insulinEffects: [GlucoseEffect] = []
var carbEffects: [GlucoseEffect] = []
var retrospectiveCorrectionEffects: [GlucoseEffect] = []
var momentumEffects: [GlucoseEffect] = []
var insulinCounteractionEffects: [GlucoseEffectVelocity] = []
var retrospectiveGlucoseDiscrepanciesSummed: [GlucoseChange] = []
var totalRetrospectiveCorrectionEffect: LoopQuantity?
var activeInsulin: Double?
var activeCarbs: Double?
//var carbStatus: [CarbStatus] = []
var dosesRelativeToBasal: [BasalRelativeDose] = []
// Ensure basal history covers doses
let doseStart = doses.first?.startDate ?? start
if !basal.isEmpty, basal.first!.startDate <= doseStart {
// Overlay basal history on basal doses, splitting doses to get amount delivered relative to basal
dosesRelativeToBasal = doses.annotated(with: basal)
activeInsulin = dosesRelativeToBasal.insulinOnBoard(at: start)
var insulinEffectsInterval = dosesRelativeToBasal.effectsInterval() ?? DateInterval(start: start, end: start)
// Extend range of insulin effects to cover glucose, if needed
if let glucoseStart = glucoseHistory.first?.startDate, glucoseStart < insulinEffectsInterval.start {
insulinEffectsInterval = insulinEffectsInterval.extendedToInclude(glucoseStart)
}
if let glucoseEnd = glucoseHistory.last?.endDate, glucoseEnd > insulinEffectsInterval.end {
insulinEffectsInterval = insulinEffectsInterval.extendedToInclude(glucoseEnd)
}
if useMidAbsorptionISF {
insulinEffects = dosesRelativeToBasal.glucoseEffectsMidAbsorptionISF(
insulinSensitivityHistory: sensitivity,
from: insulinEffectsInterval.start,
to: insulinEffectsInterval.end)
} else {
insulinEffects = dosesRelativeToBasal.glucoseEffects(
insulinSensitivityHistory: sensitivity,
from: insulinEffectsInterval.start,
to: insulinEffectsInterval.end)
}
// ICE
insulinCounteractionEffects = glucoseHistory.counteractionEffects(to: insulinEffects)
} else {
activeInsulin = 0
}
// Carb Effects
let carbStatus = carbEntries.map(
to: insulinCounteractionEffects,
carbRatio: carbRatio,
insulinSensitivity: sensitivity
)
carbEffects = carbStatus.dynamicGlucoseEffects(
from: start.addingTimeInterval(-IntegralRetrospectiveCorrection.retrospectionInterval),
carbRatios: carbRatio,
insulinSensitivities: sensitivity,
absorptionModel: carbAbsorptionModel
)
activeCarbs = carbStatus.dynamicCarbsOnBoard(at: start, absorptionModel: carbAbsorptionModel)
// RC
let retrospectiveGlucoseDiscrepancies = insulinCounteractionEffects.subtracting(carbEffects)
retrospectiveGlucoseDiscrepanciesSummed = retrospectiveGlucoseDiscrepancies.combinedSums(of: LoopMath.retrospectiveCorrectionGroupingInterval * 1.01)
let rc: RetrospectiveCorrection
if useIntegralRetrospectiveCorrection {
rc = IntegralRetrospectiveCorrection(effectDuration: LoopMath.retrospectiveCorrectionEffectDuration)
} else {
rc = StandardRetrospectiveCorrection(effectDuration: LoopMath.retrospectiveCorrectionEffectDuration)
}
if let latestGlucose = glucoseHistory.last {
retrospectiveCorrectionEffects = rc.computeEffect(
startingAt: latestGlucose,
retrospectiveGlucoseDiscrepanciesSummed: retrospectiveGlucoseDiscrepanciesSummed,
recencyInterval: TimeInterval(minutes: 15),
retrospectiveCorrectionGroupingInterval: LoopMath.retrospectiveCorrectionGroupingInterval
)
totalRetrospectiveCorrectionEffect = rc.totalGlucoseCorrectionEffect
var effects = [[GlucoseEffect]]()
if algorithmEffectsOptions.contains(.carbs) {
effects.append(carbEffects)
}
if algorithmEffectsOptions.contains(.insulin) {
effects.append(insulinEffects)
}
if algorithmEffectsOptions.contains(.retrospection) {
// Check if glucose data is smooth enough for RC
// Use the same input window as retrospective correction
var useRC: Bool = true
// Don't apply RC if glucose has large jumps
let rcTransitionData = glucoseHistory.filterDateRange(
start.addingTimeInterval(-LoopMath.retrospectiveCorrectionGroupingInterval),
start
)
if !rcTransitionData.hasGradualTransitions(gradualTransitionThreshold: gradualTransitionsThreshold ?? 40.0) {
useRC = false
}
// Don't apply positive RC if that setting is disabled
if !includingPositiveVelocityAndRC,
let netRC = retrospectiveCorrectionEffects.netEffect(),
netRC.quantity.doubleValue(for: .milligramsPerDeciliter) > 0 {
useRC = false
}
if useRC {
effects.append(retrospectiveCorrectionEffects)
}
}
// Glucose Momentum
var useMomentum: Bool = true
if algorithmEffectsOptions.contains(.momentum) {
let momentumInputData = glucoseHistory.filterDateRange(start.addingTimeInterval(-GlucoseMath.momentumDataInterval), start)
momentumEffects = momentumInputData.linearMomentumEffect(velocityMaximum: momentumVelocityMaximum)
if !includingPositiveVelocityAndRC, let netMomentum = momentumEffects.netEffect(), netMomentum.quantity.doubleValue(for: .milligramsPerDeciliter) > 0 {
// positive momentum is turned off
useMomentum = false
}
} else {
useMomentum = false
}
prediction = LoopMath.predictGlucose(
startingAt: latestGlucose,
momentum: useMomentum ? momentumEffects : [],
effects: effects
)
// Dosing requires prediction entries at least as long as the insulin model duration.
// If our prediction is shorter than that, then extend it here.
let finalDate = start.addingTimeInterval(InsulinMath.defaultInsulinActivityDuration)
if let last = prediction.last, last.startDate < finalDate {
prediction.append(PredictedGlucoseValue(startDate: finalDate, quantity: last.quantity))
}
}
return LoopPrediction(
glucose: prediction,
effects: LoopAlgorithmEffects(
insulin: insulinEffects,
carbs: carbEffects,
carbStatus: carbStatus,
retrospectiveCorrection: retrospectiveCorrectionEffects,
momentum: momentumEffects,
insulinCounteraction: insulinCounteractionEffects,
retrospectiveGlucoseDiscrepancies: retrospectiveGlucoseDiscrepanciesSummed,
totalRetrospectiveCorrectionEffect: totalRetrospectiveCorrectionEffect
),
dosesRelativeToBasal: dosesRelativeToBasal,
activeInsulin: activeInsulin,
activeCarbs: activeCarbs
)
}
/// Generates a forecast using pre-annotated insulin data.
///
/// This overload is optimised for multi-step historical sweeps where the
/// same dose history is evaluated at many consecutive time points. By
/// accepting a `PrecomputedInsulinInput` the caller can:
///
/// 1. **Skip `annotated(with: basal)`** — the most expensive per-step
/// operation (~O(doses × basalSegments)). Annotate the full window
/// once with `PrecomputedInsulinInput.build(...)`, then slice
/// `annotatedDoses` to the lookback window for each call.
///
/// 2. **Skip `glucoseEffects(...)`** — when `precomputedInsulin.insulinEffects`
/// is non-nil the function clips the pre-built effect timeline to the
/// needed range instead of recomputing from scratch. This is only
/// valid when ISF does not change between steps (i.e. you are NOT
/// sweeping ISF multipliers).
///
/// All other effects (carbs, RC, momentum) are computed normally.
///
/// - Parameters:
/// - start: The starting time of the glucose prediction.
/// - glucoseHistory: History of glucose values: t-10h to t.
/// - precomputedInsulin: Pre-annotated dose data for this step. Caller
/// must slice `annotatedDoses` to `[t - insulinLookback, t]` (or
/// `[t - lookback, t + 6h]` for future-insulin mode).
/// - carbEntries: History of carb entries.
/// - sensitivity: ISF timeline — still required for carb + RC effects.
/// - carbRatio: Carb ratio timeline.
/// - algorithmEffectsOptions: Which effects to include.
/// - useIntegralRetrospectiveCorrection: Use integral RC.
/// - includingPositiveVelocityAndRC: Include positive velocity/RC.
/// - useMidAbsorptionISF: Use mid-absorption ISF (ignored when
/// `precomputedInsulin.insulinEffects` is non-nil).
/// - carbAbsorptionModel: Carb absorption model.
/// - gradualTransitionsThreshold: RC smoothness gate (default 40 mg/dL).
/// - Returns: A `LoopPrediction` struct. `dosesRelativeToBasal` is
/// populated from `precomputedInsulin.annotatedDoses`.
public static func generatePrediction<CarbType, GlucoseType>(
start: Date,
glucoseHistory: [GlucoseType],
precomputedInsulin: PrecomputedInsulinInput,
carbEntries: [CarbType],
sensitivity: [AbsoluteScheduleValue<LoopQuantity>],
carbRatio: [AbsoluteScheduleValue<Double>],
algorithmEffectsOptions: AlgorithmEffectsOptions = .all,
useIntegralRetrospectiveCorrection: Bool = false,
includingPositiveVelocityAndRC: Bool = true,
useMidAbsorptionISF: Bool = false,
carbAbsorptionModel: CarbAbsorptionComputable = PiecewiseLinearAbsorption(),
gradualTransitionsThreshold: Double? = 40.0,
momentumVelocityMaximum: LoopQuantity? = nil
) -> LoopPrediction<CarbType> where CarbType: CarbEntry, GlucoseType: GlucoseSampleValue {
let dosesRelativeToBasal = precomputedInsulin.annotatedDoses
let activeInsulin = dosesRelativeToBasal.insulinOnBoard(at: start)
// ── Insulin effects ──────────────────────────────────────────────────────
// Fast path: clip the pre-computed effect timeline to the needed range.
// Slow path: compute from annotated doses (still faster than the full
// overload because annotation is already done).
let insulinEffects: [GlucoseEffect]
if let prebuilt = precomputedInsulin.insulinEffects {
// Use the pre-built effects directly. Extra entries (outside the
// needed range) are harmless; counteractionEffects() and
// predictGlucose() only consume entries within their required window.
// Pass the full array — callers should pre-build with a generous
// `effectsTo` covering the full sweep end + activity duration.
insulinEffects = prebuilt
} else {
var effectsInterval = dosesRelativeToBasal.effectsInterval() ?? DateInterval(start: start, end: start)
if let glucoseStart = glucoseHistory.first?.startDate, glucoseStart < effectsInterval.start {
effectsInterval = effectsInterval.extendedToInclude(glucoseStart)
}
if let glucoseEnd = glucoseHistory.last?.endDate, glucoseEnd > effectsInterval.end {
effectsInterval = effectsInterval.extendedToInclude(glucoseEnd)
}
if useMidAbsorptionISF {
insulinEffects = dosesRelativeToBasal.glucoseEffectsMidAbsorptionISF(
insulinSensitivityHistory: sensitivity,
from: effectsInterval.start,
to: effectsInterval.end
)
} else {
insulinEffects = dosesRelativeToBasal.glucoseEffects(
insulinSensitivityHistory: sensitivity,
from: effectsInterval.start,
to: effectsInterval.end
)
}
}
// ── ICE, carbs, RC, momentum — identical to the standard overload ────────
let insulinCounteractionEffects = glucoseHistory.counteractionEffects(to: insulinEffects)
let carbStatus = carbEntries.map(
to: insulinCounteractionEffects,
carbRatio: carbRatio,
insulinSensitivity: sensitivity
)
let carbEffects = carbStatus.dynamicGlucoseEffects(
from: start.addingTimeInterval(-IntegralRetrospectiveCorrection.retrospectionInterval),
carbRatios: carbRatio,
insulinSensitivities: sensitivity,
absorptionModel: carbAbsorptionModel
)
let activeCarbs = carbStatus.dynamicCarbsOnBoard(at: start, absorptionModel: carbAbsorptionModel)
let retrospectiveGlucoseDiscrepancies = insulinCounteractionEffects.subtracting(carbEffects)
let retrospectiveGlucoseDiscrepanciesSummed = retrospectiveGlucoseDiscrepancies
.combinedSums(of: LoopMath.retrospectiveCorrectionGroupingInterval * 1.01)
let rc: RetrospectiveCorrection = useIntegralRetrospectiveCorrection
? IntegralRetrospectiveCorrection(effectDuration: LoopMath.retrospectiveCorrectionEffectDuration)
: StandardRetrospectiveCorrection(effectDuration: LoopMath.retrospectiveCorrectionEffectDuration)
var prediction: [PredictedGlucoseValue] = []
var retrospectiveCorrectionEffects: [GlucoseEffect] = []
var momentumEffects: [GlucoseEffect] = []
var totalRetrospectiveCorrectionEffect: LoopQuantity?
if let latestGlucose = glucoseHistory.last {
retrospectiveCorrectionEffects = rc.computeEffect(
startingAt: latestGlucose,
retrospectiveGlucoseDiscrepanciesSummed: retrospectiveGlucoseDiscrepanciesSummed,
recencyInterval: TimeInterval(minutes: 15),
retrospectiveCorrectionGroupingInterval: LoopMath.retrospectiveCorrectionGroupingInterval
)
totalRetrospectiveCorrectionEffect = rc.totalGlucoseCorrectionEffect
var effects = [[GlucoseEffect]]()
if algorithmEffectsOptions.contains(.carbs) { effects.append(carbEffects) }
if algorithmEffectsOptions.contains(.insulin) { effects.append(insulinEffects) }
if algorithmEffectsOptions.contains(.retrospection) {
var useRC = true
let rcTransitionData = glucoseHistory.filterDateRange(
start.addingTimeInterval(-LoopMath.retrospectiveCorrectionGroupingInterval),
start
)
if !rcTransitionData.hasGradualTransitions(gradualTransitionThreshold: gradualTransitionsThreshold ?? 40.0) {
useRC = false
}
if !includingPositiveVelocityAndRC,
let netRC = retrospectiveCorrectionEffects.netEffect(),
netRC.quantity.doubleValue(for: .milligramsPerDeciliter) > 0 {
useRC = false
}
if useRC { effects.append(retrospectiveCorrectionEffects) }
}
var useMomentum = true
if algorithmEffectsOptions.contains(.momentum) {
let momentumInputData = glucoseHistory.filterDateRange(
start.addingTimeInterval(-GlucoseMath.momentumDataInterval), start
)
momentumEffects = momentumInputData.linearMomentumEffect(velocityMaximum: momentumVelocityMaximum)
if !includingPositiveVelocityAndRC,
let netMomentum = momentumEffects.netEffect(),
netMomentum.quantity.doubleValue(for: .milligramsPerDeciliter) > 0 {
useMomentum = false
}
} else {
useMomentum = false
}
prediction = LoopMath.predictGlucose(
startingAt: latestGlucose,
momentum: useMomentum ? momentumEffects : [],
effects: effects
)
let finalDate = start.addingTimeInterval(InsulinMath.defaultInsulinActivityDuration)
if let last = prediction.last, last.startDate < finalDate {
prediction.append(PredictedGlucoseValue(startDate: finalDate, quantity: last.quantity))
}
}
return LoopPrediction(
glucose: prediction,
effects: LoopAlgorithmEffects(
insulin: insulinEffects,
carbs: carbEffects,
carbStatus: carbStatus,
retrospectiveCorrection: retrospectiveCorrectionEffects,
momentum: momentumEffects,
insulinCounteraction: insulinCounteractionEffects,
retrospectiveGlucoseDiscrepancies: retrospectiveGlucoseDiscrepanciesSummed,
totalRetrospectiveCorrectionEffect: totalRetrospectiveCorrectionEffect
),
dosesRelativeToBasal: dosesRelativeToBasal,
activeInsulin: activeInsulin,
activeCarbs: activeCarbs
)
}
// Helper to generate prediction with LoopPredictionInput struct
public static func generatePrediction<CarbType, GlucoseType, InsulinDoseType>(input: LoopPredictionInput<CarbType, GlucoseType, InsulinDoseType>) -> LoopPrediction<CarbType> {
return generatePrediction(
start: input.glucoseHistory.last?.startDate ?? Date(),
glucoseHistory: input.glucoseHistory,
doses: input.doses,
carbEntries: input.carbEntries,
basal: input.basal,
sensitivity: input.sensitivity,
carbRatio: input.carbRatio,
algorithmEffectsOptions: input.algorithmEffectsOptions,
useIntegralRetrospectiveCorrection: input.useIntegralRetrospectiveCorrection,
carbAbsorptionModel: input.carbAbsorptionModel.model,
gradualTransitionsThreshold: input.gradualTransitionsThreshold
)
}
// Computes an amount of insulin to correct the given prediction
public static func insulinCorrection(
prediction: [PredictedGlucoseValue],
at deliveryDate: Date,
target: GlucoseRangeTimeline,
suspendThreshold: LoopQuantity,
sensitivity: [AbsoluteScheduleValue<LoopQuantity>],
insulinModel: InsulinModel
) -> InsulinCorrection {
return prediction.insulinCorrection(
to: target,
at: deliveryDate,
suspendThreshold: suspendThreshold,
insulinSensitivity: sensitivity,
model: insulinModel)
}
// Computes a 30 minute temp basal dose to correct the given prediction
public static func recommendTempBasal(
for correction: InsulinCorrection,
neutralBasalRate: Double,
activeInsulin: Double,
maxBolus: Double,
maxBasalRate: Double,
maxActiveInsulin: Double
) -> TempBasalRecommendation {
var maxBasalRate = maxBasalRate
// TODO: Allow `highBasalThreshold` to be a configurable setting
if case .aboveRange(min: let min, correcting: _, minTarget: let highBasalThreshold, units: _) = correction,
min.quantity < highBasalThreshold
{
maxBasalRate = neutralBasalRate
}
// Enforce max active insulin
let activeInsulinHeadroom = maxActiveInsulin - activeInsulin
let maxThirtyMinuteRateToKeepActiveInsulinBelowLimit = activeInsulinHeadroom * (TimeInterval.hours(1) / tempBasalDuration) + neutralBasalRate // 30 minutes of a U/hr rate
maxBasalRate = Swift.min(maxThirtyMinuteRateToKeepActiveInsulinBelowLimit, maxBasalRate)
return correction.asTempBasal(
neutralBasalRate: neutralBasalRate,
maxBasalRate: maxBasalRate,
duration: tempBasalDuration
)
}
// Computes a bolus or low-temp basal dose to correct the given prediction
public static func recommendAutomaticDose(
for correction: InsulinCorrection,
applicationFactor: Double,
neutralBasalRate: Double,
activeInsulin: Double,
maxBolus: Double,
maxBasalRate: Double,
maxActiveInsulin: Double
) -> AutomaticDoseRecommendation {
let deliveryHeadroom = max(0, maxActiveInsulin - activeInsulin)
var deliveryMax = min(maxBolus * applicationFactor, deliveryHeadroom)
if case .aboveRange(min: let min, correcting: _, minTarget: let minTarget, units: _) = correction,
min.quantity < minTarget
{
deliveryMax = 0
}
let temp: TempBasalRecommendation = correction.asTempBasal(
neutralBasalRate: neutralBasalRate,
maxBasalRate: neutralBasalRate,
duration: .minutes(30)
)
let bolusUnits = correction.asPartialBolus(
partialApplicationFactor: applicationFactor,
maxBolusUnits: deliveryMax
)
return AutomaticDoseRecommendation(basalAdjustment: temp, direction: .from(correction: correction), bolusUnits: bolusUnits)
}
// Computes a manual bolus to correct the given prediction
public static func recommendManualBolus(
for correction: InsulinCorrection,
maxBolus: Double,
currentGlucose: GlucoseSampleValue,
target: GlucoseRangeTimeline
) -> ManualBolusRecommendation {
var bolus = correction.asManualBolus(maxBolus: maxBolus)
if let targetAtCurrentGlucose = target.closestPrior(to: currentGlucose.startDate),
currentGlucose.quantity < targetAtCurrentGlucose.value.lowerBound
{
bolus.notice = .currentGlucoseBelowTarget(glucose: SimpleGlucoseValue(currentGlucose))
}
return bolus
}
public static func run<LoopAlgorithmInputType: AlgorithmInput>(input: LoopAlgorithmInputType) -> AlgorithmOutput<LoopAlgorithmInputType.CarbType> {
var prediction = LoopPrediction(
glucose: [],
effects: LoopAlgorithmEffects(
insulin: [],
carbs: [],
carbStatus: [CarbStatus<LoopAlgorithmInputType.CarbType>](),
retrospectiveCorrection: [],
momentum: [],
insulinCounteraction: [],
retrospectiveGlucoseDiscrepancies: []
),
dosesRelativeToBasal: []
)
// Now validate/recommend
let result: Result<LoopAlgorithmDoseRecommendation,Error>
do {
guard let latestGlucose = input.glucoseHistory.last else {
throw AlgorithmError.missingGlucose
}
guard input.predictionStart.timeIntervalSince(latestGlucose.startDate) < inputDataRecencyInterval else {
throw AlgorithmError.glucoseTooOld
}
// When running the algorithm for automated dosing, future basal should not be included
if let basalEnd = input.doses.filter({ $0.deliveryType == .basal }).map({ $0.endDate }).max() {
guard !input.recommendationType.automated || basalEnd <= input.predictionStart else {
throw AlgorithmError.futureBasalNotAllowed
}
}
let forecastEnd = input.predictionStart.addingTimeInterval(input.recommendationInsulinModel.effectDuration).dateCeiledToTimeInterval(GlucoseMath.defaultDelta)
let glucoseStart = input.glucoseHistory.first?.startDate ?? input.predictionStart
// Make sure ISF covers needed timeline
let recommendationEffectInterval = DateInterval(
start: input.predictionStart,
duration: input.recommendationInsulinModel.effectDuration)
let neededISFInterval = timelineIntervalForSensitivity(
doses: input.doses,
glucoseHistoryStart: glucoseStart,
recommendationEffectInterval: recommendationEffectInterval
)
guard let sensitivityStartDate = input.sensitivity.first?.startDate, sensitivityStartDate <= neededISFInterval.start else {
throw AlgorithmError.sensitivityTimelineStartsTooLate
}
guard let sensitivityEndDate = input.sensitivity.last?.endDate, sensitivityEndDate >= neededISFInterval.end else {
throw AlgorithmError.sensitivityTimelineEndsTooEarly
}
// Make sure Basal covers needed timeline
guard let scheduledBasalRate = input.basal.closestPrior(to: input.predictionStart)?.value else {
throw AlgorithmError.basalTimelineIncomplete
}
guard let suspendThreshold = input.suspendThreshold ?? input.target.closestPrior(to: input.predictionStart)?.value.lowerBound else {
throw AlgorithmError.missingSuspendThreshold
}
prediction = generatePrediction(
start: input.predictionStart,
glucoseHistory: input.glucoseHistory,
doses: input.doses,
carbEntries: input.carbEntries,
basal: input.basal,
sensitivity: input.sensitivity,
carbRatio: input.carbRatio,
algorithmEffectsOptions: .all,
useIntegralRetrospectiveCorrection: input.useIntegralRetrospectiveCorrection,
includingPositiveVelocityAndRC: input.includePositiveVelocityAndRC,
useMidAbsorptionISF: input.useMidAbsorptionISF,
carbAbsorptionModel: input.carbAbsorptionModel.model,
gradualTransitionsThreshold: input.gradualTransitionsThreshold
)
let sensitivityForDosing: [AbsoluteScheduleValue<LoopQuantity>]
if input.useMidAbsorptionISF {
sensitivityForDosing = input.sensitivity
} else {
// This sets a single ISF value for the duration of the dose.
let sensitivityEnd = max(forecastEnd, prediction.effects.insulin.last?.startDate ?? .distantPast)
let sensitivityAtPredictionStart = input.sensitivity.first { $0.startDate <= input.predictionStart && $0.endDate >= input.predictionStart }!
let sensitivityOverPrediction = AbsoluteScheduleValue(
startDate: sensitivityAtPredictionStart.startDate,
endDate: sensitivityEnd,
value: sensitivityAtPredictionStart.value
)
sensitivityForDosing = [sensitivityOverPrediction]
}
let correction = insulinCorrection(
prediction: prediction.glucose,
at: input.predictionStart,
target: input.target,
suspendThreshold: suspendThreshold,
sensitivity: sensitivityForDosing,
insulinModel: input.recommendationInsulinModel)
let maxActiveInsulin = input.maxBolus * (input.maxActiveInsulinMultiplier ?? 2)
switch input.recommendationType {
case .manualBolus:
let recommendation = recommendManualBolus(
for: correction,
maxBolus: input.maxBolus,
currentGlucose: latestGlucose,
target: input.target)
result = .success(.init(manual: recommendation))
case .automaticBolus:
let recommendation = recommendAutomaticDose(
for: correction,
applicationFactor: input.automaticBolusApplicationFactor ?? defaultBolusPartialApplicationFactor,
neutralBasalRate: scheduledBasalRate,
activeInsulin: prediction.activeInsulin!,
maxBolus: input.maxBolus,
maxBasalRate: input.maxBasalRate,
maxActiveInsulin: maxActiveInsulin)
result = .success(.init(automatic: recommendation))
case .tempBasal:
let recommendation = recommendTempBasal(
for: correction,
neutralBasalRate: scheduledBasalRate,
activeInsulin: prediction.activeInsulin!,
maxBolus: input.maxBolus,
maxBasalRate: input.maxBasalRate,
maxActiveInsulin: maxActiveInsulin)
result = .success(.init(automatic: AutomaticDoseRecommendation(basalAdjustment: recommendation, direction: .from(correction: correction))))
}
} catch {
result = .failure(error)
}
return AlgorithmOutput(
recommendationResult: result,
predictedGlucose: prediction.glucose,
effects: prediction.effects,
dosesRelativeToBasal: prediction.dosesRelativeToBasal,
activeInsulin: prediction.activeInsulin,
activeCarbs: prediction.activeCarbs
)
}
}