IobJsonTests.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. autosensInputs: nil
  85. )
  86. if comparison.resultType == .valueDifference {
  87. print(comparison.differences!.prettyPrintedJSON!)
  88. }
  89. if comparison.resultType != .matching {
  90. print("REPLAY ERROR: Fixed JS didn't match")
  91. }
  92. #expect(comparison.resultType == .matching)
  93. }
  94. func checkBundleJsAgainstSwift(iobInputs: IobInputs) async throws {
  95. let openAps = OpenAPS(storage: BaseFileStorage(), tddStorage: MockTDDStorage())
  96. let (iobResultSwift, _) = OpenAPSSwift.iob(
  97. pumphistory: iobInputs.history,
  98. profile: try JSONBridge.to(iobInputs.profile),
  99. clock: iobInputs.clock,
  100. autosens: try JSONBridge.to(iobInputs.autosens)
  101. )
  102. let iobResultJavascript = await openAps.iobJavascript(
  103. pumphistory: iobInputs.history,
  104. profile: try JSONBridge.to(iobInputs.profile),
  105. clock: iobInputs.clock,
  106. autosens: try JSONBridge.to(iobInputs.autosens)
  107. )
  108. let comparison = JSONCompare.createComparison(
  109. function: .iob,
  110. swift: iobResultSwift,
  111. swiftDuration: 0.1,
  112. javascript: iobResultJavascript,
  113. javascriptDuration: 0.1,
  114. iobInputs: nil,
  115. mealInputs: nil,
  116. autosensInputs: nil
  117. )
  118. if comparison.resultType != .valueDifference {
  119. print("REPLAY ERROR: bundle JS did't produce value difference")
  120. }
  121. #expect(comparison.resultType == .valueDifference)
  122. }
  123. func checkHistoryConsistency(swiftTreatments: [ComputedPumpHistoryEvent], jsTreatments: [IobHistoryResult]) {
  124. let swiftNetBolus = swiftTreatments.compactMap(\.insulin).filter({ $0 >= 0.1 }).reduce(0, +)
  125. let jsNetBolus = jsTreatments.compactMap(\.insulin).filter({ $0 >= 0.1 }).reduce(0, +)
  126. let swiftNetBasal = swiftTreatments.compactMap(\.insulin).filter({ $0 < 0.1 }).reduce(0, +)
  127. let jsNetBasal = jsTreatments.compactMap(\.insulin).filter({ $0 < 0.1 }).reduce(0, +)
  128. #expect(swiftNetBasal == jsNetBasal)
  129. #expect(swiftNetBolus == jsNetBolus)
  130. }
  131. func checkRunningBasal(swiftTreatments: [ComputedPumpHistoryEvent], jsTreatments: [IobHistoryResult]) {
  132. let swiftBasals = swiftTreatments.filter({ $0.rate != nil }).filter({ $0.duration! > 0 })
  133. let jsBasals = jsTreatments.filter({ $0.rate != nil }).filter({ $0.duration! > 0 })
  134. #expect(swiftBasals.count == jsBasals.count)
  135. for (swift, js) in zip(swiftBasals, jsBasals) {
  136. #expect(Decimal(swift.date) == js.date!)
  137. #expect(swift.duration!.isWithin(0.01, of: js.duration!))
  138. #expect(swift.rate == js.rate)
  139. let start = js.date!
  140. let end = js.date! + js.duration! * 60 * 1000
  141. let swiftTempBolus = swiftTreatments
  142. .filter({ Decimal($0.date) >= start && Decimal($0.date) < end && $0.insulin != nil && $0.insulin! < 0.1 })
  143. .map({ $0.insulin! }).reduce(0, +)
  144. let jsTempBolus = jsTreatments
  145. .filter({ $0.date! >= start && $0.date! < end && $0.insulin != nil && $0.insulin! < 0.1 }).map({ $0.insulin! })
  146. .reduce(0, +)
  147. if swiftTempBolus != jsTempBolus {
  148. print("temp bolus @ \(swift.timestamp) mismatch swift: \(swiftTempBolus) js: \(jsTempBolus)")
  149. }
  150. #expect(swiftTempBolus == jsTempBolus)
  151. }
  152. }
  153. @Test("Debug utility for checking iob-history", .enabled(if: false)) func debugIobHistory() async throws {
  154. let testBundle = Bundle(for: BundleReference.self)
  155. let path = testBundle.path(forResource: "iob-error-log", ofType: "json")!
  156. let data = try Data(contentsOf: URL(fileURLWithPath: path))
  157. let decoder = JSONDecoder()
  158. decoder.dateDecodingStrategy = .secondsSince1970
  159. let algorithmComparison = try decoder.decode(AlgorithmComparison.self, from: data)
  160. let iobInputs = algorithmComparison.iobInput!
  161. timeZoneForTests.setTimezone(identifier: algorithmComparison.timezone)
  162. let swiftIobHistory = try IobHistory.calcTempTreatments(
  163. history: iobInputs.history.map { $0.computedEvent() },
  164. profile: iobInputs.profile,
  165. clock: iobInputs.clock,
  166. autosens: iobInputs.autosens,
  167. zeroTempDuration: nil
  168. )
  169. let openAps = OpenAPSFixed()
  170. let jsIobHistoryRaw = try await openAps.iobHistory(
  171. pumphistory: iobInputs.history,
  172. profile: JSONBridge.to(iobInputs.profile),
  173. clock: iobInputs.clock,
  174. autosens: JSONBridge.to(iobInputs.autosens),
  175. zeroTempDuration: RawJSON.null
  176. )
  177. let jsIobHistory = try JSONDecoder().decode([IobHistoryResult].self, from: jsIobHistoryRaw.rawJSON.data(using: .utf8)!)
  178. let encoder = JSONCoding.encoder
  179. var output = try encoder.encode(swiftIobHistory)
  180. var sharedDir = FileManager.default.temporaryDirectory
  181. var outputURL = sharedDir.appendingPathComponent("swift_treatments.json")
  182. print("Writing to: \(outputURL.path)")
  183. try output.write(to: outputURL)
  184. output = try encoder.encode(jsIobHistory)
  185. sharedDir = FileManager.default.temporaryDirectory
  186. outputURL = sharedDir.appendingPathComponent("js_treatments.json")
  187. print("Writing to: \(outputURL.path)")
  188. try output.write(to: outputURL)
  189. checkHistoryConsistency(swiftTreatments: swiftIobHistory, jsTreatments: jsIobHistory)
  190. checkRunningBasal(swiftTreatments: swiftIobHistory, jsTreatments: jsIobHistory)
  191. timeZoneForTests.resetTimezone()
  192. }
  193. /// simple utility for creating inputs for Javascript for use in testing
  194. @Test("format inputs for Javascript", .enabled(if: false)) func generateJavascriptInputs() throws {
  195. let testBundle = Bundle(for: BundleReference.self)
  196. let path = testBundle.path(forResource: "iob-error-log", ofType: "json")!
  197. let data = try Data(contentsOf: URL(fileURLWithPath: path))
  198. let decoder = JSONDecoder()
  199. decoder.dateDecodingStrategy = .secondsSince1970
  200. let algorithmComparison = try decoder.decode(AlgorithmComparison.self, from: data)
  201. let iobInputs = algorithmComparison.iobInput!
  202. let encoder = JSONCoding.encoder
  203. let output = try encoder.encode(iobInputs)
  204. let sharedDir = FileManager.default.temporaryDirectory
  205. let outputURL = sharedDir.appendingPathComponent("js_iob_input_error.json")
  206. // Print the path so you can find it
  207. print("Writing to: \(outputURL.path)")
  208. try output.write(to: outputURL)
  209. timeZoneForTests.setTimezone(identifier: algorithmComparison.timezone)
  210. let treatments = try IobHistory.calcTempTreatments(
  211. history: iobInputs.history.map { $0.computedEvent() },
  212. profile: iobInputs.profile,
  213. clock: iobInputs.clock,
  214. autosens: iobInputs.autosens,
  215. zeroTempDuration: nil
  216. )
  217. let iobSomething = try IobCalculation.iobTotal(treatments: treatments, profile: iobInputs.profile, time: iobInputs.clock)
  218. timeZoneForTests.resetTimezone()
  219. print(iobSomething.prettyPrintedJSON!)
  220. let treatmentsOut = try encoder.encode(treatments)
  221. let treatmentsUrl = sharedDir.appendingPathComponent("treatments.json")
  222. print("Writing to: \(treatmentsUrl.path)")
  223. try treatmentsOut.write(to: treatmentsUrl)
  224. }
  225. }