ProfileGenerator.swift 8.9 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. skipNeutralTemps = preferences.skipNeutralTemps
  41. enableUAM = preferences.enableUAM
  42. a52RiskEnable = preferences.a52RiskEnable
  43. enableSMBWithCOB = preferences.enableSMBWithCOB
  44. enableSMBWithTemptarget = preferences.enableSMBWithTemptarget
  45. allowSMBWithHighTemptarget = preferences.allowSMBWithHighTemptarget
  46. enableSMBAlways = preferences.enableSMBAlways
  47. enableSMBAfterCarbs = preferences.enableSMBAfterCarbs
  48. rewindResetsAutosens = preferences.rewindResetsAutosens
  49. unsuspendIfNoTemp = preferences.unsuspendIfNoTemp
  50. enableSMBHighBg = preferences.enableSMB_high_bg
  51. useCustomPeakTime = preferences.useCustomPeakTime
  52. suspendZerosIob = preferences.suspendZerosIOB
  53. useNewFormula = preferences.useNewFormula
  54. enableDynamicCR = preferences.enableDynamicCR
  55. sigmoid = preferences.sigmoid
  56. tddAdjBasal = preferences.tddAdjBasal
  57. // Enum properties
  58. curve = preferences.curve
  59. }
  60. }
  61. enum ProfileGenerator {
  62. /// This function is a port of the prepare/profile.js function from Trio, and it calls the core OpenAPS function
  63. static func generate(
  64. pumpSettings: PumpSettings,
  65. bgTargets: BGTargets,
  66. basalProfile: [BasalProfileEntry],
  67. isf: InsulinSensitivities,
  68. preferences: Preferences,
  69. carbRatios: CarbRatios,
  70. tempTargets: [TempTarget],
  71. model: String,
  72. freeaps _: FreeAPSSettings
  73. ) throws -> Profile {
  74. let model = model.replacingOccurrences(of: "\"", with: "").trimmingCharacters(in: .whitespacesAndNewlines)
  75. guard !carbRatios.schedule.isEmpty else {
  76. throw ProfileError.invalidCarbRatio
  77. }
  78. var preferences = preferences
  79. switch (preferences.curve, preferences.useCustomPeakTime) {
  80. case (.rapidActing, true):
  81. preferences.insulinPeakTime = max(50, min(preferences.insulinPeakTime, 120))
  82. case (.rapidActing, false):
  83. preferences.insulinPeakTime = 75
  84. case (.ultraRapid, true):
  85. preferences.insulinPeakTime = max(35, min(preferences.insulinPeakTime, 100))
  86. case (.ultraRapid, false):
  87. preferences.insulinPeakTime = 55
  88. default:
  89. // don't do anything
  90. debug(.openAPS, "don't modify insulin peak time")
  91. }
  92. return try generate(
  93. pumpSettings: pumpSettings,
  94. bgTargets: bgTargets,
  95. basalProfile: basalProfile,
  96. isf: isf,
  97. preferences: preferences,
  98. carbRatios: carbRatios,
  99. tempTargets: tempTargets,
  100. model: model
  101. )
  102. }
  103. /// Direct port of the OpenAPS profile generate function
  104. static func generate(
  105. pumpSettings: PumpSettings,
  106. bgTargets: BGTargets,
  107. basalProfile: [BasalProfileEntry],
  108. isf: InsulinSensitivities,
  109. preferences: Preferences,
  110. carbRatios: CarbRatios,
  111. tempTargets: [TempTarget],
  112. model: String
  113. ) throws -> Profile {
  114. var profile = Profile() // start with the defaults
  115. // check if inputs has overrides for any of the default prefs
  116. // and apply if applicable. Note, this comes from the generate/profile.js
  117. // where preferences get copied to the input then in the generate function
  118. // where it checks the input for properties that match the defaults
  119. profile.update(from: preferences)
  120. // in the Javascript version this check is for 1, but in Trio
  121. // the minimum dia you can set with the UI is 5
  122. guard pumpSettings.insulinActionCurve >= 5 else {
  123. throw ProfileError.invalidDIA(value: pumpSettings.insulinActionCurve)
  124. }
  125. profile.dia = pumpSettings.insulinActionCurve
  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. }