Преглед изворни кода

Merge pull request #613 from nightscout/oref-swift-add-autosens-debug-info

Add debug info for autosens
Sam King пре 5 месеци
родитељ
комит
d76aeba746

+ 16 - 5
Trio/Sources/APS/OpenAPSSwift/Autosens/AutosensGenerator.swift

@@ -9,11 +9,12 @@ struct AutosensGenerator {
 
     /// Internal structure to keep track of the insulin effects simulation state
     struct SimulationState {
-        enum StateType {
-            case initialState
+        // match the state strings from JS
+        enum StateType: String {
+            case initialState = ""
             case csf
             case uam
-            case nonMeal
+            case nonMeal = "non-meal"
         }
 
         var meals: [MealInput]
@@ -61,9 +62,9 @@ struct AutosensGenerator {
         // run through the simulation loop
         var state = SimulationState(meals: meals)
         var deviations: [Decimal] = []
+        var debugInfoList: [Autosens.DebugInfo] = []
         // in JS the simulation loop starts at index 3 but checks for i-1 (prev)
         // and i-3 (old) values for computations
-        var oldGlucoseIndex = 0
         for (oldGlucose, (prevGlucose, currGlucose)) in zip(
             bucketedData,
             zip(bucketedData.dropFirst(2), bucketedData.dropFirst(3))
@@ -108,6 +109,14 @@ struct AutosensGenerator {
                 deviation: deviation
             )
 
+            debugInfoList.append(Autosens.DebugInfo(
+                bgi: bgi,
+                iobActivity: iob.activity,
+                deltaGlucose: deltaGlucose,
+                deviation: deviation,
+                stateType: state.type.rawValue
+            ))
+
             if state.type == .nonMeal {
                 deviations.append(deviation)
             }
@@ -145,6 +154,7 @@ struct AutosensGenerator {
         return try statisticsOnDeviations(
             deviations: deviations,
             profile: profile,
+            debugInfoList: debugInfoList,
             includeDeviationsForTesting: includeDeviationsForTesting
         )
     }
@@ -169,6 +179,7 @@ struct AutosensGenerator {
     private static func statisticsOnDeviations(
         deviations: [Decimal],
         profile: Profile,
+        debugInfoList: [Autosens.DebugInfo],
         includeDeviationsForTesting: Bool
     ) throws -> Autosens {
         guard let profileSensitivity = profile.sens else {
@@ -209,7 +220,7 @@ struct AutosensGenerator {
         let newISF = (profileSensitivity / ratio).rounded()
 
         if includeDeviationsForTesting {
-            return Autosens(ratio: ratio, newisf: newISF, deviationsUnsorted: deviationsUnsorted)
+            return Autosens(ratio: ratio, newisf: newISF, deviationsUnsorted: deviationsUnsorted, debugInfo: debugInfoList)
         } else {
             return Autosens(ratio: ratio, newisf: newISF)
         }

+ 9 - 0
Trio/Sources/Models/Autosens.swift

@@ -1,9 +1,18 @@
 import Foundation
 
 struct Autosens: JSON {
+    struct DebugInfo: Codable {
+        let bgi: Decimal
+        let iobActivity: Decimal
+        let deltaGlucose: Decimal
+        let deviation: Decimal
+        let stateType: String
+    }
+
     let ratio: Decimal
     let newisf: Decimal?
     var deviationsUnsorted: [Decimal]?
     var timestamp: Date?
+    var debugInfo: [DebugInfo]?
     var error: String?
 }

+ 21 - 4
TrioTests/OpenAPSSwiftTests/AutosensJsonTests.swift

@@ -59,6 +59,15 @@ import Testing
         let swiftDict = try JSONSerialization.jsonObject(with: swiftData) as! [String: Any]
         let jsDict = try JSONSerialization.jsonObject(with: jsData) as! [String: Any]
 
+        // Extract debug info
+        let swiftDebugInfo = swiftDict["debugInfo"] as! [Any]
+        let jsDebugInfo = jsDict["debugInfo"] as! [Any]
+        for (s, js) in zip(swiftDebugInfo, jsDebugInfo) {
+            print("Debug Info")
+            print("  - Swift: \(s)")
+            print("  - JS: \(js)")
+        }
+
         // Extract deviationsUnsorted arrays
         let swiftDeviations = swiftDict["deviationsUnsorted"] as! [Any]
         let jsDeviations = jsDict["deviationsUnsorted"] as! [Any]
@@ -86,8 +95,14 @@ import Testing
 
         guard swiftDoubles.count == jsDoubles.count else {
             print("Arrays have different lengths!")
-            print("Swift: \(swiftDoubles)")
-            print("JS: \(jsDoubles)")
+            let count = max(swiftDoubles.count, jsDoubles.count)
+            var index = 0
+            while index < count {
+                let swiftDouble = index < swiftDoubles.count ? String(swiftDoubles[index]) : "nil"
+                let jsDouble = index < jsDoubles.count ? String(jsDoubles[index]) : "nil"
+                print("Index: \(index), Swift: \(swiftDouble), JS: \(jsDouble)")
+                index += 1
+            }
             return
         }
 
@@ -155,6 +170,9 @@ import Testing
         let outputURL = sharedDir.appendingPathComponent("autosens_error_inputs.json")
         try output.write(to: outputURL)
 
+        // Print the path so you can find it
+        print("Writing to: \(outputURL.path)")
+
         timeZoneForTests.setTimezone(identifier: algorithmComparison.timezone)
 
         let openAps = OpenAPSFixed()
@@ -183,8 +201,7 @@ import Testing
             try compareDeviations(swiftJson: swiftJson, jsJson: jsJson)
         }
 
-        // Print the path so you can find it
-        print("Writing to: \(outputURL.path)")
+        try await checkFixedJsAgainstSwift(autosensInputs: autosensInputs)
 
         timeZoneForTests.resetTimezone()
     }

Разлика између датотеке није приказан због своје велике величине
+ 1 - 1
TrioTests/OpenAPSSwiftTests/javascript/bundle/autosens.js