"""Checks a V2X log recorded with Settings > Ride > "Record motion sensors" on, before it is used for sensor fusion: are the motion sensors complete and at their rate, are both phone GNSS sources there, and do the clocks line up. See docs/07-sensor-fusion-logging.md. py -3.11 tools/fusion_log_check.py LOG.db [LOG.db ...] Pull a log off the phone with Share on the V2X data logger screen, or with adb exec-out run-as com.hawhamburg.micr0bu cat files/v2x_logs/.db > .db Reads the file read-only. Prints a report per file and ends with PASS, WARN or FAIL lines; the exit code is 1 if any file has a FAIL. Standard library only. """ import math import sqlite3 import statistics import sys from bisect import bisect_left from pathlib import Path IMU_SENSORS = ('accel', 'gyro', 'gravity') G = 9.80665 # What a usable fusion log looks like. Rates are what the logger asks for (100 Hz); the phone may # deliver a little more or less. IMU_RATE_MIN_HZ, IMU_RATE_MAX_HZ = 80.0, 130.0 IMU_GAP_WARN_MS, IMU_GAP_FAIL_MS = 100.0, 1000.0 GNSS_GAP_WARN_S = 5.0 class Report: def __init__(self): self.verdicts = [] def line(self, text=''): print(text) def verdict(self, level, text): self.verdicts.append((level, text)) @property def failed(self): return any(level == 'FAIL' for level, _ in self.verdicts) def pct(values, q): """The q-th percentile (0..100) of a non-empty list, nearest rank.""" s = sorted(values) return s[min(len(s) - 1, max(0, math.ceil(q / 100 * len(s)) - 1))] def haversine_m(lat1, lon1, lat2, lon2): r = 6_371_000.0 p1, p2 = math.radians(lat1), math.radians(lat2) a = math.sin((p2 - p1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(math.radians(lon2 - lon1) / 2) ** 2 return 2 * r * math.asin(math.sqrt(a)) def tables(db): return {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")} def check_meta(db, rep): meta = dict(db.execute('SELECT key, value FROM meta')) rep.line('meta') for key in ('schema_version', 'phone', 'android_sdk', 'app_version', 'hardware', 'phone_mount', 'fusion_logging', 'imu_period_us', 'sensor_accel', 'sensor_gyro', 'sensor_gravity', 'gnss_hardware', 'started_ms', 'ended_ms'): if key in meta: rep.line(f' {key:15} {meta[key]}') if int(meta.get('schema_version', '1')) < 2: rep.verdict('FAIL', 'schema version below 2: recorded before sensor fusion logging existed') if meta.get('fusion_logging') != 'true': rep.verdict('FAIL', 'fusion_logging is not on: turn on Settings > Ride > Record motion sensors before starting the log') if 'ended_ms' not in meta: rep.verdict('WARN', 'no ended_ms: the log was not stopped cleanly (app killed?); data up to the last batch is still usable') return meta def check_imu(db, rep): rep.line('imu') spans = {} for sensor in IMU_SENSORS: t = [r[0] for r in db.execute('SELECT elapsed_ns FROM imu WHERE sensor=? ORDER BY id', (sensor,))] if not t: level = 'WARN' if sensor == 'gravity' else 'FAIL' rep.line(f' {sensor:8} no samples') rep.verdict(level, f'imu {sensor}: no samples') continue backwards = sum(1 for a, b in zip(t, t[1:]) if b <= a) ts = sorted(t) dts = [(b - a) / 1e6 for a, b in zip(ts, ts[1:]) if b > a] span_s = (ts[-1] - ts[0]) / 1e9 rate = (len(ts) - 1) / span_s if span_s > 0 else 0.0 max_gap = max(dts) if dts else 0.0 gaps = sum(1 for d in dts if d > IMU_GAP_WARN_MS) spans[sensor] = (ts[0], ts[-1]) rep.line(f' {sensor:8} {len(ts):8d} samples over {span_s:7.1f} s = {rate:6.1f} Hz, ' f'dt median {statistics.median(dts):5.2f} ms, p99 {pct(dts, 99):6.2f} ms, max {max_gap:7.1f} ms, ' f'{gaps} gaps > {IMU_GAP_WARN_MS:.0f} ms, {backwards} out of order') if not IMU_RATE_MIN_HZ <= rate <= IMU_RATE_MAX_HZ: rep.verdict('WARN', f'imu {sensor}: {rate:.1f} Hz, expected about 100') if max_gap > IMU_GAP_FAIL_MS: rep.verdict('FAIL', f'imu {sensor}: a gap of {max_gap / 1000:.1f} s (screen off without the log service? app paused?)') elif gaps: rep.verdict('WARN', f'imu {sensor}: {gaps} gaps over {IMU_GAP_WARN_MS:.0f} ms') if backwards: rep.verdict('WARN', f'imu {sensor}: {backwards} samples not after the previous one in write order') # Magnitudes: accelerometer and gravity should average to g; the gyroscope tells how much it turned. mags = [math.sqrt(x * x + y * y + z * z) for x, y, z in db.execute('SELECT x, y, z FROM imu WHERE sensor=?', (sensor,))] unit = 'rad/s' if sensor == 'gyro' else 'm/s^2' rep.line(f' {"":8} |v| median {statistics.median(mags):.3f} {unit}, p95 {pct(mags, 95):.3f}') if sensor in ('accel', 'gravity') and abs(statistics.median(mags) - G) > 0.5: rep.verdict('WARN', f'imu {sensor}: median magnitude {statistics.median(mags):.2f}, expected about {G:.2f}') return spans def check_gnss(db, rep, imu_spans): rep.line('gnss') sources = [r[0] for r in db.execute('SELECT DISTINCT source FROM gnss ORDER BY source')] by_source = {} imu_t = [r[0] for r in db.execute("SELECT elapsed_ns FROM imu WHERE sensor='gyro' ORDER BY elapsed_ns")] for src in sources: rows = list(db.execute( 'SELECT ts_ms, fix_ms, elapsed_ns, lat, lon, accuracy_m, speed_mps, speed_accuracy_mps, ' 'bearing_accuracy_deg, provider FROM gnss WHERE source=? ORDER BY id', (src,))) by_source[src] = rows fix_ms = [r[1] for r in rows] dts = [(b - a) / 1000 for a, b in zip(fix_ms, fix_ms[1:]) if b > a] acc = [r[5] for r in rows if r[5] is not None] latency = [r[0] - r[1] for r in rows] with_elapsed = sum(1 for r in rows if r[2] is not None) with_speed_acc = sum(1 for r in rows if r[7] is not None) with_bearing_acc = sum(1 for r in rows if r[8] is not None) providers = sorted({r[9] for r in rows if r[9]}) rate = 1 / statistics.median(dts) if dts else 0.0 rep.line(f' {src:9} {len(rows):6d} fixes, interval median {statistics.median(dts) if dts else 0:5.2f} s ' f'({rate:4.1f} Hz), max {max(dts) if dts else 0:6.1f} s, accuracy median ' f'{statistics.median(acc) if acc else float("nan"):5.1f} m p95 {pct(acc, 95) if acc else float("nan"):5.1f} m') rep.line(f' {"":9} received after the fix: median {statistics.median(latency):.0f} ms, p95 {pct(latency, 95):.0f} ms; ' f'elapsed_ns {with_elapsed}/{len(rows)}, speed accuracy {with_speed_acc}, bearing accuracy {with_bearing_acc}; ' f'provider {", ".join(providers) or "-"}') if dts and max(dts) > GNSS_GAP_WARN_S: rep.verdict('WARN', f'gnss {src}: a gap of {max(dts):.1f} s between fixes') if src in ('phone', 'phone_gps') and with_elapsed < len(rows): rep.verdict('FAIL', f'gnss {src}: {len(rows) - with_elapsed} fixes without elapsed_ns, which fusion lines up on') if src in ('phone', 'phone_gps') and imu_t: inside = sum(1 for r in rows if r[2] is not None and imu_t[0] <= r[2] <= imu_t[-1]) covered = sum(1 for r in rows if r[2] is not None and _near(imu_t, r[2], 20_000_000)) rep.line(f' {"":9} {inside}/{len(rows)} fixes inside the gyro recording, {covered} with a gyro sample within 20 ms') if inside and covered < inside: rep.verdict('WARN', f'gnss {src}: {inside - covered} fixes inside the recording with no gyro sample within 20 ms') for needed in ('phone', 'phone_gps'): if needed not in by_source: rep.verdict('FAIL', f'gnss: no {needed} fixes' + (' (location permission? GPS off?)' if needed == 'phone_gps' else '')) if 'phone' in by_source and 'phone_gps' in by_source: compare_sources(rep, by_source['phone_gps'], by_source['phone'], 'phone_gps vs phone (fused)') if 'obu' in by_source and 'phone_gps' in by_source: compare_sources(rep, by_source['phone_gps'], by_source['obu'], 'phone_gps vs obu', key=1, tol_ms=500) def _near(sorted_t, t, tol): i = bisect_left(sorted_t, t) return any(0 <= j < len(sorted_t) and abs(sorted_t[j] - t) <= tol for j in (i - 1, i)) def compare_sources(rep, a_rows, b_rows, label, key=2, tol_ms=500): """Horizontal distance between two sources' fixes taken at about the same time (key: 2 = elapsed_ns, 1 = fix_ms).""" scale = 1_000_000 if key == 2 else 1 b = sorted((r[key], r[3], r[4]) for r in b_rows if r[key] is not None) bt = [x[0] for x in b] d = [] for r in a_rows: if r[key] is None: continue i = bisect_left(bt, r[key]) best = min((j for j in (i - 1, i) if 0 <= j < len(b)), key=lambda j: abs(bt[j] - r[key]), default=None) if best is not None and abs(bt[best] - r[key]) <= tol_ms * scale: d.append(haversine_m(r[3], r[4], b[best][1], b[best][2])) if d: rep.line(f' {label}: {len(d)} pairs within {tol_ms} ms, distance median {statistics.median(d):.1f} m, ' f'p95 {pct(d, 95):.1f} m, max {max(d):.1f} m') def check_clock(db, rep): rep.line('clock') rows = list(db.execute('SELECT elapsed_ns, wall_ms, gnss_ms FROM clock ORDER BY id')) if not rows: rep.verdict('FAIL', 'clock: no rows') return with_gnss = [r for r in rows if r[2] is not None] # Wall clock against the monotonic clock: a step shows up as a jump in their difference. off = [r[1] - r[0] / 1e6 for r in rows] steps = [(b - a) for a, b in zip(off, off[1:]) if abs(b - a) > 100] rep.line(f' {len(rows)} rows, {len(with_gnss)} with GNSS time') if with_gnss: err = [r[1] - r[2] for r in with_gnss] rep.line(f' phone clock minus GNSS time: median {statistics.median(err):+.0f} ms, ' f'range {min(err):+.0f} .. {max(err):+.0f} ms') else: rep.verdict('WARN', 'clock: no GNSS time at all (no fix for the whole log?)') if steps: rep.line(f' phone clock stepped {len(steps)} times: ' + ', '.join(f'{s:+.0f} ms' for s in steps[:10])) rep.verdict('WARN', f'clock: the phone clock stepped {len(steps)} times; use elapsed_ns and the clock table, not ts_ms, to line data up') def check(path): rep = Report() print(f'== {path}') db = sqlite3.connect(f'file:{Path(path).as_posix()}?mode=ro', uri=True) have = tables(db) if 'meta' not in have: rep.verdict('FAIL', 'not a MicrOBU V2X log (no meta table)') else: check_meta(db, rep) if not {'imu', 'clock'} <= have: rep.verdict('FAIL', 'no imu/clock tables: recorded with an app from before sensor fusion logging') else: spans = check_imu(db, rep) check_gnss(db, rep, spans) check_clock(db, rep) db.close() for level, text in rep.verdicts: print(f'{level}: {text}') if not rep.verdicts: print('PASS: ready for sensor fusion') elif not any(level in ('FAIL', 'WARN') for level, _ in rep.verdicts): print('PASS') print() return rep.failed def main(argv): if not argv: print(__doc__) return 2 failed = [p for p in argv if check(p)] return 1 if failed else 0 if __name__ == '__main__': sys.exit(main(sys.argv[1:]))