MainChartView2.swift 23 KB

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