StatsView.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import CoreData
  2. import SwiftDate
  3. import SwiftUI
  4. struct StatsView: View {
  5. @FetchRequest var fetchRequest: FetchedResults<LoopStatRecord>
  6. @FetchRequest var glucose: FetchedResults<GlucoseStored>
  7. @State var headline: Color = .secondary
  8. var highLimit: Decimal
  9. var lowLimit: Decimal
  10. var units: GlucoseUnits
  11. var overrideUnit: Bool
  12. private let conversionFactor = 0.0555
  13. var body: some View {
  14. VStack(spacing: 10) {
  15. loops
  16. Divider()
  17. hba1c
  18. Divider()
  19. bloodGlucose
  20. }
  21. }
  22. init(
  23. filter: NSDate,
  24. highLimit: Decimal,
  25. lowLimit: Decimal,
  26. units: GlucoseUnits,
  27. overrideUnit: Bool
  28. ) {
  29. _fetchRequest = FetchRequest<LoopStatRecord>(
  30. sortDescriptors: [NSSortDescriptor(key: "start", ascending: false)],
  31. predicate: NSPredicate(format: "interval > 0 AND start > %@", filter)
  32. )
  33. _glucose = FetchRequest<GlucoseStored>(
  34. sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)],
  35. predicate: NSPredicate(format: "glucose > 0 AND date > %@", filter)
  36. )
  37. self.highLimit = highLimit
  38. self.lowLimit = lowLimit
  39. self.units = units
  40. self.overrideUnit = overrideUnit
  41. }
  42. var loops: some View {
  43. let loops = fetchRequest
  44. // First date
  45. let previous = loops.last?.end ?? Date()
  46. // Last date (recent)
  47. let current = loops.first?.start ?? Date()
  48. // Total time in days
  49. let totalTime = (current - previous).timeInterval / 8.64E4
  50. let durationArray = loops.compactMap({ each in each.duration })
  51. let durationArrayCount = durationArray.count
  52. // var durationAverage = durationArray.reduce(0, +) / Double(durationArrayCount)
  53. let medianDuration = medianCalculationDouble(array: durationArray)
  54. let successsNR = loops.compactMap({ each in each.loopStatus }).filter({ each in each!.contains("Success") }).count
  55. let errorNR = durationArrayCount - successsNR
  56. let total = Double(successsNR + errorNR) == 0 ? 1 : Double(successsNR + errorNR)
  57. let successRate: Double? = (Double(successsNR) / total) * 100
  58. let loopNr = totalTime <= 1 ? total : round(total / (totalTime != 0 ? totalTime : 1))
  59. let intervalArray = loops.compactMap({ each in each.interval as Double })
  60. let count = intervalArray.count != 0 ? intervalArray.count : 1
  61. let intervalAverage = intervalArray.reduce(0, +) / Double(count)
  62. // let maximumInterval = intervalArray.max()
  63. // let minimumInterval = intervalArray.min()
  64. return VStack(spacing: 10) {
  65. HStack(spacing: 35) {
  66. VStack(spacing: 5) {
  67. Text("Loops").font(.subheadline).foregroundColor(headline)
  68. Text(loopNr.formatted())
  69. }
  70. VStack(spacing: 5) {
  71. Text("Interval").font(.subheadline).foregroundColor(headline)
  72. Text(intervalAverage.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1))) + " min")
  73. }
  74. VStack(spacing: 5) {
  75. Text("Duration").font(.subheadline).foregroundColor(headline)
  76. Text(
  77. (medianDuration * 60)
  78. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(1))) + " s"
  79. )
  80. }
  81. VStack(spacing: 5) {
  82. Text("Success").font(.subheadline).foregroundColor(headline)
  83. Text(
  84. ((successRate ?? 100) / 100)
  85. .formatted(.percent.grouping(.never).rounded().precision(.fractionLength(1)))
  86. )
  87. }
  88. }
  89. }
  90. }
  91. private func medianCalculation(array: [Int]) -> Double {
  92. guard !array.isEmpty else {
  93. return 0
  94. }
  95. let sorted = array.sorted()
  96. let length = array.count
  97. if length % 2 == 0 {
  98. return Double((sorted[length / 2 - 1] + sorted[length / 2]) / 2)
  99. }
  100. return Double(sorted[length / 2])
  101. }
  102. private func medianCalculationDouble(array: [Double]) -> Double {
  103. guard !array.isEmpty else {
  104. return 0
  105. }
  106. let sorted = array.sorted()
  107. let length = array.count
  108. if length % 2 == 0 {
  109. return (sorted[length / 2 - 1] + sorted[length / 2]) / 2
  110. }
  111. return sorted[length / 2]
  112. }
  113. var hba1c: some View {
  114. HStack(spacing: 50) {
  115. let useUnit: GlucoseUnits = (units == .mmolL && overrideUnit) ? .mgdL :
  116. (units == .mgdL && overrideUnit || units == .mmolL) ? .mmolL : .mgdL
  117. let hba1cs = glucoseStats()
  118. // First date
  119. let previous = glucose.last?.date ?? Date()
  120. // Last date (recent)
  121. let current = glucose.first?.date ?? Date()
  122. // Total time in days
  123. let numberOfDays = (current - previous).timeInterval / 8.64E4
  124. let hba1cString = (
  125. useUnit == .mmolL ? hba1cs.ifcc
  126. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(1))) : hba1cs.ngsp
  127. .formatted(.number.grouping(.never).rounded().precision(.fractionLength(1)))
  128. + " %"
  129. )
  130. VStack(spacing: 5) {
  131. Text("HbA1C").font(.subheadline).foregroundColor(headline)
  132. Text(hba1cString)
  133. }
  134. VStack(spacing: 5) {
  135. Text("SD").font(.subheadline).foregroundColor(.secondary)
  136. Text(
  137. hba1cs.sd
  138. .formatted(
  139. .number.grouping(.never).rounded()
  140. .precision(.fractionLength(units == .mmolL ? 1 : 0))
  141. )
  142. )
  143. }
  144. VStack(spacing: 5) {
  145. Text("CV").font(.subheadline).foregroundColor(.secondary)
  146. Text(hba1cs.cv.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))))
  147. }
  148. VStack(spacing: 5) {
  149. Text("Days").font(.subheadline).foregroundColor(.secondary)
  150. Text(numberOfDays.formatted(.number.grouping(.never).rounded().precision(.fractionLength(1))))
  151. }
  152. }
  153. }
  154. var bloodGlucose: some View {
  155. HStack(spacing: 30) {
  156. let bgs = glucoseStats()
  157. // First date
  158. let previous = glucose.last?.date ?? Date()
  159. // Last date (recent)
  160. let current = glucose.first?.date ?? Date()
  161. // Total time in days
  162. let numberOfDays = (current - previous).timeInterval / 8.64E4
  163. VStack(spacing: 5) {
  164. Text(numberOfDays < 1 ? "Readings" : "Readings / 24h").font(.subheadline)
  165. .foregroundColor(.secondary)
  166. Text(bgs.readings.formatted(.number.grouping(.never).rounded().precision(.fractionLength(0))))
  167. }
  168. VStack(spacing: 5) {
  169. Text("Average").font(.subheadline).foregroundColor(headline)
  170. Text(
  171. bgs.average
  172. .formatted(
  173. .number.grouping(.never).rounded()
  174. .precision(.fractionLength(units == .mmolL ? 1 : 0))
  175. )
  176. )
  177. }
  178. VStack(spacing: 5) {
  179. Text("Median").font(.subheadline).foregroundColor(.secondary)
  180. Text(
  181. bgs.median
  182. .formatted(
  183. .number.grouping(.never).rounded()
  184. .precision(.fractionLength(units == .mmolL ? 1 : 0))
  185. )
  186. )
  187. }
  188. }
  189. }
  190. private func glucoseStats()
  191. -> (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double)
  192. {
  193. // First date
  194. let previous = glucose.last?.date ?? Date()
  195. // Last date (recent)
  196. let current = glucose.first?.date ?? Date()
  197. // Total time in days
  198. let numberOfDays = (current - previous).timeInterval / 8.64E4
  199. let denominator = numberOfDays < 1 ? 1 : numberOfDays
  200. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  201. let sumReadings = justGlucoseArray.reduce(0, +)
  202. let countReadings = justGlucoseArray.count
  203. let glucoseAverage = Double(sumReadings) / Double(countReadings)
  204. let medianGlucose = medianCalculation(array: justGlucoseArray)
  205. var NGSPa1CStatisticValue = 0.0
  206. var IFCCa1CStatisticValue = 0.0
  207. if numberOfDays > 0 {
  208. NGSPa1CStatisticValue = (glucoseAverage + 46.7) / 28.7 // NGSP (%)
  209. IFCCa1CStatisticValue = 10.929 *
  210. (NGSPa1CStatisticValue - 2.152) // IFCC (mmol/mol) A1C(mmol/mol) = 10.929 * (A1C(%) - 2.15)
  211. }
  212. var sumOfSquares = 0.0
  213. for array in justGlucoseArray {
  214. sumOfSquares += pow(Double(array) - Double(glucoseAverage), 2)
  215. }
  216. var sd = 0.0
  217. var cv = 0.0
  218. // Avoid division by zero
  219. if glucoseAverage > 0 {
  220. sd = sqrt(sumOfSquares / Double(countReadings))
  221. cv = sd / Double(glucoseAverage) * 100
  222. }
  223. var output: (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double)
  224. output = (
  225. ifcc: IFCCa1CStatisticValue,
  226. ngsp: NGSPa1CStatisticValue,
  227. average: glucoseAverage * (units == .mmolL ? conversionFactor : 1),
  228. median: medianGlucose * (units == .mmolL ? conversionFactor : 1),
  229. sd: sd * (units == .mmolL ? conversionFactor : 1), cv: cv,
  230. readings: Double(countReadings) / denominator
  231. )
  232. return output
  233. }
  234. private func tir() -> [(decimal: Decimal, string: String)] {
  235. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  236. let totalReadings = justGlucoseArray.count
  237. let hyperArray = glucose.filter({ $0.glucose >= Int(highLimit) })
  238. let hyperReadings = hyperArray.compactMap({ each in each.glucose as Int16 }).count
  239. let hyperPercentage = Double(hyperReadings) / Double(totalReadings) * 100
  240. let hypoArray = glucose.filter({ $0.glucose <= Int(lowLimit) })
  241. let hypoReadings = hypoArray.compactMap({ each in each.glucose as Int16 }).count
  242. let hypoPercentage = Double(hypoReadings) / Double(totalReadings) * 100
  243. let tir = 100 - (hypoPercentage + hyperPercentage)
  244. var array: [(decimal: Decimal, string: String)] = []
  245. array.append((decimal: Decimal(hypoPercentage), string: "Low"))
  246. array.append((decimal: Decimal(tir), string: "NormaL"))
  247. array.append((decimal: Decimal(hyperPercentage), string: "High"))
  248. return array
  249. }
  250. }