StatRootView.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. import Charts
  2. import CoreData
  3. import SwiftDate
  4. import SwiftUI
  5. import Swinject
  6. extension Stat {
  7. struct RootView: BaseView {
  8. let resolver: Resolver
  9. @StateObject var state = StateModel()
  10. // @Environment(\.managedObjectContext) var moc
  11. @FetchRequest(
  12. entity: Readings.entity(),
  13. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)], predicate: NSPredicate(
  14. format: "date >= %@", Calendar.current.startOfDay(for: Date()) as NSDate
  15. )
  16. ) var fetchedGlucoseDay: FetchedResults<Readings>
  17. @FetchRequest(
  18. entity: Readings.entity(),
  19. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)],
  20. predicate: NSPredicate(format: "date > %@", Date().addingTimeInterval(-24.hours.timeInterval) as NSDate)
  21. ) var fetchedGlucoseTwentyFourHours: FetchedResults<Readings>
  22. @FetchRequest(
  23. entity: Readings.entity(),
  24. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)],
  25. predicate: NSPredicate(format: "date > %@", Date().addingTimeInterval(-7.days.timeInterval) as NSDate)
  26. ) var fetchedGlucoseWeek: FetchedResults<Readings>
  27. @FetchRequest(
  28. entity: Readings.entity(),
  29. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)], predicate: NSPredicate(
  30. format: "date > %@",
  31. Date().addingTimeInterval(-30.days.timeInterval) as NSDate
  32. )
  33. ) var fetchedGlucoseMonth: FetchedResults<Readings>
  34. @FetchRequest(
  35. entity: Readings.entity(),
  36. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)], predicate: NSPredicate(
  37. format: "date > %@",
  38. Date().addingTimeInterval(-90.days.timeInterval) as NSDate
  39. )
  40. ) var fetchedGlucose: FetchedResults<Readings>
  41. @FetchRequest(
  42. entity: TDD.entity(),
  43. sortDescriptors: [NSSortDescriptor(key: "timestamp", ascending: false)]
  44. ) var fetchedTDD: FetchedResults<TDD>
  45. @FetchRequest(
  46. entity: LoopStatRecord.entity(),
  47. sortDescriptors: [NSSortDescriptor(key: "start", ascending: false)], predicate: NSPredicate(
  48. format: "start > %@",
  49. Date().addingTimeInterval(-24.hours.timeInterval) as NSDate
  50. )
  51. ) var fetchedLoopStats: FetchedResults<LoopStatRecord>
  52. @FetchRequest(
  53. entity: InsulinDistribution.entity(),
  54. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]
  55. ) var fetchedInsulin: FetchedResults<InsulinDistribution>
  56. enum Duration: String, CaseIterable, Identifiable {
  57. case Today
  58. case Day
  59. case Week
  60. case Month
  61. case Total
  62. var id: Self { self }
  63. }
  64. @State private var selectedDuration: Duration = .Today
  65. @State var paddingAmount: CGFloat? = 10
  66. @State var headline: Color = .secondary
  67. @State var days: Double = 0
  68. @State var pointSize: CGFloat = 3
  69. @State var conversionFactor = 0.0555
  70. @ViewBuilder func stats() -> some View {
  71. bloodGlucose
  72. Divider()
  73. tirChart
  74. Divider()
  75. hba1c
  76. Divider()
  77. loops
  78. }
  79. @ViewBuilder func chart() -> some View {
  80. Text("Statistics").font(.largeTitle).bold().padding(.top, 25)
  81. switch selectedDuration {
  82. case .Today:
  83. glucoseChart
  84. case .Day:
  85. glucoseChartTwentyFourHours
  86. case .Week:
  87. glucoseChartWeek
  88. case .Month:
  89. glucoseChartMonth
  90. case .Total:
  91. glucoseChart90
  92. }
  93. }
  94. var body: some View {
  95. ZStack {
  96. VStack(alignment: .center, spacing: 8) {
  97. chart().padding(.horizontal, 10)
  98. Divider()
  99. stats()
  100. Spacer()
  101. Picker("Duration", selection: $selectedDuration) {
  102. ForEach(Duration.allCases) { duration in
  103. Text(duration.rawValue).tag(Optional(duration))
  104. }
  105. }.pickerStyle(.segmented)
  106. }
  107. }.onAppear(perform: configureView)
  108. }
  109. var loops: some View {
  110. VStack {
  111. let loops_ = loopStats(fetchedLoopStats)
  112. HStack {
  113. ForEach(0 ..< loops_.count, id: \.self) { index in
  114. VStack {
  115. Text(loops_[index].string).font(.subheadline).foregroundColor(.secondary)
  116. Text(
  117. index == 0 ? loops_[index].double.formatted() : (
  118. index == 2 ? loops_[index].double
  119. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(2))) :
  120. loops_[index]
  121. .double
  122. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))
  123. )
  124. )
  125. }.padding(.horizontal, 6)
  126. }
  127. }
  128. }
  129. }
  130. var hba1c: some View {
  131. let useUnit: GlucoseUnits = (state.units == .mmolL && (state.overrideUnit ?? false)) ? .mgdL :
  132. (state.units == .mgdL && (state.overrideUnit ?? false) || state.units == .mmolL) ? .mmolL : .mgdL
  133. return HStack {
  134. let hba1cs = glucoseStats(fetchedGlucose)
  135. let hba1cString = (
  136. useUnit == .mmolL ? hba1cs.ifcc
  137. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(1))) : hba1cs.ngsp
  138. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))
  139. + " %"
  140. )
  141. VStack {
  142. Text("HbA1C").font(.subheadline).foregroundColor(headline)
  143. HStack {
  144. VStack {
  145. Text(hba1cString)
  146. }
  147. }
  148. }.padding([.horizontal], 15)
  149. VStack {
  150. Text("SD").font(.subheadline).foregroundColor(.secondary)
  151. HStack {
  152. VStack {
  153. Text(
  154. hba1cs.sd
  155. .formatted(
  156. .number.grouping(.never).rounded()
  157. .precision(.fractionLength(state.units == .mmolL ? 1 : 0))
  158. )
  159. )
  160. }
  161. }
  162. }.padding([.horizontal], 15)
  163. VStack {
  164. Text("CV").font(.subheadline).foregroundColor(.secondary)
  165. HStack {
  166. VStack {
  167. Text(
  168. hba1cs.cv.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))
  169. )
  170. }
  171. }
  172. }.padding([.horizontal], 15)
  173. if selectedDuration == .Total {
  174. VStack {
  175. Text("Days").font(.subheadline).foregroundColor(.secondary)
  176. HStack {
  177. VStack {
  178. Text(numberOfDays.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1))))
  179. }
  180. }
  181. }.padding([.horizontal], 15)
  182. }
  183. }
  184. }
  185. var bloodGlucose: some View {
  186. VStack {
  187. HStack {
  188. let bgs = glucoseStats(fetchedGlucose)
  189. VStack {
  190. HStack {
  191. Text("Average").font(.subheadline).foregroundColor(headline)
  192. }
  193. HStack {
  194. VStack {
  195. Text(
  196. bgs.average
  197. .formatted(
  198. .number.grouping(.never).rounded()
  199. .precision(.fractionLength(state.units == .mmolL ? 1 : 0))
  200. )
  201. )
  202. }
  203. }
  204. }
  205. VStack {
  206. HStack {
  207. Text("Median").font(.subheadline).foregroundColor(.secondary)
  208. }
  209. HStack {
  210. VStack {
  211. Text(
  212. bgs.median
  213. .formatted(
  214. .number.grouping(.never).rounded()
  215. .precision(.fractionLength(state.units == .mmolL ? 1 : 0))
  216. )
  217. )
  218. }
  219. }
  220. }
  221. VStack {
  222. HStack {
  223. Text(selectedDuration == .Today ? "Readings today" : "Readings / 24h").font(.subheadline)
  224. .foregroundColor(.secondary)
  225. }
  226. HStack {
  227. VStack {
  228. Text(
  229. bgs.readings.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0)))
  230. )
  231. }
  232. }
  233. }
  234. }
  235. }
  236. }
  237. var numberOfDays: Double {
  238. let endIndex = fetchedGlucose.count - 1
  239. var days = 0.0
  240. if endIndex > 0 {
  241. let firstElementTime = fetchedGlucose.first?.date ?? Date()
  242. let lastElementTime = fetchedGlucose[endIndex].date ?? Date()
  243. days = (firstElementTime - lastElementTime).timeInterval / 8.64E4
  244. }
  245. return days
  246. }
  247. var tirChart: some View {
  248. let array = selectedDuration == .Today ? fetchedGlucoseDay : selectedDuration == .Day ?
  249. fetchedGlucoseTwentyFourHours :
  250. selectedDuration == .Week ? fetchedGlucoseWeek : selectedDuration == .Month ? fetchedGlucoseMonth :
  251. selectedDuration ==
  252. .Total ? fetchedGlucose : fetchedGlucoseDay
  253. let fetched = tir(array)
  254. let data: [ShapeModel] = [
  255. .init(type: "Low", percent: fetched[0].decimal),
  256. .init(type: "In Range", percent: fetched[1].decimal),
  257. .init(type: "High", percent: fetched[2].decimal)
  258. ]
  259. return VStack(alignment: .center) {
  260. Chart(data) { shape in
  261. BarMark(
  262. x: .value("Shape", shape.type),
  263. y: .value("Percentage", shape.percent)
  264. )
  265. .foregroundStyle(by: .value("Group", shape.type))
  266. .annotation(position: shape.percent < 5 ? .top : .overlay, alignment: .center) {
  267. Text(shape.percent == 0 ? "" : "\(shape.percent, format: .number.precision(.fractionLength(0))) %")
  268. }
  269. }
  270. .chartYAxis(.hidden)
  271. .chartLegend(.hidden)
  272. .chartForegroundStyleScale(["Low": .red, "In Range": .green, "High": .orange])
  273. }
  274. }
  275. var glucoseChart: some View {
  276. let count = fetchedGlucoseDay.count
  277. let lowLimit = (state.lowLimit ?? (4 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  278. let highLimit = (state.highLimit ?? (10 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  279. return Chart {
  280. ForEach(fetchedGlucoseDay.filter({ $0.glucose > Int(state.highLimit ?? 145) }), id: \.date) { item in
  281. PointMark(
  282. x: .value("Date", item.date ?? Date()),
  283. y: .value("High", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  284. )
  285. .foregroundStyle(.orange)
  286. .symbolSize(count < 20 ? 30 : 12)
  287. }
  288. ForEach(
  289. fetchedGlucoseDay
  290. .filter({ $0.glucose >= Int(state.lowLimit ?? 70) && $0.glucose <= Int(state.highLimit ?? 145) }),
  291. id: \.date
  292. ) { item in
  293. PointMark(
  294. x: .value("Date", item.date ?? Date()),
  295. y: .value("In Range", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  296. )
  297. .foregroundStyle(.green)
  298. .symbolSize(count < 20 ? 30 : 12)
  299. }
  300. ForEach(fetchedGlucoseDay.filter({ $0.glucose < Int(state.lowLimit ?? 70) }), id: \.date) { item in
  301. PointMark(
  302. x: .value("Date", item.date ?? Date()),
  303. y: .value("Low", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  304. )
  305. .foregroundStyle(.red)
  306. .symbolSize(count < 20 ? 30 : 12)
  307. }
  308. }
  309. .chartYScale(domain: [0, state.units == .mmolL ? 17 : 306])
  310. .chartYAxis {
  311. AxisMarks(
  312. values: [
  313. 0,
  314. lowLimit,
  315. highLimit,
  316. state.units == .mmolL ? 15 : 270
  317. ]
  318. )
  319. }
  320. }
  321. var glucoseChartTwentyFourHours: some View {
  322. let count = fetchedGlucoseTwentyFourHours.count
  323. let lowLimit = (state.lowLimit ?? (4 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  324. let highLimit = (state.highLimit ?? (10 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  325. return Chart {
  326. ForEach(fetchedGlucoseTwentyFourHours.filter({ $0.glucose > Int(state.highLimit ?? 145) }), id: \.date) { item in
  327. PointMark(
  328. x: .value("Date", item.date ?? Date()),
  329. y: .value("High", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  330. )
  331. .foregroundStyle(.orange)
  332. .symbolSize(count < 20 ? 20 : 10)
  333. }
  334. ForEach(
  335. fetchedGlucoseTwentyFourHours
  336. .filter({ $0.glucose >= Int(state.lowLimit ?? 70) && $0.glucose <= Int(state.highLimit ?? 145) }),
  337. id: \.date
  338. ) { item in
  339. PointMark(
  340. x: .value("Date", item.date ?? Date()),
  341. y: .value("In Range", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  342. )
  343. .foregroundStyle(.green)
  344. .symbolSize(count < 20 ? 20 : 10)
  345. }
  346. ForEach(fetchedGlucoseTwentyFourHours.filter({ $0.glucose < Int(state.lowLimit ?? 70) }), id: \.date) { item in
  347. PointMark(
  348. x: .value("Date", item.date ?? Date()),
  349. y: .value("Low", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  350. )
  351. .foregroundStyle(.red)
  352. .symbolSize(count < 20 ? 20 : 10)
  353. }
  354. }
  355. .chartYScale(domain: [0, state.units == .mmolL ? 17 : 306])
  356. .chartYAxis {
  357. AxisMarks(
  358. values: [
  359. 0,
  360. lowLimit,
  361. highLimit,
  362. state.units == .mmolL ? 15 : 270
  363. ]
  364. )
  365. }
  366. }
  367. var glucoseChartWeek: some View {
  368. let lowLimit = (state.lowLimit ?? (4 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  369. let highLimit = (state.highLimit ?? (10 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  370. return Chart {
  371. ForEach(fetchedGlucoseWeek.filter({ $0.glucose > Int(state.highLimit ?? 145) }), id: \.date) { item in
  372. PointMark(
  373. x: .value("Date", item.date ?? Date()),
  374. y: .value("Low", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  375. )
  376. .foregroundStyle(.orange)
  377. .symbolSize(5)
  378. }
  379. ForEach(
  380. fetchedGlucoseWeek
  381. .filter({ $0.glucose >= Int(state.lowLimit ?? 70) && $0.glucose <= Int(state.highLimit ?? 145) }),
  382. id: \.date
  383. ) { item in
  384. PointMark(
  385. x: .value("Date", item.date ?? Date()),
  386. y: .value("In Range", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  387. )
  388. .foregroundStyle(.green)
  389. .symbolSize(5)
  390. }
  391. ForEach(fetchedGlucoseWeek.filter({ $0.glucose < Int(state.lowLimit ?? 70) }), id: \.date) { item in
  392. PointMark(
  393. x: .value("Date", item.date ?? Date()),
  394. y: .value("High", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  395. )
  396. .foregroundStyle(.red)
  397. .symbolSize(5)
  398. }
  399. }
  400. .chartYScale(domain: [0, state.units == .mmolL ? 17 : 306])
  401. .chartYAxis {
  402. AxisMarks(
  403. values: [
  404. 0,
  405. lowLimit,
  406. highLimit,
  407. state.units == .mmolL ? 15 : 270
  408. ]
  409. )
  410. }
  411. }
  412. var glucoseChartMonth: some View {
  413. let lowLimit = (state.lowLimit ?? (4 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  414. let highLimit = (state.highLimit ?? (10 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  415. return Chart {
  416. ForEach(fetchedGlucoseMonth.filter({ $0.glucose > Int(state.highLimit ?? 145) }), id: \.date) { item in
  417. PointMark(
  418. x: .value("Date", item.date ?? Date()),
  419. y: .value("Low", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  420. )
  421. .foregroundStyle(.orange)
  422. .symbolSize(2)
  423. }
  424. ForEach(
  425. fetchedGlucoseMonth
  426. .filter({ $0.glucose >= Int(state.lowLimit ?? 70) && $0.glucose <= Int(state.highLimit ?? 145) }),
  427. id: \.date
  428. ) { item in
  429. PointMark(
  430. x: .value("Date", item.date ?? Date()),
  431. y: .value("In Range", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  432. )
  433. .foregroundStyle(.green)
  434. .symbolSize(2)
  435. }
  436. ForEach(fetchedGlucoseMonth.filter({ $0.glucose < Int(state.lowLimit ?? 70) }), id: \.date) { item in
  437. PointMark(
  438. x: .value("Date", item.date ?? Date()),
  439. y: .value("High", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  440. )
  441. .foregroundStyle(.red)
  442. .symbolSize(2)
  443. }
  444. }
  445. .chartYScale(domain: [0, state.units == .mmolL ? 17 : 306])
  446. .chartYAxis {
  447. AxisMarks(
  448. values: [
  449. 0,
  450. lowLimit,
  451. highLimit,
  452. state.units == .mmolL ? 15 : 270
  453. ]
  454. )
  455. }
  456. }
  457. var glucoseChart90: some View {
  458. let lowLimit = (state.lowLimit ?? (4 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  459. let highLimit = (state.highLimit ?? (10 * 0.0555)) * (state.units == .mmolL ? Decimal(conversionFactor) : 1)
  460. return Chart {
  461. ForEach(fetchedGlucose.filter({ $0.glucose > Int(state.highLimit ?? 145) }), id: \.date) { item in
  462. PointMark(
  463. x: .value("Date", item.date ?? Date()),
  464. y: .value("Low", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  465. )
  466. .foregroundStyle(.orange)
  467. .symbolSize(2)
  468. }
  469. ForEach(
  470. fetchedGlucose
  471. .filter({ $0.glucose >= Int(state.lowLimit ?? 70) && $0.glucose <= Int(state.highLimit ?? 145) }),
  472. id: \.date
  473. ) { item in
  474. PointMark(
  475. x: .value("Date", item.date ?? Date()),
  476. y: .value("In Range", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  477. )
  478. .foregroundStyle(.green)
  479. .symbolSize(2)
  480. }
  481. ForEach(fetchedGlucose.filter({ $0.glucose < Int(state.lowLimit ?? 70) }), id: \.date) { item in
  482. PointMark(
  483. x: .value("Date", item.date ?? Date()),
  484. y: .value("High", Double(item.glucose) * (state.units == .mmolL ? conversionFactor : 1))
  485. )
  486. .foregroundStyle(.red)
  487. .symbolSize(2)
  488. }
  489. }
  490. .chartYScale(domain: [0, state.units == .mmolL ? 17 : 306])
  491. .chartYAxis {
  492. AxisMarks(
  493. values: [
  494. 0,
  495. lowLimit,
  496. highLimit,
  497. state.units == .mmolL ? 15 : 270
  498. ]
  499. )
  500. }
  501. }
  502. private func loopStats(_ loops: FetchedResults<LoopStatRecord>) -> [(double: Double, string: String)] {
  503. guard (loops.first?.start) != nil else { return [] }
  504. var i = 0.0
  505. var minimumInt = 999.0
  506. var maximumInt = 0.0
  507. var timeIntervalLoops = 0.0
  508. var previousTimeLoop = loops.first?.end ?? Date()
  509. var timeIntervalLoopArray: [Double] = []
  510. let durationArray = loops.compactMap({ each in each.duration })
  511. let durationArrayCount = durationArray.count
  512. // var durationAverage = durationArray.reduce(0, +) / Double(durationArrayCount)
  513. let medianDuration = medianCalculationDouble(array: durationArray)
  514. let successsNR = loops.compactMap({ each in each.loopStatus }).filter({ each in each!.contains("Success") }).count
  515. let errorNR = durationArrayCount - successsNR
  516. let successRate: Double? = (Double(successsNR) / Double(successsNR + errorNR)) * 100
  517. for each in loops {
  518. if let loopEnd = each.end {
  519. i += 1
  520. timeIntervalLoops = (previousTimeLoop - (each.start ?? previousTimeLoop)).timeInterval / 60
  521. if timeIntervalLoops > 0.0, i != 1 {
  522. timeIntervalLoopArray.append(timeIntervalLoops)
  523. }
  524. if timeIntervalLoops > maximumInt {
  525. maximumInt = timeIntervalLoops
  526. }
  527. if timeIntervalLoops < minimumInt, i != 1 {
  528. minimumInt = timeIntervalLoops
  529. }
  530. previousTimeLoop = loopEnd
  531. }
  532. }
  533. // Average Loop Interval in minutes
  534. let timeOfFirstIndex = loops.first?.start ?? Date()
  535. let lastIndexWithTimestamp = loops.count - 1
  536. let timeOfLastIndex = loops[lastIndexWithTimestamp].end ?? Date()
  537. let averageInterval = (timeOfFirstIndex - timeOfLastIndex).timeInterval / 60 / Double(errorNR + successsNR)
  538. if minimumInt == 999.0 {
  539. minimumInt = 0.0
  540. }
  541. var array: [(double: Double, string: String)] = []
  542. array.append((double: Double(successsNR + errorNR), string: "Loops"))
  543. array.append((double: averageInterval, string: "Interval"))
  544. array.append((double: medianDuration, string: "Duration"))
  545. array.append((double: successRate ?? 100, string: "%"))
  546. return array
  547. }
  548. private func medianCalculation(array: [Int]) -> Double {
  549. guard !array.isEmpty else {
  550. return 0
  551. }
  552. let sorted = array.sorted()
  553. let length = array.count
  554. if length % 2 == 0 {
  555. return Double((sorted[length / 2 - 1] + sorted[length / 2]) / 2)
  556. }
  557. return Double(sorted[length / 2])
  558. }
  559. private func medianCalculationDouble(array: [Double]) -> Double {
  560. guard !array.isEmpty else {
  561. return 0
  562. }
  563. let sorted = array.sorted()
  564. let length = array.count
  565. if length % 2 == 0 {
  566. return (sorted[length / 2 - 1] + sorted[length / 2]) / 2
  567. }
  568. return sorted[length / 2]
  569. }
  570. private func glucoseStats(_ glucose_90: FetchedResults<Readings>)
  571. -> (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double)
  572. {
  573. var numberOfDays: Double = 0
  574. let endIndex = glucose_90.count - 1
  575. if endIndex > 0 {
  576. let firstElementTime = glucose_90[0].date ?? Date()
  577. let lastElementTime = glucose_90[endIndex].date ?? Date()
  578. numberOfDays = (firstElementTime - lastElementTime).timeInterval / 8.64E4
  579. }
  580. var duration = 1
  581. var denominator: Double = 1
  582. switch selectedDuration {
  583. case .Today:
  584. let minutesSinceMidnight = Calendar.current.component(.hour, from: Date()) * 60 + Calendar.current
  585. .component(.minute, from: Date())
  586. duration = minutesSinceMidnight
  587. denominator = 1
  588. case .Day:
  589. duration = 1 * 1440
  590. denominator = 1
  591. case .Week:
  592. duration = 7 * 1440
  593. if numberOfDays > 7 { denominator = 7 } else { denominator = numberOfDays }
  594. case .Month:
  595. duration = 30 * 1440
  596. if numberOfDays > 30 { denominator = 30 } else { denominator = numberOfDays }
  597. case .Total:
  598. duration = 90 * 1440
  599. if numberOfDays >= 90 { denominator = 90 } else { denominator = numberOfDays }
  600. }
  601. let timeAgo = Date().addingTimeInterval(-duration.minutes.timeInterval)
  602. let glucose = glucose_90.filter({ ($0.date ?? Date()) >= timeAgo })
  603. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  604. let sumReadings = justGlucoseArray.reduce(0, +)
  605. let countReadings = justGlucoseArray.count
  606. let glucoseAverage = Double(sumReadings) / Double(countReadings)
  607. let medianGlucose = medianCalculation(array: justGlucoseArray)
  608. var NGSPa1CStatisticValue = 0.0
  609. var IFCCa1CStatisticValue = 0.0
  610. if numberOfDays > 0 {
  611. NGSPa1CStatisticValue = (glucoseAverage + 46.7) / 28.7 // NGSP (%)
  612. IFCCa1CStatisticValue = 10.929 *
  613. (NGSPa1CStatisticValue - 2.152) // IFCC (mmol/mol) A1C(mmol/mol) = 10.929 * (A1C(%) - 2.15)
  614. }
  615. var sumOfSquares = 0.0
  616. for array in justGlucoseArray {
  617. sumOfSquares += pow(Double(array) - Double(glucoseAverage), 2)
  618. }
  619. var sd = 0.0
  620. var cv = 0.0
  621. // Avoid division by zero
  622. if glucoseAverage > 0 {
  623. sd = sqrt(sumOfSquares / Double(countReadings))
  624. cv = sd / Double(glucoseAverage) * 100
  625. }
  626. var output: (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double)
  627. output = (
  628. ifcc: IFCCa1CStatisticValue,
  629. ngsp: NGSPa1CStatisticValue,
  630. average: glucoseAverage * (state.units == .mmolL ? conversionFactor : 1),
  631. median: medianGlucose * (state.units == .mmolL ? conversionFactor : 1),
  632. sd: sd * (state.units == .mmolL ? conversionFactor : 1), cv: cv,
  633. readings: Double(countReadings) / denominator
  634. )
  635. return output
  636. }
  637. private func tir(_ glucose_90: FetchedResults<Readings>) -> [(decimal: Decimal, string: String)] {
  638. var duration = 1
  639. switch selectedDuration {
  640. case .Today:
  641. let minutesSinceMidnight = Calendar.current.component(.hour, from: Date()) * 60 + Calendar.current
  642. .component(.minute, from: Date())
  643. duration = minutesSinceMidnight
  644. case .Day:
  645. duration = 1 * 1440
  646. case .Week:
  647. duration = 7 * 1440
  648. case .Month:
  649. duration = 30 * 1440
  650. case .Total:
  651. duration = 90 * 1440
  652. }
  653. let hypoLimit = Int(state.lowLimit ?? 70)
  654. let hyperLimit = Int(state.highLimit ?? 145)
  655. let timeAgo = Date().addingTimeInterval(-duration.minutes.timeInterval)
  656. let glucose = glucose_90.filter({ ($0.date ?? Date()) >= timeAgo })
  657. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  658. let totalReadings = justGlucoseArray.count
  659. let hyperArray = glucose.filter({ $0.glucose >= hyperLimit })
  660. let hyperReadings = hyperArray.compactMap({ each in each.glucose as Int16 }).count
  661. let hyperPercentage = Double(hyperReadings) / Double(totalReadings) * 100
  662. let hypoArray = glucose.filter({ $0.glucose <= hypoLimit })
  663. let hypoReadings = hypoArray.compactMap({ each in each.glucose as Int16 }).count
  664. let hypoPercentage = Double(hypoReadings) / Double(totalReadings) * 100
  665. let tir = 100 - (hypoPercentage + hyperPercentage)
  666. var array: [(decimal: Decimal, string: String)] = []
  667. array.append((decimal: Decimal(hypoPercentage), string: "Low"))
  668. array.append((decimal: Decimal(tir), string: "NormaL"))
  669. array.append((decimal: Decimal(hyperPercentage), string: "High"))
  670. return array
  671. }
  672. private func colorOfGlucose(_ index: Int) -> Color {
  673. let whichIndex = index
  674. switch whichIndex {
  675. case 0:
  676. return .red
  677. case 1:
  678. return .green
  679. case 2:
  680. return .orange
  681. default:
  682. return .primary
  683. }
  684. }
  685. }
  686. }