forked from LoopKit/LoopAlgorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCarbMath.swift
More file actions
792 lines (668 loc) · 34.3 KB
/
Copy pathCarbMath.swift
File metadata and controls
792 lines (668 loc) · 34.3 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
//
// CarbMath.swift
// CarbKit
//
// Created by Nathan Racklyeft on 1/16/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
public struct CarbMath {
public static let maximumAbsorptionTimeInterval: TimeInterval = .hours(10)
public static let defaultAbsorptionTime: TimeInterval = .hours(3)
public static let defaultAbsorptionTimeOverrun: Double = 1.5
public static let defaultEffectDelay: TimeInterval = .minutes(10)
}
public enum CarbAbsorptionModel: String, Codable {
case linear = "linear"
case piecewiseLinear = "piecewiseLinear"
public var model: CarbAbsorptionComputable {
switch self {
case .linear:
return LinearAbsorption()
case .piecewiseLinear:
return PiecewiseLinearAbsorption()
}
}
}
public protocol CarbAbsorptionComputable {
/// Returns the percentage of total carbohydrates absorbed as blood glucose at a specified interval after eating.
///
/// - Parameters:
/// - percentTime: The percentage of the total absorption time
/// - Returns: The percentage of the total carbohydrates that have been absorbed as blood glucose
func percentAbsorptionAtPercentTime(_ percentTime: Double) -> Double
/// Returns the percent of total absorption time for a percentage of total carbohydrates absorbed
///
/// The is the inverse of perecentAbsorptionAtPercentTime( :percentTime: )
///
/// - Parameters:
/// - percentAbsorption: The percentage of the total carbohydrates that have been absorbed as blood glucose
/// - Returns: The percentage of the absorption time needed to absorb the percentage of the total carbohydrates
func percentTimeAtPercentAbsorption(_ percentAbsorption: Double) -> Double
/// Returns the total absorption time for a percentage of total carbohydrates absorbed as blood glucose at a specified interval after eating.
///
/// - Parameters:
/// - percentAbsorption: The percentage of the total carbohydrates that have been absorbed as blood glucose
/// - time: The interval after the carbohydrates were eaten
/// - Returns: The total time of carbohydrates absorption
func absorptionTime(forPercentAbsorption percentAbsorption: Double, atTime time: TimeInterval) -> TimeInterval
/// Returns the number of total carbohydrates absorbed as blood glucose at a specified interval after eating
///
/// - Parameters:
/// - total: The total number of carbohydrates eaten
/// - time: The interval after carbohydrates were eaten
/// - absorptionTime: The total time of carbohydrates absorption
/// - Returns: The number of total carbohydrates that have been absorbed as blood glucose
func absorbedCarbs(of total: Double, atTime time: TimeInterval, absorptionTime: TimeInterval) -> Double
/// Returns the number of total carbohydrates not yet absorbed as blood glucose at a specified interval after eating
///
/// - Parameters:
/// - total: The total number of carbs eaten
/// - time: The interval after carbohydrates were eaten
/// - absorptionTime: The total time of carb absorption
/// - Returns: The number of total carbohydrates that have not yet been absorbed as blood glucose
func unabsorbedCarbs(of total: Double, atTime time: TimeInterval, absorptionTime: TimeInterval) -> Double
/// Returns the normalized rate of carbohydrates absorption at a specified percentage of the absorption time
///
/// - Parameters:
/// - percentTime: The percentage of absorption time elapsed since the carbohydrates were eaten
/// - Returns: The percentage absorption rate at the percentage of absorption time
func percentRateAtPercentTime(_ percentTime: Double) -> Double
}
extension CarbAbsorptionComputable {
public func absorbedCarbs(of total: Double, atTime time: TimeInterval, absorptionTime: TimeInterval) -> Double {
let percentTime = time / absorptionTime
return total * percentAbsorptionAtPercentTime(percentTime)
}
public func unabsorbedCarbs(of total: Double, atTime time: TimeInterval, absorptionTime: TimeInterval) -> Double {
let percentTime = time / absorptionTime
return total * (1.0 - percentAbsorptionAtPercentTime(percentTime))
}
public func absorptionTime(forPercentAbsorption percentAbsorption: Double, atTime time: TimeInterval) -> TimeInterval {
let percentTime = max(percentTimeAtPercentAbsorption(percentAbsorption), .ulpOfOne)
return time / percentTime
}
func timeToAbsorb(forPercentAbsorbed percentAbsorption: Double, totalAbsorptionTime: TimeInterval) -> TimeInterval {
let percentTime = percentTimeAtPercentAbsorption(percentAbsorption)
return percentTime * totalAbsorptionTime
}
}
// MARK: - Linear absorption as a factor of reported duration
struct LinearAbsorption: CarbAbsorptionComputable {
func percentAbsorptionAtPercentTime(_ percentTime: Double) -> Double {
switch percentTime {
case let t where t <= 0.0:
return 0.0
case let t where t < 1.0:
return t
default:
return 1.0
}
}
func percentTimeAtPercentAbsorption(_ percentAbsorption: Double) -> Double {
switch percentAbsorption {
case let a where a <= 0.0:
return 0.0
case let a where a < 1.0:
return a
default:
return 1.0
}
}
func percentRateAtPercentTime(_ percentTime: Double) -> Double {
switch percentTime {
case let t where t > 0.0 && t <= 1.0:
return 1.0
default:
return 0.0
}
}
}
// MARK: - Piecewise linear absorption as a factor of reported duration
/// Nonlinear carb absorption model where absorption rate increases linearly from zero to a maximum value at a fraction of absorption time equal to percentEndOfRise, then remains constant until a fraction of absorption time equal to percentStartOfFall, and then decreases linearly to zero at the end of absorption time
/// - Parameters:
/// - percentEndOfRise: the percentage of absorption time when absorption rate reaches maximum, must be strictly between 0 and 1
/// - percentStartOfFall: the percentage of absorption time when absorption rate starts to decay, must be stritctly between 0 and 1 and greater than percentEndOfRise
public struct PiecewiseLinearAbsorption: CarbAbsorptionComputable {
let percentEndOfRise = 0.15
let percentStartOfFall = 0.5
var scale: Double {
return 2.0 / (1.0 + percentStartOfFall - percentEndOfRise)
}
public init() { }
public func percentAbsorptionAtPercentTime(_ percentTime: Double) -> Double {
switch percentTime {
case let t where t <= 0.0:
return 0.0
case let t where t < percentEndOfRise:
return 0.5 * scale * pow(t, 2.0) / percentEndOfRise
case let t where t >= percentEndOfRise && t < percentStartOfFall:
return scale * (t - 0.5 * percentEndOfRise)
case let t where t >= percentStartOfFall && t < 1.0:
return scale * (percentStartOfFall - 0.5 * percentEndOfRise +
(t - percentStartOfFall) * (1.0 - 0.5 * (t - percentStartOfFall) / (1.0 - percentStartOfFall)))
default:
return 1.0
}
}
public func percentTimeAtPercentAbsorption(_ percentAbsorption: Double) -> Double {
switch percentAbsorption {
case let a where a <= 0:
return 0.0
case let a where a > 0.0 && a < 0.5 * scale * percentEndOfRise:
return sqrt(2.0 * percentEndOfRise * a / scale)
case let a where a >= 0.5 * scale * percentEndOfRise && a < scale * (percentStartOfFall - 0.5 * percentEndOfRise):
return 0.5 * percentEndOfRise + a / scale
case let a where a >= scale * (percentStartOfFall - 0.5 * percentEndOfRise) && a < 1.0:
return 1.0 - sqrt((1.0 - percentStartOfFall) *
(1.0 + percentStartOfFall - percentEndOfRise) * (1.0 - a))
default:
return 1.0
}
}
public func percentRateAtPercentTime(_ percentTime: Double) -> Double {
switch percentTime {
case let t where t > 0 && t < percentEndOfRise:
return scale * t / percentEndOfRise
case let t where t >= percentEndOfRise && t < percentStartOfFall:
return scale
case let t where t >= percentStartOfFall && t < 1.0:
return scale * ((1.0 - t) / (1.0 - percentStartOfFall))
default:
return 0.0
}
}
}
extension CarbEntry {
public func carbsOnBoard(at date: Date, defaultAbsorptionTime: TimeInterval, delay: TimeInterval, absorptionModel: CarbAbsorptionComputable) -> Double {
let time = date.timeIntervalSince(startDate)
let value: Double
if time >= 0 {
value = absorptionModel.unabsorbedCarbs(of: quantity.doubleValue(for: LoopUnit.gram), atTime: time - delay, absorptionTime: absorptionTime ?? defaultAbsorptionTime)
} else {
value = 0
}
return value
}
// g
public func absorbedCarbs(
at date: Date,
absorptionTime: TimeInterval,
delay: TimeInterval,
absorptionModel: CarbAbsorptionComputable
) -> Double {
let time = date.timeIntervalSince(startDate)
return absorptionModel.absorbedCarbs(
of: quantity.doubleValue(for: .gram),
atTime: time - delay,
absorptionTime: absorptionTime
)
}
// mg/dL / g * g
fileprivate func glucoseEffect(
at date: Date,
carbRatio: LoopQuantity,
insulinSensitivity: LoopQuantity,
defaultAbsorptionTime: TimeInterval,
delay: TimeInterval,
absorptionModel: CarbAbsorptionComputable
) -> Double {
return insulinSensitivity.doubleValue(for: LoopUnit.milligramsPerDeciliter) / carbRatio.doubleValue(for: .gram) * absorbedCarbs(at: date, absorptionTime: absorptionTime ?? defaultAbsorptionTime, delay: delay, absorptionModel: absorptionModel)
}
}
extension Collection where Element: CarbEntry {
fileprivate func simulationDateRange(
from start: Date? = nil,
to end: Date? = nil,
defaultAbsorptionTime: TimeInterval,
delay: TimeInterval,
delta: TimeInterval
) -> (start: Date, end: Date)? {
guard count > 0 else {
return nil
}
if let start = start, let end = end {
return (start: start.dateFlooredToTimeInterval(delta), end: end.dateCeiledToTimeInterval(delta))
} else {
var minDate = first!.startDate
var maxDate = minDate
for sample in self {
if sample.startDate < minDate {
minDate = sample.startDate
}
let endDate = sample.endDate.addingTimeInterval(sample.absorptionTime ?? defaultAbsorptionTime).addingTimeInterval(delay)
if endDate > maxDate {
maxDate = endDate
}
}
return (
start: (start ?? minDate).dateFlooredToTimeInterval(delta),
end: (end ?? maxDate).dateCeiledToTimeInterval(delta)
)
}
}
func carbsOnBoard(
from start: Date? = nil,
to end: Date? = nil,
defaultAbsorptionTime: TimeInterval = CarbMath.defaultAbsorptionTime,
absorptionModel: CarbAbsorptionComputable,
delay: TimeInterval = CarbMath.defaultEffectDelay,
delta: TimeInterval = GlucoseMath.defaultDelta
) -> [CarbValue] {
guard let (startDate, endDate) = simulationDateRange(from: start, to: end, defaultAbsorptionTime: defaultAbsorptionTime, delay: delay, delta: delta) else {
return []
}
var date = startDate
var values = [CarbValue]()
repeat {
let value = reduce(0.0) { (value, entry) -> Double in
return value + entry.carbsOnBoard(at: date, defaultAbsorptionTime: defaultAbsorptionTime, delay: delay, absorptionModel: absorptionModel)
}
values.append(CarbValue(startDate: date, value: value))
date = date.addingTimeInterval(delta)
} while date <= endDate
return values
}
}
// MARK: - Dyanamic absorption overrides
extension Collection {
public func dynamicCarbsOnBoard<T>(
at date: Date,
absorptionModel: CarbAbsorptionComputable
) -> Double where Element == CarbStatus<T> {
reduce(0.0) { (value, entry) -> Double in
return value + entry.dynamicCarbsOnBoard(
at: date,
defaultAbsorptionTime: CarbMath.defaultAbsorptionTime,
delay: CarbMath.defaultEffectDelay,
delta: GlucoseMath.defaultDelta,
absorptionModel: absorptionModel
)
}
}
public func dynamicCarbsOnBoard<T>(
from start: Date? = nil,
to end: Date? = nil,
defaultAbsorptionTime: TimeInterval = TimeInterval(3 /* hours */ * 60 /* minutes */ * 60 /* seconds */),
absorptionModel: CarbAbsorptionComputable = PiecewiseLinearAbsorption(),
delay: TimeInterval = TimeInterval(10 /* minutes */ * 60 /* seconds */),
delta: TimeInterval = TimeInterval(5 /* minutes */ * 60 /* seconds */)
) -> [CarbValue] where Element == CarbStatus<T> {
guard let (startDate, endDate) = simulationDateRange(from: start, to: end, defaultAbsorptionTime: defaultAbsorptionTime, delay: delay, delta: delta) else {
return []
}
var date = startDate
var values = [CarbValue]()
repeat {
let value = reduce(0.0) { (value, entry) -> Double in
return value + entry.dynamicCarbsOnBoard(
at: date,
defaultAbsorptionTime: defaultAbsorptionTime,
delay: delay,
delta: delta,
absorptionModel: absorptionModel
)
}
values.append(CarbValue(startDate: date, value: value))
date = date.addingTimeInterval(delta)
} while date <= endDate
return values
}
public func dynamicGlucoseEffects<T>(
from start: Date? = nil,
to end: Date? = nil,
carbRatios: [AbsoluteScheduleValue<Double>],
insulinSensitivities: [AbsoluteScheduleValue<LoopQuantity>],
defaultAbsorptionTime: TimeInterval = CarbMath.defaultAbsorptionTime,
absorptionModel: CarbAbsorptionComputable = PiecewiseLinearAbsorption(),
delay: TimeInterval = CarbMath.defaultEffectDelay,
delta: TimeInterval = GlucoseMath.defaultDelta
) -> [GlucoseEffect] where Element == CarbStatus<T> {
guard let (startDate, endDate) = simulationDateRange(from: start, to: end, defaultAbsorptionTime: defaultAbsorptionTime, delay: delay, delta: delta) else {
return []
}
var date = startDate
var values = [GlucoseEffect]()
let mgdL = LoopUnit.milligramsPerDeciliter
repeat {
let value = reduce(0.0) { (value, entry) -> Double in
guard let isf = insulinSensitivities.closestPrior(to: entry.startDate), let cr = carbRatios.closestPrior(to: entry.startDate) else {
preconditionFailure("Insulin Sensitivities and Carb Ratios must cover all CarbStatus start dates")
}
let csf = isf.value.doubleValue(for: mgdL) / cr.value
return value + csf * entry.dynamicAbsorbedCarbs(
at: date,
absorptionTime: entry.absorptionTime ?? defaultAbsorptionTime,
delay: delay,
delta: delta,
absorptionModel: absorptionModel
)
}
values.append(GlucoseEffect(startDate: date, quantity: LoopQuantity(unit: mgdL, doubleValue: value)))
date = date.addingTimeInterval(delta)
} while date <= endDate
return values
}
/// The quantity of carbs expected to still absorb at the last date of absorption
public func getClampedCarbsOnBoard<T>() -> CarbValue? where Element == CarbStatus<T> {
guard let firstAbsorption = first?.absorption else {
return nil
}
let gram = LoopUnit.gram
var maxObservedEndDate = firstAbsorption.observedDate.end
var remainingTotalGrams: Double = 0
for entry in self {
guard let absorption = entry.absorption else {
continue
}
maxObservedEndDate = Swift.max(maxObservedEndDate, absorption.observedDate.end)
remainingTotalGrams += absorption.remaining.doubleValue(for: gram)
}
return CarbValue(startDate: maxObservedEndDate, value: remainingTotalGrams)
}
}
/// Aggregates and computes data about the absorption of a CarbEntry to create a CarbStatus value.
///
/// There are three key components managed by this builder:
/// - The entry data as reported by the user
/// - The observed data as calculated from glucose changes relative to insulin curves
/// - The minimum/maximum amounts of absorption used to clamp our observation data within reasonable bounds
fileprivate class CarbStatusBuilder<T: CarbEntry> {
// MARK: Model settings
private var absorptionModel: CarbAbsorptionComputable
private var adaptiveAbsorptionRateEnabled: Bool
private var adaptiveRateStandbyIntervalFraction: Double
private var adaptiveRateStandbyInterval: TimeInterval {
return initialAbsorptionTime * adaptiveRateStandbyIntervalFraction
}
// MARK: User-entered data
/// The carb entry input
let entry: T
/// The unit used for carb values
let carbUnit: LoopUnit
/// The total grams entered for this entry
let entryGrams: Double
/// The total glucose effect expected for this entry, in glucose units
let entryEffect: Double
/// The carbohydrate-sensitivity factor for this entry, in glucose units per gram
let carbohydrateSensitivityFactor: Double
/// The absorption time for this entry before any absorption is observed
let initialAbsorptionTime: TimeInterval
// MARK: Minimum/maximum bounding factors
/// The maximum absorption time allowed for this entry, determining the minimum absorption rate
let maxAbsorptionTime: TimeInterval
/// An amount of time to wait after the entry date before minimum absorption is assumed to begin
let delay: TimeInterval
/// The maximum end date allowed for this entry's absorption
let maxEndDate: Date
/// The last date we have effects observed, or "now" in real-time analysis.
private let lastEffectDate: Date
/// The minimum amount of carbs we assume must have absorbed at the last observation date
private var minPredictedGrams: Double {
// We incorporate a delay when calculating minimum absorption values
let time = lastEffectDate.timeIntervalSince(entry.startDate) - delay
return absorptionModel.absorbedCarbs(of: entryGrams, atTime: time, absorptionTime: maxAbsorptionTime)
}
// MARK: Incremental observation
/// The date at which we observe all the carbs were absorbed. or nil if carb absorption has not finished
private var observedCompletionDate: Date?
/// The total observed effect for each entry, in glucose units
private(set) var observedEffect: Double = 0
/// The timeline of absorption amounts credited to this carb entry, in grams, for computation of historical COB and effect history
private(set) var observedTimeline: [CarbValue] = []
/// The amount of carbs we've observed absorbing
private var observedGrams: Double {
return observedEffect / carbohydrateSensitivityFactor
}
/// The amount of effect remaining until 100% of entry absorption is observed
var remainingEffect: Double {
return max(entryEffect - observedEffect, 0)
}
/// The dates over which we observed absorption, from start until 100% or last observed effect.
private var observedAbsorptionDates: DateInterval {
return DateInterval(start: entry.startDate, end: observedCompletionDate ?? lastEffectDate)
}
// MARK: Clamped results
/// The number of carbs absorbed, suitable for use in calculations.
/// This is bounded by minimumPredictedGrams and the entry total.
private var clampedGrams: Double {
let minPredictedGrams = self.minPredictedGrams
return min(entryGrams, max(minPredictedGrams, observedGrams))
}
private var percentAbsorbed: Double {
return clampedGrams / entryGrams
}
/// The amount of time needed to absorb observed grams
private var timeToAbsorbObservedCarbs: TimeInterval {
let time = lastEffectDate.timeIntervalSince(entry.startDate) - delay
guard time > 0 else {
return 0.0
}
var timeToAbsorb: TimeInterval
if adaptiveAbsorptionRateEnabled && time > adaptiveRateStandbyInterval {
// If adaptive absorption rate is enabled, and if the time since start of absorption is greater than the standby interval, the time to absorb observed carbs equals the obervation time
timeToAbsorb = time
} else {
// If adaptive absorption rate is disabled, or if the time since start of absorption is less than the standby interval, the time to absorb observed carbs is calculated based on the absorption model
timeToAbsorb = absorptionModel.timeToAbsorb(forPercentAbsorbed: percentAbsorbed, totalAbsorptionTime: initialAbsorptionTime)
}
return min(timeToAbsorb, maxAbsorptionTime)
}
/// The amount of time needed for the remaining entry grams to absorb
private var estimatedTimeRemaining: TimeInterval {
let time = lastEffectDate.timeIntervalSince(entry.startDate) - delay
guard time > 0 else {
return initialAbsorptionTime
}
let notToExceedTimeRemaining = max(maxAbsorptionTime - time, 0.0)
guard notToExceedTimeRemaining > 0 else {
return 0.0
}
var dynamicTimeRemaining: TimeInterval
if adaptiveAbsorptionRateEnabled && time > adaptiveRateStandbyInterval {
// If adaptive absorption rate is enabled, and if the time since start of absorption is greater than the standby interval, the remaining time is estimated assuming the observed relative absorption rate persists for the remaining carbs
let dynamicAbsorptionTime = absorptionModel.absorptionTime(forPercentAbsorption: percentAbsorbed, atTime: time)
dynamicTimeRemaining = dynamicAbsorptionTime - time
} else {
// If adaptive absorption rate is disabled, or if the time since start of absorption is less than the standby interval, the remaining time is estimated assuming the modeled absorption rate
dynamicTimeRemaining = initialAbsorptionTime - timeToAbsorbObservedCarbs
}
// time remaining must not extend beyond the maximum absorption time
return min(dynamicTimeRemaining, notToExceedTimeRemaining)
}
/// The timeline of observed absorption, if greater than the minimum required absorption.
private var clampedTimeline: [CarbValue]? {
return observedGrams >= minPredictedGrams ? observedTimeline : nil
}
/// Configures a new builder
///
/// - Parameters:
/// - entry: The carb entry input
/// - carbUnit: The unit used for carb values
/// - carbohydrateSensitivityFactor: The carbohydrate-sensitivity factor for the entry, in glucose units per gram
/// - initialAbsorptionTime: The absorption initially assigned to this entry before any absorption is observed
/// - maxAbsorptionTime: The maximum absorption time allowed for this entry, determining the minimum absorption rate
/// - delay: An amount of time to wait after the entry date before minimum absorption is assumed to begin
/// - lastEffectDate: The last recorded date of effect observation, used to initialize absorption at model defined rate
/// - initialObservedEffect: The initial amount of observed effect, in glucose units. Defaults to 0
/// - absorptionModel: The absorption model to use when computing remaining absorption
/// - adaptiveAbsorptionRateEnabled: Whether the remaining absorption rate changes based in observed absorption rate
/// - adaptiveRateStandbyIntervalFraction: The delay, specified as a fraction of total absorption time, before the absorption rate will change based on observed absorption rate. Only used if adaptiveAbsorptionRateEnabled is true.
init(entry: T, carbUnit: LoopUnit, carbohydrateSensitivityFactor: Double, initialAbsorptionTime: TimeInterval, maxAbsorptionTime: TimeInterval, delay: TimeInterval, lastEffectDate: Date?, absorptionModel: CarbAbsorptionComputable, adaptiveAbsorptionRateEnabled: Bool, adaptiveRateStandbyIntervalFraction: Double, initialObservedEffect: Double = 0) {
self.entry = entry
self.carbUnit = carbUnit
self.carbohydrateSensitivityFactor = carbohydrateSensitivityFactor
self.initialAbsorptionTime = initialAbsorptionTime
self.maxAbsorptionTime = maxAbsorptionTime
self.delay = delay
self.observedEffect = initialObservedEffect
self.absorptionModel = absorptionModel
self.adaptiveAbsorptionRateEnabled = adaptiveAbsorptionRateEnabled
self.adaptiveRateStandbyIntervalFraction = adaptiveRateStandbyIntervalFraction
self.entryGrams = entry.quantity.doubleValue(for: carbUnit)
self.entryEffect = entryGrams * carbohydrateSensitivityFactor
self.maxEndDate = entry.startDate.addingTimeInterval(maxAbsorptionTime + delay)
self.lastEffectDate = min(
maxEndDate,
Swift.max(lastEffectDate ?? entry.startDate, entry.startDate)
)
}
/// Increments the builder state with the next glucose effect.
///
/// This function should only be called with values in ascending date order.
///
/// - Parameters:
/// - effect: The effect value, in glucose units corresponding to `carbohydrateSensitivityFactor`
/// - start: The start date of the effect
/// - end: The end date of the effect
func addNextEffect(_ effect: Double, start: Date, end: Date) {
guard start >= entry.startDate else {
return
}
observedEffect += effect
if observedCompletionDate == nil {
// Continue recording the timeline until 100% of the carbs have been observed
observedTimeline.append(
CarbValue(
startDate: start,
endDate: end,
value: effect / carbohydrateSensitivityFactor
)
)
// Once 100% of the carbs are observed, track the endDate
if observedEffect + Double(Float.ulpOfOne) >= entryEffect {
observedCompletionDate = end
}
}
}
/// The resulting CarbStatus value
var result: CarbStatus<T> {
let absorption = AbsorbedCarbValue(
observed: LoopQuantity(unit: carbUnit, doubleValue: observedGrams),
clamped: LoopQuantity(unit: carbUnit, doubleValue: clampedGrams),
total: entry.quantity,
remaining: LoopQuantity(unit: carbUnit, doubleValue: entryGrams - clampedGrams),
observedDate: observedAbsorptionDates,
estimatedTimeRemaining: estimatedTimeRemaining,
timeToAbsorbObservedCarbs: timeToAbsorbObservedCarbs
)
return CarbStatus(
entry: entry,
absorption: absorption,
observedTimeline: clampedTimeline
)
}
func absorptionRateAtTime(t: TimeInterval) -> Double {
let dynamicAbsorptionTime = min(observedAbsorptionDates.duration + estimatedTimeRemaining, maxAbsorptionTime)
guard dynamicAbsorptionTime > 0 else {
return 0.0
}
// time t nomalized to absorption time
let percentTime = t / dynamicAbsorptionTime
let averageAbsorptionRate = entryGrams / dynamicAbsorptionTime
return averageAbsorptionRate * absorptionModel.percentRateAtPercentTime(percentTime)
}
}
// MARK: - Sorted collections of CarbEntries
extension Collection where Element: CarbEntry {
/// Maps a sorted timeline of carb entries to the observed absorbed carbohydrates for each, from a timeline of glucose effect velocities.
///
/// This makes some important assumptions:
/// - insulin effects, used with glucose to calculate counteraction, are "correct"
/// - carbs are absorbed completely in the order they were eaten without mixing or overlapping effects
///
/// - Parameters:
/// - effectVelocities: A timeline of glucose effect velocities, ordered by start date
/// - carbRatio: The timeline of carb ratios, in grams per unit
/// - insulinSensitivity: The timeline of insulin sensitivities, in units of insulin per glucose-unit, covering the carb entries
/// - absorptionTimeOverrun: A multiplier for determining the minimum absorption time from the specified absorption time
/// - defaultAbsorptionTime: The absorption time to use for unspecified carb entries
/// - delay: The time to delay the dose effect
/// - Returns: A new array of `CarbStatus` values describing the absorbed carb quantities
public func map(
to effectVelocities: [GlucoseEffectVelocity],
carbRatio: [AbsoluteScheduleValue<Double>],
insulinSensitivity: [AbsoluteScheduleValue<LoopQuantity>],
absorptionTimeOverrun: Double = CarbMath.defaultAbsorptionTimeOverrun,
defaultAbsorptionTime: TimeInterval = CarbMath.defaultAbsorptionTime,
delay: TimeInterval = CarbMath.defaultEffectDelay,
initialAbsorptionTimeOverrun: Double = CarbMath.defaultAbsorptionTimeOverrun,
absorptionModel: CarbAbsorptionComputable = PiecewiseLinearAbsorption(),
adaptiveAbsorptionRateEnabled: Bool = false,
adaptiveRateStandbyIntervalFraction: Double = 0.2
) -> [CarbStatus<Element>] {
guard count > 0 else {
// TODO: Apply unmatched effects to meal prediction
return []
}
// for computation
let glucoseUnit = LoopUnit.milligramsPerDeciliter
let carbUnit = LoopUnit.gram
let builders: [CarbStatusBuilder<Element>] = map { (entry) in
guard
let entryCarbRatio = carbRatio.closestPrior(to: entry.startDate),
let entryInsulinSensitivity = insulinSensitivity.closestPrior(to: entry.startDate) else
{
preconditionFailure("Insulin sensitivity and carb ratio timelines must cover carb entry start dates")
}
let initialAbsorptionTimeOverrun = initialAbsorptionTimeOverrun
return CarbStatusBuilder(
entry: entry,
carbUnit: carbUnit,
carbohydrateSensitivityFactor: entryInsulinSensitivity.value.doubleValue(for: glucoseUnit) / entryCarbRatio.value,
initialAbsorptionTime: (entry.absorptionTime ?? defaultAbsorptionTime) * initialAbsorptionTimeOverrun,
maxAbsorptionTime: (entry.absorptionTime ?? defaultAbsorptionTime) * absorptionTimeOverrun,
delay: delay,
lastEffectDate: effectVelocities.last?.endDate,
absorptionModel: absorptionModel,
adaptiveAbsorptionRateEnabled: adaptiveAbsorptionRateEnabled,
adaptiveRateStandbyIntervalFraction: adaptiveRateStandbyIntervalFraction
)
}
for dxEffect in effectVelocities {
guard dxEffect.endDate > dxEffect.startDate else {
assertionFailure()
continue
}
// calculate instantanous absorption rate for all active entries
// Apply effect to all active entries
// Select only the entries whose dates overlap the current date interval.
// These are not necessarily contiguous as maxEndDate varies between entries
let activeBuilders = builders.filter { (builder) -> Bool in
return dxEffect.startDate < builder.maxEndDate && dxEffect.startDate >= builder.entry.startDate
}
// Ignore velocities < 0 when estimating carb absorption.
// These are most likely the result of insulin absorption increases such as
// during activity
var effectValue = Swift.max(0, dxEffect.effect.quantity.doubleValue(for: glucoseUnit))
// Sum the current absorption rates of each active entry to determine how to split the active effects
var totalRate = activeBuilders.reduce(0) { (totalRate, builder) -> Double in
let effectTime = dxEffect.startDate.timeIntervalSince(builder.entry.startDate)
let absorptionRateAtEffectTime = builder.absorptionRateAtTime(t: effectTime)
return totalRate + absorptionRateAtEffectTime
}
for builder in activeBuilders {
// Apply a portion of the effect to this entry
let effectTime = dxEffect.startDate.timeIntervalSince(builder.entry.startDate)
let absorptionRateAtEffectTime = builder.absorptionRateAtTime(t: effectTime)
// If total rate is zero, assign zero to partial effect
var partialEffectValue: Double = 0.0
if totalRate > 0 {
partialEffectValue = Swift.min(builder.remainingEffect, (absorptionRateAtEffectTime / totalRate) * effectValue)
totalRate -= absorptionRateAtEffectTime
effectValue -= partialEffectValue
}
builder.addNextEffect(partialEffectValue, start: dxEffect.startDate, end: dxEffect.endDate)
// If there's still remainder effects with no additional entries to account them to, count them as overrun on the final entry
if effectValue > Double(Float.ulpOfOne) && builder === activeBuilders.last! {
builder.addNextEffect(effectValue, start: dxEffect.startDate, end: dxEffect.endDate)
}
}
// We have remaining effect and no activeBuilders (otherwise we would have applied the effect to the last one)
if effectValue > Double(Float.ulpOfOne) {
// TODO: Track "phantom meals"
}
}
return builders.map { $0.result }
}
}