ForeCastChart.swift 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. HStack {
  33. HStack {
  34. Text("Added carbs: ")
  35. .font(.footnote)
  36. .fontWeight(.bold)
  37. .foregroundStyle(.orange)
  38. Text("\(state.carbs.description) g")
  39. .font(.footnote)
  40. .foregroundStyle(.orange)
  41. }
  42. .padding(8)
  43. .background {
  44. RoundedRectangle(cornerRadius: 10)
  45. .fill(Color.orange.opacity(0.2))
  46. }
  47. Spacer()
  48. HStack {
  49. Text("Added insulin: ")
  50. .font(.footnote)
  51. .fontWeight(.bold)
  52. .foregroundStyle(.blue)
  53. Text("\(state.amount.description) U")
  54. .font(.footnote)
  55. .foregroundStyle(.blue)
  56. }
  57. .padding(8)
  58. .background {
  59. RoundedRectangle(cornerRadius: 10)
  60. .fill(Color.blue.opacity(0.2))
  61. }
  62. }
  63. forecastChart
  64. .padding(.vertical, 3)
  65. HStack {
  66. Spacer()
  67. Image(systemName: "arrow.right.circle")
  68. .font(.system(size: 16, weight: .bold))
  69. if let eventualBG = state.simulatedDetermination?.eventualBG {
  70. HStack {
  71. Text(
  72. units == .mgdL ? Decimal(eventualBG).description : eventualBG.formattedAsMmolL
  73. )
  74. .font(.footnote)
  75. .foregroundStyle(.primary)
  76. Text("\(units.rawValue)")
  77. .font(.footnote)
  78. .foregroundStyle(.secondary)
  79. }
  80. } else {
  81. Text("---")
  82. .font(.footnote)
  83. .foregroundStyle(.primary)
  84. Text("\(units.rawValue)")
  85. .font(.footnote)
  86. .foregroundStyle(.secondary)
  87. }
  88. }
  89. }
  90. }
  91. private var forecastChart: some View {
  92. Chart {
  93. drawGlucose()
  94. drawCurrentTimeMarker()
  95. if state.forecastDisplayType == .lines {
  96. drawForecastLines()
  97. } else {
  98. drawForecastsCone()
  99. }
  100. }
  101. .chartXAxis { forecastChartXAxis }
  102. .chartXScale(domain: startMarker ... endMarker)
  103. .chartYAxis { forecastChartYAxis }
  104. .chartYScale(domain: units == .mgdL ? 0 ... 300 : 0.asMmolL ... 300.asMmolL)
  105. .backport.chartForegroundStyleScale(state: state)
  106. }
  107. private func drawGlucose() -> some ChartContent {
  108. ForEach(state.glucoseFromPersistence) { item in
  109. let glucoseToDisplay = state.units == .mgdL ? Decimal(item.glucose) : Decimal(item.glucose).asMmolL
  110. let pointMarkColor = FreeAPS.getDynamicGlucoseColor(
  111. glucoseValue: glucoseToDisplay,
  112. highGlucoseColorValue: state.highGlucose,
  113. lowGlucoseColorValue: state.lowGlucose,
  114. targetGlucose: (state.determination.first?.currentTarget ?? state.currentBGTarget as NSDecimalNumber) as Decimal,
  115. glucoseColorScheme: state.glucoseColorScheme,
  116. offset: units == .mgdL ? 20 : 20.asMmolL
  117. )
  118. if !state.isSmoothingEnabled {
  119. PointMark(
  120. x: .value("Time", item.date ?? Date(), unit: .second),
  121. y: .value("Value", glucoseToDisplay)
  122. )
  123. .foregroundStyle(pointMarkColor)
  124. .symbolSize(20)
  125. } else {
  126. PointMark(
  127. x: .value("Time", item.date ?? Date(), unit: .second),
  128. y: .value("Value", glucoseToDisplay)
  129. )
  130. .symbol {
  131. Image(systemName: "record.circle.fill")
  132. .font(.system(size: 8))
  133. .bold()
  134. .foregroundStyle(pointMarkColor)
  135. }
  136. }
  137. }
  138. }
  139. private func timeForIndex(_ index: Int32) -> Date {
  140. let currentTime = Date()
  141. let timeInterval = TimeInterval(index * 300)
  142. return currentTime.addingTimeInterval(timeInterval)
  143. }
  144. private func drawForecastsCone() -> some ChartContent {
  145. // Draw AreaMark for the forecast bounds
  146. ForEach(0 ..< max(state.minForecast.count, state.maxForecast.count), id: \.self) { index in
  147. if index < state.minForecast.count, index < state.maxForecast.count {
  148. let yMinMaxDelta = Decimal(state.minForecast[index] - state.maxForecast[index])
  149. let xValue = timeForIndex(Int32(index))
  150. // if distance between respective min and max is 0, provide a default range
  151. if yMinMaxDelta == 0 {
  152. let yMinValue = units == .mgdL ? Decimal(state.minForecast[index] - 1) :
  153. Decimal(state.minForecast[index] - 1)
  154. .asMmolL
  155. let yMaxValue = units == .mgdL ? Decimal(state.minForecast[index] + 1) :
  156. Decimal(state.minForecast[index] + 1)
  157. .asMmolL
  158. AreaMark(
  159. x: .value("Time", xValue <= endMarker ? xValue : endMarker),
  160. yStart: .value("Min Value", units == .mgdL ? yMinValue : yMinValue.asMmolL),
  161. yEnd: .value("Max Value", units == .mgdL ? yMaxValue : yMaxValue.asMmolL)
  162. )
  163. .foregroundStyle(Color.blue.opacity(0.5))
  164. .interpolationMethod(.catmullRom)
  165. } else {
  166. let yMinValue = Decimal(state.minForecast[index]) <= 300 ? Decimal(state.minForecast[index]) : Decimal(300)
  167. let yMaxValue = Decimal(state.maxForecast[index]) <= 300 ? Decimal(state.maxForecast[index]) : Decimal(300)
  168. AreaMark(
  169. x: .value("Time", timeForIndex(Int32(index)) <= endMarker ? timeForIndex(Int32(index)) : endMarker),
  170. yStart: .value("Min Value", units == .mgdL ? yMinValue : yMinValue.asMmolL),
  171. yEnd: .value("Max Value", units == .mgdL ? yMaxValue : yMaxValue.asMmolL)
  172. )
  173. .foregroundStyle(Color.blue.opacity(0.5))
  174. .interpolationMethod(.catmullRom)
  175. }
  176. }
  177. }
  178. }
  179. private func drawForecastLines() -> some ChartContent {
  180. let predictions = state.predictionsForChart
  181. // Prepare the prediction data with only the first 36 values, i.e. 3 hours in the future
  182. let predictionData = [
  183. ("iob", predictions?.iob?.prefix(36)),
  184. ("zt", predictions?.zt?.prefix(36)),
  185. ("cob", predictions?.cob?.prefix(36)),
  186. ("uam", predictions?.uam?.prefix(36))
  187. ]
  188. return ForEach(predictionData, id: \.0) { name, values in
  189. if let values = values {
  190. ForEach(values.indices, id: \.self) { index in
  191. LineMark(
  192. x: .value("Time", timeForIndex(Int32(index))),
  193. y: .value("Value", units == .mgdL ? Decimal(values[index]) : Decimal(values[index]).asMmolL)
  194. )
  195. .foregroundStyle(by: .value("Prediction Type", name))
  196. }
  197. }
  198. }
  199. }
  200. private func drawCurrentTimeMarker() -> some ChartContent {
  201. RuleMark(
  202. x: .value(
  203. "",
  204. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  205. unit: .second
  206. )
  207. ).lineStyle(.init(lineWidth: 2, dash: [3])).foregroundStyle(Color(.systemGray2))
  208. }
  209. private var forecastChartXAxis: some AxisContent {
  210. AxisMarks(values: .stride(by: .hour, count: 2)) { _ in
  211. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  212. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  213. .font(.footnote)
  214. .foregroundStyle(Color.primary)
  215. }
  216. }
  217. private var forecastChartYAxis: some AxisContent {
  218. AxisMarks(position: .trailing) { _ in
  219. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  220. AxisTick(length: 3, stroke: .init(lineWidth: 3)).foregroundStyle(Color.secondary)
  221. AxisValueLabel().font(.footnote).foregroundStyle(Color.primary)
  222. }
  223. }
  224. }