StatsView.swift 11 KB

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