ForeCastChart.swift 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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(
  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.asMmolL.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.displayForecastsAsLines {
  65. drawForecastLines()
  66. } else {
  67. drawForecastCone()
  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 func drawGlucose() -> some ChartContent {
  77. ForEach(state.glucoseFromPersistence) { item in
  78. if item.glucose > Int(state.highGlucose) {
  79. PointMark(
  80. x: .value("Time", item.date ?? Date(), unit: .second),
  81. y: .value("Value", units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL)
  82. )
  83. .foregroundStyle(Color.orange.gradient)
  84. .symbolSize(20)
  85. } else if item.glucose < Int(state.lowGlucose) {
  86. PointMark(
  87. x: .value("Time", item.date ?? Date(), unit: .second),
  88. y: .value("Value", units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL)
  89. )
  90. .foregroundStyle(Color.red.gradient)
  91. .symbolSize(20)
  92. } else {
  93. PointMark(
  94. x: .value("Time", item.date ?? Date(), unit: .second),
  95. y: .value("Value", units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL)
  96. )
  97. .foregroundStyle(Color.green.gradient)
  98. .symbolSize(20)
  99. }
  100. }
  101. }
  102. private func timeForIndex(_ index: Int32) -> Date {
  103. let currentTime = Date()
  104. let timeInterval = TimeInterval(index * 300)
  105. return currentTime.addingTimeInterval(timeInterval)
  106. }
  107. private func drawForecastCone() -> some ChartContent {
  108. ForEach(0 ..< max(state.minForecast.count, state.maxForecast.count), id: \.self) { index in
  109. if index < state.minForecast.count, index < state.maxForecast.count {
  110. let yMinValue = Decimal(state.minForecast[index]) <= 300 ? Decimal(state.minForecast[index]) : Decimal(300)
  111. let yMaxValue = Decimal(state.maxForecast[index]) <= 300 ? Decimal(state.maxForecast[index]) : Decimal(300)
  112. AreaMark(
  113. x: .value("Time", timeForIndex(Int32(index)) <= endMarker ? timeForIndex(Int32(index)) : endMarker),
  114. yStart: .value("Min Value", units == .mgdL ? yMinValue : yMinValue.asMmolL),
  115. yEnd: .value("Max Value", units == .mgdL ? yMaxValue : yMaxValue.asMmolL)
  116. )
  117. .foregroundStyle(Color.blue.opacity(0.5))
  118. .interpolationMethod(.catmullRom)
  119. }
  120. }
  121. }
  122. private func drawForecastLines() -> some ChartContent {
  123. let predictions = state.predictionsForChart
  124. // Prepare the prediction data with only the first 36 values, i.e. 3 hours in the future
  125. let predictionData = [
  126. ("iob", predictions?.iob?.prefix(36)),
  127. ("zt", predictions?.zt?.prefix(36)),
  128. ("cob", predictions?.cob?.prefix(36)),
  129. ("uam", predictions?.uam?.prefix(36))
  130. ]
  131. return ForEach(predictionData, id: \.0) { name, values in
  132. if let values = values {
  133. ForEach(values.indices, id: \.self) { index in
  134. LineMark(
  135. x: .value("Time", timeForIndex(Int32(index))),
  136. y: .value("Value", units == .mgdL ? Decimal(values[index]) : Decimal(values[index]).asMmolL)
  137. )
  138. .foregroundStyle(by: .value("Prediction Type", name))
  139. }
  140. }
  141. }
  142. }
  143. private func drawCurrentTimeMarker() -> some ChartContent {
  144. RuleMark(
  145. x: .value(
  146. "",
  147. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  148. unit: .second
  149. )
  150. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  151. }
  152. private var forecastChartXAxis: some AxisContent {
  153. AxisMarks(values: .stride(by: .hour, count: 2)) { _ in
  154. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  155. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  156. .font(.footnote)
  157. .foregroundStyle(Color.primary)
  158. }
  159. }
  160. private var forecastChartYAxis: some AxisContent {
  161. AxisMarks(position: .trailing) { _ in
  162. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  163. AxisTick(length: 3, stroke: .init(lineWidth: 3)).foregroundStyle(Color.secondary)
  164. AxisValueLabel().font(.footnote).foregroundStyle(Color.primary)
  165. }
  166. }
  167. }