Просмотр исходного кода

Merge pull request #416 from nightscout/refactor-dynamic-settings

marv-out 1 год назад
Родитель
Сommit
49563ba351

+ 1 - 150
Trio/Sources/APS/APSManager.swift

@@ -117,7 +117,7 @@ final class BaseAPSManager: APSManager, Injectable {
 
     init(resolver: Resolver) {
         injectServices(resolver)
-        openAPS = OpenAPS(storage: storage)
+        openAPS = OpenAPS(storage: storage, tddStorage: tddStorage)
         subscribe()
         lastLoopDateSubject.send(lastLoopDate)
 
@@ -715,10 +715,6 @@ final class BaseAPSManager: APSManager, Injectable {
                 guard self.privateContext.hasChanges else { return }
                 try self.privateContext.save()
                 debug(.apsManager, "Determination enacted. Enacted: \(wasEnacted)")
-
-                Task.detached(priority: .low) {
-                    await self.statistics()
-                }
             }
         } catch {
             debug(
@@ -904,125 +900,6 @@ final class BaseAPSManager: APSManager, Injectable {
         }
     }
 
-    // TODO: - Refactor this whole shit here...
-
-    // Add to statistics.JSON for upload to NS.
-    private func statistics() async {
-        let now = Date()
-        if settingsManager.settings.uploadStats != nil {
-            let hour = Calendar.current.component(.hour, from: now)
-            guard hour > 20 else {
-                return
-            }
-
-            // MARK: - Core Data related
-
-            async let glucoseStats = glucoseForStats()
-            async let lastLoopForStats = lastLoopForStats()
-            async let carbTotal = carbsForStats()
-            async let preferences = settingsManager.preferences
-
-            let loopStats = await loopStats(oneDayGlucose: Double(rawValue: (await glucoseStats?.oneDayGlucose.readings)!) ?? 0.0)
-
-            // Only save and upload once per day
-            guard (-1 * (await lastLoopForStats ?? .distantPast).timeIntervalSinceNow.hours) > 22 else { return }
-
-            let units = settingsManager.settings.units
-
-            // MARK: - Not Core Data related stuff
-
-            let pref = await preferences
-            var algo_ = "Oref0"
-
-            if pref.sigmoid, pref.enableDynamicCR {
-                algo_ = "Dynamic ISF + CR: Sigmoid"
-            } else if pref.sigmoid, !pref.enableDynamicCR {
-                algo_ = "Dynamic ISF: Sigmoid"
-            } else if pref.useNewFormula, pref.enableDynamicCR {
-                algo_ = "Dynamic ISF + CR: Logarithmic"
-            } else if pref.useNewFormula, !pref.sigmoid,!pref.enableDynamicCR {
-                algo_ = "Dynamic ISF: Logarithmic"
-            }
-            let af = pref.adjustmentFactor
-            let insulin_type = pref.curve
-            let buildDate = BuildDetails.shared.buildDate()
-            let version = Bundle.main.releaseVersionNumber
-            let build = Bundle.main.buildVersionNumber
-
-            var branch = BuildDetails.shared.branchAndSha
-
-            let copyrightNotice_ = Bundle.main.infoDictionary?["NSHumanReadableCopyright"] as? String ?? ""
-            let pump_ = pumpManager?.localizedTitle ?? ""
-            let cgm = settingsManager.settings.cgm
-            let file = OpenAPS.Monitor.statistics
-            var iPa: Decimal = 75
-            if pref.useCustomPeakTime {
-                iPa = pref.insulinPeakTime
-            } else if pref.curve.rawValue == "rapid-acting" {
-                iPa = 65
-            } else if pref.curve.rawValue == "ultra-rapid" {
-                iPa = 50
-            }
-
-            // Insulin placeholder
-            let insulin = Ins(
-                TDD: 0,
-                bolus: 0,
-                temp_basal: 0,
-                scheduled_basal: 0,
-                total_average: 0
-            )
-            guard let processedGlucoseStats = await glucoseStats else { return }
-
-            let eA1cDisplayUnit = processedGlucoseStats.eA1cDisplayUnit
-
-            let dailystat = await Statistics(
-                created_at: Date(),
-                iPhone: UIDevice.current.getDeviceId,
-                iOS: UIDevice.current.getOSInfo,
-                Build_Version: version ?? "",
-                Build_Number: build ?? "1",
-                Branch: branch,
-                CopyRightNotice: String(copyrightNotice_.prefix(32)),
-                Build_Date: buildDate ?? Date(),
-                Algorithm: algo_,
-                AdjustmentFactor: af,
-                Pump: pump_,
-                CGM: cgm.rawValue,
-                insulinType: insulin_type.rawValue,
-                peakActivityTime: iPa,
-                Carbs_24h: await carbTotal,
-                GlucoseStorage_Days: Decimal(roundDouble(Double(rawValue: processedGlucoseStats.numberofDays) ?? 0.0, 1)),
-                Statistics: Stats(
-                    Distribution: processedGlucoseStats.TimeInRange,
-                    Glucose: processedGlucoseStats.avg,
-                    EstimatedA1c: processedGlucoseStats.hbs,
-                    Units: Units(Glucose: units.rawValue, EstimatedA1c: eA1cDisplayUnit.rawValue),
-                    LoopCycles: loopStats,
-                    Insulin: insulin,
-                    Variance: processedGlucoseStats.variance
-                )
-            )
-            storage.save(dailystat, as: file)
-
-            await saveStatsToCoreData()
-        }
-    }
-
-    private func saveStatsToCoreData() async {
-        await privateContext.perform {
-            let saveStatsCoreData = StatsData(context: self.privateContext)
-            saveStatsCoreData.lastrun = Date()
-
-            do {
-                guard self.privateContext.hasChanges else { return }
-                try self.privateContext.save()
-            } catch {
-                print(error.localizedDescription)
-            }
-        }
-    }
-
     private func lastLoopForStats() async -> Date? {
         let requestStats = StatsData.fetchRequest() as NSFetchRequest<StatsData>
         let sortStats = NSSortDescriptor(key: "lastrun", ascending: false)
@@ -1039,32 +916,6 @@ final class BaseAPSManager: APSManager, Injectable {
         }
     }
 
-    private func carbsForStats() async -> Decimal {
-        let requestCarbs = CarbEntryStored.fetchRequest() as NSFetchRequest<CarbEntryStored>
-        let daysAgo = Date().addingTimeInterval(-1.days.timeInterval)
-        requestCarbs.predicate = NSPredicate(format: "carbs > 0 AND date > %@", daysAgo as NSDate)
-        requestCarbs.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
-
-        return await privateContext.perform {
-            do {
-                let carbs = try self.privateContext.fetch(requestCarbs)
-                debugPrint(
-                    "APSManager: statistics() -> \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) fetched carbs"
-                )
-
-                return carbs.reduce(0) { sum, meal in
-                    let mealCarbs = Decimal(string: "\(meal.carbs)") ?? Decimal.zero
-                    return sum + mealCarbs
-                }
-            } catch {
-                debugPrint(
-                    "APSManager: statistics() -> \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) error while fetching carbs"
-                )
-                return 0
-            }
-        }
-    }
-
     private func loopStats(oneDayGlucose: Double) async -> LoopCycles {
         let requestLSR = LoopStatRecord.fetchRequest() as NSFetchRequest<LoopStatRecord>
         requestLSR.predicate = NSPredicate(

+ 16 - 5
Trio/Sources/APS/OpenAPS/OpenAPS.swift

@@ -8,13 +8,15 @@ final class OpenAPS {
     private let processQueue = DispatchQueue(label: "OpenAPS.processQueue", qos: .utility)
 
     private let storage: FileStorage
+    private let tddStorage: TDDStorage
 
     let context = CoreDataStack.shared.newTaskContext()
 
     let jsonConverter = JSONConverter()
 
-    init(storage: FileStorage) {
+    init(storage: FileStorage, tddStorage: TDDStorage) {
         self.storage = storage
+        self.tddStorage = tddStorage
     }
 
     static let dateFormatter: ISO8601DateFormatter = {
@@ -284,7 +286,8 @@ final class OpenAPS {
         async let basalAsync = loadFileFromStorageAsync(name: Settings.basalProfile)
         async let autosenseAsync = loadFileFromStorageAsync(name: Settings.autosense)
         async let reservoirAsync = loadFileFromStorageAsync(name: Monitor.reservoir)
-        async let preferencesAsync = loadFileFromStorageAsync(name: Settings.preferences)
+        async let preferencesAsync = storage.retrieveAsync(OpenAPS.Settings.preferences, as: Preferences.self) ?? Preferences()
+        async let hasSufficientTddForDynamic = tddStorage.hasSufficientTDD()
 
         // Await the results of asynchronous tasks
         let (
@@ -296,7 +299,7 @@ final class OpenAPS {
             basalProfile,
             autosens,
             reservoir,
-            preferences
+            hasSufficientTdd
         ) = await (
             try parsePumpHistory(await pumpHistoryObjectIDs, simulatedBolusAmount: simulatedBolusAmount),
             try carbs,
@@ -306,7 +309,7 @@ final class OpenAPS {
             basalAsync,
             autosenseAsync,
             reservoirAsync,
-            preferencesAsync
+            try hasSufficientTddForDynamic
         )
 
         // Meal calculation
@@ -332,6 +335,14 @@ final class OpenAPS {
             storage.save(iob, as: Monitor.iob)
         }
 
+        var preferences = await preferencesAsync
+
+        if !hasSufficientTdd, preferences.useNewFormula || (preferences.useNewFormula && preferences.sigmoid) {
+            debug(.openAPS, "Insufficient TDD for dynamic formula; disabling for determine basal run.")
+            preferences.useNewFormula = false
+            preferences.sigmoid = false
+        }
+
         // Determine basal
         let orefDetermination = try await determineBasal(
             glucose: glucoseAsJSON,
@@ -348,7 +359,7 @@ final class OpenAPS {
             oref2_variables: oref2_variables
         )
 
-        debug(.openAPS, "Determinated: \(orefDetermination)")
+        debug(.openAPS, "OREF DETERMINATION: \(orefDetermination)")
 
         if var determination = Determination(from: orefDetermination), let deliverAt = determination.deliverAt {
             // set both timestamp and deliverAt to the SAME date; this will be updated for timestamp once it is enacted

+ 142 - 113
Trio/Sources/APS/Storage/TDDStorage.swift

@@ -1,3 +1,4 @@
+import CoreData
 import Foundation
 import LoopKitUI
 import Swinject
@@ -10,6 +11,7 @@ protocol TDDStorage {
     ) async throws
         -> TDDResult
     func storeTDD(_ tddResult: TDDResult) async
+    func hasSufficientTDD() async throws -> Bool
 }
 
 /// Structure containing the results of TDD calculations
@@ -25,12 +27,13 @@ struct TDDResult {
 /// Implementation of the TDD Calculator
 final class BaseTDDStorage: TDDStorage, Injectable {
     @Injected() private var storage: FileStorage!
+    
+    private let privateContext = CoreDataStack.shared.newTaskContext()
 
     init(resolver: Resolver) {
         injectServices(resolver)
     }
 
-    private let privateContext = CoreDataStack.shared.newTaskContext()
 
     /// Main function to calculate TDD from pump history and basal profile
     /// - Parameters:
@@ -395,118 +398,118 @@ final class BaseTDDStorage: TDDStorage, Injectable {
 
         return gaps
     }
-
-//    /// Finds gaps between tempBasal events where scheduled basal ran, excluding suspend-resume periods
-//    /// - Parameters:
-//    ///   - tempBasalEvents: Array of pump history events of type tempBasal
-//    ///   - suspendResumePairs: Array of suspend and resume event pairs
-//    /// - Returns: Array of gaps, where each gap has a start and end time
-//    private func findBasalGaps(
-//        in tempBasalEvents: [PumpHistoryEvent],
-//        excluding suspendResumePairs: [(suspend: PumpHistoryEvent, resume: PumpHistoryEvent)]
-//    ) -> [(start: Date, end: Date)] {
-//        guard !tempBasalEvents.isEmpty else {
-//            let startOfDay = Calendar.current.startOfDay(for: Date())
-//            return [(start: startOfDay, end: startOfDay.addingTimeInterval(24 * 60 * 60 - 1))]
-//        }
-//
-//        // Merge temp basal and suspend-resume events into a unified timeline
-//        var timeline = [(start: Date, end: Date, type: EventType)]()
-//
-//        for event in tempBasalEvents {
-//            guard let duration = event.duration else { continue }
-//            let eventEnd = event.timestamp.addingTimeInterval(TimeInterval(duration * 60))
-//            timeline.append((start: event.timestamp, end: eventEnd, type: .tempBasal))
-//        }
-//
-//        for suspendResume in suspendResumePairs {
-//            timeline.append((start: suspendResume.suspend.timestamp, end: suspendResume.resume.timestamp, type: .pumpSuspend))
-//        }
-//
-//        // Sort the timeline by start time
-//        timeline.sort { $0.start < $1.start }
-//
-//        // Process the timeline to calculate gaps
-//        var gaps = [(start: Date, end: Date)]()
-//        var lastEndTime = Calendar.current.startOfDay(for: timeline.first!.start)
-//        let endOfDay = lastEndTime.addingTimeInterval(24 * 60 * 60 - 1)
-//
-//        for interval in timeline {
-//            if interval.type == .pumpSuspend {
-//                // Extend lastEndTime for suspend periods
-//                lastEndTime = max(lastEndTime, interval.end)
-//                continue
-//            }
-//
-//            if interval.start > lastEndTime {
-//                // Add a gap if there is a gap between lastEndTime and interval.start
-//                gaps.append((start: lastEndTime, end: interval.start))
-//            }
-//
-//            // Update lastEndTime to the maximum end time encountered
-//            lastEndTime = max(lastEndTime, interval.end)
-//        }
-//
-//        if lastEndTime < endOfDay {
-//            // Add a final gap if the lastEndTime is before the end of the day
-//            gaps.append((start: lastEndTime, end: endOfDay))
-//        }
-//
-//        return gaps
-//    }
-
-//    /// Calculates scheduled basal insulin delivery during gaps between temporary basals
-//    /// - Parameters:
-//    ///   - gaps: Array of time periods where scheduled basal was active
-//    ///   - profile: Basal profile entries defining rates throughout the day
-//    ///   - roundToSupportedBasalRate: Closure to round rates to pump-supported values
-//    /// - Returns: Total insulin delivered via scheduled basal in units
-//    private func calculateScheduledBasalInsulin(
-//        gaps: [(start: Date, end: Date)],
-//        profile: [BasalProfileEntry],
-//        roundToSupportedBasalRate: @escaping (_ unitsPerHour: Double) -> Double
-//    ) -> Decimal {
-//        // Initialize cached formatter for time string conversion
-//        let timeFormatter: DateFormatter = {
-//            let formatter = DateFormatter()
-//            formatter.dateFormat = "HH:mm:ss"
-//            return formatter
-//        }()
-//
-//        // Pre-calculate profile switch times for efficient lookup
-//        let profileSwitches = profile.map(\.minutes)
-//
-//        return gaps.reduce(into: Decimal(0)) { totalInsulin, gap in
-//            var currentTime = gap.start
-//
-//            while currentTime < gap.end {
-//                // Find applicable basal rate for the current time
-//                guard let rate = findBasalRate(
-//                    for: timeFormatter.string(from: currentTime),
-//                    in: profile
-//                ) else { break }
-//
-//                // Determine when the rate changes (profile switch or gap end)
-//                let nextSwitchTime = getNextBasalRateSwitch(
-//                    after: currentTime,
-//                    switches: profileSwitches,
-//                    calendar: Calendar.current
-//                ) ?? gap.end
-//                let endTime = min(nextSwitchTime, gap.end)
-//                let durationHours = Decimal(endTime.timeIntervalSince(currentTime)) / 3600
-//
-//                let insulin = Decimal(roundToSupportedBasalRate(Double(rate * durationHours)))
-//                totalInsulin += insulin
-//
-//                debug(
-//                    .apsManager,
-//                    "Scheduled Insulin added: \(insulin) U. Duration: \(durationHours) hrs (\(currentTime)-\(endTime))"
-//                )
-//
-//                currentTime = endTime
-//            }
-//        }
-//    }
+    
+    //    /// Finds gaps between tempBasal events where scheduled basal ran, excluding suspend-resume periods
+    //    /// - Parameters:
+    //    ///   - tempBasalEvents: Array of pump history events of type tempBasal
+    //    ///   - suspendResumePairs: Array of suspend and resume event pairs
+    //    /// - Returns: Array of gaps, where each gap has a start and end time
+    //    private func findBasalGaps(
+    //        in tempBasalEvents: [PumpHistoryEvent],
+    //        excluding suspendResumePairs: [(suspend: PumpHistoryEvent, resume: PumpHistoryEvent)]
+    //    ) -> [(start: Date, end: Date)] {
+    //        guard !tempBasalEvents.isEmpty else {
+    //            let startOfDay = Calendar.current.startOfDay(for: Date())
+    //            return [(start: startOfDay, end: startOfDay.addingTimeInterval(24 * 60 * 60 - 1))]
+    //        }
+    //
+    //        // Merge temp basal and suspend-resume events into a unified timeline
+    //        var timeline = [(start: Date, end: Date, type: EventType)]()
+    //
+    //        for event in tempBasalEvents {
+    //            guard let duration = event.duration else { continue }
+    //            let eventEnd = event.timestamp.addingTimeInterval(TimeInterval(duration * 60))
+    //            timeline.append((start: event.timestamp, end: eventEnd, type: .tempBasal))
+    //        }
+    //
+    //        for suspendResume in suspendResumePairs {
+    //            timeline.append((start: suspendResume.suspend.timestamp, end: suspendResume.resume.timestamp, type: .pumpSuspend))
+    //        }
+    //
+    //        // Sort the timeline by start time
+    //        timeline.sort { $0.start < $1.start }
+    //
+    //        // Process the timeline to calculate gaps
+    //        var gaps = [(start: Date, end: Date)]()
+    //        var lastEndTime = Calendar.current.startOfDay(for: timeline.first!.start)
+    //        let endOfDay = lastEndTime.addingTimeInterval(24 * 60 * 60 - 1)
+    //
+    //        for interval in timeline {
+    //            if interval.type == .pumpSuspend {
+    //                // Extend lastEndTime for suspend periods
+    //                lastEndTime = max(lastEndTime, interval.end)
+    //                continue
+    //            }
+    //
+    //            if interval.start > lastEndTime {
+    //                // Add a gap if there is a gap between lastEndTime and interval.start
+    //                gaps.append((start: lastEndTime, end: interval.start))
+    //            }
+    //
+    //            // Update lastEndTime to the maximum end time encountered
+    //            lastEndTime = max(lastEndTime, interval.end)
+    //        }
+    //
+    //        if lastEndTime < endOfDay {
+    //            // Add a final gap if the lastEndTime is before the end of the day
+    //            gaps.append((start: lastEndTime, end: endOfDay))
+    //        }
+    //
+    //        return gaps
+    //    }
+
+    //    /// Calculates scheduled basal insulin delivery during gaps between temporary basals
+    //    /// - Parameters:
+    //    ///   - gaps: Array of time periods where scheduled basal was active
+    //    ///   - profile: Basal profile entries defining rates throughout the day
+    //    ///   - roundToSupportedBasalRate: Closure to round rates to pump-supported values
+    //    /// - Returns: Total insulin delivered via scheduled basal in units
+    //    private func calculateScheduledBasalInsulin(
+    //        gaps: [(start: Date, end: Date)],
+    //        profile: [BasalProfileEntry],
+    //        roundToSupportedBasalRate: @escaping (_ unitsPerHour: Double) -> Double
+    //    ) -> Decimal {
+    //        // Initialize cached formatter for time string conversion
+    //        let timeFormatter: DateFormatter = {
+    //            let formatter = DateFormatter()
+    //            formatter.dateFormat = "HH:mm:ss"
+    //            return formatter
+    //        }()
+    //
+    //        // Pre-calculate profile switch times for efficient lookup
+    //        let profileSwitches = profile.map(\.minutes)
+    //
+    //        return gaps.reduce(into: Decimal(0)) { totalInsulin, gap in
+    //            var currentTime = gap.start
+    //
+    //            while currentTime < gap.end {
+    //                // Find applicable basal rate for the current time
+    //                guard let rate = findBasalRate(
+    //                    for: timeFormatter.string(from: currentTime),
+    //                    in: profile
+    //                ) else { break }
+    //
+    //                // Determine when the rate changes (profile switch or gap end)
+    //                let nextSwitchTime = getNextBasalRateSwitch(
+    //                    after: currentTime,
+    //                    switches: profileSwitches,
+    //                    calendar: Calendar.current
+    //                ) ?? gap.end
+    //                let endTime = min(nextSwitchTime, gap.end)
+    //                let durationHours = Decimal(endTime.timeIntervalSince(currentTime)) / 3600
+    //
+    //                let insulin = Decimal(roundToSupportedBasalRate(Double(rate * durationHours)))
+    //                totalInsulin += insulin
+    //
+    //                debug(
+    //                    .apsManager,
+    //                    "Scheduled Insulin added: \(insulin) U. Duration: \(durationHours) hrs (\(currentTime)-\(endTime))"
+    //                )
+    //
+    //                currentTime = endTime
+    //            }
+    //        }
+    //    }
 
     /// Finds the next basal rate switch time after a given time
     /// - Parameters:
@@ -634,6 +637,32 @@ final class BaseTDDStorage: TDDStorage, Injectable {
             return weightedTDD.truncated(toPlaces: 3)
         }
     }
+
+    /// Checks if there is enough Total Daily Dose (TDD) data collected over the past 7 days.
+    ///
+    /// This function performs a count fetch for TDDStored records in Core Data where:
+    /// - The record's date is within the last 7 days.
+    /// - The total value is greater than 0.
+    ///
+    /// It then checks if at least 85% of the expected data points are present,
+    /// assuming at least 288 expected entries per day (one every 5 minutes).
+    ///
+    /// - Returns: `true` if sufficient TDD data is available, otherwise `false`.
+    /// - Throws: An error if the Core Data count operation fails.
+    func hasSufficientTDD() async throws -> Bool {
+        try await privateContext.perform {
+            let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "TDDStored")
+            fetchRequest.predicate = NSPredicate(
+                format: "date > %@ AND total > 0",
+                Date().addingTimeInterval(-86400 * 7) as NSDate
+            )
+            fetchRequest.resultType = .countResultType
+
+            let count = try self.privateContext.count(for: fetchRequest)
+            let threshold = Int(Double(7 * 288) * 0.85)
+            return count >= threshold
+        }
+    }
 }
 
 /// Extension for rounding Decimal numbers

Разница между файлами не показана из-за своего большого размера
+ 42 - 0
Trio/Sources/Localizations/Main/Localizable.xcstrings


+ 2 - 1
Trio/Sources/Models/Preferences.swift

@@ -298,8 +298,9 @@ extension Preferences: Decodable {
             preferences.sigmoid = sigmoid
         }
 
+        // FIXME: remove this at a later release; hard code it to false for now
         if let enableDynamicCR = try? container.decode(Bool.self, forKey: .enableDynamicCR) {
-            preferences.enableDynamicCR = enableDynamicCR
+            preferences.enableDynamicCR = false
         }
 
         if let useNewFormula = try? container.decode(Bool.self, forKey: .useNewFormula) {

+ 118 - 4
Trio/Sources/Modules/DynamicSettings/DynamicSettingsStateModel.swift

@@ -1,3 +1,5 @@
+import Combine
+import CoreData
 import Observation
 import SwiftUI
 
@@ -5,9 +7,28 @@ extension DynamicSettings {
     final class StateModel: BaseStateModel<Provider> {
         @Injected() var settings: SettingsManager!
         @Injected() var storage: FileStorage!
+        @Injected() var tddStorage: TDDStorage!
 
+        // this is an *interim* fix to provide better UI/UX
+        // FIXME: needs to be refactored, once oref-swift lands and dynamicISF becomes swift-bound
+        @Published var dynamicSensitivityType: DynamicSensitivityType = .disabled {
+            didSet {
+                switch dynamicSensitivityType {
+                case .logarithmic:
+                    useNewFormula = true
+                    sigmoid = false
+                case .sigmoid:
+                    useNewFormula = true
+                    sigmoid = true
+                default:
+                    useNewFormula = false
+                    sigmoid = false
+                }
+            }
+        }
+
+        @Published var hasValidTDD: Bool = false
         @Published var useNewFormula: Bool = false
-        @Published var enableDynamicCR: Bool = false
         @Published var sigmoid: Bool = false
         @Published var adjustmentFactor: Decimal = 0.8
         @Published var adjustmentFactorSigmoid: Decimal = 0.5
@@ -15,19 +36,90 @@ extension DynamicSettings {
         @Published var tddAdjBasal: Bool = false
         @Published var threshold_setting: Decimal = 60
 
+        @ObservedObject var pickerSettingsProvider = PickerSettingsProvider.shared
+
         var units: GlucoseUnits = .mgdL
 
+        let context = CoreDataStack.shared.newTaskContext()
+
         override func subscribe() {
             units = settingsManager.settings.units
 
-            subscribePreferencesSetting(\.useNewFormula, on: $useNewFormula) { useNewFormula = $0 }
-            subscribePreferencesSetting(\.enableDynamicCR, on: $enableDynamicCR) { enableDynamicCR = $0 }
-            subscribePreferencesSetting(\.sigmoid, on: $sigmoid) { sigmoid = $0 }
+            /// DynamicISF handling
+            /// Initially, load once from storage and infer `dynamicSensitivityType` based on values of `useNewFormula` (log) and/or `sigmoid`
+            let storedUseNewFormula = settingsManager.preferences.useNewFormula
+            let storedSigmoid = settingsManager.preferences.sigmoid
+            inferDynamicSensitivityType(useNewFormula: storedUseNewFormula, sigmoid: storedSigmoid)
+            /// Subsequently, subscribe to changes from the UI and persist them in the (kept for now) two variables
+            subscribePreferencesSetting(\.useNewFormula, on: $useNewFormula) { _ in }
+            subscribePreferencesSetting(\.sigmoid, on: $sigmoid) { _ in }
+
             subscribePreferencesSetting(\.adjustmentFactor, on: $adjustmentFactor) { adjustmentFactor = $0 }
             subscribePreferencesSetting(\.adjustmentFactorSigmoid, on: $adjustmentFactorSigmoid) { adjustmentFactorSigmoid = $0 }
             subscribePreferencesSetting(\.weightPercentage, on: $weightPercentage) { weightPercentage = $0 }
             subscribePreferencesSetting(\.tddAdjBasal, on: $tddAdjBasal) { tddAdjBasal = $0 }
             subscribePreferencesSetting(\.threshold_setting, on: $threshold_setting) { threshold_setting = $0 }
+
+            Task {
+                do {
+                    let hasValidTDD = try await tddStorage.hasSufficientTDD()
+                    await MainActor.run {
+                        self.hasValidTDD = hasValidTDD
+                    }
+                } catch {
+                    debug(.coreData, "Error when fetching TDD for validity checking: \(error)")
+                    await MainActor.run {
+                        hasValidTDD = false
+                    }
+                }
+            }
+        }
+
+        /// Infers the `dynamicSensitivityType` based on the stored values of `useNewFormula` and `sigmoid`.
+        /// - Logic:
+        ///   - If `useNewFormula` is `true` and `sigmoid` is `false`, sets type to `.logarithmic`.
+        ///   - If both `useNewFormula` and `sigmoid` are `true`, sets type to `.sigmoid`.
+        ///   - Otherwise, sets type to `.disabled`.
+        ///
+        /// This is used at startup to derive the dynamic sensitivity state from persisted values until
+        /// a future refactor makes `dynamicSensitivityType` a first-class stored preference.
+        // FIXME: needs to be refactored, once oref-swift lands and dynamicISF becomes swift-bound
+        private func inferDynamicSensitivityType(useNewFormula: Bool, sigmoid: Bool) {
+            if useNewFormula {
+                dynamicSensitivityType = sigmoid ? .sigmoid : .logarithmic
+            } else {
+                dynamicSensitivityType = .disabled
+            }
+        }
+
+        /// Checks if there is enough Total Daily Dose (TDD) data collected over the past 7 days.
+        ///
+        /// This function performs a count fetch for TDDStored records in Core Data where:
+        /// - The record's date is within the last 7 days.
+        /// - The total value is greater than 0.
+        ///
+        /// It then checks if at least 85% of the expected data points are present,
+        /// assuming at least 288 expected entries per day (one every 5 minutes).
+        ///
+        /// - Returns: `true` if sufficient TDD data is available, otherwise `false`.
+        /// - Throws: An error if the Core Data count operation fails.
+        private func hasSufficientTDD() throws -> Bool {
+            var result = false
+
+            context.performAndWait {
+                let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "TDDStored")
+                fetchRequest.predicate = NSPredicate(
+                    format: "date > %@ AND total > 0",
+                    Date().addingTimeInterval(-86400 * 7) as NSDate
+                )
+                fetchRequest.resultType = .countResultType
+
+                let count = (try? context.count(for: fetchRequest)) ?? 0
+                let threshold = Int(Double(7 * 288) * 0.85)
+                result = count >= threshold
+            }
+
+            return result
         }
     }
 }
@@ -37,3 +129,25 @@ extension DynamicSettings.StateModel: SettingsObserver {
         units = settingsManager.settings.units
     }
 }
+
+extension DynamicSettings {
+    enum DynamicSensitivityType: String, JSON, CaseIterable, Identifiable, Codable, Hashable {
+        var id: String { rawValue }
+        case disabled
+        case logarithmic
+        case sigmoid
+
+        var displayName: String {
+            switch self {
+            case .disabled:
+                return String(localized: "Disabled")
+
+            case .logarithmic:
+                return String(localized: "Logarithmic")
+
+            case .sigmoid:
+                return String(localized: "Sigmoid")
+            }
+        }
+    }
+}

+ 125 - 131
Trio/Sources/Modules/DynamicSettings/View/DynamicSettingsRootView.swift

@@ -41,111 +41,104 @@ extension DynamicSettings {
 
         var body: some View {
             List {
-                SettingInputSection(
-                    decimalValue: $decimalPlaceholder,
-                    booleanValue: $state.useNewFormula,
-                    shouldDisplayHint: $shouldDisplayHint,
-                    selectedVerboseHint: Binding(
-                        get: { selectedVerboseHint },
-                        set: {
-                            selectedVerboseHint = $0.map { AnyView($0) }
-                            hintLabel = String(localized: "Activate Dynamic Sensitivity (Dynamic ISF)")
-                        }
-                    ),
-                    units: state.units,
-                    type: .boolean,
-                    label: String(localized: "Activate Dynamic ISF"),
-                    miniHint: String(
-                        localized: "Dynamically adjust insulin sensitivity using Dynamic Ratio rather than Autosens Ratio."
-                    ),
-                    verboseHint:
-                    VStack(alignment: .leading, spacing: 10) {
-                        Text("Default: OFF").bold()
-                        Text(
-                            "Enabling this feature allows Trio to calculate a new Insulin Sensitivity Factor with each loop cycle by considering your current glucose, the weighted total daily dose of insulin, the set adjustment factor, and a few other data points. This helps tailor your insulin response more accurately in real time."
-                        )
-                        Text(
-                            "Dynamic ISF produces a Dynamic Ratio, replacing the Autosens Ratio, determining how much your profile ISF will be adjusted every loop cycle, ensuring it stays within safe limits set by your Autosens Min/Max settings. It provides more precise insulin dosing by responding to changes in insulin needs throughout the day."
-                        )
-                        Text(
-                            "You can influence the adjustments made by Dynamic ISF primarily by adjusting Autosens Max, Autosens Min, and Adjustment Factor. Other settings also influence Dynamic ISF's response, such as Glucose Target, Profile ISF, Peak Insulin Time, and Weighted Average of TDD."
-                        )
-                        Text(
-                            "Warning: Before adjusting these settings, make sure you are fully aware of the impact those changes will have."
-                        )
-                        .bold()
-                    },
-                    headerText: String(localized: "Dynamic Settings")
-                )
-
-                if state.useNewFormula {
-                    SettingInputSection(
-                        decimalValue: $decimalPlaceholder,
-                        booleanValue: $state.enableDynamicCR,
-                        shouldDisplayHint: $shouldDisplayHint,
-                        selectedVerboseHint: Binding(
-                            get: { selectedVerboseHint },
-                            set: {
-                                selectedVerboseHint = $0.map { AnyView($0) }
-                                hintLabel = String(localized: "Activate Dynamic CR (Carb Ratio)")
+                Section(
+                    header: Text("Dynamic Insulin Sensitivity"),
+                    content: {
+                        VStack(alignment: .leading) {
+                            Picker(
+                                selection: $state.dynamicSensitivityType,
+                                label: Text("Dynamic ISF").multilineTextAlignment(.leading)
+                            ) {
+                                ForEach(DynamicSensitivityType.allCases) { selection in
+                                    Text(selection.displayName).tag(selection)
+                                }
                             }
-                        ),
-                        units: state.units,
-                        type: .boolean,
-                        label: String(localized: "Activate Dynamic CR (Carb Ratio)"),
-                        miniHint: String(localized: "Dynamically adjust your Carb Ratio (CR)."),
-                        verboseHint:
+                            .disabled(!state.hasValidTDD)
+                            .padding(.top)
 
-                        VStack(alignment: .leading, spacing: 10) {
-                            Text("Default: OFF").bold()
-                            Text(
-                                "Dynamic CR adjusts your carb ratio based on your Dynamic Ratio, adapting automatically to changes in insulin sensitivity."
-                            )
-                            Text(
-                                "When Dynamic Ratio increases, indicating you need more insulin, the carb ratio value is decreased to make your insulin dosing more effective."
-                            )
-                            Text(
-                                "When Dynamic Ratio decreases, indicating you need less insulin, the carb ratio value is increased to avoid over-delivery."
-                            )
-                        }
-                    )
+                            HStack(alignment: .center) {
+                                let miniHintText = state.hasValidTDD ?
+                                    String(
+                                        localized: "Dynamically adjust insulin sensitivity using Dynamic Ratio rather than Autosens Ratio."
+                                    ) :
+                                    String(
+                                        localized: "Trio has only been actively used and looping for less than seven days. Cannot enable dynamic ISF."
+                                    )
+                                let miniHintTextColorForDisabled: Color = colorScheme == .dark ? .orange :
+                                    .accentColor
+                                let miniHintTextColor: Color = state.hasValidTDD ? .secondary : miniHintTextColorForDisabled
 
-                    SettingInputSection(
-                        decimalValue: $decimalPlaceholder,
-                        booleanValue: $state.sigmoid,
-                        shouldDisplayHint: $shouldDisplayHint,
-                        selectedVerboseHint: Binding(
-                            get: { selectedVerboseHint },
-                            set: {
-                                selectedVerboseHint = $0.map { AnyView($0) }
-                                hintLabel = String(localized: "Use Sigmoid Formula")
-                            }
-                        ),
-                        units: state.units,
-                        type: .boolean,
-                        label: String(localized: "Use Sigmoid Formula"),
-                        miniHint: String(localized: "Adjust insulin sensitivity using a sigmoid-shaped curve."),
-                        verboseHint:
-                        VStack(alignment: .leading, spacing: 10) {
-                            Text("Default: OFF").bold()
-                            Text(
-                                "Turning on the Sigmoid Formula setting alters how your Dynamic Ratio, and thus your New ISF and New Carb Ratio, are calculated using a sigmoid curve rather than the default logarithmic function."
-                            )
-                            Text(
-                                "The curve's steepness is influenced by the Adjustment Factor, while the Autosens Min/Max settings determine the limits of the ratio adjustment, which can also influence the steepness of the sigmoid curve."
-                            )
-                            Text(
-                                "When using the Sigmoid Formula, the weighted Total Daily Dose has a much lower impact on the dynamic adjustments to sensitivity."
-                            )
-                            Text("Careful tuning is essential to avoid overly aggressive insulin changes.")
-                            Text("It is not recommended to set Autosens Max above 150% to maintain safe insulin dosing.")
-                            Text(
-                                "There has been no empirical data analysis to support the use of the Sigmoid Formula for dynamic sensitivity determination."
-                            ).bold()
-                        }
-                    )
+                                Text(miniHintText)
+                                    .font(.footnote)
+                                    .foregroundColor(miniHintTextColor)
+                                    .lineLimit(nil)
 
-                    if !state.sigmoid {
+                                Spacer()
+                                Button(
+                                    action: {
+                                        hintLabel = String(localized: "Time in Range Chart Style")
+                                        selectedVerboseHint =
+                                            AnyView(
+                                                VStack(alignment: .leading, spacing: 10) {
+                                                    Text("Default: Disabled").bold()
+                                                    Text(
+                                                        "Enabling this feature allows Trio to calculate a new Insulin Sensitivity Factor with each loop cycle dynamically. Trio offers two dynamic formulas:"
+                                                    )
+                                                    VStack(alignment: .leading, spacing: 10) {
+                                                        Text("Logarithmic Dynamic ISF").bold()
+                                                        Text(
+                                                            "Enabling this feature allows Trio to calculate a new Insulin Sensitivity Factor with each loop cycle by considering your current glucose, the weighted total daily dose of insulin, the set adjustment factor, and a few other data points. This helps tailor your insulin response more accurately in real time."
+                                                        )
+                                                        Text(
+                                                            "Dynamic ISF produces a Dynamic Ratio, replacing the Autosens Ratio, determining how much your profile ISF will be adjusted every loop cycle, ensuring it stays within safe limits set by your Autosens Min/Max settings. It provides more precise insulin dosing by responding to changes in insulin needs throughout the day."
+                                                        )
+                                                        Text(
+                                                            "You can influence the adjustments made by Dynamic ISF primarily by adjusting Autosens Max, Autosens Min, and Adjustment Factor. Other settings also influence Dynamic ISF's response, such as Glucose Target, Profile ISF, Peak Insulin Time, and Weighted Average of TDD."
+                                                        )
+                                                        Text(
+                                                            "Warning: Before adjusting these settings, make sure you are fully aware of the impact those changes will have."
+                                                        )
+                                                        .bold()
+                                                    }
+
+                                                    VStack(alignment: .leading, spacing: 10) {
+                                                        Text("Sigmoid Dynamic ISF").bold()
+                                                        Text(
+                                                            "Turning on the Sigmoid Formula setting alters how your Dynamic Ratio, and thus your New ISF, are calculated using a sigmoid curve."
+                                                        )
+                                                        Text(
+                                                            "The curve's steepness is influenced by the Adjustment Factor, while the Autosens Min/Max settings determine the limits of the ratio adjustment, which can also influence the steepness of the sigmoid curve."
+                                                        )
+                                                        Text(
+                                                            "When using the Sigmoid Formula, the weighted Total Daily Dose has a much lower impact on the dynamic adjustments to sensitivity."
+                                                        )
+                                                        Text(
+                                                            "Careful tuning is essential to avoid overly aggressive insulin changes."
+                                                        )
+                                                        Text(
+                                                            "It is not recommended to set Autosens Max above 150% to maintain safe insulin dosing."
+                                                        )
+                                                        Text(
+                                                            "There has been no empirical data analysis to support the use of the Sigmoid Formula for dynamic sensitivity determination."
+                                                        ).bold()
+                                                    }
+                                                }
+                                            )
+                                        shouldDisplayHint.toggle()
+                                    },
+                                    label: {
+                                        HStack {
+                                            Image(systemName: "questionmark.circle")
+                                        }
+                                    }
+                                ).buttonStyle(BorderlessButtonStyle())
+                            }.padding(.top)
+                        }.padding(.bottom)
+                    }
+                ).listRowBackground(Color.chart)
+
+                if state.dynamicSensitivityType != .disabled {
+                    if state.dynamicSensitivityType == .logarithmic {
                         SettingInputSection(
                             decimalValue: $state.adjustmentFactor,
                             booleanValue: $booleanPlaceholder,
@@ -176,6 +169,35 @@ extension DynamicSettings {
                                 )
                             }
                         )
+
+                        SettingInputSection(
+                            decimalValue: $state.weightPercentage,
+                            booleanValue: $booleanPlaceholder,
+                            shouldDisplayHint: $shouldDisplayHint,
+                            selectedVerboseHint: Binding(
+                                get: { selectedVerboseHint },
+                                set: {
+                                    selectedVerboseHint = $0.map { AnyView($0) }
+                                    hintLabel = String(localized: "Weighted Average of TDD")
+                                }
+                            ),
+                            units: state.units,
+                            type: .decimal("weightPercentage"),
+                            label: String(localized: "Weighted Average of TDD"),
+                            miniHint: String(localized: "Weight of 24-hr TDD against 10-day TDD."),
+                            verboseHint:
+                            VStack(alignment: .leading, spacing: 10) {
+                                Text("Default: 35%").bold()
+                                Text(
+                                    "This setting adjusts how much weight is given to your recent total daily insulin dose when calculating Dynamic ISF and Dynamic CR."
+                                )
+                                Text(
+                                    "At the default setting, 35% of the calculation is based on the last 24 hours of insulin use, with the remaining 65% considering the last 10 days of data."
+                                )
+                                Text("Setting this to 100% means only the past 24 hours will be used.")
+                                Text("A lower value smooths out these variations for more stability.")
+                            }
+                        )
                     } else {
                         SettingInputSection(
                             decimalValue: $state.adjustmentFactorSigmoid,
@@ -212,35 +234,6 @@ extension DynamicSettings {
                     }
 
                     SettingInputSection(
-                        decimalValue: $state.weightPercentage,
-                        booleanValue: $booleanPlaceholder,
-                        shouldDisplayHint: $shouldDisplayHint,
-                        selectedVerboseHint: Binding(
-                            get: { selectedVerboseHint },
-                            set: {
-                                selectedVerboseHint = $0.map { AnyView($0) }
-                                hintLabel = String(localized: "Weighted Average of TDD")
-                            }
-                        ),
-                        units: state.units,
-                        type: .decimal("weightPercentage"),
-                        label: String(localized: "Weighted Average of TDD"),
-                        miniHint: String(localized: "Weight of 24-hr TDD against 10-day TDD."),
-                        verboseHint:
-                        VStack(alignment: .leading, spacing: 10) {
-                            Text("Default: 35%").bold()
-                            Text(
-                                "This setting adjusts how much weight is given to your recent total daily insulin dose when calculating Dynamic ISF and Dynamic CR."
-                            )
-                            Text(
-                                "At the default setting, 35% of the calculation is based on the last 24 hours of insulin use, with the remaining 65% considering the last 10 days of data."
-                            )
-                            Text("Setting this to 100% means only the past 24 hours will be used.")
-                            Text("A lower value smooths out these variations for more stability.")
-                        }
-                    )
-
-                    SettingInputSection(
                         decimalValue: $decimalPlaceholder,
                         booleanValue: $state.tddAdjBasal,
                         shouldDisplayHint: $shouldDisplayHint,
@@ -265,7 +258,8 @@ extension DynamicSettings {
                             )
                             Text("Autosens Ratio =\n(Weighted Average of TDD) ÷ (10-day Average of TDD)")
                             Text("New Basal Profile =\n(Current Basal Profile) × (Autosens Ratio)")
-                        }
+                        },
+                        headerText: String(localized: "Dynamic-dependent Features")
                     )
 
                     SettingInputSection(