StatsView.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 hbA1cDisplayUnit: HbA1cDisplayUnit
  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. hbA1cDisplayUnit: HbA1cDisplayUnit
  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.hbA1cDisplayUnit = hbA1cDisplayUnit
  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 = {
  116. if units == .mmolL && hbA1cDisplayUnit == .mmolMol {
  117. return .mgdL
  118. } else if (units == .mgdL && hbA1cDisplayUnit == .mmolMol) || units == .mmolL {
  119. return .mmolL
  120. } else {
  121. return .mgdL
  122. }
  123. }()
  124. let hba1cs = glucoseStats()
  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. // 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" : "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. // First date
  201. let previous = glucose.last?.date ?? Date()
  202. // Last date (recent)
  203. let current = glucose.first?.date ?? Date()
  204. // Total time in days
  205. let numberOfDays = (current - previous).timeInterval / 8.64E4
  206. let denominator = numberOfDays < 1 ? 1 : numberOfDays
  207. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  208. let sumReadings = justGlucoseArray.reduce(0, +)
  209. let countReadings = justGlucoseArray.count
  210. let glucoseAverage = Double(sumReadings) / Double(countReadings)
  211. let medianGlucose = medianCalculation(array: justGlucoseArray)
  212. var NGSPa1CStatisticValue = 0.0
  213. var IFCCa1CStatisticValue = 0.0
  214. if numberOfDays > 0 {
  215. NGSPa1CStatisticValue = (glucoseAverage + 46.7) / 28.7 // NGSP (%)
  216. IFCCa1CStatisticValue = 10.929 *
  217. (NGSPa1CStatisticValue - 2.152) // IFCC (mmol/mol) A1C(mmol/mol) = 10.929 * (A1C(%) - 2.15)
  218. }
  219. var sumOfSquares = 0.0
  220. for array in justGlucoseArray {
  221. sumOfSquares += pow(Double(array) - Double(glucoseAverage), 2)
  222. }
  223. var sd = 0.0
  224. var cv = 0.0
  225. // Avoid division by zero
  226. if glucoseAverage > 0 {
  227. sd = sqrt(sumOfSquares / Double(countReadings))
  228. cv = sd / Double(glucoseAverage) * 100
  229. }
  230. var output: (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double)
  231. output = (
  232. ifcc: IFCCa1CStatisticValue,
  233. ngsp: NGSPa1CStatisticValue,
  234. average: glucoseAverage * (units == .mmolL ? conversionFactor : 1),
  235. median: medianGlucose * (units == .mmolL ? conversionFactor : 1),
  236. sd: sd * (units == .mmolL ? conversionFactor : 1), cv: cv,
  237. readings: Double(countReadings) / denominator
  238. )
  239. return output
  240. }
  241. private func tir() -> [(decimal: Decimal, string: String)] {
  242. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  243. let totalReadings = justGlucoseArray.count
  244. let hyperArray = glucose.filter({ $0.glucose >= Int(highLimit) })
  245. let hyperReadings = hyperArray.compactMap({ each in each.glucose as Int16 }).count
  246. let hyperPercentage = Double(hyperReadings) / Double(totalReadings) * 100
  247. let hypoArray = glucose.filter({ $0.glucose <= Int(lowLimit) })
  248. let hypoReadings = hypoArray.compactMap({ each in each.glucose as Int16 }).count
  249. let hypoPercentage = Double(hypoReadings) / Double(totalReadings) * 100
  250. let tir = 100 - (hypoPercentage + hyperPercentage)
  251. var array: [(decimal: Decimal, string: String)] = []
  252. array.append((decimal: Decimal(hypoPercentage), string: "Low"))
  253. array.append((decimal: Decimal(tir), string: "NormaL"))
  254. array.append((decimal: Decimal(hyperPercentage), string: "High"))
  255. return array
  256. }
  257. }