commit 8794dff6f27bd4975871db53d1f02975a37336f5
parent 1661a36f14b587892f48c0d876217d5fbdc4efd0
Author: Jean Schurger <jean@schurger.org>
Date: Fri, 13 Nov 2026 15:08:39 -0500
Comparison with a Shearwater: decoder for the Shearwater Cloud export (PNF) and a test that replays the dives through the engine
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYGcjJYQu2t1EUEKgbs
Diffstat:
3 files changed, 186 insertions(+), 0 deletions(-)
diff --git a/Packages/RemoraDeco/Tests/RemoraDecoTests/ShearwaterComparisonTests.swift b/Packages/RemoraDeco/Tests/RemoraDecoTests/ShearwaterComparisonTests.swift
@@ -0,0 +1,110 @@
+import Foundation
+import Testing
+@testable import RemoraDeco
+
+/// Compare le moteur à un ordinateur certifié : rejoue des plongées Shearwater (même algorithme, mêmes GF)
+/// et confronte le temps sans palier et les paliers à ceux que l'ordinateur affichait.
+/// Données personnelles hors dépôt : `tools/shearwater_decode.py` produit le JSON, chemin dans SHEARWATER_JSON.
+struct ShearwaterDive: Decodable {
+ struct Sample: Decodable {
+ let depth: Double
+ let stop_depth: Int
+ let tts: Int
+ let o2: Int
+ let ndl_or_stop: Int
+ let ceiling: Int
+ }
+ let number: String?
+ let site: String?
+ let date: String
+ let gf_low: Int
+ let gf_high: Int
+ let surface_mbar: Int
+ let sample_ms: Int
+ let samples: [Sample]
+}
+
+@Suite("Comparaison Shearwater")
+struct ShearwaterComparisonTests {
+ static let path = ProcessInfo.processInfo.environment["SHEARWATER_JSON"]
+
+ @Test(.enabled(if: path != nil))
+ func replayAgainstShearwater() throws {
+ let dives = try JSONDecoder().decode([ShearwaterDive].self,
+ from: Data(contentsOf: URL(fileURLWithPath: Self.path!)))
+ let dates = DateFormatter()
+ dates.locale = Locale(identifier: "en_US_POSIX")
+ dates.timeZone = TimeZone(secondsFromGMT: 0)
+ dates.dateFormat = "yyyy-MM-dd HH:mm:ss"
+
+ var previous: (end: Date, tissues: TissueState)?
+ var allNDL: [Double] = []
+ var shortNDL: [Double] = [] // quand le Shearwater affiche 30 min ou moins : là où ça compte
+ for dive in dives {
+ let start = try #require(dates.date(from: dive.date))
+ let surface = Double(dive.surface_mbar) / 1000
+ let step = Double(dive.sample_ms) / 1000
+
+ var config = DiveComputer.Configuration()
+ config.gas = Gas(o2: Double(dive.samples[0].o2) / 100)
+ config.water = .en13319
+ config.deco.gradientFactors = GradientFactors(low: Double(dive.gf_low) / 100, high: Double(dive.gf_high) / 100)
+ config.deco.ascentRate = 10
+
+ var tissues: TissueState?
+ var interval: Double?
+ if let p = previous, start.timeIntervalSince(p.end) < 48 * 3600 {
+ interval = start.timeIntervalSince(p.end) / 60
+ tissues = DiveComputer.surfaceInterval(p.tissues, minutes: interval!, surfacePressure: surface)
+ }
+ var computer = DiveComputer(configuration: config, surfacePressure: surface, tissues: tissues)
+ computer.update(time: 0, pressure: surface)
+
+ var ndlDiffs: [Double] = []
+ var stopRows: [String] = []
+ var firstDeco: String?
+ for (i, s) in dive.samples.enumerated() {
+ computer.update(time: Double(i + 1) * step, pressure: computer.scale.pressure(atDepth: s.depth))
+ let plan = computer.status.plan
+ if s.stop_depth == 0, s.ndl_or_stop > 0, s.ndl_or_stop < 99, s.depth > 9, !plan.inDecompression {
+ let diff = floor(plan.noDecompressionLimit ?? 99) - Double(s.ndl_or_stop)
+ ndlDiffs.append(diff)
+ if s.ndl_or_stop <= 30 { shortNDL.append(diff) }
+ if s.ndl_or_stop <= 30, abs(diff) >= 5, i % 6 == 0 {
+ print(" écart t=\(Int(Double(i + 1) * step / 60))' \(s.depth) m : Shearwater \(s.ndl_or_stop) min, Rémora \(Int(plan.noDecompressionLimit ?? 99)) min")
+ }
+ }
+ if s.stop_depth > 0 || plan.inDecompression {
+ let ours = plan.stops.first.map { "\(Int($0.depth)) m \($0.minutes) min, surface \(Int(plan.timeToSurface.rounded(.up)))" } ?? "aucun"
+ let theirs = s.stop_depth > 0 ? "\(s.stop_depth) m \(s.ndl_or_stop) min, surface \(s.tts)" : "aucun"
+ if firstDeco == nil { firstDeco = "t=\(Int(Double(i + 1) * step / 60)) min" }
+ if i % 12 == 0 { stopRows.append(" t=\(Int(Double(i + 1) * step / 60))' \(s.depth) m | Shearwater \(theirs) | Rémora \(ours)") }
+ }
+ }
+ allNDL.append(contentsOf: ndlDiffs)
+ let mean = ndlDiffs.isEmpty ? 0 : ndlDiffs.reduce(0, +) / Double(ndlDiffs.count)
+ let worst = ndlDiffs.map { abs($0) }.max() ?? 0
+ print("Plongée \(dive.number ?? "?") \(dive.site ?? "") GF \(dive.gf_low)/\(dive.gf_high) O2 \(dive.samples[0].o2) %"
+ + (interval.map { " (intervalle \(Int($0)) min)" } ?? "")
+ + String(format: " : sans palier, %d points, écart moyen %+.1f min, pire %.0f min", ndlDiffs.count, mean, worst))
+ stopRows.forEach { print($0) }
+
+ let duration = Double(dive.samples.count) * step
+ previous = (start.addingTimeInterval(duration), computer.tissues)
+ }
+ let mean = allNDL.reduce(0, +) / Double(max(1, allNDL.count))
+ let meanAbs = allNDL.map { abs($0) }.reduce(0, +) / Double(max(1, allNDL.count))
+ print(String(format: "TOTAL sans palier : %d points, écart moyen %+.2f min, écart absolu moyen %.2f min", allNDL.count, mean, meanAbs))
+ let shortMean = shortNDL.reduce(0, +) / Double(max(1, shortNDL.count))
+ let shortAbs = shortNDL.map { abs($0) }.reduce(0, +) / Double(max(1, shortNDL.count))
+ let within2 = Double(shortNDL.filter { abs($0) <= 2 }.count) / Double(max(1, shortNDL.count)) * 100
+ print(String(format: "COURT (Shearwater ≤ 30 min) : %d points, écart moyen %+.2f min, absolu moyen %.2f min, pire %.0f min, %.0f %% à 2 min près",
+ shortNDL.count, shortMean, shortAbs, shortNDL.map { abs($0) }.max() ?? 0, within2))
+ // Résultat du 2026-11-13 (10 plongées d'un Petrel 3) : paliers identiques à une minute près ; temps sans
+ // palier en moyenne 1,9 min plus court que le Shearwater quand il affiche 30 min ou moins. Une variante
+ // qui compte la désaturation pendant la remontée donnait 2 min de PLUS que lui : écartée, on reste prudent.
+ #expect(meanAbs < 3.5)
+ #expect(shortAbs < 3)
+ #expect(shortMean < 0, "le moteur doit rester du côté prudent par rapport au Shearwater")
+ }
+}
diff --git a/tools/shearwater_decode.py b/tools/shearwater_decode.py
@@ -0,0 +1,57 @@
+"""Décode l'export Shearwater Cloud (dive_data.db, format sw-pnf) en JSON.
+Usage : python3 -I shearwater_decode.py chemin/dive_data.db [sortie.json] [--dump N]
+Champs des échantillons d'après libdivecomputer (shearwater_predator_parser.c, format PNF)."""
+import gzip, json, sqlite3, struct, sys
+
+def records(blob):
+ data = gzip.decompress(blob[4:])
+ return [data[i:i + 32] for i in range(0, len(data), 32)]
+
+def decode(db_path):
+ db = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
+ details = {r[0]: r for r in db.execute("select DiveId, DiveNumber, Site, Depth, DiveLengthTime, DiveDate from dive_details")}
+ dives = []
+ for log_id, name, blob, calc in db.execute("select log_id, file_name, data_bytes_1, calculated_values_from_samples from log_data order by log_id"):
+ recs = records(blob)
+ byt = {r[0]: r for r in recs if r[0] != 0x01}
+ o0, o1, o5 = byt.get(0x10), byt.get(0x11), byt.get(0x15)
+ d = details.get(log_id)
+ dive = {
+ "id": log_id, "file": name, "number": d[1] if d else None, "site": d[2] if d else None,
+ "date": d[5] if d else None, "cloud_max_depth": float(d[3]) if d else None,
+ "gf_low": o0[4], "gf_high": o0[5], "imperial": o0[8],
+ "surface_mbar": struct.unpack(">H", o1[16:18])[0],
+ "sample_ms": struct.unpack(">H", o5[23:25])[0] if o5 else None,
+ "raw_opening": {f"{k:02x}": v.hex() for k, v in sorted(byt.items()) if k < 0x20},
+ "calc": json.loads(calc) if calc else None, "samples": [],
+ }
+ for r in recs:
+ if r[0] != 0x01: continue
+ stop_depth = struct.unpack(">H", r[3:5])[0]
+ dive["samples"].append({
+ "depth": struct.unpack(">H", r[1:3])[0] / 10, "stop_depth": stop_depth,
+ "tts": struct.unpack(">H", r[5:7])[0], "ppo2": r[7] / 100, "o2": r[8], "he": r[9],
+ "ndl_or_stop": r[10], "status": r[12], "temp": struct.unpack("b", r[14:15])[0],
+ "cns": r[23], "ceiling": r[24], "gf99": r[25],
+ })
+ dives.append(dive)
+ return dives
+
+if __name__ == "__main__":
+ dives = decode(sys.argv[1])
+ if "--dump" in sys.argv:
+ n = int(sys.argv[sys.argv.index("--dump") + 1])
+ d = dives[n]
+ print({k: v for k, v in d.items() if k not in ("samples", "raw_opening")})
+ for i, s in enumerate(d["samples"]):
+ if i % max(1, len(d["samples"]) // 40) == 0: print(i, s)
+ else:
+ for d in dives:
+ s = d["samples"]
+ print(d["number"], d["date"], d["site"], "GF", d["gf_low"], d["gf_high"], "surf", d["surface_mbar"],
+ "pas", d["sample_ms"], "n", len(s), "max", max(x["depth"] for x in s), "cloud", d["cloud_max_depth"],
+ "O2", sorted({x["o2"] for x in s}), "NDLmin", min(x["ndl_or_stop"] for x in s if x["stop_depth"] == 0),
+ "stops", sorted({x["stop_depth"] for x in s}), "temp", min(x["temp"] for x in s))
+ if len(sys.argv) > 2 and not sys.argv[2].startswith("--"):
+ json.dump(dives, open(sys.argv[2], "w"))
+ print("écrit", sys.argv[2])
diff --git a/tools/shearwater_probe.py b/tools/shearwater_probe.py
@@ -0,0 +1,19 @@
+"""Sonde de l'export Shearwater Cloud (dive_data.db) : usage python3 -I shearwater_probe.py chemin/dive_data.db"""
+import sqlite3, sys, zlib, gzip, binascii
+db = sqlite3.connect(f"file:{sys.argv[1]}?mode=ro", uri=True)
+row = db.execute("select log_id, file_name, data_bytes_1, data_bytes_2, data_bytes_3 from log_data order by log_id desc limit 1").fetchone()
+print(row[1])
+for i, b in enumerate(row[2:], 1):
+ print(f"bytes_{i}", len(b), binascii.hexlify(b[:48]).decode())
+b = row[2]
+for name, f in (("zlib", zlib.decompress), ("gzip", gzip.decompress), ("raw-deflate", lambda x: zlib.decompress(x, -15)),
+ ("zlib+4", lambda x: zlib.decompress(x[4:])), ("gzip+4", lambda x: gzip.decompress(x[4:]))):
+ try:
+ out = f(b); print(name, "OK", len(out)); break
+ except Exception as e:
+ print(name, "non:", str(e)[:50]); out = None
+data = out or b
+print("taille", len(data), "reste/32", len(data) % 32)
+for k in range(0, min(len(data), 32 * 14), 32):
+ print(binascii.hexlify(data[k:k + 32], " ").decode())
+print(row[3][:107]); print(row[4][:200])