ForeCastChart.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. .forecastDisplayType == .lines ? Date(timeIntervalSinceNow: TimeInterval(hours: 3)) :
  13. Date(timeIntervalSinceNow: TimeInterval(
  14. Int(1.5) * 5 * state
  15. .minCount * 60
  16. )) // min is 1.5h -> (1.5*1h = 1.5*(5*12*60))
  17. }
  18. private var glucoseFormatter: NumberFormatter {
  19. let formatter = NumberFormatter()
  20. formatter.numberStyle = .decimal
  21. if units == .mmolL {
  22. formatter.maximumFractionDigits = 1
  23. formatter.minimumFractionDigits = 1
  24. formatter.roundingMode = .halfUp
  25. } else {
  26. formatter.maximumFractionDigits = 0
  27. }
  28. return formatter
  29. }
  30. var body: some View {
  31. VStack {
  32. forecastChart
  33. .padding(.vertical, 3)
  34. HStack {
  35. Spacer()
  36. Image(systemName: "arrow.right.circle")
  37. .font(.system(size: 16, weight: .bold))
  38. if let eventualBG = state.simulatedDetermination?.eventualBG {
  39. HStack {
  40. Text(
  41. units == .mgdL ? Decimal(eventualBG).description : eventualBG.formattedAsMmolL
  42. )
  43. .font(.footnote)
  44. .foregroundStyle(.primary)
  45. Text("\(units.rawValue)")
  46. .font(.footnote)
  47. .foregroundStyle(.secondary)
  48. }
  49. } else {
  50. Text("---")
  51. .font(.footnote)
  52. .foregroundStyle(.primary)
  53. Text("\(units.rawValue)")
  54. .font(.footnote)
  55. .foregroundStyle(.secondary)
  56. }
  57. }
  58. }
  59. }
  60. private var forecastChart: some View {
  61. Chart {
  62. drawGlucose()
  63. drawCurrentTimeMarker()
  64. if state.forecastDisplayType == .lines {
  65. drawForecastLines()
  66. } else {
  67. drawForecastsCone()
  68. }
  69. }
  70. .chartXAxis { forecastChartXAxis }
  71. .chartXScale(domain: startMarker ... endMarker)
  72. .chartYAxis { forecastChartYAxis }
  73. .chartYScale(domain: units == .mgdL ? 0 ... 300 : 0.asMmolL ... 300.asMmolL)
  74. .backport.chartForegroundStyleScale(state: state)
  75. }
  76. private var stops: [Gradient.Stop] {
  77. let low = Double(state.lowGlucose)
  78. let high = Double(state.highGlucose)
  79. let glucoseValues = state.glucoseFromPersistence
  80. .map { units == .mgdL ? Decimal($0.glucose) : Decimal($0.glucose).asMmolL }
  81. let minimum = glucoseValues.min() ?? 0.0
  82. let maximum = glucoseValues.max() ?? 0.0
  83. // Calculate positions for gradient
  84. let lowPosition = (low - Double(truncating: minimum as NSNumber)) /
  85. (Double(truncating: maximum as NSNumber) - Double(truncating: minimum as NSNumber))
  86. let highPosition = (high - Double(truncating: minimum as NSNumber)) /
  87. (Double(truncating: maximum as NSNumber) - Double(truncating: minimum as NSNumber))
  88. // Ensure positions are in bounds [0, 1]
  89. let clampedLowPosition = max(0.0, min(lowPosition, 1.0))
  90. let clampedHighPosition = max(0.0, min(highPosition, 1.0))
  91. // Ensure lowPosition is less than highPosition
  92. let sortedPositions = [clampedLowPosition, clampedHighPosition].sorted()
  93. return [
  94. Gradient.Stop(color: .red, location: 0.0),
  95. Gradient.Stop(color: .red, location: sortedPositions[0]), // draw red gradient till lowGlucose
  96. Gradient.Stop(color: .green, location: sortedPositions[0] + 0.0001), // draw green above lowGlucose till highGlucose
  97. Gradient.Stop(color: .green, location: sortedPositions[1]),
  98. Gradient.Stop(color: .orange, location: sortedPositions[1] + 0.0001), // draw orange above highGlucose
  99. Gradient.Stop(color: .orange, location: 1.0)
  100. ]
  101. }
  102. private func drawGlucose() -> some ChartContent {
  103. ForEach(state.glucoseFromPersistence) { item in
  104. let glucoseToDisplay = units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL
  105. if state.smooth {
  106. LineMark(
  107. x: .value("Time", item.date ?? Date()),
  108. y: .value("Value", glucoseToDisplay)
  109. )
  110. .foregroundStyle(
  111. .linearGradient(stops: stops, startPoint: .bottom, endPoint: .top)
  112. )
  113. .symbol(.circle).symbolSize(34)
  114. } else {
  115. if item.glucose > Int(state.highGlucose) {
  116. PointMark(
  117. x: .value("Time", item.date ?? Date(), unit: .second),
  118. y: .value("Value", glucoseToDisplay)
  119. )
  120. .foregroundStyle(Color.orange.gradient)
  121. .symbolSize(20)
  122. } else if item.glucose < Int(state.lowGlucose) {
  123. PointMark(
  124. x: .value("Time", item.date ?? Date(), unit: .second),
  125. y: .value("Value", glucoseToDisplay)
  126. )
  127. .foregroundStyle(Color.red.gradient)
  128. .symbolSize(20)
  129. } else {
  130. PointMark(
  131. x: .value("Time", item.date ?? Date(), unit: .second),
  132. y: .value("Value", glucoseToDisplay)
  133. )
  134. .foregroundStyle(Color.green.gradient)
  135. .symbolSize(20)
  136. }
  137. }
  138. }
  139. }
  140. private func timeForIndex(_ index: Int32) -> Date {
  141. let currentTime = Date()
  142. let timeInterval = TimeInterval(index * 300)
  143. return currentTime.addingTimeInterval(timeInterval)
  144. }
  145. private func drawForecastsCone() -> some ChartContent {
  146. // Draw AreaMark for the forecast bounds
  147. ForEach(0 ..< max(state.minForecast.count, state.maxForecast.count), id: \.self) { index in
  148. if index < state.minForecast.count, index < state.maxForecast.count {
  149. let yMinMaxDelta = Decimal(state.minForecast[index] - state.maxForecast[index])
  150. let xValue = timeForIndex(Int32(index))
  151. // if distance between respective min and max is 0, provide a default range
  152. if yMinMaxDelta == 0 {
  153. let yMinValue = units == .mgdL ? Decimal(state.minForecast[index] - 1) :
  154. Decimal(state.minForecast[index] - 1)
  155. .asMmolL
  156. let yMaxValue = units == .mgdL ? Decimal(state.minForecast[index] + 1) :
  157. Decimal(state.minForecast[index] + 1)
  158. .asMmolL
  159. AreaMark(
  160. x: .value("Time", xValue <= endMarker ? xValue : endMarker),
  161. yStart: .value("Min Value", units == .mgdL ? yMinValue : yMinValue.asMmolL),
  162. yEnd: .value("Max Value", units == .mgdL ? yMaxValue : yMaxValue.asMmolL)
  163. )
  164. .foregroundStyle(Color.blue.opacity(0.5))
  165. .interpolationMethod(.catmullRom)
  166. } else {
  167. let yMinValue = Decimal(state.minForecast[index]) <= 300 ? Decimal(state.minForecast[index]) : Decimal(300)
  168. let yMaxValue = Decimal(state.maxForecast[index]) <= 300 ? Decimal(state.maxForecast[index]) : Decimal(300)
  169. AreaMark(
  170. x: .value("Time", timeForIndex(Int32(index)) <= endMarker ? timeForIndex(Int32(index)) : endMarker),
  171. yStart: .value("Min Value", units == .mgdL ? yMinValue : yMinValue.asMmolL),
  172. yEnd: .value("Max Value", units == .mgdL ? yMaxValue : yMaxValue.asMmolL)
  173. )
  174. .foregroundStyle(Color.blue.opacity(0.5))
  175. .interpolationMethod(.catmullRom)
  176. }
  177. }
  178. }
  179. }
  180. private func drawForecastLines() -> some ChartContent {
  181. let predictions = state.predictionsForChart
  182. // Prepare the prediction data with only the first 36 values, i.e. 3 hours in the future
  183. let predictionData = [
  184. ("iob", predictions?.iob?.prefix(36)),
  185. ("zt", predictions?.zt?.prefix(36)),
  186. ("cob", predictions?.cob?.prefix(36)),
  187. ("uam", predictions?.uam?.prefix(36))
  188. ]
  189. return ForEach(predictionData, id: \.0) { name, values in
  190. if let values = values {
  191. ForEach(values.indices, id: \.self) { index in
  192. LineMark(
  193. x: .value("Time", timeForIndex(Int32(index))),
  194. y: .value("Value", units == .mgdL ? Decimal(values[index]) : Decimal(values[index]).asMmolL)
  195. )
  196. .foregroundStyle(by: .value("Prediction Type", name))
  197. }
  198. }
  199. }
  200. }
  201. private func drawCurrentTimeMarker() -> some ChartContent {
  202. RuleMark(
  203. x: .value(
  204. "",
  205. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  206. unit: .second
  207. )
  208. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  209. }
  210. private var forecastChartXAxis: some AxisContent {
  211. AxisMarks(values: .stride(by: .hour, count: 2)) { _ in
  212. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  213. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  214. .font(.footnote)
  215. .foregroundStyle(Color.primary)
  216. }
  217. }
  218. private var forecastChartYAxis: some AxisContent {
  219. AxisMarks(position: .trailing) { _ in
  220. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  221. AxisTick(length: 3, stroke: .init(lineWidth: 3)).foregroundStyle(Color.secondary)
  222. AxisValueLabel().font(.footnote).foregroundStyle(Color.primary)
  223. }
  224. }
  225. }