forked from tidepool-org/LoopAlgorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoopMath.swift
More file actions
325 lines (255 loc) · 13.1 KB
/
LoopMath.swift
File metadata and controls
325 lines (255 loc) · 13.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
//
// LoopMath.swift
//
// Created by Nathan Racklyeft on 1/24/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
public enum LoopMath {
/// The interval over which to aggregate changes in glucose for retrospective correction
public static let retrospectiveCorrectionGroupingInterval = TimeInterval(minutes: 30)
public static let retrospectiveCorrectionEffectDuration = TimeInterval(hours: 1)
public static func simulationDateRangeForSamples<T: Collection>(
_ samples: T,
from start: Date? = nil,
to end: Date? = nil,
duration: TimeInterval,
delay: TimeInterval = 0,
delta: TimeInterval
) -> (start: Date, end: Date)? where T.Element: TimelineValue {
if let start = start, let end = end {
return (start: start.dateFlooredToTimeInterval(delta), end: end.dateCeiledToTimeInterval(delta))
} else {
guard samples.count > 0 else {
return nil
}
var minDate = samples.first!.startDate
var maxDate = minDate
for sample in samples {
if sample.startDate < minDate {
minDate = sample.startDate
}
if sample.endDate > maxDate {
maxDate = sample.endDate
}
}
return (
start: (start ?? minDate).dateFlooredToTimeInterval(delta),
end: (end ?? maxDate.addingTimeInterval(duration + delay)).dateCeiledToTimeInterval(delta)
)
}
}
/**
Calculates a range of time in `delta`-value intervals
- parameter start: The range start date
- parameter end: The range end date
- parameter delta: The time differential for items in the returned range
- returns: An array of dates
*/
public static func simulationDateRange(
from start: Date,
to end: Date,
delta: TimeInterval
) -> [Date] {
let flooredStart = start.dateFlooredToTimeInterval(delta)
let ceiledEnd = end.dateCeiledToTimeInterval(delta)
var output: [Date] = []
var curr = flooredStart
repeat {
output.append(curr)
let new = curr.addingTimeInterval(delta)
curr = new
} while curr <= ceiledEnd
return output
}
/**
Calculates a timeline of predicted glucose values from a variety of effects timelines.
Each effect timeline:
- Is given equal weight, with the exception of the momentum effect timeline
- Can be of arbitrary size and start date
- Should be in ascending order
- Should have aligning dates with any overlapping timelines to ensure a smooth result
- parameter startingGlucose: The starting glucose value
- parameter momentum: The momentum effect timeline determined from prior glucose values
- parameter effects: The glucose effect timelines to apply to the prediction.
- returns: A timeline of glucose values
*/
public static func predictGlucose(startingAt startingGlucose: GlucoseValue, momentum: [GlucoseEffect] = [], effects: [GlucoseEffect]...) -> [PredictedGlucoseValue] {
return predictGlucose(startingAt: startingGlucose, momentum: momentum, effects: effects)
}
/**
Calculates a timeline of predicted glucose values from a variety of effects timelines.
Each effect timeline:
- Is given equal weight, with the exception of the momentum effect timeline
- Can be of arbitrary size and start date
- Should be in ascending order
- Should have aligning dates with any overlapping timelines to ensure a smooth result
- parameter startingGlucose: The starting glucose value
- parameter momentum: The momentum effect timeline determined from prior glucose values
- parameter effects: The glucose effect timelines to apply to the prediction.
- returns: A timeline of glucose values
*/
public static func predictGlucose(startingAt startingGlucose: GlucoseValue, momentum: [GlucoseEffect] = [], effects: [[GlucoseEffect]]) -> [PredictedGlucoseValue] {
var effectValuesAtDate: [Date: Double] = [:]
let unit = LoopUnit.milligramsPerDeciliter
for timeline in effects {
var previousEffectValue: Double = timeline.first?.quantity.doubleValue(for: unit) ?? 0
for effect in timeline {
let value = effect.quantity.doubleValue(for: unit)
effectValuesAtDate[effect.startDate] = (effectValuesAtDate[effect.startDate] ?? 0) + value - previousEffectValue
previousEffectValue = value
}
}
// Blend the momentum effect linearly into the summed effect list
if momentum.count > 1 {
var previousEffectValue: Double = momentum[0].quantity.doubleValue(for: unit)
// The blend begins delta minutes after after the last glucose (1.0) and ends at the last momentum point (0.0)
// We're assuming the first one occurs on or before the starting glucose.
let blendCount = momentum.count - 2
let timeDelta = momentum[1].startDate.timeIntervalSince(momentum[0].startDate)
// The difference between the first momentum value and the starting glucose value
let momentumOffset = startingGlucose.startDate.timeIntervalSince(momentum[0].startDate)
let blendSlope = 1.0 / Double(blendCount)
let blendOffset = momentumOffset / timeDelta * blendSlope
for (index, effect) in momentum.enumerated() {
let value = effect.quantity.doubleValue(for: unit)
let effectValueChange = value - previousEffectValue
let split = min(1.0, max(0.0, Double(momentum.count - index) / Double(blendCount) - blendSlope + blendOffset))
let effectBlend = (1.0 - split) * (effectValuesAtDate[effect.startDate] ?? 0)
let momentumBlend = split * effectValueChange
effectValuesAtDate[effect.startDate] = effectBlend + momentumBlend
previousEffectValue = value
}
}
let prediction = effectValuesAtDate.sorted { $0.0 < $1.0 }.reduce([PredictedGlucoseValue(startDate: startingGlucose.startDate, quantity: startingGlucose.quantity)]) { (prediction, effect) -> [PredictedGlucoseValue] in
if effect.0 > startingGlucose.startDate, let lastValue = prediction.last {
let nextValue = PredictedGlucoseValue(
startDate: effect.0,
quantity: LoopQuantity(unit: unit, doubleValue: effect.1 + lastValue.quantity.doubleValue(for: unit))
)
return prediction + [nextValue]
} else {
return prediction
}
}
return prediction
}
}
extension GlucoseValue {
/**
Calculates a timeline of glucose effects by applying a linear decay to a rate of change.
- parameter rate: The glucose velocity
- parameter duration: The duration the effect should continue before ending
- parameter delta: The time differential for the returned values
- returns: An array of glucose effects
*/
public func decayEffect(atRate rate: LoopQuantity, for duration: TimeInterval, withDelta delta: TimeInterval = 5 * 60) -> [GlucoseEffect] {
guard let (startDate, endDate) = LoopMath.simulationDateRangeForSamples([self], duration: duration, delta: delta) else {
return []
}
let glucoseUnit = LoopUnit.milligramsPerDeciliter
let velocityUnit = GlucoseEffectVelocity.perSecondUnit
// The starting rate, which we will decay to 0 over the specified duration
let intercept = rate.doubleValue(for: velocityUnit) // mg/dL/s
let decayStartDate = startDate.addingTimeInterval(delta)
let slope = -intercept / (duration - delta) // mg/dL/s/s
var values = [GlucoseEffect(startDate: startDate, quantity: quantity)]
var date = decayStartDate
var lastValue = quantity.doubleValue(for: glucoseUnit)
repeat {
let value = lastValue + (intercept + slope * date.timeIntervalSince(decayStartDate)) * delta
values.append(GlucoseEffect(startDate: date, quantity: LoopQuantity(unit: glucoseUnit, doubleValue: value)))
lastValue = value
date = date.addingTimeInterval(delta)
} while date < endDate
return values
}
}
extension BidirectionalCollection where Element == GlucoseEffect {
/// Sums adjacent glucose effects into buckets of the specified duration.
///
/// Requires the receiver to be sorted chronologically by endDate
///
/// - Parameter duration: The duration of each resulting summed element
/// - Returns: An array of summed effects
public func combinedSums(of duration: TimeInterval) -> [GlucoseChange] {
var sums = [GlucoseChange]()
sums.reserveCapacity(self.count)
var lastValidIndex = sums.startIndex
for effect in reversed() {
sums.append(GlucoseChange(startDate: effect.startDate, endDate: effect.endDate, quantity: effect.quantity))
for sumsIndex in lastValidIndex..<(sums.endIndex - 1) {
guard sums[sumsIndex].endDate <= effect.endDate.addingTimeInterval(duration) else {
lastValidIndex += 1
continue
}
sums[sumsIndex].append(effect)
}
}
return sums.reversed()
}
/// Returns the net effect of the receiver as a GlucoseChange object
///
/// Requires the receiver to be sorted chronologically by endDate
///
/// - Returns: A single GlucoseChange representing the net effect
public func netEffect() -> GlucoseChange? {
guard let first = self.first, let last = self.last else {
return nil
}
let net = last.quantity.doubleValue(for: .milligramsPerDeciliter) - first.quantity.doubleValue(for: .milligramsPerDeciliter)
return GlucoseChange(startDate: first.startDate, endDate: last.endDate, quantity: LoopQuantity(unit: .milligramsPerDeciliter, doubleValue: net))
}
}
extension BidirectionalCollection where Element == GlucoseEffectVelocity {
/// Subtracts an array of glucose effects with uniform intervals and no gaps from the collection of effect changes, which may not have uniform intervals.
///
/// - Parameters:
/// - otherEffects: The array of glucose effects to subtract
/// - effectInterval: The time interval between elements in the otherEffects array
/// - Returns: A resulting array of glucose effects
public func subtracting(_ otherEffects: [GlucoseEffect], withUniformInterval effectInterval: TimeInterval = GlucoseMath.defaultDelta) -> [GlucoseEffect] {
// Trim both collections to match
let otherEffects = otherEffects.filterDateRange(self.first?.endDate, nil)
let effects = self.filterDateRange(otherEffects.first?.startDate, nil)
var subtracted: [GlucoseEffect] = []
var previousOtherEffectValue = otherEffects.first?.quantity.doubleValue(for: .milligramsPerDeciliter) ?? 0 // mg/dL
var effectIndex = effects.startIndex
for otherEffect in otherEffects.dropFirst() {
guard effectIndex < effects.endIndex else {
break
}
let otherEffectValue = otherEffect.quantity.doubleValue(for: .milligramsPerDeciliter)
let otherEffectChange = otherEffectValue - previousOtherEffectValue
previousOtherEffectValue = otherEffectValue
let effect = effects[effectIndex]
// Our effect array may have gaps, or have longer segments than 5 minutes.
guard effect.endDate <= otherEffect.endDate else {
continue // Move on to the next other effect
}
effectIndex += 1
let effectValue = effect.quantity.doubleValue(for: GlucoseEffectVelocity.perSecondUnit) // mg/dL/s
let effectValueMatchingOtherEffectInterval = effectValue * effectInterval // mg/dL
subtracted.append(GlucoseEffect(
startDate: effect.endDate,
quantity: LoopQuantity(
unit: .milligramsPerDeciliter,
doubleValue: effectValueMatchingOtherEffectInterval - otherEffectChange
)
))
}
// If we have run out of otherEffect items, we assume the otherEffectChange remains zero
for effect in effects[effectIndex..<effects.endIndex] {
let effectValue = effect.quantity.doubleValue(for: GlucoseEffectVelocity.perSecondUnit) // mg/dL/s
let effectValueMatchingOtherEffectInterval = effectValue * effectInterval // mg/dL
subtracted.append(GlucoseEffect(
startDate: effect.endDate,
quantity: LoopQuantity(
unit: .milligramsPerDeciliter,
doubleValue: effectValueMatchingOtherEffectInterval
)
))
}
return subtracted
}
}