MainChartView2.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. import Charts
  2. import SwiftUI
  3. let screenSize: CGRect = UIScreen.main.bounds
  4. let calendar = Calendar.current
  5. private struct BasalProfile: Hashable {
  6. let amount: Double
  7. var isOverwritten: Bool
  8. let startDate: Date
  9. let endDate: Date?
  10. init(amount: Double, isOverwritten: Bool, startDate: Date, endDate: Date? = nil) {
  11. self.amount = amount
  12. self.isOverwritten = isOverwritten
  13. self.startDate = startDate
  14. self.endDate = endDate
  15. }
  16. }
  17. private struct Prediction: Hashable {
  18. let amount: Int
  19. let timestamp: Date
  20. let type: PredictionType
  21. }
  22. private struct Carb: Hashable {
  23. let amount: Decimal
  24. let timestamp: Date
  25. let nearestGlucose: BloodGlucose
  26. }
  27. private struct ChartBolus: Hashable {
  28. let amount: Decimal
  29. let timestamp: Date
  30. let nearestGlucose: BloodGlucose
  31. }
  32. private struct ChartTempTarget: Hashable {
  33. let amount: Decimal
  34. let start: Date
  35. let end: Date
  36. }
  37. private enum PredictionType: Hashable {
  38. case iob
  39. case cob
  40. case zt
  41. case uam
  42. }
  43. struct MainChartView2: View {
  44. private enum Config {
  45. static let bolusSize: CGFloat = 4
  46. static let bolusScale: CGFloat = 2.5
  47. static let carbsSize: CGFloat = 5
  48. static let carbsScale: CGFloat = 0.3
  49. static let fpuSize: CGFloat = 5
  50. }
  51. @Binding var glucose: [BloodGlucose]
  52. @Binding var eventualBG: Int?
  53. @Binding var suggestion: Suggestion?
  54. @Binding var tempBasals: [PumpHistoryEvent]
  55. @Binding var boluses: [PumpHistoryEvent]
  56. @Binding var suspensions: [PumpHistoryEvent]
  57. @Binding var announcement: [Announcement]
  58. @Binding var hours: Int
  59. @Binding var maxBasal: Decimal
  60. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  61. @Binding var basalProfile: [BasalProfileEntry]
  62. @Binding var tempTargets: [TempTarget]
  63. @Binding var carbs: [CarbsEntry]
  64. @Binding var smooth: Bool
  65. @Binding var highGlucose: Decimal
  66. @Binding var lowGlucose: Decimal
  67. @Binding var screenHours: Int16
  68. @Binding var displayXgridLines: Bool
  69. @Binding var displayYgridLines: Bool
  70. @Binding var thresholdLines: Bool
  71. @State var didAppearTrigger = false
  72. @State private var BasalProfiles: [BasalProfile] = []
  73. @State private var TempBasals: [PumpHistoryEvent] = []
  74. @State private var ChartTempTargets: [ChartTempTarget] = []
  75. @State private var Predictions: [Prediction] = []
  76. @State private var ChartCarbs: [Carb] = []
  77. @State private var ChartFpus: [Carb] = []
  78. @State private var ChartBoluses: [ChartBolus] = []
  79. @State private var startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  80. @State private var endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  81. private var bolusFormatter: NumberFormatter {
  82. let formatter = NumberFormatter()
  83. formatter.numberStyle = .decimal
  84. formatter.minimumIntegerDigits = 0
  85. formatter.maximumFractionDigits = 2
  86. formatter.decimalSeparator = "."
  87. return formatter
  88. }
  89. private var carbsFormatter: NumberFormatter {
  90. let formatter = NumberFormatter()
  91. formatter.numberStyle = .decimal
  92. formatter.maximumFractionDigits = 0
  93. return formatter
  94. }
  95. private var fpuFormatter: NumberFormatter {
  96. let formatter = NumberFormatter()
  97. formatter.numberStyle = .decimal
  98. formatter.maximumFractionDigits = 1
  99. formatter.decimalSeparator = "."
  100. formatter.minimumIntegerDigits = 0
  101. return formatter
  102. }
  103. var body: some View {
  104. VStack(alignment: .center, spacing: 8, content: {
  105. ScrollViewReader { scroller in
  106. ScrollView(.horizontal, showsIndicators: false) {
  107. VStack {
  108. MainChart()
  109. BasalChart()
  110. .padding(.bottom, 8)
  111. }.onChange(of: screenHours) { _ in
  112. scroller.scrollTo("MainChart", anchor: .trailing)
  113. }.onAppear {
  114. scroller.scrollTo("MainChart", anchor: .trailing)
  115. }.onChange(of: glucose) { _ in
  116. scroller.scrollTo("MainChart", anchor: .trailing)
  117. }
  118. .onChange(of: suggestion) { _ in
  119. scroller.scrollTo("MainChart", anchor: .trailing)
  120. }
  121. .onChange(of: tempBasals) { _ in
  122. scroller.scrollTo("MainChart", anchor: .trailing)
  123. }
  124. }
  125. }
  126. Legend()
  127. })
  128. }
  129. }
  130. // MARK: Components
  131. extension MainChartView2 {
  132. private func MainChart() -> some View {
  133. VStack {
  134. Chart {
  135. if thresholdLines {
  136. RuleMark(y: .value("High", highGlucose)).foregroundStyle(Color.loopYellow)
  137. .lineStyle(.init(lineWidth: 1, dash: [2]))
  138. RuleMark(y: .value("Low", lowGlucose)).foregroundStyle(Color.loopRed)
  139. .lineStyle(.init(lineWidth: 1, dash: [2]))
  140. }
  141. RuleMark(
  142. x: .value(
  143. "",
  144. startMarker,
  145. unit: .second
  146. )
  147. ).foregroundStyle(.clear)
  148. RuleMark(
  149. x: .value(
  150. "",
  151. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  152. unit: .second
  153. )
  154. ).lineStyle(.init(lineWidth: 1, dash: [2]))
  155. RuleMark(
  156. x: .value(
  157. "",
  158. endMarker,
  159. unit: .second
  160. )
  161. ).foregroundStyle(.clear)
  162. ForEach(ChartCarbs, id: \.self) { carb in
  163. let carbAmount = carb.amount
  164. PointMark(
  165. x: .value("Time", carb.timestamp, unit: .second),
  166. y: .value("Value", carb.nearestGlucose.sgv ?? 120)
  167. )
  168. .symbolSize((Config.carbsSize + CGFloat(carbAmount) * Config.carbsScale) * 10)
  169. .foregroundStyle(Color.orange)
  170. .annotation(position: .top) {
  171. Text(bolusFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  172. }
  173. }
  174. ForEach(ChartFpus, id: \.self) { fpu in
  175. let fpuAmount = fpu.amount
  176. PointMark(
  177. x: .value("Time", fpu.timestamp, unit: .second),
  178. y: .value("Value", fpu.nearestGlucose.sgv ?? 120)
  179. )
  180. .symbolSize((Config.fpuSize + CGFloat(fpuAmount) * Config.carbsScale) * 10)
  181. .foregroundStyle(Color.brown)
  182. .annotation(position: .top) {
  183. Text(bolusFormatter.string(from: fpuAmount as NSNumber)!).font(.caption2)
  184. }
  185. }
  186. ForEach(ChartBoluses, id: \.self) { bolus in
  187. let bolusAmount = bolus.amount
  188. PointMark(
  189. x: .value("Time", bolus.timestamp, unit: .second),
  190. y: .value("Value", bolus.nearestGlucose.sgv ?? 120)
  191. )
  192. .symbolSize((Config.bolusSize + CGFloat(bolusAmount) * Config.bolusScale) * 10)
  193. .foregroundStyle(Color.insulin)
  194. .annotation(position: .bottom) {
  195. Text(bolusFormatter.string(from: bolusAmount as NSNumber)!).font(.caption2)
  196. }
  197. }
  198. // MARK: this code causes 'compiler is unable to type-check this expression'-error
  199. ForEach(ChartTempTargets, id: \.self) { tt in
  200. let randomString = UUID().uuidString
  201. LineMark(
  202. x: .value("Time", tt.start),
  203. y: .value("Value", tt.amount),
  204. series: .value("tt", randomString)
  205. )
  206. .foregroundStyle(Color.purple).lineStyle(.init(lineWidth: 8, dash: [2, 3]))
  207. LineMark(
  208. x: .value("Time", tt.end),
  209. y: .value("Value", tt.amount),
  210. series: .value("tt", randomString)
  211. )
  212. .foregroundStyle(Color.purple).lineStyle(.init(lineWidth: 8, dash: [2, 3]))
  213. }
  214. ForEach(Predictions, id: \.self) { info in
  215. if info.type == .uam {
  216. LineMark(
  217. x: .value("Time", info.timestamp, unit: .second),
  218. y: .value("Value", info.amount),
  219. series: .value("uam", "uam")
  220. ).foregroundStyle(Color.uam).symbolSize(16)
  221. }
  222. if info.type == .cob {
  223. LineMark(
  224. x: .value("Time", info.timestamp, unit: .second),
  225. y: .value("Value", info.amount),
  226. series: .value("cob", "cob")
  227. ).foregroundStyle(Color.orange).symbolSize(16)
  228. }
  229. if info.type == .iob {
  230. LineMark(
  231. x: .value("Time", info.timestamp, unit: .second),
  232. y: .value("Value", info.amount),
  233. series: .value("iob", "iob")
  234. ).foregroundStyle(Color.insulin).symbolSize(16)
  235. }
  236. if info.type == .zt {
  237. LineMark(
  238. x: .value("Time", info.timestamp, unit: .second),
  239. y: .value("Value", info.amount),
  240. series: .value("zt", "zt")
  241. ).foregroundStyle(Color.zt).symbolSize(16)
  242. }
  243. }
  244. ForEach(glucose) {
  245. if let sgv = $0.sgv {
  246. /* let color: Color
  247. if sgv < lowGlucose {
  248. color = Color.red
  249. } else if sgv > highGlucose {
  250. color = Color.loopYellow
  251. } else {
  252. color = Color.green
  253. }*/
  254. PointMark(
  255. x: .value("Time", $0.dateString, unit: .second),
  256. y: .value("Value", sgv)
  257. // series: .value("Value", "unsmooth")
  258. ).foregroundStyle(Color.green.gradient).symbolSize(16)
  259. if smooth {
  260. LineMark(
  261. x: .value("Time", $0.dateString, unit: .second),
  262. y: .value("Value", sgv)
  263. // series: .value("Value", "smooth")
  264. ).foregroundStyle(Color.green.gradient).symbolSize(16)
  265. .interpolationMethod(.cardinal)
  266. }
  267. }
  268. }
  269. }.id("MainChart")
  270. .onChange(of: glucose) { _ in
  271. calculatePredictions()
  272. }
  273. .onChange(of: carbs) { _ in
  274. calculateCarbs()
  275. calculateFpus()
  276. }
  277. .onChange(of: boluses) { _ in
  278. calculateBoluses()
  279. }
  280. .onChange(of: tempTargets) { _ in
  281. calculateTTs()
  282. }
  283. .onChange(of: didAppearTrigger) { _ in
  284. calculatePredictions()
  285. calculateTTs()
  286. }.onChange(of: suggestion) { _ in
  287. calculatePredictions()
  288. }
  289. .onReceive(
  290. Foundation.NotificationCenter.default
  291. .publisher(for: UIApplication.willEnterForegroundNotification)
  292. ) { _ in
  293. calculatePredictions()
  294. }
  295. .frame(
  296. width: max(0, screenSize.width - 20, fullWidth(viewWidth: screenSize.width)),
  297. height: UIScreen.main.bounds.height / 3.5
  298. )
  299. // .chartYScale(domain: 0 ... 450)
  300. .chartXAxis {
  301. AxisMarks(values: .stride(by: .hour, count: 2)) { _ in
  302. if displayXgridLines {
  303. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  304. } else {
  305. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  306. }
  307. }
  308. }.chartYAxis {
  309. AxisMarks(position: .trailing, values: .stride(by: 100)) { value in
  310. if displayYgridLines {
  311. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  312. } else {
  313. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  314. }
  315. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  316. AxisTick(length: 4, stroke: .init(lineWidth: 4))
  317. .foregroundStyle(Color.gray)
  318. AxisValueLabel()
  319. }
  320. }
  321. }
  322. .aspectRatio(1, contentMode: .fit)
  323. }
  324. }
  325. func BasalChart() -> some View {
  326. VStack {
  327. Chart {
  328. RuleMark(
  329. x: .value(
  330. "",
  331. startMarker,
  332. unit: .second
  333. )
  334. ).foregroundStyle(.clear)
  335. RuleMark(
  336. x: .value(
  337. "",
  338. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  339. unit: .second
  340. )
  341. ).lineStyle(.init(lineWidth: 1, dash: [2]))
  342. RuleMark(
  343. x: .value(
  344. "",
  345. endMarker,
  346. unit: .second
  347. )
  348. ).foregroundStyle(.clear)
  349. ForEach(TempBasals) {
  350. BarMark(
  351. x: .value("Time", $0.timestamp),
  352. y: .value("Rate", $0.rate ?? 0)
  353. )
  354. }
  355. ForEach(BasalProfiles, id: \.self) { profile in
  356. LineMark(
  357. x: .value("Start Date", profile.startDate),
  358. y: .value("Amount", profile.amount),
  359. series: .value("profile", "profile")
  360. ).lineStyle(.init(lineWidth: 2, dash: [2, 3]))
  361. LineMark(
  362. x: .value("End Date", profile.endDate ?? endMarker),
  363. y: .value("Amount", profile.amount),
  364. series: .value("profile", "profile")
  365. ).lineStyle(.init(lineWidth: 2, dash: [2, 3]))
  366. }
  367. }.onChange(of: tempBasals) { _ in
  368. calculateBasals()
  369. calculateTempBasals()
  370. }
  371. .onChange(of: maxBasal) { _ in
  372. calculateBasals()
  373. calculateTempBasals()
  374. }
  375. .onChange(of: autotunedBasalProfile) { _ in
  376. calculateBasals()
  377. calculateTempBasals()
  378. }
  379. .onChange(of: didAppearTrigger) { _ in
  380. calculateBasals()
  381. calculateTempBasals()
  382. }.onChange(of: basalProfile) { _ in
  383. calculateBasals()
  384. calculateTempBasals()
  385. }
  386. // .frame(height: 80)
  387. .frame(
  388. width: max(0, screenSize.width - 20, fullWidth(viewWidth: screenSize.width)),
  389. height: UIScreen.main.bounds.height / 10
  390. )
  391. // .chartYScale(domain: 0 ... maxBasal)
  392. // .rotationEffect(.degrees(180))
  393. // .chartXAxis(.hidden)
  394. .chartXAxis {
  395. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  396. if displayXgridLines {
  397. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  398. } else {
  399. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  400. }
  401. // AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  402. AxisValueLabel(format: .dateTime.hour())
  403. }
  404. }.chartYAxis {
  405. AxisMarks(position: .trailing, values: .stride(by: 1)) { _ in
  406. if displayYgridLines {
  407. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  408. } else {
  409. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  410. }
  411. AxisTick(length: 30, stroke: .init(lineWidth: 4))
  412. .foregroundStyle(Color.clear)
  413. }
  414. }
  415. }
  416. }
  417. private func Legend() -> some View {
  418. HStack {
  419. Image(systemName: "line.diagonal")
  420. .rotationEffect(Angle(degrees: 45))
  421. .foregroundColor(.green)
  422. Text("BG")
  423. .foregroundColor(.secondary)
  424. Spacer()
  425. Image(systemName: "line.diagonal")
  426. .rotationEffect(Angle(degrees: 45))
  427. .foregroundColor(.insulin)
  428. Text("IOB")
  429. .foregroundColor(.secondary)
  430. Spacer()
  431. Image(systemName: "line.diagonal")
  432. .rotationEffect(Angle(degrees: 45))
  433. .foregroundColor(.purple)
  434. Text("ZT")
  435. .foregroundColor(.secondary)
  436. Spacer()
  437. Image(systemName: "line.diagonal")
  438. .frame(height: 10)
  439. .rotationEffect(Angle(degrees: 45))
  440. .foregroundColor(.loopYellow)
  441. Text("COB")
  442. .foregroundColor(.secondary)
  443. Spacer()
  444. Image(systemName: "line.diagonal")
  445. .rotationEffect(Angle(degrees: 45))
  446. .foregroundColor(.orange)
  447. Text("UAM")
  448. .foregroundColor(.secondary)
  449. if eventualBG != nil {
  450. Text("⇢ " + String(eventualBG ?? 0))
  451. }
  452. }
  453. .font(.caption2)
  454. .padding(.horizontal, 40)
  455. .padding(.vertical, 1)
  456. }
  457. }
  458. // MARK: Calculations
  459. extension MainChartView2 {
  460. private func timeToNearestGlucose(time: TimeInterval) -> BloodGlucose {
  461. var nextIndex = 0
  462. if glucose.last?.dateString.timeIntervalSince1970 ?? Date().timeIntervalSince1970 < time {
  463. return glucose.last ?? BloodGlucose(
  464. date: 0,
  465. dateString: Date(),
  466. unfiltered: nil,
  467. filtered: nil,
  468. noise: nil,
  469. type: nil
  470. )
  471. }
  472. for (index, value) in glucose.enumerated() {
  473. if value.dateString.timeIntervalSince1970 > time {
  474. nextIndex = index
  475. print("Break", value.dateString.timeIntervalSince1970, time)
  476. break
  477. }
  478. }
  479. return glucose[nextIndex]
  480. }
  481. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  482. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  483. }
  484. private func calculateCarbs() {
  485. var calculatedCarbs: [Carb] = []
  486. carbs.forEach { carb in
  487. let bg = timeToNearestGlucose(time: carb.createdAt.timeIntervalSince1970)
  488. calculatedCarbs.append(Carb(amount: carb.carbs, timestamp: carb.createdAt, nearestGlucose: bg))
  489. }
  490. ChartCarbs = calculatedCarbs
  491. }
  492. private func calculateFpus() {
  493. var calculatedFpus: [Carb] = []
  494. let fpus = carbs.filter { $0.isFPU ?? false }
  495. fpus.forEach { fpu in
  496. let bg = timeToNearestGlucose(time: fpu.createdAt.timeIntervalSince1970)
  497. calculatedFpus.append(Carb(amount: fpu.carbs, timestamp: fpu.actualDate ?? Date(), nearestGlucose: bg))
  498. }
  499. ChartFpus = calculatedFpus
  500. }
  501. private func calculateBoluses() {
  502. var calculatedBoluses: [ChartBolus] = []
  503. boluses.forEach { bolus in
  504. let bg = timeToNearestGlucose(time: bolus.timestamp.timeIntervalSince1970)
  505. calculatedBoluses.append(ChartBolus(amount: bolus.amount ?? 0, timestamp: bolus.timestamp, nearestGlucose: bg))
  506. }
  507. ChartBoluses = calculatedBoluses
  508. }
  509. private func calculateTTs() {
  510. var calculatedTTs: [ChartTempTarget] = []
  511. tempTargets.forEach { tt in
  512. let end = tt.createdAt.addingTimeInterval(TimeInterval(tt.duration * 60))
  513. if tt.targetTop != nil {
  514. calculatedTTs
  515. .append(ChartTempTarget(amount: tt.targetTop ?? 0, start: tt.createdAt, end: end))
  516. }
  517. }
  518. ChartTempTargets = calculatedTTs
  519. }
  520. private func calculatePredictions() {
  521. var calculatedPredictions: [Prediction] = []
  522. let uam = suggestion?.predictions?.uam ?? []
  523. let iob = suggestion?.predictions?.iob ?? []
  524. let cob = suggestion?.predictions?.cob ?? []
  525. let zt = suggestion?.predictions?.zt ?? []
  526. guard let deliveredAt = suggestion?.deliverAt else {
  527. return
  528. }
  529. uam.indices.forEach { index in
  530. let predTime = Date(
  531. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  532. .timeInterval
  533. )
  534. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  535. calculatedPredictions.append(
  536. Prediction(amount: uam[index], timestamp: predTime, type: .uam)
  537. )
  538. }
  539. }
  540. iob.indices.forEach { index in
  541. let predTime = Date(
  542. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  543. .timeInterval
  544. )
  545. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  546. calculatedPredictions.append(
  547. Prediction(amount: iob[index], timestamp: predTime, type: .iob)
  548. )
  549. }
  550. }
  551. cob.indices.forEach { index in
  552. let predTime = Date(
  553. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  554. .timeInterval
  555. )
  556. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  557. calculatedPredictions.append(
  558. Prediction(amount: cob[index], timestamp: predTime, type: .cob)
  559. )
  560. }
  561. }
  562. zt.indices.forEach { index in
  563. let predTime = Date(
  564. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  565. .timeInterval
  566. )
  567. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  568. calculatedPredictions.append(
  569. Prediction(amount: zt[index], timestamp: predTime, type: .zt)
  570. )
  571. }
  572. }
  573. Predictions = calculatedPredictions
  574. }
  575. private func getLastUam() -> Int {
  576. let uam = suggestion?.predictions?.uam ?? []
  577. return uam.last ?? 0
  578. }
  579. private func calculateTempBasals() {
  580. var basals = tempBasals
  581. var returnTempBasalRates: [PumpHistoryEvent] = []
  582. var finished: [Int: Bool] = [:]
  583. basals.indices.forEach { i in
  584. basals.indices.forEach { j in
  585. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  586. let rate = basals[i].rate ?? basals[j].rate
  587. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  588. finished[i] = true
  589. if rate != 0 || durationMin != 0 {
  590. returnTempBasalRates.append(
  591. PumpHistoryEvent(
  592. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  593. timestamp: basals[i].timestamp,
  594. durationMin: durationMin,
  595. rate: rate
  596. )
  597. )
  598. }
  599. }
  600. }
  601. }
  602. TempBasals = returnTempBasalRates
  603. }
  604. private func findRegularBasalPoints(
  605. timeBegin: TimeInterval,
  606. timeEnd: TimeInterval,
  607. autotuned: Bool
  608. ) -> [BasalProfile] {
  609. guard timeBegin < timeEnd else {
  610. return []
  611. }
  612. let beginDate = Date(timeIntervalSince1970: timeBegin)
  613. let calendar = Calendar.current
  614. let startOfDay = calendar.startOfDay(for: beginDate)
  615. let profile = autotuned ? autotunedBasalProfile : basalProfile
  616. let basalNormalized = profile.map {
  617. (
  618. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  619. rate: $0.rate
  620. )
  621. } + profile.map {
  622. (
  623. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  624. .timeIntervalSince1970,
  625. rate: $0.rate
  626. )
  627. } + profile.map {
  628. (
  629. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  630. .timeIntervalSince1970,
  631. rate: $0.rate
  632. )
  633. }
  634. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  635. .compactMap { window -> BasalProfile? in
  636. let window = Array(window)
  637. if window[0].time < timeBegin, window[1].time < timeBegin {
  638. return nil
  639. }
  640. if window[0].time < timeBegin, window[1].time >= timeBegin {
  641. let startDate = Date(timeIntervalSince1970: timeBegin)
  642. let rate = window[0].rate
  643. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  644. }
  645. if window[0].time >= timeBegin, window[0].time < timeEnd {
  646. let startDate = Date(timeIntervalSince1970: window[0].time)
  647. let rate = window[0].rate
  648. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  649. }
  650. return nil
  651. }
  652. return basalTruncatedPoints
  653. }
  654. private func calculateBasals() {
  655. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  656. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  657. let regularPoints = findRegularBasalPoints(
  658. timeBegin: dayAgoTime,
  659. timeEnd: endMarker.timeIntervalSince1970,
  660. autotuned: false
  661. )
  662. let autotunedBasalPoints = findRegularBasalPoints(
  663. timeBegin: dayAgoTime,
  664. timeEnd: endMarker.timeIntervalSince1970,
  665. autotuned: true
  666. )
  667. var totalBasal = regularPoints + autotunedBasalPoints
  668. totalBasal.sort {
  669. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  670. }
  671. var basals: [BasalProfile] = []
  672. totalBasal.indices.forEach { index in
  673. basals.append(BasalProfile(
  674. amount: totalBasal[index].amount,
  675. isOverwritten: totalBasal[index].isOverwritten,
  676. startDate: totalBasal[index].startDate,
  677. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  678. ))
  679. print(
  680. "Basal",
  681. totalBasal[index].startDate,
  682. totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  683. totalBasal[index].amount,
  684. totalBasal[index].isOverwritten
  685. )
  686. }
  687. BasalProfiles = basals
  688. }
  689. }