StatsView.swift 11 KB

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