IobJsonTests.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import Foundation
  2. import Testing
  3. @testable import Trio
  4. /// This test suite is to help us debug and verify iob errors from Trio devices
  5. ///
  6. /// There are two key components. First, we have a version of the Javascript that has a number
  7. /// of bugs fixed. We don't want to fix the real Javascript, so we put this fixed Javascript in the
  8. /// testing bundle and use it to run comparisons. If the error we see in the field is one that we know
  9. /// about and have fixed in JS, the Swift and JS implementations will produce the same results. You
  10. /// can find the fixed JS here:
  11. /// https://github.com/kingst/trio-oref/tree/tcd-fixes-for-swift-comparison
  12. ///
  13. /// Second, we have a server that runs (part of `trio-oref-logs`) to serve error logs captured
  14. /// from the field. This server needs to run on the same machine as the simulator where this test runs.
  15. /// You can find more information about it from the `trio-oref-logs` repo.
  16. @Suite("IoB using real pump history JSON", .serialized) struct IobJsonTests {
  17. let timeZoneForTests = TimeZoneForTests()
  18. struct IobHistoryResult: Codable {
  19. var insulin: Decimal?
  20. var rate: Decimal?
  21. var duration: Decimal?
  22. var timestamp: String?
  23. var started_at: String?
  24. var created_at: String?
  25. var date: Decimal?
  26. enum CodingKeys: String, CodingKey {
  27. case insulin
  28. case rate
  29. case duration
  30. case timestamp
  31. case started_at
  32. case created_at
  33. case date
  34. }
  35. }
  36. // Note: This test case has a memory leak so limit your inputs
  37. // to about 250 files at a time
  38. @Test(
  39. "IoB should produce same results for fixed JS and different for bundle JS",
  40. .enabled(if: false)
  41. ) func replayErrorInputs() async throws {
  42. let files = try await HttpFiles.listFiles()
  43. for filePath in files {
  44. let algorithmComparison = try await HttpFiles.downloadFile(at: filePath)
  45. print("Checking \(filePath) @ \(algorithmComparison.createdAt)")
  46. guard let iobInputs = algorithmComparison.iobInput else {
  47. print("Skipping, no iobInputs found")
  48. if let str = algorithmComparison.comparisonError {
  49. print(str)
  50. }
  51. if let str = algorithmComparison.swiftException {
  52. print(str)
  53. }
  54. continue
  55. }
  56. timeZoneForTests.setTimezone(identifier: algorithmComparison.timezone)
  57. try await checkFixedJsAgainstSwift(iobInputs: iobInputs)
  58. try await checkBundleJsAgainstSwift(iobInputs: iobInputs)
  59. timeZoneForTests.resetTimezone()
  60. }
  61. }
  62. func checkFixedJsAgainstSwift(iobInputs: IobInputs) async throws {
  63. let openAps = OpenAPSFixed()
  64. let (iobResultSwift, _) = OpenAPSSwift.iob(
  65. pumphistory: iobInputs.history,
  66. profile: try JSONBridge.to(iobInputs.profile),
  67. clock: iobInputs.clock,
  68. autosens: try JSONBridge.to(iobInputs.autosens)
  69. )
  70. let iobResultJavascript = await openAps.iobJavascript(
  71. pumphistory: iobInputs.history,
  72. profile: try JSONBridge.to(iobInputs.profile),
  73. clock: iobInputs.clock,
  74. autosens: try JSONBridge.to(iobInputs.autosens)
  75. )
  76. let comparison = JSONCompare.createComparison(
  77. function: .iob,
  78. swift: iobResultSwift,
  79. swiftDuration: 0.1,
  80. javascript: iobResultJavascript,
  81. javascriptDuration: 0.1,
  82. iobInputs: nil,
  83. mealInputs: nil
  84. )
  85. if comparison.resultType == .valueDifference {
  86. print(comparison.differences!.prettyPrintedJSON!)
  87. }
  88. if comparison.resultType != .matching {
  89. print("REPLAY ERROR: Fixed JS didn't match")
  90. }
  91. #expect(comparison.resultType == .matching)
  92. }
  93. func checkBundleJsAgainstSwift(iobInputs: IobInputs) async throws {
  94. let openAps = OpenAPS(storage: BaseFileStorage(), tddStorage: MockTDDStorage())
  95. let (iobResultSwift, _) = OpenAPSSwift.iob(
  96. pumphistory: iobInputs.history,
  97. profile: try JSONBridge.to(iobInputs.profile),
  98. clock: iobInputs.clock,
  99. autosens: try JSONBridge.to(iobInputs.autosens)
  100. )
  101. let iobResultJavascript = await openAps.iobJavascript(
  102. pumphistory: iobInputs.history,
  103. profile: try JSONBridge.to(iobInputs.profile),
  104. clock: iobInputs.clock,
  105. autosens: try JSONBridge.to(iobInputs.autosens)
  106. )
  107. let comparison = JSONCompare.createComparison(
  108. function: .iob,
  109. swift: iobResultSwift,
  110. swiftDuration: 0.1,
  111. javascript: iobResultJavascript,
  112. javascriptDuration: 0.1,
  113. iobInputs: nil,
  114. mealInputs: nil
  115. )
  116. if comparison.resultType != .valueDifference {
  117. print("REPLAY ERROR: bundle JS did't produce value difference")
  118. }
  119. #expect(comparison.resultType == .valueDifference)
  120. }
  121. func checkHistoryConsistency(swiftTreatments: [ComputedPumpHistoryEvent], jsTreatments: [IobHistoryResult]) {
  122. let swiftNetBolus = swiftTreatments.compactMap(\.insulin).filter({ $0 >= 0.1 }).reduce(0, +)
  123. let jsNetBolus = jsTreatments.compactMap(\.insulin).filter({ $0 >= 0.1 }).reduce(0, +)
  124. let swiftNetBasal = swiftTreatments.compactMap(\.insulin).filter({ $0 < 0.1 }).reduce(0, +)
  125. let jsNetBasal = jsTreatments.compactMap(\.insulin).filter({ $0 < 0.1 }).reduce(0, +)
  126. #expect(swiftNetBasal == jsNetBasal)
  127. #expect(swiftNetBolus == jsNetBolus)
  128. }
  129. func checkRunningBasal(swiftTreatments: [ComputedPumpHistoryEvent], jsTreatments: [IobHistoryResult]) {
  130. let swiftBasals = swiftTreatments.filter({ $0.rate != nil }).filter({ $0.duration! > 0 })
  131. let jsBasals = jsTreatments.filter({ $0.rate != nil }).filter({ $0.duration! > 0 })
  132. #expect(swiftBasals.count == jsBasals.count)
  133. for (swift, js) in zip(swiftBasals, jsBasals) {
  134. #expect(Decimal(swift.date) == js.date!)
  135. #expect(swift.duration!.isWithin(0.01, of: js.duration!))
  136. #expect(swift.rate == js.rate)
  137. let start = js.date!
  138. let end = js.date! + js.duration! * 60 * 1000
  139. let swiftTempBolus = swiftTreatments
  140. .filter({ Decimal($0.date) >= start && Decimal($0.date) < end && $0.insulin != nil && $0.insulin! < 0.1 })
  141. .map({ $0.insulin! }).reduce(0, +)
  142. let jsTempBolus = jsTreatments
  143. .filter({ $0.date! >= start && $0.date! < end && $0.insulin != nil && $0.insulin! < 0.1 }).map({ $0.insulin! })
  144. .reduce(0, +)
  145. if swiftTempBolus != jsTempBolus {
  146. print("temp bolus @ \(swift.timestamp) mismatch swift: \(swiftTempBolus) js: \(jsTempBolus)")
  147. }
  148. #expect(swiftTempBolus == jsTempBolus)
  149. }
  150. }
  151. @Test("Debug utility for checking iob-history", .enabled(if: false)) func debugIobHistory() async throws {
  152. let testBundle = Bundle(for: BundleReference.self)
  153. let path = testBundle.path(forResource: "iob-error-log", ofType: "json")!
  154. let data = try Data(contentsOf: URL(fileURLWithPath: path))
  155. let decoder = JSONDecoder()
  156. decoder.dateDecodingStrategy = .secondsSince1970
  157. let algorithmComparison = try decoder.decode(AlgorithmComparison.self, from: data)
  158. let iobInputs = algorithmComparison.iobInput!
  159. timeZoneForTests.setTimezone(identifier: algorithmComparison.timezone)
  160. let swiftIobHistory = try IobHistory.calcTempTreatments(
  161. history: iobInputs.history.map { $0.computedEvent() },
  162. profile: iobInputs.profile,
  163. clock: iobInputs.clock,
  164. autosens: iobInputs.autosens,
  165. zeroTempDuration: nil
  166. )
  167. let openAps = OpenAPSFixed()
  168. let jsIobHistoryRaw = try await openAps.iobHistory(
  169. pumphistory: iobInputs.history,
  170. profile: JSONBridge.to(iobInputs.profile),
  171. clock: iobInputs.clock,
  172. autosens: JSONBridge.to(iobInputs.autosens),
  173. zeroTempDuration: RawJSON.null
  174. )
  175. let jsIobHistory = try JSONDecoder().decode([IobHistoryResult].self, from: jsIobHistoryRaw.rawJSON.data(using: .utf8)!)
  176. let encoder = JSONCoding.encoder
  177. var output = try encoder.encode(swiftIobHistory)
  178. var sharedDir = FileManager.default.temporaryDirectory
  179. var outputURL = sharedDir.appendingPathComponent("swift_treatments.json")
  180. print("Writing to: \(outputURL.path)")
  181. try output.write(to: outputURL)
  182. output = try encoder.encode(jsIobHistory)
  183. sharedDir = FileManager.default.temporaryDirectory
  184. outputURL = sharedDir.appendingPathComponent("js_treatments.json")
  185. print("Writing to: \(outputURL.path)")
  186. try output.write(to: outputURL)
  187. checkHistoryConsistency(swiftTreatments: swiftIobHistory, jsTreatments: jsIobHistory)
  188. checkRunningBasal(swiftTreatments: swiftIobHistory, jsTreatments: jsIobHistory)
  189. timeZoneForTests.resetTimezone()
  190. }
  191. /// simple utility for creating inputs for Javascript for use in testing
  192. @Test("format inputs for Javascript", .enabled(if: false)) func generateJavascriptInputs() throws {
  193. let testBundle = Bundle(for: BundleReference.self)
  194. let path = testBundle.path(forResource: "iob-error-log", ofType: "json")!
  195. let data = try Data(contentsOf: URL(fileURLWithPath: path))
  196. let decoder = JSONDecoder()
  197. decoder.dateDecodingStrategy = .secondsSince1970
  198. let algorithmComparison = try decoder.decode(AlgorithmComparison.self, from: data)
  199. let iobInputs = algorithmComparison.iobInput!
  200. let encoder = JSONCoding.encoder
  201. let output = try encoder.encode(iobInputs)
  202. let sharedDir = FileManager.default.temporaryDirectory
  203. let outputURL = sharedDir.appendingPathComponent("js_iob_input_error.json")
  204. // Print the path so you can find it
  205. print("Writing to: \(outputURL.path)")
  206. try output.write(to: outputURL)
  207. timeZoneForTests.setTimezone(identifier: algorithmComparison.timezone)
  208. let treatments = try IobHistory.calcTempTreatments(
  209. history: iobInputs.history.map { $0.computedEvent() },
  210. profile: iobInputs.profile,
  211. clock: iobInputs.clock,
  212. autosens: iobInputs.autosens,
  213. zeroTempDuration: nil
  214. )
  215. let iobSomething = try IobCalculation.iobTotal(treatments: treatments, profile: iobInputs.profile, time: iobInputs.clock)
  216. timeZoneForTests.resetTimezone()
  217. print(iobSomething.prettyPrintedJSON!)
  218. let treatmentsOut = try encoder.encode(treatments)
  219. let treatmentsUrl = sharedDir.appendingPathComponent("treatments.json")
  220. print("Writing to: \(treatmentsUrl.path)")
  221. try treatmentsOut.write(to: treatmentsUrl)
  222. }
  223. }