ProfileGenerator.swift 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. autotune _: Autotune?,
  74. freeaps _: FreeAPSSettings
  75. ) throws -> Profile {
  76. let model = model.replacingOccurrences(of: "\"", with: "").trimmingCharacters(in: .whitespacesAndNewlines)
  77. guard !carbRatios.schedule.isEmpty else {
  78. throw ProfileError.invalidCarbRatio
  79. }
  80. var preferences = preferences
  81. switch (preferences.curve, preferences.useCustomPeakTime) {
  82. case (.rapidActing, true):
  83. preferences.insulinPeakTime = max(50, min(preferences.insulinPeakTime, 120))
  84. case (.rapidActing, false):
  85. preferences.insulinPeakTime = 75
  86. case (.ultraRapid, true):
  87. preferences.insulinPeakTime = max(35, min(preferences.insulinPeakTime, 100))
  88. case (.ultraRapid, false):
  89. preferences.insulinPeakTime = 55
  90. default:
  91. // don't do anything
  92. debug(.openAPS, "don't modify insulin peak time")
  93. }
  94. return try generate(
  95. pumpSettings: pumpSettings,
  96. bgTargets: bgTargets,
  97. basalProfile: basalProfile,
  98. isf: isf,
  99. preferences: preferences,
  100. carbRatios: carbRatios,
  101. tempTargets: tempTargets,
  102. model: model
  103. )
  104. }
  105. /// Direct port of the OpenAPS profile generate function
  106. static func generate(
  107. pumpSettings: PumpSettings,
  108. bgTargets: BGTargets,
  109. basalProfile: [BasalProfileEntry],
  110. isf: InsulinSensitivities,
  111. preferences: Preferences,
  112. carbRatios: CarbRatios,
  113. tempTargets: [TempTarget],
  114. model: String
  115. ) throws -> Profile {
  116. var profile = Profile() // start with the defaults
  117. // check if inputs has overrides for any of the default prefs
  118. // and apply if applicable. Note, this comes from the generate/profile.js
  119. // where preferences get copied to the input then in the generate function
  120. // where it checks the input for properties that match the defaults
  121. profile.update(from: preferences)
  122. if pumpSettings.insulinActionCurve > 1 {
  123. profile.dia = pumpSettings.insulinActionCurve
  124. } else {
  125. throw ProfileError.invalidDIA(value: pumpSettings.insulinActionCurve)
  126. }
  127. profile.model = model
  128. profile.skipNeutralTemps = preferences.skipNeutralTemps
  129. profile.currentBasal = try Basal.basalLookup(basalProfile)
  130. profile.basalprofile = basalProfile
  131. let basalProfile = basalProfile
  132. .map { BasalProfileEntry(start: $0.start, minutes: $0.minutes, rate: $0.rate.rounded(scale: 3)) }
  133. profile.maxDailyBasal = Basal.maxDailyBasal(basalProfile)
  134. profile.maxBasal = pumpSettings.maxBasal
  135. // this check is an error check profile.currentBasal === 0 in Javascript
  136. guard let currentBasal = profile.currentBasal, abs(currentBasal) > 0 else {
  137. throw ProfileError.invalidCurrentBasal(value: profile.currentBasal)
  138. }
  139. guard let maxDailyBasal = profile.maxDailyBasal, abs(maxDailyBasal) > 0 else {
  140. throw ProfileError.invalidMaxDailyBasal(value: profile.maxDailyBasal)
  141. }
  142. guard let maxBasal = profile.maxBasal, maxBasal >= 0.1 else {
  143. throw ProfileError.invalidMaxBasal(value: profile.maxBasal)
  144. }
  145. profile.outUnits = bgTargets.userPreferredUnits.rawValue
  146. let (updatedTargets, range) = try Targets.bgTargetsLookup(targets: bgTargets, tempTargets: tempTargets, profile: profile)
  147. profile.minBg = range.minBg?.rounded()
  148. profile.maxBg = range.maxBg?.rounded()
  149. // Note: we're using updatedTargets here because in Javascript the bgTargetsLookup
  150. // function mutates the input, so we want the mutated version in the
  151. // profile and we need to round the properties
  152. let roundedTargets = updatedTargets.targets.map { target -> ComputedBGTargetEntry in
  153. ComputedBGTargetEntry(
  154. low: target.low.rounded(),
  155. high: target.high.rounded(),
  156. start: target.start,
  157. offset: target.offset,
  158. maxBg: target.maxBg?.rounded(),
  159. minBg: target.minBg?.rounded(),
  160. temptargetSet: target.temptargetSet
  161. )
  162. }
  163. // Set the rounded targets on the profile
  164. profile.bgTargets = ComputedBGTargets(
  165. units: updatedTargets.units,
  166. userPreferredUnits: updatedTargets.userPreferredUnits,
  167. targets: roundedTargets
  168. )
  169. profile.temptargetSet = range.temptargetSet
  170. let (sens, isfUpdated) = try Isf.isfLookup(isfDataInput: isf)
  171. profile.sens = sens
  172. profile.isfProfile = isfUpdated
  173. guard let sens = profile.sens, sens >= 5 else {
  174. debug(.openAPS, "ISF of \(String(describing: profile.sens)) is not supported")
  175. throw ProfileError.invalidISF(value: profile.sens)
  176. }
  177. // Handle carb ratio data
  178. guard let currentCarbRatio = Carbs.carbRatioLookup(carbRatio: carbRatios) else {
  179. throw ProfileError.invalidCarbRatio
  180. }
  181. profile.carbRatio = currentCarbRatio
  182. profile.carbRatios = carbRatios
  183. return profile
  184. }
  185. }