MainChartView2.swift 23 KB

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