MainChartView2.swift 23 KB

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