open-remora

Open Remora, a free secondary dive computer for Apple Watch Ultra
git clone https://git.schurger.org/open-remora.git
Log | Files | Refs | README | LICENSE

validation_tables.py (10486B)


      1 # SPDX-License-Identifier: GPL-2.0-only
      2 """Builds the tables of docs/VALIDATION.md from the output of the Shearwater comparison test.
      3 
      4 The test (RemoraKit, ShearwaterComparisonTests) prints one ROW line per replayed dive, with an anonymous
      5 identifier (a letter per diver, the rank of the dive in the export): no name, no site, no date but the year.
      6 
      7 Usage: python3 -I validation_tables.py run-A.txt run-B.txt [--update ../docs/VALIDATION.md]
      8 With --update, the text between the GENERATED markers of the report is replaced; otherwise it is printed."""
      9 import math, sys
     10 
     11 FIELDS = ("id year computer mode model gf gases depth minutes surface density origin kind gf_used "
     12           "snapshots tissue_sq ndl_n ndl_sum short_n short_sum short_abs short_within2 liberal zero_early "
     13           "enter_theirs enter_ours leave_theirs leave_ours deco_both deco_same stop_sum stop_worst "
     14           "only_theirs only_ours longest_stop longest_tts last_stop").split()
     15 NUMBERS = set("snapshots tissue_sq ndl_n ndl_sum short_n short_sum short_abs short_within2 liberal zero_early "
     16               "deco_both deco_same stop_sum stop_worst only_theirs only_ours longest_stop longest_tts".split())
     17 KINDS = [
     18     ("reference", "Open circuit, one mix, gradient factors", "the computer runs the algorithm of the engine"),
     19     ("closedCircuitModelled", "Rebreather, gradient factors, logged ppO2", "the planner with the ppO2 logged in the loop"),
     20     ("otherModel", "Open circuit, one mix, VPM-B", "as the watch would see it, default GF 30/70"),
     21     ("multiGas", "Open circuit, gas switch", "as the watch would see it: bottom mix only, default GF 30/70"),
     22     ("closedCircuit", "Rebreather", "as the watch would see it: air in open circuit, default GF 30/70"),
     23 ]
     24 ALGORITHM = ("reference", "closedCircuitModelled")
     25 
     26 def load(paths):
     27     rows = []
     28     for path in paths:
     29         for line in open(path, encoding="utf-8"):
     30             if not line.startswith("ROW;"): continue
     31             values = line.rstrip("\n").split(";")[1:]
     32             row = dict(zip(FIELDS, values))
     33             for key in NUMBERS: row[key] = float(row[key])
     34             row["diver"] = row["id"][0]
     35             rows.append(row)
     36     return rows
     37 
     38 def signed(value, digits=2): return f"{value:+.{digits}f}".replace("-", "−")
     39 def ratio(a, b): return a / b if b else 0.0
     40 
     41 def gas(row):
     42     mixes = []
     43     for mix in row["gases"].split("+"):
     44         o2, he = (int(x) for x in mix.split("/"))
     45         mixes.append(f"Tx {o2}/{he}" if he else "Air" if o2 == 21 else "O2" if o2 >= 99 else f"EAN{o2}")
     46     return ", ".join(mixes)
     47 
     48 def mode(row):
     49     if row["mode"] == "cc": return "rebreather"
     50     return "open circuit"
     51 
     52 def total(rows):
     53     t = {key: sum(r[key] for r in rows) for key in NUMBERS if key != "stop_worst"}
     54     t["dives"] = len(rows)
     55     t["stop_worst"] = max((r["stop_worst"] for r in rows), key=abs, default=0)
     56     t["deco_theirs"] = sum(1 for r in rows if r["enter_theirs"])
     57     t["deco_ours"] = sum(1 for r in rows if r["enter_ours"])
     58     enters = [float(r["enter_ours"]) - float(r["enter_theirs"]) for r in rows if r["enter_theirs"] and r["enter_ours"]]
     59     leaves = [float(r["leave_ours"]) - float(r["leave_theirs"]) for r in rows if r["leave_theirs"] and r["leave_ours"]]
     60     t["enter"] = ratio(sum(enters), len(enters)); t["leave"] = ratio(sum(leaves), len(leaves)); t["deco_pairs"] = len(enters)
     61     return t
     62 
     63 def totals_tables(rows):
     64     out = []
     65     divers = sorted({r["diver"] for r in rows})
     66     everyone = [("all divers", rows)] + [(f"diver {d}", [r for r in rows if r["diver"] == d]) for d in divers]
     67 
     68     def groups(key, field=None):
     69         """All divers together, then each of them; a single line when one diver only has such dives."""
     70         present = [(name, group) for name, group in everyone[1:]
     71                    if any(r["kind"] == key and (field is None or r[field]) for r in group)]
     72         return present if len(present) == 1 else everyone[:1] + present
     73 
     74     out += ["#### Tissue loading against the tissues logged by the computer", "",
     75             "| Replay | Dives with snapshots | Snapshots | RMS error |", "|---|---|---|---|"]
     76     for key, label, _ in KINDS:
     77         if key in ("multiGas", "closedCircuit"): continue
     78         for name, group in groups(key, "snapshots"):
     79             sel = [r for r in group if r["kind"] == key and r["snapshots"]]
     80             if not sel: continue
     81             t = total(sel)
     82             out.append(f"| {label}, {name} | {len(sel)} | {t['snapshots']:.0f} | "
     83                        f"{math.sqrt(ratio(t['tissue_sq'], t['snapshots'] * 16)):.4f} bar |")
     84     out.append("")
     85 
     86     out += ["#### No-decompression limit, where the computer shows 30 min or less", "",
     87             "| Replay | Dives | Samples | Mean difference | Mean absolute difference | Within 2 min | "
     88             "5 min or more above the computer | At zero while the computer shows 5 min or more |",
     89             "|---|---|---|---|---|---|---|---|"]
     90     for key, label, _ in KINDS:
     91         for name, group in groups(key, "short_n"):
     92             sel = [r for r in group if r["kind"] == key]
     93             t = total(sel)
     94             if not t["short_n"]: continue
     95             out.append(f"| {label}, {name} | {sum(1 for r in sel if r['short_n'])} | {t['short_n']:.0f} | {signed(ratio(t['short_sum'], t['short_n']))} min | "
     96                        f"{ratio(t['short_abs'], t['short_n']):.2f} min | {100 * ratio(t['short_within2'], t['short_n']):.0f} % | "
     97                        f"{t['liberal']:.0f} | {t['zero_early']:.0f} |")
     98     out.append("")
     99 
    100     out += ["#### Decompression stops", "",
    101             "| Replay | Dives in deco (computer / Open Rémora) | Enters deco | Leaves deco | Samples in deco for both | "
    102             "Same stop depth | Stop time, mean difference | Largest difference | Deco for the computer only (samples) | For Open Rémora only |",
    103             "|---|---|---|---|---|---|---|---|---|---|"]
    104     for key, label, _ in KINDS:
    105         for name, group in groups(key):
    106             sel = [r for r in group if r["kind"] == key]
    107             t = total(sel)
    108             if not sel or not (t["deco_theirs"] or t["deco_ours"]): continue
    109             out.append(f"| {label}, {name} | {t['deco_theirs']} / {t['deco_ours']} | "
    110                        f"{signed(t['enter'], 1) + ' min' if t['deco_pairs'] else '—'} | {signed(t['leave'], 1) + ' min' if t['deco_pairs'] else '—'} | "
    111                        f"{t['deco_both']:.0f} | {t['deco_same']:.0f} ({100 * ratio(t['deco_same'], t['deco_both']):.0f} %) | "
    112                        f"{signed(ratio(t['stop_sum'], t['deco_same'])) + ' min' if t['deco_same'] else '—'} | "
    113                        f"{signed(t['stop_worst'], 0) + ' min' if t['deco_same'] else '—'} | {t['only_theirs']:.0f} | {t['only_ours']:.0f} |")
    114     out.append("")
    115     return out
    116 
    117 def deco_cell(row):
    118     if not row["enter_theirs"] and not row["enter_ours"]: return "—"
    119     def pair(a, b): return f"{row[a] or 'never'} / {row[b] or 'never'}"
    120     cell = f"in {pair('enter_theirs', 'enter_ours')}, out {pair('leave_theirs', 'leave_ours')}"
    121     if row["deco_both"]:
    122         cell += f"; same depth {row['deco_same']:.0f}/{row['deco_both']:.0f}"
    123         if row["deco_same"]: cell += f", stop {signed(ratio(row['stop_sum'], row['deco_same']))} min"
    124     return cell
    125 
    126 def dive_tables(rows):
    127     out = []
    128     for key, label, how in KINDS:
    129         sel = [r for r in rows if r["kind"] == key]
    130         if not sel: continue
    131         algorithm = key in ALGORITHM
    132         out += [f"#### {label} ({len(sel)} dives)", "", f"Replayed as: {how}.", ""]
    133         head = ["Dive", "Year", "Computer", "Model, GF" if not algorithm else "GF", "Gas", "Max depth", "Duration",
    134                 "Surface", "Water", "Starting tissues", "Tissues RMS (snapshots)", "NDL samples ≤ 30 min", "NDL mean difference",
    135                 "Deco: minute in and out (computer / Open Rémora); stops"]
    136         if not algorithm: head.append("Longest stops asked by Open Rémora")
    137         out += ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
    138         for r in sel:
    139             model = r["gf"] if algorithm else (f"{r['model']}" if r["model"] != "GF" else f"GF {r['gf']}")
    140             if algorithm and r["last_stop"] == "6": model += ", last stop 6 m"
    141             cells = [r["id"], r["year"], r["computer"], model, gas(r), f"{r['depth']} m", f"{r['minutes']} min",
    142                      f"{r['surface']} mbar", f"{r['density']} kg/m³", r["origin"].replace("interval", "previous dive,"),
    143                      f"{math.sqrt(ratio(r['tissue_sq'], r['snapshots'] * 16)):.4f} bar ({r['snapshots']:.0f})" if r["snapshots"] else "—",
    144                      f"{r['short_n']:.0f}", signed(ratio(r["short_sum"], r["short_n"])) + " min" if r["short_n"] else "—",
    145                      deco_cell(r)]
    146             if not algorithm: cells.append(f"{r['longest_stop']:.0f} min" if r["longest_stop"] else "—")
    147             out.append("| " + " | ".join(cells) + " |")
    148         out.append("")
    149     return out
    150 
    151 def data_table(rows):
    152     out = ["| Diver | Dives | Years | Computers | Depth | Replays |", "|---|---|---|---|---|---|"]
    153     for d in sorted({r["diver"] for r in rows}):
    154         sel = [r for r in rows if r["diver"] == d]
    155         dives = {r["id"]: r for r in sel}.values()
    156         kinds = "; ".join(f"{sum(1 for r in sel if r['kind'] == key)} × {label}" for key, label, _ in KINDS
    157                           if any(r["kind"] == key for r in sel))
    158         years = sorted({r["year"] for r in dives})
    159         out.append(f"| {d} | {len(dives)} | {years[0]}–{years[-1]} | {', '.join(sorted({r['computer'] for r in dives}))} | "
    160                    f"{min(float(r['depth']) for r in dives):.0f} to {max(float(r['depth']) for r in dives):.1f} m | {kinds} |")
    161     return out + [""]
    162 
    163 if __name__ == "__main__":
    164     args = [a for a in sys.argv[1:] if not a.startswith("--")]
    165     update = args.pop() if "--update" in sys.argv else None
    166     rows = load(args)
    167     sections = {"DATA": data_table(rows), "TOTALS": totals_tables(rows), "DIVES": dive_tables(rows)}
    168     if not update:
    169         for name, lines in sections.items(): print("\n".join(lines))
    170         sys.exit(0)
    171     text = open(update, encoding="utf-8").read()
    172     for name, lines in sections.items():
    173         begin, end = f"<!-- GENERATED {name} -->", f"<!-- END {name} -->"
    174         a, b = text.index(begin) + len(begin), text.index(end)
    175         text = text[:a] + "\n" + "\n".join(lines) + text[b:]
    176     open(update, "w", encoding="utf-8").write(text)
    177     print("updated", update)