ProfileGenerator.swift 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import Foundation
  2. extension Profile {
  3. /// Updates profile properties from preferences where CodingKeys match
  4. /// This function ended up being pretty ugly, but I couldn't think of a cleaner
  5. /// way. I considered converting to JSON or using Mirror, but these weren't
  6. /// great so in the end I think that this approach is simpliest.
  7. ///
  8. /// Also, this implementation does _not_ copy any of the optional properties
  9. /// since these should get set in the `generate` method.
  10. mutating func update(from preferences: Preferences) {
  11. // Decimal properties
  12. maxIob = preferences.maxIOB
  13. min5mCarbImpact = preferences.min5mCarbimpact
  14. maxCOB = preferences.maxCOB
  15. maxDailySafetyMultiplier = preferences.maxDailySafetyMultiplier
  16. currentBasalSafetyMultiplier = preferences.currentBasalSafetyMultiplier
  17. autosensMax = preferences.autosensMax
  18. autosensMin = preferences.autosensMin
  19. halfBasalExerciseTarget = preferences.halfBasalExerciseTarget
  20. remainingCarbsCap = preferences.remainingCarbsCap
  21. smbInterval = preferences.smbInterval
  22. maxSMBBasalMinutes = preferences.maxSMBBasalMinutes
  23. maxUAMSMBBasalMinutes = preferences.maxUAMSMBBasalMinutes
  24. bolusIncrement = preferences.bolusIncrement
  25. carbsReqThreshold = preferences.carbsReqThreshold
  26. remainingCarbsFraction = preferences.remainingCarbsFraction
  27. enableSMBHighBgTarget = preferences.enableSMB_high_bg_target
  28. maxDeltaBgThreshold = preferences.maxDeltaBGthreshold
  29. insulinPeakTime = preferences.insulinPeakTime
  30. noisyCGMTargetMultiplier = preferences.noisyCGMTargetMultiplier
  31. adjustmentFactor = preferences.adjustmentFactor
  32. adjustmentFactorSigmoid = preferences.adjustmentFactorSigmoid
  33. weightPercentage = preferences.weightPercentage
  34. thresholdSetting = preferences.threshold_setting
  35. // Bool properties
  36. highTemptargetRaisesSensitivity = preferences.highTemptargetRaisesSensitivity
  37. lowTemptargetLowersSensitivity = preferences.lowTemptargetLowersSensitivity
  38. sensitivityRaisesTarget = preferences.sensitivityRaisesTarget
  39. resistanceLowersTarget = preferences.resistanceLowersTarget
  40. exerciseMode = preferences.exerciseMode
  41. skipNeutralTemps = preferences.skipNeutralTemps
  42. enableUAM = preferences.enableUAM
  43. a52RiskEnable = preferences.a52RiskEnable
  44. enableSMBWithCOB = preferences.enableSMBWithCOB
  45. enableSMBWithTemptarget = preferences.enableSMBWithTemptarget
  46. allowSMBWithHighTemptarget = preferences.allowSMBWithHighTemptarget
  47. enableSMBAlways = preferences.enableSMBAlways
  48. enableSMBAfterCarbs = preferences.enableSMBAfterCarbs
  49. rewindResetsAutosens = preferences.rewindResetsAutosens
  50. unsuspendIfNoTemp = preferences.unsuspendIfNoTemp
  51. enableSMBHighBg = preferences.enableSMB_high_bg
  52. useCustomPeakTime = preferences.useCustomPeakTime
  53. suspendZerosIob = preferences.suspendZerosIOB
  54. useNewFormula = preferences.useNewFormula
  55. enableDynamicCR = preferences.enableDynamicCR
  56. sigmoid = preferences.sigmoid
  57. tddAdjBasal = preferences.tddAdjBasal
  58. // Enum properties
  59. curve = preferences.curve
  60. }
  61. }
  62. enum ProfileGenerator {
  63. /// This function is a port of the prepare/profile.js function from Trio, and it calls the core OpenAPS function
  64. static func generate(
  65. pumpSettings: PumpSettings,
  66. bgTargets: BGTargets,
  67. basalProfile: [BasalProfileEntry],
  68. isf: InsulinSensitivities,
  69. preferences: Preferences,
  70. carbRatios: CarbRatios,
  71. tempTargets: [TempTarget],
  72. model: String,
  73. freeaps _: FreeAPSSettings
  74. ) throws -> Profile {
  75. let model = model.replacingOccurrences(of: "\"", with: "").trimmingCharacters(in: .whitespacesAndNewlines)
  76. guard !carbRatios.schedule.isEmpty else {
  77. throw ProfileError.invalidCarbRatio
  78. }
  79. var preferences = preferences
  80. switch (preferences.curve, preferences.useCustomPeakTime) {
  81. case (.rapidActing, true):
  82. preferences.insulinPeakTime = max(50, min(preferences.insulinPeakTime, 120))
  83. case (.rapidActing, false):
  84. preferences.insulinPeakTime = 75
  85. case (.ultraRapid, true):
  86. preferences.insulinPeakTime = max(35, min(preferences.insulinPeakTime, 100))
  87. case (.ultraRapid, false):
  88. preferences.insulinPeakTime = 55
  89. default:
  90. // don't do anything
  91. debug(.openAPS, "don't modify insulin peak time")
  92. }
  93. return try generate(
  94. pumpSettings: pumpSettings,
  95. bgTargets: bgTargets,
  96. basalProfile: basalProfile,
  97. isf: isf,
  98. preferences: preferences,
  99. carbRatios: carbRatios,
  100. tempTargets: tempTargets,
  101. model: model
  102. )
  103. }
  104. /// Direct port of the OpenAPS profile generate function
  105. static func generate(
  106. pumpSettings: PumpSettings,
  107. bgTargets: BGTargets,
  108. basalProfile: [BasalProfileEntry],
  109. isf: InsulinSensitivities,
  110. preferences: Preferences,
  111. carbRatios: CarbRatios,
  112. tempTargets: [TempTarget],
  113. model: String
  114. ) throws -> Profile {
  115. var profile = Profile() // start with the defaults
  116. // check if inputs has overrides for any of the default prefs
  117. // and apply if applicable. Note, this comes from the generate/profile.js
  118. // where preferences get copied to the input then in the generate function
  119. // where it checks the input for properties that match the defaults
  120. profile.update(from: preferences)
  121. if pumpSettings.insulinActionCurve > 1 {
  122. profile.dia = pumpSettings.insulinActionCurve
  123. } else {
  124. throw ProfileError.invalidDIA(value: pumpSettings.insulinActionCurve)
  125. }
  126. profile.model = model
  127. profile.skipNeutralTemps = preferences.skipNeutralTemps
  128. profile.currentBasal = try Basal.basalLookup(basalProfile)
  129. profile.basalprofile = basalProfile
  130. let basalProfile = basalProfile
  131. .map { BasalProfileEntry(start: $0.start, minutes: $0.minutes, rate: $0.rate.rounded(scale: 3)) }
  132. profile.maxDailyBasal = Basal.maxDailyBasal(basalProfile)
  133. profile.maxBasal = pumpSettings.maxBasal
  134. // this check is an error check profile.currentBasal === 0 in Javascript
  135. guard let currentBasal = profile.currentBasal, abs(currentBasal) > 0 else {
  136. throw ProfileError.invalidCurrentBasal(value: profile.currentBasal)
  137. }
  138. guard let maxDailyBasal = profile.maxDailyBasal, abs(maxDailyBasal) > 0 else {
  139. throw ProfileError.invalidMaxDailyBasal(value: profile.maxDailyBasal)
  140. }
  141. guard let maxBasal = profile.maxBasal, maxBasal >= 0.1 else {
  142. throw ProfileError.invalidMaxBasal(value: profile.maxBasal)
  143. }
  144. profile.outUnits = bgTargets.userPreferredUnits.rawValue
  145. let (updatedTargets, range) = try Targets.bgTargetsLookup(targets: bgTargets, tempTargets: tempTargets, profile: profile)
  146. profile.minBg = range.minBg?.rounded()
  147. profile.maxBg = range.maxBg?.rounded()
  148. // Note: we're using updatedTargets here because in Javascript the bgTargetsLookup
  149. // function mutates the input, so we want the mutated version in the
  150. // profile and we need to round the properties
  151. let roundedTargets = updatedTargets.targets.map { target -> ComputedBGTargetEntry in
  152. ComputedBGTargetEntry(
  153. low: target.low.rounded(),
  154. high: target.high.rounded(),
  155. start: target.start,
  156. offset: target.offset,
  157. maxBg: target.maxBg?.rounded(),
  158. minBg: target.minBg?.rounded(),
  159. temptargetSet: target.temptargetSet
  160. )
  161. }
  162. // Set the rounded targets on the profile
  163. profile.bgTargets = ComputedBGTargets(
  164. units: updatedTargets.units,
  165. userPreferredUnits: updatedTargets.userPreferredUnits,
  166. targets: roundedTargets
  167. )
  168. profile.temptargetSet = range.temptargetSet
  169. let (sens, isfUpdated) = try Isf.isfLookup(isfDataInput: isf)
  170. profile.sens = sens
  171. profile.isfProfile = isfUpdated
  172. guard let sens = profile.sens, sens >= 5 else {
  173. debug(.openAPS, "ISF of \(String(describing: profile.sens)) is not supported")
  174. throw ProfileError.invalidISF(value: profile.sens)
  175. }
  176. // Handle carb ratio data
  177. guard let currentCarbRatio = Carbs.carbRatioLookup(carbRatio: carbRatios) else {
  178. throw ProfileError.invalidCarbRatio
  179. }
  180. profile.carbRatio = currentCarbRatio
  181. profile.carbRatios = carbRatios
  182. return profile
  183. }
  184. }