MainChartView.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  1. import Algorithms
  2. import SwiftDate
  3. import SwiftUI
  4. private enum PredictionType: Hashable {
  5. case iob
  6. case cob
  7. case zt
  8. case uam
  9. }
  10. struct DotInfo {
  11. let rect: CGRect
  12. let value: Decimal
  13. }
  14. typealias GlucoseYRange = (minValue: Int, minY: CGFloat, maxValue: Int, maxY: CGFloat)
  15. struct MainChartView: View {
  16. private enum Config {
  17. static let endID = "End"
  18. static let screenHours = 6
  19. static let basalHeight: CGFloat = 80
  20. static let topYPadding: CGFloat = 20
  21. static let bottomYPadding: CGFloat = 50
  22. static let minAdditionalWidth: CGFloat = 150
  23. static let maxGlucose = 250
  24. static let minGlucose = 50
  25. static let yLinesCount = 5
  26. static let glucoseScale: CGFloat = 2 // default 2
  27. static let bolusSize: CGFloat = 8
  28. static let bolusScale: CGFloat = 2.5
  29. static let carbsSize: CGFloat = 10
  30. static let carbsScale: CGFloat = 0.3
  31. static let upperTarget: CGFloat = 180
  32. static let lowerTarget: CGFloat = 70
  33. }
  34. @Binding var glucose: [BloodGlucose]
  35. @Binding var suggestion: Suggestion?
  36. @Binding var statistcs: Statistics?
  37. @Binding var tempBasals: [PumpHistoryEvent]
  38. @Binding var boluses: [PumpHistoryEvent]
  39. @Binding var suspensions: [PumpHistoryEvent]
  40. @Binding var hours: Int
  41. @Binding var maxBasal: Decimal
  42. @Binding var autotunedBasalProfile: [BasalProfileEntry]
  43. @Binding var basalProfile: [BasalProfileEntry]
  44. @Binding var tempTargets: [TempTarget]
  45. @Binding var carbs: [CarbsEntry]
  46. @Binding var timerDate: Date
  47. @Binding var units: GlucoseUnits
  48. @State var didAppearTrigger = false
  49. @State private var glucoseDots: [CGRect] = []
  50. @State private var predictionDots: [PredictionType: [CGRect]] = [:]
  51. @State private var bolusDots: [DotInfo] = []
  52. @State private var bolusPath = Path()
  53. @State private var tempBasalPath = Path()
  54. @State private var regularBasalPath = Path()
  55. @State private var tempTargetsPath = Path()
  56. @State private var suspensionsPath = Path()
  57. @State private var carbsDots: [DotInfo] = []
  58. @State private var carbsPath = Path()
  59. @State private var glucoseYGange: GlucoseYRange = (0, 0, 0, 0)
  60. @State private var offset: CGFloat = 0
  61. @State private var cachedMaxBasalRate: Decimal?
  62. private let calculationQueue = DispatchQueue(label: "MainChartView.calculationQueue")
  63. private var dateFormatter: DateFormatter {
  64. let formatter = DateFormatter()
  65. formatter.timeStyle = .short
  66. return formatter
  67. }
  68. private var glucoseFormatter: NumberFormatter {
  69. let formatter = NumberFormatter()
  70. formatter.numberStyle = .decimal
  71. formatter.maximumFractionDigits = 1
  72. return formatter
  73. }
  74. private var bolusFormatter: NumberFormatter {
  75. let formatter = NumberFormatter()
  76. formatter.numberStyle = .decimal
  77. formatter.minimumIntegerDigits = 0
  78. formatter.maximumFractionDigits = 2
  79. formatter.decimalSeparator = "."
  80. return formatter
  81. }
  82. private var carbsFormatter: NumberFormatter {
  83. let formatter = NumberFormatter()
  84. formatter.numberStyle = .decimal
  85. formatter.maximumFractionDigits = 0
  86. return formatter
  87. }
  88. @Environment(\.horizontalSizeClass) var hSizeClass
  89. @Environment(\.verticalSizeClass) var vSizeClass
  90. // MARK: - Views
  91. var body: some View {
  92. GeometryReader { geo in
  93. ZStack(alignment: .leading) {
  94. yGridView(fullSize: geo.size)
  95. mainScrollView(fullSize: geo.size)
  96. glucoseLabelsView(fullSize: geo.size)
  97. }
  98. .onChange(of: hSizeClass) { _ in
  99. update(fullSize: geo.size)
  100. }
  101. .onChange(of: vSizeClass) { _ in
  102. update(fullSize: geo.size)
  103. }
  104. .onReceive(
  105. Foundation.NotificationCenter.default
  106. .publisher(for: UIDevice.orientationDidChangeNotification)
  107. ) { _ in
  108. update(fullSize: geo.size)
  109. }
  110. }
  111. }
  112. private func mainScrollView(fullSize: CGSize) -> some View {
  113. ScrollView(.horizontal, showsIndicators: false) {
  114. ScrollViewReader { scroll in
  115. ZStack(alignment: .top) {
  116. tempTargetsView(fullSize: fullSize).drawingGroup()
  117. basalView(fullSize: fullSize).drawingGroup()
  118. mainView(fullSize: fullSize).id(Config.endID)
  119. .drawingGroup()
  120. .onChange(of: glucose) { _ in
  121. scroll.scrollTo(Config.endID, anchor: .trailing)
  122. }
  123. .onChange(of: suggestion) { _ in
  124. scroll.scrollTo(Config.endID, anchor: .trailing)
  125. }
  126. .onChange(of: tempBasals) { _ in
  127. scroll.scrollTo(Config.endID, anchor: .trailing)
  128. }
  129. .onAppear {
  130. // add trigger to the end of main queue
  131. DispatchQueue.main.async {
  132. scroll.scrollTo(Config.endID, anchor: .trailing)
  133. didAppearTrigger = true
  134. }
  135. }
  136. }
  137. }
  138. }
  139. }
  140. private func yGridView(fullSize: CGSize) -> some View {
  141. ZStack {
  142. Path { path in
  143. let range = glucoseYGange
  144. let step = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  145. for line in 0 ... Config.yLinesCount {
  146. path.move(to: CGPoint(x: 0, y: range.minY + CGFloat(line) * step))
  147. path.addLine(to: CGPoint(x: fullSize.width, y: range.minY + CGFloat(line) * step))
  148. }
  149. }.stroke(Color.secondary, lineWidth: 0.2)
  150. // horizontal limits
  151. let range = glucoseYGange
  152. let topstep = (range.maxY - range.minY) / CGFloat(range.maxValue - range.minValue) *
  153. (CGFloat(range.maxValue) - Config.upperTarget)
  154. if CGFloat(range.maxValue) > Config.upperTarget {
  155. Path { path in
  156. path.move(to: CGPoint(x: 0, y: range.minY + topstep))
  157. path.addLine(to: CGPoint(x: fullSize.width, y: range.minY + topstep))
  158. }.stroke(Color.loopYellow, lineWidth: 0.5)
  159. }
  160. let yrange = glucoseYGange
  161. let bottomstep = (yrange.maxY - yrange.minY) / CGFloat(yrange.maxValue - yrange.minValue) *
  162. (CGFloat(yrange.maxValue) - Config.lowerTarget)
  163. if CGFloat(yrange.minValue) < Config.lowerTarget {
  164. Path { path in
  165. path.move(to: CGPoint(x: 0, y: yrange.minY + bottomstep))
  166. path.addLine(to: CGPoint(x: fullSize.width, y: yrange.minY + bottomstep))
  167. }.stroke(Color.loopRed, lineWidth: 0.5)
  168. }
  169. }
  170. }
  171. private func glucoseLabelsView(fullSize: CGSize) -> some View {
  172. ForEach(0 ..< Config.yLinesCount + 1, id: \.self) { line -> AnyView in
  173. let range = glucoseYGange
  174. let yStep = (range.maxY - range.minY) / CGFloat(Config.yLinesCount)
  175. let valueStep = Double(range.maxValue - range.minValue) / Double(Config.yLinesCount)
  176. let value = round(Double(range.maxValue) - Double(line) * valueStep) *
  177. (units == .mmolL ? Double(GlucoseUnits.exchangeRate) : 1)
  178. return Text(glucoseFormatter.string(from: value as NSNumber)!)
  179. .position(CGPoint(x: fullSize.width - 12, y: range.minY + CGFloat(line) * yStep))
  180. .font(.caption2)
  181. .asAny()
  182. }
  183. }
  184. private func basalView(fullSize: CGSize) -> some View {
  185. ZStack {
  186. tempBasalPath.fill(Color.basal.opacity(0.5))
  187. tempBasalPath.stroke(Color.insulin, lineWidth: 1)
  188. regularBasalPath.stroke(Color.insulin, style: StrokeStyle(lineWidth: 0.7, dash: [4]))
  189. suspensionsPath.stroke(Color.loopGray.opacity(0.7), style: StrokeStyle(lineWidth: 0.7)).scaleEffect(x: 1, y: -1)
  190. suspensionsPath.fill(Color.loopGray.opacity(0.2)).scaleEffect(x: 1, y: -1)
  191. }
  192. .scaleEffect(x: 1, y: -1)
  193. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  194. .frame(maxHeight: Config.basalHeight)
  195. .background(Color.secondary.opacity(0.1))
  196. .onChange(of: tempBasals) { _ in
  197. calculateBasalPoints(fullSize: fullSize)
  198. }
  199. .onChange(of: suspensions) { _ in
  200. calculateSuspensions(fullSize: fullSize)
  201. }
  202. .onChange(of: maxBasal) { _ in
  203. calculateBasalPoints(fullSize: fullSize)
  204. }
  205. .onChange(of: autotunedBasalProfile) { _ in
  206. calculateBasalPoints(fullSize: fullSize)
  207. }
  208. .onChange(of: didAppearTrigger) { _ in
  209. calculateBasalPoints(fullSize: fullSize)
  210. }
  211. }
  212. private func mainView(fullSize: CGSize) -> some View {
  213. Group {
  214. VStack {
  215. ZStack {
  216. xGridView(fullSize: fullSize)
  217. carbsView(fullSize: fullSize)
  218. bolusView(fullSize: fullSize)
  219. glucoseView(fullSize: fullSize)
  220. predictionsView(fullSize: fullSize)
  221. }
  222. timeLabelsView(fullSize: fullSize)
  223. }
  224. }
  225. .frame(width: fullGlucoseWidth(viewWidth: fullSize.width) + additionalWidth(viewWidth: fullSize.width))
  226. }
  227. @Environment(\.colorScheme) var colorScheme
  228. private func xGridView(fullSize: CGSize) -> some View {
  229. ZStack {
  230. Path { path in
  231. for hour in 0 ..< hours + hours {
  232. let x = firstHourPosition(viewWidth: fullSize.width) +
  233. oneSecondStep(viewWidth: fullSize.width) *
  234. CGFloat(hour) * CGFloat(1.hours.timeInterval)
  235. path.move(to: CGPoint(x: x, y: 0))
  236. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  237. }
  238. }
  239. .stroke(Color.secondary, lineWidth: 0.2)
  240. Path { path in // vertical timeline
  241. let x = timeToXCoordinate(timerDate.timeIntervalSince1970, fullSize: fullSize)
  242. path.move(to: CGPoint(x: x, y: 0))
  243. path.addLine(to: CGPoint(x: x, y: fullSize.height - 20))
  244. }
  245. .stroke(
  246. colorScheme == .dark ? Color.white : Color.black,
  247. style: StrokeStyle(lineWidth: 0.5, dash: [5])
  248. )
  249. }
  250. }
  251. private func timeLabelsView(fullSize: CGSize) -> some View {
  252. ZStack {
  253. // X time labels
  254. ForEach(0 ..< hours + hours) { hour in
  255. Text(dateFormatter.string(from: firstHourDate().addingTimeInterval(hour.hours.timeInterval)))
  256. .font(.caption)
  257. .position(
  258. x: firstHourPosition(viewWidth: fullSize.width) +
  259. oneSecondStep(viewWidth: fullSize.width) *
  260. CGFloat(hour) * CGFloat(1.hours.timeInterval),
  261. y: 10.0
  262. )
  263. .foregroundColor(.secondary)
  264. }
  265. }.frame(maxHeight: 20)
  266. }
  267. private func glucoseView(fullSize: CGSize) -> some View {
  268. Path { path in
  269. for rect in glucoseDots {
  270. path.addEllipse(in: rect)
  271. }
  272. }
  273. .fill(Color.loopGreen)
  274. .onChange(of: glucose) { _ in
  275. update(fullSize: fullSize)
  276. }
  277. .onChange(of: didAppearTrigger) { _ in
  278. update(fullSize: fullSize)
  279. }
  280. .onReceive(Foundation.NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
  281. update(fullSize: fullSize)
  282. }
  283. }
  284. private func bolusView(fullSize: CGSize) -> some View {
  285. ZStack {
  286. bolusPath
  287. .fill(Color.insulin)
  288. bolusPath
  289. .stroke(Color.primary, lineWidth: 0.5)
  290. ForEach(bolusDots, id: \.rect.minX) { info -> AnyView in
  291. let position = CGPoint(x: info.rect.midX, y: info.rect.maxY + 8)
  292. return Text(bolusFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  293. .position(position)
  294. .asAny()
  295. }
  296. }
  297. .onChange(of: boluses) { _ in
  298. calculateBolusDots(fullSize: fullSize)
  299. }
  300. .onChange(of: didAppearTrigger) { _ in
  301. calculateBolusDots(fullSize: fullSize)
  302. }
  303. }
  304. private func carbsView(fullSize: CGSize) -> some View {
  305. ZStack {
  306. carbsPath
  307. .fill(Color.loopYellow)
  308. carbsPath
  309. .stroke(Color.primary, lineWidth: 0.5)
  310. ForEach(carbsDots, id: \.rect.minX) { info -> AnyView in
  311. let position = CGPoint(x: info.rect.midX, y: info.rect.minY - 8)
  312. return Text(carbsFormatter.string(from: info.value as NSNumber)!).font(.caption2)
  313. .position(position)
  314. .asAny()
  315. }
  316. }
  317. .onChange(of: carbs) { _ in
  318. calculateCarbsDots(fullSize: fullSize)
  319. }
  320. .onChange(of: didAppearTrigger) { _ in
  321. calculateCarbsDots(fullSize: fullSize)
  322. }
  323. }
  324. private func tempTargetsView(fullSize: CGSize) -> some View {
  325. ZStack {
  326. tempTargetsPath
  327. .fill(Color.tempBasal.opacity(0.5))
  328. tempTargetsPath
  329. .stroke(Color.basal.opacity(0.5), lineWidth: 1)
  330. }
  331. .onChange(of: glucose) { _ in
  332. calculateTempTargetsRects(fullSize: fullSize)
  333. }
  334. .onChange(of: tempTargets) { _ in
  335. calculateTempTargetsRects(fullSize: fullSize)
  336. }
  337. .onChange(of: didAppearTrigger) { _ in
  338. calculateTempTargetsRects(fullSize: fullSize)
  339. }
  340. }
  341. private func predictionsView(fullSize: CGSize) -> some View {
  342. Group {
  343. Path { path in
  344. for rect in predictionDots[.iob] ?? [] {
  345. path.addEllipse(in: rect)
  346. }
  347. }.fill(Color.insulin)
  348. Path { path in
  349. for rect in predictionDots[.cob] ?? [] {
  350. path.addEllipse(in: rect)
  351. }
  352. }.fill(Color.loopYellow)
  353. Path { path in
  354. for rect in predictionDots[.zt] ?? [] {
  355. path.addEllipse(in: rect)
  356. }
  357. }.fill(Color.zt)
  358. Path { path in
  359. for rect in predictionDots[.uam] ?? [] {
  360. path.addEllipse(in: rect)
  361. }
  362. }.fill(Color.uam)
  363. }
  364. .onChange(of: suggestion) { _ in
  365. update(fullSize: fullSize)
  366. }
  367. }
  368. }
  369. // MARK: - Calculations
  370. extension MainChartView {
  371. private func update(fullSize: CGSize) {
  372. calculatePredictionDots(fullSize: fullSize, type: .iob)
  373. calculatePredictionDots(fullSize: fullSize, type: .cob)
  374. calculatePredictionDots(fullSize: fullSize, type: .zt)
  375. calculatePredictionDots(fullSize: fullSize, type: .uam)
  376. calculateGlucoseDots(fullSize: fullSize)
  377. calculateBolusDots(fullSize: fullSize)
  378. calculateCarbsDots(fullSize: fullSize)
  379. calculateTempTargetsRects(fullSize: fullSize)
  380. calculateBasalPoints(fullSize: fullSize)
  381. calculateSuspensions(fullSize: fullSize)
  382. }
  383. private func calculateGlucoseDots(fullSize: CGSize) {
  384. calculationQueue.async {
  385. let dots = glucose.concurrentMap { value -> CGRect in
  386. let position = glucoseToCoordinate(value, fullSize: fullSize)
  387. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  388. }
  389. let range = self.getGlucoseYRange(fullSize: fullSize)
  390. DispatchQueue.main.async {
  391. glucoseYGange = range
  392. glucoseDots = dots
  393. }
  394. }
  395. }
  396. private func calculateBolusDots(fullSize: CGSize) {
  397. calculationQueue.async {
  398. let dots = boluses.map { value -> DotInfo in
  399. let center = timeToInterpolatedPoint(value.timestamp.timeIntervalSince1970, fullSize: fullSize)
  400. let size = Config.bolusSize + CGFloat(value.amount ?? 0) * Config.bolusScale
  401. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  402. return DotInfo(rect: rect, value: value.amount ?? 0)
  403. }
  404. let path = Path { path in
  405. for dot in dots {
  406. path.addEllipse(in: dot.rect)
  407. }
  408. }
  409. DispatchQueue.main.async {
  410. bolusDots = dots
  411. bolusPath = path
  412. }
  413. }
  414. }
  415. private func calculateCarbsDots(fullSize: CGSize) {
  416. calculationQueue.async {
  417. let dots = carbs.map { value -> DotInfo in
  418. let center = timeToInterpolatedPoint(value.createdAt.timeIntervalSince1970, fullSize: fullSize)
  419. let size = Config.carbsSize + CGFloat(value.carbs) * Config.carbsScale
  420. let rect = CGRect(x: center.x - size / 2, y: center.y - size / 2, width: size, height: size)
  421. return DotInfo(rect: rect, value: value.carbs)
  422. }
  423. let path = Path { path in
  424. for dot in dots {
  425. path.addEllipse(in: dot.rect)
  426. }
  427. }
  428. DispatchQueue.main.async {
  429. carbsDots = dots
  430. carbsPath = path
  431. }
  432. }
  433. }
  434. private func calculatePredictionDots(fullSize: CGSize, type: PredictionType) {
  435. calculationQueue.async {
  436. let values: [Int] = { () -> [Int] in
  437. switch type {
  438. case .iob:
  439. return suggestion?.predictions?.iob ?? []
  440. case .cob:
  441. return suggestion?.predictions?.cob ?? []
  442. case .zt:
  443. return suggestion?.predictions?.zt ?? []
  444. case .uam:
  445. return suggestion?.predictions?.uam ?? []
  446. }
  447. }()
  448. var index = 0
  449. let dots = values.map { value -> CGRect in
  450. let position = predictionToCoordinate(value, fullSize: fullSize, index: index)
  451. index += 1
  452. return CGRect(x: position.x - 2, y: position.y - 2, width: 4, height: 4)
  453. }
  454. DispatchQueue.main.async {
  455. predictionDots[type] = dots
  456. }
  457. }
  458. }
  459. private func calculateBasalPoints(fullSize: CGSize) {
  460. calculationQueue.async {
  461. self.cachedMaxBasalRate = nil
  462. let dayAgoTime = Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  463. let firstTempTime = (tempBasals.first?.timestamp ?? Date()).timeIntervalSince1970
  464. var lastTimeEnd = firstTempTime
  465. let firstRegularBasalPoints = findRegularBasalPoints(
  466. timeBegin: dayAgoTime,
  467. timeEnd: firstTempTime,
  468. fullSize: fullSize,
  469. autotuned: false
  470. )
  471. let tempBasalPoints = firstRegularBasalPoints + tempBasals.chunks(ofCount: 2).map { chunk -> [CGPoint] in
  472. let chunk = Array(chunk)
  473. guard chunk.count == 2, chunk[0].type == .tempBasal, chunk[1].type == .tempBasalDuration else { return [] }
  474. let timeBegin = chunk[0].timestamp.timeIntervalSince1970
  475. let timeEnd = timeBegin + (chunk[1].durationMin ?? 0).minutes.timeInterval
  476. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  477. let x0 = timeToXCoordinate(timeBegin, fullSize: fullSize)
  478. let y0 = Config.basalHeight - CGFloat(chunk[0].rate ?? 0) * rateCost
  479. let regularPoints = findRegularBasalPoints(
  480. timeBegin: lastTimeEnd,
  481. timeEnd: timeBegin,
  482. fullSize: fullSize,
  483. autotuned: false
  484. )
  485. lastTimeEnd = timeEnd
  486. return regularPoints + [CGPoint(x: x0, y: y0)]
  487. }.flatMap { $0 }
  488. let tempBasalPath = Path { path in
  489. var yPoint: CGFloat = Config.basalHeight
  490. path.move(to: CGPoint(x: 0, y: yPoint))
  491. for point in tempBasalPoints {
  492. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  493. path.addLine(to: point)
  494. yPoint = point.y
  495. }
  496. let lastPoint = lastBasalPoint(fullSize: fullSize)
  497. path.addLine(to: CGPoint(x: lastPoint.x, y: yPoint))
  498. path.addLine(to: CGPoint(x: lastPoint.x, y: Config.basalHeight))
  499. path.addLine(to: CGPoint(x: 0, y: Config.basalHeight))
  500. }
  501. let endDateTime = dayAgoTime + 1.days.timeInterval + 6.hours.timeInterval
  502. let autotunedBasalPoints = findRegularBasalPoints(
  503. timeBegin: dayAgoTime,
  504. timeEnd: endDateTime,
  505. fullSize: fullSize,
  506. autotuned: true
  507. )
  508. let autotunedBasalPath = Path { path in
  509. var yPoint: CGFloat = Config.basalHeight
  510. path.move(to: CGPoint(x: -50, y: yPoint))
  511. for point in autotunedBasalPoints {
  512. path.addLine(to: CGPoint(x: point.x, y: yPoint))
  513. path.addLine(to: point)
  514. yPoint = point.y
  515. }
  516. path.addLine(to: CGPoint(x: timeToXCoordinate(endDateTime, fullSize: fullSize), y: yPoint))
  517. }
  518. DispatchQueue.main.async {
  519. self.tempBasalPath = tempBasalPath
  520. self.regularBasalPath = autotunedBasalPath
  521. }
  522. }
  523. }
  524. private func calculateSuspensions(fullSize: CGSize) {
  525. calculationQueue.async {
  526. var rects = suspensions.windows(ofCount: 2).map { window -> CGRect? in
  527. let window = Array(window)
  528. guard window[0].type == .pumpSuspend, window[1].type == .pumpResume else { return nil }
  529. let x0 = self.timeToXCoordinate(window[0].timestamp.timeIntervalSince1970, fullSize: fullSize)
  530. let x1 = self.timeToXCoordinate(window[1].timestamp.timeIntervalSince1970, fullSize: fullSize)
  531. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  532. }
  533. let firstRec = self.suspensions.first.flatMap { event -> CGRect? in
  534. guard event.type == .pumpResume else { return nil }
  535. let tbrTime = self.tempBasals.last { $0.timestamp < event.timestamp }
  536. .map { $0.timestamp.timeIntervalSince1970 + TimeInterval($0.durationMin ?? 0) * 60 } ?? Date()
  537. .addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  538. let x0 = self.timeToXCoordinate(tbrTime, fullSize: fullSize)
  539. let x1 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  540. return CGRect(
  541. x: x0,
  542. y: 0,
  543. width: x1 - x0,
  544. height: Config.basalHeight * 0.7
  545. )
  546. }
  547. let lastRec = self.suspensions.last.flatMap { event -> CGRect? in
  548. guard event.type == .pumpSuspend else { return nil }
  549. let tbrTimeX = self.tempBasals.first { $0.timestamp > event.timestamp }
  550. .map { self.timeToXCoordinate($0.timestamp.timeIntervalSince1970, fullSize: fullSize) }
  551. let x0 = self.timeToXCoordinate(event.timestamp.timeIntervalSince1970, fullSize: fullSize)
  552. let x1 = tbrTimeX ?? self.fullGlucoseWidth(viewWidth: fullSize.width) + self
  553. .additionalWidth(viewWidth: fullSize.width)
  554. return CGRect(x: x0, y: 0, width: x1 - x0, height: Config.basalHeight * 0.7)
  555. }
  556. rects.append(firstRec)
  557. rects.append(lastRec)
  558. let path = Path { path in
  559. path.addRects(rects.compactMap { $0 })
  560. }
  561. DispatchQueue.main.async {
  562. suspensionsPath = path
  563. }
  564. }
  565. }
  566. private func maxBasalRate() -> Decimal {
  567. if let cached = cachedMaxBasalRate {
  568. return cached
  569. }
  570. let maxRegularBasalRate = max(
  571. basalProfile.map(\.rate).max() ?? maxBasal,
  572. autotunedBasalProfile.map(\.rate).max() ?? maxBasal
  573. )
  574. var maxTempBasalRate = tempBasals.compactMap(\.rate).max() ?? maxRegularBasalRate
  575. if maxTempBasalRate == 0 {
  576. maxTempBasalRate = maxRegularBasalRate
  577. }
  578. cachedMaxBasalRate = max(maxTempBasalRate, maxRegularBasalRate)
  579. return cachedMaxBasalRate ?? maxBasal
  580. }
  581. private func calculateTempTargetsRects(fullSize: CGSize) {
  582. calculationQueue.async {
  583. var rects = tempTargets.map { tempTarget -> CGRect in
  584. let x0 = timeToXCoordinate(tempTarget.createdAt.timeIntervalSince1970, fullSize: fullSize)
  585. let y0 = glucoseToYCoordinate(Int(tempTarget.targetTop ?? 0), fullSize: fullSize)
  586. let x1 = timeToXCoordinate(
  587. tempTarget.createdAt.timeIntervalSince1970 + Int(tempTarget.duration).minutes.timeInterval,
  588. fullSize: fullSize
  589. )
  590. let y1 = glucoseToYCoordinate(Int(tempTarget.targetBottom ?? 0), fullSize: fullSize)
  591. return CGRect(
  592. x: x0,
  593. y: y0 - 3,
  594. width: x1 - x0,
  595. height: y1 - y0 + 6
  596. )
  597. }
  598. if rects.count > 1 {
  599. rects = rects.reduce([]) { result, rect -> [CGRect] in
  600. guard var last = result.last else { return [rect] }
  601. if last.origin.x + last.width > rect.origin.x {
  602. last.size.width = rect.origin.x - last.origin.x
  603. }
  604. var res = Array(result.dropLast())
  605. res.append(contentsOf: [last, rect])
  606. return res
  607. }
  608. }
  609. let path = Path { path in
  610. path.addRects(rects)
  611. }
  612. DispatchQueue.main.async {
  613. tempTargetsPath = path
  614. }
  615. }
  616. }
  617. private func findRegularBasalPoints(
  618. timeBegin: TimeInterval,
  619. timeEnd: TimeInterval,
  620. fullSize: CGSize,
  621. autotuned: Bool
  622. ) -> [CGPoint] {
  623. guard timeBegin < timeEnd else {
  624. return []
  625. }
  626. let beginDate = Date(timeIntervalSince1970: timeBegin)
  627. let calendar = Calendar.current
  628. let startOfDay = calendar.startOfDay(for: beginDate)
  629. let profile = autotuned ? autotunedBasalProfile : basalProfile
  630. let basalNormalized = profile.map {
  631. (
  632. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval).timeIntervalSince1970,
  633. rate: $0.rate
  634. )
  635. } + profile.map {
  636. (
  637. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 1.days.timeInterval).timeIntervalSince1970,
  638. rate: $0.rate
  639. )
  640. } + profile.map {
  641. (
  642. time: startOfDay.addingTimeInterval($0.minutes.minutes.timeInterval + 2.days.timeInterval).timeIntervalSince1970,
  643. rate: $0.rate
  644. )
  645. }
  646. let basalTruncatedPoints = basalNormalized.windows(ofCount: 2)
  647. .compactMap { window -> CGPoint? in
  648. let window = Array(window)
  649. if window[0].time < timeBegin, window[1].time < timeBegin {
  650. return nil
  651. }
  652. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  653. if window[0].time < timeBegin, window[1].time >= timeBegin {
  654. let x = timeToXCoordinate(timeBegin, fullSize: fullSize)
  655. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  656. return CGPoint(x: x, y: y)
  657. }
  658. if window[0].time >= timeBegin, window[0].time < timeEnd {
  659. let x = timeToXCoordinate(window[0].time, fullSize: fullSize)
  660. let y = Config.basalHeight - CGFloat(window[0].rate) * rateCost
  661. return CGPoint(x: x, y: y)
  662. }
  663. return nil
  664. }
  665. return basalTruncatedPoints
  666. }
  667. private func lastBasalPoint(fullSize: CGSize) -> CGPoint {
  668. let lastBasal = Array(tempBasals.suffix(2))
  669. guard lastBasal.count == 2 else {
  670. return CGPoint(x: timeToXCoordinate(Date().timeIntervalSince1970, fullSize: fullSize), y: Config.basalHeight)
  671. }
  672. let endBasalTime = lastBasal[0].timestamp.timeIntervalSince1970 + (lastBasal[1].durationMin?.minutes.timeInterval ?? 0)
  673. let rateCost = Config.basalHeight / CGFloat(maxBasalRate())
  674. let x = timeToXCoordinate(endBasalTime, fullSize: fullSize)
  675. let y = Config.basalHeight - CGFloat(lastBasal[0].rate ?? 0) * rateCost
  676. return CGPoint(x: x, y: y)
  677. }
  678. private func fullGlucoseWidth(viewWidth: CGFloat) -> CGFloat {
  679. viewWidth * CGFloat(hours) / CGFloat(Config.screenHours)
  680. }
  681. private func additionalWidth(viewWidth: CGFloat) -> CGFloat {
  682. guard let predictions = suggestion?.predictions,
  683. let deliveredAt = suggestion?.deliverAt,
  684. let last = glucose.last
  685. else {
  686. return Config.minAdditionalWidth
  687. }
  688. let iob = predictions.iob?.count ?? 0
  689. let zt = predictions.zt?.count ?? 0
  690. let cob = predictions.cob?.count ?? 0
  691. let uam = predictions.uam?.count ?? 0
  692. let max = [iob, zt, cob, uam].max() ?? 0
  693. let lastDeltaTime = last.dateString.timeIntervalSince(deliveredAt)
  694. let additionalTime = CGFloat(TimeInterval(max) * 5.minutes.timeInterval - lastDeltaTime)
  695. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  696. return Swift.max(additionalTime * oneSecondWidth, Config.minAdditionalWidth)
  697. }
  698. private func oneSecondStep(viewWidth: CGFloat) -> CGFloat {
  699. viewWidth / (CGFloat(Config.screenHours) * CGFloat(1.hours.timeInterval))
  700. }
  701. private func maxPredValue() -> Int? {
  702. [
  703. suggestion?.predictions?.cob ?? [],
  704. suggestion?.predictions?.iob ?? [],
  705. suggestion?.predictions?.zt ?? [],
  706. suggestion?.predictions?.uam ?? []
  707. ]
  708. .flatMap { $0 }
  709. .max()
  710. }
  711. private func minPredValue() -> Int? {
  712. [
  713. suggestion?.predictions?.cob ?? [],
  714. suggestion?.predictions?.iob ?? [],
  715. suggestion?.predictions?.zt ?? [],
  716. suggestion?.predictions?.uam ?? []
  717. ]
  718. .flatMap { $0 }
  719. .min()
  720. }
  721. private func maxTargetValue() -> Int? {
  722. tempTargets.map { $0.targetTop ?? 0 }.filter { $0 > 0 }.max().map(Int.init)
  723. }
  724. private func minTargetValue() -> Int? {
  725. tempTargets.map { $0.targetBottom ?? 0 }.filter { $0 > 0 }.min().map(Int.init)
  726. }
  727. private func glucoseToCoordinate(_ glucoseEntry: BloodGlucose, fullSize: CGSize) -> CGPoint {
  728. let x = timeToXCoordinate(glucoseEntry.dateString.timeIntervalSince1970, fullSize: fullSize)
  729. let y = glucoseToYCoordinate(glucoseEntry.glucose ?? 0, fullSize: fullSize)
  730. return CGPoint(x: x, y: y)
  731. }
  732. private func predictionToCoordinate(_ pred: Int, fullSize: CGSize, index: Int) -> CGPoint {
  733. guard let deliveredAt = suggestion?.deliverAt else {
  734. return .zero
  735. }
  736. let predTime = deliveredAt.timeIntervalSince1970 + TimeInterval(index) * 5.minutes.timeInterval
  737. let x = timeToXCoordinate(predTime, fullSize: fullSize)
  738. let y = glucoseToYCoordinate(pred, fullSize: fullSize)
  739. return CGPoint(x: x, y: y)
  740. }
  741. private func timeToXCoordinate(_ time: TimeInterval, fullSize: CGSize) -> CGFloat {
  742. let xOffset = -Date().addingTimeInterval(-1.days.timeInterval).timeIntervalSince1970
  743. let stepXFraction = fullGlucoseWidth(viewWidth: fullSize.width) / CGFloat(hours.hours.timeInterval)
  744. let x = CGFloat(time + xOffset) * stepXFraction
  745. return x
  746. }
  747. private func glucoseToYCoordinate(_ glucoseValue: Int, fullSize: CGSize) -> CGFloat {
  748. let topYPaddint = Config.topYPadding + Config.basalHeight
  749. let bottomYPadding = Config.bottomYPadding
  750. let (minValue, maxValue) = minMaxYValues()
  751. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  752. let yOffset = CGFloat(minValue) * stepYFraction
  753. let y = fullSize.height - CGFloat(glucoseValue) * stepYFraction + yOffset - bottomYPadding
  754. return y
  755. }
  756. private func timeToInterpolatedPoint(_ time: TimeInterval, fullSize: CGSize) -> CGPoint {
  757. var nextIndex = 0
  758. for (index, value) in glucose.enumerated() {
  759. if value.dateString.timeIntervalSince1970 > time {
  760. nextIndex = index
  761. break
  762. }
  763. }
  764. let x = timeToXCoordinate(time, fullSize: fullSize)
  765. guard nextIndex > 0 else {
  766. let lastY = glucoseToYCoordinate(glucose.last?.glucose ?? 0, fullSize: fullSize)
  767. return CGPoint(x: x, y: lastY)
  768. }
  769. let prevX = timeToXCoordinate(glucose[nextIndex - 1].dateString.timeIntervalSince1970, fullSize: fullSize)
  770. let prevY = glucoseToYCoordinate(glucose[nextIndex - 1].glucose ?? 0, fullSize: fullSize)
  771. let nextX = timeToXCoordinate(glucose[nextIndex].dateString.timeIntervalSince1970, fullSize: fullSize)
  772. let nextY = glucoseToYCoordinate(glucose[nextIndex].glucose ?? 0, fullSize: fullSize)
  773. let delta = nextX - prevX
  774. let fraction = (x - prevX) / delta
  775. return pointInLine(CGPoint(x: prevX, y: prevY), CGPoint(x: nextX, y: nextY), fraction)
  776. }
  777. private func minMaxYValues() -> (min: Int, max: Int) {
  778. var maxValue = glucose.compactMap(\.glucose).max() ?? Config.maxGlucose
  779. if let maxPredValue = maxPredValue() {
  780. maxValue = max(maxValue, maxPredValue)
  781. }
  782. if let maxTargetValue = maxTargetValue() {
  783. maxValue = max(maxValue, maxTargetValue)
  784. }
  785. var minValue = glucose.compactMap(\.glucose).min() ?? Config.minGlucose
  786. if let minPredValue = minPredValue() {
  787. minValue = min(minValue, minPredValue)
  788. }
  789. if let minTargetValue = minTargetValue() {
  790. minValue = min(minValue, minTargetValue)
  791. }
  792. if minValue == maxValue {
  793. minValue = Config.minGlucose
  794. maxValue = Config.maxGlucose
  795. }
  796. // fix the grah y-axis as long as the min and max BG values are within set borders
  797. if minValue > Config.minGlucose {
  798. minValue = Config.minGlucose
  799. }
  800. if maxValue < Config.maxGlucose {
  801. maxValue = Config.maxGlucose
  802. }
  803. return (min: minValue, max: maxValue)
  804. }
  805. private func getGlucoseYRange(fullSize: CGSize) -> GlucoseYRange {
  806. let topYPaddint = Config.topYPadding + Config.basalHeight
  807. let bottomYPadding = Config.bottomYPadding
  808. let (minValue, maxValue) = minMaxYValues()
  809. let stepYFraction = (fullSize.height - topYPaddint - bottomYPadding) / CGFloat(maxValue - minValue)
  810. let yOffset = CGFloat(minValue) * stepYFraction
  811. let maxY = fullSize.height - CGFloat(minValue) * stepYFraction + yOffset - bottomYPadding
  812. let minY = fullSize.height - CGFloat(maxValue) * stepYFraction + yOffset - bottomYPadding
  813. return (minValue: minValue, minY: minY, maxValue: maxValue, maxY: maxY)
  814. }
  815. private func firstHourDate() -> Date {
  816. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  817. return firstDate.dateTruncated(from: .minute)!
  818. }
  819. private func firstHourPosition(viewWidth: CGFloat) -> CGFloat {
  820. let firstDate = Date().addingTimeInterval(-1.days.timeInterval)
  821. let firstHour = firstHourDate()
  822. let lastDeltaTime = firstHour.timeIntervalSince(firstDate)
  823. let oneSecondWidth = oneSecondStep(viewWidth: viewWidth)
  824. return oneSecondWidth * CGFloat(lastDeltaTime)
  825. }
  826. }