ShearwaterComparisonTests.swift (20972B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 import Testing 4 @testable import RemoraDeco 5 6 /// Compares the engine with a certified dive computer: replays Shearwater dives and checks the tissue 7 /// loading, the no-decompression time and the stops against what the computer logged and displayed. 8 /// Personal data kept out of the repository: `tools/shearwater_decode.py` (Open Rémora repository) 9 /// produces the JSON, path in SHEARWATER_JSON. 10 struct ShearwaterDive: Decodable { 11 struct Sample: Decodable { 12 let depth: Double // m 13 let stop_depth: Int // m 14 let tts: Int 15 let o2: Int 16 let he: Int? 17 let ppo2: Double? // bar, as measured in the loop on a rebreather 18 let ndl_or_stop: Int 19 let status: Int? 20 } 21 /// The 16 nitrogen pressures the computer logs about every 5 minutes; `index` = samples logged before. 22 struct Tissues: Decodable { 23 let index: Int 24 let n2: [Double] 25 } 26 let number: String? 27 let site: String? 28 let date: String 29 let gf_low: Int 30 let gf_high: Int 31 let surface_mbar: Int 32 let sample_ms: Int 33 let model: String? // "GF", "VPM-B"… 34 let mode: String? // "oc-rec", "oc-tec", "cc"… 35 let density: Int? // kg/m³ 36 let computer: String? // model name 37 let samples: [Sample] 38 let tissues: [Tissues]? 39 40 enum Kind: String, CaseIterable { 41 /// Open circuit, one nitrox mix, gradient factors: the computer runs the algorithm of the engine, 42 /// its display is the reference. 43 case reference = "open circuit, GF" 44 /// Open circuit, another decompression model (VPM-B): same tissues, different limits. 45 case otherModel = "open circuit, other model" 46 /// Gas switch or helium: the engine knows one nitrox mix only. 47 case multiGas = "gas switch or helium" 48 /// Rebreather, as the watch would go through it: it knows open circuit only (air = the diluent). 49 case closedCircuit = "closed circuit, as the watch sees it" 50 /// Rebreather with the gradient factors of the computer and the ppO2 it logged in the loop, on the 51 /// planner alone (`Gas.loopPPO2`, replays only): what the algorithm gives on these dives. 52 case closedCircuitModelled = "closed circuit, logged ppO2" 53 } 54 55 var hasHelium: Bool { samples.contains { ($0.he ?? 0) > 0 } } 56 57 var kind: Kind { 58 let openCircuit = (mode ?? "oc").hasPrefix("oc") && samples.allSatisfy { ($0.status ?? 0x10) & 0x10 != 0 } 59 if !openCircuit { return .closedCircuit } 60 if Set(samples.map(\.o2)).count > 1 || hasHelium { return .multiGas } 61 return (model ?? "GF") == "GF" ? .reference : .otherModel 62 } 63 } 64 65 @Suite("Shearwater comparison") 66 struct ShearwaterComparisonTests { 67 static let path = ProcessInfo.processInfo.environment["SHEARWATER_JSON"] 68 69 struct Totals { 70 var dives = 0 71 var ndl: [Double] = [] 72 var shortNDL: [Double] = [] // when the Shearwater shows 30 min or less: where it matters 73 var zeroEarly = 0, liberal = 0 74 var tissueErrors: [Double] = [] 75 var decoBoth = 0, decoSameDepth = 0, decoOnlyTheirs = 0, decoOnlyOurs = 0 76 var stopMinutes: [Double] = [] 77 var enterDiffs: [Double] = [] 78 var decoDivesTheirs = 0, decoDivesOurs = 0 79 } 80 81 static func mean(_ v: [Double]) -> Double { v.isEmpty ? 0 : v.reduce(0, +) / Double(v.count) } 82 static func rms(_ v: [Double]) -> Double { v.isEmpty ? 0 : (v.map { $0 * $0 }.reduce(0, +) / Double(v.count)).squareRoot() } 83 84 @Test(.enabled(if: path != nil)) 85 func replayAgainstShearwater() throws { 86 let dives = try JSONDecoder().decode([ShearwaterDive].self, 87 from: Data(contentsOf: URL(fileURLWithPath: Self.path!))) 88 let dates = DateFormatter() 89 dates.locale = Locale(identifier: "en_US_POSIX") 90 dates.timeZone = TimeZone(secondsFromGMT: 0) 91 dates.dateFormat = "yyyy-MM-dd HH:mm:ss" 92 93 var previous: (end: Date, tissues: TissueState)? 94 var totals: [ShearwaterDive.Kind: Totals] = [:] 95 // Anonymous dive identifiers for the validation report: a letter per diver (SHEARWATER_DIVER) and 96 // the rank of the dive in the export. The ROW lines feed tools/validation_tables.py (Open Rémora). 97 let diver = ProcessInfo.processInfo.environment["SHEARWATER_DIVER"] ?? "A" 98 var rank = 0 99 for dive in dives where !dive.samples.isEmpty { 100 rank += 1 101 let start = try #require(dates.date(from: dive.date)) 102 // A rebreather dive is replayed twice: as the watch would see it, then with the logged ppO2. 103 var kinds = [dive.kind] 104 if dive.kind == .closedCircuit, !dive.hasHelium, (dive.model ?? "GF") == "GF", 105 dive.samples.allSatisfy({ $0.ppo2 != nil }) { kinds.append(.closedCircuitModelled) } 106 for kind in kinds { 107 let surface = Double(dive.surface_mbar) / 1000 108 let step = Double(dive.sample_ms) / 1000 109 // The computer derives its depth from the pressure with its own water density setting. 110 let density = Double(dive.density ?? 1020) 111 let barPerMetre = density * 9.80665 / 100_000 112 113 // Reference dives: the settings of the computer. The others are replayed the way the watch 114 // would have gone through them: bottom gas (air on a rebreather, i.e. the diluent) and the 115 // conservative default gradient factors. 116 var config = DiveComputer.Configuration() 117 config.gas = kind == .closedCircuit ? .air : Gas(o2: Double(dive.samples[0].o2) / 100) 118 config.water = density < 1010 ? .fresh : density > 1022 ? .salt : .en13319 119 config.deco.gradientFactors = kind == .reference || kind == .closedCircuitModelled 120 ? GradientFactors(low: Double(dive.gf_low) / 100, high: Double(dive.gf_high) / 100) 121 : .conservative 122 config.deco.ascentRate = 10 123 // A computer set for a last stop at 6 m (usual on a rebreather) never shows a shallower one. 124 if kind == .closedCircuitModelled, let last = dive.samples.map(\.stop_depth).filter({ $0 > 0 }).min(), last >= 6 { 125 config.deco.lastStopDepth = 6 126 } 127 // Trial of another off-gassing credit for the no-stop time (see the result at the end). 128 if let rate = ProcessInfo.processInfo.environment["SHEARWATER_NOSTOP_RATE"].flatMap(Double.init) { 129 config.deco.noStopAscentRate = rate 130 } 131 132 // Initial tissues: the ones the computer logged at the start of the dive when it did (they 133 // carry every earlier dive, logged here or not), otherwise ours from the previous dive. 134 var tissues: TissueState? 135 var origin = "saturated" 136 if let first = dive.tissues?.first, first.index == 0, first.n2.count == ZHL16C.nitrogen.count { 137 tissues = TissueState(nitrogen: first.n2, compartments: ZHL16C.nitrogen) 138 origin = "logged tissues" 139 } else if kind != .closedCircuitModelled, let p = previous, start.timeIntervalSince(p.end) < 48 * 3600, start > p.end { 140 let interval = start.timeIntervalSince(p.end) / 60 141 tissues = DiveComputer.surfaceInterval(p.tissues, minutes: interval, surfacePressure: surface) 142 origin = "interval \(Int(interval)) min" 143 } 144 var computer = DiveComputer(configuration: config, surfacePressure: surface, tissues: tissues) 145 computer.update(time: 0, pressure: surface) 146 147 var t = Totals() 148 t.dives = 1 149 var snapshots = (dive.tissues ?? []).filter { $0.index > 0 }[...] 150 var stopRows: [String] = [] 151 var decoTTS: [Double] = [] 152 var enter: (theirs: Double?, ours: Double?) = (nil, nil) 153 var leave: (theirs: Double?, ours: Double?) = (nil, nil) 154 var longest = (stop: 0, tts: 0.0) 155 // Logged ppO2: the planner alone, with the mix of each sample (open circuit when bailed out). 156 var loop = (tissues: computer.tissues, pressure: surface, anchor: Double?.none) 157 for (i, s) in dive.samples.enumerated() { 158 let pressure = surface + s.depth * barPerMetre 159 let plan: AscentPlan 160 let nitrogen: [Double] 161 if kind == .closedCircuitModelled { 162 var gas = Gas(o2: Double(s.o2) / 100) 163 if (s.status ?? 0) & 0x10 == 0 { gas.loopPPO2 = s.ppo2 } 164 loop.tissues.change(from: loop.pressure, to: pressure, gas: gas, minutes: step / 60) 165 loop.pressure = pressure 166 plan = AscentPlanner.plan(tissues: loop.tissues, pressure: pressure, gas: gas, scale: computer.scale, 167 settings: config.deco, anchorDepth: loop.anchor) 168 if let anchor = plan.gradientAnchorDepth { loop.anchor = max(loop.anchor ?? 0, anchor) } 169 nitrogen = loop.tissues.nitrogen 170 } else { 171 computer.update(time: Double(i + 1) * step, pressure: pressure) 172 plan = computer.status.plan 173 nitrogen = computer.tissues.nitrogen 174 } 175 let minute = Double(i + 1) * step / 60 176 177 // Never an absurd answer, whatever the dive (deeper than the watch goes, hours long…). 178 #expect(plan.timeToSurface.isFinite && plan.timeToSurface >= 0) 179 #expect(plan.stops.allSatisfy { $0.minutes > 0 && $0.minutes < 999 && $0.depth >= 3 180 && $0.depth.truncatingRemainder(dividingBy: 3) == 0 }) 181 #expect(nitrogen.allSatisfy { $0.isFinite && $0 > 0 }) 182 longest.stop = max(longest.stop, plan.stops.map(\.minutes).reduce(0, +)) 183 longest.tts = max(longest.tts, plan.timeToSurface) 184 185 // Tissue loading against the tissues the computer logged (same gas only). 186 if let snapshot = snapshots.first, snapshot.index == i + 1 { 187 snapshots = snapshots.dropFirst() 188 if kind == .reference || kind == .otherModel || kind == .closedCircuitModelled { 189 t.tissueErrors += zip(nitrogen, snapshot.n2).map { $0 - $1 } 190 } 191 } 192 193 if s.stop_depth == 0, s.ndl_or_stop > 0, s.ndl_or_stop < 99, s.depth > 9, !plan.inDecompression { 194 let diff = floor(plan.noDecompressionLimit ?? 99) - Double(s.ndl_or_stop) 195 t.ndl.append(diff) 196 if s.ndl_or_stop <= 30 { t.shortNDL.append(diff) } 197 if s.ndl_or_stop >= 5, (plan.noDecompressionLimit ?? 99) < 1 { t.zeroEarly += 1 } 198 if s.ndl_or_stop <= 30, diff >= 5 { t.liberal += 1 } 199 if kind == .reference, s.ndl_or_stop <= 30, abs(diff) >= 5, i % 6 == 0 { 200 print(" diff t=\(Int(minute))' \(s.depth) m: Shearwater \(s.ndl_or_stop) min, Rémora \(Int(plan.noDecompressionLimit ?? 99)) min") 201 } 202 } 203 if s.stop_depth > 0 { if enter.theirs == nil { enter.theirs = minute }; leave.theirs = minute } 204 if plan.inDecompression { if enter.ours == nil { enter.ours = minute }; leave.ours = minute } 205 if s.stop_depth > 0, let stop = plan.stops.first { 206 t.decoBoth += 1 207 if Int(stop.depth.rounded()) == s.stop_depth { 208 t.decoSameDepth += 1 209 t.stopMinutes.append(Double(stop.minutes - s.ndl_or_stop)) 210 } 211 decoTTS.append(plan.timeToSurface.rounded(.up) - Double(s.tts)) 212 } else if s.stop_depth > 0 { t.decoOnlyTheirs += 1 } else if plan.inDecompression { t.decoOnlyOurs += 1 } 213 if s.stop_depth > 0 || plan.inDecompression, i % 12 == 0 { 214 let ours = plan.stops.first.map { "\(Int($0.depth)) m \($0.minutes) min, surface \(Int(plan.timeToSurface.rounded(.up)))" } ?? "none" 215 let theirs = s.stop_depth > 0 ? "\(s.stop_depth) m \(s.ndl_or_stop) min, surface \(s.tts)" : "none" 216 stopRows.append(" t=\(Int(minute))' \(s.depth) m | Shearwater \(theirs) | Rémora \(ours)") 217 } 218 } 219 220 let deepest = dive.samples.map(\.depth).max() ?? 0 221 print("Dive \(dive.number ?? "?") \(dive.date.prefix(10)) \(dive.site ?? "") [\(kind.rawValue)] " 222 + "\(dive.model ?? "GF") \(dive.gf_low)/\(dive.gf_high) -> \(config.deco.gradientFactors), \(config.gas), " 223 + String(format: "%.1f m, %.0f min, %@: no-deco %d samples, mean diff %+.1f min (%+.2f on the %d where the Shearwater shows 30 min or less), worst %+.0f min; tissues RMS %.4f bar", 224 deepest, Double(dive.samples.count) * step / 60, origin, t.ndl.count, Self.mean(t.ndl), 225 Self.mean(t.shortNDL), t.shortNDL.count, 226 t.ndl.max(by: { abs($0) < abs($1) }) ?? 0, Self.rms(t.tissueErrors))) 227 if enter.theirs != nil || enter.ours != nil { 228 func f(_ v: Double?) -> String { v.map { String(format: "%.1f", $0) } ?? "never" } 229 print(" DECO: entered Shearwater \(f(enter.theirs)) min, Rémora \(f(enter.ours)) min; left \(f(leave.theirs)) / \(f(leave.ours)) min; " 230 + String(format: "%d samples in common, same depth %d, stop time %+.2f min on average (worst %+.0f), surface %+.1f min; Shearwater only %d samples, Rémora only %d; Rémora's longest: stops %d min, surface %.0f min", 231 t.decoBoth, t.decoSameDepth, Self.mean(t.stopMinutes), 232 t.stopMinutes.max(by: { abs($0) < abs($1) }) ?? 0, Self.mean(decoTTS), 233 t.decoOnlyTheirs, t.decoOnlyOurs, longest.stop, longest.tts)) 234 if ProcessInfo.processInfo.environment["SHEARWATER_ROWS"] != nil { stopRows.forEach { print($0) } } 235 } 236 do { 237 func f(_ v: Double?) -> String { v.map { String(format: "%.1f", $0) } ?? "" } 238 let within2 = t.shortNDL.filter { abs($0) <= 2 }.count 239 let fields: [String] = [ 240 "ROW", String(format: "%@%03d", diver, rank), String(dive.date.prefix(4)), dive.computer ?? "", 241 dive.mode ?? "", dive.model ?? "GF", "\(dive.gf_low)/\(dive.gf_high)", 242 Set(dive.samples.map { "\($0.o2)/\($0.he ?? 0)" }).sorted().joined(separator: "+"), 243 String(format: "%.1f", deepest), String(format: "%.0f", Double(dive.samples.count) * step / 60), 244 "\(dive.surface_mbar)", "\(Int(density))", origin, "\(kind)", 245 "\(Int(config.deco.gradientFactors.low * 100 + 0.5))/\(Int(config.deco.gradientFactors.high * 100 + 0.5))", 246 "\(t.tissueErrors.count / 16)", String(format: "%.8f", t.tissueErrors.map { $0 * $0 }.reduce(0, +)), 247 "\(t.ndl.count)", String(format: "%.0f", t.ndl.reduce(0, +)), 248 "\(t.shortNDL.count)", String(format: "%.0f", t.shortNDL.reduce(0, +)), 249 String(format: "%.0f", t.shortNDL.map { abs($0) }.reduce(0, +)), "\(within2)", "\(t.liberal)", "\(t.zeroEarly)", 250 f(enter.theirs), f(enter.ours), f(leave.theirs), f(leave.ours), 251 "\(t.decoBoth)", "\(t.decoSameDepth)", String(format: "%.0f", t.stopMinutes.reduce(0, +)), 252 String(format: "%.0f", t.stopMinutes.max(by: { abs($0) < abs($1) }) ?? 0), 253 "\(t.decoOnlyTheirs)", "\(t.decoOnlyOurs)", "\(longest.stop)", String(format: "%.0f", longest.tts), 254 "\(Int(config.deco.lastStopDepth))", 255 ] 256 print(fields.joined(separator: ";")) 257 } 258 if enter.theirs != nil { t.decoDivesTheirs = 1 } 259 if enter.ours != nil { t.decoDivesOurs = 1 } 260 if let a = enter.theirs, let b = enter.ours { t.enterDiffs.append(b - a) } 261 262 var sum = totals[kind] ?? Totals() 263 sum.dives += 1 264 sum.ndl += t.ndl; sum.shortNDL += t.shortNDL; sum.zeroEarly += t.zeroEarly; sum.liberal += t.liberal 265 sum.tissueErrors += t.tissueErrors 266 sum.decoBoth += t.decoBoth; sum.decoSameDepth += t.decoSameDepth 267 sum.decoOnlyTheirs += t.decoOnlyTheirs; sum.decoOnlyOurs += t.decoOnlyOurs 268 sum.stopMinutes += t.stopMinutes; sum.enterDiffs += t.enterDiffs 269 sum.decoDivesTheirs += t.decoDivesTheirs; sum.decoDivesOurs += t.decoDivesOurs 270 totals[kind] = sum 271 272 if kind != .closedCircuitModelled { 273 previous = (start.addingTimeInterval(Double(dive.samples.count) * step), computer.tissues) 274 } 275 } 276 } 277 278 for kind in ShearwaterDive.Kind.allCases { 279 guard let t = totals[kind] else { continue } 280 let short = t.shortNDL 281 let within2 = Double(short.filter { abs($0) <= 2 }.count) / Double(max(1, short.count)) * 100 282 print("TOTAL [\(kind.rawValue)] \(t.dives) dives") 283 print(String(format: " no-deco: %d samples, mean diff %+.2f min, mean absolute %.2f min", t.ndl.count, Self.mean(t.ndl), Self.mean(t.ndl.map { abs($0) }))) 284 print(String(format: " no-deco, Shearwater ≤ 30 min: %d samples, mean diff %+.2f min, mean absolute %.2f min, worst %+.0f min, %.0f%% within 2 min, %d at +5 min or more, %d at zero while the Shearwater shows 5 min or more", 285 short.count, Self.mean(short), Self.mean(short.map { abs($0) }), 286 short.max(by: { abs($0) < abs($1) }) ?? 0, within2, t.liberal, t.zeroEarly)) 287 print(String(format: " deco: %d dives for the Shearwater, %d for Rémora; entered %+.1f min from the Shearwater on average; %d samples in common, same stop depth %d, stop time %+.2f min on average (worst %+.0f); Shearwater only %d samples, Rémora only %d", 288 t.decoDivesTheirs, t.decoDivesOurs, Self.mean(t.enterDiffs), t.decoBoth, t.decoSameDepth, 289 Self.mean(t.stopMinutes), t.stopMinutes.max(by: { abs($0) < abs($1) }) ?? 0, t.decoOnlyTheirs, t.decoOnlyOurs)) 290 print(String(format: " tissues: %d snapshots, mean %+.4f bar, RMS %.4f bar, worst %.3f bar", 291 t.tissueErrors.count / 16, Self.mean(t.tissueErrors), Self.rms(t.tissueErrors), 292 t.tissueErrors.map { abs($0) }.max() ?? 0)) 293 } 294 295 // Tissue loading does not depend on the decompression model of the computer. 296 let tissueErrors = (totals[.reference]?.tissueErrors ?? []) + (totals[.otherModel]?.tissueErrors ?? []) 297 #expect(Self.rms(tissueErrors) < 0.02) 298 299 // Result of 2026-11-13 (10 dives from a Petrel 3): stops identical to within one minute. 300 // No-decompression time, when the Shearwater shows 30 min or less, depending on the ascent off-gassing credit: 301 // no credit : -1.8 min on average, 77% within 2 min, 44 samples at zero too early; 302 // credit at 30 m/min : -0.3 min, 88% within 2 min, 7 samples at zero too early ← chosen (noStopAscentRate); 303 // credit at 18 m/min : +0.6 min (less conservative than the Shearwater): rejected. 304 // 305 // Result of 2026-11-23 (second diver, 127 dives, 2018 to 2026, Perdix AI then Petrel 2 on a rebreather): 306 // tissues, open circuit (49 dives, 567 snapshots) : RMS 0.0065 bar; 307 // tissues, closed circuit with the logged ppO2 (697) : RMS 0.0126 bar (ppO2 logged to 0.01 bar); 308 // stops, closed circuit, GF 30/70 and 40/65, last stop 6 m : same depth on 627 samples of 649, stop time 309 // -0.15 min on average, never more than 1 min apart (6 dives); no-stop time -1.1 min; 310 // stops, open circuit GF 30/70 (1 dive of 2018) : same depth on 184 of 186, -0.35 min; 311 // no-stop time, open circuit GF (4 dives of 2018, feet, tissues at the start unknown): +0.14 min on 312 // average, 93% within 2 min. The expectation below fails on that set by this much; with the credit 313 // at 60 m/min it gives -0.54 min there and -1.15 min on the 2026-11-13 set. 314 if let t = totals[.reference], !t.ndl.isEmpty { 315 #expect(Self.mean(t.ndl.map { abs($0) }) < 3) 316 #expect(Self.mean(t.shortNDL.map { abs($0) }) < 2) 317 #expect(Self.mean(t.shortNDL) < 0, "the engine must stay on the conservative side of the Shearwater") 318 #expect(t.zeroEarly < 15) 319 } 320 } 321 }