ForeCastChart.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. import Charts
  2. import CoreData
  3. import Foundation
  4. import SwiftUI
  5. struct ForeCastChart: View {
  6. @StateObject var state: Bolus.StateModel
  7. @Environment(\.colorScheme) var colorScheme
  8. @Binding var units: GlucoseUnits
  9. @State private var startMarker = Date(timeIntervalSinceNow: -4 * 60 * 60)
  10. private var endMarker: Date {
  11. state
  12. .displayForecastsAsLines ? Date(timeIntervalSinceNow: TimeInterval(hours: 3)) :
  13. Date(timeIntervalSinceNow: TimeInterval(2 * 5 * state.minCount * 60)) // min is 2h -> (2*1h = 2*(5*12*60))
  14. }
  15. var body: some View {
  16. VStack {
  17. forecastChart
  18. .padding(.vertical, 3)
  19. HStack {
  20. Spacer()
  21. Image(systemName: "arrow.right.circle")
  22. .font(.system(size: 16, weight: .bold))
  23. if let eventualBG = state.simulatedDetermination?.eventualBG {
  24. HStack {
  25. Text("\(eventualBG)")
  26. .font(.footnote)
  27. .foregroundStyle(.primary)
  28. Text("\(units.rawValue)")
  29. .font(.footnote)
  30. .foregroundStyle(.secondary)
  31. }
  32. } else {
  33. Text("---")
  34. .font(.footnote)
  35. .foregroundStyle(.primary)
  36. Text("\(units.rawValue)")
  37. .font(.footnote)
  38. .foregroundStyle(.secondary)
  39. }
  40. }
  41. }
  42. }
  43. private var forecastChart: some View {
  44. Chart {
  45. drawGlucose()
  46. drawCurrentTimeMarker()
  47. if state.displayForecastsAsLines {
  48. drawForecastLines()
  49. } else {
  50. drawForecastCone()
  51. }
  52. }
  53. .chartXAxis { forecastChartXAxis }
  54. .chartXScale(domain: startMarker ... endMarker)
  55. .chartYAxis { forecastChartYAxis }
  56. .chartYScale(domain: units == .mgdL ? 0 ... 300 : 0.asMmolL ... 300.asMmolL)
  57. .backport.chartForegroundStyleScale(state: state)
  58. }
  59. private func drawGlucose() -> some ChartContent {
  60. ForEach(state.glucoseFromPersistence) { item in
  61. if item.glucose > Int(state.highGlucose) {
  62. PointMark(
  63. x: .value("Time", item.date ?? Date(), unit: .second),
  64. y: .value("Value", units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL)
  65. )
  66. .foregroundStyle(Color.orange.gradient)
  67. .symbolSize(20)
  68. } else if item.glucose < Int(state.lowGlucose) {
  69. PointMark(
  70. x: .value("Time", item.date ?? Date(), unit: .second),
  71. y: .value("Value", units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL)
  72. )
  73. .foregroundStyle(Color.red.gradient)
  74. .symbolSize(20)
  75. } else {
  76. PointMark(
  77. x: .value("Time", item.date ?? Date(), unit: .second),
  78. y: .value("Value", units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL)
  79. )
  80. .foregroundStyle(Color.green.gradient)
  81. .symbolSize(20)
  82. }
  83. }
  84. }
  85. private func timeForIndex(_ index: Int32) -> Date {
  86. let currentTime = Date()
  87. let timeInterval = TimeInterval(index * 300)
  88. return currentTime.addingTimeInterval(timeInterval)
  89. }
  90. private func drawForecastCone() -> some ChartContent {
  91. ForEach(0 ..< max(state.minForecast.count, state.maxForecast.count), id: \.self) { index in
  92. if index < state.minForecast.count, index < state.maxForecast.count {
  93. let yMinValue = Decimal(state.minForecast[index]) <= 300 ? Decimal(state.minForecast[index]) : Decimal(300)
  94. let yMaxValue = Decimal(state.maxForecast[index]) <= 300 ? Decimal(state.maxForecast[index]) : Decimal(300)
  95. AreaMark(
  96. x: .value("Time", timeForIndex(Int32(index)) <= endMarker ? timeForIndex(Int32(index)) : endMarker),
  97. yStart: .value("Min Value", units == .mgdL ? yMinValue : yMinValue.asMmolL),
  98. yEnd: .value("Max Value", units == .mgdL ? yMaxValue : yMaxValue.asMmolL)
  99. )
  100. .foregroundStyle(Color.blue.opacity(0.5))
  101. .interpolationMethod(.catmullRom)
  102. }
  103. }
  104. }
  105. private func drawForecastLines() -> some ChartContent {
  106. let predictions = state.predictionsForChart
  107. // Prepare the prediction data with only the first 36 values, i.e. 3 hours in the future
  108. let predictionData = [
  109. ("IOB", predictions?.iob?.prefix(36)),
  110. ("ZT", predictions?.zt?.prefix(36)),
  111. ("COB", predictions?.cob?.prefix(36)),
  112. ("UAM", predictions?.uam?.prefix(36))
  113. ]
  114. return ForEach(predictionData, id: \.0) { name, values in
  115. if let values = values {
  116. ForEach(values.indices, id: \.self) { index in
  117. LineMark(
  118. x: .value("Time", timeForIndex(Int32(index))),
  119. y: .value("Value", units == .mgdL ? Decimal(values[index]) : Decimal(values[index]).asMmolL)
  120. )
  121. .foregroundStyle(by: .value("Prediction Type", name))
  122. }
  123. }
  124. }
  125. }
  126. private func drawCurrentTimeMarker() -> some ChartContent {
  127. RuleMark(
  128. x: .value(
  129. "",
  130. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  131. unit: .second
  132. )
  133. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  134. }
  135. private var forecastChartXAxis: some AxisContent {
  136. AxisMarks(values: .stride(by: .hour, count: 2)) { _ in
  137. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  138. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  139. .font(.footnote)
  140. .foregroundStyle(Color.primary)
  141. }
  142. }
  143. private var forecastChartYAxis: some AxisContent {
  144. AxisMarks(position: .trailing) { _ in
  145. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  146. AxisTick(length: 3, stroke: .init(lineWidth: 3)).foregroundStyle(Color.secondary)
  147. AxisValueLabel().font(.footnote).foregroundStyle(Color.primary)
  148. }
  149. }
  150. }
  151. extension Backport {
  152. @ViewBuilder func chartForegroundStyleScale(state: Bolus.StateModel) -> some View {
  153. if state.displayForecastsAsLines {
  154. content.chartForegroundStyleScale([
  155. "IOB": .blue,
  156. "UAM": Color.uam,
  157. "ZT": Color.zt,
  158. "COB": .orange
  159. ])
  160. } else {
  161. content
  162. }
  163. }
  164. }