MainChartView2.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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, info.timestamp.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  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, 300)
  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. .onChange(of: basalProfile) { _ in
  351. calculcateBasals()
  352. }
  353. .onChange(of: tempBasals) { _ in
  354. calculateTempBasals()
  355. }
  356. }
  357. }
  358. // MARK: Calculations
  359. extension MainChartView2 {
  360. private func timeToNearestGlucose(time: TimeInterval) -> BloodGlucose {
  361. var nextIndex = 0
  362. if glucose.last?.dateString.timeIntervalSince1970 ?? Date().timeIntervalSince1970 < time {
  363. return glucose.last ?? BloodGlucose(
  364. date: 0,
  365. dateString: Date(),
  366. unfiltered: nil,
  367. filtered: nil,
  368. noise: nil,
  369. type: nil
  370. )
  371. }
  372. for (index, value) in glucose.enumerated() {
  373. if value.dateString.timeIntervalSince1970 > time {
  374. nextIndex = index
  375. print("Break", value.dateString.timeIntervalSince1970, time)
  376. break
  377. }
  378. print("Glucose", value.dateString.timeIntervalSince1970, time)
  379. }
  380. return glucose[nextIndex]
  381. }
  382. private func fullWidth(viewWidth: CGFloat) -> CGFloat {
  383. viewWidth * CGFloat(hours) / CGFloat(min(max(screenHours, 2), 24))
  384. }
  385. private func calculatePredictions() -> [Prediction] {
  386. var calculatedPredictions: [Prediction] = []
  387. let uam = suggestion?.predictions?.uam ?? []
  388. let iob = suggestion?.predictions?.iob ?? []
  389. let cob = suggestion?.predictions?.cob ?? []
  390. let zt = suggestion?.predictions?.zt ?? []
  391. guard let deliveredAt = suggestion?.deliverAt else {
  392. return []
  393. }
  394. uam.indices.forEach { index in
  395. let predTime = Date(
  396. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  397. .timeInterval
  398. )
  399. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  400. calculatedPredictions.append(
  401. Prediction(amount: uam[index], timestamp: predTime, type: .uam)
  402. )
  403. }
  404. print(
  405. "Vergleich",
  406. index,
  407. predTime.timeIntervalSince1970,
  408. endMarker.timeIntervalSince1970,
  409. predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970
  410. )
  411. }
  412. iob.indices.forEach { index in
  413. let predTime = Date(
  414. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  415. .timeInterval
  416. )
  417. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  418. calculatedPredictions.append(
  419. Prediction(amount: iob[index], timestamp: predTime, type: .iob)
  420. )
  421. }
  422. }
  423. cob.indices.forEach { index in
  424. let predTime = Date(
  425. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  426. .timeInterval
  427. )
  428. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  429. calculatedPredictions.append(
  430. Prediction(amount: cob[index], timestamp: predTime, type: .cob)
  431. )
  432. }
  433. }
  434. zt.indices.forEach { index in
  435. let predTime = Date(
  436. timeIntervalSince1970: deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes
  437. .timeInterval
  438. )
  439. if predTime.timeIntervalSince1970 < endMarker.timeIntervalSince1970 {
  440. calculatedPredictions.append(
  441. Prediction(amount: zt[index], timestamp: predTime, type: .zt)
  442. )
  443. }
  444. }
  445. return calculatedPredictions
  446. }
  447. private func getLastUam() -> Int {
  448. let uam = suggestion?.predictions?.uam ?? []
  449. return uam.last ?? 0
  450. }
  451. private func calculateTempBasals() -> [PumpHistoryEvent] {
  452. var basals = tempBasals
  453. var returnTempBasalRates: [PumpHistoryEvent] = []
  454. var finished: [Int: Bool] = [:]
  455. basals.indices.forEach { i in
  456. basals.indices.forEach { j in
  457. if basals[i].timestamp == basals[j].timestamp, i != j, !(finished[i] ?? false), !(finished[j] ?? false) {
  458. let rate = basals[i].rate ?? basals[j].rate
  459. let durationMin = basals[i].durationMin ?? basals[j].durationMin
  460. finished[i] = true
  461. if rate != 0 || durationMin != 0 {
  462. returnTempBasalRates.append(
  463. PumpHistoryEvent(
  464. id: basals[i].id, type: FreeAPS.EventType.tempBasal,
  465. timestamp: basals[i].timestamp,
  466. durationMin: durationMin,
  467. rate: rate
  468. )
  469. )
  470. }
  471. }
  472. }
  473. }
  474. print("Temp Basals", returnTempBasalRates)
  475. return returnTempBasalRates
  476. }
  477. private func findRegularBasalPoints(
  478. timeBegin: TimeInterval,
  479. timeEnd: TimeInterval,
  480. autotuned: Bool
  481. ) -> [BasalProfile] {
  482. guard timeBegin < timeEnd else {
  483. return []
  484. }
  485. let beginDate = Date(timeIntervalSince1970: timeBegin)
  486. let calendar = Calendar.current
  487. let startOfDay = calendar.startOfDay(for: beginDate)
  488. let profile = autotuned ? autotunedBasalProfile : basalProfile
  489. let basalNormalized = profile.map {
  490. (
  491. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  492. rate: $0.rate
  493. )
  494. } + profile.map {
  495. (
  496. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval)
  497. .timeIntervalSince1970,
  498. rate: $0.rate
  499. )
  500. } + profile.map {
  501. (
  502. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval)
  503. .timeIntervalSince1970,
  504. rate: $0.rate
  505. )
  506. }
  507. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  508. .compactMap { window -> BasalProfile? in
  509. let window = Array(window)
  510. if window[0].time < timeBegin, window[1].time < timeBegin {
  511. return nil
  512. }
  513. if window[0].time < timeBegin, window[1].time >= timeBegin {
  514. let startDate = Date(timeIntervalSince1970: timeBegin)
  515. let rate = window[0].rate
  516. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  517. }
  518. if window[0].time >= timeBegin, window[0].time < timeEnd {
  519. let startDate = Date(timeIntervalSince1970: window[0].time)
  520. let rate = window[0].rate
  521. return BasalProfile(amount: Double(rate), isOverwritten: false, startDate: startDate)
  522. }
  523. return nil
  524. }
  525. return basalTruncatedPoints
  526. }
  527. private func calculcateBasals() {
  528. private func calculateBasals() {
  529. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  530. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  531. let regularPoints = findRegularBasalPoints(
  532. timeBegin: dayAgoTime,
  533. timeEnd: endMarker.timeIntervalSince1970,
  534. autotuned: false
  535. )
  536. let autotunedBasalPoints = findRegularBasalPoints(
  537. timeBegin: dayAgoTime,
  538. timeEnd: endMarker.timeIntervalSince1970,
  539. autotuned: true
  540. )
  541. var totalBasal = regularPoints + autotunedBasalPoints
  542. totalBasal.sort {
  543. $0.startDate.timeIntervalSince1970 < $1.startDate.timeIntervalSince1970
  544. }
  545. var basals: [BasalProfile] = []
  546. totalBasal.indices.forEach { index in
  547. basals.append(BasalProfile(
  548. amount: totalBasal[index].amount,
  549. isOverwritten: totalBasal[index].isOverwritten,
  550. startDate: totalBasal[index].startDate,
  551. endDate: totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker
  552. ))
  553. print(
  554. "Basal",
  555. totalBasal[index].startDate,
  556. totalBasal.count > index + 1 ? totalBasal[index + 1].startDate : endMarker,
  557. totalBasal[index].amount,
  558. totalBasal[index].isOverwritten
  559. )
  560. }
  561. BasalProfiles = basals
  562. }
  563. }