BolusStateModel.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. import CoreData
  2. import Foundation
  3. import LoopKit
  4. import SwiftUI
  5. import Swinject
  6. extension Bolus {
  7. final class StateModel: BaseStateModel<Provider> {
  8. @Injected() var unlockmanager: UnlockManager!
  9. @Injected() var apsManager: APSManager!
  10. @Injected() var broadcaster: Broadcaster!
  11. @Injected() var pumpHistoryStorage: PumpHistoryStorage!
  12. // added for bolus calculator
  13. @Injected() var settings: SettingsManager!
  14. @Injected() var nsManager: NightscoutManager!
  15. @Injected() var carbsStorage: CarbsStorage!
  16. @Injected() var glucoseStorage: GlucoseStorage!
  17. @Injected() var determinationStorage: DeterminationStorage!
  18. @Published var lowGlucose: Decimal = 4 / 0.0555
  19. @Published var highGlucose: Decimal = 10 / 0.0555
  20. @Published var predictions: Predictions?
  21. @Published var amount: Decimal = 0
  22. @Published var insulinRecommended: Decimal = 0
  23. @Published var insulinRequired: Decimal = 0
  24. @Published var units: GlucoseUnits = .mgdL
  25. @Published var percentage: Decimal = 0
  26. @Published var threshold: Decimal = 0
  27. @Published var maxBolus: Decimal = 0
  28. @Published var errorString: Decimal = 0
  29. @Published var evBG: Decimal = 0
  30. @Published var insulin: Decimal = 0
  31. @Published var isf: Decimal = 0
  32. @Published var error: Bool = false
  33. @Published var minGuardBG: Decimal = 0
  34. @Published var minDelta: Decimal = 0
  35. @Published var expectedDelta: Decimal = 0
  36. @Published var minPredBG: Decimal = 0
  37. @Published var waitForSuggestion: Bool = false
  38. @Published var carbRatio: Decimal = 0
  39. @Published var addButtonPressed: Bool = false
  40. var waitForSuggestionInitial: Bool = false
  41. // added for bolus calculator
  42. @Published var target: Decimal = 0
  43. @Published var cob: Int16 = 0
  44. @Published var iob: Decimal = 0
  45. @Published var currentBG: Decimal = 0
  46. @Published var fifteenMinInsulin: Decimal = 0
  47. @Published var deltaBG: Decimal = 0
  48. @Published var targetDifferenceInsulin: Decimal = 0
  49. @Published var targetDifference: Decimal = 0
  50. @Published var wholeCob: Decimal = 0
  51. @Published var wholeCobInsulin: Decimal = 0
  52. @Published var iobInsulinReduction: Decimal = 0
  53. @Published var wholeCalc: Decimal = 0
  54. @Published var insulinCalculated: Decimal = 0
  55. @Published var fraction: Decimal = 0
  56. @Published var useCalc: Bool = false
  57. @Published var basal: Decimal = 0
  58. @Published var fattyMeals: Bool = false
  59. @Published var fattyMealFactor: Decimal = 0
  60. @Published var useFattyMealCorrectionFactor: Bool = false
  61. @Published var displayPresets: Bool = true
  62. @Published var currentBasal: Decimal = 0
  63. @Published var sweetMeals: Bool = false
  64. @Published var sweetMealFactor: Decimal = 0
  65. @Published var useSuperBolus: Bool = false
  66. @Published var superBolusInsulin: Decimal = 0
  67. @Published var meal: [CarbsEntry]?
  68. @Published var carbs: Decimal = 0
  69. @Published var fat: Decimal = 0
  70. @Published var protein: Decimal = 0
  71. @Published var note: String = ""
  72. @Published var date = Date()
  73. @Published var carbsRequired: Decimal?
  74. @Published var useFPUconversion: Bool = false
  75. @Published var dish: String = ""
  76. @Published var selection: MealPresetStored?
  77. @Published var summation: [String] = []
  78. @Published var maxCarbs: Decimal = 0
  79. @Published var id_: String = ""
  80. @Published var summary: String = ""
  81. @Published var skipBolus: Bool = false
  82. @Published var externalInsulin: Bool = false
  83. @Published var showInfo: Bool = false
  84. @Published var glucoseFromPersistence: [GlucoseStored] = []
  85. @Published var determination: [OrefDetermination] = []
  86. @Published var preprocessedData: [(id: UUID, forecast: Forecast, forecastValue: ForecastValue)] = []
  87. @Published var predictionsForChart: Predictions?
  88. @Published var simulatedDetermination: Determination?
  89. @Published var minForecast: [Int] = []
  90. @Published var maxForecast: [Int] = []
  91. let now = Date.now
  92. let viewContext = CoreDataStack.shared.persistentContainer.viewContext
  93. let backgroundContext = CoreDataStack.shared.newTaskContext()
  94. private var coreDataObserver: CoreDataObserver?
  95. typealias PumpEvent = PumpEventStored.EventType
  96. override func subscribe() {
  97. setupGlucoseNotification()
  98. coreDataObserver = CoreDataObserver()
  99. registerHandlers()
  100. Task {
  101. await updateForecasts()
  102. }
  103. setupGlucoseArray()
  104. setupDeterminationsArray()
  105. broadcaster.register(DeterminationObserver.self, observer: self)
  106. broadcaster.register(BolusFailureObserver.self, observer: self)
  107. units = settingsManager.settings.units
  108. percentage = settingsManager.settings.insulinReqPercentage
  109. maxBolus = provider.pumpSettings().maxBolus
  110. // added
  111. fraction = settings.settings.overrideFactor
  112. useCalc = settings.settings.useCalc
  113. fattyMeals = settings.settings.fattyMeals
  114. fattyMealFactor = settings.settings.fattyMealFactor
  115. sweetMeals = settings.settings.sweetMeals
  116. sweetMealFactor = settings.settings.sweetMealFactor
  117. displayPresets = settings.settings.displayPresets
  118. lowGlucose = settingsManager.settings.low
  119. highGlucose = settingsManager.settings.high
  120. maxCarbs = settings.settings.maxCarbs
  121. skipBolus = settingsManager.settings.skipBolusScreenAfterCarbs
  122. useFPUconversion = settingsManager.settings.useFPUconversion
  123. if waitForSuggestionInitial {
  124. Task {
  125. let ok = await apsManager.determineBasal()
  126. if !ok {
  127. self.waitForSuggestion = false
  128. self.insulinRequired = 0
  129. self.insulinRecommended = 0
  130. }
  131. }
  132. }
  133. }
  134. // MARK: - Basal
  135. func getCurrentBasal() async {
  136. let basalEntries = provider.getProfile()
  137. let now = Date()
  138. let calendar = Calendar.current
  139. let dateFormatter = DateFormatter()
  140. dateFormatter.dateFormat = "HH:mm:ss"
  141. dateFormatter.timeZone = TimeZone.current
  142. for (index, entry) in basalEntries.enumerated() {
  143. guard let entryTime = dateFormatter.date(from: entry.start) else {
  144. print("Invalid entry start time: \(entry.start)")
  145. continue
  146. }
  147. let entryComponents = calendar.dateComponents([.hour, .minute, .second], from: entryTime)
  148. let entryStartTime = calendar.date(
  149. bySettingHour: entryComponents.hour!,
  150. minute: entryComponents.minute!,
  151. second: entryComponents.second!,
  152. of: now
  153. )!
  154. let entryEndTime: Date
  155. if index < basalEntries.count - 1,
  156. let nextEntryTime = dateFormatter.date(from: basalEntries[index + 1].start)
  157. {
  158. let nextEntryComponents = calendar.dateComponents([.hour, .minute, .second], from: nextEntryTime)
  159. entryEndTime = calendar.date(
  160. bySettingHour: nextEntryComponents.hour!,
  161. minute: nextEntryComponents.minute!,
  162. second: nextEntryComponents.second!,
  163. of: now
  164. )!
  165. } else {
  166. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  167. }
  168. if now >= entryStartTime, now < entryEndTime {
  169. await MainActor.run {
  170. currentBasal = entry.rate
  171. }
  172. break
  173. }
  174. }
  175. }
  176. // MARK: CALCULATIONS FOR THE BOLUS CALCULATOR
  177. /// Calculate insulin recommendation
  178. func calculateInsulin() -> Decimal {
  179. // ensure that isf is in mg/dL
  180. var conversion: Decimal {
  181. units == .mmolL ? 0.0555 : 1
  182. }
  183. let isfForCalculation = isf / conversion
  184. // insulin needed for the current blood glucose
  185. targetDifference = currentBG - target
  186. targetDifferenceInsulin = targetDifference / isfForCalculation
  187. // more or less insulin because of bg trend in the last 15 minutes
  188. fifteenMinInsulin = deltaBG / isfForCalculation
  189. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  190. wholeCob = Decimal(cob) + carbs
  191. wholeCobInsulin = wholeCob / carbRatio
  192. // determine how much the calculator reduces/ increases the bolus because of IOB
  193. iobInsulinReduction = (-1) * iob
  194. // adding everything together
  195. // add a calc for the case that no fifteenMinInsulin is available
  196. if deltaBG != 0 {
  197. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  198. } else {
  199. // add (rare) case that no glucose value is available -> maybe display warning?
  200. // if no bg is available, ?? sets its value to 0
  201. if currentBG == 0 {
  202. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  203. } else {
  204. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  205. }
  206. }
  207. // apply custom factor at the end of the calculations
  208. let result = wholeCalc * fraction
  209. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  210. if useFattyMealCorrectionFactor {
  211. insulinCalculated = result * fattyMealFactor
  212. } else if useSuperBolus {
  213. superBolusInsulin = sweetMealFactor * currentBasal
  214. insulinCalculated = result + superBolusInsulin
  215. } else {
  216. insulinCalculated = result
  217. }
  218. // display no negative insulinCalculated
  219. insulinCalculated = max(insulinCalculated, 0)
  220. insulinCalculated = min(insulinCalculated, maxBolus)
  221. guard let apsManager = apsManager else {
  222. debug(.apsManager, "APSManager could not be gracefully unwrapped")
  223. return insulinCalculated
  224. }
  225. return apsManager.roundBolus(amount: insulinCalculated)
  226. }
  227. // MARK: - Button tasks
  228. @MainActor func invokeTreatmentsTask() {
  229. Task {
  230. addButtonPressed = true
  231. let isInsulinGiven = amount > 0
  232. let isCarbsPresent = carbs > 0
  233. let isFatPresent = fat > 0
  234. let isProteinPresent = protein > 0
  235. if isInsulinGiven {
  236. try await handleInsulin(isExternal: externalInsulin)
  237. } else if isCarbsPresent || isFatPresent || isProteinPresent {
  238. waitForSuggestion = true
  239. } else {
  240. hideModal()
  241. return
  242. }
  243. await saveMeal()
  244. // if glucose data is stale end the custom loading animation by hiding the modal
  245. guard glucoseStorage.isGlucoseDataFresh(glucoseFromPersistence.first?.date) else {
  246. waitForSuggestion = false
  247. return hideModal()
  248. }
  249. }
  250. }
  251. // MARK: - Insulin
  252. @MainActor private func handleInsulin(isExternal: Bool) async throws {
  253. if !isExternal {
  254. await addPumpInsulin()
  255. } else {
  256. await addExternalInsulin()
  257. }
  258. waitForSuggestion = true
  259. }
  260. @MainActor func addPumpInsulin() async {
  261. guard amount > 0 else {
  262. showModal(for: nil)
  263. return
  264. }
  265. let maxAmount = Double(min(amount, maxBolus))
  266. do {
  267. let authenticated = try await unlockmanager.unlock()
  268. if authenticated {
  269. await apsManager.enactBolus(amount: maxAmount, isSMB: false)
  270. } else {
  271. print("authentication failed")
  272. }
  273. } catch {
  274. print("authentication error for pump bolus: \(error.localizedDescription)")
  275. DispatchQueue.main.async {
  276. self.waitForSuggestion = false
  277. if self.addButtonPressed {
  278. self.hideModal()
  279. }
  280. }
  281. }
  282. }
  283. private func savePumpInsulin(amount _: Decimal) {
  284. backgroundContext.perform {
  285. // create pump event
  286. let newPumpEvent = PumpEventStored(context: self.backgroundContext)
  287. newPumpEvent.timestamp = Date()
  288. newPumpEvent.type = PumpEvent.bolus.rawValue
  289. // create bolus entry and specify relationship to pump event
  290. let newBolusEntry = BolusStored(context: self.backgroundContext)
  291. newBolusEntry.pumpEvent = newPumpEvent
  292. newBolusEntry.amount = self.amount as NSDecimalNumber
  293. newBolusEntry.isExternal = false
  294. newBolusEntry.isSMB = false
  295. do {
  296. guard self.backgroundContext.hasChanges else { return }
  297. try self.backgroundContext.save()
  298. } catch let error as NSError {
  299. debugPrint(
  300. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to save Bolus with error: \(error.userInfo)"
  301. )
  302. }
  303. }
  304. }
  305. // MARK: - EXTERNAL INSULIN
  306. @MainActor func addExternalInsulin() async {
  307. guard amount > 0 else {
  308. showModal(for: nil)
  309. return
  310. }
  311. amount = min(amount, maxBolus * 3)
  312. do {
  313. let authenticated = try await unlockmanager.unlock()
  314. if authenticated {
  315. // store external dose to pump history
  316. await pumpHistoryStorage.storeExternalInsulinEvent(amount: amount, timestamp: date)
  317. // perform determine basal sync
  318. await apsManager.determineBasalSync()
  319. } else {
  320. print("authentication failed")
  321. }
  322. } catch {
  323. print("authentication error for external insulin: \(error.localizedDescription)")
  324. DispatchQueue.main.async {
  325. self.waitForSuggestion = false
  326. if self.addButtonPressed {
  327. self.hideModal()
  328. }
  329. }
  330. }
  331. }
  332. // MARK: - Carbs
  333. @MainActor func saveMeal() async {
  334. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  335. await MainActor.run {
  336. self.carbs = min(self.carbs, self.maxCarbs)
  337. self.id_ = UUID().uuidString
  338. }
  339. let carbsToStore = [CarbsEntry(
  340. id: id_,
  341. createdAt: now,
  342. actualDate: date,
  343. carbs: carbs,
  344. fat: fat,
  345. protein: protein,
  346. note: note,
  347. enteredBy: CarbsEntry.manual,
  348. isFPU: false, fpuID: UUID().uuidString
  349. )]
  350. await carbsStorage.storeCarbs(carbsToStore)
  351. if carbs > 0 || fat > 0 || protein > 0 {
  352. // only perform determine basal sync if the user doesn't use the pump bolus, otherwise the enact bolus func in the APSManger does a sync
  353. if amount <= 0 {
  354. await apsManager.determineBasalSync()
  355. }
  356. }
  357. }
  358. // MARK: - Presets
  359. func deletePreset() {
  360. if selection != nil {
  361. viewContext.delete(selection!)
  362. do {
  363. guard viewContext.hasChanges else { return }
  364. try viewContext.save()
  365. } catch {
  366. print(error.localizedDescription)
  367. }
  368. carbs = 0
  369. fat = 0
  370. protein = 0
  371. }
  372. selection = nil
  373. }
  374. func removePresetFromNewMeal() {
  375. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  376. if a != nil, summation[a ?? 0] != "" {
  377. summation.remove(at: a!)
  378. }
  379. }
  380. func addPresetToNewMeal() {
  381. let test: String = selection?.dish ?? "dontAdd"
  382. if test != "dontAdd" {
  383. summation.append(test)
  384. }
  385. }
  386. func addNewPresetToWaitersNotepad(_ dish: String) {
  387. summation.append(dish)
  388. }
  389. func addToSummation() {
  390. summation.append(selection?.dish ?? "")
  391. }
  392. func waitersNotepad() -> String {
  393. var filteredArray = summation.filter { !$0.isEmpty }
  394. if carbs == 0, protein == 0, fat == 0 {
  395. filteredArray = []
  396. }
  397. guard filteredArray != [] else {
  398. return ""
  399. }
  400. var carbs_: Decimal = 0.0
  401. var fat_: Decimal = 0.0
  402. var protein_: Decimal = 0.0
  403. var presetArray = [MealPresetStored]()
  404. // TODO: purge Jons code
  405. viewContext.performAndWait {
  406. let requestPresets = MealPresetStored.fetchRequest() as NSFetchRequest<MealPresetStored>
  407. try? presetArray = viewContext.fetch(requestPresets)
  408. }
  409. var waitersNotepad = [String]()
  410. var stringValue = ""
  411. for each in filteredArray {
  412. let countedSet = NSCountedSet(array: filteredArray)
  413. let count = countedSet.count(for: each)
  414. if each != stringValue {
  415. waitersNotepad.append("\(count) \(each)")
  416. }
  417. stringValue = each
  418. for sel in presetArray {
  419. if sel.dish == each {
  420. carbs_ += (sel.carbs)! as Decimal
  421. fat_ += (sel.fat)! as Decimal
  422. protein_ += (sel.protein)! as Decimal
  423. break
  424. }
  425. }
  426. }
  427. let extracarbs = carbs - carbs_
  428. let extraFat = fat - fat_
  429. let extraProtein = protein - protein_
  430. var addedString = ""
  431. if extracarbs > 0, filteredArray.isNotEmpty {
  432. addedString += "Additional carbs: \(extracarbs) ,"
  433. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  434. if extraFat > 0, filteredArray.isNotEmpty {
  435. addedString += "Additional fat: \(extraFat) ,"
  436. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  437. if extraProtein > 0, filteredArray.isNotEmpty {
  438. addedString += "Additional protein: \(extraProtein) ,"
  439. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  440. if addedString != "" {
  441. waitersNotepad.append(addedString)
  442. }
  443. var waitersNotepadString = ""
  444. if waitersNotepad.count == 1 {
  445. waitersNotepadString = waitersNotepad[0]
  446. } else if waitersNotepad.count > 1 {
  447. for each in waitersNotepad {
  448. if each != waitersNotepad.last {
  449. waitersNotepadString += " " + each + ","
  450. } else { waitersNotepadString += " " + each }
  451. }
  452. }
  453. return waitersNotepadString
  454. }
  455. }
  456. }
  457. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  458. func determinationDidUpdate(_: Determination) {
  459. DispatchQueue.main.async {
  460. self.waitForSuggestion = false
  461. if self.addButtonPressed {
  462. self.hideModal()
  463. }
  464. }
  465. }
  466. func bolusDidFail() {
  467. DispatchQueue.main.async {
  468. self.waitForSuggestion = false
  469. if self.addButtonPressed {
  470. self.hideModal()
  471. }
  472. }
  473. }
  474. }
  475. extension Bolus.StateModel {
  476. private func registerHandlers() {
  477. coreDataObserver?.registerHandler(for: "OrefDetermination") { [weak self] in
  478. guard let self = self else { return }
  479. self.setupDeterminationsArray()
  480. }
  481. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  482. coreDataObserver?.registerHandler(for: "GlucoseStored") { [weak self] in
  483. guard let self = self else { return }
  484. self.setupGlucoseArray()
  485. }
  486. }
  487. private func setupGlucoseNotification() {
  488. /// custom notification that is sent when a batch insert of glucose objects is done
  489. Foundation.NotificationCenter.default.addObserver(
  490. self,
  491. selector: #selector(handleBatchInsert),
  492. name: .didPerformBatchInsert,
  493. object: nil
  494. )
  495. }
  496. @objc private func handleBatchInsert() {
  497. setupGlucoseArray()
  498. }
  499. }
  500. // MARK: - Setup Glucose and Determinations
  501. extension Bolus.StateModel {
  502. // Glucose
  503. private func setupGlucoseArray() {
  504. Task {
  505. let ids = await self.fetchGlucose()
  506. let glucoseObjects: [GlucoseStored] = await CoreDataStack.shared.getNSManagedObject(with: ids, context: viewContext)
  507. await updateGlucoseArray(with: glucoseObjects)
  508. }
  509. }
  510. private func fetchGlucose() async -> [NSManagedObjectID] {
  511. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  512. ofType: GlucoseStored.self,
  513. onContext: backgroundContext,
  514. predicate: NSPredicate.predicateForFourHoursAgo,
  515. key: "date",
  516. ascending: false,
  517. fetchLimit: 48
  518. )
  519. return await backgroundContext.perform {
  520. return results.map(\.objectID)
  521. }
  522. }
  523. @MainActor private func updateGlucoseArray(with objects: [GlucoseStored]) {
  524. glucoseFromPersistence = objects
  525. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  526. let thirdLastGlucose = glucoseFromPersistence.dropFirst(2).first?.glucose ?? 0
  527. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  528. currentBG = Decimal(lastGlucose)
  529. deltaBG = delta
  530. }
  531. // Determinations
  532. private func setupDeterminationsArray() {
  533. Task {
  534. let ids = await determinationStorage.fetchLastDeterminationObjectID(
  535. predicate: NSPredicate.predicateFor30MinAgoForDetermination
  536. )
  537. let determinationObjects: [OrefDetermination] = await CoreDataStack.shared
  538. .getNSManagedObject(with: ids, context: viewContext)
  539. async let updateDetermination: () = updateDeterminationsArray(with: determinationObjects)
  540. async let getCurrentBasal: () = getCurrentBasal()
  541. async let updateForecasts: () = updateForecasts()
  542. await updateForecasts
  543. await getCurrentBasal
  544. await updateDetermination
  545. }
  546. }
  547. @MainActor private func updateDeterminationsArray(with objects: [OrefDetermination]) {
  548. guard let mostRecentDetermination = objects.first else { return }
  549. determination = objects
  550. // setup vars for bolus calculation
  551. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  552. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  553. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  554. target = (mostRecentDetermination.currentTarget ?? 100) as Decimal
  555. isf = (mostRecentDetermination.insulinSensitivity ?? 0) as Decimal
  556. cob = mostRecentDetermination.cob as Int16
  557. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  558. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  559. carbRatio = (mostRecentDetermination.carbRatio ?? 0) as Decimal
  560. insulinCalculated = calculateInsulin()
  561. }
  562. }
  563. extension Bolus.StateModel {
  564. func calculateForecasts(predictions: Predictions?) -> ([Int], [Int]) {
  565. let iob: [Int] = predictions?.iob ?? []
  566. let zt: [Int] = predictions?.zt ?? []
  567. let cob: [Int] = predictions?.cob ?? []
  568. let uam: [Int] = predictions?.uam ?? []
  569. // Filter out the empty arrays and find the maximum length of the remaining arrays
  570. let nonEmptyArrays: [[Int]] = [iob, zt, cob, uam].filter { !$0.isEmpty }
  571. guard !nonEmptyArrays.isEmpty, let maxCount = nonEmptyArrays.map(\.count).max(), maxCount > 0 else {
  572. return ([], [])
  573. }
  574. let minForecast = (0 ..< maxCount).map { index -> Int in
  575. let valuesAtCurrentIndex = nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }
  576. return valuesAtCurrentIndex.min() ?? 0
  577. }
  578. let maxForecast = (0 ..< maxCount).map { index -> Int in
  579. let valuesAtCurrentIndex = nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }
  580. return valuesAtCurrentIndex.max() ?? 0
  581. }
  582. return (minForecast, maxForecast)
  583. }
  584. @MainActor func updateForecasts() async {
  585. // Run simulateDetermineBasal on a background thread
  586. let result = await Task.detached { [self] in
  587. await apsManager.simulateDetermineBasal(carbs: carbs, iob: amount)
  588. }.value
  589. simulatedDetermination = result
  590. predictionsForChart = result?.predictions
  591. let iob: [Int] = predictionsForChart?.iob ?? []
  592. let zt: [Int] = predictionsForChart?.zt ?? []
  593. let cob: [Int] = predictionsForChart?.cob ?? []
  594. let uam: [Int] = predictionsForChart?.uam ?? []
  595. // Filter out the empty arrays and find the maximum length of the remaining arrays
  596. let nonEmptyArrays: [[Int]] = [iob, zt, cob, uam].filter { !$0.isEmpty }
  597. guard !nonEmptyArrays.isEmpty, let maxCount = nonEmptyArrays.map(\.count).max(), maxCount > 0 else {
  598. minForecast = []
  599. maxForecast = []
  600. return
  601. }
  602. minForecast = (0 ..< maxCount).map { index -> Int in
  603. let valuesAtCurrentIndex = nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }
  604. return valuesAtCurrentIndex.min() ?? 0
  605. }
  606. maxForecast = (0 ..< maxCount).map { index -> Int in
  607. let valuesAtCurrentIndex = nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }
  608. return valuesAtCurrentIndex.max() ?? 0
  609. }
  610. }
  611. }