MainChartView2.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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 enum PredictionType: Hashable {
  23. case iob
  24. case cob
  25. case zt
  26. case uam
  27. }
  28. struct MainChartView2: View {
  29. private enum Config {
  30. static let bolusSize: CGFloat = 8
  31. static let bolusScale: CGFloat = 2.5
  32. static let carbsSize: CGFloat = 10
  33. static let carbsScale: CGFloat = 0.3
  34. }
  35. @Binding var glucose: [BloodGlucose]
  36. @Binding var eventualBG: Int?
  37. @Binding var suggestion: Suggestion?
  38. @Binding var tempBasals: [PumpHistoryEvent]
  39. @Binding var boluses: [PumpHistoryEvent]
  40. @Binding var suspensions: [PumpHistoryEvent]
  41. @Binding var announcement: [Announcement]
  42. @Binding var hours: Int
  43. @Binding var maxBasal: Decimal
  44. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  45. @Binding var basalProfile: [BasalProfileEntry]
  46. @Binding var tempTargets: [TempTarget]
  47. @Binding var carbs: [CarbsEntry]
  48. @Binding var smooth: Bool
  49. @Binding var highGlucose: Decimal
  50. @Binding var lowGlucose: Decimal
  51. @Binding var screenHours: Int16
  52. @Binding var displayXgridLines: Bool
  53. @Binding var displayYgridLines: Bool
  54. @Binding var thresholdLines: Bool
  55. @State var didAppearTrigger = false
  56. @State private var BasalProfiles: [BasalProfile] = []
  57. @State private var TempBasals: [PumpHistoryEvent] = []
  58. @State private var startMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 86400))
  59. @State private var endMarker = Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 + 10800))
  60. private var bolusFormatter: NumberFormatter {
  61. let formatter = NumberFormatter()
  62. formatter.numberStyle = .decimal
  63. formatter.minimumIntegerDigits = 0
  64. formatter.maximumFractionDigits = 2
  65. formatter.decimalSeparator = "."
  66. return formatter
  67. }
  68. private var carbsFormatter: NumberFormatter {
  69. let formatter = NumberFormatter()
  70. formatter.numberStyle = .decimal
  71. formatter.maximumFractionDigits = 0
  72. return formatter
  73. }
  74. var body: some View {
  75. VStack(alignment: .center, spacing: 8, content: {
  76. ScrollViewReader { scroller in
  77. ScrollView(.horizontal, showsIndicators: false) {
  78. VStack {
  79. MainChart()
  80. BasalChart()
  81. .padding(.bottom, 8)
  82. }.onChange(of: screenHours) { _ in
  83. scroller.scrollTo("MainChart", anchor: .trailing)
  84. }.onAppear {
  85. scroller.scrollTo("MainChart", anchor: .trailing)
  86. }.onChange(of: tempBasals) { _ in
  87. calculateBasals()
  88. }
  89. .onChange(of: maxBasal) { _ in
  90. calculateBasals()
  91. }
  92. .onChange(of: autotunedBasalProfile) { _ in
  93. calculateBasals()
  94. }
  95. .onChange(of: didAppearTrigger) { _ in
  96. calculateBasals()
  97. }.onChange(of: basalProfile) { _ in
  98. calculateBasals()
  99. }
  100. }
  101. }
  102. Legend()
  103. })
  104. }
  105. }
  106. // MARK: Components
  107. extension MainChartView2 {
  108. private func MainChart() -> some View {
  109. VStack {
  110. Chart {
  111. if thresholdLines {
  112. RuleMark(y: .value("High", highGlucose)).foregroundStyle(Color.loopYellow)
  113. .lineStyle(.init(lineWidth: 1, dash: [2]))
  114. RuleMark(y: .value("Low", lowGlucose)).foregroundStyle(Color.loopRed)
  115. .lineStyle(.init(lineWidth: 1, dash: [2]))
  116. }
  117. RuleMark(
  118. x: .value(
  119. "",
  120. startMarker,
  121. unit: .second
  122. )
  123. ).foregroundStyle(.clear)
  124. RuleMark(
  125. x: .value(
  126. "",
  127. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  128. unit: .second
  129. )
  130. ).lineStyle(.init(lineWidth: 1, dash: [2]))
  131. RuleMark(
  132. x: .value(
  133. "",
  134. endMarker,
  135. unit: .second
  136. )
  137. ).foregroundStyle(.clear)
  138. ForEach(carbs) { carb in
  139. let glucose = timeToNearestGlucose(time: carb.createdAt.timeIntervalSince1970)
  140. let carbAmount = carb.carbs
  141. PointMark(
  142. x: .value("Time", carb.createdAt, unit: .second),
  143. y: .value("Value", glucose.sgv ?? 120)
  144. )
  145. .symbolSize((Config.carbsSize + CGFloat(carb.carbs) * Config.carbsScale) * 10)
  146. .foregroundStyle(Color.orange)
  147. .annotation(position: .top) {
  148. Text(bolusFormatter.string(from: carbAmount as NSNumber)!).font(.caption2)
  149. }
  150. }
  151. ForEach(boluses) { bolus in
  152. let glucose = timeToNearestGlucose(time: bolus.timestamp.timeIntervalSince1970)
  153. let bolusAmount = bolus.amount ?? 0
  154. PointMark(
  155. x: .value("Time", bolus.timestamp, unit: .second),
  156. y: .value("Value", glucose.sgv ?? 120)
  157. )
  158. .symbolSize((Config.bolusSize + CGFloat(bolus.amount ?? 0) * Config.bolusScale) * 10)
  159. .foregroundStyle(Color.insulin)
  160. .annotation(position: .bottom) {
  161. Text(bolusFormatter.string(from: bolusAmount as NSNumber)!).font(.caption2)
  162. }
  163. }
  164. ForEach(calculatePredictions(), id: \.self) { info in
  165. if info.type == .uam {
  166. LineMark(
  167. x: .value("Time", info.timestamp, unit: .second),
  168. y: .value("Value", info.amount),
  169. series: .value("uam", "uam")
  170. ).foregroundStyle(Color.uam).symbolSize(16)
  171. }
  172. if info.type == .cob {
  173. LineMark(
  174. x: .value("Time", info.timestamp, unit: .second),
  175. y: .value("Value", info.amount),
  176. series: .value("cob", "cob")
  177. ).foregroundStyle(Color.orange).symbolSize(16)
  178. }
  179. if info.type == .iob {
  180. LineMark(
  181. x: .value("Time", info.timestamp, unit: .second),
  182. y: .value("Value", info.amount),
  183. series: .value("iob", "iob")
  184. ).foregroundStyle(Color.insulin).symbolSize(16)
  185. }
  186. if info.type == .zt {
  187. LineMark(
  188. x: .value("Time", info.timestamp, unit: .second),
  189. y: .value("Value", info.amount),
  190. series: .value("zt", "zt")
  191. ).foregroundStyle(Color.zt).symbolSize(16)
  192. }
  193. }
  194. ForEach(glucose) {
  195. if $0.sgv != nil {
  196. PointMark(
  197. x: .value("Time", $0.dateString, unit: .second),
  198. y: .value("Value", $0.sgv!)
  199. ).foregroundStyle(Color.green).symbolSize(16)
  200. if smooth {
  201. LineMark(
  202. x: .value("Time", $0.dateString, unit: .second),
  203. y: .value("Value", $0.sgv!),
  204. series: .value("glucose", "glucose")
  205. ).foregroundStyle(Color.green)
  206. }
  207. }
  208. }
  209. }.id("MainChart")
  210. .frame(
  211. width: max(0, screenSize.width - 20, fullWidth(viewWidth: screenSize.width)),
  212. height: min(screenSize.height, 200)
  213. )
  214. // .chartYScale(domain: 0 ... 450)
  215. .chartXAxis {
  216. AxisMarks(values: .stride(by: .hour, count: 2)) { _ in
  217. if displayXgridLines {
  218. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  219. } else {
  220. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  221. }
  222. }
  223. }.chartYAxis {
  224. AxisMarks(position: .trailing, values: .stride(by: 100)) { value in
  225. if displayYgridLines {
  226. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  227. } else {
  228. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  229. }
  230. if let glucoseValue = value.as(Double.self), glucoseValue > 0 {
  231. AxisTick(length: 4, stroke: .init(lineWidth: 4))
  232. .foregroundStyle(Color.gray)
  233. AxisValueLabel()
  234. }
  235. }
  236. }
  237. }
  238. }
  239. func BasalChart() -> some View {
  240. VStack {
  241. Chart {
  242. RuleMark(
  243. x: .value(
  244. "",
  245. startMarker,
  246. unit: .second
  247. )
  248. ).foregroundStyle(.clear)
  249. RuleMark(
  250. x: .value(
  251. "",
  252. Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)),
  253. unit: .second
  254. )
  255. ).lineStyle(.init(lineWidth: 1, dash: [2]))
  256. RuleMark(
  257. x: .value(
  258. "",
  259. endMarker,
  260. unit: .second
  261. )
  262. ).foregroundStyle(.clear)
  263. ForEach(calculateTempBasals()) {
  264. BarMark(
  265. x: .value("Time", $0.timestamp),
  266. y: .value("Rate", $0.rate ?? 0)
  267. )
  268. }
  269. ForEach(BasalProfiles, id: \.self) { profile in
  270. LineMark(
  271. x: .value("Start Date", profile.startDate),
  272. y: .value("Amount", profile.amount),
  273. series: .value("profile", "profile")
  274. ).lineStyle(.init(lineWidth: 2, dash: [2, 3]))
  275. LineMark(
  276. x: .value("End Date", profile.endDate ?? endMarker),
  277. y: .value("Amount", profile.amount),
  278. series: .value("profile", "profile")
  279. ).lineStyle(.init(lineWidth: 2, dash: [2, 3]))
  280. }
  281. }
  282. .frame(height: 80)
  283. // .chartYScale(domain: 0 ... maxBasal)
  284. // .rotationEffect(.degrees(180))
  285. // .chartXAxis(.hidden)
  286. .chartXAxis {
  287. AxisMarks(values: .stride(by: .hour, count: screenHours == 24 ? 4 : 2)) { _ in
  288. if displayXgridLines {
  289. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  290. } else {
  291. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  292. }
  293. AxisValueLabel(format: .dateTime.hour(.defaultDigits(amPM: .narrow)), anchor: .top)
  294. }
  295. }.chartYAxis {
  296. AxisMarks(position: .trailing, values: .stride(by: 1)) { _ in
  297. if displayYgridLines {
  298. AxisGridLine(stroke: .init(lineWidth: 0.5, dash: [2, 3]))
  299. } else {
  300. AxisGridLine(stroke: .init(lineWidth: 0, dash: [2, 3]))
  301. }
  302. AxisTick(length: 30, stroke: .init(lineWidth: 4))
  303. .foregroundStyle(Color.clear)
  304. }
  305. }
  306. .chartPlotStyle { plotArea in
  307. plotArea.background(.blue.gradient.opacity(0.1))
  308. }
  309. }
  310. }
  311. private func Legend() -> some View {
  312. HStack {
  313. Image(systemName: "line.diagonal")
  314. .rotationEffect(Angle(degrees: 45))
  315. .foregroundColor(.green)
  316. Text("BG")
  317. .foregroundColor(.secondary)
  318. Spacer()
  319. Image(systemName: "line.diagonal")
  320. .rotationEffect(Angle(degrees: 45))
  321. .foregroundColor(.insulin)
  322. Text("IOB")
  323. .foregroundColor(.secondary)
  324. Spacer()
  325. Image(systemName: "line.diagonal")
  326. .rotationEffect(Angle(degrees: 45))
  327. .foregroundColor(.purple)
  328. Text("ZT")
  329. .foregroundColor(.secondary)
  330. Spacer()
  331. Image(systemName: "line.diagonal")
  332. .frame(height: 10)
  333. .rotationEffect(Angle(degrees: 45))
  334. .foregroundColor(.loopYellow)
  335. Text("COB")
  336. .foregroundColor(.secondary)
  337. Spacer()
  338. Image(systemName: "line.diagonal")
  339. .rotationEffect(Angle(degrees: 45))
  340. .foregroundColor(.orange)
  341. Text("UAM")
  342. .foregroundColor(.secondary)
  343. if eventualBG != nil {
  344. Text("⇢ " + String(eventualBG ?? 0))
  345. }
  346. }
  347. .font(.caption2)
  348. .padding(.horizontal, 40)
  349. .padding(.vertical, 1)
  350. }
  351. }
  352. // MARK: Calculations
  353. extension MainChartView2 {
  354. private func timeToNearestGlucose(time: TimeInterval) -> BloodGlucose {
  355. var nextIndex = 0
  356. if glucose.last?.dateString.timeIntervalSince1970 ?? Date().timeIntervalSince1970 < time {
  357. return glucose.last ?? BloodGlucose(
  358. date: 0,
  359. dateString: Date(),
  360. unfiltered: nil,
  361. filtered: nil,
  362. noise: nil,
  363. type: nil
  364. )
  365. }
  366. for (index, value) in glucose.enumerated() {
  367. if value.dateString.timeIntervalSince1970 > time {
  368. nextIndex = index
  369. print("Break", value.dateString.timeIntervalSince1970, time)
  370. break
  371. }
  372. print("Glucose", value.dateString.timeIntervalSince1970, time)
  373. }
  374. return glucose[nextIndex]
  375. }
  376. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  377. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  378. }
  379. private func calculatePredictions() -> [Prediction] {
  380. var calculatedPredictions: [Prediction] = []
  381. let uam = suggestion?.predictions?.uam ?? []
  382. let iob = suggestion?.predictions?.iob ?? []
  383. let cob = suggestion?.predictions?.cob ?? []
  384. let zt = suggestion?.predictions?.zt ?? []
  385. guard let deliveredAt = suggestion?.deliverAt else {
  386. return []
  387. }
  388. uam.indices.forEach { index in
  389. let predTime = Date(
  390. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  391. .timeInterval
  392. )
  393. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  394. calculatedPredictions.append(
  395. Prediction(amount: uam[index], timestamp: predTime, type: .uam)
  396. )
  397. }
  398. print(
  399. "Vergleich",
  400. index,
  401. predTime.timeIntervalSince1970,
  402. endMarker.timeIntervalSince1970,
  403. predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970
  404. )
  405. }
  406. iob.indices.forEach { index in
  407. let predTime = Date(
  408. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  409. .timeInterval
  410. )
  411. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  412. calculatedPredictions.append(
  413. Prediction(amount: iob[index], timestamp: predTime, type: .iob)
  414. )
  415. }
  416. }
  417. cob.indices.forEach { index in
  418. let predTime = Date(
  419. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  420. .timeInterval
  421. )
  422. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  423. calculatedPredictions.append(
  424. Prediction(amount: cob[index], timestamp: predTime, type: .cob)
  425. )
  426. }
  427. }
  428. zt.indices.forEach { index in
  429. let predTime = Date(
  430. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  431. .timeInterval
  432. )
  433. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  434. calculatedPredictions.append(
  435. Prediction(amount: zt[index], timestamp: predTime, type: .zt)
  436. )
  437. }
  438. }
  439. return calculatedPredictions
  440. }
  441. private func getLastUam() -> Int {
  442. let uam = suggestion?.predictions?.uam ?? []
  443. return uam.last ?? 0
  444. }
  445. private func calculateTempBasals() -> [PumpHistoryEvent] {
  446. var basals = tempBasals
  447. var returnTempBasalRates: [PumpHistoryEvent] = []
  448. var finished: [Int: Bool] = [:]
  449. basals.indices.forEach { i in
  450. basals.indices.forEach { j in
  451. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  452. let rate = basals[i].rate ?? basals[j].rate
  453. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  454. finished[i] = true
  455. if rate != 0 || durationMin != 0 {
  456. returnTempBasalRates.append(
  457. PumpHistoryEvent(
  458. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  459. timestamp: basals[i].timestamp,
  460. durationMin: durationMin,
  461. rate: rate
  462. )
  463. )
  464. }
  465. }
  466. }
  467. }
  468. print("Temp Basals", returnTempBasalRates)
  469. return returnTempBasalRates
  470. }
  471. private func findRegularBasalPoints(
  472. timeBegin: TimeInterval,
  473. timeEnd: TimeInterval,
  474. autotuned: Bool
  475. ) -> [BasalProfile] {
  476. guard timeBegin < timeEnd else {
  477. return []
  478. }
  479. let beginDate = Date(timeIntervalSince1970: timeBegin)
  480. let calendar = Calendar.current
  481. let startOfDay = calendar.startOfDay(for: beginDate)
  482. let profile = autotuned ? autotunedBasalProfile : basalProfile
  483. let basalNormalized = profile.map {
  484. (
  485. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  486. rate: $0.rate
  487. )
  488. } + profile.map {
  489. (
  490. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  491. .timeIntervalSince1970,
  492. rate: $0.rate
  493. )
  494. } + profile.map {
  495. (
  496. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  497. .timeIntervalSince1970,
  498. rate: $0.rate
  499. )
  500. }
  501. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  502. .compactMap { window -> BasalProfile? in
  503. let window = Array(window)
  504. if window[0].time < timeBegin, window[1].time < timeBegin {
  505. return nil
  506. }
  507. if window[0].time < timeBegin, window[1].time >= timeBegin {
  508. let startDate = Date(timeIntervalSince1970: timeBegin)
  509. let rate = window[0].rate
  510. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  511. }
  512. if window[0].time >= timeBegin, window[0].time < timeEnd {
  513. let startDate = Date(timeIntervalSince1970: window[0].time)
  514. let rate = window[0].rate
  515. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  516. }
  517. return nil
  518. }
  519. return basalTruncatedPoints
  520. }
  521. private func calculateBasals() {
  522. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  523. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  524. let regularPoints = findRegularBasalPoints(
  525. timeBegin: dayAgoTime,
  526. timeEnd: endMarker.timeIntervalSince1970,
  527. autotuned: false
  528. )
  529. let autotunedBasalPoints = findRegularBasalPoints(
  530. timeBegin: dayAgoTime,
  531. timeEnd: endMarker.timeIntervalSince1970,
  532. autotuned: true
  533. )
  534. var totalBasal = regularPoints + autotunedBasalPoints
  535. totalBasal.sort {
  536. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  537. }
  538. var basals: [BasalProfile] = []
  539. totalBasal.indices.forEach { index in
  540. basals.append(BasalProfile(
  541. amount: totalBasal[index].amount,
  542. isOverwritten: totalBasal[index].isOverwritten,
  543. startDate: totalBasal[index].startDate,
  544. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  545. ))
  546. print(
  547. "Basal",
  548. totalBasal[index].startDate,
  549. totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  550. totalBasal[index].amount,
  551. totalBasal[index].isOverwritten
  552. )
  553. }
  554. BasalProfiles = basals
  555. }
  556. }