Skip to content

armgit / moss

Public Imported from GitHub
0

MOSS: a small, mostly 3D-printed litter-picking rover. Cleaner streets, one maker at a time.

Python

the floor lessons of the earlier rover come back: costmap guards, directional contacts, camera workers, speed guard, run film

metrox0e94d04888d6
diff --git a/benches/bench_bump_imu_cold.py b/benches/bench_bump_imu_cold.py
index bb6ef8f..93a744e 100644
--- a/benches/bench_bump_imu_cold.py
+++ b/benches/bench_bump_imu_cold.py
@@ -7,21 +7,30 @@ down axis (y = -9.81 m/s^2), a little fixed-seed noise:
A. the rule - a 6 m/s^2 deceleration pulse of 60 ms while the tracks are
commanded (70, 60) -> exactly one contact at the pulse, its
- high-pass about -6.0 m/s^2; no command, a (0, 0) command or
- a stale one -> none; a 1.5 m/s^2 wobble -> none; two pulses
- 0.3 s apart -> one, 1.0 s apart -> two; an acceleration
- (wrong sign) while driving forward -> none, the same kick
- while reversing -> one; a pivot takes either sign; a 2 m/s^2
- tilt held 3 s, a camera pitched 10 or 30 deg, a slope of
- 5 m/s^2 reached over 2 s -> none; a pulse before 0.25 s of
- history -> none
+ high-pass about -6.0 m/s^2, in front; no command, a (0, 0)
+ command or a stale one -> none; a 1.5 m/s^2 wobble -> none;
+ two pulses 0.3 s apart -> one, 1.0 s apart -> two; an
+ acceleration (wrong sign) while driving forward -> none, the
+ same kick while reversing -> one, behind; a pivot takes
+ either sign, the sign giving the side; a 2 m/s^2 tilt held
+ 3 s, a camera pitched 10 or 30 deg, a slope of 5 m/s^2
+ reached over 2 s -> none; a pulse before 0.25 s of history
+ -> none
+ F. the sides - a front contact, then the command reversed and a kick
+ behind 0.4 s later (inside the 0.7 s debounce) -> two
+ contacts, front then rear (a rear contact is not a repeat
+ of a front one); the same kick under the SAME pivot
+ command -> one (the rebound of the impact); a reverse
+ take-off while the telemetry still says forward -> none
B. the knobs - MOSS_BUMP_ACCEL=8 -> the 6 pulse is not a contact, a 9 one
is; MOSS_BUMP_AXIS=-z on a camera turned round -> the
contact again; bad values refused, defaults kept
C. the module - base_telemetry then the pulse sample by sample -> one
- Bool(True) on bump and the log line with its numbers;
- no command, a stale firmware line, an unwired Out, a NaN
- sample, a bad telemetry line -> no bump and no exception
+ Bool(True) on bump and the log line with its numbers and
+ side; reversing then the kick -> one Bool(True) on
+ bump_rear and nothing on bump; no command, a stale firmware
+ line, an unwired Out, a NaN sample, a bad telemetry line
+ -> no bump and no exception
D. the CSV - MOSS_IMU_LOG writes a header and one row per sample with
the high-pass and the command; an unwritable path warns
once and never raises
@@ -32,6 +41,17 @@ down axis (y = -9.81 m/s^2), a little fixed-seed noise:
module / a gyro rate not offered / a start that fails ->
a warning and the camera goes on; the parent publishes the
motion axes unrotated in <camera>_accel_optical_frame
+ G. the watchdog - ImuWatchdog on a fake clock: no sample for 10 s after start
+ -> one "waiting" status line; 200 Hz for 10 s -> a status
+ line "alive ... (200 Hz)" with gravity on y; samples stop
+ -> exactly one "MOSS IMU: no sample for 1 s - IMU contacts
+ and gyro prior OFF" at 1 s, nothing more while quiet but a
+ QUIET status every 10 s; samples resume -> "MOSS IMU:
+ samples back (200 Hz) after 3.2 s quiet" once the resumed
+ stream ran 1 s; a stream dropping out every 2 s -> at most
+ one "no sample" line per 5 s, the spells in between
+ counted; the module's own thread says it on the real clock,
+ stop() ends it; a failing look warns once, never raises
No hardware, no pyrealsense2 (a fake stands in), no bus.
@@ -44,6 +64,7 @@ import os
import random
import sys
import tempfile
+import time
import types
from pathlib import Path
@@ -130,8 +151,9 @@ check(" ... at the first sample of the pulse (t = 1.500 s)",
len(hits) == 1 and abs(hits[0][0] - (T0 + 1.5)) < 1e-6, f"{[round(h[0] - T0, 3) for h in hits]}")
check(" ... its high-pass is the pulse: -6.0 m/s^2 within 0.15",
len(hits) == 1 and abs(hits[0][1] - (-6.0)) <= 0.15, f"{[round(h[1], 3) for h in hits]}")
-check(" ... the detector counts one contact and remembers the command",
- det.contacts == 1 and det.last_contact["commanded"] == (70, 60), f"{det.contacts} {det.last_contact}")
+check(" ... the detector counts one contact and remembers the command and its side (in front)",
+ det.contacts == 1 and det.last_contact["commanded"] == (70, 60) and det.last_contact["side"] == "front",
+ f"{det.contacts} {det.last_contact}")
check("(b) the same pulse with commanded (0, 0) -> none", run(trace(pulses=[PULSE]), commanded=(0, 0))[1] == [])
check(" ... with no command at all -> none", run(trace(pulses=[PULSE]), commanded=None)[1] == [])
check(" ... with a command 1.5 s old (older than 1 s) -> none", run(trace(pulses=[PULSE]), age=1.5)[1] == [])
@@ -148,12 +170,17 @@ check(" ... 1.0 s apart -> two, at 1.5 s and 2.5 s",
[round(h[0] - T0, 3) for h in far_hits] == [1.5, 2.5], f"{[round(h[0] - T0, 3) for h in far_hits]}")
kick = trace(pulses=[(1.5, 0.06, +6.0)])
check("(e) a +6 m/s^2 pulse (an acceleration) while commanded forward -> none", run(kick)[1] == [])
-check(" ... the same +6 kick while reversing (-70, -60) -> one (a contact behind)",
- len(run(kick, commanded=(-70, -60))[1]) == 1)
+rev_det, rev_hits = run(kick, commanded=(-70, -60))
+check(" ... the same +6 kick while reversing (-70, -60) -> one, a contact behind (side rear)",
+ len(rev_hits) == 1 and rev_det.last_contact["side"] == "rear", f"{rev_det.last_contact}")
check(" ... a -6 pulse while reversing -> none (that is the reverse taking off)",
run(trace(pulses=[PULSE]), commanded=(-70, -60))[1] == [])
-check(" ... a pivot (70, -70) takes either sign: -6 -> one, +6 -> one",
- len(run(trace(pulses=[PULSE]), commanded=(70, -70))[1]) == 1 and len(run(kick, commanded=(70, -70))[1]) == 1)
+piv_dec, piv_dec_hits = run(trace(pulses=[PULSE]), commanded=(70, -70))
+piv_kick, piv_kick_hits = run(kick, commanded=(70, -70))
+check(" ... a pivot (70, -70) takes either sign: -6 -> one in front, +6 -> one behind",
+ len(piv_dec_hits) == 1 and len(piv_kick_hits) == 1
+ and (piv_dec.last_contact["side"], piv_kick.last_contact["side"]) == ("front", "rear"),
+ f"{piv_dec.last_contact} {piv_kick.last_contact}")
check(" ... an arc with one track stopped (70, 0) is forward: -6 -> one, +6 -> none",
len(run(trace(pulses=[PULSE]), commanded=(70, 0))[1]) == 1 and run(kick, commanded=(70, 0))[1] == [])
check("(f) tilt: +2 m/s^2 held on the forward axis for 3 s -> none (the running mean eats it)",
@@ -175,6 +202,73 @@ check("a NaN sample or a short tuple is ignored, never raises",
d.feed(T0, (0.0, -G, float("nan")), (70, 60)) is False and d.feed(T0, (0.0,), (70, 60)) is False)
check("command_direction: (70, 60) +1, (-70, -60) -1, (70, -70) 0, (0, 0) None, None None",
[bi.command_direction(c) for c in ((70, 60), (-70, -60), (70, -70), (0, 0), None)] == [1, -1, 0, None, None])
+check("contact_side: forward front, reversing rear, a pivot by the sign (-6 front, +6 rear); its stream bump / bump_rear",
+ [bi.contact_side(d, hp) for d, hp in ((1, -6.0), (-1, 6.0), (0, -6.0), (0, 6.0))] == ["front", "rear", "front", "rear"]
+ and (bi.contact_stream("front"), bi.contact_stream("rear")) == ("bump", "bump_rear"))
+
+# ── F. the sides: one debounce per side ──────────────────────────────────
+print("F. the sides: a rear contact is not a repeat of a front one; a kick within 0.1 s of a contact is its rebound")
+
+
+def run_cmds(samples, command_at):
+ """Feed a trace with the command each sample sees: command_at(t) -> pair;
+ -> (detector, [(t, hp, side)] of the contacts)."""
+ det = bi.ImuContactDetector()
+ hits = []
+ for ts, acc in samples:
+ if det.feed(ts, acc, command_at(ts - T0), command_age_s=0.1):
+ hits.append((round(ts - T0, 3), det.last_hp, det.last_contact["side"]))
+ return det, hits
+
+
+wedge = trace(pulses=[PULSE, (1.9, 0.06, +6.0)])
+_, wedge_hits = run_cmds(wedge, lambda t: (70, 60) if t < 1.7 else (-70, -60))
+check("(j) a front contact at 1.5 s, the escape reversing from 1.7 s, a kick behind at 1.9 s (0.4 s later, inside "
+ "the 0.7 s debounce) -> two contacts: front then rear",
+ [(t, side) for t, _, side in wedge_hits] == [(1.5, "front"), (1.9, "rear")], f"{wedge_hits}")
+_, same_hits = run_cmds(wedge, lambda t: (70, 60))
+check(" ... the same +6 kick with the command still forward -> no second contact (forward takes no kick)",
+ [(t, side) for t, _, side in same_hits] == [(1.5, "front")], f"{same_hits}")
+check("the rebound window: REBOUND_S 0.1 s, the detector's default",
+ bi.REBOUND_S == 0.1 and bi.ImuContactDetector().rebound_s == 0.1)
+_, corner_hits = run_cmds(trace(pulses=[PULSE, (1.68, 0.06, +6.0)]), lambda t: (70, -70))
+check("(j2) a rover wedging into a corner during ONE pivot (70, -70): -6 at 1.5 s, +6 at 1.68 s (0.18 s later, the "
+ "same command) -> two contacts: front then rear (one debounce per side, past the rebound)",
+ [(t, side) for t, _, side in corner_hits] == [(1.5, "front"), (1.68, "rear")], f"{corner_hits}")
+_, corner_hits2 = run_cmds(trace(pulses=[PULSE, (1.9, 0.06, +6.0)]), lambda t: (70, -70))
+check(" ... the same pivot with the rear contact 0.4 s later -> two contacts as well",
+ [(t, side) for t, _, side in corner_hits2] == [(1.5, "front"), (1.9, "rear")], f"{corner_hits2}")
+rebound = trace(pulses=[PULSE, (1.56, 0.04, +6.0)])
+reb_det, reb_hits = run_cmds(rebound, lambda t: (70, -70))
+check("(k) a pivot (70, -70): -6 at 1.5 s then a +6 rebound at 1.56 s -> one contact, in front",
+ [(t, side) for t, _, side in reb_hits] == [(1.5, "front")], f"{reb_hits}")
+check(" ... the rebound is counted ONCE (8 samples past the threshold), behind, 0.06 s after the contact",
+ reb_det.rebounds == 1 and reb_det.last_rebound["side"] == "rear"
+ and abs(reb_det.last_rebound["after_s"] - 0.06) < 1e-6 and reb_det.last_rebound["hp"] >= 4.0,
+ f"{reb_det.rebounds} {reb_det.last_rebound}")
+ring_det, ring_hits = run_cmds(trace(pulses=[(1.5, 0.04, -6.0), (1.56, 0.03, +6.0)]),
+ lambda t: (70, 60) if t < 1.55 else (-30, -30))
+check("(k2) driving forward: -6 at 1.5 s, the telemetry flips to the escape's reverse at 1.55 s, +6 ringing at "
+ "1.56 s -> one contact, in front: the ringing is the rebound whatever the command, never a rear contact",
+ [(t, side) for t, _, side in ring_hits] == [(1.5, "front")] and ring_det.rebounds == 1,
+ f"{ring_hits} {ring_det.rebounds}")
+long_det, long_hits = run_cmds(trace(pulses=[(1.5, 0.02, -6.0), (1.58, 0.04, +6.0)]), lambda t: (70, -70))
+check(" ... a rebound that starts 0.08 s after the contact and runs past 0.1 s stays the rebound while it is past "
+ "the threshold -> one contact, one rebound",
+ [(t, side) for t, _, side in long_hits] == [(1.5, "front")] and long_det.rebounds == 1,
+ f"{long_hits} {long_det.rebounds}")
+_, flip_hits = run_cmds(trace(pulses=[PULSE, (2.0, 0.06, +6.0)]), lambda t: (70, -70) if t < 1.8 else (-70, -60))
+check(" ... a +6 kick 0.5 s later once the command reverses (-70, -60) -> a new contact, behind",
+ [(t, side) for t, _, side in flip_hits] == [(1.5, "front"), (2.0, "rear")], f"{flip_hits}")
+_, again_hits = run_cmds(trace(pulses=[PULSE, (1.9, 0.06, -6.0)]), lambda t: (70, 60) if t < 1.7 else (70, -70))
+check(" ... a second deceleration in front 0.4 s later under another command -> none (the same side debounces)",
+ [(t, side) for t, _, side in again_hits] == [(1.5, "front")], f"{again_hits}")
+_, takeoff_hits = run_cmds(trace(pulses=[PULSE, (1.8, 0.10, -6.0)]), lambda t: (70, 60))
+check("(l) the escape taking off in reverse (-6 at 1.8 s) while the telemetry still says forward -> no second contact",
+ [(t, side) for t, _, side in takeoff_hits] == [(1.5, "front")], f"{takeoff_hits}")
+_, late_hits = run_cmds(trace(pulses=[PULSE, (2.3, 0.06, -6.0)]), lambda t: (70, 60))
+check(" ... a second deceleration 0.8 s later (past the debounce) -> a second contact in front",
+ [(t, side) for t, _, side in late_hits] == [(1.5, "front"), (2.3, "front")], f"{late_hits}")
# ── B. the knobs ─────────────────────────────────────────────────────────
print("B. the knobs: MOSS_BUMP_ACCEL, MOSS_BUMP_AXIS, MOSS_BUMP_DEBOUNCE_S, MOSS_IMU_LOG")
@@ -243,6 +337,11 @@ class BumpOut:
self.sent.append((type(msg), bool(getattr(msg, "data", False))))
+class RefusingOut(BumpOut):
+ def publish(self, msg):
+ raise RuntimeError("transport closed")
+
+
def imu_msgs(samples, gyro=(0.01, -0.02, 0.03)):
return [Imu(angular_velocity=Vector3(*gyro), linear_acceleration=Vector3(*acc),
frame_id="camera_accel_optical_frame", ts=ts) for ts, acc in samples]
@@ -258,14 +357,17 @@ MODULES = []
def module(wired=True, **kwargs):
m = bi.BumpImu(**kwargs)
m.bump = BumpOut(wired)
+ m.bump_rear = BumpOut(wired)
MODULES.append(m)
return m
-check("streams: In imu (Imu), In base_telemetry (String), Out bump (Bool), nothing else",
- set(bi.BumpImu.__annotations__) == {"imu", "base_telemetry", "bump"}, f"{sorted(bi.BumpImu.__annotations__)}")
+check("streams: In imu (Imu), In base_telemetry (String), Out bump and Out bump_rear (Bool), nothing else",
+ set(bi.BumpImu.__annotations__) == {"imu", "base_telemetry", "bump", "bump_rear"}, f"{sorted(bi.BumpImu.__annotations__)}")
import moss_dimos.blueprints as _bp_mod # noqa: E402
-check("bump carries the SAME Bool class as the coordinator's (one stream type on the bus)", bi.Bool is _bp_mod.Bool)
+import moss_dimos.recovering_planner as _rp_mod # noqa: E402
+check("bump and bump_rear carry the SAME Bool class as the coordinator's and the planner's (one stream type on the bus)",
+ bi.Bool is _bp_mod.Bool is _rp_mod.Bool)
check("no async handle_imu: every sample goes through a plain subscription (the async handler keeps only the latest)",
not hasattr(bi.BumpImu, "handle_imu") and callable(getattr(bi.BumpImu, "on_imu", None)))
check("start/stop keep @rpc", {"start", "stop"} <= set(bi.BumpImu.rpcs))
@@ -280,18 +382,55 @@ check("(h) base_telemetry target_pct [70, 60], firmware age 0.1 s -> command (70
cmd == (70, 60) and 0.09 <= age < 0.5, f"{cmd} {age:.3f}")
results = [mod.on_imu(m) for m in imu_msgs(trace(pulses=[PULSE]))]
check(" ... then the pulse sample by sample -> on_imu True exactly once", results.count(True) == 1, f"{results.count(True)}")
-check(" ... one Bool(True) published on bump", mod.bump.sent == [(Bool, True)], f"{mod.bump.sent}")
+check(" ... one Bool(True) published on bump, nothing on bump_rear", mod.bump.sent == [(Bool, True)]
+ and mod.bump_rear.sent == [], f"{mod.bump.sent} {mod.bump_rear.sent}")
contact_lines = [ln for ln in spy.lines if ln.startswith("IMU contact:")]
-check(" ... the log line: 'IMU contact: forward -6.0 m/s^2 (threshold 4.0) while commanded L=+70% R=+60%'",
- contact_lines == ["IMU contact: forward -6.0 m/s^2 (threshold 4.0) while commanded L=+70% R=+60%"], f"{contact_lines}")
+check(" ... the log line: 'IMU contact: forward -6.0 m/s^2 (threshold 4.0) while commanded L=+70% R=+60%, "
+ "front contact -> bump'",
+ contact_lines == ["IMU contact: forward -6.0 m/s^2 (threshold 4.0) while commanded L=+70% R=+60%, "
+ "front contact -> bump"], f"{contact_lines}")
check(" ... and the IMU is announced alive at its first sample (gravity on y)",
any(ln.startswith("MOSS IMU: first sample") and "-9.8" in ln for ln in spy.lines), f"{spy.lines[:3]}")
check("every other line of the module starts with 'MOSS IMU:' (the launcher's log filter keeps MOSS lines), "
"none of them with 'IMU contact'",
all(ln.startswith("MOSS IMU:") for ln in spy.lines if not ln.startswith("IMU contact:"))
and len([ln for ln in spy.lines if ln.startswith("IMU contact")]) == 1, f"{spy.lines}")
-check("contact_line on a reverse contact: 'forward +5.2 ... L=-70% R=-60%'",
- bi.contact_line(5.24, 4.0, (-70, -60)) == "IMU contact: forward +5.2 m/s^2 (threshold 4.0) while commanded L=-70% R=-60%")
+check("contact_line on a reverse contact: 'forward +5.2 ... L=-70% R=-60%, rear contact -> bump_rear'",
+ bi.contact_line(5.24, 4.0, (-70, -60), "rear")
+ == "IMU contact: forward +5.2 m/s^2 (threshold 4.0) while commanded L=-70% R=-60%, rear contact -> bump_rear")
+spy.lines.clear()
+backing = module()
+asyncio.run(backing.handle_base_telemetry(telemetry((-70, -60))))
+back_results = [backing.on_imu(m) for m in imu_msgs(trace(pulses=[(1.5, 0.06, +6.0)]))]
+check("(m) reversing (-70, -60) then a +6 kick sample by sample -> one Bool(True) on bump_rear, nothing on bump",
+ back_results.count(True) == 1 and backing.bump_rear.sent == [(Bool, True)] and backing.bump.sent == [],
+ f"{backing.bump_rear.sent} {backing.bump.sent}")
+check(" ... its line ends 'rear contact -> bump_rear'",
+ [ln for ln in spy.lines if ln.startswith("IMU contact:")]
+ == ["IMU contact: forward +6.0 m/s^2 (threshold 4.0) while commanded L=-70% R=-60%, rear contact -> bump_rear"],
+ f"{[ln for ln in spy.lines if ln.startswith('IMU contact:')]}")
+spy.lines.clear()
+pivoting = module()
+asyncio.run(pivoting.handle_base_telemetry(telemetry((70, -70))))
+pivot_results = [pivoting.on_imu(m) for m in imu_msgs(trace(pulses=[PULSE, (1.56, 0.04, +6.0)]))]
+rebound_lines = [ln for ln in spy.lines if "rebound" in ln]
+check("(m2) a pivot (70, -70), a contact and its rebound 0.06 s later -> one Bool(True) on bump, nothing on bump_rear",
+ pivot_results.count(True) == 1 and pivoting.bump.sent == [(Bool, True)] and pivoting.bump_rear.sent == [],
+ f"{pivoting.bump.sent} {pivoting.bump_rear.sent}")
+check(" ... and ONE line for the rebound, never silent, not an 'IMU contact' line: 'MOSS IMU: forward +6.x m/s^2 "
+ "while commanded L=+70% R=-70%, 0.06 s after the front contact: taken as its rebound, not published on bump_rear'",
+ len(rebound_lines) == 1 and rebound_lines[0].startswith("MOSS IMU: forward +6.")
+ and rebound_lines[0].endswith("while commanded L=+70% R=-70%, 0.06 s after the front contact: taken as its "
+ "rebound, not published on bump_rear")
+ and len([ln for ln in spy.lines if ln.startswith("IMU contact")]) == 1, f"{spy.lines}")
+spy.lines.clear()
+refused = module()
+refused.bump = RefusingOut()
+asyncio.run(refused.handle_base_telemetry(telemetry((70, 60))))
+refused_results = [refused.on_imu(m) for m in imu_msgs(trace(pulses=[PULSE]))]
+check("a refused publish: the contact is logged first, then one warning naming bump, nothing raised",
+ refused_results.count(True) == 1 and any(ln.startswith("IMU contact:") for ln in spy.lines)
+ and len([ln for ln in spy.lines if "not published on bump " in ln]) == 1, f"{spy.lines}")
idle = module()
asyncio.run(idle.handle_base_telemetry(telemetry((0, 0))))
@@ -313,7 +452,8 @@ check("bad telemetry lines (not JSON, no pair, a list) leave the last good comma
unwired = module(wired=False)
asyncio.run(unwired.handle_base_telemetry(telemetry((70, 60))))
check("an unwired bump (no transport): the contact is detected and logged, nothing published, nothing raised",
- [unwired.on_imu(m) for m in imu_msgs(trace(pulses=[PULSE]))].count(True) == 1 and unwired.bump.sent == [])
+ [unwired.on_imu(m) for m in imu_msgs(trace(pulses=[PULSE]))].count(True) == 1 and unwired.bump.sent == []
+ and unwired.bump_rear.sent == [])
weird = module()
check("a sample with NaN or a message without fields -> False, never raises",
weird.on_imu(Imu(linear_acceleration=Vector3(float("nan"), 0.0, 0.0), ts=T0)) is False
@@ -554,6 +694,182 @@ check("a start that fails ('failed to set power state'): the sensor is closed ag
ri.logger = real_ri_logger
del sys.modules["pyrealsense2"]
+# ── G. the watchdog: a contact sensor never goes quiet unnoticed ─────────
+print("G. ImuWatchdog: quiet, back, the status line (fake clock), then the module's own thread")
+GRAVITY = (0.0, -G, 0.0)
+
+
+def feed_watch(wd, t0, t1, hz=200.0):
+ """Samples arriving at hz from t0 (included) to t1 (excluded), on the fake clock."""
+ n = int(round((t1 - t0) * hz))
+ for i in range(n):
+ wd.sample(t0 + i / hz, GRAVITY)
+
+
+def tick_until(wd, t0, t1, step=0.1, contacts=0):
+ """tick() every step from t0 (included) to t1 (included): -> [(t, level, text)]."""
+ out, n = [], int(round((t1 - t0) / step))
+ for i in range(n + 1):
+ t = round(t0 + i * step, 6)
+ out += [(t, lvl, txt) for lvl, txt in wd.tick(t, contacts)]
+ return out
+
+
+wd = bi.ImuWatchdog()
+check("defaults: quiet after 1 s, at most one 'no sample' line per 5 s, rate over 1 s, a status line every 10 s",
+ (wd.quiet_s, wd.repeat_s, wd.rate_window_s, wd.status_s) == (1.0, 5.0, 1.0, 10.0)
+ and (bi.QUIET_S, bi.STATUS_PERIOD_S) == (1.0, 10.0))
+check("tick() before start() says nothing", wd.tick(5.0) == [])
+wd.start(0.0)
+waiting = tick_until(wd, 0.1, 10.0)
+check("(n) no sample at all: nothing for 10 s (the camera takes seconds to start), then ONE status line at warning: "
+ "'waiting, no sample 10 s after start - IMU contacts and gyro prior OFF'",
+ [(t, lvl) for t, lvl, _ in waiting] == [(10.0, "warning")]
+ and waiting[0][2] == "MOSS IMU: status waiting, no sample 10 s after start - IMU contacts and gyro prior OFF",
+ f"{waiting}")
+feed_watch(wd, 10.0, 20.0)
+alive = wd.tick(20.0, 3)
+check("200 Hz for 10 s -> the status line at info: 'alive, 2000 samples in 10 s (200 Hz)', gravity on y, 3 contacts, "
+ "0 quiet spells",
+ alive == [("info", "MOSS IMU: status alive, 2000 samples in 10 s (200 Hz), mean accel (+0.00, -9.81, +0.00) m/s^2, "
+ "3 contact(s) so far, 0 quiet spell(s)")], f"{alive}")
+lost = tick_until(wd, 20.1, 23.0)
+check("(o) the samples stop (last at 19.995 s): exactly one line, at warning, at 21.0 s: "
+ "'MOSS IMU: no sample for 1 s - IMU contacts and gyro prior OFF'",
+ lost == [(21.0, "warning", "MOSS IMU: no sample for 1 s - IMU contacts and gyro prior OFF")], f"{lost}")
+check(" ... the watchdog is quiet and counts one spell", wd.quiet is True and wd.spells == 1)
+feed_watch(wd, 23.2, 25.0)
+back = tick_until(wd, 23.1, 25.0)
+check("(p) samples again from 23.2 s -> one line once the resumed stream ran 1 s: "
+ "'MOSS IMU: samples back (200 Hz) after 3.2 s quiet'",
+ back == [(24.2, "info", "MOSS IMU: samples back (200 Hz) after 3.2 s quiet")], f"{back}")
+check(" ... no longer quiet", wd.quiet is False)
+feed_watch(wd, 25.0, 30.0)
+status2 = wd.tick(30.0, 3)
+check(" ... the next status line counts the samples of its 10 s (1360) and 1 quiet spell",
+ len(status2) == 1 and status2[0][0] == "info" and "1360 samples in 10 s" in status2[0][1]
+ and status2[0][1].endswith("3 contact(s) so far, 1 quiet spell(s)"), f"{status2}")
+quiet_status = tick_until(wd, 30.1, 40.0, contacts=3)
+check("a status line while quiet: warning 'status QUIET, no sample for 10 s - IMU contacts and gyro prior OFF'",
+ [ln for ln in quiet_status if "status" in ln[2]]
+ == [(40.0, "warning", "MOSS IMU: status QUIET, no sample for 10 s - IMU contacts and gyro prior OFF, "
+ "3 contact(s) so far, 2 quiet spell(s)")],
+ f"{[ln for ln in quiet_status if 'status' in ln[2]]}")
+
+flap = bi.ImuWatchdog()
+flap.start(0.0)
+lines = []
+t = 0.0
+for k in range(6): # 1.5 s of samples, then 2 s of silence, six times
+ feed_watch(flap, t, t + 1.5)
+ lines += [ln for ln in tick_until(flap, t + 0.1, t + 3.5) if "status" not in ln[2]]
+ t += 3.5
+lost_lines = [ln for ln in lines if "no sample" in ln[2]]
+back_lines = [ln for ln in lines if "samples back" in ln[2]]
+check("(q) a stream dropping out every 3.5 s, six times -> six spells, a 'no sample' line at most once per 5 s: "
+ "spells 1, 3 and 5 said, spells 2, 4 and 6 counted",
+ flap.spells == 6 and [round(ln[0], 1) for ln in lost_lines] == [2.5, 9.5, 16.5], f"{flap.spells} {lost_lines}")
+check(" ... the next line counts the spell it did not say: '(1 more quiet spell(s) since the last line)'",
+ len(lost_lines) == 3 and lost_lines[0][2].endswith("gyro prior OFF")
+ and all(ln[2].endswith("OFF (1 more quiet spell(s) since the last line)") for ln in lost_lines[1:]),
+ f"{lost_lines}")
+check(" ... and a spell that was not said gets no 'back' line either (3 back lines, after spells 1, 3, 5)",
+ len(back_lines) == 3, f"{back_lines}")
+
+burst = bi.ImuWatchdog()
+burst.start(0.0)
+feed_watch(burst, 0.0, 2.0)
+burst_lines = tick_until(burst, 0.1, 4.0)
+feed_watch(burst, 4.0, 4.4) # a 0.4 s burst, then nothing again
+burst_lines += tick_until(burst, 4.1, 11.9)
+check("(s) samples to 2 s, then a 0.4 s burst at 4.0 s and nothing more: the 'no sample' line at 3.0 s, and NO "
+ "'samples back' line (the burst stopped before its rate window ended): the watchdog stays quiet, one spell",
+ [(t, txt) for t, _, txt in burst_lines if "status" not in txt]
+ == [(3.0, "MOSS IMU: no sample for 1 s - IMU contacts and gyro prior OFF")]
+ and burst.quiet is True and burst.spells == 1, f"{burst_lines} {burst.quiet} {burst.spells}")
+check(" ... the status line at 10 s says QUIET, no sample for 6 s",
+ [txt for _, _, txt in burst_lines if "status" in txt]
+ == ["MOSS IMU: status QUIET, no sample for 6 s - IMU contacts and gyro prior OFF, 0 contact(s) so far, "
+ "1 quiet spell(s)"], f"{burst_lines}")
+feed_watch(burst, 12.0, 14.0)
+resumed = tick_until(burst, 12.0, 14.0)
+check(" ... a stream that resumes for good at 12.0 s -> 'samples back (200 Hz) after 10.0 s quiet' at 13.0 s, "
+ "the same spell",
+ resumed == [(13.0, "info", "MOSS IMU: samples back (200 Hz) after 10.0 s quiet")]
+ and burst.quiet is False and burst.spells == 1, f"{resumed}")
+
+spy.lines.clear()
+bi.logger = spy
+wmod = module()
+asyncio.run(wmod.handle_base_telemetry(telemetry((70, 60))))
+for m in imu_msgs(trace(duration_s=0.5)):
+ wmod.on_imu(m)
+check("on_imu feeds the watchdog with the arrival time (monotonic), whatever the sample's own stamp",
+ wmod.watchdog._last is not None and abs(wmod.watchdog._last - time.monotonic()) < 1.0, f"{wmod.watchdog._last}")
+wmod.watchdog.start(time.monotonic())
+said = wmod.watch(time.monotonic() + 1.5)
+check("watch(): the lines go through the module's logger and come back as texts",
+ said == ["MOSS IMU: no sample for 1 s - IMU contacts and gyro prior OFF"]
+ and "MOSS IMU: no sample for 1 s - IMU contacts and gyro prior OFF" in spy.lines, f"{said} {spy.lines[-3:]}")
+
+
+class BrokenWatchdog(bi.ImuWatchdog):
+ def tick(self, now, contacts=0):
+ raise ZeroDivisionError("float division by zero")
+
+
+spy.lines.clear()
+wmod._watchdog = BrokenWatchdog()
+check("a look that fails: watch() returns [], never raises, ONE warning for two failures",
+ wmod.watch(1.0) == [] and wmod.watch(2.0) == []
+ and len([ln for ln in spy.lines if "watchdog look failed" in ln]) == 1, f"{spy.lines}")
+
+spy.lines.clear()
+live = module()
+for m in imu_msgs(trace(duration_s=0.2)):
+ live.on_imu(m)
+live._start_watchdog()
+thread = live._watch_thread
+for m in imu_msgs(trace(duration_s=0.2)):
+ live.on_imu(m)
+t_stop = time.monotonic()
+seen = None
+while time.monotonic() - t_stop < 3.0:
+ if any("no sample for 1 s" in ln for ln in spy.lines):
+ seen = time.monotonic() - t_stop
+ break
+ time.sleep(0.02)
+check("(r) the module's own thread, on the real clock: the samples stop -> the 'no sample' line within 1.0 to 1.3 s",
+ seen is not None and 1.0 <= seen <= 1.3 and thread is not None and thread.name == "moss-imu-watchdog",
+ f"{seen} {spy.lines}")
+live.stop()
+check(" ... stop() ends the thread", thread is not None and not thread.is_alive() and live._watch_thread is None)
+
+# start() itself starts the watchdog: the dimOS base start is stood in for and
+# the imu stream stubbed, so the module's own start() runs bare.
+spy.lines.clear()
+base_start = next((k, vars(k)["start"]) for k in bi.BumpImu.__mro__[1:] if "start" in vars(k))
+started = module()
+subscribed = []
+started.imu = types.SimpleNamespace(subscribe=lambda cb: subscribed.append(cb) or (lambda: None))
+setattr(base_start[0], "start", lambda self: None)
+try:
+ started.start()
+ start_thread = started._watch_thread
+ alive_after_start = start_thread is not None and start_thread.is_alive()
+finally:
+ setattr(base_start[0], "start", base_start[1])
+check("(t) BumpImu.start() subscribes on_imu and starts the watchdog thread 'moss-imu-watchdog'",
+ alive_after_start and start_thread.name == "moss-imu-watchdog"
+ and len(subscribed) == 1 and subscribed[0] == started.on_imu, f"{start_thread} {subscribed}")
+check(" ... its start line says the watchdog: 'watchdog: quiet after 1 s, status every 10 s'",
+ any(ln.startswith("MOSS IMU: contacts on") and ln.endswith("watchdog: quiet after 1 s, status every 10 s")
+ for ln in spy.lines), f"{spy.lines}")
+started.stop()
+check(" ... stop() ends that thread", start_thread is not None and not start_thread.is_alive()
+ and started._watch_thread is None)
+bi.logger = real_logger
+
MODULES.clear()
import shutil # noqa: E402
shutil.rmtree(tmp, ignore_errors=True)
diff --git a/benches/bench_costmap2d_cold.py b/benches/bench_costmap2d_cold.py
index 257a3c5..5b9b64c 100644
--- a/benches/bench_costmap2d_cold.py
+++ b/benches/bench_costmap2d_cold.py
@@ -1,57 +1,101 @@
"""Cold bench for costmap2d: the scored grid and MossCostMap, written as numbers.
-Known input -> known output, in metres and cells:
- 1. a table leg at (1.0, 0) seen from two places -> occupied; the floor along
+Known input -> known output, in metres, cells and seconds:
+ 1. the doctrine defaults: without the environment a wall needs two places
+ 10 cm apart (OCCUPIED_AT 2, NEW_VIEWPOINT_M 0.10), a grid goes out every
+ 2 revolutions, the contact wall is off, a camera hit protects its cell
+ for 3 s and the camera rays carve between 0.013 and 0.060 m up;
+ MOSS_OCCUPIED_AT, MOSS_NEW_VIEWPOINT_M and MOSS_CONTACT_WALL still move them
+ 2. a table leg at (1.0, 0) seen from two places -> occupied; the floor along
the ray (0.3..0.9 m) -> free; nothing else touched
- 2. a ramp: 50 hits from the SAME spot -> never occupied (one viewpoint)
- 3. a chair: occupied, then lidar revolutions see through it -> free
- 4. a ceiling of reinforcement: 30 viewpoints -> score 10, then bounded
+ 3. a ramp: 50 hits from the SAME spot -> never occupied (one viewpoint)
+ 4. a chair: occupied, then lidar revolutions see through it -> free
+ 5. a ceiling of reinforcement: 30 viewpoints -> score 10, then bounded
unlearning (never a wall for a day)
- 5. a parked rover: a wall raised to HIT_CAP by 12 viewpoints, then
+ 6. a parked rover: a wall raised to HIT_CAP by 12 viewpoints, then
revolutions from the spot it is parked on and 0.5 m of creep -> still
- HIT_CAP, still occupancy 100 (the viewpoint rule caps the increase, it
- never lowers a score)
- 6. body_clear: the MOSS footprint (0.20 x 0.16 m half extents) clears 63
+ HIT_CAP, still occupancy 100, on the lidar layer and on the camera layer
+ (the viewpoint rule caps the increase, it never lowers a score)
+ 7. body_clear: the MOSS footprint (0.20 x 0.16 m half extents) clears 63
cells at the origin; MOSS_BODY_CLEAR_M moves it at call time
- 7. the lidar tag: a float32 point at exactly the profile's lidar height
+ 8. the lidar tag: a float32 point at exactly the profile's lidar height
(0.20 m) is a lidar return; 0.37 m, 0.2005 m and the floor are not;
- MOSS_LIDAR_HEIGHT_M moves the tag at call time; a camera obstacle maps
- after two viewpoints (even when the second lands on a carving
- revolution), survives the rays while the camera sees it, and is freed
- by the camera's floor samples once taken away
- 8. the mission gate: 20 revolutions and a passer-by on a PARKED rover ->
+ MOSS_LIDAR_HEIGHT_M moves the tag at call time; through MossCostMap a
+ camera obstacle maps after the gate's frame and two viewpoints, never
+ from one parked spot, the lidar's rays through its cell take nothing
+ from it, and the camera's floor frees it once the 3 s window is over
+ 9. the mission gate: 20 revolutions and a passer-by on a PARKED rover ->
0 cells; 6 cm of displacement -> the map opens and the room's wall at
2.5 m is mapped; "exploration complete" and "exploration stopped" ->
- the map keeps writing (lidar is MOSS's only obstacle source)
- 9. the explore order: parked revolutions write nothing until explore_cmd,
+ the map keeps writing
+ 10. the explore order: parked revolutions write nothing until explore_cmd,
then the same parked revolutions carve free floor up to the wall
- 10. what goes out: one OccupancyGrid every 5 revolutions on global_costmap,
+ 11. Clear map: a fresh grid on the pose, the mission gate as it was
+ 12. the contact wall (MOSS_CONTACT_WALL): off, a contact on `bump` writes
+ nothing and says so; on, only a contact felt while driving straight
+ forward marks the band 0.02-0.20 m beyond the body's front as a wall (a
+ pivot, a reverse, a contact while standing still, 10 cm driven while
+ turning 20 deg: nothing; 10 cm with 6 deg of turn: written); the camera's
+ floor frees the band
+ 13. what goes out: one OccupancyGrid every 5 revolutions on global_costmap,
0.05 m cells, frame `world`, the wall at 2.5 m = 100 in the grid
- 11. the mission signals land on the topics the rest of the stack uses: one
+ 14. the mission signals land on the topics the rest of the stack uses: one
Bool class for explore_cmd / explore_done / stop_explore_cmd across
costmap2d, explorer2 and tools/explore_ctl.py
- 12. the cost of one revolution (400 rays, 0.5-12 m) stays under 40 ms
- 13. a camera obstacle seen from ONE parked spot for 20 frames, with the
- lidar rays crossing its cell, stays below OCCUPIED_AT (never a wall); a
- camera cell at FREE_FLOOR hit 5 frames from one spot stays below 0
- 14. a passer-by's legs: a camera wall (two viewpoints) in the camera's view,
- no longer seen, under lidar rays through its cell -> freed within 10
- revolutions (2 at score 2, 10 at score 6)
- 15. a camera wall the camera KEEPS seeing from the same spot, rays carving
- its cell every other revolution -> a wall for all 20 revolutions
- 16. the knobs, read at import: MOSS_HIT_CAP=4 unlearns a leg seen from 6
+ 15. the cost: one lidar revolution (400 rays, 0.5-12 m) and one camera floor
+ frame (its floor samples and rays) each stay under 40 ms
+ 16. a camera obstacle seen from ONE parked spot for 20 frames, with the
+ lidar's rays and the camera's rays crossing its cell, stays below
+ OCCUPIED_AT (never a wall); a camera cell at FREE_FLOOR seen 5 frames
+ from one spot stays below 0
+ 17. a passer-by's legs: a camera wall no longer seen is untouched by the
+ camera's rays for 3 s, then freed by them (1 look at score 2, 5 at 6)
+ 18. a camera wall the camera KEEPS seeing from one spot, its own floor rays
+ and the lidar's crossing its cell, stays a wall for 20 frames (4 s, past
+ the window: every frame stamps it again)
+ 19. the knobs, read at import: MOSS_HIT_CAP=4 unlearns a leg seen from 6
viewpoints in fewer revolutions than 10; MOSS_FREE_FLOOR=-1 lets long-seen
floor become a wall in fewer hits; MOSS_RAY_MAX_M=6 carves a leg at 4.5 m
that the default 4 m never reaches; bad values fall back or clamp
- 17. the rays carve the camera layer only inside the camera's view (87 deg,
- 3 m): a table top (320 cells, a wall from 3 viewpoints) stays a wall
- while the rover turns its back on it and for 20 revolutions facing away,
- rays through every cell; legs at 35 deg off the heading are freed while
- in view, kept while behind the rover; MossCostMap passes the odom heading
- 18. body_clear resets camera_wall: a camera wall the body drives over is
- FREE_FLOOR and unflagged, and same-spot camera hits never make it a wall
- again (10 frames right away, and 10 after new viewpoints lift it to
- OCCUPIED_AT - 1)
+ 20. the camera layer is carved only where the camera looks: a table top
+ (320 cells, a wall from 3 viewpoints) stays a wall while the rover turns
+ its back on it and 20 revolutions of lidar rays cross every cell; facing
+ it with the table gone, the camera's floor frees it; legs 35 deg off the
+ heading are freed while in view, kept while behind the rover, through
+ MossCostMap and the odom heading
+ 21. body_clear frees the camera layer under the body, and same-spot camera
+ frames never make the cell a wall again
+ 22. the thin leg: armed at 2, 25 floor samples on its own cell inside 3 s ->
+ still 2 and a wall, the lidar layer untouched; past the window ->
+ forgotten; through MossCostMap a parked rover seeing the leg and the
+ floor on its cell for 10 frames keeps the wall (without the window the
+ first floor frame frees it)
+ 23. moving things: a vacuum rolling past one cell per frame leaves no wall and
+ no 3 s stamp (only the cells the gate keeps are stamped); a standing box
+ maps; ONE depth frame carried by 5 revolutions while the rover drives
+ 12 cm takes no hit (the same 5 revolutions taken as 5 frames would hit);
+ the same bytes on a cloud stamped 0.4 s later are that frame again, 1.5 s
+ later a new look (by the clouds' own stamps); a revolution without camera
+ points clears the gate
+ 24. the camera's rays: a floor point 3 m ahead carves cells 0.75 to 2.50 m
+ (36 cells: from 20 % to 82 % of the ray), not its endpoint; a ghost
+ crossed low dies, a ray climbing over it (22 cm up) leaves it, a cell hit
+ 2 s ago is protected; camera rays never touch the lidar layer and lidar
+ rays never touch the camera layer; through MossCostMap, a 5 cm threshold
+ beyond a ghost at score 5: one depth frame carried by 3 revolutions takes
+ one miss, a new frame a second; in a frame, hits go before rays, so a
+ thin leg the frame confirms is not carved by a low ray of that frame
+ 25. the rays start at the camera, 0.156 m ahead of base_link and turned by
+ the heading: a floor sample 3 m ahead carves from 0.75 m, not from the
+ 0.60 m a base-cast ray would, and a ghost at 0.675 m survives the look
+ that a base-cast ray would erase; through MossCostMap, a stale ghost at
+ 1.5 m dies to a floor sample 3 m ahead, facing +x and facing +y; a 4 cm
+ cable 0.95 m ahead leaves a ghost at 0.475 m that a base-cast ray would
+ carve; under MOSS_CAMERA_XYZ_M="0.156 0.05 0.15" the origin moves 5 cm
+ sideways and the band and height move together (the floor ray still
+ carves 0.75 to 2.50 m)
+ 26. the carve band follows the camera height: 0.013-0.060 m at 0.075 m,
+ the original 0.10-0.45 m at 0.56 m
Needs dimOS (the messages are real).
@@ -76,9 +120,9 @@ import numpy as np # noqa: E402
# MOSS's own numbers, whatever the shell exported
for _var in [v for v in os.environ if v.startswith("MOSS_")]:
del os.environ[_var]
-# the checks below pin the cautious rules (a wall from two places, viewpoints 10 cm apart, one grid per
-# five revolutions); the module defaults are the fast ones (first sighting counts, 5 cm, every two),
-# checked in a subprocess by test_the_fast_defaults
+# the checks below pin the doctrine (a wall from two places 10 cm apart: the module defaults too,
+# checked in a subprocess by test_the_doctrine_defaults) and one grid per five revolutions (the
+# module publishes every two; test_what_goes_out counts five)
os.environ["MOSS_OCCUPIED_AT"] = "2"
os.environ["MOSS_NEW_VIEWPOINT_M"] = "0.10"
os.environ["MOSS_PUBLISH_EVERY"] = "5"
@@ -86,26 +130,28 @@ os.environ["MOSS_PUBLISH_EVERY"] = "5"
from dimos_lcm.std_msgs import Bool # noqa: E402
from moss_dimos import costmap2d as cmod # noqa: E402
-from moss_dimos.robot_profile import current as _current_profile
+from moss_dimos.robot_profile import current as _current_profile # noqa: E402
from moss_dimos.costmap2d import ( # noqa: E402
- FREE_FLOOR, HIT_CAP, MISSION_START_M, OCCUPIED_AT, PUBLISH_EVERY, RAY_EVERY, RESOLUTION_M,
- CONTACT_BAND_M, MossCostMap, ScoredGrid, lidar_returns,
+ CONTACT_BAND_M, FREE_FLOOR, HIT_CAP, LOW_HIT_PROTECT_S, MISSION_START_M, OCCUPIED_AT, PUBLISH_EVERY,
+ RAY_EVERY, RESOLUTION_M, MossCostMap, ScoredGrid, camera_xy, carve_z_band, lidar_returns,
)
from moss_dimos.robot_profile import MOSS # noqa: E402
ROOT = Path(__file__).resolve().parent.parent
LEG = np.array([[1.0, 0.0]])
LIDAR_Z = MOSS.lidar_height_m # 0.20 m: where lidar_odometry lifts every return
+CAM_X, CAM_Y, CAM_Z = MOSS.camera_xyz_base_m # 0.156, 0, 0.075 m: the depth camera on the nose
def fresh() -> ScoredGrid:
return ScoredGrid(span_m=6.0)
-def _cloud(pts: np.ndarray):
- """A world cloud on the wire, float32 like the real one."""
+def _cloud(pts: np.ndarray, ts: float | None = None):
+ """A world cloud on the wire, float32 like the real one, stamped now (or `ts`, wall seconds)."""
from dimos.msgs.sensor_msgs.PointCloud2 import PointCloud2
- return PointCloud2.from_numpy(pts.astype(np.float32), frame_id="world", timestamp=time.time())
+ return PointCloud2.from_numpy(pts.astype(np.float32), frame_id="world",
+ timestamp=time.time() if ts is None else ts)
def _lidar_cloud(xy: np.ndarray, z: float = LIDAR_Z) -> np.ndarray:
@@ -153,6 +199,22 @@ ANG = np.radians(np.arange(0, 360, 2.0))
ROOM = np.stack([2.5 * np.cos(ANG), 2.5 * np.sin(ANG)], 1) # a 5 m round room
+def _frame(pts: np.ndarray, k: int) -> np.ndarray:
+ """Depth frame number k of the same scene: the points moved by k x 0.1 mm
+ in x, as depth noise moves them, so every frame's bytes differ from the
+ last one's (MossCostMap takes a cloud carrying the previous frame's
+ points, byte for byte, as that frame again). Points sit at cell centres,
+ so 2 mm of noise never changes their cell."""
+ return np.asarray(pts, dtype=np.float64) + np.array([1e-4 * k] + [0.0] * (np.shape(pts)[1] - 1))
+
+
+def _armed(g: ScoredGrid, xy: np.ndarray, t: float, viewpoints=((0.0, 0.0), (0.0, 0.15))) -> None:
+ """A camera wall: the gate's first frame, then one frame per viewpoint, all at time t."""
+ g.camera_obstacles(_frame(xy, 0), viewpoints[0], now=t)
+ for k, vp in enumerate(viewpoints, start=1):
+ g.camera_obstacles(_frame(xy, k), vp, now=t)
+
+
def test_leg_needs_two_viewpoints_and_ray_is_free() -> None:
"""An obstacle is REAL when seen from two viewpoints: a passer-by hammered
from one parked spot must never become a wall."""
@@ -214,7 +276,7 @@ def test_parked_rover_never_erases_an_established_wall() -> None:
"""The viewpoint rule caps the INCREASE, not the value: a hit from a spot
the cell already knows adds nothing and takes nothing away. Capping the
value would collapse a wall built by 12 approach viewpoints to 1 on the
- next revolution taken from a parked rover."""
+ next revolution taken from a parked rover. Same rule on the camera layer."""
g = fresh()
for i in range(12): # approach: 12 viewpoints, 0.15 m apart
g.lidar_revolution(LEG, (0.0, 0.15 * i))
@@ -230,8 +292,20 @@ def test_parked_rover_never_erases_an_established_wall() -> None:
g.lidar_revolution(LEG, (0.02 * k, parked[1]))
assert g.value_at(1.0, 0.0) == 100, f"wall published FREE while creeping, revolution {k}"
assert g.lidar[gy[0], gx[0]] == HIT_CAP
+ # the camera layer holds an obstacle the same way
+ c = fresh()
+ box = np.array([[1.025, 0.025]])
+ t0 = 500.0
+ c.camera_obstacles(_frame(box, 0), (0.0, 0.0), now=t0) # the moving-object gate's first frame
+ for i in range(12):
+ c.camera_obstacles(_frame(box, i + 1), (0.0, 0.15 * i), now=t0 + 0.2 * (i + 1))
+ bx, by = c.cell(box[:, 0], box[:, 1])
+ assert c.camera[by[0], bx[0]] == HIT_CAP and c.value_at(*box[0]) == 100, "12 viewpoints -> a camera wall"
+ c.camera_obstacles(_frame(box, 13), (0.0, 0.15 * 11), now=t0 + 2.8)
+ assert c.camera[by[0], bx[0]] == HIT_CAP, "the camera layer is capped the same way"
+ assert c.value_at(*box[0]) == 100, "a camera obstacle survives a parked rover too"
print(f" wall at 1.0 m, 12 viewpoints -> score {HIT_CAP}; parked + 1 revolution and 0.5 m of "
- f"creep -> still {HIT_CAP}, occupancy 100")
+ f"creep -> still {HIT_CAP}, occupancy 100 (lidar and camera layers)")
def test_body_clear_is_the_moss_footprint() -> None:
@@ -268,8 +342,9 @@ def test_body_clear_is_the_moss_footprint() -> None:
def test_the_lidar_tag_is_one_exact_height() -> None:
"""lidar_odometry lifts every return to exactly lidar_height_m; anything
else on the cloud (a depth camera's points, at their true height) is not
- a lidar return, even millimetres away from the scan plane - it is a camera
- obstacle, hit without a ray."""
+ a lidar return, even millimetres away from the scan plane: it is a camera
+ obstacle, on the camera layer, behind the moving-object gate, and only
+ the camera can take it back."""
cloud = np.array([[1.0, 0.0, np.float32(0.20)], [2.0, 0.0, 0.2005], [3.0, 0.0, 0.37],
[4.0, 0.0, 0.0]], dtype=np.float32).astype(np.float64)
assert list(lidar_returns(cloud)) == [True, False, False, False], list(lidar_returns(cloud))
@@ -280,49 +355,56 @@ def test_the_lidar_tag_is_one_exact_height() -> None:
del os.environ["MOSS_LIDAR_HEIGHT_M"]
assert moved == [False, False, True, False], moved
# through the module: one cloud with 180 wall returns at 0.20 m and a
- # point 2 mm above the scan plane - only the wall is mapped
+ # point 2 mm above the scan plane - the wall on the lidar layer, the point
+ # on the camera layer
m = costmap()
asyncio.run(m.handle_odom(_odom(0.0, 0.0)))
asyncio.run(m.handle_explore_cmd(Bool(data=True)))
- stray = np.array([[1.0, 0.5, LIDAR_Z + 0.002]])
- for y in (0.0, 0.15):
+ stray = np.array([[1.025, 0.525, LIDAR_Z + 0.002]])
+ for k, y in enumerate((0.0, 0.0, 0.15)): # the gate's first frame, then two viewpoints
asyncio.run(m.handle_odom(_odom(0.0, y)))
- asyncio.run(m.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), stray]))))
+ asyncio.run(m.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), _frame(stray, k)]))))
assert m._grid.value_at(2.5, 0.0) == 100, "the wall is mapped"
- assert m._grid.value_at(1.0, 0.5) == 100, "the off-plane point is a camera obstacle: mapped after two viewpoints"
+ sx, sy = m._grid.cell(stray[:, 0], stray[:, 1])
+ assert m._grid.value_at(1.025, 0.525) == 100 and m._grid.camera[sy[0], sx[0]] == 2, \
+ "the off-plane point is a camera obstacle: mapped after the gate's frame and two viewpoints"
+ assert m._grid.lidar[sy[0], sx[0]] <= 0, "the lidar layer never claimed a cell the lidar never returned"
n = m._revolutions
asyncio.run(m.handle_lidar(_cloud(stray)))
assert m._revolutions == n, "a cloud with no lidar return is not a revolution"
- # a camera obstacle from ONE viewpoint stays below OCCUPIED_AT, like a lidar hit
+ # a shoe: from ONE parked viewpoint it stays below OCCUPIED_AT, like a lidar hit
m2 = costmap()
asyncio.run(m2.handle_odom(_odom(0.0, 0.0)))
asyncio.run(m2.handle_explore_cmd(Bool(data=True)))
- low = np.array([[1.5, -0.4, 0.05]]) # a shoe: 5 cm high, invisible to the scan plane
- for _ in range(3):
- asyncio.run(m2.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), low]))))
- assert m2._grid.value_at(1.5, -0.4) != 100, "one parked viewpoint never makes a camera obstacle a wall"
+ low = np.array([[1.525, -0.375, 0.05]]) # 5 cm high, invisible to the scan plane
+ for k in range(3): # the gate's first frame, then two frames from one spot
+ asyncio.run(m2.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), _frame(low, k)]))))
+ assert m2._grid.value_at(1.525, -0.375) != 100, "one parked viewpoint never makes a camera obstacle a wall"
asyncio.run(m2.handle_odom(_odom(0.0, 0.15)))
- asyncio.run(m2.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), low]))))
- assert m2._grid.value_at(1.5, -0.4) == 100, "the second viewpoint makes the shoe a wall"
- # the lidar sees the wall behind the shoe: its rays cross the shoe's cell every other
- # revolution, and the shoe the camera still sees survives them
- for _ in range(6):
- asyncio.run(m2.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), low]))))
- assert m2._grid.value_at(1.5, -0.4) == 100, "the shoe the camera still sees survives the rays"
- # the same rays without the shoe in the cloud do cross its cell: two revolutions free it
+ asyncio.run(m2.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), _frame(low, 3)]))))
+ assert m2._grid.value_at(1.525, -0.375) == 100, "the second viewpoint makes the shoe a wall"
+ # the lidar sees the room's wall behind the shoe: its rays cross the shoe's
+ # cell (its own layer goes below 0 there) and take nothing from the camera layer
probe = copy.deepcopy(m2._grid)
- for _ in range(2):
- probe.lidar_revolution(ROOM, (0.0, 0.15), yaw=0.0)
- assert probe.value_at(1.5, -0.4) != 100, "the rays cross the shoe's cell (so the survival above is the camera's)"
- # the shoe is taken away: the camera sees bare floor there -> freed after two floor samples
- floor = np.array([[1.5, -0.4, 0.0], [1.52, -0.42, 0.0]])
+ lx, ly = probe.cell(low[:, 0], low[:, 1])
+ before = int(probe.camera[ly[0], lx[0]])
+ for _ in range(4):
+ probe.lidar_revolution(ROOM, (0.0, 0.15))
+ assert probe.lidar[ly[0], lx[0]] < 0, "the lidar's rays do cross the shoe's cell"
+ assert int(probe.camera[ly[0], lx[0]]) == before == 2, "and leave the shoe on the camera layer"
+ # the shoe is taken away: the camera sees bare floor on its cell. Inside
+ # the 3 s window that floor is the thin leg's and changes nothing; past it,
+ # two floor samples free the cell
+ floor = np.array([[1.525, -0.375, 0.0], [1.535, -0.385, 0.0]])
+ asyncio.run(m2.handle_camera_floor(_cloud(floor)))
+ assert m2._grid.value_at(1.525, -0.375) == 100, "a floor sample inside the 3 s window changes nothing"
+ m2._grid._last_low_hit[:] = time.monotonic() - LOW_HIT_PROTECT_S - 1.0 # nothing confirmed the shoe since
for _ in range(2):
asyncio.run(m2.handle_camera_floor(_cloud(floor)))
- assert m2._grid.value_at(1.5, -0.4) != 100, "bare floor seen by the camera frees the shoe's cell"
- # the camera point carves no ray: the floor between the rover and the shoe is not marked free by it
+ assert m2._grid.value_at(1.525, -0.375) != 100, "bare floor seen by the camera frees the shoe's cell"
print(" float32 0.20 m -> lidar; 0.2005 / 0.37 / 0.0 -> camera; MOSS_LIDAR_HEIGHT_M=0.37 moves the tag; "
- "a camera obstacle maps after two viewpoints (a 5 cm shoe), never from one parked spot; "
- "it survives the rays while seen, and the camera's floor frees it")
+ "a camera obstacle maps after the gate's frame and two viewpoints (a 5 cm shoe), never from one parked "
+ "spot; the lidar's rays through it take nothing; the camera's floor frees it after the 3 s window")
def test_the_map_writes_only_during_the_mission() -> None:
@@ -451,34 +533,103 @@ def test_clear_map_starts_a_fresh_grid_and_keeps_the_gate() -> None:
print(" clear_map_cmd: fresh grid centred on the pose, open mission stays open, unstarted one stays shut, False ignored")
+# the cockpit's decision feed reads a written contact by this line (tools/moss_cockpit.py)
+_N = r"([-+]?\d+(?:\.\d+)?)"
+CONTACT_LINE = r"costmap: contact at \(" + _N + r", " + _N + r"\) heading " + _N + r" deg: (\d+) cells ahead marked as a wall"
+
+
+def _drive(m: MossCostMap, poses) -> None:
+ for x, y, yaw in poses:
+ asyncio.run(m.handle_odom(_odom(x, y, yaw)))
+
+
def test_a_contact_marks_the_band_ahead_as_a_wall() -> None:
- """The stall guard fired: the band just beyond the body's front becomes a wall
- at once, in the heading direction, and the planner's occupancy shows it;
- the body itself and the floor behind stay clear; a bump before any pose or
- with the mission shut does nothing; the camera's bare floor frees it."""
- m = costmap()
- asyncio.run(m.handle_bump(Bool(data=True))) # no pose yet
- assert m._grid is None
- asyncio.run(m.handle_odom(_odom(0.0, 0.0, yaw=0.0)))
- asyncio.run(m.handle_bump(Bool(data=True))) # mission not started: nothing written
- assert m._grid.value_at(0.35, 0.0) != 100
- asyncio.run(m.handle_explore_cmd(Bool(data=True)))
- asyncio.run(m.handle_bump(Bool(data=True)))
+ """Contacts are reflexes: with MOSS_CONTACT_WALL off (the default) a
+ contact on `bump` writes nothing, and says so. On, a contact felt while
+ driving straight forward makes the band just beyond the body's front a
+ wall at once, in the heading direction; a contact while standing still
+ (an explorer's back-off), pivoting or reversing writes nothing; the body
+ itself and the floor behind stay clear; a bump before any pose or with the
+ mission shut does nothing; the camera's bare floor frees the band."""
+ import re
+ spy, real = LogSpy(), cmod.logger
+ cmod.logger = spy
hx, _ = _current_profile().body_clear_m
- assert m._grid.value_at(hx + 0.10, 0.0) == 100, "the band ahead is a wall"
- assert m._grid.value_at(hx + 0.10, 0.12) == 100 and m._grid.value_at(hx + 0.10, -0.12) == 100, "across the body's width"
- assert m._grid.value_at(0.0, 0.0) != 100 and m._grid.value_at(-0.3, 0.0) != 100, "the body and the floor behind are not"
- assert m._grid.value_at(hx + 0.40, 0.0) != 100, "the wall is a short band, not a ray"
- # heading east, the band lies east; turned north, a new contact marks north
- asyncio.run(m.handle_odom(_odom(0.0, 0.0, yaw=math.pi / 2)))
- asyncio.run(m.handle_bump(Bool(data=True)))
- assert m._grid.value_at(0.0, hx + 0.10) == 100, "a contact while heading north marks the band north"
- floor = np.array([[hx + 0.10, 0.0, 0.0], [hx + 0.12, 0.02, 0.0]])
- for _ in range(3):
- asyncio.run(m.handle_camera_floor(_cloud(floor)))
- assert m._grid.value_at(hx + 0.10, 0.0) != 100, "bare floor seen by the camera frees the contact mark"
- asyncio.run(m.handle_bump(Bool(data=False)))
- print(f" contact: the band {CONTACT_BAND_M[0]:.2f}-{CONTACT_BAND_M[1]:.2f} m beyond the body is a wall at once, in the heading, freed by seen floor")
+ try:
+ assert cmod.CONTACT_WALL is False, "the contact wall is off by default"
+ off = costmap()
+ _drive(off, [(0.0, 0.0, 0.0)])
+ asyncio.run(off.handle_explore_cmd(Bool(data=True)))
+ _drive(off, [(0.05, 0.0, 0.0), (0.10, 0.0, 0.0)])
+ asyncio.run(off.handle_bump(Bool(data=True)))
+ assert off._grid.value_at(0.10 + hx + 0.125, 0.025) != 100, "knob off: a forward contact writes no wall"
+ assert spy.lines[-1].endswith("not written: contacts are reflexes, only the lidar and the camera write the "
+ "map (MOSS_CONTACT_WALL=1 writes a forward contact)"), spy.lines[-1]
+ assert not re.search(CONTACT_LINE, spy.lines[-1]), "a contact not written never reads as a wall in the feed"
+
+ cmod.CONTACT_WALL = True
+ m = costmap()
+ asyncio.run(m.handle_bump(Bool(data=True))) # no pose yet
+ assert m._grid is None
+ _drive(m, [(0.0, 0.0, 0.0)])
+ asyncio.run(m.handle_bump(Bool(data=True))) # mission not started: nothing written
+ assert m._grid.value_at(hx + 0.125, 0.025) != 100
+ asyncio.run(m.handle_explore_cmd(Bool(data=True)))
+ asyncio.run(m.handle_bump(Bool(data=True))) # standing still: an explorer's back-off
+ assert m._grid.value_at(hx + 0.125, 0.025) != 100, "a contact while standing still writes nothing"
+ assert "not driving straight forward (+0 cm along the heading, +0 deg in the last 0.5 s)" in spy.lines[-1], \
+ spy.lines[-1]
+ _drive(m, [(0.05, 0.0, 0.0), (0.10, 0.0, 0.0)]) # 10 cm straight ahead
+ asyncio.run(m.handle_bump(Bool(data=True)))
+ x0 = 0.10
+ assert m._grid.value_at(x0 + hx + 0.125, 0.025) == 100, "a forward contact: the band ahead is a wall"
+ assert m._grid.value_at(x0 + hx + 0.125, 0.125) == 100 and m._grid.value_at(x0 + hx + 0.125, -0.125) == 100, \
+ "across the body's width"
+ assert m._grid.value_at(x0, 0.025) != 100 and m._grid.value_at(x0 - 0.3, 0.025) != 100, \
+ "the body and the floor behind are not"
+ assert m._grid.value_at(x0 + hx + 0.425, 0.025) != 100, "the wall is a short band, not a ray"
+ written = re.search(CONTACT_LINE, spy.lines[-1])
+ assert written and written.group(1, 2, 3) == ("+0.10", "+0.00", "+0"), spy.lines[-1]
+ cells = int(written.group(4))
+
+ verdicts = {}
+ for label, poses in (("pivot", [(0.0, 0.0, 0.0), (0.0, 0.0, math.radians(30.0))]),
+ ("reverse", [(0.10, 0.0, 0.0), (0.05, 0.0, 0.0), (0.0, 0.0, 0.0)]),
+ ("arc", [(0.0, 0.0, 0.0), (0.05, 0.0, math.radians(3.0)), (0.10, 0.005, math.radians(6.0))]),
+ # 10 cm along the heading (more than the 3 cm) while turning 20 deg: the turn refuses it
+ ("sharp arc", [(0.0, 0.0, 0.0), (0.05, 0.004, math.radians(10.0)),
+ (0.10, 0.017, math.radians(20.0))])):
+ c = costmap()
+ _drive(c, poses[:1])
+ asyncio.run(c.handle_explore_cmd(Bool(data=True)))
+ _drive(c, poses[1:])
+ asyncio.run(c.handle_bump(Bool(data=True)))
+ x, y, yaw = poses[-1]
+ ahead = (x + math.cos(yaw) * (hx + 0.11), y + math.sin(yaw) * (hx + 0.11))
+ verdicts[label] = c._grid.value_at(*ahead) == 100
+ assert verdicts == {"pivot": False, "reverse": False, "arc": True, "sharp arc": False}, verdicts
+ assert "not driving straight forward (+10 cm along the heading, +20 deg in the last 0.5 s)" in spy.lines[-1], \
+ spy.lines[-1]
+ # heading north, driving north: the band lies north
+ n = costmap()
+ _drive(n, [(0.0, 0.0, math.pi / 2)])
+ asyncio.run(n.handle_explore_cmd(Bool(data=True)))
+ _drive(n, [(0.0, 0.05, math.pi / 2), (0.0, 0.10, math.pi / 2)])
+ asyncio.run(n.handle_bump(Bool(data=True)))
+ assert n._grid.value_at(0.025, 0.10 + hx + 0.125) == 100, "a contact while driving north marks the band north"
+ # the camera's bare floor frees the band (a contact mark is no camera hit: no 3 s window)
+ floor = np.array([[x0 + hx + 0.125, 0.025, 0.0], [x0 + hx + 0.13, 0.03, 0.0]])
+ for _ in range(3):
+ asyncio.run(m.handle_camera_floor(_cloud(floor)))
+ assert m._grid.value_at(x0 + hx + 0.125, 0.025) != 100, "bare floor seen by the camera frees the contact mark"
+ asyncio.run(m.handle_bump(Bool(data=False)))
+ finally:
+ cmod.CONTACT_WALL = False
+ cmod.logger = real
+ print(f" MOSS_CONTACT_WALL off: a forward contact writes nothing, said in the log; on: driving 10 cm straight "
+ f"ahead -> the band {CONTACT_BAND_M[0]:.2f}-{CONTACT_BAND_M[1]:.2f} m beyond the body is a wall ({cells} "
+ f"cells); standing still, pivoting 30 deg, reversing or 10 cm while turning 20 deg -> nothing; a 6 deg arc -> "
+ "written; freed by seen floor")
def test_what_goes_out_on_global_costmap() -> None:
@@ -561,18 +712,28 @@ def test_revolution_cost() -> None:
g = ScoredGrid(span_m=24.0)
t0 = time.perf_counter()
for i in range(10):
- g.lidar_revolution(hits, (0.01 * i, 0.0), yaw=0.0)
+ g.lidar_revolution(hits, (0.01 * i, 0.0))
ms = (time.perf_counter() - t0) / 10 * 1000
assert ms < 40, ms
- print(f" one revolution (400 rays, 0.5-12 m, carving every other one, camera layer in view) = {ms:.0f} ms")
-
+ # one depth frame's bare floor: every cell centre the camera sees within 3 m, its samples and its rays
+ floor = _floor_view((0.0, 0.0), 0.0)
+ t0 = time.perf_counter()
+ for i in range(10):
+ g.camera_floor(floor[:, :2], now=1000.0 + i)
+ g.camera_rays(floor, camera_xy((0.01 * i, 0.0), 0.0), now=1000.0 + i)
+ floor_ms = (time.perf_counter() - t0) / 10 * 1000
+ assert floor_ms < 40, floor_ms
+ print(f" one revolution (400 rays, 0.5-12 m, carving every other one) = {ms:.1f} ms; one camera floor frame "
+ f"({len(floor)} samples and their rays) = {floor_ms:.1f} ms")
-# --- the camera layer forgets: lidar rays carve it, the camera holds what it sees ---
+# --- the camera layer: only the camera writes it, only the camera clears it ---
SHOE = np.array([[1.525, 0.025]]) # a camera obstacle at a cell centre, 1.5 m ahead
WALL = np.column_stack([np.full(101, 3.0), np.linspace(-0.5, 0.5, 101)]) # lidar returns behind it, 3 m away
SPOT_B = (0.0, 0.025) # the last viewpoint: it looks straight through the shoe
HEADING = 0.0 # the rover faces +x: the shoe is straight ahead, in the camera's view
+BEYOND = np.array([[3.025, 0.025, 0.0]]) # bare floor 3 m ahead: from the camera at (0.156, 0.025), 7.5 cm up,
+ # its ray crosses the shoe's cell 4 cm up (inside the carve band)
def _camera_score(g: ScoredGrid, xy: np.ndarray) -> int:
@@ -584,9 +745,7 @@ def _in_view(xy: np.ndarray, rover_xy, yaw: float, margin_deg: float = 1.0) -> n
"""What a D455 on MOSS's nose sees of these points, written here apart
from costmap2d: within 87 / 2 degrees (+ margin_deg) of the heading, seen
from the camera (the profile's camera_xyz_base_m ahead of base_link),
- and within 3 m of the rover. The default margin makes this camera see a
- degree wider than the carve, so every cell the carve reaches inside the
- view is one the camera reports."""
+ and within 3 m of the rover."""
cx, cy = MOSS.camera_xyz_base_m[0], MOSS.camera_xyz_base_m[1]
cam = (rover_xy[0] + math.cos(yaw) * cx - math.sin(yaw) * cy, rover_xy[1] + math.sin(yaw) * cx + math.cos(yaw) * cy)
off = np.degrees(np.arctan2(xy[:, 1] - cam[1], xy[:, 0] - cam[0])) - math.degrees(yaw)
@@ -594,119 +753,137 @@ def _in_view(xy: np.ndarray, rover_xy, yaw: float, margin_deg: float = 1.0) -> n
return (np.abs(off) <= 87.0 / 2 + margin_deg) & (np.hypot(xy[:, 0] - rover_xy[0], xy[:, 1] - rover_xy[1]) <= 3.0)
-def _revolution(g: ScoredGrid, from_xy, camera_xy=None, spare=True) -> None:
- """One revolution as MossCostMap.handle_lidar runs it: lidar rays and hits
- (sparing the cells the camera sees in it), then the camera's hits.
- spare=False lets the carve land on the camera's cells first, as it does
- when the camera's points fall in a cell only every other revolution."""
- g.lidar_revolution(WALL, from_xy, camera_xy=camera_xy if spare else None, yaw=HEADING)
- if camera_xy is not None:
- g.camera_hits(camera_xy, from_xy)
+_FX, _FY = np.meshgrid(np.arange(-5.975, 6.0, 0.05), np.arange(-5.975, 6.0, 0.05))
+_CENTRES = np.column_stack([_FX.ravel(), _FY.ravel()]) # cell centres around the origin, 0.05 m apart
+
+
+def _floor_view(rover_xy, yaw: float) -> np.ndarray:
+ """One depth frame's bare floor, written here apart from lidar_odometry:
+ every cell centre the camera sees from this pose (87 degrees, 3 m), z = 0."""
+ pts = _CENTRES[_in_view(_CENTRES, rover_xy, yaw, margin_deg=0.0)]
+ return np.column_stack([pts, np.zeros(len(pts))])
-def _camera_wall(viewpoints: int = 2) -> ScoredGrid:
- """The shoe made a wall by the camera from `viewpoints` spots 0.15 m apart, ending at SPOT_B."""
+def _camera_wall(viewpoints: int = 2, t: float = 100.0) -> ScoredGrid:
+ """The shoe made a wall by the camera from `viewpoints` spots 0.15 m apart, ending at SPOT_B, stamped at t."""
g = fresh()
- for k in range(viewpoints - 1, -1, -1):
- g.camera_hits(SHOE, (0.0, SPOT_B[1] + 0.15 * k))
+ _armed(g, SHOE, t, viewpoints=[(0.0, SPOT_B[1] + 0.15 * k) for k in range(viewpoints - 1, -1, -1)])
assert g.value_at(*SHOE[0]) == 100 and _camera_score(g, SHOE) == min(viewpoints, HIT_CAP)
return g
def test_camera_one_viewpoint_never_becomes_a_wall() -> None:
- """A camera hit from the same viewpoint adds 1 while the cell is at 0 or
- above and below its ceiling (the camera must hold what it sees against
- the rays), but one spot never makes a wall: 20 frames from one parked
- spot, the rays crossing the cell, stay below OCCUPIED_AT. Below 0 it adds
- nothing: a camera cell held free at FREE_FLOOR, hit 5 frames from one
- spot, stays below 0 and needs OCCUPIED_AT - FREE_FLOOR viewpoints."""
+ """One spot never makes a wall on the camera layer either: 20 depth
+ frames from one parked spot stay below OCCUPIED_AT, with or without the
+ lidar's rays and the camera's own floor rays crossing the cell. Below 0
+ nothing changes that: a camera cell held free at FREE_FLOOR, seen 5 frames
+ from one spot, stays below 0 and needs OCCUPIED_AT - FREE_FLOOR viewpoints."""
+ cam = camera_xy(SPOT_B, HEADING)
traces = {}
- for spare in (True, False):
+ for rays in (False, True):
g = fresh()
trace = []
- for _ in range(20):
- _revolution(g, SPOT_B, SHOE, spare=spare)
+ for k in range(20):
+ t = 100.0 + 0.2 * k
+ g.camera_obstacles(_frame(SHOE, k), SPOT_B, now=t)
+ if rays:
+ g.lidar_revolution(WALL, SPOT_B)
+ g.camera_rays(BEYOND, cam, now=t)
trace.append(_camera_score(g, SHOE))
- assert g.value_at(*SHOE[0]) != 100, f"a wall from one spot after {len(trace)} frames (spare={spare})"
- assert max(trace) == OCCUPIED_AT - 1, trace
- traces[spare] = trace
+ assert g.value_at(*SHOE[0]) != 100, f"a wall from one spot after {len(trace)} frames (rays={rays})"
+ traces[rays] = trace
+ assert max(traces[False]) == OCCUPIED_AT - 1 and max(traces[True]) <= OCCUPIED_AT - 1, traces
# long-seen free floor on the camera layer: the camera's floor samples took it to FREE_FLOOR
g = fresh()
for _ in range(-FREE_FLOOR + 2):
- g.camera_floor(SHOE)
+ g.camera_floor(SHOE, now=50.0)
assert _camera_score(g, SHOE) == FREE_FLOOR, _camera_score(g, SHOE)
+ g.camera_obstacles(_frame(SHOE, 0), SPOT_B, now=100.0) # the gate's first frame
floor_trace = []
- for _ in range(5): # a phantom seen 5 frames from one parked spot
- g.camera_hits(SHOE, SPOT_B)
+ for k in range(1, 6): # a phantom seen 5 frames from one parked spot
+ g.camera_obstacles(_frame(SHOE, k), SPOT_B, now=100.0 + 0.2 * k)
floor_trace.append(_camera_score(g, SHOE))
- assert max(floor_trace) < 0, f"one spot lifted floor held free at {FREE_FLOOR} to {floor_trace}"
assert floor_trace == [FREE_FLOOR + 1] * 5, floor_trace
- k = 1 # SPOT_B was the first viewpoint
+ k = 1 # SPOT_B was the first viewpoint
while g.value_at(*SHOE[0]) != 100:
- g.camera_hits(SHOE, (0.0, SPOT_B[1] + 0.15 * k)); k += 1
+ g.camera_obstacles(_frame(SHOE, 10 + k), (0.0, SPOT_B[1] + 0.15 * k), now=102.0 + 0.2 * k); k += 1
assert k <= 20
assert k == OCCUPIED_AT - FREE_FLOOR, k
- print(f" 20 frames from one spot: camera score {sorted(set(traces[True]))} (OCCUPIED_AT {OCCUPIED_AT}); "
- f"rays landing first every other frame: {sorted(set(traces[False]))}; never a wall")
+ print(f" 20 frames from one spot: camera score {sorted(set(traces[False]))} (OCCUPIED_AT {OCCUPIED_AT}); "
+ f"with the lidar's and the camera's rays through it: {sorted(set(traces[True]))}; never a wall")
print(f" camera cell at FREE_FLOOR {FREE_FLOOR}, 5 frames from one spot: scores {floor_trace}; "
f"a wall after {k} viewpoints (as on the lidar layer)")
def test_camera_wall_no_longer_seen_is_carved_free() -> None:
- """The passer-by's legs: a camera wall in the camera's view that the
- camera no longer sees, under lidar rays that pass through its cell, is
- freed (1 per RAY_EVERY revolutions)."""
+ """The passer-by's legs: a camera wall the camera no longer sees keeps
+ its score for LOW_HIT_PROTECT_S however many rays cross it, then the
+ camera's own rays through its cell at low height free it, one miss per
+ look; once forgotten, the same spot cannot raise it back to a wall."""
+ cam = camera_xy(SPOT_B, HEADING)
assert _in_view(SHOE, SPOT_B, HEADING, margin_deg=-1.0).all(), "the shoe is well inside the camera's view"
counts = {}
for viewpoints in (2, 6):
- g = _camera_wall(viewpoints)
+ g = _camera_wall(viewpoints, t=100.0)
+ for k in range(1, 11): # 2 s of looks through it, inside the window
+ g.camera_rays(BEYOND, cam, now=100.0 + 0.2 * k)
+ assert _camera_score(g, SHOE) == viewpoints, "the 3 s window: a cell hit 2 s ago is not carved"
n = 0
while g.value_at(*SHOE[0]) == 100:
- _revolution(g, SPOT_B); n += 1
- assert n <= 10, f"a camera wall from {viewpoints} viewpoints still stands after 10 revolutions"
+ n += 1
+ g.camera_rays(BEYOND, cam, now=100.0 + LOW_HIT_PROTECT_S + 0.2 * n)
+ assert n <= 10, f"a camera wall from {viewpoints} viewpoints still stands after 10 looks"
m = n
while _camera_score(g, SHOE) > 0:
- _revolution(g, SPOT_B); m += 1
- assert m <= 40
- gx, gy = g.cell(SHOE[:, 0], SHOE[:, 1])
- assert not g.camera_wall[gy[0], gx[0]], "carved back to 0: one spot no longer holds it"
+ m += 1
+ g.camera_rays(BEYOND, cam, now=100.0 + LOW_HIT_PROTECT_S + 0.2 * m)
+ assert m <= 20
counts[viewpoints] = (n, m)
- assert counts[2][0] <= 2 and counts[6][0] <= 10, counts
- # once forgotten, the same spot cannot raise it back to a wall: it needs two viewpoints again
- g = _camera_wall(2)
+ assert counts == {2: (1, 2), 6: (5, 6)}, counts
+ g = _camera_wall(2, t=100.0)
+ t = 100.0 + LOW_HIT_PROTECT_S
while _camera_score(g, SHOE) > 0:
- _revolution(g, SPOT_B)
- for _ in range(10):
- _revolution(g, SPOT_B, SHOE)
+ t += 0.2
+ g.camera_rays(BEYOND, cam, now=t)
+ for k in range(10):
+ t += 0.2
+ g.camera_obstacles(_frame(SHOE, 20 + k), SPOT_B, now=t)
assert g.value_at(*SHOE[0]) != 100, "forgotten, then seen again from the same spot: not a wall"
- print(f" camera wall no longer seen: 2 viewpoints -> free after {counts[2][0]} revolutions (score 0 after "
- f"{counts[2][1]}); 6 viewpoints -> free after {counts[6][0]} (score 0 after {counts[6][1]}); "
- f"seen again from the same spot afterwards -> not a wall")
+ print(f" camera wall no longer seen: 10 looks through it inside {LOW_HIT_PROTECT_S:.0f} s -> untouched; then "
+ f"2 viewpoints -> free after {counts[2][0]} look (score 0 after {counts[2][1]}); 6 viewpoints -> free after "
+ f"{counts[6][0]} (score 0 after {counts[6][1]}); seen again from the same spot afterwards -> not a wall")
def test_camera_wall_still_seen_survives_the_rays() -> None:
- """The shoe the camera keeps seeing: the rays take 1 every RAY_EVERY
- revolutions, the camera's same-viewpoint hit puts it back every
- revolution, the wall holds. Both orders are checked: the module's (the
- camera's cells spared by the carve) and the carve landing first."""
- carves = 0
- for spare in (True, False):
- g = _camera_wall(2)
- dips = 0
- for k in range(20):
- before = _camera_score(g, SHOE)
- g.lidar_revolution(WALL, SPOT_B, camera_xy=SHOE if spare else None, yaw=HEADING)
- dips += _camera_score(g, SHOE) < before
- g.camera_hits(SHOE, SPOT_B)
- assert g.value_at(*SHOE[0]) == 100, f"the wall the camera still sees fell at revolution {k + 1} (spare={spare})"
- if spare:
- assert dips == 0, f"the carve touched a cell the camera saw in the same revolution ({dips} times)"
- else:
- assert dips == 20 // RAY_EVERY, f"the rays reached the cell {dips} times, expected {20 // RAY_EVERY}"
- carves = dips
- print(f" camera wall kept in view from one spot: a wall for 20/20 revolutions, spared by the carve; "
- f"with the carve landing first ({carves} carves through it) the same-viewpoint hit holds it at "
- f"{OCCUPIED_AT}")
+ """The shoe the camera keeps seeing from one spot, 20 frames (4 s, past
+ the 3 s window): every frame stamps its cell again, so the camera's own
+ floor rays through it, the floor sampled beside it on its own cell and
+ the lidar's rays take nothing; it stays a wall at the score two
+ viewpoints gave it. Stop seeing it, and the same looks free it once the
+ window is over."""
+ g = _camera_wall(2, t=100.0)
+ cam = camera_xy(SPOT_B, HEADING)
+ dips = 0
+ for k in range(20):
+ t = 100.0 + 0.2 * (k + 1)
+ before = _camera_score(g, SHOE)
+ g.camera_obstacles(_frame(SHOE, 10 + k), SPOT_B, now=t)
+ g.camera_rays(BEYOND, cam, now=t)
+ g.camera_floor(SHOE + [0.02, 0.0], now=t) # the floor beside it, on its own cell
+ g.lidar_revolution(WALL, SPOT_B)
+ dips += _camera_score(g, SHOE) < before
+ assert g.value_at(*SHOE[0]) == 100, f"the wall the camera still sees fell at frame {k + 1}"
+ assert dips == 0 and _camera_score(g, SHOE) == 2, (dips, _camera_score(g, SHOE))
+ t_last = 100.0 + 0.2 * 20 # the last frame's stamp
+ looks = 0
+ while g.value_at(*SHOE[0]) == 100: # unseen now: a look every 0.25 s
+ looks += 1
+ g.camera_rays(BEYOND, cam, now=t_last + 0.25 * looks)
+ assert looks <= 30
+ assert looks == round(LOW_HIT_PROTECT_S / 0.25), f"freed at look {looks}: the first one 3 s after the last frame"
+ print(f" camera wall kept in view from one spot: a wall for 20/20 frames (4 s) under its own floor rays, "
+ f"the floor beside it and the lidar's rays; unseen afterwards -> free at look {looks}, "
+ f"{0.25 * looks:.2f} s after the last frame")
def _reload(**env):
@@ -788,59 +965,72 @@ def test_the_knobs_are_read_at_import() -> None:
f"MOSS_FREE_FLOOR 2 -> {odd[('MOSS_FREE_FLOOR', '2')]}, MOSS_RAY_MAX_M -1 -> {odd[('MOSS_RAY_MAX_M', '-1')]}")
-# --- the carve stays in the camera's view; body_clear forgets the camera_wall flag ---
+# --- the camera layer is carved only where the camera looks; body_clear frees it ---
_tx, _ty = np.meshgrid(np.arange(1.525, 2.30, 0.05), np.arange(-0.475, 0.50, 0.05))
TABLE = np.column_stack([_tx.ravel(), _ty.ravel()]) # a table top: 16 x 20 cell centres, 1.5-2.3 m ahead
RING = np.column_stack([2.9 * np.cos(np.radians(np.arange(0, 360, 0.5))),
2.9 * np.sin(np.radians(np.arange(0, 360, 0.5)))]) # lidar returns 2.9 m all around
-def _cells_scores(g: ScoredGrid, xy: np.ndarray) -> np.ndarray:
+def _cells_scores(g: ScoredGrid, xy: np.ndarray, layer: str = "camera") -> np.ndarray:
gx, gy = g.cell(xy[:, 0], xy[:, 1])
- return g.camera[gy, gx].astype(int)
+ return getattr(g, layer)[gy, gx].astype(int)
-def _turn(g: ScoredGrid, rover_xy, yaw: float, obstacle: np.ndarray | None) -> int:
- """One revolution as MossCostMap.handle_lidar runs it, with the camera
- seeing the part of `obstacle` inside its view. Returns how many points it saw."""
+def _turn(g: ScoredGrid, rover_xy, yaw: float, obstacle: np.ndarray | None, t: float, k: int) -> int:
+ """One revolution as MossCostMap.handle_lidar runs it, carrying a new depth
+ frame of the part of `obstacle` inside the camera's view (none: a frame
+ with no obstacle). Returns how many points the camera saw."""
seen = obstacle[_in_view(obstacle, rover_xy, yaw)] if obstacle is not None else np.zeros((0, 2))
- g.lidar_revolution(RING + rover_xy, rover_xy, camera_xy=seen if len(seen) else None, yaw=yaw)
- if len(seen):
- g.camera_hits(seen, rover_xy)
+ g.camera_obstacles(_frame(seen, k) if len(seen) else seen, rover_xy, now=t)
+ g.lidar_revolution(RING + rover_xy, rover_xy)
return len(seen)
+def _look(g: ScoredGrid, rover_xy, yaw: float, t: float) -> None:
+ """One depth frame of bare floor from this pose: its samples and its rays."""
+ floor = _floor_view(rover_xy, yaw)
+ g.camera_floor(floor[:, :2], now=t)
+ g.camera_rays(floor, camera_xy(rover_xy, yaw), now=t)
+
+
def test_the_carve_stays_in_the_cameras_view() -> None:
"""The camera layer holds what the scan plane misses (a table top, a
- chair seat, a shoe). A lidar ray passing under such a cell is no evidence
- against it unless the camera looks at the cell too, so the rays carve the
- camera layer only inside the camera's horizontal field of view.
+ chair seat, a shoe), and only the camera clears it, so it is carved only
+ where the camera looks.
Known input -> known output: a table top seen from 3 viewpoints (score 3
- on 320 cells); the rover pivots 180 degrees on the spot in 10 revolutions,
- then faces away for 20, the rays crossing every table cell -> all 320
- cells still score 3. Facing it again with the table gone -> free in
- RAY_EVERY * 2 revolutions."""
+ on 320 cells); the rover pivots 180 degrees on the spot in 10 frames, then
+ faces away for 20 (4 s, past the 3 s window), the lidar's rays crossing
+ every table cell -> all 320 cells still score 3. Facing it again with the
+ table gone, the camera's floor frees it."""
g = fresh()
+ t, k = 100.0, 0
+ g.camera_obstacles(_frame(TABLE, k), (-0.30, 0.0), now=t) # the gate's first frame
for x in (-0.30, -0.15, 0.0): # the approach, facing the table
- assert _turn(g, (x, 0.0), 0.0, TABLE) == len(TABLE)
+ t, k = t + 0.2, k + 1
+ assert _turn(g, (x, 0.0), 0.0, TABLE, t, k) == len(TABLE)
assert (_cells_scores(g, TABLE) == 3).all(), _cells_scores(g, TABLE)
seen_per_rev = []
- for k in range(1, 11): # pivot on the spot, 18 deg per revolution
- seen_per_rev.append(_turn(g, (0.0, 0.0), math.radians(18.0 * k), TABLE))
- assert (_cells_scores(g, TABLE) == 3).all(), f"table cells carved at yaw {18 * k} deg"
+ for j in range(1, 11): # pivot on the spot, 18 deg per frame
+ t, k = t + 0.2, k + 1
+ seen_per_rev.append(_turn(g, (0.0, 0.0), math.radians(18.0 * j), TABLE, t, k))
+ assert (_cells_scores(g, TABLE) == 3).all(), f"table cells carved at yaw {18 * j} deg"
assert seen_per_rev[0] == len(TABLE) and seen_per_rev[-1] == 0, seen_per_rev
for _ in range(20): # facing away: the table is behind the rover
- _turn(g, (0.0, 0.0), math.pi, TABLE)
+ t, k = t + 0.2, k + 1
+ _turn(g, (0.0, 0.0), math.pi, TABLE, t, k)
walls = int((_cells_scores(g, TABLE) >= OCCUPIED_AT).sum())
assert walls == len(TABLE) and (_cells_scores(g, TABLE) == 3).all(), walls
- # the same rays DO cross every table cell: facing it with the table taken away frees it
+ assert (_cells_scores(g, TABLE, "lidar") < 0).all(), "the lidar's rays did cross every table cell"
+ # facing it again with the table taken away: the camera's floor frees it
probe = copy.deepcopy(g)
gone = 0
while (_cells_scores(probe, TABLE) >= OCCUPIED_AT).any():
- _turn(probe, (0.0, 0.0), 0.0, None); gone += 1
- assert gone <= 10, int((_cells_scores(probe, TABLE) >= OCCUPIED_AT).sum())
- assert gone <= RAY_EVERY * 2, gone
+ gone += 1
+ _look(probe, (0.0, 0.0), 0.0, t + 0.2 * gone)
+ assert gone <= 5, int((_cells_scores(probe, TABLE) >= OCCUPIED_AT).sum())
+ assert gone <= 2, gone
# a passer-by's legs 35 deg off the heading, 1.2 m away: in the camera's view
legs = np.array([[1.025, 0.625]])
@@ -849,95 +1039,449 @@ def test_the_carve_stays_in_the_cameras_view() -> None:
freed = {}
for yaw, label in ((0.0, "facing"), (math.pi, "away")):
h = fresh()
- h.camera_hits(legs, (0.0, -0.15)); h.camera_hits(legs, (0.0, 0.0))
+ _armed(h, legs, 100.0, viewpoints=((0.0, -0.15), (0.0, 0.0)))
assert h.value_at(*legs[0]) == 100
n = 0
- while h.value_at(*legs[0]) == 100 and n < 20: # gone: the camera sees nothing there any more
- _turn(h, (0.0, 0.0), yaw, None); n += 1
+ while h.value_at(*legs[0]) == 100 and n < 20: # gone: the camera sees the floor in its view
+ n += 1
+ _look(h, (0.0, 0.0), yaw, 100.0 + LOW_HIT_PROTECT_S + 0.2 * n)
+ h.lidar_revolution(RING, (0.0, 0.0))
freed[label] = n if h.value_at(*legs[0]) != 100 else None
if label == "away":
kept = h
- assert freed["facing"] is not None and freed["facing"] <= 10 and freed["away"] is None, freed
+ assert freed["facing"] is not None and freed["facing"] <= 2 and freed["away"] is None, freed
m = 0
while kept.value_at(*legs[0]) == 100: # the rover turns back toward where they stood
- _turn(kept, (0.0, 0.0), 0.0, None); m += 1
- assert m <= 10
- # through the module: handle_lidar carves with the odom heading
+ m += 1
+ _look(kept, (0.0, 0.0), 0.0, 120.0 + 0.2 * m)
+ assert m <= 5
+ # through the module: handle_camera_floor casts from the camera turned by the odom heading
module = {}
for yaw in (math.pi, 0.0):
cm = costmap()
asyncio.run(cm.handle_odom(_odom(0.0, 0.0)))
asyncio.run(cm.handle_explore_cmd(Bool(data=True)))
- top = np.array([[1.5, 0.3, 0.72]]) # a table top corner: above the scan plane
- for y in (0.0, 0.15):
+ top = np.array([[1.525, 0.325, 0.72]]) # a table top corner: above the scan plane
+ for f, y in enumerate((0.0, 0.0, 0.15)): # the gate's frame, then two viewpoints
asyncio.run(cm.handle_odom(_odom(0.0, y)))
- asyncio.run(cm.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), top]))))
- assert cm._grid.value_at(1.5, 0.3) == 100, "two viewpoints make the table top a wall"
+ asyncio.run(cm.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), _frame(top, f)]))))
+ assert cm._grid.value_at(1.525, 0.325) == 100, "two viewpoints make the table top a wall"
asyncio.run(cm.handle_odom(_odom(0.0, 0.15, yaw)))
+ cm._grid._last_low_hit[:] = time.monotonic() - LOW_HIT_PROTECT_S - 1.0 # the camera stopped reporting it
n = 0
- while cm._grid.value_at(1.5, 0.3) == 100 and n < 10: # the camera no longer reports it
- asyncio.run(cm.handle_lidar(_cloud(_lidar_cloud(ROOM)))); n += 1
- module[round(math.degrees(yaw))] = n if cm._grid.value_at(1.5, 0.3) != 100 else None
- assert module[180] is None and module[0] is not None and module[0] <= RAY_EVERY, module
+ while cm._grid.value_at(1.525, 0.325) == 100 and n < 10:
+ n += 1
+ asyncio.run(cm.handle_camera_floor(_cloud(_floor_view((0.0, 0.15), yaw))))
+ asyncio.run(cm.handle_lidar(_cloud(_lidar_cloud(ROOM))))
+ module[round(math.degrees(yaw))] = n if cm._grid.value_at(1.525, 0.325) != 100 else None
+ assert module[180] is None and module[0] is not None and module[0] <= 2, module
print(f" table top, 320 cells at score 3: points in view while turning {seen_per_rev}; after the turn and "
- f"20 revolutions facing away -> {walls}/320 still a wall; facing it with the table gone -> free after {gone} "
- f"revolutions")
- print(f" legs 35 deg off the heading: freed after {freed['facing']} revolutions in view; behind the rover a wall "
- f"for 20; turning back -> freed after {m}; MossCostMap with odom yaw 180 deg -> kept 10, yaw 0 -> freed after "
- f"{module[0]}")
-
-
-def test_body_clear_resets_the_camera_wall_flag() -> None:
- """What the body drove over is free, and a camera wall there loses its
- `camera_wall` flag: with the flag left on, same-spot camera hits would
- raise the cell back to OCCUPIED_AT, a wall from one spot."""
- g = _camera_wall(2)
+ f"20 frames facing away under the lidar's rays -> {walls}/320 still a wall; facing it with the table gone "
+ f"-> free after {gone} floor frame(s)")
+ print(f" legs 35 deg off the heading: freed after {freed['facing']} floor frame(s) in view; behind the rover a "
+ f"wall for 20; turning back -> freed after {m}; MossCostMap with odom yaw 180 deg -> kept 10, yaw 0 -> "
+ f"freed after {module[0]}")
+
+
+def test_body_clear_frees_the_camera_layer() -> None:
+ """What the body drove over is free on both layers, and a camera wall
+ there does not come back from one spot: same-spot frames add nothing,
+ new viewpoints lift it to OCCUPIED_AT - 1, and the same spot holds it
+ there."""
+ g = _camera_wall(2, t=100.0)
gx, gy = g.cell(SHOE[:, 0], SHOE[:, 1])
- assert g.camera_wall[gy[0], gx[0]], "two viewpoints flag the camera wall"
+ g.lidar[gy[0], gx[0]] = HIT_CAP # a lidar ghost on the same cell
g.body_clear((SHOE[0, 0], SHOE[0, 1], 0.0)) # the rover drove over the shoe's cell
- assert not g.camera_wall[gy[0], gx[0]], "body_clear resets the flag"
- assert _camera_score(g, SHOE) == FREE_FLOOR and g.value_at(*SHOE[0]) == 0
+ assert _camera_score(g, SHOE) == FREE_FLOOR and g.lidar[gy[0], gx[0]] == FREE_FLOOR and g.value_at(*SHOE[0]) == 0
right_away = []
- for _ in range(10): # the last viewpoint, 10 frames
- g.camera_hits(SHOE, SPOT_B)
+ for k in range(10): # the last viewpoint, 10 frames
+ g.camera_obstacles(_frame(SHOE, 10 + k), SPOT_B, now=101.0 + 0.2 * k)
right_away.append(_camera_score(g, SHOE))
- assert max(right_away) < OCCUPIED_AT, right_away
- # new viewpoints lift it back to OCCUPIED_AT - 1, then 10 frames from the last of them
+ assert right_away == [FREE_FLOOR] * 10, right_away
k = 0
- while _camera_score(g, SHOE) < OCCUPIED_AT - 1:
+ while _camera_score(g, SHOE) < OCCUPIED_AT - 1: # new viewpoints lift it back
k += 1
- g.camera_hits(SHOE, (0.0, SPOT_B[1] - 0.15 * k))
+ g.camera_obstacles(_frame(SHOE, 30 + k), (0.0, SPOT_B[1] - 0.15 * k), now=104.0 + 0.2 * k)
assert k <= 10
+ assert k == OCCUPIED_AT - 1 - FREE_FLOOR, k
last = (0.0, SPOT_B[1] - 0.15 * k)
- flagged = copy.deepcopy(g)
- flagged.camera_wall[gy[0], gx[0]] = True # what a body_clear that kept the flag leaves
after = []
- for _ in range(10):
- g.camera_hits(SHOE, last)
- flagged.camera_hits(SHOE, last)
+ for j in range(10):
+ g.camera_obstacles(_frame(SHOE, 50 + j), last, now=106.0 + 0.2 * j)
after.append(_camera_score(g, SHOE))
assert g.value_at(*SHOE[0]) != 100, "a wall from one spot after body_clear"
- assert max(after) == OCCUPIED_AT - 1, after
- assert flagged.value_at(*SHOE[0]) == 100, "the flag is what this check guards: left on, one spot makes a wall"
- print(f" camera wall under the body -> score {FREE_FLOOR}, flag reset; 10 same-spot frames -> {sorted(set(right_away))}; "
- f"{k} new viewpoints to {OCCUPIED_AT - 1}, then 10 same-spot frames -> {sorted(set(after))} (with the flag "
- f"left on: a wall)")
-
-
-def test_the_fast_defaults() -> None:
- """Without the environment the module counts an obstacle at its first sighting,
- takes a new viewpoint every 5 cm and publishes every two revolutions (the
- obstacle-latency levers)."""
- import subprocess, sys as _sys
- env = {k: v for k, v in os.environ.items() if not k.startswith("MOSS_")}
- env["PYTHONPATH"] = os.environ.get("PYTHONPATH", "")
- out = subprocess.run([_sys.executable, "-c", "import moss_dimos.costmap2d as c; print(c.OCCUPIED_AT, c.NEW_VIEWPOINT_M, c.PUBLISH_EVERY)"],
- capture_output=True, text=True, env=env, timeout=120).stdout.split()
- assert out == ["1", "0.05", "2"], out
- print(" defaults: OCCUPIED_AT 1, NEW_VIEWPOINT_M 0.05, PUBLISH_EVERY 2 (this bench pins 2 / 0.10 / 5 for its own checks)")
-
-
-TESTS = (test_the_fast_defaults, test_leg_needs_two_viewpoints_and_ray_is_free, test_ramp_hit_from_one_spot_never_becomes_a_wall,
+ assert after == [OCCUPIED_AT - 1] * 10, after
+ print(f" camera wall under the body -> score {FREE_FLOOR} on both layers; 10 same-spot frames -> "
+ f"{sorted(set(right_away))}; {k} new viewpoints to {OCCUPIED_AT - 1}, then 10 same-spot frames -> "
+ f"{sorted(set(after))}")
+
+
+# --- the three camera guards: thin legs, moving things, the camera's own rays ---
+def test_thin_leg_survives_the_floor_sampled_beside_it() -> None:
+ """A table leg thinner than a 5 cm cell, seen ten times, sat at -3: the
+ camera calls the cell an obstacle in one frame and bare floor in the next
+ (5 cm of quantisation), and the two cancelled forever. A cell the camera
+ hit is deaf to floor samples for LOW_HIT_PROTECT_S; past that window it is
+ forgotten exactly as before."""
+ g = fresh()
+ leg = np.array([[1.025, 0.025]])
+ t = 1000.0 # an injected clock, in seconds
+ _armed(g, leg, t)
+ gx, gy = g.cell(leg[:, 0], leg[:, 1])
+ assert g.camera[gy[0], gx[0]] == 2 and g.value_at(*leg[0]) == 100, "two hits, two viewpoints"
+ for i in range(25): # 2.5 s of floor samples on its own cell
+ g.camera_floor(leg, now=t + 0.1 + 0.1 * i)
+ assert g.camera[gy[0], gx[0]] == 2, "a leg seen 0.1 s ago is not erased by the floor beside it"
+ assert g.value_at(*leg[0]) == 100
+ assert g.lidar[gy[0], gx[0]] == 0, "the camera's floor never touches the lidar layer"
+ n = 0 # nothing hits it any more
+ while g.value_at(*leg[0]) == 100:
+ n += 1
+ g.camera_floor(leg, now=t + LOW_HIT_PROTECT_S + n)
+ assert n < 10
+ assert g.camera[gy[0], gx[0]] < OCCUPIED_AT and n == 1, n
+ # through MossCostMap: a parked rover sees the leg and, in every frame, the
+ # floor on the leg's own cell; without the window the first floor frame frees it
+ traces = {}
+ for protect in (LOW_HIT_PROTECT_S, 0.0):
+ cmod.LOW_HIT_PROTECT_S = protect
+ try:
+ m = costmap()
+ asyncio.run(m.handle_odom(_odom(0.0, 0.0)))
+ asyncio.run(m.handle_explore_cmd(Bool(data=True)))
+ leg3 = np.array([[1.025, 0.025, 0.40]])
+ for k, y in enumerate((0.0, 0.0, 0.15)): # the gate's frame, then two viewpoints
+ asyncio.run(m.handle_odom(_odom(0.0, y)))
+ asyncio.run(m.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), _frame(leg3, k)]))))
+ assert m._grid.value_at(1.025, 0.025) == 100
+ trace = []
+ for k in range(10): # 10 frames, parked
+ asyncio.run(m.handle_camera_floor(_cloud(np.array([[1.04, 0.04, 0.0]]))))
+ asyncio.run(m.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), _frame(leg3, 3 + k)]))))
+ trace.append(m._grid.value_at(1.025, 0.025))
+ traces[protect] = trace
+ finally:
+ cmod.LOW_HIT_PROTECT_S = LOW_HIT_PROTECT_S
+ assert traces[LOW_HIT_PROTECT_S] == [100] * 10, traces
+ assert 100 not in traces[0.0], traces
+ print(f" thin leg: 25 floor samples inside the {LOW_HIT_PROTECT_S:.0f} s window -> still a wall, the lidar "
+ f"layer untouched; {n} past it -> forgotten; MossCostMap, leg and floor on its cell for 10 frames -> "
+ f"a wall for all 10 (without the window: free from the first frame)")
+
+
+def test_moving_object_never_writes_the_map() -> None:
+ """A cell takes a camera hit only if the previous depth frame also saw an
+ obstacle within one cell of it: a rolling vacuum or a walking person moves
+ on before the second look, a standing box repeats, a thin leg one cell off
+ still counts. The gate counts depth frames, not lidar revolutions:
+ lidar_odometry carries one frame on every revolution for 0.5 s."""
+ g = fresh()
+ path = (1.025, 1.225, 1.425, 1.625, 1.825)
+ for k, x in enumerate(path): # rolls by 20 cm per frame, two viewpoints anyway
+ g.camera_obstacles(np.array([[x, 0.025]]), (0.0, 0.15 * k), now=100.0 + 0.2 * k)
+ for x in path:
+ assert g.value_at(x, 0.025) != 100 and _camera_score(g, np.array([[x, 0.025]])) == 0, \
+ f"a moving object left a hit at {x} m"
+ assert np.isinf(g._last_low_hit).all(), \
+ "cells the gate held back are not stamped: a walker's trail stays open to the camera's floor and rays"
+ box = fresh() # a box STANDS there: three frames, two viewpoints
+ _armed(box, np.array([[1.025, 0.025]]), 100.0)
+ assert box.value_at(1.025, 0.025) == 100, "a standing box must still map"
+ thin = fresh() # a thin leg re-projected one cell off, diagonally
+ thin.camera_obstacles(np.array([[1.025, 0.025]]), (0.0, 0.0), now=100.0)
+ thin.camera_obstacles(np.array([[1.075, 0.075], [1.525, 0.525]]), (0.0, 0.0), now=100.2) # + a walker, new
+ assert _camera_score(thin, np.array([[1.075, 0.075]])) == 1, "one cell of tolerance"
+ assert _camera_score(thin, np.array([[1.525, 0.525]])) == 0, "the walker in the same frame is held back"
+ tx, ty = thin.cell(np.array([1.025, 1.075, 1.525]), np.array([0.025, 0.075, 0.525]))
+ assert list(thin._last_low_hit[ty, tx]) == [-np.inf, 100.2, -np.inf], \
+ "only the cell the gate kept is stamped, not the walker held back in the same frame"
+ # through MossCostMap: ONE depth frame (somebody 1.1 m away) carried by 5
+ # revolutions while the rover drives 12 cm, after a frame that saw
+ # something elsewhere
+ walker = np.array([[1.025, 0.525, 0.50]])
+ elsewhere = np.array([[2.025, -1.025, 0.50]])
+ hits = {}
+ spy, real = LogSpy(), cmod.logger
+ cmod.logger = spy
+ try:
+ for distinct in (False, True):
+ m = costmap()
+ asyncio.run(m.handle_odom(_odom(0.0, 0.0)))
+ asyncio.run(m.handle_explore_cmd(Bool(data=True)))
+ asyncio.run(m.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), elsewhere]))))
+ for k in range(5): # 10 Hz, 3 cm per revolution
+ asyncio.run(m.handle_odom(_odom(0.03 * k, 0.0)))
+ pts = _frame(walker, k + 1) if distinct else walker
+ asyncio.run(m.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), pts]))))
+ hits[distinct] = _camera_score(m._grid, walker)
+ if not distinct:
+ line = [s for s in spy.lines if s.startswith("costmap: camera obstacles:")][-1]
+ finally:
+ cmod.logger = real
+ assert hits == {False: 0, True: 1}, hits
+ assert line == ("costmap: camera obstacles: 2 points, 0 cell hits over the last 5 revolutions (2 depth frames, "
+ "3 repeats skipped, 2 cells held back by the moving-object gate)"), line
+ # a revolution without camera points: no frame of the last 0.5 s saw an obstacle, the gate forgets
+ m = costmap()
+ asyncio.run(m.handle_odom(_odom(0.0, 0.0)))
+ asyncio.run(m.handle_explore_cmd(Bool(data=True)))
+ standing = np.array([[1.525, 0.025, 0.30]])
+ asyncio.run(m.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), _frame(standing, 0)]))))
+ asyncio.run(m.handle_lidar(_cloud(_lidar_cloud(ROOM))))
+ asyncio.run(m.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), _frame(standing, 1)]))))
+ assert _camera_score(m._grid, standing) == 0, "the frame before saw nothing: no hit"
+ asyncio.run(m.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), _frame(standing, 2)]))))
+ assert _camera_score(m._grid, standing) == 1, "two frames in a row: a hit"
+ # the repeat window is read on the clouds' own stamps: the same bytes 0.4 s
+ # later are the frame lidar_odometry re-attached; 1.5 s later (it never
+ # re-attaches a frame past 0.5 s) they are a new look, and the gate passes
+ m = costmap()
+ asyncio.run(m.handle_odom(_odom(0.0, 0.0)))
+ asyncio.run(m.handle_explore_cmd(Bool(data=True)))
+ box = np.vstack([_lidar_cloud(ROOM), standing])
+ t0 = time.time()
+ window = []
+ for dt in (0.0, 0.4, 1.5):
+ asyncio.run(m.handle_lidar(_cloud(box, ts=t0 + dt)))
+ window.append((_camera_score(m._grid, standing), m._camera_frames, m._camera_repeats))
+ assert window == [(0, 1, 0), (0, 1, 1), (1, 2, 1)], window
+ print(" vacuum rolling 20 cm per frame -> no hit on its path, no stamp; standing box -> mapped; a leg one cell "
+ "off -> kept, only its kept cell stamped (not a walker held back in that frame); one depth frame on 5 revolutions over 12 cm -> 0 hits (as 5 "
+ f"frames it would hit: {hits[True]}); the same bytes 0.4 s later -> a repeat, 1.5 s later -> a new frame "
+ "(a hit); an empty revolution resets the gate")
+
+
+def test_the_cameras_rays_carve_the_camera_layer_only() -> None:
+ """Every cell a camera ray crosses at low height held nothing standing:
+ a miss on the camera layer, from the camera (0.156, 0.025), 7.5 cm up.
+ A floor point at 3.025 m: the ray is inside the band (0.013-0.060 m)
+ from 20 % to 82 % of its 2.869 m, i.e. the cells from 0.75 to 2.50 m."""
+ cam = camera_xy((0.0, 0.025), 0.0)
+ assert cam == (CAM_X, 0.025), cam
+ g = fresh()
+ g.camera_rays(BEYOND, cam, now=1000.0)
+ ys, xs = np.nonzero(g.camera < 0)
+ edges = np.round(g.ox + xs * g.res, 3)
+ assert set(np.round(g.oy + ys * g.res, 3)) == {0.0} and edges.min() == 0.75 and edges.max() == 2.50 \
+ and len(xs) == 36, (sorted(set(edges)), len(xs))
+ assert g.value_at(3.025, 0.025) == -1 and g.value_at(0.725, 0.025) == -1 and g.value_at(2.575, 0.025) == -1
+ assert (g.lidar == 0).all(), "camera rays never touch the lidar layer"
+ # a ghost at 2.0 m, armed by the camera: one look decides
+ ghost = np.array([[2.025, 0.025]])
+ out = {}
+ for label, end, after in (("floor 3 m ahead", 0.0, LOW_HIT_PROTECT_S + 1.0),
+ ("a 4 cm cable 3 m ahead", 0.04, LOW_HIT_PROTECT_S + 1.0),
+ ("a 0.30 m box 3 m ahead", 0.30, LOW_HIT_PROTECT_S + 1.0),
+ ("floor, 2 s after the hit", 0.0, 2.0)):
+ h = fresh()
+ _armed(h, ghost, 100.0)
+ h.camera_rays(np.array([[3.025, 0.025, end]]), cam, now=100.0 + after)
+ out[label] = h.value_at(*ghost[0])
+ # heights at the ghost's cell (1.85 m out of 2.869): floor 2.7 cm, cable 5.2 cm, box 22 cm
+ assert out == {"floor 3 m ahead": 0, "a 4 cm cable 3 m ahead": 0, "a 0.30 m box 3 m ahead": 100,
+ "floor, 2 s after the hit": 100}, out
+ # a lidar wall: the camera's rays and floor leave it; a camera wall: the lidar's rays leave it
+ w = fresh()
+ w.lidar_revolution(np.array([[2.025, 0.025]]), (0.01, 0.025))
+ w.lidar_revolution(np.array([[2.025, 0.025]]), (0.01, 0.175))
+ assert w.value_at(2.025, 0.025) == 100
+ w.camera_rays(BEYOND, cam, now=200.0)
+ w.camera_floor(np.array([[2.025, 0.025]]), now=200.0)
+ assert w.value_at(2.025, 0.025) == 100, "only a lidar ray may retract a lidar claim"
+ b = fresh()
+ _armed(b, ghost, 100.0)
+ for _ in range(20):
+ b.lidar_revolution(np.array([[3.025, 0.025]]), (0.01, 0.025))
+ bx, by = b.cell(ghost[:, 0], ghost[:, 1])
+ assert b.lidar[by[0], bx[0]] < 0 and b.value_at(*ghost[0]) == 100, \
+ "20 lidar rays through a camera wall: a ray 0.20 m up does not prove a low box gone"
+ # through MossCostMap, the frame path: a 5 cm door threshold 1.5 m ahead (an
+ # obstacle for lidar_odometry: its floor band is 4.6 cm there), a ghost at
+ # 1.225 m the rover saw from many places (score 5); the threshold's ray
+ # crosses it 5.5 cm up, inside the band. ONE depth frame carried by 3
+ # revolutions is one look: one miss; a new frame is a second look
+ sill = np.array([[1.525, 0.025, 0.05]])
+ m = costmap()
+ asyncio.run(m.handle_odom(_odom(0.0, 0.0)))
+ asyncio.run(m.handle_explore_cmd(Bool(data=True)))
+ sx, sy = m._grid.cell(np.array([1.225]), np.array([0.025]))
+ m._grid.camera[sy[0], sx[0]] = 5
+ trail = [int(m._grid.camera[sy[0], sx[0]])]
+ for k in (0, 0, 0, 1):
+ asyncio.run(m.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), _frame(sill, k)]))))
+ trail.append(int(m._grid.camera[sy[0], sx[0]]))
+ assert trail == [5, 4, 4, 4, 3], trail
+ # hits before rays inside a frame: a thin leg at 1.225 m, then a frame with
+ # the leg and the threshold behind it. The gate passes the leg, its hit
+ # stamps it, and the threshold's low ray through the leg's cell skips it:
+ # +1. Rays first would carve it before the hit (-1 + 1 = 0)
+ m = costmap()
+ asyncio.run(m.handle_odom(_odom(0.0, 0.0)))
+ asyncio.run(m.handle_explore_cmd(Bool(data=True)))
+ leg = np.array([[1.225, 0.025, 0.40]])
+ asyncio.run(m.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), _frame(leg, 0)]))))
+ first = _camera_score(m._grid, leg)
+ asyncio.run(m.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), _frame(leg, 1), sill]))))
+ assert (first, _camera_score(m._grid, leg)) == (0, 1), (first, _camera_score(m._grid, leg))
+ print(f" floor 3 m ahead -> cells {edges.min():.2f}-{edges.max():.2f} m carved ({len(xs)}), not its endpoint; "
+ f"ghost at 2 m: floor ray / cable ray -> free, ray over it at 22 cm -> kept, 2 s after its hit -> kept; "
+ f"lidar wall untouched by the camera, camera wall untouched by 20 lidar revolutions; MossCostMap: a ghost "
+ f"at score 5 behind a threshold, one frame on 3 revolutions then a new one -> {trail}; a leg the frame "
+ "confirms is not carved by that frame's ray (+1)")
+
+
+def test_camera_rays_start_at_the_camera_not_the_base() -> None:
+ """The rays start where the camera is: the profile's camera_xyz_base_m,
+ turned by the heading (0.156 m ahead of base_link on MOSS). Cast from the
+ base, a floor sample's ray opens the band 0.15 m too close and carves
+ cells the camera's ray crosses above it."""
+ assert camera_xy((0.0, 0.0), 0.0) == (CAM_X, CAM_Y), "facing +x: the camera is 0.156 m ahead"
+ x, y = camera_xy((1.0, 2.0), math.pi / 2)
+ assert abs(x - 1.0) < 1e-9 and abs(y - (2.0 + CAM_X)) < 1e-9, "turned 90 deg: the offset turns with the rover"
+ os.environ["MOSS_CAMERA_XYZ_M"] = "-0.20 0 0.56"
+ try:
+ moved = camera_xy((0.0, 0.0), 0.0)
+ finally:
+ del os.environ["MOSS_CAMERA_XYZ_M"]
+ assert moved == (-0.20, 0.0), "read from the profile at call time"
+
+ def first_carved(origin) -> float:
+ g = fresh()
+ g.camera_rays(BEYOND, origin, now=1000.0)
+ return round(g.ox + np.nonzero(g.camera < 0)[1].min() * g.res, 3)
+
+ pose = (0.02, 0.025)
+ from_camera, from_base = first_carved(camera_xy(pose, 0.0)), first_carved(pose)
+ assert (from_camera, from_base) == (0.75, 0.60), (from_camera, from_base)
+ # a ghost at 0.675 m: the camera's own ray crosses it 6.2 cm up, above the band
+ ghost = np.array([[0.675, 0.025]])
+ old = time.monotonic() - 10.0
+ m = costmap()
+ asyncio.run(m.handle_odom(_odom(*pose)))
+ asyncio.run(m.handle_explore_cmd(Bool(data=True)))
+ m._grid = fresh()
+ _armed(m._grid, ghost, old)
+ asyncio.run(m.handle_camera_floor(_cloud(BEYOND)))
+ assert m._grid.value_at(*ghost[0]) == 100, "the camera's ray crosses the ghost above the band: it stays"
+ g = fresh()
+ _armed(g, ghost, old)
+ g.camera_rays(BEYOND, pose, now=time.monotonic())
+ assert g.value_at(*ghost[0]) != 100, "cast from the base, the same look erases it"
+
+ # through MossCostMap, the floor path: a ghost 1.5 m ahead, hit 10 s ago
+ # (outside its window), dies to ONE floor sample 3 m ahead whose ray from
+ # the camera crosses it 3.9 cm up. Facing +y, the camera sits at (0, 0.156)
+ # and the same look along +y kills the same ghost turned by 90 deg; an
+ # offset not turned with the heading, (0.156, 0), would pass a cell beside it
+ stale = {}
+ for yaw, ghost_xy, floor_xy in ((0.0, (1.525, 0.025), (3.025, 0.025)),
+ (math.pi / 2, (0.025, 1.525), (0.025, 3.025))):
+ m = costmap()
+ asyncio.run(m.handle_odom(_odom(0.0, 0.0, yaw)))
+ asyncio.run(m.handle_explore_cmd(Bool(data=True)))
+ _armed(m._grid, np.array([ghost_xy]), old)
+ before = (_camera_score(m._grid, np.array([ghost_xy])), m._grid.value_at(*ghost_xy))
+ asyncio.run(m.handle_camera_floor(_cloud(np.array([[*floor_xy, 0.0]]))))
+ stale[round(math.degrees(yaw))] = (before, (_camera_score(m._grid, np.array([ghost_xy])),
+ m._grid.value_at(*ghost_xy)))
+ assert stale == {0: ((2, 100), (1, 0)), 90: ((2, 100), (1, 0))}, stale
+ turned = m._camera_xy()
+ assert abs(turned[0]) < 1e-9 and abs(turned[1] - CAM_X) < 1e-9, turned
+
+ # through MossCostMap, the frame path: a 4 cm cable 0.95 m ahead of a rover
+ # at x = 0.02 (an obstacle for lidar_odometry, whose floor band is 3 cm
+ # there). The camera's own ray crosses the cell at 0.475 m 6.19 cm up, above
+ # the band, and leaves a ghost there; a base-cast ray crosses it 5.85 cm up
+ # and would carve it
+ cable = np.array([[0.975, 0.025, 0.04]])
+ frame_path = {}
+ for label in ("camera", "base"):
+ m = costmap()
+ asyncio.run(m.handle_odom(_odom(*pose)))
+ asyncio.run(m.handle_explore_cmd(Bool(data=True)))
+ m._grid = fresh()
+ cx, cy = m._grid.cell(np.array([0.475]), np.array([0.025]))
+ m._grid.camera[cy[0], cx[0]] = 5
+ if label == "base":
+ m._camera_xy = lambda m=m: m._pose_xy
+ asyncio.run(m.handle_lidar(_cloud(np.vstack([_lidar_cloud(ROOM), cable]))))
+ frame_path[label] = int(m._grid.camera[cy[0], cx[0]])
+ assert frame_path == {"camera": 5, "base": 4}, frame_path
+
+ # the mount is read at call time, all three numbers: 5 cm to the left moves
+ # the origin sideways (turned with the heading), and a camera 0.15 m up
+ # moves the band with it, so a floor ray carves the same stretch of its
+ # length, in the row of the moved origin
+ os.environ["MOSS_CAMERA_XYZ_M"] = "0.156 0.05 0.15"
+ try:
+ left, left_north = camera_xy((0.0, 0.0), 0.0), camera_xy((0.0, 0.0), math.pi / 2)
+ h = fresh()
+ h.camera_rays(np.array([[3.025, 0.075, 0.0]]), camera_xy((0.0, 0.025), 0.0), now=1000.0)
+ finally:
+ del os.environ["MOSS_CAMERA_XYZ_M"]
+ assert left == (CAM_X, 0.05), left
+ assert abs(left_north[0] + 0.05) < 1e-9 and abs(left_north[1] - CAM_X) < 1e-9, left_north
+ hy, hx = np.nonzero(h.camera < 0)
+ rows, cols = set(np.round(h.oy + hy * h.res, 3)), np.round(h.ox + hx * h.res, 3)
+ assert rows == {0.05} and (cols.min(), cols.max(), len(hx)) == (0.75, 2.50, 36), (rows, sorted(set(cols)))
+ print(f" camera at {camera_xy((0.0, 0.0), 0.0)} facing +x; floor at 3 m: carving starts at {from_camera:.2f} m "
+ f"from the camera vs {from_base:.2f} m from the base; ghost at 0.675 m kept by the camera-cast ray, "
+ "erased by a base-cast one; MossCostMap: a stale ghost at 1.5 m, floor 3 m ahead -> score 2 -> 1, free, "
+ f"facing +x and +y (camera at {turned[0]:.2f}, {turned[1]:.3f}); a cable 0.95 m ahead -> ghost at 0.475 m "
+ f"{frame_path['camera']} from the camera, {frame_path['base']} from the base; camera 5 cm left and 0.15 m "
+ "up -> origin y 0.05 (-0.05 m in x facing +y), the floor ray still carves 0.75-2.50 m")
+
+
+def test_the_carve_band_follows_the_camera_height() -> None:
+ """The original band, 0.10-0.45 m for a camera 0.56 m up, as fractions of
+ the camera height: on a floor sample's ray, the stretch from 20 % to 82 %
+ of its range at any camera height. 0.013-0.060 m on MOSS's 0.075 m; the
+ profile is read at call time."""
+ lo, hi = carve_z_band()
+ assert (round(lo, 4), round(hi, 4)) == (0.0134, 0.0603), (lo, hi)
+ assert abs(lo - 0.075 * 0.10 / 0.56) < 1e-12 and abs(hi - 0.075 * 0.45 / 0.56) < 1e-12
+ o_lo, o_hi = carve_z_band(0.56)
+ assert abs(o_lo - 0.10) < 1e-12 and abs(o_hi - 0.45) < 1e-12, "the original band at the original height"
+ for h in (0.075, 0.56):
+ b_lo, b_hi = carve_z_band(h)
+ assert abs((1 - b_hi / h) - 0.196) < 1e-3 and abs((1 - b_lo / h) - 0.821) < 1e-3
+ os.environ["MOSS_CAMERA_XYZ_M"] = "0.156 0 0.15"
+ try:
+ r_lo, r_hi = carve_z_band()
+ finally:
+ del os.environ["MOSS_CAMERA_XYZ_M"]
+ assert (round(r_lo, 4), round(r_hi, 4)) == (0.0268, 0.1205), (r_lo, r_hi)
+ print(f" band {lo:.4f}-{hi:.4f} m at 0.075 m; {o_lo:.2f}-{o_hi:.2f} m at 0.56 m; a floor ray carves 20-82 % "
+ f"of its range at both; MOSS_CAMERA_XYZ_M z=0.15 -> {r_lo:.4f}-{r_hi:.4f} m")
+
+
+def test_the_doctrine_defaults() -> None:
+ """Without the environment the module takes a wall from two places 10 cm
+ apart (a passer-by painted from one parked spot never walls the rover
+ in), publishes every two revolutions and writes no contact into the map;
+ the knobs still move them."""
+ import subprocess
+ code = ("import moss_dimos.costmap2d as c; lo, hi = c.carve_z_band(); "
+ "print(c.OCCUPIED_AT, c.NEW_VIEWPOINT_M, c.PUBLISH_EVERY, c.CONTACT_WALL, c.LOW_HIT_PROTECT_S, "
+ "f'{lo:.4f}', f'{hi:.4f}')")
+
+ def run(**extra) -> list:
+ env = {k: v for k, v in os.environ.items() if not k.startswith("MOSS_")}
+ env["PYTHONPATH"] = os.environ.get("PYTHONPATH", "")
+ env.update(extra)
+ return subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, env=env,
+ timeout=120).stdout.split()
+
+ out = run()
+ assert out == ["2", "0.1", "2", "False", "3.0", "0.0134", "0.0603"], out
+ knobs = run(MOSS_OCCUPIED_AT="1", MOSS_NEW_VIEWPOINT_M="0.05", MOSS_CONTACT_WALL="1")
+ assert knobs[:4] == ["1", "0.05", "2", "True"], knobs
+ print(" defaults: OCCUPIED_AT 2, NEW_VIEWPOINT_M 0.1, PUBLISH_EVERY 2, contact wall off, thin-leg window 3 s, "
+ "carve band 0.0134-0.0603 m; MOSS_OCCUPIED_AT=1 MOSS_NEW_VIEWPOINT_M=0.05 MOSS_CONTACT_WALL=1 -> "
+ f"{' '.join(knobs[:4])} (this bench pins 2 / 0.10 / 5)")
+
+
+TESTS = (test_the_doctrine_defaults, test_leg_needs_two_viewpoints_and_ray_is_free, test_ramp_hit_from_one_spot_never_becomes_a_wall,
test_chair_moved_is_forgotten_by_lidar_rays, test_reinforcement_is_capped_and_unlearning_bounded,
test_parked_rover_never_erases_an_established_wall, test_body_clear_is_the_moss_footprint,
test_the_lidar_tag_is_one_exact_height, test_the_map_writes_only_during_the_mission,
@@ -947,7 +1491,10 @@ TESTS = (test_the_fast_defaults, test_leg_needs_two_viewpoints_and_ray_is_free,
test_the_mission_signals_cross_the_process_boundary, test_revolution_cost,
test_camera_one_viewpoint_never_becomes_a_wall, test_camera_wall_no_longer_seen_is_carved_free,
test_camera_wall_still_seen_survives_the_rays, test_the_knobs_are_read_at_import,
- test_the_carve_stays_in_the_cameras_view, test_body_clear_resets_the_camera_wall_flag)
+ test_the_carve_stays_in_the_cameras_view, test_body_clear_frees_the_camera_layer,
+ test_thin_leg_survives_the_floor_sampled_beside_it, test_moving_object_never_writes_the_map,
+ test_the_cameras_rays_carve_the_camera_layer_only, test_camera_rays_start_at_the_camera_not_the_base,
+ test_the_carve_band_follows_the_camera_height)
if __name__ == "__main__":
OK = KO = 0
diff --git a/benches/bench_moss_adapter_cold.py b/benches/bench_moss_adapter_cold.py
index 98f8b58..69e9599 100644
--- a/benches/bench_moss_adapter_cold.py
+++ b/benches/bench_moss_adapter_cold.py
@@ -622,6 +622,142 @@ for env_on, label in (("1", "MOSS_ONE_TRACK_PIVOT on"), ("0", "MOSS_ONE_TRACK_PI
os.environ.pop("MOSS_ONE_TRACK_PIVOT", None)
os.environ.pop("MOSS_BUS_REF_MV", None)
+# ── 16. feedback loss: logged once, rate-limited, with a count and a recovery line ──
+print("16. feedback loss: telemetry silent while driving -> one warning, a counted repeat per READ_WARN_PERIOD_S, "
+ "a recovery line; a failing serial read the same way")
+import moss_dimos.moss_adapter as _MA # noqa: E402
+from moss_dimos.moss_adapter import READ_WARN_PERIOD_S, TELEMETRY_FRESH_S # noqa: E402
+
+
+class _CapLog:
+ """Stands in for the adapter's logger: every line, by level."""
+
+ def __init__(self):
+ self.lines = []
+
+ def _add(self, level, msg):
+ self.lines.append((level, str(msg)))
+
+ def info(self, msg, *a, **k):
+ self._add("info", msg)
+
+ def warning(self, msg, *a, **k):
+ self._add("warning", msg)
+
+ def error(self, msg, *a, **k):
+ self._add("error", msg)
+
+ def of(self, level, text):
+ return [m for lv, m in self.lines if lv == level and text in m]
+
+
+class _MutedTelemetry(FakeMossFirmware):
+ """The firmware answers every command, but its telemetry can be cut (the CDC
+ FIFO guard dropping the lines): the deadman and the arm expiry still run."""
+ mute = False
+
+ def _auto_tick(self):
+ if not self.mute:
+ return super()._auto_tick()
+ self.now()
+ self._poll()
+
+
+class _FlakyReads(FakeMossFirmware):
+ """readline() raises `fail` times (an I/O error on an open port), then reads again."""
+ fail = 0
+
+ def readline(self):
+ if self.fail > 0:
+ self.fail -= 1
+ raise OSError(5, "Input/output error")
+ return super().readline()
+
+
+_saved_logger = _MA._LOGGER
+_cap = _CapLog()
+_MA._LOGGER = _cap
+_saved_period = _MA.READ_WARN_PERIOD_S
+try:
+ check(READ_WARN_PERIOD_S == 5.0 and TELEMETRY_FRESH_S == 1.0,
+ f"the rate limit is 5 s, the telemetry is stale past 1 s ({READ_WARN_PERIOD_S}, {TELEMETRY_FRESH_S})")
+ os.environ["MOSS_PULSE_MS"] = "0"
+ os.environ["MOSS_BUS_REF_MV"] = "0"
+ fwm = _MutedTelemetry(auto_time=True) # the stock encoders never turn: with telemetry, a long drive would be a stall
+ fm = lambda: fwm # noqa: E731
+ fm.is_mock = True
+ ma = MossBaseAdapter(dof=3, port_factory=fm, geometry=MossGeometry(track_m=0.30, mps_at_limit=0.15, max_pct=100, min_pct=0))
+ check(ma.connect() and ma.write_enable(True), "connected and armed on a fake whose telemetry can be cut")
+
+ def _drive_for(seconds, twist=(0.06, 0.0, 0.0)):
+ t_end = time.monotonic() + seconds
+ while time.monotonic() < t_end:
+ ma.write_velocities(list(twist)); settle(0.1)
+
+ _drive_for(0.4)
+ check(_cap.of("warning", "blind") == [] and ma.blind_count == 0,
+ f"telemetry fresh while driving 40 %: no warning, blind count 0 ({ma.blind_count})")
+ fwm.mute = True
+ _drive_for(TELEMETRY_FRESH_S + 0.8)
+ blind = _cap.of("warning", "stall guard and IMU bump blind")
+ check(len(blind) == 1, f"telemetry silent for {TELEMETRY_FRESH_S + 0.8:.1f} s while driving: exactly ONE warning, "
+ f"not one per tick ({len(blind)}): {blind[:1]}")
+ check(blind and "no telemetry from the motor board for" in blind[0] and "L=+40% R=+40%" in blind[0]
+ and "(1 consecutive ticks)" in blind[0], f"it says what is blind, the command held and the count: {blind[:1]}")
+ n_blind = ma.blind_count
+ check(n_blind >= 4, f"every blind keepalive tick is counted: {n_blind} ticks past the 1 s mark (10 per second)")
+ check(ma.stall_count == 0 and not ma.stalled and fwm.mode == DRIVE,
+ f"meanwhile the stall guard cannot see the frozen encoders: no stall, the fake still DRIVEs "
+ f"(count {ma.stall_count}, mode {fwm.mode}) - why the line matters")
+ _MA.READ_WARN_PERIOD_S = 0.3
+ _drive_for(0.75)
+ blind = _cap.of("warning", "stall guard and IMU bump blind")
+ counts = [int(re.search(r"\((\d+) consecutive", m).group(1)) for m in blind]
+ check(2 <= len(blind) - 1 <= 4 and counts == sorted(counts) and len(set(counts)) == len(counts),
+ f"period shortened to 0.3 s: the warning repeats about every 0.3 s ({len(blind) - 1} more lines over "
+ f"0.75 s more of driving), each with a growing count {counts}")
+ _MA.READ_WARN_PERIOD_S = _saved_period
+ before_back = ma.blind_count
+ fwm.mute = False
+ _drive_for(0.5)
+ back = _cap.of("info", "telemetry recovered after")
+ check(len(back) == 1 and f"after {before_back} failures" in back[0] and "s without a line" in back[0],
+ f"telemetry back: exactly one recovery line with the count ({before_back}): {back}")
+ check(ma.blind_count == 0, f"the count resets on recovery ({ma.blind_count})")
+ ma.write_stop()
+ n_w = len(_cap.of("warning", "blind"))
+ fwm.mute = True
+ settle(TELEMETRY_FRESH_S + 0.5)
+ check(len(_cap.of("warning", "blind")) == n_w and ma.blind_count == 0,
+ "telemetry silent while the tracks are at rest: nothing is blind, nothing is said")
+ fwm.mute = False
+ ma.disconnect()
+
+ fwf = _FlakyReads(auto_time=True)
+ ff = lambda: fwf # noqa: E731
+ ff.is_mock = True
+ mf = MossBaseAdapter(dof=3, port_factory=ff, geometry=MossGeometry(track_m=0.30, mps_at_limit=0.15, max_pct=100, min_pct=0))
+ check(mf.connect(), "connected on a fake whose reads can fail")
+ n_err = len(_cap.lines)
+ fwf.fail = 30
+ t_end = time.monotonic() + 4.0
+ peak = 0
+ while time.monotonic() < t_end and (fwf.fail > 0 or mf.read_failure_count):
+ peak = max(peak, mf.read_failure_count); settle(0.02)
+ errs = [m for lv, m in _cap.lines[n_err:] if lv == "error" and "serial read failed" in m]
+ check(len(errs) == 1 and "(1 consecutive)" in errs[0] and "Input/output error" in errs[0],
+ f"30 failed reads in ~1.5 s (inside the 5 s period): ONE error line, not 30 ({len(errs)}): {errs[:1]}")
+ check(peak >= 25, f"the failures are counted ({peak} at the peak, 30 thrown)")
+ rec = [m for lv, m in _cap.lines[n_err:] if lv == "info" and "serial reads recovered" in m]
+ check(rec == ["MOSS base: serial reads recovered after 30 failures"] and mf.read_failure_count == 0,
+ f"reads work again: one recovery line with the count, the count reset: {rec}")
+ mf.disconnect()
+finally:
+ _MA._LOGGER = _saved_logger
+ _MA.READ_WARN_PERIOD_S = _saved_period
+ os.environ.pop("MOSS_PULSE_MS", None)
+ os.environ.pop("MOSS_BUS_REF_MV", None)
+
print(f"{OK} OK, {KO} KO")
print("TEST PASSED" if KO == 0 else "TEST FAILED")
sys.exit(1 if KO else 0)
diff --git a/benches/bench_moss_blueprints_cold.py b/benches/bench_moss_blueprints_cold.py
index df8eb7a..dd3c4ca 100644
--- a/benches/bench_moss_blueprints_cold.py
+++ b/benches/bench_moss_blueprints_cold.py
@@ -31,31 +31,46 @@ Known input -> known output in physical units. Groups:
profile, no gamepad -> cmd_vel remap in explore; switches
MOSS_CAMERA=0 / MOSS_RECORD=0 / MOSS_WRIST=0 / MOSS_RERUN=1
(and off / no / false: robot_profile.env_on);
- MossMemoryConfig defaults; base_telemetry on the coordinator
- J. MOSS_IMU - unset / 0 / off: dimOS's RealSenseCamera with enable_imu False
- and no BumpImu, the same blueprint as without the switch;
- MOSS_IMU=1: MossRealSense with enable_imu True and imu_hz
- 200 and every other camera kwarg unchanged, a BumpImu atom
- with the knobs read at build time, its bump on the stream
- the coordinator / explorer publish and the planner / costmap
- read, imu from the camera, base_telemetry from the
- coordinator, no stream type conflict; refused without the
- camera; both classes pickle by reference into a clean
- interpreter; importing the blueprints imports neither
- K. MOSS_GYRO - the odometry's rotation prior: on by default with the
- in-process IMU (MossRealSense, enable_imu True), off with
- MOSS_GYRO=0 (the contacts stay) or MOSS_IMU=0 (quietly);
- MOSS_IMU=0 MOSS_GYRO=1 refused with one warning (dimOS's
- camera keeps enable_imu False); MOSS_GYRO_FORCE=1 on top
- builds dimOS's camera with enable_imu True and the prior
- on, its imu wired to the odometry, with a warning; FORCE
- alone changes nothing; no camera, no prior
+ MossMemoryConfig defaults; base_telemetry and stall on the
+ coordinator; its telemetry loop on a stall count 0, 1, 1, 2
+ -> two Bool(True) on stall, two lines, nothing else
+ L. own workers - every camera module runs in a worker of its own
+ (dedicated_worker): the RealSense with the IMU
+ (DedicatedMossRealSense), without it (MOSS_IMU=0:
+ DedicatedRealSenseCamera) and the wrist camera; each is
+ its base class plus the flag and nothing else (same
+ streams); moss-explore has five dedicated modules
+ J. MOSS_IMU - unset / 0 / off: dimOS's RealSenseCamera (in its own worker)
+ with enable_imu False and no BumpImu, the same blueprint as
+ without the switch; MOSS_IMU=1: MossRealSense (in its own
+ worker) with enable_imu True and imu_hz 200 and every other
+ camera kwarg unchanged, a BumpImu atom with the knobs read
+ at build time; bump (in front) published by BumpImu and the
+ explorer, read by the planner, the costmap, the sounds and
+ the odometry; bump_rear (behind) published by BumpImu, read
+ by the planner only; stall published by the coordinator,
+ read by the planner only; imu from the camera,
+ base_telemetry from the coordinator, no stream type
+ conflict; refused without the camera; the classes pickle
+ by reference into a clean interpreter; importing the
+ blueprints imports neither bump_imu nor realsense_imu
+ K. MOSS_GYRO - the odometry's rotation prior: OFF by default until its
+ sign is measured, with one info line pointing to
+ tools/gyro_sign_bench.py; MOSS_GYRO=1 turns it on with the
+ in-process IMU (MossRealSense, enable_imu True); MOSS_GYRO=0
+ the same as unset (the contacts stay); MOSS_IMU=0 off
+ (quietly); MOSS_IMU=0 MOSS_GYRO=1 refused with one warning
+ (dimOS's camera keeps enable_imu False); MOSS_GYRO_FORCE=1
+ on top builds dimOS's camera with enable_imu True and the
+ prior on, its imu wired to the odometry, with a warning;
+ FORCE alone changes nothing; no camera, no prior
I. the worker - what a dimOS forkserver worker does: unpickle the
coordinator class in a clean interpreter -> the module is
imported, 'moss' is registered, the registry builds a
MossBaseAdapter from the factory string, the LCM clamp is
on, no other moss_dimos module came along. WristCamera
- pickles by reference both ways. A conflicting 'moss'
+ and the two RealSense classes pickle by reference both
+ ways. A conflicting 'moss'
registration is reported with both paths, not swallowed.
Needs dimOS (the module imports it). No hardware.
@@ -452,7 +467,7 @@ check("MOSS_MPS_AT_LIMIT=0.30 read when the blueprint is built -> 0.30 m/s, rim
nav = mb.build_moss_nav()
n = names(nav)
want = {"MossControlCoordinator", "GamepadTeleop", "RPLidarC1", "LidarOdometry",
- "MossCostMap", "MossRealSense", "BumpImu", "MossRecorder"} # the camera carries the IMU by default
+ "MossCostMap", "DedicatedMossRealSense", "BumpImu", "MossRecorder"} # the camera carries the IMU by default
check("moss-nav modules", want <= n, f"{sorted(n)}")
check("moss-nav has no planner, no explorer, no MovementManager, no viewer",
not ({"RecoveringPlanner", "Explorer2", "MovementManager", "WebsocketVisModule"} & n))
@@ -470,9 +485,10 @@ check("lidar on the CP2102N by-id at 460800, frame lidar_link",
hw = atom(nav, "MossControlCoordinator").kwargs["hardware"][0]
check("base: adapter 'moss' on the QT Py by-id", hw.adapter_type == "moss" and hw.address == os.path.join(byid, QTPY))
check("pad: the same MOSS envelope as moss-gamepad", atom(nav, "GamepadTeleop").kwargs.get("envelope") == teleop_envelope(g))
-check("odometry with the gyro prior (MOSS_GYRO unset = on with MOSS_IMU, the default)", atom(nav, "LidarOdometry").kwargs.get("use_gyro_prior") is True)
+check("odometry WITHOUT the gyro prior (MOSS_GYRO unset = off until its sign is measured)",
+ atom(nav, "LidarOdometry").kwargs.get("use_gyro_prior") is False)
check("odometry without deskew (MOSS_DESKEW unset = off: on the rover the deskew thread fails)", atom(nav, "LidarOdometry").kwargs.get("deskew") is False)
-cam = atom(nav, "MossRealSense").kwargs
+cam = atom(nav, "DedicatedMossRealSense").kwargs
check("RealSense 640x480 @ 5 fps, colour + depth (aligned), no point cloud, the IMU in the camera's own process (MOSS_IMU on by default)",
(cam.get("width"), cam.get("height"), cam.get("fps"), cam.get("enable_depth"),
cam.get("enable_pointcloud"), cam.get("enable_imu")) == (640, 480, 5, True, False, True))
@@ -498,7 +514,7 @@ wspec = nav.transport_map.get(("wrist_image", Image))
check("wrist_image crosses the bus as JPEG on /wrist_image",
isinstance(wspec, TransportSpec) and wspec.cls is JpegLcmTransport and wspec.args[0] == "/wrist_image")
check("the RealSense keeps its own names (no remap on the camera module)",
- not any(k[0] in ("RealSenseCamera", "MossRealSense") for k in nav.remapping_map))
+ not any(k[0] == atom(nav, "DedicatedMossRealSense").name for k in nav.remapping_map))
exp = mb.build_moss_explore()
e = names(exp)
@@ -544,25 +560,30 @@ def blueprint_text(bp):
from moss_dimos.bump_imu import BumpImu # noqa: E402
from moss_dimos.realsense_imu import MossRealSense # noqa: E402
# the default (MOSS_IMU unset) is the IMU ON: colour, depth and IMU were seen alive together on the robot
-check("MOSS_IMU unset (the default): moss-nav has MossRealSense and BumpImu, and no stock RealSenseCamera",
- {"MossRealSense", "BumpImu"} <= names(nav) and "RealSenseCamera" not in names(nav), f"{sorted(names(nav))}")
+check("MOSS_IMU unset (the default): moss-nav has the in-process IMU camera (DedicatedMossRealSense) and BumpImu, "
+ "and no stock RealSense camera",
+ {"DedicatedMossRealSense", "BumpImu"} <= names(nav)
+ and not ({"RealSenseCamera", "DedicatedRealSenseCamera"} & names(nav)), f"{sorted(names(nav))}")
check("MOSS_IMU unset: moss-explore too, with the planner and the explorer still there",
- {"MossRealSense", "BumpImu", "RecoveringPlanner", "Explorer2"} <= names(exp) and "RealSenseCamera" not in names(exp))
+ {"DedicatedMossRealSense", "BumpImu", "RecoveringPlanner", "Explorer2"} <= names(exp)
+ and not ({"RealSenseCamera", "DedicatedRealSenseCamera"} & names(exp)))
for spelled_off in ("0", "off"):
os.environ["MOSS_IMU"] = spelled_off
off_nav, off_exp = mb.build_moss_nav(), mb.build_moss_explore()
- cam_off = atom(off_nav, "RealSenseCamera")
- check(f"MOSS_IMU={spelled_off}: the camera atom is dimOS's own RealSenseCamera, enable_imu False, no imu_hz kwarg, no BumpImu, no MossRealSense",
- cam_off is not None and cam_off.module is RealSenseCamera and cam_off.kwargs.get("enable_imu") is False
- and "imu_hz" not in cam_off.kwargs and not ({"BumpImu", "MossRealSense"} & (names(off_nav) | names(off_exp))),
+ cam_off = atom(off_nav, "DedicatedRealSenseCamera")
+ check(f"MOSS_IMU={spelled_off}: the camera atom is dimOS's own RealSenseCamera in its own worker "
+ "(DedicatedRealSenseCamera), enable_imu False, no imu_hz kwarg, no BumpImu, no MossRealSense",
+ cam_off is not None and cam_off.module.__mro__[1] is RealSenseCamera and cam_off.kwargs.get("enable_imu") is False
+ and "imu_hz" not in cam_off.kwargs
+ and not ({"BumpImu", "DedicatedMossRealSense"} & (names(off_nav) | names(off_exp))),
f"{sorted(names(off_exp))}")
os.environ["MOSS_IMU"] = "1"
imu_nav, imu_exp = mb.build_moss_nav(), mb.build_moss_explore()
check("MOSS_IMU=1: the same blueprints as the unset switch, kwarg for kwarg",
blueprint_text(imu_nav) == blueprint_text(nav) and blueprint_text(imu_exp) == blueprint_text(exp))
-cam_imu = atom(imu_nav, "MossRealSense")
-check("the camera atom is moss_dimos.realsense_imu.MossRealSense, a RealSenseCamera subclass",
- cam_imu.module is MossRealSense and issubclass(MossRealSense, RealSenseCamera))
+cam_imu = atom(imu_nav, "DedicatedMossRealSense")
+check("the camera atom is moss_dimos.realsense_imu.MossRealSense in its own worker, a RealSenseCamera subclass",
+ cam_imu.module.__mro__[1] is MossRealSense and issubclass(MossRealSense, RealSenseCamera))
check("... enable_imu True, imu_hz 200", cam_imu.kwargs.get("enable_imu") is True and cam_imu.kwargs.get("imu_hz") == 200,
f"{cam_imu.kwargs.get('enable_imu')} {cam_imu.kwargs.get('imu_hz')}")
strip = lambda kw: repr(sorted((k, v) for k, v in kw.items() if k not in ("enable_imu", "imu_hz"))) # noqa: E731
@@ -573,22 +594,34 @@ check("BumpImu atom: forward axis +z, 4.0 m/s^2, debounce 0.7 s, no CSV (the def
bk == {"axis": "+z", "threshold": 4.0, "debounce_s": 0.7, "log_path": None}, f"{bk}")
w = wiring(imu_exp)
bump_side = w.get(("bump", mb.Bool), set())
-check("moss-explore: BumpImu's bump is the stream the coordinator and the explorer publish on",
- {("BumpImu", "out"), ("MossControlCoordinator", "out"), ("Explorer2", "out")} <= bump_side, f"{sorted(bump_side)}")
-check("... and the one the planner's escape and the costmap's contact memory read",
- {("RecoveringPlanner", "in"), ("MossCostMap", "in")} <= bump_side, f"{sorted(bump_side)}")
+rear_side = w.get(("bump_rear", mb.Bool), set())
+stall_side = w.get(("stall", mb.Bool), set())
+check("moss-explore: bump (a contact in front) is published by BumpImu and the explorer's back-off, NOT by the "
+ "coordinator (a stall is not a felt contact)",
+ {o for o in bump_side if o[1] == "out"} == {("BumpImu", "out"), ("Explorer2", "out")}, f"{sorted(bump_side)}")
+check("... and read by the planner's escape, the costmap and the lidar odometry (the shaken revolution dropped)",
+ {("RecoveringPlanner", "in"), ("MossCostMap", "in"), ("LidarOdometry", "in")} <= bump_side, f"{sorted(bump_side)}")
check("... the sounds read it too when the sound module is in the build",
"MossSounds" not in names(imu_exp) or ("MossSounds", "in") in bump_side, f"{sorted(names(imu_exp))}")
-check("... no second bump stream of another type",
- [k for k in w if k[0] == "bump"] == [("bump", mb.Bool)], f"{[k for k in w if k[0] == 'bump']}")
-check("... and the lidar odometry's contact In (the shaken revolution dropped), on the costmap's stream, in moss-explore and "
- "moss-nav; with MOSS_IMU=0 the stall guard's bump still reaches it",
- ("LidarOdometry", "in") in bump_side
- and {("LidarOdometry", "in"), ("MossCostMap", "in")} <= wiring(imu_nav).get(("bump", mb.Bool), set())
- and {("MossControlCoordinator", "out"), ("LidarOdometry", "in")} <= wiring(off_exp).get(("bump", mb.Bool), set()),
- f"{sorted(wiring(imu_nav).get(('bump', mb.Bool), set()))}")
-check("imu: MossRealSense out -> BumpImu in (and the odometry's In)",
- {("MossRealSense", "out"), ("BumpImu", "in"), ("LidarOdometry", "in")} <= w.get(("imu", Imu), set()),
+check("bump_rear (a contact behind): BumpImu out -> the planner in, and nobody else (a rear contact is not a "
+ "front wall: no costmap, no sounds)",
+ rear_side == {("BumpImu", "out"), ("RecoveringPlanner", "in")}, f"{sorted(rear_side)}")
+check("stall: the coordinator out -> the planner in (abandon, no motion), and nobody else",
+ stall_side == {("MossControlCoordinator", "out"), ("RecoveringPlanner", "in")}, f"{sorted(stall_side)}")
+check("... one stream type per name: bump, bump_rear and stall are each the bus's Bool and nothing else",
+ sorted(k for k in w if k[0] in ("bump", "bump_rear", "stall"))
+ == sorted([("bump", mb.Bool), ("bump_rear", mb.Bool), ("stall", mb.Bool)]),
+ f"{[k for k in w if k[0] in ('bump', 'bump_rear', 'stall')]}")
+off_w = wiring(off_exp)
+check("moss-nav: bump reaches the odometry and the costmap; MOSS_IMU=0 moss-explore: no bump_rear producer, the "
+ "explorer still on bump, the coordinator's stall still reaches the planner",
+ {("LidarOdometry", "in"), ("MossCostMap", "in")} <= wiring(imu_nav).get(("bump", mb.Bool), set())
+ and {o for o in off_w.get(("bump", mb.Bool), set()) if o[1] == "out"} == {("Explorer2", "out")}
+ and not any(o[1] == "out" for o in off_w.get(("bump_rear", mb.Bool), set()))
+ and {("MossControlCoordinator", "out"), ("RecoveringPlanner", "in")} <= off_w.get(("stall", mb.Bool), set()),
+ f"{sorted(off_w.get(('bump', mb.Bool), set()))} {sorted(off_w.get(('bump_rear', mb.Bool), set()))}")
+check("imu: the camera out -> BumpImu in (and the odometry's In)",
+ {("DedicatedMossRealSense", "out"), ("BumpImu", "in"), ("LidarOdometry", "in")} <= w.get(("imu", Imu), set()),
f"{sorted(w.get(('imu', Imu), set()))}")
check("base_telemetry: the coordinator out -> BumpImu in",
{("MossControlCoordinator", "out"), ("BumpImu", "in")} <= w.get(("base_telemetry", String), set()))
@@ -600,7 +633,9 @@ except ValueError as exc:
check("dimOS's stream type check accepts both MOSS_IMU builds", False, str(exc)[:300])
check("moss-nav with MOSS_IMU=1: bump reaches the costmap (no planner there)",
{("BumpImu", "out"), ("MossCostMap", "in")} <= wiring(imu_nav).get(("bump", mb.Bool), set()))
-check("MOSS_IMU=1 (MOSS_GYRO unset): the gyro prior on, from the in-process IMU", atom(imu_nav, "LidarOdometry").kwargs.get("use_gyro_prior") is True)
+check("MOSS_IMU=1 (MOSS_GYRO unset): the gyro prior OFF, the IMU still on for the contacts",
+ atom(imu_nav, "LidarOdometry").kwargs.get("use_gyro_prior") is False
+ and atom(imu_nav, "DedicatedMossRealSense").kwargs.get("enable_imu") is True)
os.environ.update(MOSS_BUMP_ACCEL="6", MOSS_BUMP_AXIS="-z", MOSS_BUMP_DEBOUNCE_S="0.5", MOSS_IMU_LOG="/data/imu.csv", MOSS_GYRO="1")
tuned = mb.build_moss_nav()
for k in ("MOSS_BUMP_ACCEL", "MOSS_BUMP_AXIS", "MOSS_BUMP_DEBOUNCE_S", "MOSS_IMU_LOG", "MOSS_GYRO"):
@@ -609,12 +644,13 @@ check("MOSS_BUMP_ACCEL=6 MOSS_BUMP_AXIS=-z MOSS_BUMP_DEBOUNCE_S=0.5 MOSS_IMU_LOG
atom(tuned, "BumpImu").kwargs == {"axis": "-z", "threshold": 6.0, "debounce_s": 0.5, "log_path": "/data/imu.csv"},
f"{atom(tuned, 'BumpImu').kwargs}")
check("MOSS_IMU=1 MOSS_GYRO=1: the gyro prior rides the in-process IMU (MossRealSense, prior on)",
- atom(tuned, "MossRealSense").kwargs.get("enable_imu") is True and atom(tuned, "LidarOdometry").kwargs.get("use_gyro_prior") is True)
+ atom(tuned, "DedicatedMossRealSense").kwargs.get("enable_imu") is True
+ and atom(tuned, "LidarOdometry").kwargs.get("use_gyro_prior") is True)
os.environ["MOSS_CAMERA"] = "0"
nocam = mb.build_moss_nav()
os.environ.pop("MOSS_CAMERA")
check("MOSS_IMU=1 MOSS_CAMERA=0: no camera, so no BumpImu either (refused with a warning)",
- not ({"MossRealSense", "RealSenseCamera", "BumpImu"} & names(nocam)), f"{sorted(names(nocam))}")
+ not ({"DedicatedMossRealSense", "DedicatedRealSenseCamera", "BumpImu"} & names(nocam)), f"{sorted(names(nocam))}")
os.environ.pop("MOSS_IMU")
# ── K. MOSS_GYRO: the gyro as the rotation prior ──────────────────────────
@@ -664,26 +700,48 @@ def gyro_lines(lines, level="warning"):
return [text for lvl, text in lines if "MOSS_GYRO" in text and level in (None, lvl)]
+HINT = "MOSS blueprint: lidar odometry prior: gyro=False (run tools/gyro_sign_bench.py once, then MOSS_GYRO=1)"
+PRIOR_ON = "MOSS blueprint: lidar odometry prior: gyro=True (MOSS_GYRO=1)"
+
+
+def prior_lines(lines):
+ """The (level, text) of the 'lidar odometry prior' lines."""
+ return [(lvl, text) for lvl, text in lines if "lidar odometry prior" in text]
+
+
for builder, label, default_bp in ((mb.build_moss_nav, "moss-nav", nav), (mb.build_moss_explore, "moss-explore", exp)):
bp, log = build_logged(builder)
- cam_k = find(bp, "MossRealSense")
- check(f"{label}, every switch unset: use_gyro_prior True on MossRealSense with enable_imu True, no MOSS_GYRO line",
- prior(bp) is True and cam_k is not None and cam_k.kwargs.get("enable_imu") is True
- and "RealSenseCamera" not in names(bp) and not gyro_lines(log, None), f"{prior(bp)} {gyro_lines(log, None)}")
+ cam_k = find(bp, "DedicatedMossRealSense")
+ check(f"{label}, every switch unset: use_gyro_prior FALSE (off until its sign is measured), the camera keeps "
+ "enable_imu True for the contacts, no MOSS_GYRO warning",
+ prior(bp) is False and cam_k is not None and cam_k.kwargs.get("enable_imu") is True
+ and "DedicatedRealSenseCamera" not in names(bp) and not gyro_lines(log), f"{prior(bp)} {gyro_lines(log, None)}")
+ check(f"{label}: ... one info line: '{HINT}'", prior_lines(log) == [("info", HINT)], f"{prior_lines(log)}")
check(f"{label}: the same blueprint as built in G, kwarg for kwarg", blueprint_text(bp) == blueprint_text(default_bp))
+for builder, label in ((mb.build_moss_nav, "moss-nav"), (mb.build_moss_explore, "moss-explore")):
+ bp, log = build_logged(builder, MOSS_GYRO="1")
+ cam_k = find(bp, "DedicatedMossRealSense")
+ check(f"{label}, MOSS_GYRO=1: use_gyro_prior True on the in-process IMU (enable_imu True, BumpImu there), "
+ "no MOSS_GYRO warning, the info line says gyro=True",
+ prior(bp) is True and cam_k is not None and cam_k.kwargs.get("enable_imu") is True and "BumpImu" in names(bp)
+ and not gyro_lines(log) and prior_lines(log) == [("info", PRIOR_ON)], f"{prior(bp)} {prior_lines(log)}")
+ check(f"{label}, MOSS_GYRO=1: its imu reaches the odometry's In",
+ {("DedicatedMossRealSense", "out"), ("LidarOdometry", "in")} <= wiring(bp).get(("imu", Imu), set()))
for spelled_off, builder in (("0", mb.build_moss_nav), ("off", mb.build_moss_explore)):
bp, log = build_logged(builder, MOSS_GYRO=spelled_off)
- cam_k = find(bp, "MossRealSense")
- check(f"MOSS_GYRO={spelled_off}: use_gyro_prior False, and the contacts stay (MossRealSense enable_imu True, BumpImu)",
+ cam_k = find(bp, "DedicatedMossRealSense")
+ check(f"MOSS_GYRO={spelled_off}: the same as unset: use_gyro_prior False, the contacts stay (enable_imu True, BumpImu), "
+ "the info line points to the bench",
prior(bp) is False and cam_k is not None and cam_k.kwargs.get("enable_imu") is True
- and "BumpImu" in names(bp) and not gyro_lines(log, None), f"{prior(bp)} {sorted(names(bp))}")
+ and "BumpImu" in names(bp) and not gyro_lines(log) and prior_lines(log) == [("info", HINT)],
+ f"{prior(bp)} {sorted(names(bp))}")
bp, log = build_logged(mb.build_moss_nav, MOSS_IMU="0")
-cam_k = find(bp, "RealSenseCamera")
+cam_k = find(bp, "DedicatedRealSenseCamera")
check("MOSS_IMU=0 alone: use_gyro_prior False, dimOS's camera with enable_imu False, no MOSS_GYRO line (the default follows quietly)",
prior(bp) is False and cam_k is not None and cam_k.kwargs.get("enable_imu") is False
- and "MossRealSense" not in names(bp) and not gyro_lines(log, None), f"{prior(bp)} {gyro_lines(log, None)}")
+ and "DedicatedMossRealSense" not in names(bp) and not gyro_lines(log, None), f"{prior(bp)} {gyro_lines(log, None)}")
bp, log = build_logged(mb.build_moss_nav, MOSS_IMU="0", MOSS_GYRO="1")
-cam_k = find(bp, "RealSenseCamera")
+cam_k = find(bp, "DedicatedRealSenseCamera")
warned = gyro_lines(log)
check("MOSS_IMU=0 MOSS_GYRO=1: refused, use_gyro_prior False, dimOS's camera keeps enable_imu False",
prior(bp) is False and cam_k is not None and cam_k.kwargs.get("enable_imu") is False, f"{prior(bp)}")
@@ -693,14 +751,14 @@ check("... with one line at warning level that says refused and names MOSS_IMU=1
f"{warned}")
for builder, label in ((mb.build_moss_nav, "moss-nav"), (mb.build_moss_explore, "moss-explore")):
bp, log = build_logged(builder, MOSS_IMU="0", MOSS_GYRO="1", MOSS_GYRO_FORCE="1")
- cam_k = find(bp, "RealSenseCamera")
+ cam_k = find(bp, "DedicatedRealSenseCamera")
warned = gyro_lines(log)
check(f"{label}, MOSS_IMU=0 MOSS_GYRO=1 MOSS_GYRO_FORCE=1: dimOS's own camera with enable_imu True, use_gyro_prior True, no BumpImu",
- cam_k is not None and cam_k.module is RealSenseCamera and cam_k.kwargs.get("enable_imu") is True
+ cam_k is not None and cam_k.module.__mro__[1] is RealSenseCamera and cam_k.kwargs.get("enable_imu") is True
and "imu_hz" not in cam_k.kwargs and prior(bp) is True
- and not ({"MossRealSense", "BumpImu"} & names(bp)), f"{prior(bp)} {sorted(names(bp))}")
+ and not ({"DedicatedMossRealSense", "BumpImu"} & names(bp)), f"{prior(bp)} {sorted(names(bp))}")
check(f"{label}: ... its imu reaches the odometry's In, and one line at warning level calls it an experiment",
- {("RealSenseCamera", "out"), ("LidarOdometry", "in")} <= wiring(bp).get(("imu", Imu), set())
+ {("DedicatedRealSenseCamera", "out"), ("LidarOdometry", "in")} <= wiring(bp).get(("imu", Imu), set())
and len(warned) == 1 == len(gyro_lines(log, None)) and "experiment" in warned[0],
f"{sorted(wiring(bp).get(('imu', Imu), set()))} {warned}")
try:
@@ -709,22 +767,58 @@ for builder, label in ((mb.build_moss_nav, "moss-nav"), (mb.build_moss_explore,
except ValueError as exc:
check(f"{label}: dimOS's stream type check accepts the forced build", False, str(exc)[:300])
bp, log = build_logged(mb.build_moss_nav, MOSS_GYRO_FORCE="1")
-check("MOSS_GYRO_FORCE=1 alone changes nothing: the default blueprint, no MOSS_GYRO line",
- blueprint_text(bp) == blueprint_text(nav) and not gyro_lines(log, None), f"{gyro_lines(log, None)}")
+check("MOSS_GYRO_FORCE=1 alone changes nothing: the default blueprint, no MOSS_GYRO warning, the default's info line",
+ blueprint_text(bp) == blueprint_text(nav) and not gyro_lines(log) and prior_lines(log) == [("info", HINT)],
+ f"{gyro_lines(log, None)}")
bp, log = build_logged(mb.build_moss_nav, MOSS_IMU="0", MOSS_GYRO="0", MOSS_GYRO_FORCE="1")
check("MOSS_IMU=0 MOSS_GYRO=0 MOSS_GYRO_FORCE=1: the force never turns the prior on by itself (enable_imu False)",
- prior(bp) is False and find(bp, "RealSenseCamera").kwargs.get("enable_imu") is False and not gyro_lines(log, None))
+ prior(bp) is False and find(bp, "DedicatedRealSenseCamera").kwargs.get("enable_imu") is False
+ and not gyro_lines(log, None))
for force in ("0", "1"):
bp, log = build_logged(mb.build_moss_nav, MOSS_CAMERA="0", MOSS_GYRO="1", MOSS_GYRO_FORCE=force)
warned = gyro_lines(log)
check(f"MOSS_CAMERA=0 MOSS_GYRO=1 MOSS_GYRO_FORCE={force}: no camera, no prior, one line at warning level: MOSS_GYRO needs the RealSense",
- prior(bp) is False and not ({"RealSenseCamera", "MossRealSense"} & names(bp))
+ prior(bp) is False and not ({"DedicatedRealSenseCamera", "DedicatedMossRealSense"} & names(bp))
and len(warned) == 1 == len(gyro_lines(log, None)) and "needs the RealSense" in warned[0], f"{prior(bp)} {warned}")
bp, log = build_logged(mb.build_moss_nav, MOSS_CAMERA="0")
check("MOSS_CAMERA=0 alone: no prior, and no MOSS_GYRO line (nothing was asked)", prior(bp) is False and not gyro_lines(log, None))
check("every MOSS_GYRO* variable is gone from the environment after the builds",
not [k for k in os.environ if k.startswith("MOSS_GYRO") or k in ("MOSS_IMU", "MOSS_CAMERA")])
+# ── L. every camera in a worker of its own ───────────────────────────────
+print("L. own workers: the RealSense with and without the IMU, the wrist camera")
+import inspect # noqa: E402
+from dimos.core.coordination.blueprints import BlueprintAtom # noqa: E402
+
+
+def streams_of(cls):
+ return {(r.name, r.type, r.direction) for r in BlueprintAtom.create(cls, {}).streams}
+
+
+nose_cls, stock_cls = mb.DedicatedMossRealSense, mb.DedicatedRealSenseCamera
+check("the RealSense with the IMU runs in its own worker: dedicated_worker True in moss-nav and moss-explore",
+ atom(nav, "DedicatedMossRealSense").module.dedicated_worker is True
+ and atom(exp, "DedicatedMossRealSense").module.dedicated_worker is True)
+check(" ... without the IMU (MOSS_IMU=0, dimOS's own camera) too",
+ atom(off_nav, "DedicatedRealSenseCamera").module.dedicated_worker is True
+ and atom(off_exp, "DedicatedRealSenseCamera").module.dedicated_worker is True)
+check(" ... and the wrist camera (cv2 capture and JPEG at 5 fps)",
+ atom(nav, "WristCamera").module.dedicated_worker is True and mb.WristCamera.dedicated_worker is True)
+check("each RealSense class is its base plus the flag: the same streams, the same RPCs, no method of its own",
+ nose_cls.__mro__[1] is MossRealSense and stock_cls.__mro__[1] is RealSenseCamera
+ and streams_of(nose_cls) == streams_of(MossRealSense) and streams_of(stock_cls) == streams_of(RealSenseCamera)
+ and set(nose_cls.rpcs) == set(MossRealSense.rpcs) and set(stock_cls.rpcs) == set(RealSenseCamera.rpcs)
+ and vars(nose_cls).get("dedicated_worker") is True and vars(stock_cls).get("dedicated_worker") is True
+ and not any(inspect.isfunction(v) for c in (nose_cls, stock_cls) for v in vars(c).values()))
+check("the base classes are untouched (no class-wide patch): MossRealSense and RealSenseCamera keep dedicated_worker False",
+ MossRealSense.dedicated_worker is False and RealSenseCamera.dedicated_worker is False)
+check("the classes are built once: the module attribute is the same object every time",
+ mb.DedicatedMossRealSense is nose_cls and mb.DedicatedRealSenseCamera is stock_cls)
+own_workers = sorted(b.module.__name__ for b in exp.active_blueprints if b.module.dedicated_worker)
+check("moss-explore: five modules in workers of their own: the coordinator, the pad, the lidar, the RealSense, the wrist camera",
+ own_workers == sorted(["MossControlCoordinator", "GamepadTeleop", "RPLidarC1", "DedicatedMossRealSense", "WristCamera"]),
+ f"{own_workers}")
+
pick = run_child("""
import json, pickle, sys
import moss_dimos.blueprints as b
@@ -739,6 +833,28 @@ check("importing moss_dimos.blueprints imports neither bump_imu nor realsense_im
payload_imu = pickle.dumps((MossRealSense, BumpImu))
check("MossRealSense and BumpImu pickle by reference to their modules",
b"moss_dimos.realsense_imu" in payload_imu and b"moss_dimos.bump_imu" in payload_imu)
+own = (mb.DedicatedMossRealSense, mb.DedicatedRealSenseCamera)
+payload_own = pickle.dumps(own)
+check("DedicatedMossRealSense and DedicatedRealSenseCamera pickle by reference to moss_dimos.blueprints and back "
+ "to the same classes (served by the module __getattr__)",
+ b"moss_dimos.blueprints" in payload_own and b"DedicatedMossRealSense" in payload_own
+ and pickle.loads(payload_own) == own)
+own_unp = run_child("""
+ import json, pickle, sys
+ a, b = pickle.loads(sys.stdin.buffer.read())
+ print(json.dumps({"names": [a.__name__, b.__name__], "bases": [f"{c.__mro__[1].__module__}.{c.__mro__[1].__name__}" for c in (a, b)],
+ "dedicated": [a.dedicated_worker, b.dedicated_worker]}))
+""", stdin=payload_own)
+try:
+ got_own = json.loads(last_line(own_unp))
+except ValueError:
+ got_own = {}
+ print(own_unp.stderr.decode(errors="replace")[-600:])
+check("... and unpickle in a clean interpreter, as a dimOS worker does: the same bases, dedicated_worker True",
+ got_own == {"names": ["DedicatedMossRealSense", "DedicatedRealSenseCamera"],
+ "bases": ["moss_dimos.realsense_imu.MossRealSense",
+ "dimos.hardware.sensors.camera.realsense.camera.RealSenseCamera"],
+ "dedicated": [True, True]}, f"{got_own}")
unp = run_child("""
import json, pickle, sys
cam, bump = pickle.loads(sys.stdin.buffer.read())
@@ -802,12 +918,63 @@ os.environ.pop("MOSS_STATE_DIR")
ins = set(MossRecorder.__annotations__) | set(MossRecorder.__mro__[1].__annotations__)
check("MossRecorder records odom, global_costmap, lidar, color_image, wrist_image, cmd_vel, base_telemetry, episode_marker",
{"odom", "global_costmap", "lidar", "color_image", "wrist_image", "cmd_vel", "base_telemetry", "episode_marker"} <= ins)
-check("MossControlCoordinator has the base_telemetry and bump Outs, and no other stream of its own",
- set(MossControlCoordinator.__annotations__) == {"base_telemetry", "bump"}, f"{sorted(MossControlCoordinator.__annotations__)}")
+check("MossControlCoordinator has the base_telemetry and stall Outs, no bump, and no other stream of its own",
+ set(MossControlCoordinator.__annotations__) == {"base_telemetry", "stall"}, f"{sorted(MossControlCoordinator.__annotations__)}")
import moss_dimos.blueprints as _bp_mod # noqa: E402
import moss_dimos.recovering_planner as _rp_mod # noqa: E402
-check("the coordinator's bump carries the SAME Bool class as RecoveringPlanner's (dimOS refuses a blueprint otherwise)",
+check("the coordinator's stall carries the SAME Bool class as RecoveringPlanner's (dimOS refuses a blueprint otherwise)",
_bp_mod.Bool is _rp_mod.Bool, f"{_bp_mod.Bool} vs {_rp_mod.Bool}")
+
+
+class _Out:
+ def __init__(self):
+ self.transport, self.sent = object(), []
+
+ def publish(self, msg):
+ self.sent.append(msg)
+
+
+class _StallingCoordinator:
+ """What _telemetry_loop reads of the coordinator: one adapter whose
+ stall_count goes through `counts`, one value per loop; the loop ends after
+ the last one."""
+ TELEMETRY_PERIOD_S = 0.0
+
+ def __init__(self, counts):
+ import threading
+ self._hardware_lock = threading.Lock()
+ self.adapter = FakeAdapter(dict(v3_line), 0.1)
+ self.adapter.stalled, self.adapter.stall_count = False, 0
+ self._hardware = {"base": type("Hw", (), {"adapter": self.adapter})()}
+ self.base_telemetry, self.stall = _Out(), _Out()
+ self._counts = list(counts)
+
+ @property
+ def _telemetry_running(self):
+ if not self._counts:
+ return False
+ self.adapter.stall_count = self._counts.pop(0)
+ return True
+
+
+import asyncio # noqa: E402
+coord_spy, coord_real = [], mb._logger
+mb._logger = type("Spy", (), {k: (lambda self, msg, *a, _k=k, **kw: coord_spy.append((_k, str(msg))))
+ for k in ("info", "warning", "error", "debug", "exception")})()
+fake_coord = _StallingCoordinator([0, 1, 1, 2])
+try:
+ asyncio.run(MossControlCoordinator._telemetry_loop(fake_coord))
+finally:
+ mb._logger = coord_real
+check("the telemetry loop, stall count 0, 1, 1, 2: four base_telemetry documents and two Bool(True) on stall",
+ len(fake_coord.base_telemetry.sent) == 4
+ and [(type(m), m.data) for m in fake_coord.stall.sent] == [(mb.Bool, True), (mb.Bool, True)],
+ f"{len(fake_coord.base_telemetry.sent)} {fake_coord.stall.sent}")
+check("... one warning per new stall: 'base stall #1: publishing stall (the planner stops and abandons the goal, "
+ "no motion)', then #2; nothing else logged (no bump anywhere)",
+ coord_spy == [("warning", "base stall #1: publishing stall (the planner stops and abandons the goal, no motion)"),
+ ("warning", "base stall #2: publishing stall (the planner stops and abandons the goal, no motion)")],
+ f"{coord_spy}")
check("its start/stop overrides keep @rpc (else dimOS pickles the module to call them)",
{"start", "stop"} <= set(MossControlCoordinator.rpcs))
check("it runs in its own worker (dedicated_worker)", MossControlCoordinator.dedicated_worker is True)
diff --git a/benches/bench_recovering_planner_cold.py b/benches/bench_recovering_planner_cold.py
index 65d2e91..a5a5acf 100644
--- a/benches/bench_recovering_planner_cold.py
+++ b/benches/bench_recovering_planner_cold.py
@@ -1,10 +1,13 @@
-"""Cold bench for RecoveringGlobalPlanner.
+"""Cold bench for RecoveringGlobalPlanner and RecoveringPlanner's inputs.
Under test: stuck = goal abandoned, NO recovery motion of any kind (a blind
back-off on every stuck verdict walks the robot into whatever is behind it).
-The only scripted move left is the contact escape (the `bump` stream; on MOSS
-its producer is the explorer's back-off), and a second contact aborts it dead
-instead of being dropped.
+A stall of the base (the `stall` stream) is inferred, not felt: the same,
+goal abandoned and no motion, and a stall during an escape stops it dead.
+The only scripted move left is the contact escape: `bump` (in front: the
+IMU, the explorer's back-off) backs off 0.20 m in reverse, `bump_rear`
+(behind: the IMU while reversing) moves 0.20 m FORWARD, and a second contact
+aborts a running escape dead instead of being dropped.
No robot. A fake local planner integrates the escape twists it receives into
the odometry the planner reads. Needs dimOS and reactivex.
@@ -12,9 +15,11 @@ the odometry the planner reads. Needs dimOS and reactivex.
Run from the repository root: python benches/bench_recovering_planner_cold.py
"""
+import asyncio
import sys
import threading
import time
+import types
from pathlib import Path as _FsPath
sys.path.insert(0, str(_FsPath(__file__).resolve().parent.parent))
@@ -26,7 +31,9 @@ from dimos.msgs.geometry_msgs.PoseStamped import PoseStamped # noqa: E402
from dimos.msgs.geometry_msgs.Twist import Twist # noqa: E402
from dimos.msgs.geometry_msgs.Vector3 import Vector3 # noqa: E402
from dimos.msgs.nav_msgs.Path import Path # noqa: E402
-from moss_dimos.recovering_planner import RecoveringGlobalPlanner # noqa: E402
+from dimos_lcm.std_msgs import Bool # noqa: E402
+import moss_dimos.recovering_planner as rp_mod # noqa: E402
+from moss_dimos.recovering_planner import RecoveringGlobalPlanner, RecoveringPlanner # noqa: E402
FOLLOWER_SPEED_MPS = 0.30 # what the fake follower puts on cmd_vel once started
@@ -174,9 +181,9 @@ def test_escape_moves_away_then_abandons() -> None:
def test_escape_times_out_when_not_moving() -> None:
planner, fake = make_planner(moves=False)
planner.escape_timeout_s = 1.0
- assert planner.escape(direction=+1.0, trigger="bench") is True
+ assert planner.escape(direction=+1.0, trigger="bump_rear") is True
wait_escape_done(planner)
- assert all(tw.linear.x >= 0.0 for tw in fake.sent), "a forward escape only drives forward"
+ assert all(tw.linear.x >= 0.0 for tw in fake.sent), "a rear bump escapes FORWARD"
assert fake.sent[-1].linear.x == 0.0
print(" blocked escape times out and ends with a zero twist")
@@ -187,7 +194,7 @@ def test_second_contact_aborts_the_escape() -> None:
t0 = time.perf_counter()
assert planner.escape(direction=-1.0, trigger="bump") is True
time.sleep(0.15)
- assert planner.escape(direction=+1.0, trigger="bump") is False, \
+ assert planner.escape(direction=+1.0, trigger="bump_rear") is False, \
"a second contact must ABORT, not start a new scripted move"
wait_escape_done(planner)
dt = time.perf_counter() - t0
@@ -276,6 +283,176 @@ def test_a_plan_racing_the_escape_start_never_leaves_the_follower_running() -> N
print(" plan racing an escape -> follower never left running, goal held")
+class LogSpy:
+ """Stands in for the planner module's logger: (level, event, fields)."""
+
+ def __init__(self):
+ self.lines = []
+
+ def _at(level):
+ def record(self, event, *args, **kwargs):
+ self.lines.append((level, str(event), kwargs))
+ return record
+
+ info, warning, error, debug, exception = _at("info"), _at("warning"), _at("error"), _at("debug"), _at("exception")
+ del _at
+
+ def events(self, prefix):
+ return [(event, fields) for _, event, fields in self.lines if event.startswith(prefix)]
+
+
+def with_log(fn):
+ spy, real = LogSpy(), rp_mod.logger
+ rp_mod.logger = spy
+ try:
+ return fn(spy)
+ finally:
+ rp_mod.logger = real
+
+
+def module_on(planner):
+ """The RecoveringPlanner handlers on this planner, without the dimOS module
+ machinery: the handlers only use self._planner."""
+ return types.SimpleNamespace(_planner=planner)
+
+
+def test_the_module_has_the_three_inputs() -> None:
+ ann = RecoveringPlanner.__annotations__
+ assert {"bump", "bump_rear", "stall"} <= set(ann), sorted(ann)
+ for name in ("bump", "bump_rear", "stall"):
+ assert getattr(ann[name], "__args__", (None,))[0] is Bool, (name, ann[name])
+ assert all(callable(getattr(RecoveringPlanner, f"handle_{n}", None)) for n in ("bump", "bump_rear", "stall"))
+ print(" RecoveringPlanner: In bump, In bump_rear, In stall (dimos_lcm Bool), one handler each")
+
+
+def test_front_contact_backs_off_in_reverse() -> None:
+ planner, fake = make_planner(moves=True)
+ planner._current_goal = PoseStamped(position=Vector3(4.0, 1.0, 0.0))
+
+ def go(spy):
+ asyncio.run(RecoveringPlanner.handle_bump(module_on(planner), Bool(data=True)))
+ wait_escape_done(planner)
+ return spy.events("BUMP received")
+ got = with_log(go)
+ assert got == [("BUMP received: front contact", {"reflex": "escape reverse 0.20 m", "acted": True})], got
+ assert fake.sent and all(tw.linear.x <= 0.0 for tw in fake.sent), "a front contact escapes in REVERSE"
+ moved = 2.0 - planner._current_odom.position.x
+ assert 0.19 <= moved <= 0.30, moved
+ assert planner._current_goal is None
+ print(f" bump -> 'BUMP received: front contact', {moved:.2f} m in reverse, goal abandoned")
+
+
+def test_rear_contact_escapes_forward() -> None:
+ planner, fake = make_planner(moves=True)
+ failed = []
+ planner.goal_reached.subscribe(lambda b: failed.append(bool(b.data)))
+ planner._current_goal = PoseStamped(position=Vector3(4.0, 1.0, 0.0))
+
+ def go(spy):
+ asyncio.run(RecoveringPlanner.handle_bump_rear(module_on(planner), Bool(data=True)))
+ wait_escape_done(planner)
+ return spy.events("BUMP received"), spy.events("Contact escape")
+ bumps, escapes = with_log(go)
+ assert bumps == [("BUMP received: rear contact", {"reflex": "escape forward 0.20 m", "acted": True})], bumps
+ assert fake.sent and all(tw.linear.x >= 0.0 for tw in fake.sent), "a rear contact escapes FORWARD, never in reverse"
+ moved = planner._current_odom.position.x - 2.0
+ assert 0.19 <= moved <= 0.30, moved
+ assert len(escapes) == 1 and escapes[0][1]["trigger"] == "bump_rear" and escapes[0][1]["direction"] == "forward", escapes
+ assert planner._current_goal is None and failed == [False], "a rear contact abandons the goal too"
+ print(f" bump_rear -> 'BUMP received: rear contact', {moved:.2f} m FORWARD, goal abandoned")
+
+
+def test_a_false_message_does_nothing() -> None:
+ planner, fake = make_planner(moves=True)
+ planner._current_goal = PoseStamped(position=Vector3(4.0, 1.0, 0.0))
+ for handler in (RecoveringPlanner.handle_bump, RecoveringPlanner.handle_bump_rear, RecoveringPlanner.handle_stall):
+ asyncio.run(handler(module_on(planner), Bool(data=False)))
+ assert fake.sent == [] and not planner._escaping and planner._current_goal is not None
+ print(" Bool(False) on bump / bump_rear / stall -> nothing")
+
+
+def test_stall_abandons_the_goal_without_any_motion() -> None:
+ planner, fake = make_planner(moves=True)
+ failed = []
+ planner.goal_reached.subscribe(lambda b: failed.append(bool(b.data)))
+ planner._current_goal = PoseStamped(position=Vector3(4.0, 1.0, 0.0))
+ planner._path_started_at = time.perf_counter() - 30.0
+
+ def go(spy):
+ asyncio.run(RecoveringPlanner.handle_stall(module_on(planner), Bool(data=True)))
+ time.sleep(0.3) # an escape would have written twists by now
+ return spy.events("Goal abandoned"), spy.events("STALL received")
+ abandoned, stalls = with_log(go)
+ assert fake.sent == [] and not planner._escaping, "a stall must not command ANY motion"
+ assert planner._current_goal is None and failed == [False], "the goal is abandoned (the explorer excludes the spot)"
+ assert abandoned == [("Goal abandoned, no recovery motion", {"trigger": "stall"})], abandoned
+ assert stalls == [("STALL received", {"reflex": "stop, goal abandoned, no motion", "acted": True})], stalls
+ assert planner._path_started_at == float("inf")
+ print(" stall -> zero twists, 'Goal abandoned, no recovery motion' (trigger stall), goal_reached=False")
+
+
+def test_stall_without_a_goal_gives_nothing_up() -> None:
+ planner, fake = make_planner(moves=True)
+ failed = []
+ planner.goal_reached.subscribe(lambda b: failed.append(bool(b.data)))
+
+ def go(spy):
+ acted = planner.stall(trigger="stall")
+ return acted, spy.events("Goal abandoned")
+ acted, abandoned = with_log(go)
+ assert acted is False and abandoned == [] and failed == [] and fake.sent == []
+ print(" stall with no goal (the pad was driving) -> nothing cancelled, no line")
+
+
+def test_stall_during_an_escape_stops_it_dead_and_drops_the_held_goal() -> None:
+ planner, fake = make_planner(moves=False) # wedged: the escape would run its full timeout
+ plannable(planner)
+ failed = []
+ planner.goal_reached.subscribe(lambda b: failed.append(bool(b.data)))
+ planner._current_goal = PoseStamped(position=Vector3(4.0, 1.0, 0.0))
+ planner.escape_timeout_s = 5.0
+ assert planner.escape(direction=-1.0, trigger="bump") is True
+ time.sleep(0.2)
+ planner.handle_goal_request(PoseStamped(position=Vector3(6.0, 1.0, 0.0))) # held by the escape
+ assert planner._held_goal is not None
+ t0 = time.perf_counter()
+
+ def go(spy): # through the module's handler, the path the coordinator's `stall` takes
+ asyncio.run(RecoveringPlanner.handle_stall(module_on(planner), Bool(data=True)))
+ wait_escape_done(planner)
+ return spy.events("STALL received"), spy.events("Stall during an escape"), spy.events("Contact escape")
+ stalls, dead, escapes = with_log(go)
+ dt = time.perf_counter() - t0
+ assert stalls == [("STALL received", {"reflex": "stop, goal abandoned, no motion", "acted": True})], stalls
+ assert dead == [("Stall during an escape: stopping dead", {"trigger": "stall"})], dead
+ assert dt < 1.0, f"the stall must stop the escape at once, took {dt:.1f} s"
+ assert fake.sent[-1].linear.x == 0.0, "the wheels end at zero"
+ assert len(escapes) == 1 and escapes[0][1]["aborted"] is True, escapes
+ time.sleep(0.2)
+ assert fake.starts == 0 and planner._held_goal is None, "the held goal is dropped, never planned"
+ assert planner._current_goal is None and False in failed
+ print(f" stall (handle_stall) during an escape -> stopped dead after {dt:.2f} s, held goal dropped, nothing planned")
+
+
+def test_a_rear_contact_during_a_front_escape_stops_it_dead() -> None:
+ planner, fake = make_planner(moves=False)
+ planner.escape_timeout_s = 5.0
+ asyncio.run(RecoveringPlanner.handle_bump(module_on(planner), Bool(data=True)))
+ time.sleep(0.15)
+ t0 = time.perf_counter()
+
+ def go(spy):
+ asyncio.run(RecoveringPlanner.handle_bump_rear(module_on(planner), Bool(data=True)))
+ wait_escape_done(planner)
+ return spy.events("BUMP received"), spy.events("Contact during an escape")
+ bumps, dead = with_log(go)
+ assert bumps == [("BUMP received: rear contact", {"reflex": "escape forward 0.20 m", "acted": False})], bumps
+ assert dead == [("Contact during an escape: stopping dead", {"trigger": "bump_rear"})], dead
+ assert time.perf_counter() - t0 < 1.0 and fake.sent[-1].linear.x == 0.0
+ assert all(tw.linear.x <= 0.0 for tw in fake.sent), "nothing moves forward: the rear contact only stops the reverse"
+ print(" bump then bump_rear during the reverse -> stopped dead, logged acted=False, never a forward move")
+
+
if __name__ == "__main__":
for t in (test_stuck_abandons_goal_without_any_motion,
test_stuck_needs_a_driven_path_and_ignores_rotation,
@@ -285,6 +462,14 @@ if __name__ == "__main__":
test_stuck_is_silent_during_an_escape,
test_goal_during_an_escape_is_held_then_planned,
test_goal_outside_an_escape_is_planned_at_once,
- test_a_plan_racing_the_escape_start_never_leaves_the_follower_running):
+ test_a_plan_racing_the_escape_start_never_leaves_the_follower_running,
+ test_the_module_has_the_three_inputs,
+ test_front_contact_backs_off_in_reverse,
+ test_rear_contact_escapes_forward,
+ test_a_false_message_does_nothing,
+ test_stall_abandons_the_goal_without_any_motion,
+ test_stall_without_a_goal_gives_nothing_up,
+ test_stall_during_an_escape_stops_it_dead_and_drops_the_held_goal,
+ test_a_rear_contact_during_a_front_escape_stops_it_dead):
print(t.__name__); t()
print("TEST PASSED")
diff --git a/benches/bench_robot_profile_cold.py b/benches/bench_robot_profile_cold.py
index 4433eb8..ff8442f 100644
--- a/benches/bench_robot_profile_cold.py
+++ b/benches/bench_robot_profile_cold.py
@@ -12,6 +12,15 @@ Known input -> known output in physical units. Groups:
C. devices - by-id resolution of the QT Py and the CP2102N lidar bridge,
the sentinels, the env overrides, the absolute state dir;
env_on, the one parser of the MOSS_* on/off switches
+ S. the speed - tools/speed_guard.py: the speed comes from the LOG's own
+ guard timestamps, one interval over the profile's 0.45 m/s ceiling
+ is a kill (exploration stop, then the stack down), the
+ planner's 0.385 m/s cruise is not, a ceiling at or under that
+ cruise is refused, a run that is over makes the watchdog stand
+ down, the pid file is ours
+ T. arming - tools/arm_speed_guard.sh REPLACES the previous run's
+ watchdog (killed by its pid, the new one proven born after the
+ launch), and refuses without that proof or below the cruise
L. the log - outside dimOS the warnings go to the stdlib logger (stderr)
and dimOS is never imported; inside a dimOS process they
land in the run's main.jsonl (subprocess; needs dimOS)
@@ -24,7 +33,8 @@ Known input -> known output in physical units. Groups:
lidar lift and depth projection follow the profile
A-C need nothing. L needs dimOS for its main.jsonl half (SKIPPED with a line
-without it). D and E import the modules: with dimOS when it is there, else
+without it). S and T need dimos_lcm (tools/explore_ctl.py imports it; SKIPPED
+with a line without it) and Linux's /proc. D and E import the modules: with dimOS when it is there, else
behind a stand-in for every dimOS name - the functions under test are pure
numpy and never touch dimOS objects. A reader module that does not import,
or lacks a function under test, is a KO.
@@ -41,6 +51,7 @@ import importlib.machinery
import logging
import math
import os
+import re
import subprocess
import sys
import tempfile
@@ -112,6 +123,7 @@ check("width 0.34, pivot 0.50, margin 0.05, track 0.266 m",
(M.robot_width_m, M.pivot_diameter_m, M.control_margin_m, M.track_m) == (0.34, 0.50, 0.05, 0.266))
check("camera (0.156, 0, 0.075) m, pitch 0",
M.camera_xyz_base_m == (0.156, 0.0, 0.075) and M.camera_pitch_deg == 0.0)
+check("speed ceiling 0.45 m/s (tools/speed_guard.py's limit)", M.max_speed_mps == 0.45)
dm = rp.derived(M)
check("lethal clearance 0.22 m, pivot clearance 0.25 m",
close(dm.lethal_clearance_m, 0.22) and close(dm.pivot_clearance_m, 0.25),
@@ -122,8 +134,8 @@ fields = {f.name for f in dataclasses.fields(rp.RobotProfile)}
want = {"name", "lidar_height_m", "lidar_yaw_offset_deg", "scan_min_range_m",
"scan_mask_sectors_deg", "scan_mask_range_m", "body_box_m", "body_clear_m",
"robot_width_m", "pivot_diameter_m", "control_margin_m", "track_m",
- "camera_xyz_base_m", "camera_pitch_deg"}
-check("RobotProfile holds exactly the 14 fields MOSS reads", fields == want,
+ "camera_xyz_base_m", "camera_pitch_deg", "max_speed_mps"}
+check("RobotProfile holds exactly the 15 fields MOSS reads", fields == want,
f"extra {sorted(fields - want)}, missing {sorted(want - fields)}")
check("every numeric field has its MOSS_* override",
set(rp._MOSS_ENV) == want - {"name"}, f"{sorted(set(rp._MOSS_ENV) ^ (want - {'name'}))}")
@@ -179,6 +191,11 @@ os.environ["MOSS_LIDAR_HEIGHT_M"] = "nan"
check("MOSS_LIDAR_HEIGHT_M=nan -> placeholder kept (finite numbers only)", rp.current().lidar_height_m == 0.20)
os.environ["MOSS_LIDAR_HEIGHT_M"] = "0.215"
check("MOSS_LIDAR_HEIGHT_M=0.215 -> 0.215 m", rp.current().lidar_height_m == 0.215)
+os.environ["MOSS_MAX_SPEED_MPS"] = "0.5"
+check("MOSS_MAX_SPEED_MPS=0.5 -> a 0.50 m/s ceiling, read now", rp.current().max_speed_mps == 0.5)
+os.environ["MOSS_MAX_SPEED_MPS"] = "fast"
+check("MOSS_MAX_SPEED_MPS=fast -> placeholder 0.45 kept", rp.current().max_speed_mps == 0.45)
+os.environ.pop("MOSS_MAX_SPEED_MPS", None)
check("an explicit env dict wins over os.environ",
rp.current({"MOSS_LIDAR_HEIGHT_M": "0.30"}).lidar_height_m == 0.30)
clear_env()
@@ -297,6 +314,627 @@ with tempfile.TemporaryDirectory() as _run:
check("... with the placeholder kept (0.2 m)", _ok, "" if _ok else f"stdout {_r.stdout.strip()[-200:]!r}")
+# ── S. the speed guard: tools/speed_guard.py ─────────────────────────────
+print("S. the speed guard: speed from the log's own timestamps, one interval over the profile's ceiling is a kill")
+import importlib.util # noqa: E402
+import io # noqa: E402
+import json # noqa: E402
+from contextlib import redirect_stdout # noqa: E402
+from datetime import datetime, timezone # noqa: E402
+
+clear_env()
+SG = EC = None
+SKIP_GUARD = None
+sys.path.insert(0, str(ROOT / "tools"))
+try:
+ import explore_ctl as EC # noqa: E402
+ import speed_guard as SG # noqa: E402
+except ImportError as exc:
+ if importlib.util.find_spec("dimos_lcm") is None:
+ SKIP_GUARD = f"no dimos_lcm here ({exc}): run this where dimOS is installed"
+ else:
+ check("tools/speed_guard.py imports", False, f"{type(exc).__name__}: {exc}")
+if SKIP_GUARD:
+ print(f" -- SKIP S and T: {SKIP_GUARD}")
+
+T0 = 1_800_000_000.25 # a known epoch, in seconds
+STEP_S = 2.0 # LidarOdometry's log_every_s: the cadence of the odom lines
+ODOM_LOGGER = "/home/x/moss/moss_dimos/lidar_odometry.py"
+
+
+def iso(t):
+ return datetime.fromtimestamp(t, timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z"
+
+
+def odom_line(n, t, x, y):
+ """One line shaped like the robot's own: structlog jsonl, %+.3f positions."""
+ return json.dumps({
+ "event": f"lidar odom #{n}: x={x:+.3f} y={y:+.3f} yaw=+0.0deg (380 pts, 31.0 ms, prior gyro, "
+ "depth cloud 274 pts) | gyro integral x=+0.0 y=-1.1 z=-0.2deg | wheels none",
+ "level": "info", "logger": ODOM_LOGGER, "timestamp": iso(t),
+ "func_name": "handle_pointcloud", "lineno": 535,
+ })
+
+
+def straight_run(speed, steps=5, step_s=STEP_S):
+ """Lines for a body going straight at `speed` m/s, one line every `step_s`."""
+ return [odom_line(20 * i + 1, T0 + i * step_s, i * speed * step_s, 0.0) for i in range(steps + 1)]
+
+
+def one_line(out) -> str:
+ """Captured output on one line, for a check's detail."""
+ text = out.getvalue() if hasattr(out, "getvalue") else str(out)
+ return " / ".join(t for t in text.strip().splitlines() if t)
+
+
+def lines_with(out: str, text: str) -> str:
+ return " / ".join(t for t in out.splitlines() if text in t) or "(none)"
+
+
+if SG is not None:
+ check("the limit is the profile's max_speed_mps: 0.45 m/s", SG.LIMIT_MS == 0.45 == rp.MOSS.max_speed_mps,
+ f"{SG.LIMIT_MS}")
+ check("limit_ms() reads MOSS_MAX_SPEED_MPS (0.5 -> 0.50 m/s)", SG.limit_ms({"MOSS_MAX_SPEED_MPS": "0.5"}) == 0.5)
+
+ # the ceiling against the speed the stack itself commands
+ check("cruise = 0.55 m/s x the launcher's 0.7 = 0.385 m/s (MOSS_NERF_SPEED unset)",
+ abs(SG.cruise_mps({}) - 0.385) < 1e-12, f"{SG.cruise_mps({}):.4f}")
+ check("MOSS_NERF_SPEED=0.5 -> 0.275 m/s; 1.0 (and above, and junk -> the default) as dimOS applies it",
+ abs(SG.cruise_mps({"MOSS_NERF_SPEED": "0.5"}) - 0.275) < 1e-12
+ and SG.cruise_mps({"MOSS_NERF_SPEED": "1.0"}) == 0.55 and SG.cruise_mps({"MOSS_NERF_SPEED": "2"}) == 0.55
+ and abs(SG.cruise_mps({"MOSS_NERF_SPEED": "fast"}) - 0.385) < 1e-12)
+ check("the profile's 0.45 m/s sits above that cruise: armed", SG.ceiling_refusal(0.45, SG.cruise_mps({})) is None)
+ why = SG.ceiling_refusal(0.30, SG.cruise_mps({}))
+ check("a 0.30 m/s ceiling under the 0.385 m/s cruise is refused, and says what to raise",
+ why is not None and "0.385" in why and "MOSS_MAX_SPEED_MPS" in why, str(why))
+ check("a ceiling equal to the cruise is refused too",
+ SG.ceiling_refusal(0.55, SG.cruise_mps({"MOSS_NERF_SPEED": "1"})) is not None)
+ _fly = (ROOT / "tools" / "moss-fly.sh").read_text()
+ _m = re.search(r'NERF_SPEED="\$\{MOSS_NERF_SPEED:-([0-9.]+)\}"', _fly)
+ check("the cruise's default scale is tools/moss-fly.sh's own (NERF_SPEED default)",
+ _m is not None and float(_m.group(1)) == SG.NERF_SPEED_DEFAULT,
+ f"launcher {_m.group(1) if _m else None}, guard {SG.NERF_SPEED_DEFAULT}")
+ _spec = importlib.util.find_spec("dimos")
+ _lp = Path(_spec.origin).parent / "navigation" / "replanning_a_star" / "local_planner.py" if _spec and _spec.origin else None
+ if _lp is None or not _lp.is_file():
+ print(" -- SKIP the planner-speed check: no dimOS source here")
+ else:
+ _speed = None
+ for _node in ast.walk(ast.parse(_lp.read_text())):
+ if isinstance(_node, ast.ClassDef) and _node.name == "LocalPlanner":
+ for _st in _node.body:
+ if (isinstance(_st, ast.AnnAssign) and getattr(_st.target, "id", "") == "_speed"
+ and isinstance(_st.value, ast.Constant)):
+ _speed = _st.value.value
+ check("the cruise's 0.55 m/s is dimOS's own LocalPlanner._speed", _speed == SG.PLANNER_SPEED_MPS,
+ f"dimOS {_speed}, guard {SG.PLANNER_SPEED_MPS}")
+
+ # dating the lines
+ sample = SG.parse_odom(odom_line(1, T0, 0.0, 0.0))
+ check("a real-shaped odom line parses", sample is not None)
+ check(f"its stamp comes back as {T0} s", sample is not None and abs(sample[0] - T0) < 1e-6,
+ f"{sample[0]:.6f}" if sample else "")
+ later = SG.parse_odom(odom_line(21, T0 + STEP_S, 1.0, 0.0))
+ check("two lines 2 s apart -> 2.000 s of log time", abs((later[0] - sample[0]) - 2.0) < 1e-6,
+ f"{later[0] - sample[0]:.6f} s")
+
+ # runaway at 0.5 m/s
+ guard = SG.SpeedGuard()
+ speeds, kills = [], []
+ for i, line in enumerate(straight_run(0.5)):
+ v = guard.feed(line)
+ if v is not None:
+ speeds.append(v)
+ if v > SG.LIMIT_MS:
+ kills.append(i)
+ check("6 lines -> 5 intervals (the first line closes none)", len(speeds) == 5, f"{len(speeds)}")
+ check("every interval measures 0.50 m/s", all(abs(v - 0.5) < 1e-9 for v in speeds),
+ ", ".join(f"{v:.3f}" for v in speeds))
+ check("the SECOND line already breaches (1 interval = 1 kill, ~1 m of runaway)", kills[:1] == [1], f"{kills}")
+ check("no strike counter: all 5 intervals breach", len(kills) == 5, f"{kills}")
+
+ # inside the 0.45 m/s ceiling
+ guard = SG.SpeedGuard()
+ measured = [v for v in (guard.feed(line) for line in straight_run(0.25)) if v is not None]
+ check("0.500 m per 2 s line -> every interval 0.25 m/s", len(measured) == 5 and all(abs(v - 0.25) < 1e-9 for v in measured))
+ guard = SG.SpeedGuard()
+ check("the planner's cruise, 0.385 m/s (0.770 m per line), stays silent",
+ all(guard.breach(line) is None for line in straight_run(0.385)))
+ guard = SG.SpeedGuard()
+ check("0.44 m/s (0.880 m per line) stays silent", all(guard.breach(line) is None for line in straight_run(0.44)))
+ guard = SG.SpeedGuard()
+ check("0.46 m/s (0.920 m per line) kills", any(guard.breach(line) is not None for line in straight_run(0.46)))
+ guard = SG.SpeedGuard(limit=0.50)
+ check("with MOSS_MAX_SPEED_MPS=0.5 the same 0.46 m/s stays silent",
+ all(guard.breach(line) is None for line in straight_run(0.46)))
+
+ # geometry: the chord, sign-free
+ guard = SG.SpeedGuard()
+ guard.feed(odom_line(1, T0, 0.0, 0.0))
+ v = guard.feed(odom_line(21, T0 + STEP_S, 0.6, 0.8))
+ check("dx 0.600 m, dy 0.800 m in 2 s -> 0.50 m/s (the chord, not one axis)", abs(v - 0.5) < 1e-9, f"{v:.6f}")
+ guard = SG.SpeedGuard()
+ guard.feed(odom_line(1, T0, 5.0, -3.0))
+ v = guard.feed(odom_line(21, T0 + STEP_S, 5.0, -3.5))
+ check("0.500 m backwards on y in 2 s -> 0.25 m/s (sign-free)", abs(v - 0.25) < 1e-9, f"{v:.6f}")
+
+ # the cadence: the log's own interval jitters around 2 s
+ gaps = [1.699, 2.4, 3.071, 1.9, 2.0, 2.65, 1.75, 3.0, 2.2, 2.05]
+ lines, t, x = [], T0, 0.0
+ lines.append(odom_line(1, t, x, 0.0))
+ for k, g in enumerate(gaps):
+ t += g; x += 0.149 * g
+ lines.append(odom_line(20 * (k + 1), t, x, 0.0))
+ guard = SG.SpeedGuard()
+ crawl = [v for v in (guard.feed(line) for line in lines) if v is not None]
+ check("a 0.149 m/s crawl with gaps of 1.699 to 3.071 s: all 10 intervals measured",
+ len(crawl) == 10 and all(abs(v - 0.149) < 1e-3 for v in crawl), f"{len(crawl)}: {[round(v, 3) for v in crawl]}")
+ check("(a wall-clock window 0.02 < dt < 2.0 would keep only 3 of them)", sum(1 for g in gaps if 0.02 < g < 2.0) == 3)
+ guard = SG.SpeedGuard()
+ check("and the crawl never trips the 0.45 m/s ceiling", all(guard.breach(line) is None for line in lines))
+
+ # the kill: exploration stop on the bus, then the stack down
+ TMPS = tempfile.TemporaryDirectory()
+ STOP_LOG = Path(TMPS.name) / "stack_stop.log"
+ RECORDER = Path(TMPS.name) / "stack_stop.py"
+ RECORDER.write_text("import os, sys\n"
+ "open(sys.argv[1], 'a').write(os.getcwd() + '\\n')\n"
+ "print('stack down')\n")
+ published = []
+ saved_pub, saved_stop = EC.publish, SG.STACK_STOP
+ try:
+ EC.publish = lambda cmd: published.append(cmd) or f"/{cmd}_explore_cmd#std_msgs.Bool"
+ SG.STACK_STOP = [sys.executable, str(RECORDER), str(STOP_LOG)]
+ out = io.StringIO()
+ with redirect_stdout(out):
+ SG.stop_all()
+ ran = STOP_LOG.read_text().splitlines() if STOP_LOG.exists() else []
+ check("a breach publishes exactly one 'stop' through explore_ctl (the run's bus)",
+ published == ["stop"] and "STOP EXPLORE published on /stop_explore_cmd" in out.getvalue(), one_line(out))
+ check("then runs the stack stop once, from the checkout root (tools/moss-fly.sh stop by default)",
+ ran == [str(ROOT)] and "STACK STOP" in out.getvalue() and "exit 0: stack down" in out.getvalue(),
+ f"{ran}")
+ check("the default stack stop is tools/moss-fly.sh stop",
+ saved_stop == ["tools/moss-fly.sh", "stop"] if "SPEED_GUARD_STACK_STOP" not in os.environ else True,
+ f"{saved_stop}")
+
+ def sick(cmd):
+ raise RuntimeError("bus down")
+
+ EC.publish = sick
+ out = io.StringIO()
+ with redirect_stdout(out):
+ SG.stop_all() # must not raise: the watchdog keeps watching
+ ran = STOP_LOG.read_text().splitlines()
+ check("a failing bus is logged, not fatal, and the stack still goes down",
+ "STOP EXPLORE FAILED: bus down" in out.getvalue() and len(ran) == 2, one_line(out))
+ SG.STACK_STOP = [str(Path(TMPS.name) / "no_such_launcher")]
+ out = io.StringIO()
+ with redirect_stdout(out):
+ SG.stop_all()
+ check("a missing launcher is logged, not fatal", "STACK STOP FAILED" in out.getvalue(), one_line(out)[-120:])
+ finally:
+ EC.publish, SG.STACK_STOP = saved_pub, saved_stop
+
+ # junk invents nothing
+ guard = SG.SpeedGuard()
+ guard.feed(odom_line(1, T0, 0.0, 0.0))
+ check("a non-odom line -> None", guard.feed('{"event": "BUMP received", "timestamp": "' + iso(T0 + 1) + '"}') is None)
+ check("an odom line with no timestamp -> None (no wall clock fallback)",
+ guard.feed("lidar odom #7: x=+9.000 y=+9.000 yaw=+0.0deg") is None)
+ check("tail's '==> file <==' header -> None", guard.feed("==> /tmp/moss_fly_launch.log <==\n") is None)
+ check("a line dated BEFORE the previous one -> None", guard.feed(odom_line(41, T0 - 5.0, 9.0, 9.0)) is None)
+ guard = SG.SpeedGuard()
+ guard.feed(odom_line(1, T0, 0.0, 0.0))
+ check("a repeated line (same stamp, dt = 0) -> None, no division", guard.feed(odom_line(1, T0, 0.0, 0.0)) is None)
+ guard = SG.SpeedGuard()
+ lines = straight_run(0.5)
+ lines.insert(3, '{"event": "costmap tick", "timestamp": "' + iso(T0 + 2.5) + '"}')
+ check("junk between odom lines does not break the chain", sum(1 for line in lines if guard.breach(line) is not None) == 5)
+
+ # standing down (fake clock, fake log tree, fake registry)
+ LOGS = Path(TMPS.name) / "state" / "dimos" / "logs"
+ RUNS = Path(TMPS.name) / "state" / "dimos" / "runs"
+ LOGS.mkdir(parents=True); RUNS.mkdir(parents=True)
+ GLOB, RGLOB = str(LOGS / "*"), str(RUNS / "*.json")
+
+ class Clock:
+ def __init__(self, t=1_000_000.0):
+ self.t = t
+
+ def __call__(self):
+ return self.t
+
+ def make_run(parent, name, lines=1, mtime=None):
+ run = Path(parent) / name
+ run.mkdir(parents=True, exist_ok=True)
+ (run / "main.jsonl").write_text("".join(odom_line(i, T0 + i * STEP_S, 0.0, 0.0) + "\n" for i in range(lines)))
+ if mtime:
+ os.utime(run, (mtime, mtime))
+ return run
+
+ RUN_A = make_run(LOGS, "run-a-moss-dimos-moss-explore", lines=2, mtime=T0)
+ clk = Clock()
+ watch = SG.RunWatch(str(RUN_A), idle_s=30.0, glob_pat=GLOB, clock=clk, runs_glob=RGLOB)
+ check("a fresh watchdog on the live run stays on watch", watch.reason() is None)
+ clk.t += 10.0
+ with open(RUN_A / "main.jsonl", "a") as f:
+ f.write(odom_line(9, T0 + 20.0, 0.1, 0.0) + "\n")
+ check("the log grew: still on watch, the idle clock restarts", watch.reason() is None)
+ clk.t += 29.0
+ check("29 s of silence: still on watch (limit 30 s)", watch.reason() is None)
+ clk.t += 2.0
+ why = watch.reason()
+ check("31 s of silence: stands down, and says so in seconds",
+ why is not None and "has not grown for 31 s (limit 30 s)" in why, str(why))
+ clk = Clock()
+ edge = SG.RunWatch(str(RUN_A), idle_s=30.0, glob_pat=GLOB, clock=clk, runs_glob=RGLOB)
+ clk.t += 29.999
+ check("29.999 s: not yet", edge.reason() is None)
+ clk.t += 0.001
+ check("exactly 30.000 s: retired", edge.reason() is not None)
+ orphan = SG.RunWatch(str(RUN_A), idle_s=1e6, glob_pat=GLOB, clock=Clock(), runs_glob=RGLOB)
+ check("still the newest run: on watch", orphan.reason() is None)
+ RUN_B = make_run(LOGS, "run-b-moss-dimos-moss-explore", lines=1, mtime=T0 + 3600)
+ why = orphan.reason()
+ check("a newer run dir retires the orphan at once (idle limit not even reached)",
+ why is not None and RUN_B.name in why and "newest run" in why, str(why))
+ live = SG.RunWatch(str(RUN_B), idle_s=1e6, glob_pat=GLOB, clock=Clock(), runs_glob=RGLOB)
+ check("the watchdog of the NEWEST run keeps watching", live.reason() is None)
+ # a dimOS from a git clone logs under the clone: only the registry names the dir
+ CLONE = Path(TMPS.name) / "clone" / "logs"
+ RUN_C = make_run(CLONE, "run-c-moss-dimos-moss-explore", lines=1, mtime=T0 + 7200)
+ check("a run dir outside the log root is not seen without its registry entry",
+ str(RUN_C.resolve()) not in SG.run_dirs(GLOB, RGLOB))
+ (RUNS / "run-c.json").write_text(json.dumps({"pid": 1, "blueprint": "moss_dimos.moss-explore", "log_dir": str(RUN_C)}))
+ (RUNS / "half-written.json").write_text('{"pid": 1, "log_')
+ check("with its registry entry it is the newest (a half-written entry is skipped)",
+ SG.run_dirs(GLOB, RGLOB)[-1] == str(RUN_C.resolve()), f"{SG.run_dirs(GLOB, RGLOB)[-1:]}")
+ why = live.reason()
+ check("so a run started from a clone retires the previous watchdog too",
+ why is not None and RUN_C.name in why, str(why))
+ (RUNS / "run-c.json").unlink()
+ mine = SG.RunWatch(str(RUN_C), idle_s=1e6, glob_pat=GLOB, clock=Clock(), runs_glob=RGLOB)
+ check("a watchdog given its run dir (SPEED_GUARD_RUN_DIR) whose registry entry is gone does not retire "
+ "for an OLDER dir", mine.reason() is None)
+ CRASHED = LOGS / "run-d-moss-dimos-moss-explore" # newest run, but the stack died before writing
+ CRASHED.mkdir()
+ os.utime(CRASHED, (T0 + 9000, T0 + 9000))
+ clk = Clock()
+ dead = SG.RunWatch(str(CRASHED), idle_s=30.0, glob_pat=GLOB, clock=clk, runs_glob=RGLOB)
+ check("a newest run dir with no main.jsonl: on watch while the limit runs", dead.reason() is None)
+ clk.t += 30.0
+ why = dead.reason()
+ check("... and retired by the same silence, not left tailing nothing",
+ why is not None and "has not grown for 30 s" in why, str(why))
+ check("defaults: 30 s idle, /tmp/moss_speed_guard.pid",
+ (SG.IDLE_S, SG.PID_FILE) == (30.0, "/tmp/moss_speed_guard.pid")
+ if not (os.environ.get("SPEED_GUARD_IDLE_S") or os.environ.get("SPEED_GUARD_PID_FILE")) else True,
+ f"{SG.IDLE_S} s, {SG.PID_FILE}")
+
+ # the pid file the launcher kills by
+ PID_PATH = str(Path(TMPS.name) / "guard.pid")
+ SG.write_pid_file(PID_PATH)
+ check("write_pid_file stamps our own pid", Path(PID_PATH).read_text().strip() == str(os.getpid()))
+ Path(PID_PATH).write_text("999999\n")
+ SG.clear_pid_file(PID_PATH)
+ check("clear_pid_file leaves a file that names ANOTHER watchdog", Path(PID_PATH).exists())
+ Path(PID_PATH).write_text(f"{os.getpid()}\n")
+ SG.clear_pid_file(PID_PATH)
+ check("and removes it when it names us", not Path(PID_PATH).exists())
+ SG.clear_pid_file(PID_PATH)
+ check("clearing a pid file that is already gone is harmless", not Path(PID_PATH).exists())
+
+ # the real script
+ def guard_env(home, **extra):
+ env = {k: v for k, v in os.environ.items()
+ if not k.startswith(("MOSS_", "SPEED_GUARD_")) and k != "XDG_STATE_HOME"}
+ env.update({"HOME": str(home), "PYTHONPATH": str(ROOT) + os.pathsep + os.environ.get("PYTHONPATH", ""),
+ "PYTHONDONTWRITEBYTECODE": "1", "SPEED_GUARD_PID_FILE": str(Path(home) / "guard.pid"),
+ "SPEED_GUARD_STACK_STOP": f"{sys.executable} {RECORDER} {Path(home) / 'stack_stop.log'}"})
+ env.update({k: str(v) for k, v in extra.items()})
+ return env
+
+ def run_guard(home, timeout_s=30, after_start=None, **extra):
+ """Launch tools/speed_guard.py for real against a fake HOME; returns
+ (returncode, seconds, stdout, stamped pid, pid, pid file)."""
+ env = guard_env(home, **extra)
+ pid_file = env["SPEED_GUARD_PID_FILE"]
+ t0 = time.monotonic()
+ proc = subprocess.Popen([sys.executable, str(ROOT / "tools" / "speed_guard.py")],
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env, cwd=str(ROOT))
+ stamped = None
+ while time.monotonic() - t0 < timeout_s and proc.poll() is None:
+ if Path(pid_file).exists():
+ stamped = Path(pid_file).read_text().strip()
+ break
+ time.sleep(0.05)
+ if after_start:
+ after_start()
+ try:
+ out = proc.communicate(timeout=timeout_s)[0]
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ out = proc.communicate()[0]
+ return proc.returncode, time.monotonic() - t0, out, stamped, proc.pid, pid_file
+
+ HOME1 = Path(TMPS.name) / "orphan_home"
+ LOGS1 = HOME1 / ".local" / "state" / "dimos" / "logs" / "run-a-moss-dimos-moss-explore"
+ LOGS1.mkdir(parents=True)
+ (LOGS1 / "main.jsonl").write_text(odom_line(1, T0, 0.0, 0.0) + "\n") # written once, never again
+ rc, took, out, stamped, pid, pid_file = run_guard(HOME1, SPEED_GUARD_IDLE_S=1.0, SPEED_GUARD_POLL_S=0.2)
+ check("the real script stamped its own pid while running", stamped == str(pid), f"{stamped} vs {pid}")
+ check("it exits by itself on a dead log, rc 0", rc == 0, f"rc {rc} after {took:.1f} s")
+ check("in seconds (idle limit 1 s here, 30 s on the robot)", took < 35.0, f"{took:.1f} s")
+ check("with a clear message naming the silent log", "standing down" in out and "has not grown" in out,
+ out.strip().splitlines()[-1] if out.strip() else "(no output)")
+ check("and it watched with the profile's 0.45 m/s limit, the 0.385 m/s cruise said beside it",
+ "(limit 0.45 m/s, cruise 0.385 m/s commanded" in out, out.strip().splitlines()[0] if out.strip() else "")
+ check("the pid file is cleaned up behind it", not Path(pid_file).exists())
+
+ HOME2 = Path(TMPS.name) / "second_run_home"
+ LOGS2 = HOME2 / ".local" / "state" / "dimos" / "logs"
+ (LOGS2 / "run-a-moss-dimos-moss-explore").mkdir(parents=True)
+ (LOGS2 / "run-a-moss-dimos-moss-explore" / "main.jsonl").write_text(odom_line(1, T0, 0.0, 0.0) + "\n")
+ NEXT_RUN = LOGS2 / "run-b-moss-dimos-moss-explore"
+
+ def start_second_run():
+ NEXT_RUN.mkdir()
+ (NEXT_RUN / "main.jsonl").write_text(odom_line(1, T0 + 3600, 0.0, 0.0) + "\n")
+
+ rc, took, out, stamped, pid, pid_file = run_guard(HOME2, after_start=start_second_run,
+ SPEED_GUARD_IDLE_S=1e6, SPEED_GUARD_POLL_S=0.2)
+ check("the previous run's watchdog retires when the next run starts", rc == 0, f"rc {rc} after {took:.1f} s")
+ check("it names the newer run (idle limit 1e6 s: it cannot be the silence)",
+ NEXT_RUN.name in out and "newest run" in out, out.strip().splitlines()[-1] if out.strip() else "(no output)")
+
+ # a runaway on a live log, end to end: the bus refused (not LCM here), the stack still stopped
+ HOME3 = Path(TMPS.name) / "runaway_home"
+ RUN3 = HOME3 / ".local" / "state" / "dimos" / "logs" / "run-a-moss-dimos-moss-explore"
+ RUN3.mkdir(parents=True)
+ (RUN3 / "main.jsonl").write_text("")
+
+ def runaway():
+ time.sleep(0.5) # the tail is up
+ with open(RUN3 / "main.jsonl", "a") as f:
+ for line in straight_run(0.5, steps=1): # 1.000 m in 2 s of log time
+ f.write(line + "\n")
+ deadline = time.monotonic() + 15
+ while time.monotonic() < deadline and not (HOME3 / "stack_stop.log").exists():
+ time.sleep(0.05)
+ time.sleep(0.3)
+
+ rc, took, out, stamped, pid, pid_file = run_guard(HOME3, after_start=runaway, SPEED_GUARD_IDLE_S=2.0,
+ SPEED_GUARD_POLL_S=0.2, SPEED_GUARD_RUN_DIR=RUN3,
+ DIMOS_TRANSPORT="zenoh")
+ stopped = (HOME3 / "stack_stop.log").read_text().splitlines() if (HOME3 / "stack_stop.log").exists() else []
+ check("a 0.50 m/s interval in the run's log -> the real watchdog says so",
+ "0.50 m/s over the 0.45 m/s envelope" in out, lines_with(out, "envelope"))
+ check("its bus stop is refused off LCM and logged, not fatal",
+ "STOP EXPLORE FAILED" in out and "LCM only" in out, lines_with(out, "STOP EXPLORE")[:160])
+ check("and the stack stop ran, once, from the checkout root", stopped == [str(ROOT)], f"{stopped}")
+
+ HOME4 = Path(TMPS.name) / "killed_home"
+ RUN4 = HOME4 / ".local" / "state" / "dimos" / "logs" / "run-a-moss-dimos-moss-explore"
+ RUN4.mkdir(parents=True)
+ (RUN4 / "main.jsonl").write_text(odom_line(1, T0, 0.0, 0.0) + "\n")
+ env4 = guard_env(HOME4, SPEED_GUARD_IDLE_S="1e6", SPEED_GUARD_POLL_S="0.2", MOSS_MAX_SPEED_MPS="0.5")
+ killed = subprocess.Popen([sys.executable, str(ROOT / "tools" / "speed_guard.py")],
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env4, cwd=str(ROOT))
+ deadline = time.monotonic() + 20
+ while time.monotonic() < deadline and not Path(env4["SPEED_GUARD_PID_FILE"]).exists():
+ time.sleep(0.05)
+ stamped = Path(env4["SPEED_GUARD_PID_FILE"]).read_text().strip() if Path(env4["SPEED_GUARD_PID_FILE"]).exists() else None
+ if stamped:
+ os.kill(int(stamped), 15) # exactly what the arm script does: kill the pid in the file
+ try:
+ out4 = killed.communicate(timeout=15)[0]
+ dead_ok = True
+ except subprocess.TimeoutExpired:
+ killed.kill()
+ out4 = killed.communicate()[0]
+ dead_ok = False
+ check("killed by the pid in its file, it dies, rc 0", dead_ok and killed.returncode == 0, f"rc {killed.returncode}")
+ check("and takes its pid file with it", not Path(env4["SPEED_GUARD_PID_FILE"]).exists())
+ check("MOSS_MAX_SPEED_MPS=0.5 in its environment -> it watched with 0.5 m/s", "(limit 0.5 m/s" in out4,
+ out4.strip().splitlines()[0] if out4.strip() else "(no output)")
+
+ # a ceiling the stack's own cruise would cross: the real script refuses to watch
+ HOME5 = Path(TMPS.name) / "low_ceiling_home"
+ RUN5 = HOME5 / ".local" / "state" / "dimos" / "logs" / "run-a-moss-dimos-moss-explore"
+ RUN5.mkdir(parents=True)
+ (RUN5 / "main.jsonl").write_text(odom_line(1, T0, 0.0, 0.0) + "\n")
+ rc, took, out, stamped, pid, pid_file = run_guard(HOME5, timeout_s=20, MOSS_MAX_SPEED_MPS="0.30")
+ check("MOSS_MAX_SPEED_MPS=0.30 (under the 0.385 m/s cruise): exit 1, no pid file ever, the reason said",
+ rc == 1 and stamped is None and not Path(pid_file).exists() and "not above the planner's cruise 0.385" in out,
+ out.strip()[-160:])
+ rc, took, out, stamped, pid, pid_file = run_guard(HOME5, timeout_s=20, MOSS_NERF_SPEED="1.0")
+ check("MOSS_NERF_SPEED=1.0 (a 0.55 m/s cruise) under the 0.45 m/s ceiling: refused the same way",
+ rc == 1 and stamped is None and "cruise 0.550" in out, out.strip()[-160:])
+
+
+# ── T. arming: tools/arm_speed_guard.sh ──────────────────────────────────
+if SG is not None:
+ print("T. tools/arm_speed_guard.sh REPLACES the previous run's watchdog, by pid, and proves the new one")
+ ARM = ROOT / "tools" / "arm_speed_guard.sh"
+ CLK_TCK = os.sysconf("SC_CLK_TCK")
+ SPAWNED = []
+
+ def uptime_s() -> int:
+ return int(float(Path("/proc/uptime").read_text().split()[0]))
+
+ def born_s(pid) -> int:
+ raw = Path(f"/proc/{pid}/stat").read_text()
+ return int(raw.split(") ", 1)[1].split()[19]) // CLK_TCK
+
+ def alive(pid) -> bool:
+ try:
+ raw = Path(f"/proc/{int(pid)}/stat").read_text()
+ except (OSError, ValueError, TypeError):
+ return False
+ return raw.split(") ", 1)[1].split()[0] != "Z"
+
+ def wait_dead(pid, timeout_s=5.0) -> bool:
+ end = time.monotonic() + timeout_s
+ while time.monotonic() < end and alive(pid):
+ time.sleep(0.05)
+ return not alive(pid)
+
+ TMPT = tempfile.TemporaryDirectory()
+ FAKE_DIR = Path(TMPT.name) / "fake"
+ FAKE_DIR.mkdir()
+ FAKE = FAKE_DIR / "speed_guard.py" # same name: /proc/<pid>/cmdline says speed_guard.py
+ FAKE.write_text("import os, time\n"
+ "open(os.environ['SPEED_GUARD_PID_FILE'], 'w').write(f'{os.getpid()}\\n')\n"
+ "time.sleep(600)\n")
+ DEAD = FAKE_DIR / "dies_at_once.py"
+ DEAD.write_text("import sys\nsys.exit('no dimos run logs found')\n")
+ LIAR = FAKE_DIR / "stamps_an_old_pid.py"
+ LIAR.write_text("import os\nopen(os.environ['SPEED_GUARD_PID_FILE'], 'w').write(os.environ['OLD_PID'] + '\\n')\n")
+ INNOCENT = FAKE_DIR / "innocent_worker.py"
+ INNOCENT.write_text("import time\ntime.sleep(600)\n")
+
+ def spawn(script, env_extra=None):
+ p = subprocess.Popen([sys.executable, str(script)], env={**os.environ, **(env_extra or {})},
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ SPAWNED.append(p)
+ return p
+
+ def run_arm(pid_file, guard_py=None, extra=None, args=(), timeout_s=60):
+ env = {k: v for k, v in os.environ.items() if not k.startswith(("MOSS_", "SPEED_GUARD_"))}
+ env.update({"SPEED_GUARD_PID_FILE": str(pid_file), "SPEED_GUARD_PYTHON": sys.executable,
+ "SPEED_GUARD_LOG": str(Path(pid_file).with_suffix(".log")), "SPEED_GUARD_ARM_DEADLINE_S": "20",
+ "PYTHONPATH": str(ROOT) + os.pathsep + os.environ.get("PYTHONPATH", ""),
+ "PYTHONDONTWRITEBYTECODE": "1"})
+ if guard_py:
+ env["SPEED_GUARD_PY"] = str(guard_py)
+ env.update(extra or {})
+ mark = uptime_s()
+ t0 = time.monotonic()
+ r = subprocess.run(["bash", str(ARM), *args], env=env, cwd=str(ROOT), text=True,
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout_s)
+ return r.returncode, r.stdout, time.monotonic() - t0, mark
+
+ def wait_pid_file(path, timeout_s=20.0):
+ end = time.monotonic() + timeout_s
+ while time.monotonic() < end:
+ try:
+ return int(Path(path).read_text().strip())
+ except (OSError, ValueError):
+ time.sleep(0.05)
+ return None
+
+ def first(out):
+ return out.strip().splitlines()[0] if out.strip() else "(silence)"
+
+ def last(out):
+ return out.strip().splitlines()[-1] if out.strip() else "(silence)"
+
+ check("the arm script parses", subprocess.run(["bash", "-n", str(ARM)]).returncode == 0)
+ PID_A = Path(TMPT.name) / "a.pid"
+ spawn(FAKE, {"SPEED_GUARD_PID_FILE": str(PID_A)})
+ OLD_A = wait_pid_file(PID_A)
+ OLD_BORN = born_s(OLD_A)
+ time.sleep(1.2) # so the two births land in different seconds
+ rc, out, took, mark = run_arm(PID_A, guard_py=FAKE)
+ NEW_A = int(PID_A.read_text().strip())
+ check("the previous run's watchdog alive in the pid file: arming exits 0", rc == 0, f"rc {rc}")
+ check("the previous watchdog is DEAD, and the script says so", wait_dead(OLD_A) and "retired" in out, first(out))
+ check("the pid file names a DIFFERENT, live pid", NEW_A != OLD_A and alive(NEW_A), f"{OLD_A} -> {NEW_A}")
+ check("born AFTER the launch mark, the retired one BEFORE it", born_s(NEW_A) >= mark > OLD_BORN,
+ f"new born {born_s(NEW_A)} s, mark {mark} s, old born {OLD_BORN} s (since boot)")
+ check("it announces the armed pid and the profile's ceiling",
+ f"pid {NEW_A}" in out and "armed (stops the run beyond 0.45 m/s)" in out, last(out))
+ check("arming takes seconds", took < 10.0, f"{took:.1f} s")
+
+ PID_B = Path(TMPT.name) / "b.pid"
+ rc, out, took, mark = run_arm(PID_B, guard_py=FAKE)
+ NEW_B = int(PID_B.read_text().strip())
+ check("no pid file at all (first run after a boot): armed, rc 0, born after the mark",
+ rc == 0 and alive(NEW_B) and born_s(NEW_B) >= mark and "retired" not in out, f"rc {rc}, pid {NEW_B}")
+
+ DEAD_PID = subprocess.Popen([sys.executable, "-c", "pass"])
+ DEAD_PID.wait()
+ PID_C = Path(TMPT.name) / "c.pid"
+ PID_C.write_text(f"{DEAD_PID.pid}\n")
+ rc, out, took, mark = run_arm(PID_C, guard_py=FAKE)
+ NEW_C = int(PID_C.read_text().strip())
+ check("a stale pid file (its pid is gone): named stale, armed anyway",
+ rc == 0 and "stale pid file" in out and alive(NEW_C) and NEW_C != DEAD_PID.pid, first(out))
+
+ PID_D = Path(TMPT.name) / "d.pid"
+ victim = spawn(INNOCENT)
+ PID_D.write_text(f"{victim.pid}\n")
+ rc, out, took, mark = run_arm(PID_D, guard_py=FAKE)
+ NEW_D = int(PID_D.read_text().strip())
+ check("a pid file naming a live process that is NOT a watchdog: it is left alone",
+ rc == 0 and alive(victim.pid) and "not a speed guard" in out, first(out))
+ check("and a watchdog is armed beside it", alive(NEW_D) and NEW_D != victim.pid and born_s(NEW_D) >= mark)
+
+ PID_E = Path(TMPT.name) / "e.pid"
+ rc, out, took, mark = run_arm(PID_E, guard_py=DEAD, extra={"SPEED_GUARD_ARM_DEADLINE_S": "2"})
+ check("a watchdog that never comes up -> rc 1, the reason on screen, never 'armed'",
+ rc == 1 and "DID NOT COME UP" in out and "armed" not in out, out.strip()[-160:])
+ check("it refuses within its deadline", took < 8.0, f"{took:.1f} s")
+ PID_E2 = Path(TMPT.name) / "e2.pid"
+ elder = spawn(INNOCENT)
+ time.sleep(1.2)
+ rc, out, took, mark = run_arm(PID_E2, guard_py=LIAR, extra={"SPEED_GUARD_ARM_DEADLINE_S": "2", "OLD_PID": str(elder.pid)})
+ check("a pid file naming a LIVE process born BEFORE the launch -> rc 1 (liveness alone proves nothing)",
+ rc == 1 and born_s(elder.pid) < mark and alive(elder.pid), f"rc {rc}")
+ rc, out, took, mark = run_arm(Path(TMPT.name) / "f0.pid", guard_py=FAKE, args=(str(Path(TMPT.name) / "no_such_run"),))
+ check("a RUN_DIR that is not a directory -> rc 1, nothing launched", rc == 1 and "IS NOT A DIRECTORY" in out, last(out))
+
+ HOME_F = Path(TMPT.name) / "rover_home"
+ LOGS_F = HOME_F / ".local" / "state" / "dimos" / "logs"
+ RUN_OLD = LOGS_F / "run-a-moss-dimos-moss-explore"
+ RUN_NEW = LOGS_F / "run-b-moss-dimos-moss-explore"
+ for d in (RUN_OLD, RUN_NEW):
+ d.mkdir(parents=True)
+ (d / "main.jsonl").write_text(odom_line(1, T0, 0.0, 0.0) + "\n")
+ os.utime(RUN_OLD, (T0, T0))
+ os.utime(RUN_NEW, (T0 + 60, T0 + 60))
+ PID_F = Path(TMPT.name) / "f.pid"
+ env_f = {"HOME": str(HOME_F), "SPEED_GUARD_IDLE_S": "1e6", "SPEED_GUARD_POLL_S": "0.5"}
+ rc, out, took, mark = run_arm(PID_F, extra=env_f, args=(str(RUN_NEW),))
+ FIRST = int(PID_F.read_text().strip()) if PID_F.exists() else None
+ check("the REAL watchdog arms with the run dir given, rc 0", rc == 0 and FIRST is not None and alive(FIRST),
+ f"rc {rc}, pid {FIRST}")
+ guard_log = Path(str(PID_F.with_suffix(".log")))
+ for _ in range(40):
+ if "watching" in guard_log.read_text():
+ break
+ time.sleep(0.1)
+ check("and it tails THAT run's log", str(RUN_NEW / "main.jsonl") in guard_log.read_text(), first(guard_log.read_text()))
+ time.sleep(1.2)
+ rc, out, took, mark = run_arm(PID_F, extra=env_f, args=(str(RUN_NEW),))
+ SECOND = int(PID_F.read_text().strip()) if PID_F.exists() else None
+ check("armed again: rc 0 and the PID CHANGED (the arm replaced it)",
+ rc == 0 and SECOND is not None and SECOND != FIRST, f"{FIRST} -> {SECOND}")
+ check("the first real watchdog is dead, the second born after the second mark",
+ wait_dead(FIRST) and SECOND is not None and born_s(SECOND) >= mark)
+ if SECOND:
+ os.kill(SECOND, 15)
+ wait_dead(SECOND)
+ PID_G = Path(TMPT.name) / "g.pid"
+ rc, out, took, mark = run_arm(PID_G, extra={**env_f, "MOSS_MAX_SPEED_MPS": "0.30",
+ "SPEED_GUARD_ARM_DEADLINE_S": "3"}, args=(str(RUN_NEW),))
+ check("the REAL watchdog under a 0.30 m/s ceiling (below the cruise): arming fails, rc 1, the reason on screen",
+ rc == 1 and "DID NOT COME UP" in out and "not above the planner's cruise" in out and "armed (" not in out,
+ out.strip()[-200:])
+
+ for p in SPAWNED:
+ p.kill()
+ for p in SPAWNED:
+ p.wait()
+ for leftover in (PID_A, PID_B, PID_C, PID_D):
+ try:
+ os.kill(int(leftover.read_text().strip()), 9)
+ except (OSError, ValueError):
+ pass
+clear_env()
+
+
# ── D/E need the modules: real dimOS, or a stand-in for every dimOS name ──
class _Stub:
diff --git a/benches/bench_run_film_cold.py b/benches/bench_run_film_cold.py
new file mode 100644
index 0000000..095e451
--- /dev/null
+++ b/benches/bench_run_film_cold.py
@@ -0,0 +1,808 @@
+"""Cold bench for the run readers: tools/run_film.py (the film of a run and
+its verdict), tools/decision_replay.py (a recorded decision through the real
+explorer) and tools/gyro_sign_bench.py (the gyro's sign against the lidar).
+
+Known input -> known output, in metres, minutes, cells and degrees. The
+recording is written by dimOS's own SqliteStore, stream by stream as
+MossRecorder writes it (odom with its pose, global_costmap poseless), so the
+readers meet the real schema. Groups:
+
+ A. the film - a 2 min run that drives 2.0 m out and 1.0 m back over a
+ map with a 41-cell wall: the PNG is written next to the
+ recording, the verdict counts every event family (goals,
+ reached, abandons and their triggers, escapes, contacts, the
+ IMU and the stall guard) and names the back-offs; a cornered
+ back-off's own planner lines (its BUMP and its reverse escape)
+ are not a contact, a contact escape nor an abandon; the real
+ script does the same; a recording from another run is refused;
+ without matplotlib it says how to install it
+ B. the inputs - the newest exploration log (the log root and the run
+ registry; a mapping run is not an exploration) and the
+ newest recording under MOSS_STATE_DIR
+ C. replay: log - an excluded timeout is a failure, not a goal; the goal line
+ with "(beyond the cap ...)", the starvation escape and the
+ "exploration start" line that carries exp, cap and radius
+ D. replay: state - note_failed gets the goal, the point the rover STOOD at and
+ the map (unknown signature in cells); a new "exploration
+ start" is a fresh memory; the tuning is the profile's
+ clearances plus the logged exp, cap and radius
+ E. the decode - a costmap blob decoded without dimOS equals dimOS's own
+ grid, a truncated one is refused; Recording reads the
+ synthetic recording back by time
+ F. explain - the radius and the goal cap give the reasons next_target
+ acts on, and the eligible top is next_target's goal
+ G. gyro verdict - the rungs -> the verdict (no turn the lidar saw = no verdict,
+ a rung the lidar lost = no verdict); the prior's state read
+ from the run's log (on = a refusal)
+ H. gyro, recorded - recorded gyro and odometry messages through the bus
+ callbacks: a known sign gives its verdict; the gyro is
+ integrated on its own stamps, gaps over 0.1 s skipped
+ I. gyro, a rung - a rover that pivots at full power whatever rate is asked:
+ the rung ends on the lidar yaw, not on a clock; a lidar that
+ follows a tenth of the turn ends the rung on the gyro and
+ the verdict is INCONCLUSIVE, never "axes wrong"
+
+Needs dimOS (the store and the messages), numpy, matplotlib and PIL: the
+groups that need a missing one are SKIPPED with a line.
+
+Run: PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=. .venv/bin/python benches/bench_run_film_cold.py
+"""
+import ast
+import importlib.util
+import json
+import math
+import os
+import subprocess
+import sys
+import tempfile
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+
+import numpy as np
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT))
+sys.path.insert(0, str(ROOT / "tools"))
+
+OK = 0
+KO = 0
+
+
+def check(label, ok, detail=""):
+ global OK, KO
+ print(f" {'OK ' if ok else 'KO '} {label}{' - ' + detail if detail else ''}")
+ if ok:
+ OK += 1
+ else:
+ KO += 1
+
+
+def missing(*mods):
+ return [m for m in mods if importlib.util.find_spec(m) is None]
+
+
+for _var in [k for k in os.environ if k.startswith("MOSS_")] + ["XDG_STATE_HOME"]:
+ os.environ.pop(_var, None)
+
+T0 = 1_800_000_000.0 # a known epoch: the run starts here
+TMP = tempfile.TemporaryDirectory()
+WORK = Path(TMP.name)
+EXPLORER = "/home/x/moss/moss_dimos/explorer2.py"
+PLANNER = "/home/x/moss/moss_dimos/recovering_planner.py"
+ADAPTER = "/home/x/moss/moss_dimos/moss_adapter.py"
+IMU = "/home/x/moss/moss_dimos/bump_imu.py"
+GPLANNER = "/home/x/dimos/navigation/replanning_a_star/global_planner.py"
+
+
+def iso(t):
+ return datetime.fromtimestamp(t, timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z"
+
+
+def line(t, logger, event, **fields):
+ return json.dumps({"event": event, "level": "info", "logger": logger, "timestamp": iso(t), **fields})
+
+
+# One run, 120 s: a known event of every family at a known time.
+RUN_LINES = [
+ (0.0, EXPLORER, "exploration start: distance exp 2, cap 3 m, radius 4 m (0 = no limit; the radius is centred "
+ "on the first pose)", {}),
+ (1.0, EXPLORER, "goal 1: (1.00, 0.50) 1.1 m away, 12 frontier cells, 3 clusters, chosen in 40 ms", {}),
+ (30.0, GPLANNER, "Arrived at goal.", {}),
+ (31.0, EXPLORER, "goal 2: (2.50, 0.00) 3.4 m away (beyond the cap: nothing safe within it), 8 frontier cells, "
+ "2 clusters, chosen in 35 ms", {}),
+ (58.0, IMU, "IMU contact: forward -12.5 m/s^2 (threshold 8.0) while commanded L=+50% R=+50%", {}),
+ (58.1, PLANNER, "BUMP received: front contact", {"reflex": "escape reverse 0.20 m", "acted": True}),
+ (60.0, PLANNER, "Contact escape", {"trigger": "bump", "direction": "reverse", "travelled_m": 0.2}),
+ (70.0, ADAPTER, "MOSS base: STALL #1: tracks commanded L=+50% R=+50% but the encoders moved L=+3 R=+2 ticks "
+ "in 1.0 s - stopped (the encoders are the bumper)", {}),
+ (70.1, PLANNER, "Goal abandoned, no recovery motion", {"trigger": "stall"}),
+ (90.0, EXPLORER, "born cornered: 2.10 m2 of reachable floor and no frontier - one 0.22 m back-off via the "
+ "bump reflex", {}),
+ # the planner's answer to the bump the explorer published: the back-off itself, not a contact
+ (90.05, PLANNER, "BUMP received: front contact", {"reflex": "escape reverse 0.20 m", "acted": True}),
+ (92.0, PLANNER, "Contact escape", {"trigger": "bump", "direction": "reverse", "travelled_m": 0.2}),
+ (100.0, PLANNER, "Goal abandoned, no recovery motion", {"trigger": "stuck"}),
+ (120.0, EXPLORER, "exploration complete: no reachable frontier left (2 targets, 20 ms)", {}),
+]
+
+
+def write_run_log(run_dir: Path, lines=RUN_LINES, t0=T0) -> Path:
+ run_dir.mkdir(parents=True, exist_ok=True)
+ path = run_dir / "main.jsonl"
+ with open(path, "w") as f:
+ f.write("not json at all\n")
+ for dt, logger, event, fields in lines:
+ f.write(line(t0 + dt, logger, event, **fields) + "\n")
+ return path
+
+
+def x_at(dt):
+ """The trajectory: 2.0 m out along x in 60 s, then 1.0 m back in 60 s (3.0 m driven)."""
+ return 2.0 * dt / 60.0 if dt <= 60.0 else 2.0 - 1.0 * (dt - 60.0) / 60.0
+
+
+WALL_COL, WALL_ROWS = 70, range(10, 51) # 41 occupied cells, x = -1.0 + 70.5 * 0.05 = 2.525 m
+
+
+def costmap_grid():
+ g = np.zeros((60, 80), dtype=np.int8)
+ g[:, 75:] = -1
+ g[list(WALL_ROWS), WALL_COL] = 100
+ return g
+
+
+HAVE_DIMOS = not missing("dimos", "dimos_lcm")
+HAVE_DRAW = not missing("matplotlib", "PIL")
+
+
+def write_recording(db: Path, t0=T0, seconds=120, decision_grids=None):
+ """A recording as MossRecorder writes it, through dimOS's own SqliteStore:
+ odom every 1 s with its pose, global_costmap poseless (one at the end, or
+ `decision_grids` [(t, grid, res, ox, oy)])."""
+ from dimos.memory.store.sqlite import SqliteStore
+ from dimos.msgs.geometry_msgs.Pose import Pose
+ from dimos.msgs.geometry_msgs.PoseStamped import PoseStamped
+ from dimos.msgs.nav_msgs.OccupancyGrid import OccupancyGrid
+
+ store = SqliteStore(path=str(db))
+ store.start()
+ odom = store.stream("odom", PoseStamped)
+ for k in range(seconds + 1):
+ t = t0 + k
+ p = PoseStamped(ts=t, frame_id="world", position=[x_at(k), 0.0, 0.0], orientation=[0.0, 0.0, 0.0, 1.0])
+ odom.append(p, ts=t, pose=Pose(position=p.position, orientation=p.orientation))
+ cm = store.stream("global_costmap", OccupancyGrid)
+ for t, grid, res, ox, oy in (decision_grids or [(t0 + seconds - 1, costmap_grid(), 0.05, -1.0, -1.5)]):
+ og = OccupancyGrid(grid=grid, resolution=res, frame_id="world", ts=t,
+ origin=Pose(position=[ox, oy, 0.0], orientation=[0.0, 0.0, 0.0, 1.0]))
+ cm.append(og, ts=t, pose=None)
+ store.stop()
+ return db
+
+
+# ── A. the film ─────────────────────────────────────────────────────────
+print("A. the film: a 2 min, 3.0 m run with an event of every family, drawn next to its recording")
+RF = None
+if not HAVE_DIMOS or not HAVE_DRAW:
+ print(f" -- SKIP A and B: missing {missing('dimos', 'dimos_lcm', 'matplotlib', 'PIL')}")
+else:
+ import run_film as RF
+ STATE = WORK / "state" / "moss"
+ REC_DIR = STATE / "recordings"
+ REC_DIR.mkdir(parents=True)
+ DB = write_recording(REC_DIR / "moss.db")
+ RUN = WORK / "dimos" / "logs" / "run-a-moss-dimos-moss-explore"
+ LOG = write_run_log(RUN)
+
+ events, t0, t1 = RF.read_log(str(LOG))
+ n = {fam: len(rows) for fam, rows in events.items()}
+ check("the log reads 120 s of run, the junk line skipped", t0 == T0 and abs(t1 - t0 - 120.0) < 1e-6, f"{t1 - t0:.3f} s")
+ check("every family counted: 2 goals, 1 reached, 2 abandons, 1 escape, 1 contact, 1 IMU, 1 stall, 1 cornered",
+ n == {"goal": 2, "abandon": 2, "escape": 1, "bump": 1, "arrived": 1, "imu": 1, "stall": 1, "cornered": 1}, f"{n}")
+ check("a goal is drawn where it was sent: (1.00, 0.50) m and (2.50, 0.00) m",
+ [r[1] for r in events["goal"]] == [(1.0, 0.5), (2.5, 0.0)], f"{[r[1] for r in events['goal']]}")
+ check("the escape keeps its direction, the abandons their triggers",
+ [r[2] for r in events["escape"]] == ["reverse"] and [r[2] for r in events["abandon"]] == ["stall", "stuck"])
+ check("the cornered back-off took its own BUMP (90.05 s) and reverse escape (92 s): 1 contact at 58.1 s, "
+ "1 escape at 60 s, the cornered row 'reversed'",
+ [round(r[0] - T0, 2) for r in events["bump"]] == [58.1] and [r[0] - T0 for r in events["escape"]] == [60.0]
+ and [r[2] for r in events["cornered"]] == ["reversed"] and [r[2] for r in events["bump"]] == ["front"],
+ f"bumps {[round(r[0] - T0, 2) for r in events['bump']]}, escapes {[r[0] - T0 for r in events['escape']]}, "
+ f"cornered {[r[2] for r in events['cornered']]}")
+ odom, occ = RF.read_db(str(DB), t0, t1)
+ xs = [r[1] for r in odom]
+ dist = float(np.hypot(np.diff(xs), np.zeros(len(xs) - 1)).sum())
+ check("the recording gives back 121 poses and 3.0 m of path", len(odom) == 121 and abs(dist - 3.0) < 1e-9,
+ f"{len(odom)} poses, {dist:.6f} m")
+ check("and the map's wall: 41 obstacle centres at x = 2.525 m",
+ occ.shape == (41, 2) and np.allclose(occ[:, 0], 2.525), f"{occ.shape}, x {sorted(set(np.round(occ[:, 0], 4)))}")
+
+ code, lines = RF.film(str(LOG), str(DB))
+ PNG = REC_DIR / "run-a-moss-dimos-moss-explore.film.png"
+ check("film() returns 0 and writes <run>.film.png next to the recording",
+ code == 0 and PNG.is_file() and lines[0] == f"THE FILM -> {PNG}", lines[0] if lines else "(nothing)")
+ from PIL import Image
+ with Image.open(PNG) as im:
+ size = im.size
+ colours = len(set(im.convert("RGB").getdata()))
+ blue = sum(1 for r, g, b in im.convert("RGB").getdata() if b > 120 and b - r > 60)
+ check("a real picture: 1430 x 1170 px (11 x 9 in at 130 dpi), not a blank page",
+ size == (1430, 1170) and colours > 100 and blue > 500, f"{size}, {colours} colours, {blue} blue px of trajectory")
+ want = [" 2.0 min, 3.0 m driven",
+ " goals: 2 chosen, 1 reached, 3 abandoned (stuck + contact: every escape cancels its goal), "
+ "1 contact escapes, 1 contacts",
+ " back-offs: 2 (1 after a contact, 1 cornered); 0 forward contact escapes; contacts felt by the IMU 1, "
+ "inferred from an encoder stall 1",
+ " abandon triggers: stall 1, stuck 1",
+ " verdict: 1.5 stuck/contact events per minute - LOOK AT THE MAP before any conclusion"]
+ check("the verdict, line for line (minutes, metres, counts, back-offs, triggers, rate)", lines[1:] == want,
+ " | ".join(lines[1:]))
+ check("it names the back-offs: 2 (a 0.20 m reverse escape and a cornered back-off)",
+ any(ln.startswith(" back-offs: 2 (") for ln in lines))
+ fwd = [r if r[0] != 60.0 else (r[0], r[1], r[2], {**r[3], "direction": "forward", "trigger": "bump_rear"})
+ for r in RUN_LINES]
+ ev_f, f0, f1 = RF.read_log(str(write_run_log(WORK / "fwd" / "run-f", fwd)))
+ vf = RF.verdict_lines(ev_f, f0, f1, 3.0, "x.png")
+ check("a contact behind the rover escapes FORWARD: not a back-off (1 = the cornered one)",
+ any(ln.startswith(" back-offs: 1 (0 after a contact, 1 cornered); 1 forward contact escapes") for ln in vf),
+ vf[3])
+ calm = [r for r in RUN_LINES if not r[2].startswith(("BUMP received", "Goal abandoned", "Contact escape"))]
+ ev_c, c0, c1 = RF.read_log(str(write_run_log(WORK / "calm" / "run-c", calm)))
+ vc = RF.verdict_lines(ev_c, c0, c1, 3.0, "x.png")
+ check("a run with no stuck and no contact: 0.0 per minute and no alarm",
+ vc[-1] == " verdict: 0.0 stuck/contact events per minute", vc[-1])
+ check("its cornered line had no planner answer: said, and not counted as a back-off",
+ " cornered with no back-off logged: 1 (no planner BUMP and reverse escape followed the cornered line)" in vc
+ and any(ln.startswith(" back-offs: 0 (0 after a contact, 0 cornered)") for ln in vc), " | ".join(vc[3:5]))
+
+ # one cornered back-off, logged the way the stack logs it, and nothing else
+ ALONE = [(0.0, EXPLORER, "exploration start: distance exp 2, cap 3 m, radius 4 m", {}),
+ (10.0, EXPLORER, "born cornered: 0.40 m2 of reachable floor and no frontier - one 0.20 m back-off via the "
+ "bump reflex", {}),
+ (10.05, PLANNER, "BUMP received: front contact", {"reflex": "escape reverse 0.20 m", "acted": True}),
+ (12.0, PLANNER, "Contact escape", {"trigger": "bump", "direction": "reverse", "travelled_m": 0.2}),
+ (60.0, EXPLORER, "exploration complete: no reachable frontier left", {})]
+ ev_a, a0, a1 = RF.read_log(str(write_run_log(WORK / "alone" / "run-g", ALONE)))
+ va = RF.verdict_lines(ev_a, a0, a1, 0.4, "x.png")
+ check("one cornered back-off alone: 1 back-off (cornered), 0 contacts, 0 abandoned, 0.0 per minute",
+ va[2] == " goals: 0 chosen, 0 reached, 0 abandoned (stuck + contact: every escape cancels its goal), "
+ "0 contact escapes, 0 contacts"
+ and va[3].startswith(" back-offs: 1 (0 after a contact, 1 cornered)")
+ and va[-1] == " verdict: 0.0 stuck/contact events per minute", " | ".join(va[2:]))
+ LATE = ALONE[:2] + [(13.0, IMU, "IMU contact: forward -12.5 m/s^2 (threshold 8.0) while commanded L=+50% R=+50%", {}),
+ (13.05, PLANNER, "BUMP received: front contact", {"reflex": "escape reverse 0.20 m", "acted": True}),
+ (15.0, PLANNER, "Contact escape", {"trigger": "bump", "direction": "reverse", "travelled_m": 0.2})]
+ ev_l, _l0, _l1 = RF.read_log(str(write_run_log(WORK / "late" / "run-h", LATE)))
+ check("a real contact 3 s after a cornered line (no BUMP within 1 s of it) stays a contact and its escape",
+ len(ev_l["bump"]) == 1 and len(ev_l["escape"]) == 1 and [r[2] for r in ev_l["cornered"]] == [None],
+ f"{len(ev_l['bump'])} contacts, {len(ev_l['escape'])} escapes, cornered {[r[2] for r in ev_l['cornered']]}")
+ REAR = ALONE[:2] + [(10.05, PLANNER, "BUMP received: rear contact", {"reflex": "escape forward 0.20 m", "acted": True}),
+ (12.0, PLANNER, "Contact escape", {"trigger": "bump_rear", "direction": "forward"})]
+ ev_r, _r0, _r1 = RF.read_log(str(write_run_log(WORK / "rear" / "run-i", REAR)))
+ check("a REAR contact right after a cornered line is a contact (the back-off rides the front bump only)",
+ [r[2] for r in ev_r["bump"]] == ["rear"] and [r[2] for r in ev_r["escape"]] == ["forward"]
+ and [r[2] for r in ev_r["cornered"]] == [None], f"{ev_r['bump']} {ev_r['escape']}")
+ BUSY = ALONE[:1] + [(8.0, IMU, "IMU contact: forward -12.5 m/s^2 (threshold 8.0) while commanded L=+50% R=+50%", {}),
+ (8.05, PLANNER, "BUMP received: front contact", {"reflex": "escape reverse 0.20 m", "acted": True}),
+ (9.0,) + ALONE[1][1:],
+ (9.05, PLANNER, "BUMP received: front contact", {"reflex": "escape reverse 0.20 m", "acted": False}),
+ (9.2, PLANNER, "Contact escape", {"trigger": "bump", "direction": "reverse", "aborted": True})]
+ ev_b, b0, b1 = RF.read_log(str(write_run_log(WORK / "busy" / "run-j", BUSY)))
+ vb = RF.verdict_lines(ev_b, b0, b1, 0.2, "x.png")
+ check("a cornered bump the planner did not act on (an escape was running): that escape stays the contact's",
+ [round(r[0] - T0, 2) for r in ev_b["bump"]] == [8.05] and [round(r[0] - T0, 1) for r in ev_b["escape"]] == [9.2]
+ and [r[2] for r in ev_b["cornered"]] == [None]
+ and vb[3].startswith(" back-offs: 1 (1 after a contact, 0 cornered)"), " | ".join(vb[2:5]))
+
+ OTHER = write_recording(WORK / "other.db", t0=T0 + 86400)
+ code, lines = RF.film(str(LOG), str(OTHER), str(WORK / "x.png"))
+ check("a recording of another run (no odom in this log's window) is refused, nothing drawn",
+ code == 1 and "wrong db?" in lines[0] and not (WORK / "x.png").exists(), lines[0])
+ saved_mpl = {k: v for k, v in sys.modules.items() if k == "matplotlib" or k.startswith("matplotlib.")}
+ sys.modules["matplotlib"] = None # import matplotlib now raises ImportError
+ try:
+ code, lines = RF.film(str(LOG), str(DB), str(WORK / "no_mpl.png"))
+ finally:
+ del sys.modules["matplotlib"]
+ sys.modules.update(saved_mpl)
+ check("no matplotlib: exit 1, one line saying how to install it, nothing drawn",
+ code == 1 and lines == ["matplotlib is missing, nothing drawn: .venv/bin/pip install matplotlib"]
+ and not (WORK / "no_mpl.png").exists(), " | ".join(lines))
+
+ env = {k: v for k, v in os.environ.items() if not k.startswith("MOSS_")}
+ env.update({"PYTHONPATH": str(ROOT) + os.pathsep + os.environ.get("PYTHONPATH", ""), "PYTHONDONTWRITEBYTECODE": "1"})
+ PNG.unlink()
+ r = subprocess.run([sys.executable, str(ROOT / "tools" / "run_film.py"), "--log", str(LOG), "--db", str(DB)],
+ capture_output=True, text=True, env=env, timeout=300)
+ check("the real script: exit 0, the film next to the recording, the same verdict",
+ r.returncode == 0 and PNG.is_file() and r.stdout.splitlines()[1:] == want,
+ f"rc {r.returncode}, {len(r.stdout.splitlines())} lines" + ("" if r.returncode == 0 else
+ f": {r.stderr.strip()[-160:]}"))
+
+ # ── B. the inputs ───────────────────────────────────────────────────
+ print("B. the inputs: the newest exploration log and the newest recording")
+ LOGROOT = WORK / "dimos" / "logs"
+ RUNS = WORK / "dimos" / "runs"
+ RUNS.mkdir(parents=True)
+ os.utime(LOG, (T0, T0))
+ newer = write_run_log(LOGROOT / "run-b-moss-dimos-moss-explore")
+ os.utime(newer, (T0 + 100, T0 + 100))
+ mapping = write_run_log(LOGROOT / "run-c-moss-dimos-moss-nav")
+ os.utime(mapping, (T0 + 200, T0 + 200))
+ lg, rg = str(LOGROOT / "*-moss-explore" / "main.jsonl"), str(RUNS / "*.json")
+ check("the newest exploration run's log, not a newer mapping run's", RF.newest_log(lg, rg) == str(newer),
+ f"{RF.newest_log(lg, rg)}")
+ clone = write_run_log(WORK / "clone" / "logs" / "run-d")
+ os.utime(clone, (T0 + 300, T0 + 300))
+ (RUNS / "d.json").write_text(json.dumps({"blueprint": "moss_dimos.moss-explore", "log_dir": str(clone.parent)}))
+ (RUNS / "e.json").write_text(json.dumps({"blueprint": "moss_dimos.moss-nav", "log_dir": str(mapping.parent)}))
+ (RUNS / "f.json").write_text("{half")
+ check("a run from a git clone is found through its registry entry", RF.newest_log(lg, rg) == str(clone),
+ f"{RF.newest_log(lg, rg)}")
+ rotated = REC_DIR / "moss.11111111111111.db"
+ rotated.write_bytes(DB.read_bytes())
+ os.utime(rotated, (T0 - 100, T0 - 100))
+ os.utime(DB, (T0 + 100, T0 + 100))
+ check("the newest recording under MOSS_STATE_DIR: moss.db over a rotated moss.<stamp>.db",
+ RF.newest_db({"MOSS_STATE_DIR": str(STATE)}) == str(DB), f"{RF.newest_db({'MOSS_STATE_DIR': str(STATE)})}")
+ os.utime(rotated, (T0 + 500, T0 + 500))
+ check("... and the rotated one when it is the newest", RF.newest_db({"MOSS_STATE_DIR": str(STATE)}) == str(rotated))
+ check("no recording at all -> None (the script then says what is missing)",
+ RF.newest_db({"MOSS_STATE_DIR": str(WORK / "empty")}) is None)
+
+
+# ── C. replay: the log ──────────────────────────────────────────────────
+print("C. decision_replay.read_log: an excluded timeout is a failure, every explorer line routed")
+RD = None
+if missing("scipy"):
+ print(f" -- SKIP C to F: missing {missing('scipy')}")
+else:
+ import decision_replay as RD
+ from moss_dimos.explorer2 import DEFAULT_TUNING, ExploreState, next_target
+ from moss_dimos import robot_profile
+
+ LINES = [ # (seconds into the run, the explorer's own words)
+ (0.0, "exploration start: distance exp 2, cap 3 m, radius 4 m (0 = no limit; the radius is centred on "
+ "the first pose)"),
+ (1.0, "goal 1: (1.00, 2.00) 3.2 m away, 11 frontier cells, 5 clusters, chosen in 100 ms"),
+ (45.0, "goal timeout after 45 s having closed 0.10 m of 3.20 m: excluded until the map or the viewpoint "
+ "changes"),
+ (46.0, "goal 2: (3.00, 1.00) 2.1 m away (beyond the cap: nothing safe within it), 7 frontier cells, "
+ "4 clusters, chosen in 120 ms"),
+ (91.0, "goal timeout after 45 s, 1.20 m closer, re-deciding"),
+ (95.0, "planner gave up on that goal: excluded until the map or the viewpoint changes"),
+ (96.0, "starvation escape: the world stayed silent for 30 asks - reopening the oldest failed goal at "
+ "(1.00, 2.00)"),
+ (97.0, "exploration complete: no reachable frontier left (2 targets, 26 ms)"),
+ (120.0, "exploration start: distance exp 1, cap 0 m, radius 0 m (0 = no limit; the radius is centred on "
+ "the first pose)"),
+ (121.0, "goal 1: (0.50, 0.50) 0.9 m away, 9 frontier cells, 2 clusters, chosen in 30 ms"),
+ ]
+ T_EXCLUDED = T0 + LINES[2][0]
+ T_GAVE_UP = T0 + LINES[5][0]
+ STOOD_EARLY, STOOD_AT_TIMEOUT, STOOD_AT_REFUSAL = (0.10, 0.20), (0.75, 0.25), (2.50, 1.30)
+ RLOG = WORK / "replay.jsonl"
+ with open(RLOG, "w") as fh:
+ fh.write("not json at all\n")
+ fh.write(json.dumps({"logger": "/x/local_planner.py", "event": "goal 9: nonsense",
+ "timestamp": iso(T0 + LINES[1][0])}) + "\n")
+ for dt, event in LINES:
+ fh.write(json.dumps({"logger": EXPLORER, "event": event, "timestamp": iso(T0 + dt)}) + "\n")
+ ev = RD.read_log(str(RLOG))
+ kinds = [e.kind for e in ev]
+ check("10 explorer lines in, 9 events out (the 're-deciding' timeout is not one)", len(ev) == 9, f"{len(ev)}")
+ check("kinds in order: start, goal, failed, goal, failed, wait, none, start, goal",
+ kinds == ["start", "goal", "failed", "goal", "failed", "wait", "none", "start", "goal"], f"{kinds}")
+ check("the excluded timeout is the failure at its own time (45 s in)",
+ ev[2].kind == "failed" and abs(ev[2].t - T_EXCLUDED) < 1e-6, f"{ev[2].t - T0:.3f} s")
+ g = ev[1]
+ check("goal 1: n=1, (1.00, 2.00) m, 3.2 m, 11 cells, 5 clusters, 100 ms",
+ (g.goal_n, g.xy, g.path_cost_m, g.info_cells, g.n_clusters, g.elapsed_ms) == (1, (1.0, 2.0), 3.2, 11, 5, 100.0),
+ f"{g.goal_n} {g.xy} {g.path_cost_m} {g.info_cells} {g.n_clusters} {g.elapsed_ms}")
+ g = ev[3]
+ check("the goal beyond the cap: (3.00, 1.00) m, 2.1 m, 7 cells, 4 clusters, 120 ms",
+ (g.xy, g.path_cost_m, g.info_cells, g.n_clusters, g.elapsed_ms) == ((3.0, 1.0), 2.1, 7, 4, 120.0),
+ f"{g.xy} {g.path_cost_m} {g.info_cells} {g.n_clusters} {g.elapsed_ms}")
+ check("the start lines carry exp, cap, radius: (2, 3, 4) then (1, 0, 0)",
+ ev[0].shape == (2.0, 3.0, 4.0) and ev[7].shape == (1.0, 0.0, 0.0), f"{ev[0].shape} {ev[7].shape}")
+
+ # ── D. replay: the memory and the tuning ────────────────────────────
+ print("D. replay: note_failed carries the goal, the standing point and the map; a new start is a fresh memory")
+ tun = RD.run_tuning((2.0, 3.0, 4.0))
+ lethal, pivot = robot_profile.derived()
+ check("the run's tuning: the profile's clearances (0.22 / 0.25 m) and the logged exp 2, cap 3 m, radius 4 m",
+ (tun.lethal_clearance_m, tun.pivot_clearance_m, tun.distance_exponent, tun.max_goal_path_m,
+ tun.explore_radius_m) == (lethal, pivot, 2.0, 3.0, 4.0) and abs(lethal - 0.22) < 1e-9,
+ f"{tun.lethal_clearance_m:.2f} {tun.pivot_clearance_m:.2f} {tun.distance_exponent} {tun.max_goal_path_m} "
+ f"{tun.explore_radius_m}")
+ check("everything else as the blueprint leaves it (DEFAULT_TUNING)",
+ tun.min_frontier_perimeter_m == DEFAULT_TUNING.min_frontier_perimeter_m
+ and tun.failed_goal_radius_m == DEFAULT_TUNING.failed_goal_radius_m)
+
+ def build_grid():
+ """10 m x 10 m free map, origin (0, 0), with two unknown patches of known size."""
+ grid = np.full((200, 200), 0, dtype=np.int8)
+ grid[40:45, 20:24] = -1 # 20 cells, inside 0.6 m of (1.00, 2.00)
+ grid[18:21, 58:62] = -1 # 12 cells, inside 0.6 m of (3.00, 1.00)
+ return grid
+
+ class FakeRecording:
+ def __init__(self):
+ self.grid = build_grid()
+
+ def costmap_at(self, t):
+ return RD._Grid(self.grid, 0.05, 0.0, 0.0, t)
+
+ def pose_at(self, t):
+ if t >= T_GAVE_UP:
+ x, y = STOOD_AT_REFUSAL
+ elif t >= T_EXCLUDED:
+ x, y = STOOD_AT_TIMEOUT
+ else:
+ x, y = STOOD_EARLY
+ return RD._Pose(x, y, 0.0, 1.0, t)
+
+ out = list(RD.replay(FakeRecording(), ev, DEFAULT_TUNING))
+ states = [o[4] for o in out]
+ tunings = [o[6] for o in out]
+ check("5 decisions replayed (3 goals, the wait, the end of the first exploration)", len(out) == 5, f"{len(out)}")
+ check("decision 1 saw no exclusion yet", states[0].failed == [], f"{states[0].failed}")
+ check("decision 2 saw exactly the one exclusion the timeout wrote", len(states[1].failed) == 1, f"{len(states[1].failed)}")
+ if states[1].failed:
+ x, y, sx, sy, sig = states[1].failed[0]
+ check("excluded goal (1.00, 2.00) m, stood at (0.75, 0.25) m - where the rover was at the TIMEOUT",
+ (x, y) == (1.0, 2.0) and (sx, sy) == STOOD_AT_TIMEOUT, f"({x}, {y}) stood ({sx}, {sy})")
+ check("unknown signature = 20 cells around that goal", sig == 20, f"{sig}")
+ if len(states) > 2 and len(states[2].failed) == 2:
+ x, y, sx, sy, sig = states[2].failed[1]
+ check("the planner refusal excludes goal 2 (3.00, 1.00) m, stood at (2.50, 1.30) m, 12 cells",
+ (x, y) == (3.0, 1.0) and (sx, sy) == STOOD_AT_REFUSAL and sig == 12, f"({x}, {y}) ({sx}, {sy}) {sig}")
+ else:
+ check("the wait decision carries both exclusions", False, f"{[s.failed for s in states]}")
+ check("the second 'exploration start' is a fresh memory: no goal, no exclusion, no anchor",
+ states[4].visited == [] and states[4].failed == [] and states[4].anchor is None,
+ f"{states[4].visited} {states[4].failed} {states[4].anchor}")
+ check("each exploration replays with its own logged shape: exp 2 / cap 3 / radius 4, then 1 / 0 / 0",
+ (tunings[0].distance_exponent, tunings[0].max_goal_path_m, tunings[0].explore_radius_m) == (2.0, 3.0, 4.0)
+ and (tunings[4].distance_exponent, tunings[4].max_goal_path_m, tunings[4].explore_radius_m) == (1.0, 0.0, 0.0))
+ check("the anchor of the first exploration is its first pose (0.10, 0.20) m", states[1].anchor == STOOD_EARLY,
+ f"{states[1].anchor}")
+
+ # ── E. the decode and the recording ─────────────────────────────────
+ print("E. the costmap blob decoded without dimOS; the recording read back by time")
+ if not HAVE_DIMOS:
+ print(f" -- SKIP E: missing {missing('dimos', 'dimos_lcm')}")
+ else:
+ from dimos.msgs.geometry_msgs.Pose import Pose
+ from dimos.msgs.nav_msgs.OccupancyGrid import OccupancyGrid
+ grid = costmap_grid()
+ og = OccupancyGrid(grid=grid, resolution=0.05, frame_id="world", ts=T0,
+ origin=Pose(position=[-1.0, -1.5, 0.0], orientation=[0.0, 0.0, 0.0, 1.0]))
+ blob = og.lcm_encode()
+ g2, res, ox, oy, frame = RD.decode_occupancy_grid(blob)
+ check("dimOS's own blob decodes to the same 60 x 80 grid, 0.05 m, origin (-1.0, -1.5), 'world'",
+ np.array_equal(g2, grid) and abs(res - 0.05) < 1e-6 and (ox, oy) == (-1.0, -1.5) and frame == "world",
+ f"{g2.shape} {res:.4f} ({ox}, {oy}) {frame}")
+ try:
+ RD.decode_occupancy_grid(blob[:-7])
+ check("a truncated blob is refused", False, "no exception")
+ except ValueError as exc:
+ check("a truncated blob is refused (a format change cannot pass silently)", True, str(exc))
+ if RF is not None:
+ rec = RD.Recording(str(DB))
+ cm = rec.costmap_at(T0 + 200)
+ check("Recording: 121 poses and 1 costmap from the synthetic recording",
+ len(rec.odom_ts) == 121 and len(rec.costmap_ts) == 1)
+ check("the costmap held at a time is the last one before it, its wall where it was written",
+ int((cm.grid == 100).sum()) == 41 and cm.ts == T0 + 119)
+ p = rec.pose_at(T0 + 90.5)
+ check("the pose at t + 90.5 s is the row before it: x = 1.50 m (on the way back)",
+ abs(p.position.x - 1.5) < 1e-9 and p.ts == T0 + 90, f"x {p.position.x:.4f} at {p.ts - T0:.1f} s")
+ try:
+ rec.pose_at(T0 - 1)
+ check("no pose before the recording starts", False, "no exception")
+ except LookupError:
+ check("no pose before the recording starts: LookupError, not a guess", True)
+
+ # ── F. explain mirrors next_target ──────────────────────────────────
+ print("F. explain(): the radius and the cap give next_target's reasons; the eligible top is its goal")
+ from dataclasses import replace as _replace
+ from moss_dimos.explorer2 import PoseStamped as _PS
+
+ def hall():
+ """The explorer bench's hall: 6 x 2 m, its east end open onto 1 m of
+ unknown (far frontier), a 0.50 m door into a closet on the north wall."""
+ g = np.full((120, 220), -1, dtype=np.int8)
+ g[40:80, 20:140] = 0
+ g[39:81, 19] = 100
+ g[39, 19:161] = 100
+ g[80, 19:161] = 100
+ g[39:81, 160] = 100
+ g[80:93, 57] = 100
+ g[80:93, 78] = 100
+ g[93, 57:79] = 100
+ g[80, 63:73] = -1
+ return g
+
+ def pose(x, y, yaw=0.0):
+ p = _PS(ts=0.0, frame_id="world")
+ p.position.x, p.position.y = x, y
+ p.orientation.z, p.orientation.w = math.sin(yaw / 2), math.cos(yaw / 2)
+ return p
+
+ hall_cm = RD._Grid(hall(), 0.05, 0.0, 0.0, 0.0)
+ start = pose(50.5 * 0.05, 60.5 * 0.05)
+ for label, tuning, far_reason in (
+ ("radius 2 m: the far end is outside it", _replace(DEFAULT_TUNING, forward_bonus=0.0, distance_exponent=1.0,
+ max_goal_path_m=0.0, explore_radius_m=2.0), "outside-radius"),
+ ("cap 3 m, a safe closet within it: the far end waits beyond the cap",
+ _replace(DEFAULT_TUNING, forward_bonus=0.0, distance_exponent=1.0, max_goal_path_m=3.0,
+ explore_radius_m=0.0), "beyond-cap"),
+ ("no cap, no radius, exponent 1: both compete and the big far end wins",
+ _replace(DEFAULT_TUNING, forward_bonus=0.0, distance_exponent=1.0, max_goal_path_m=0.0,
+ explore_radius_m=0.0), "")):
+ target = next_target(hall_cm, start, ExploreState(), now=1.0, tuning=tuning)
+ scored, info = RD.explain(hall_cm, start, ExploreState(), 1.0, tuning)
+ top = [s for s in scored if not s.reason]
+ far = max(scored, key=lambda s: s.cluster.goal_xy[0])
+ same = (target is not None and top and abs(top[0].cluster.goal_xy[0] - target.position.x) < 1e-9
+ and abs(top[0].cluster.goal_xy[1] - target.position.y) < 1e-9 and abs(top[0].score - target.score) < 1e-12)
+ check(f"{label}: far end '{far.reason or 'competes'}', the top is next_target's goal",
+ len(scored) == 2 and far.reason == far_reason and bool(same),
+ f"far ({far.cluster.goal_xy[0]:.2f}, {far.cluster.goal_xy[1]:.2f}) {far.reason!r}, "
+ f"top {top[0].cluster.goal_xy if top else None}, next_target "
+ f"{(round(target.position.x, 2), round(target.position.y, 2)) if target else None}")
+
+
+# ── G. gyro verdict ─────────────────────────────────────────────────────
+print("G. gyro_sign_bench.verdict(): the rungs -> the verdict")
+import gyro_sign_bench as GB # noqa: E402
+
+STILL = [("+30 deg (left)", 29.5, 0.4, "time"), ("-30 deg (right)", -28.9, -0.3, "time")]
+AGREE = [("+30 deg (left)", 29.5, 30.2, "lidar"), ("-30 deg (right)", -28.9, -29.7, "lidar")]
+ONE_RUNG = [("+30 deg (left)", 29.5, 30.2, "lidar"), ("-30 deg (right)", -1.2, -0.4, "time")]
+FLIPPED = [("+30 deg (left)", -29.5, 30.2, "lidar"), ("-30 deg (right)", 28.9, -29.7, "lidar")]
+DEAD_GYRO = [("+30 deg (left)", 0.2, 30.2, "lidar"), ("-30 deg (right)", -0.1, -29.7, "lidar")]
+TOO_BIG = [("+30 deg (left)", 91.0, 30.2, "lidar"), ("-30 deg (right)", -89.0, -29.7, "lidar")]
+LOST = [("+30 deg (left)", 90.4, 9.0, "gyro"), ("-30 deg (right)", -29.1, -30.3, "lidar")]
+SLOW = [("+30 deg (left)", 20.3, 19.6, "time"), ("-30 deg (right)", -29.1, -30.3, "lidar")]
+msg, code = GB.verdict(STILL)
+check("0.4 deg of lidar yaw is not a turn: INCONCLUSIVE, exit 3, never CORRECT",
+ "INCONCLUSIVE" in msg and "CORRECT" not in msg and code == 3, msg)
+msg, code = GB.verdict([])
+check("no rung at all: INCONCLUSIVE, exit 3", "INCONCLUSIVE" in msg and code == 3, f"{code}")
+check("(the all() over an empty set this guards against WOULD say CORRECT on the same rungs)",
+ all(g * l > 0 and 0.5 < abs(g / l) < 2.0 for _, g, l, _e in STILL if abs(l) > 5) is True)
+msg, code = GB.verdict(AGREE)
+check("29.5 deg gyro vs 30.2 deg lidar, both rungs: CORRECT, exit 0, and the next step MOSS_GYRO=1",
+ "CORRECT" in msg and code == 0 and "MOSS_GYRO=1" in msg, msg)
+msg, code = GB.verdict(ONE_RUNG)
+check("one real rung is enough, and it says how many were measured (1/2)",
+ "CORRECT" in msg and code == 0 and "1/2 rungs measured" in msg, msg)
+msg, code = GB.verdict(FLIPPED)
+check("-29.5 deg gyro vs +30.2 deg lidar: SIGN FLIPPED -> 'y', exit 2", "SIGN FLIPPED" in msg and "'y'" in msg and code == 2, msg)
+msg, code = GB.verdict(DEAD_GYRO)
+check("0.2 deg gyro over a 30 deg turn: WRONG, exit 2", "WRONG" in msg and code == 2, msg)
+msg, code = GB.verdict(TOO_BIG)
+check("91 deg gyro over a 30 deg turn the lidar ended (ratio 3): WRONG, exit 2", "WRONG" in msg and code == 2, msg)
+msg, code = GB.verdict(LOST)
+check("a rung that ended on the GYRO (90 deg) with 9 deg of lidar: INCONCLUSIVE, exit 3, relaunch at "
+ "MOSS_PIVOT_PCT=50, never 'WRONG' (the other rung agreeing changes nothing)",
+ "INCONCLUSIVE" in msg and code == 3 and "MOSS_PIVOT_PCT=50" in msg and "WRONG" not in msg, msg)
+msg, code = GB.verdict([(lb, g, l, "time") for lb, g, l, _e in LOST])
+check("the same rung ended by the time limit: INCONCLUSIVE too", "INCONCLUSIVE" in msg and code == 3, msg)
+msg, code = GB.verdict(SLOW)
+check("a slow rung cut by the time limit where gyro and lidar AGREE (20.3 vs 19.6 deg) still measures: CORRECT",
+ "CORRECT" in msg and code == 0, msg)
+
+# the prior's state, from the run's own log
+PRIOR_DIR = Path(TMP.name) / "prior"
+PRIOR_DIR.mkdir()
+
+
+def prior_log(name, *events):
+ path = PRIOR_DIR / name
+ with open(path, "w") as fh:
+ for k, ev in enumerate(events):
+ fh.write(json.dumps({"event": ev, "level": "info", "timestamp": iso(T0 + k)}) + "\n")
+ return str(path)
+
+
+OFF_LOG = prior_log("off.jsonl", "MOSS blueprint: lidar odometry prior: gyro=False (run tools/gyro_sign_bench.py "
+ "once, then MOSS_GYRO=1)",
+ "lidar odometry up (kiss-icp, voxel 0.05 m, range 0.15-12.0 m, prior: gyro=False axis -y, "
+ "wheels NEVER) -> world")
+ON_LOG = prior_log("on.jsonl", "MOSS blueprint: lidar odometry prior: gyro=True (MOSS_GYRO=1)",
+ "lidar odometry up (kiss-icp, voxel 0.05 m, range 0.15-12.0 m, prior: gyro=True axis -y, "
+ "wheels NEVER) -> world")
+MUTE_LOG = prior_log("mute.jsonl", "lidar odom #1: x=+0.000 y=+0.000 yaw=+0.0deg")
+msg, code = GB.prior_check(ON_LOG)
+check("the run's log says 'prior: gyro=True': refused, exit 3, naming MOSS_GYRO", code == 3 and "MOSS_GYRO" in msg, msg)
+msg, code = GB.prior_check(OFF_LOG)
+check("'prior: gyro=False': the bench goes on", code is None and "OFF" in msg, msg)
+msg, code = GB.prior_check(MUTE_LOG)
+check("a log that says nothing of the prior: a warning naming MOSS_GYRO, the bench goes on",
+ code is None and msg.startswith("WARNING") and "MOSS_GYRO" in msg, msg)
+msg, code = GB.prior_check(None)
+check("no run log at all: a warning, the bench goes on", code is None and msg.startswith("WARNING"), msg)
+STATE_P = PRIOR_DIR / "state"
+for name, mtime, src in (("run-old", T0, ON_LOG), ("run-new", T0 + 60, OFF_LOG)):
+ (STATE_P / "dimos" / "logs" / name).mkdir(parents=True)
+ dst = STATE_P / "dimos" / "logs" / name / "main.jsonl"
+ dst.write_text(Path(src).read_text())
+ os.utime(dst, (mtime, mtime))
+check("the newest run's log is the one read (an older run with the prior on does not count)",
+ GB.newest_run_log({"XDG_STATE_HOME": str(STATE_P)}) == str(STATE_P / "dimos" / "logs" / "run-new" / "main.jsonl"),
+ f"{GB.newest_run_log({'XDG_STATE_HOME': str(STATE_P)})}")
+_tree = ast.parse((ROOT / "moss_dimos" / "lidar_odometry.py").read_text())
+_axis = None
+for _node in ast.walk(_tree):
+ if isinstance(_node, ast.FunctionDef) and _node.name == "__init__":
+ _args = _node.args
+ for _a, _d in zip(_args.kwonlyargs + _args.args[len(_args.args) - len(_args.defaults):],
+ _args.kw_defaults + list(_args.defaults)):
+ if _a.arg == "gyro_axis" and isinstance(_d, ast.Constant):
+ _axis = _d.value
+check("the axis under test is the one the odometry's prior reads (LidarOdometry gyro_axis)",
+ GB.GYRO_AXIS == _axis == "-y", f"bench {GB.GYRO_AXIS!r}, odometry {_axis!r}")
+
+
+# ── H. gyro, a recorded sequence ────────────────────────────────────────
+class FakeLC:
+ """The LCM handle the bench subscribes on: the handlers are kept, nothing spins."""
+
+ def __init__(self):
+ self.handlers = {}
+
+ def subscribe(self, channel, handler):
+ self.handlers[channel] = handler
+
+ def handle_timeout(self, ms):
+ time.sleep(ms / 1000.0)
+
+
+class Recorder:
+ def __init__(self):
+ self.sent = []
+
+ def broadcast(self, _who, msg):
+ self.sent.append(msg)
+
+
+print("H. gyro, recorded: Imu and PoseStamped messages through the bus callbacks -> a known sign, a known verdict")
+if not HAVE_DIMOS:
+ print(f" -- SKIP H and I: missing {missing('dimos', 'dimos_lcm')}")
+else:
+ from dimos.msgs.geometry_msgs.PoseStamped import PoseStamped
+ from dimos.msgs.geometry_msgs.Twist import Twist
+ from dimos.msgs.geometry_msgs.Vector3 import Vector3
+ from dimos.msgs.sensor_msgs.Imu import Imu
+
+ def recorded_rung(lc, deg, sign_y=-1.0, rate_deg_s=60.0, t0=T0, hz=200.0, gap_at=None):
+ """The messages of one rung, through the subscribed handlers: the gyro
+ reads `sign_y` * the yaw rate on its y axis (the upright mount: y points
+ down, so a left turn reads NEGATIVE y), the odometry the yaw itself."""
+ w = math.radians(rate_deg_s) * (1 if deg > 0 else -1)
+ n = int(round(abs(deg) / rate_deg_s * hz))
+ for k in range(n + 1):
+ t = t0 + k / hz
+ if gap_at is not None and gap_at[0] <= t - t0 < gap_at[1]:
+ continue
+ m = Imu(angular_velocity=Vector3(0.0, sign_y * w, 0.0), ts=t, frame_id="camera_imu_optical_frame")
+ lc.handlers["/imu#sensor_msgs.Imu"]("/imu#sensor_msgs.Imu", m.lcm_encode())
+ if k % 20 == 0 or k == n:
+ yaw = w * (k / hz)
+ p = PoseStamped(ts=t, frame_id="world", position=[0.0, 0.0, 0.0],
+ orientation=[0.0, 0.0, math.sin(yaw / 2), math.cos(yaw / 2)])
+ lc.handlers["/odom#geometry_msgs.PoseStamped"]("/odom#geometry_msgs.PoseStamped", p.lcm_encode())
+
+ def measure(deg, **kw):
+ lc = FakeLC()
+ b = GB.Bench(lc=lc, twist=Recorder(), start=False)
+ p = PoseStamped(ts=T0, frame_id="world", position=[0.0, 0.0, 0.0], orientation=[0.0, 0.0, 0.0, 1.0])
+ lc.handlers["/odom#geometry_msgs.PoseStamped"]("/odom#geometry_msgs.PoseStamped", p.lcm_encode())
+ b.reset()
+ _, y0 = b.snapshot()
+ recorded_rung(lc, deg, **kw)
+ gyro, y1 = b.snapshot()
+ return math.degrees(gyro), GB.wrap_deg(y1 - y0)
+
+ gl, ll = measure(+30.0)
+ gr, lr = measure(-30.0)
+ check("upright mount, +30 deg left: gyro(-y) +30.0 deg, lidar +30.0 deg",
+ abs(gl - 30.0) < 0.2 and abs(ll - 30.0) < 0.2, f"gyro {gl:+.2f}, lidar {ll:+.2f}")
+ check("and -30 deg right: gyro -30.0 deg, lidar -30.0 deg", abs(gr + 30.0) < 0.2 and abs(lr + 30.0) < 0.2,
+ f"gyro {gr:+.2f}, lidar {lr:+.2f}")
+ msg, code = GB.verdict([("+30 deg (left)", gl, ll, "lidar"), ("-30 deg (right)", gr, lr, "lidar")])
+ check("-> CORRECT, exit 0", "CORRECT" in msg and code == 0, msg)
+ fl, fll = measure(+30.0, sign_y=+1.0)
+ fr, flr = measure(-30.0, sign_y=+1.0)
+ msg, code = GB.verdict([("+30 deg (left)", fl, fll, "lidar"), ("-30 deg (right)", fr, flr, "lidar")])
+ check("a camera mounted upside down (y up): gyro -30 deg against lidar +30 deg -> SIGN FLIPPED 'y', exit 2",
+ abs(fl + 30.0) < 0.2 and "SIGN FLIPPED" in msg and "'y'" in msg and code == 2, f"{fl:+.2f} vs {fll:+.2f}: {msg}")
+ gg, _ = measure(+30.0, gap_at=(0.2025, 0.3525))
+ check("a 0.155 s hole in the gyro stream adds nothing (the prior's 0.1 s gap rule): "
+ "(0.500 - 0.155) s x 60 deg/s = 20.7 deg", abs(gg - 20.7) < 0.05, f"{gg:+.2f} deg")
+
+ # ── I. a rung on a rover that pivots at full power ──────────────────
+ print("I. gyro, a rung: the pivot ends on the lidar yaw (the tracks pivot at full power whatever rate is asked)")
+
+ class FullPowerRover:
+ """Every pivot command turns the body at 250 deg/s (MOSS_PIVOT_PCT 100),
+ whatever wz says; zero stops it. Sim time moves with sleep()."""
+
+ def __init__(self, bench, deg_s=250.0, sign_y=-1.0, moves=True, lidar_gain=1.0):
+ self.b, self.deg_s, self.sign_y, self.moves = bench, deg_s, sign_y, moves
+ self.lidar_gain = lidar_gain # the share of the turn the lidar odometry follows
+ self.t, self.yaw, self.w = T0, 0.0, 0.0
+ self.commands = 0
+
+ def broadcast(self, _who, msg):
+ wz = float(msg.angular.z)
+ self.commands += wz != 0.0
+ self.w = (math.radians(self.deg_s) * (1 if wz > 0 else -1)) if (wz and self.moves) else 0.0
+
+ def clock(self):
+ return self.t
+
+ def sleep(self, s):
+ steps = max(1, int(round(s * 200)))
+ for _ in range(steps):
+ self.t += s / steps
+ self.yaw += self.w * s / steps
+ self.b.on_imu(-(self.sign_y * self.w), self.t) # the gyro reads sign_y * w on y; mapped "-y"
+ if int(round((self.t - T0) * 200)) % 20 == 0:
+ self.b.on_odom(self.lidar_gain * self.yaw)
+
+ b = GB.Bench(lc=FakeLC(), twist=Recorder(), start=False)
+ rover = FullPowerRover(b)
+ b.twist = rover
+ b.on_odom(0.0)
+ took, ended = b.turn(+GB.TURN_RAD_S, clock=rover.clock, sleep=rover.sleep)
+ turned = math.degrees(rover.yaw)
+ timed = 250.0 * GB.TURN_DEG / math.degrees(GB.TURN_RAD_S)
+ check(f"asked 0.3 rad/s for 30 deg, the body pivots at 250 deg/s: the rung stops at {turned:.0f} deg "
+ f"(30 + at most one 0.1 s command), not the {timed:.0f} deg a rung timed at 0.3 rad/s would turn",
+ 30.0 <= turned <= 30.0 + 25.0 + 1.0 and took < 0.5 and ended == "lidar",
+ f"{turned:.1f} deg in {took:.2f} s, ended on {ended}")
+ check("the last command sent is a zero twist", isinstance(b.twist, FullPowerRover) and rover.w == 0.0)
+ b.on_odom(rover.yaw)
+ b2 = GB.Bench(lc=FakeLC(), twist=Recorder(), start=False)
+ r2 = FullPowerRover(b2)
+ b2.twist = r2
+ b2.on_odom(0.0)
+ results = GB.run_rungs(b2, settle_s=1.0, sleep=r2.sleep, clock=r2.clock)
+ msg, code = GB.verdict(results)
+ check("both rungs on that rover, the upright mount: CORRECT, exit 0",
+ code == 0 and all(30.0 <= abs(l) <= 56.0 and abs(g / l - 1.0) < 0.05 and e == "lidar"
+ for _, g, l, e in results),
+ " | ".join(f"{lb}: gyro {g:+.1f} lidar {l:+.1f} ({e})" for lb, g, l, e in results) + f" -> {msg[:40]}")
+ b3 = GB.Bench(lc=FakeLC(), twist=Recorder(), start=False)
+ r3 = FullPowerRover(b3, moves=False)
+ b3.twist = r3
+ b3.on_odom(0.0)
+ results = GB.run_rungs(b3, settle_s=1.0, sleep=r3.sleep, clock=r3.clock)
+ msg, code = GB.verdict(results)
+ check(f"tracks off the ground (nothing turns): each rung gives up after {GB.MAX_RUNG_S:.0f} s, INCONCLUSIVE, exit 3",
+ code == 3 and "INCONCLUSIVE" in msg and r3.commands >= 2 * int(GB.MAX_RUNG_S / 0.1) - 2,
+ f"{r3.commands} commands, {msg}")
+ b4 = GB.Bench(lc=FakeLC(), twist=Recorder(), start=False)
+ r4 = FullPowerRover(b4, lidar_gain=0.10)
+ b4.twist = r4
+ b4.on_odom(0.0)
+ results = GB.run_rungs(b4, settle_s=1.0, sleep=r4.sleep, clock=r4.clock)
+ msg, code = GB.verdict(results)
+ stop = GB.GYRO_STOP_RATIO * GB.TURN_DEG
+ check(f"a lidar that follows 10 % of a full-power pivot: each rung ends on the GYRO at {stop:.0f} deg "
+ f"(+ one 0.1 s command), not after {GB.MAX_RUNG_S:.0f} s of pivot",
+ all(e == "gyro" and stop <= abs(g) <= stop + 25.0 + 1.0 for _, g, _l, e in results),
+ " | ".join(f"{lb}: gyro {g:+.1f} lidar {l:+.1f} ({e})" for lb, g, l, e in results))
+ check("and the verdict is INCONCLUSIVE (exit 3, relaunch at MOSS_PIVOT_PCT=50), never 'axis mapping WRONG'",
+ code == 3 and "INCONCLUSIVE" in msg and "MOSS_PIVOT_PCT=50" in msg and "WRONG" not in msg, msg)
+ check("the twist the bench builds is a pure pivot (dimOS Twist, wz only)",
+ isinstance(Twist(linear=[0.0, 0.0, 0.0], angular=[0.0, 0.0, 0.3]).angular.z, float))
+
+print(f"{OK} OK, {KO} KO")
+print("TEST PASSED" if KO == 0 else "TEST FAILED")
+sys.exit(1 if KO else 0)
diff --git a/docs/base.md b/docs/base.md
index 4fa60f1..17a09c7 100644
--- a/docs/base.md
+++ b/docs/base.md
@@ -63,6 +63,27 @@ Two deadmen, both on the robot: the adapter's (0.5 s, in the dimOS process)
and the firmware's (0.3 s, on the ESP32). A cockpit on a laptop that loses the
link stops the tracks without anyone's help.
+A third guard watches the body itself, for unattended runs: the speed watchdog,
+`tools/speed_guard.py`. It reads the run's dimOS log and measures the speed
+between consecutive `lidar odom #N` lines (one every 2 s), dated by the
+timestamps the log carries. One interval faster than the profile's
+`max_speed_mps` (0.45 m/s, `MOSS_MAX_SPEED_MPS`) stops the run: the exploration
+stop on the bus (`tools/explore_ctl.py stop`), then `tools/moss-fly.sh stop`,
+and the firmware deadman stops the tracks 300 ms later. It guards one run and
+stands down by itself when a newer run starts or the log stays silent for 30 s.
+The ceiling is the planner's cruise plus a margin: dimOS's follower drives at
+0.55 m/s times the launcher's speed scale (`MOSS_NERF_SPEED`, 0.7), 0.385 m/s,
+and 0.45 m/s leaves 0.065 m/s above it. A ceiling at or under that cruise would
+stop every normal run, so the watchdog refuses to start with one and says which
+number to change. `tools/moss-fly.sh` does not arm it on its own: once the stack
+is proven, run `tools/arm_speed_guard.sh <run log dir>` by hand (without the
+argument it takes the newest run). The script kills the previous run's watchdog
+by the pid in `/tmp/moss_speed_guard.pid`, starts a fresh one and exits 1 unless
+that file then names a process born after the launch; the watchdog writes to
+`/tmp/moss_speed_guard.log`. Like the speeds below, the ceiling is a
+placeholder: once the floor speed is measured (`MOSS_MPS_AT_LIMIT`), check that
+what an exploration run really drives stays under it.
+
The coordinator publishes the firmware telemetry on `/base_telemetry` every
0.5 s (JSON: `ts`, `fw`, `driver`, `mode`, `reason`, `bus_mV`, `ina_ok`,
`ticks`, `target_pct`, `output_pct`, `ramp_ms`, `firmware_age_s`, `mock`), so
diff --git a/docs/cockpit.md b/docs/cockpit.md
index 87ac533..cd5a7b6 100644
--- a/docs/cockpit.md
+++ b/docs/cockpit.md
@@ -71,15 +71,24 @@ firmware 300 ms after the last drive.
the encoders give metres only once `MOSS_TICKS_PER_M` is set, and the
RealSense's gyro gives the odometry its rotation prior (below);
- the 2D scored costmap (`moss_dimos/costmap2d.py`), where the lidar writes obstacles
- and the depth camera adds the ones below the scan plane. An obstacle becomes a
- wall once seen from two places 10 cm apart, never from one spot. The lidar's
- rays clear the lidar layer within 4 m of the rover all around, and the camera
- layer only inside the camera's own view (87 degrees ahead, up to 3 m): somebody
- who walked past fades once gone (about 0.2 s of rays through a fresh wall, 1.8 s
- through one seen from many places), what the camera keeps seeing stays, and a
- table top the rover has turned away from keeps its wall until the camera looks
- at that spot again and sees nothing. The knobs are `MOSS_HIT_CAP`,
- `MOSS_FREE_FLOOR` and `MOSS_RAY_MAX_M` (below);
+ and the depth camera adds the ones below the scan plane, each sensor on its own
+ layer. An obstacle becomes a wall once seen from two places 10 cm apart, never
+ from one spot. The lidar's rays clear the lidar layer within 4 m of the rover;
+ they pass over a shoe and never clear what the camera saw. Only the camera clears
+ its layer: by seeing the floor on a cell, or by seeing through it low (its rays
+ from the nose, between 1.3 and 6 cm above the floor). A cell the camera hit in the
+ last 3 s keeps its score whatever the floor beside it says, so a leg thinner than
+ a cell stays a wall, and a camera hit counts only when the previous depth frame
+ also saw something within one cell, so a walker or a vacuum, which moves more
+ than a cell between frames, is rarely written: a foot planted for two frames can
+ mark a cell, and the camera clears it once it is gone. A table top the rover has
+ turned away from keeps its wall until the camera looks at that spot again and
+ sees floor there. A contact writes nothing into the map: the planner backs off,
+ and the map stays the lidar's and the camera's (`MOSS_CONTACT_WALL=1` marks a
+ short band ahead of the body for a contact felt while driving straight
+ forward). The knobs are `MOSS_OCCUPIED_AT`,
+ `MOSS_NEW_VIEWPOINT_M`, `MOSS_HIT_CAP`, `MOSS_FREE_FLOOR`, `MOSS_RAY_MAX_M`,
+ `MOSS_PUBLISH_EVERY` and `MOSS_CONTACT_WALL` (below);
- the lidar odometry's rotation prior from the RealSense's gyro, on with `MOSS_IMU` (the
default): the IMU read in the camera's own process gives the yaw rate at 200 Hz, and each
registration starts from the yaw integrated since the previous revolution. A full-power
@@ -226,14 +235,19 @@ Other variables:
| `MOSS_RS_SERIAL` | the RealSense to use, by serial number |
| `MOSS_REQUIRE_PAD=1` | a missing pad fails the flight check instead of warning |
| `MOSS_COCKPIT_PORT` | the cockpit's port, 8904 by default (also `--port`; `tools/moss-cockpit.service` sets it) |
+| `MOSS_IDLE_STOP_S` | how long a `moss-nav` or `moss-explore` stack may see no activity before the cockpit stops it, 300 s by default, 0 = never, at least 30 (a shorter value is refused: 300 s); read when the cockpit starts, from its own environment (the service's), see "The stack stops itself" |
| `PROOF_S` | how long `tools/moss-fly.sh` waits for the stack to prove itself in its log, 120 s by default |
| `MOSS_MOCK_BUS=1` | the fake firmware, no motors (`MOCK=1` on the launchers sets it) |
| `MOSS_STATE_DIR` | the state directory, `~/.local/state/moss` by default: recordings, the saved flight check |
| `MOSS_BRAKE_S` | how long the pad sends zeros after the deadman is released, 0.5 s by default, 0 to 1.0 s |
| `MOSS_TURN_GAIN` | turn authority against forward speed on the pad, 2 by default, 0.5 to 4 ([base.md](base.md)) |
-| `MOSS_HIT_CAP` | how certain a costmap cell can get, 10 by default, 2 to 127. A cell at the cap needs 2 x (cap - 1) lidar revolutions with rays through it to be forgotten (1.8 s at 10, 0.6 s at 4): lower it to forget passers-by faster, at the price of walls that fade sooner once nothing sees them |
+| `MOSS_OCCUPIED_AT` | how many hits a costmap cell needs to be a wall, 2 by default, 1 to 10: two places at least `MOSS_NEW_VIEWPOINT_M` apart, never one spot, so somebody standing next to a parked rover never walls it in. 1 makes the first sighting a wall: a faster block, and every passer-by a wall |
+| `MOSS_NEW_VIEWPOINT_M` | how far the rover must move before the same cell takes another hit, 0.10 m by default, 0 to 1 |
+| `MOSS_HIT_CAP` | how certain a costmap cell can get, 10 by default, 2 to 127. A lidar cell at the cap needs 2 x (cap - 1) revolutions with rays through it to be forgotten (1.8 s at 10, 0.6 s at 4), a camera cell at most cap - 1 looks of the camera through it once its 3 s are over (one look can take more than one point off): lower it to forget passers-by faster, at the price of walls that fade sooner once nothing sees them |
| `MOSS_FREE_FLOOR` | how free a costmap cell can get, -3 by default, -128 to 0. Nearer 0, something that appears on floor seen free for long becomes a wall after fewer viewpoints (for the lidar: 3 at -1, 5 at -3) |
-| `MOSS_RAY_MAX_M` | how far from the rover the lidar's rays clear the costmap, 4 m by default (0 = never). Anything farther than that from every place the rover stood is never forgotten: 6 forgets somebody who stood 4.5 m away, and longer rays cost more CPU per revolution |
+| `MOSS_RAY_MAX_M` | how far from the rover the lidar's rays clear the costmap's lidar layer (and the camera's rays its own), 4 m by default (0 = never). Anything farther than that from every place the rover stood is never forgotten: 6 forgets somebody who stood 4.5 m away, and longer rays cost more CPU per revolution |
+| `MOSS_PUBLISH_EVERY` | one costmap grid every N lidar revolutions, 2 by default (5 grids a second), 1 to 20. Every subscriber decodes every grid and the recorder writes each one: raise it if the load climbs |
+| `MOSS_CONTACT_WALL` | `1` turns a contact into a wall on the costmap: the band 2 to 20 cm beyond the body's front, across its width, when the rover was driving straight forward (3 cm or more along its heading and less than 10 degrees of turn over the last 0.5 s). Off by default: a contact is a reflex, only the lidar and the camera write the map |
## Recording
@@ -260,6 +274,31 @@ $ .venv/bin/dimos dataprep build --source <db> --format lerobot --output <dir> -
`--config` is required: a JSON `DataPrepConfig` naming the observation and action
streams (for MOSS: `color_image`, `odom`, `cmd_vel`) and the episode extractor.
+### Reading a run
+
+After every exploration run, draw the run before talking about it: counters
+("12 stuck, 9 contacts") hide what the robot did, one picture shows it.
+`.venv/bin/python tools/run_film.py` reads the newest exploration run's
+`main.jsonl` and the newest recording in `<MOSS_STATE_DIR>/recordings/`
+(`--log` and `--db` pick others) and writes the film of the run next to the
+recording, `<run>.film.png`: the trajectory coloured by time (light to dark)
+over the obstacles of the map the run built, with every goal, reached goal,
+abandon, contact escape, contact, IMU contact, encoder stall and cornered
+back-off where it happened. It prints the verdict: minutes and metres driven,
+goals chosen, reached and abandoned, the back-offs (after a contact, or
+cornered: the planner's bump and reverse escape that answer a cornered line
+belong to that back-off and count as neither a contact nor an abandon), the
+contacts the IMU felt and the ones the stall guard inferred, the abandon
+triggers, and the stuck or contact events per minute; above one per minute,
+look at the map before any conclusion. Then `tools/decision_replay.py` (same
+defaults; `--decision N` for goal N, `--decision final` for the last call)
+rebuilds each explorer decision from the recording and runs it through the real
+`explorer2.next_target`, printing every frontier cluster with its gain, its path
+cost, its multipliers and why the others lost, next to what the run logged. The
+film needs dimOS and matplotlib: when the venv lacks matplotlib, the script
+says so and draws nothing (`.venv/bin/pip install matplotlib`). The replay
+decodes the map itself.
+
## The cockpit
`tools/moss_cockpit.py` is a stdlib HTTP server on port 8904 (`MOSS_COCKPIT_PORT`
@@ -282,6 +321,51 @@ STOP on the page is a soft stop: it publishes `stop_explore_cmd`,
`stop_movement` and a zero twist. The hard stops are the firmware deadman
(300 ms) and `tools/moss-fly.sh stop`.
+**The stack stops itself.** A stack left up with nothing to do drains the battery:
+on the board's input rail, the explore stack idle on a parked rover drew about 2 W
+more than no stack at all (one measurement at the time of this change). The cockpit
+stops a `moss-nav` or `moss-explore` stack (the two that run the lidar odometry and
+the costmap) that saw no activity for `MOSS_IDLE_STOP_S` seconds (300 by default)
+with the message `stopping the stack to preserve battery (idle 5 min)`, in its
+journal, above the stop's lines in `/launch.json` and on the page's status line
+with its time (`..., stopped at 14:05`), where it stays until the next action. The
+cockpit keeps that note in memory only: a restarted cockpit no longer shows it. The
+stop is the same `tools/moss-fly.sh stop` as the Stop stack button (exploration off
+first, then the stack down). `moss-gamepad` and any other MOSS blueprint stay up:
+`tools/moss-teleop.sh` keeps its stack up with the pad on the table. Activity is
+any of: base telemetry whose `output_pct` is not `[0, 0]` (a track commanded, by
+the pad, the planner or the explorer) and whose firmware line is at most 1 s old
+(with the board lost, the coordinator repeats its last line), a `cmd_vel` with a
+non-zero `linear.x` or `angular.z`, an `explore_cmd`, a `goal_request`, an
+`episode_marker`, an open episode, the odometry pose more than 2 cm or 2 degrees
+from where it was 10 s before (the rover pushed by hand; drift at rest never adds
+up to that), and any command sent from the page. An exploration with nothing left
+to drive is idle. The count runs from the stack's start (from the cockpit's own
+start when the cockpit came up later) on the monotonic clock, so a clock step
+changes nothing, and each run is stopped once at most.
+
+While a `moss-nav` or `moss-explore` stack runs, the line under the chip reads
+`idle 3:20, stops at 5:00 to preserve battery · keep the stack up`: dim until half
+the limit, in the warning colour for the last minute. The line is a button: a press
+(`POST /cmd/keepalive`) starts the count again, and the line shows it at once. The
+cockpit never stops a stack it cannot see: one on another bus than LCM or with
+another `LCM_DEFAULT_URL` than the cockpit's, any stack while it does not listen to
+the bus, or while nothing arrived on any channel it listens to for 10 s (every MOSS
+stack publishes `base_telemetry` twice a second: silence means the cockpit is deaf,
+not that the rover is idle). It never stops a registry entry whose pid is no longer
+a `dimos run` (a stale entry after a power cut). It waits for a launch or a flight
+check in progress, up to 120 s, and a stop that fails to start is tried again each
+second. The journal says once per run why a due stop was held. `/state.json`
+carries `idle: {enabled, idle_s, stop_in_s, limit_s, last_source, blind}` next to
+`stack`: `last_source` names what restarted the count last (`start`, `telemetry`,
+`cmd_vel`, `odom`, `explore_cmd`, `goal_request`, `episode`, `post`, `keepalive`,
+`demo`) and `blind` why the cockpit cannot see the run, so a run that never stops
+says why. To turn it off, set `MOSS_IDLE_STOP_S=0` in the service (`sudo systemctl
+edit moss-cockpit`, a line `Environment=MOSS_IDLE_STOP_S=0` under `[Service]`) and
+restart the cockpit; a value under 30 s is refused (the cockpit says so and keeps
+300 s). In the demo, the synthetic rover's driving counts as activity, and a halted
+demo stack stops itself the same way, on the first request past the limit.
+
A goal tapped on the map goes out at once when nothing is exploring. While
exploring, the page stops the explorer first and sends the goal three seconds
later, after the explorer's own last goal, which would override it otherwise.
@@ -338,7 +422,7 @@ keeps one word on top for the state now.
| `reached` | local planner | `Reached goal position, starting final rotation` | Goal reached |
| `contact` | base adapter | `STALL #1: tracks commanded L=+76% R=+64% but the encoders moved L=+1 R=+0 ticks in 1.0 s` | Contact #1: both tracks blocked (commanded ..., encoders moved ...) |
| `contact` | recovering planner | `BUMP received`, `Contact during an escape: stopping dead`, `Contact escape` | Bump: backing off / Contact during an escape: stop dead / Escape done: 0.20 m in 2.1 s, Escape timed out: only 0.05 m in 5.0 s, Escape aborted after 0.05 m |
-| `contact` | costmap | `costmap: contact at (-0.88, +0.73) heading +147 deg: 32 cells ahead marked as a wall` | Wall remembered ahead (32 cells) |
+| `contact` | costmap (`MOSS_CONTACT_WALL=1`) | `costmap: contact at (-0.88, +0.73) heading +147 deg: 32 cells ahead marked as a wall` | Wall remembered ahead (32 cells) |
| `push` | base adapter | `tracks frozen at L=+56% R=+50% - pushing at 75 % for 1 s ...` | Tracks frozen at L=+56% R=+50%: pushing at 75 % |
| `pivot_fallback` | base adapter | `pivot L=+100% R=-100%: the right track did not turn ...` | Right track did not turn in reverse (...): pivoting on the left track from now on |
| `imu` | IMU contact detector | `IMU contact: forward -4.8 m/s^2 (threshold 4.0) while commanded L=+70% R=+60%` | the line itself |
diff --git a/docs/imu.md b/docs/imu.md
index 2d3f251..32d6c8f 100644
--- a/docs/imu.md
+++ b/docs/imu.md
@@ -2,13 +2,17 @@
MOSS knows it touched something in two ways. The base adapter watches the
encoders: tracks commanded but not turning for a second is a stall, and the
-coordinator publishes it on `bump`. That misses the contacts that matter
-most: a track that slips keeps turning against the wall, an oblique contact
-leaves one track free, and the verdict comes a second or more after the
-impact. The chassis says it at once: hitting something while driving is a
-short, hard deceleration along the direction of travel. The RealSense on the
-nose carries an IMU, and `MOSS_IMU=1` turns its decelerations into contacts on
-the same `bump` stream.
+coordinator publishes it on `stall`. A stall is inferred, not felt (a pivot
+that fails to turn reads the same as a wall), so the planner answers it by
+stopping and abandoning the goal, with no motion. The encoders also miss the
+contacts that matter most: a track that slips keeps turning against the
+wall, an oblique contact leaves one track free, and the verdict comes a
+second or more after the impact. The chassis says it at once: hitting
+something while driving is a short, hard deceleration along the direction of
+travel. The RealSense on the nose carries an IMU, and `MOSS_IMU=1` turns its
+decelerations into contacts: on `bump` for a contact in front, on
+`bump_rear` for a contact behind. A felt contact is the one thing that earns
+the planner's scripted move, 0.20 m away from it.
It is on by default since a stationary launch on the robot showed colour,
depth and the IMU alive together (below); `MOSS_IMU=0` turns it off.
@@ -38,7 +42,11 @@ samples to dimOS's own handler, which publishes `imu`. No second pipeline, no
second process. If the camera has no motion module, or the gyro does not offer
the rate, or opening fails, the camera logs a warning and goes on with colour
and depth only. `stop()` stops and closes the motion module before the
-pipeline.
+pipeline. The camera module runs in a worker process of its own
+(`dedicated_worker`, the blueprint's `DedicatedMossRealSense`): a camera
+sharing its worker with the odometry, the costmap or the recorder is starved
+under load, and its depth and IMU samples arrive late or not at all while
+the sensor drops no frame.
## The axes
@@ -76,12 +84,15 @@ kiss-icp's constant-velocity model), and the integral starts again from
zero. A full-power pivot (254 deg/s measured on the floor) turns the rover 25
degrees between two scans, more than the constant-velocity prior follows; the
gyro says where the rover turned. A revolution with no gyro sample since the
-last one falls back to the constant-velocity model. Three switches: with
-`MOSS_IMU` on (the default) the prior is on, and the odometry's start line
-says `prior: gyro=True`; `MOSS_GYRO=0` turns it off at any time; with
-`MOSS_IMU=0`, `MOSS_GYRO=1` is refused with a warning, because the gyro would
-then come from dimOS's second IMU pipeline (above), and `MOSS_GYRO_FORCE=1`
-builds it anyway, the experiment path.
+last one falls back to the constant-velocity model. The prior is off by
+default until its sign is measured on this robot, because a wrong-sign prior
+is worse than none (the build log says `prior: gyro=False (run
+tools/gyro_sign_bench.py once, then MOSS_GYRO=1)`): run that bench once, then
+`MOSS_GYRO=1` turns it on with `MOSS_IMU` (the odometry's start line then
+says `prior: gyro=True`), while with `MOSS_IMU=0`, `MOSS_GYRO=1` is refused
+with a warning, because the gyro would then come from dimOS's second IMU
+pipeline (above), and `MOSS_GYRO_FORCE=1` builds it anyway, the experiment
+path.
## The rule
@@ -100,34 +111,85 @@ traces), inside the `BumpImu` module:
plus the firmware's own age of that line). A rover kicked or lifted while
idle is not a contact.
5. **Against the command.** Driving forward (no track backward): only a
- deceleration, high-pass <= -threshold. Reversing (no track forward): only a
- forward kick, high-pass >= +threshold. Pivoting (tracks of opposite signs):
- either sign. Taking off is never a contact.
-6. **Once.** After a contact, nothing for `MOSS_BUMP_DEBOUNCE_S` (default
- 0.7 s). The debounce also covers the planner's escape taking off in
- reverse while the last telemetry line still says forward.
+ deceleration, high-pass <= -threshold, a contact in front. Reversing (no
+ track forward): only a forward kick, high-pass >= +threshold, a contact
+ behind. Pivoting (tracks of opposite signs): either sign, and the sign
+ gives the side: a deceleration is in front, a forward kick behind. Taking
+ off is never a contact.
+6. **Once.** After a contact, nothing more on the same side for
+ `MOSS_BUMP_DEBOUNCE_S` (default 0.7 s). The debounce also covers the
+ planner's escape taking off in reverse while the last telemetry line still
+ says forward. One debounce per side: a front contact and a rear one are
+ opposite reflexes, not repeats of each other, so the other side counts at
+ once (a rover wedging into a corner during one pivot is two contacts, and
+ so is the escape that backs off a front contact and hits something
+ behind). The one exception is the impact's own rebound: a kick of the
+ other sign within 0.1 s of a contact, whatever the command says by then
+ (the telemetry can already carry the escape's reverse). The contact
+ measured below lasted 20 ms, so 0.1 s covers it five times over; the
+ figure comes from that impact length, and a pivot contact recorded with
+ `MOSS_IMU_LOG` is the recording that sets it.
+
+On a contact `BumpImu` publishes `Bool(True)` on `bump` (in front) or
+`bump_rear` (behind) and logs one line first:
-On a contact `BumpImu` publishes `Bool(True)` on `bump` and logs one line:
+```
+IMU contact: forward -4.8 m/s^2 (threshold 4.0) while commanded L=+70% R=+60%, front contact -> bump
+IMU contact: forward +5.2 m/s^2 (threshold 4.0) while commanded L=-70% R=-60%, rear contact -> bump_rear
+```
+
+A rebound is published nowhere, and logged once, so that no felt kick is
+silent:
```
-IMU contact: forward -4.8 m/s^2 (threshold 4.0) while commanded L=+70% R=+60%
+MOSS IMU: forward +6.8 m/s^2 while commanded L=+70% R=-70%, 0.06 s after the front contact: taken as its rebound, not published on bump_rear
```
-`bump` is the stream the coordinator's stall guard and the explorer's back-off
-already publish on, so the same listeners react: the planner's escape
-(stop, 0.20 m in reverse, the goal abandoned; a second contact during an
-escape stops dead), the costmap's contact memory (the band ahead becomes a
-wall), the sounds (`bump_surprise`, at the impact rather than a second
-later) and the lidar odometry, which drops the shaken revolution that
-follows ([below](#a-contact-and-the-map)). The stall guard stays on: a contact with the tracks frozen can be
-reported twice, by the IMU at the impact and by the encoders a second later.
+`bump` is the stream the explorer's back-off also publishes on. Its
+listeners: the planner's escape (stop, 0.20 m in reverse, the goal
+abandoned; a second contact during an escape stops dead), the costmap (which
+logs the contact and, with `MOSS_CONTACT_WALL=1` and the rover driving
+straight forward, marks the band ahead as a wall), the sounds
+(`bump_surprise`, at the impact rather than a second later) and the lidar
+odometry, which drops the shaken revolution that follows
+([below](#a-contact-and-the-map)). `bump_rear` has one listener, the
+planner: stop, 0.20 m FORWARD, the goal abandoned. A rear contact is not a
+front wall. The stall guard stays on, on its own stream: a stall that comes
+while an escape runs stops the escape dead.
The cockpit shows each contact in its decision feed
([cockpit.md](cockpit.md#what-it-decides)). The module's other lines start
with `MOSS IMU:` and so appear in `tools/moss-fly.sh log`: the knobs at
-start, the first sample (where gravity sits), then once a minute the sample
-rate, the mean accel and the contacts so far. The contact lines themselves
-are in `.venv/bin/dimos log` and in the cockpit.
+start, the first sample (where gravity sits), the watchdog's lines (below),
+and every 10 s a status line with the state, the sample rate, the mean
+accel, the contacts and the quiet spells so far. The contact lines
+themselves are in `.venv/bin/dimos log` and in the cockpit.
+
+## When the IMU goes quiet
+
+The IMU is this robot's main bumper, and the rotation prior when
+`MOSS_GYRO=1`. A stream that stops must be said, not discovered in the map.
+A watchdog thread in `BumpImu` (`ImuWatchdog`) looks every 0.1 s at the time
+since the last sample arrived:
+
+```
+MOSS IMU: no sample for 1 s - IMU contacts and gyro prior OFF
+MOSS IMU: samples back (199 Hz) after 3.2 s quiet
+MOSS IMU: status alive, 1990 samples in 10 s (199 Hz), mean accel (+0.03, -9.80, +0.10) m/s^2, 0 contact(s) so far, 1 quiet spell(s)
+MOSS IMU: status QUIET, no sample for 12 s - IMU contacts and gyro prior OFF, 0 contact(s) so far, 1 quiet spell(s)
+MOSS IMU: status waiting, no sample 10 s after start - IMU contacts and gyro prior OFF
+```
+
+The first line comes once, 1 s after the last sample (the samples had been
+flowing); the second once the resumed stream has run for 1 s and still
+flows, with its rate over that second (a burst that stops again within that
+second says nothing, and the quiet spell goes on). A stream that keeps
+dropping out says "no sample" at most once every 5 s, and the next such
+line counts the spells it did not say.
+The status line comes every 10 s, quiet or not; before the first sample it
+says `waiting` (the camera takes a few seconds to start, so nothing louder
+comes earlier). All of it goes through the dimOS logger, at warning level for
+quiet, into the run's log.
Why the threshold should hold against the rover's own stops: the launcher sets
the firmware ramp to 5 ms per % (`MOSS_RAMP_MS="5 5"`), so a commanded stop
@@ -153,7 +215,8 @@ its neighbours carried about 300. The revolutions after it registered at the
wrong heading and kept it: one shaken sweep, one jump of the whole map.
So `LidarOdometry` listens to `bump` too (the same stream, whoever publishes
-on it) and stamps the time of each contact. Then:
+on it: the IMU's front contacts and the explorer's back-off) and stamps the
+time of each contact. Then:
1. **The shaken sweep is dropped.** A revolution that arrives within
`MOSS_CONTACT_WINDOW_S` (0.4 s) after a contact and carries fewer than
@@ -224,8 +287,9 @@ reads the count only); a shaken sweep whose revolution is handled before
`handle_bump` stamps the contact (the window only looks forward from the
stamp, so that sweep is registered at the wrong heading, the measured +6.4
degree case, and the relocation the late stamp arms starts from that
-heading); and a contact nothing publishes on `bump`. The robot replay will
-show how often a sweep beats its bump.
+heading); a contact behind, which goes out on `bump_rear`, a stream the
+odometry does not listen to; and a contact nothing publishes on `bump`. The
+robot replay will show how often a sweep beats its bump.
## Knobs
@@ -236,11 +300,11 @@ show how often a sweep beats its bump.
| `MOSS_BUMP_AXIS` | `+z` | the forward axis of the camera's frame, x, y or z with a sign |
| `MOSS_BUMP_DEBOUNCE_S` | 0.7 | seconds of silence after a contact, 0 to 10 |
| `MOSS_IMU_LOG` | unset | a CSV path: every sample is appended (below) |
-| `MOSS_GYRO` | on with `MOSS_IMU` | the gyro prior of the lidar odometry from the in-process IMU (above); `0` turns it off; with `MOSS_IMU=0`, `1` is refused with a warning |
+| `MOSS_GYRO` | off | `1` turns on the gyro prior of the lidar odometry from the in-process IMU once `tools/gyro_sign_bench.py` has measured its sign on this robot (above); with `MOSS_IMU=0`, `1` is refused with a warning |
| `MOSS_GYRO_FORCE` | off | `1` with `MOSS_IMU=0 MOSS_GYRO=1`: the prior on dimOS's second IMU pipeline, an experiment |
They are read when the blueprint is built (the build log says
-`MOSS blueprint: IMU contacts on bump, forward axis +z, threshold 4 m/s^2, ...`);
+`MOSS blueprint: IMU contacts on bump (front) and bump_rear (rear), forward axis +z, threshold 4 m/s^2, ...`);
a value that does not parse is refused with a warning and the default stays.
## Bringing it up
@@ -273,7 +337,8 @@ a value that does not parse is refused with a warning and the default stays.
2. **A stationary launch.** `tools/moss-fly.sh map`, the rover still.
`tools/moss-fly.sh log` must show `MOSS IMU: motion module open on the
- camera's own device` and `MOSS IMU: first sample`, and the cockpit must show
+ camera's own device`, `MOSS IMU: first sample`, then `MOSS IMU: status
+ alive` every 10 s, and the cockpit must show
colour and the depth obstacles as before. This launch was seen on the robot
(colour and depth at their usual rate, the IMU at 199 Hz, gravity on -y),
which is why the IMU is on by default; `MOSS_IMU=0` turns it off.
@@ -326,10 +391,23 @@ a value that does not parse is refused with a warning and the default stays.
`benches/bench_bump_imu_cold.py`: the rule on synthetic 200 Hz traces with
gravity on y (a 6 m/s^2 pulse of 60 ms while commanded is exactly one contact
-of about -6.0 m/s^2; no command, a wobble, the wrong sign, a tilt, a pitched
-camera are none; the debounce; the knobs), the module (telemetry then samples
--> one `bump` and the log line), the CSV, and `MossRealSense` on a fake
+of about -6.0 m/s^2, in front; no command, a wobble, the wrong sign, a tilt, a
+pitched camera are none; the debounce; the knobs), the sides (a kick while
+reversing is behind; a front contact then a contact behind 0.18 s or 0.4 s
+later, during one pivot or once the command reversed, is two contacts; a
+kick of the other sign 0.06 s after a contact, the ringing included when the
+telemetry already says reverse, is its rebound: one contact, the rebound
+counted once), the module (telemetry then samples -> one `bump`, or one
+`bump_rear` while reversing, and the log line; a contact and its rebound ->
+one `bump` and one rebound line), the CSV, `MossRealSense` on a fake
pyrealsense2 (the motion sensor found by name on the pipeline's own device,
-the profiles it opens, stop, every failure leaving the camera running).
-`benches/bench_moss_blueprints_cold.py` section J: the blueprint with and
-without `MOSS_IMU`, and where `bump`, `imu` and `base_telemetry` are wired.
+the profiles it opens, stop, every failure leaving the camera running) and
+the watchdog on a fake clock and on its own thread (quiet at 1 s, back with
+its rate, a burst that stops again says nothing, the rate limit, the status
+line, and `start()` starting the thread).
+`benches/bench_moss_blueprints_cold.py` sections J, K and L: the blueprint with
+and without `MOSS_IMU`, where `bump`, `bump_rear`, `stall`, `imu` and
+`base_telemetry` are wired, the gyro prior off by default, and every camera
+in a worker of its own. `benches/bench_recovering_planner_cold.py`: `bump`
+backs off in reverse, `bump_rear` moves forward, `stall` abandons the goal
+with no motion and stops a running escape dead.
diff --git a/moss_dimos/blueprints.py b/moss_dimos/blueprints.py
index 6507d9b..2c713e7 100644
--- a/moss_dimos/blueprints.py
+++ b/moss_dimos/blueprints.py
@@ -34,16 +34,19 @@ Switches (env, read when moss-nav / moss-explore is built; robot_profile.env_on
parses them: 0, false, no or off = off, any other value = on, unset = the default):
MOSS_CAMERA=0 no RealSense (default on: colour 640x480 @ 5 fps, JPEG on the bus, plus depth aligned
to colour at the same rate, turned into map obstacles by lidar_odometry)
- MOSS_GYRO=0 no gyro prior for the lidar odometry (default ON with MOSS_IMU: each registration starts
- from the yaw the RealSense's gyro integrated since the last revolution, read in the
- camera's own process). With MOSS_IMU=0 the gyro would come from dimOS's second IMU
- pipeline, which fails to open on the rover and takes the camera down with it: MOSS_GYRO=1
- is then refused with a warning, and MOSS_GYRO_FORCE=1 builds it anyway (an experiment)
+ MOSS_GYRO=1 the gyro prior for the lidar odometry: each registration starts from the yaw the
+ RealSense's gyro integrated since the last revolution, read in the camera's own process.
+ Default OFF until its sign is measured on this robot (run tools/gyro_sign_bench.py once,
+ then MOSS_GYRO=1): a wrong-sign prior is worse than none. Needs MOSS_IMU: with
+ MOSS_IMU=0 the gyro would come from dimOS's second IMU pipeline, which fails to open on
+ the rover and takes the camera down with it, so MOSS_GYRO=1 is then refused with a
+ warning, and MOSS_GYRO_FORCE=1 builds it anyway (an experiment)
MOSS_IMU=0 no IMU contacts (default ON: the RealSense's IMU is read inside the camera's own
process, colour, depth and IMU proven alive together on the robot; a deceleration against
- the commanded direction publishes bump). Knobs: MOSS_BUMP_ACCEL (default 4.0 m/s^2),
- MOSS_BUMP_DEBOUNCE_S (default 0.7), MOSS_IMU_LOG=<csv> (every sample); docs/imu.md.
- Needs the camera: with MOSS_CAMERA=0 there are no IMU contacts (said in the log)
+ the commanded direction publishes bump, in front, or bump_rear, behind). Knobs:
+ MOSS_BUMP_ACCEL (default 4.0 m/s^2), MOSS_BUMP_DEBOUNCE_S (default 0.7),
+ MOSS_IMU_LOG=<csv> (every sample); docs/imu.md. Needs the camera: with MOSS_CAMERA=0
+ there are no IMU contacts (said in the log)
MOSS_DESKEW=1 kiss-icp straightens each lidar revolution by the motion prior (default OFF: on the
rover its first thread fails and the odometry stops; an experiment)
MOSS_SOUNDS=0 no sound module (default on when pw-play or paplay is on the PATH: the sound pack
@@ -90,8 +93,15 @@ needs two things, and the second one is not obvious:
still find the coordinator by the name they expect, and ControlCoordinator
.start() warns if a subclass omits it.
-The wrist camera module (WristCamera) is a class built on first use and
-served by the same module __getattr__, so dimOS pickles it by reference too.
+The camera modules are classes built on first use and served by the same
+module __getattr__, so dimOS pickles them by reference too: the wrist camera
+(WristCamera) and the RealSense (DedicatedMossRealSense, or
+DedicatedRealSenseCamera with MOSS_IMU=0). Each runs in a worker process of
+its own (dedicated_worker), like the coordinator, the lidar and the pad: a
+camera that shares its worker with busy modules (the odometry, the costmap,
+the explorer, the recorder) gets starved under load, and its depth
+obstacles and IMU samples arrive late or not at all while the sensor itself
+drops no frame.
"""
from __future__ import annotations
@@ -112,7 +122,7 @@ from dimos.msgs.std_msgs.String import String
from dimos.utils.logging_config import setup_logger
from moss_dimos import robot_profile
-from dimos_lcm.std_msgs import Bool # the SAME Bool class as Explorer2 / RecoveringPlanner: one 'bump' stream type on the bus
+from dimos_lcm.std_msgs import Bool # the SAME Bool class as RecoveringPlanner's Ins: one stream type per name
from moss_dimos.moss_adapter import telemetry_payload
from moss_dimos.robot_profile import (MOSS_LIDAR_MISSING, MOSS_QTPY_MISSING,
RobotProfile)
@@ -166,10 +176,15 @@ class MossControlCoordinator(ControlCoordinator):
battery, mode, track outputs - see moss_adapter.telemetry_payload). The
cockpit reads the battery there, so nothing but this process ever opens
the motor board's port. An adapter without telemetry publishes nothing.
+
+ A new stall in that telemetry (the adapter's stall guard: tracks
+ commanded, encoders frozen) is published on `stall`. A stall is inferred,
+ not felt: the planner stops and abandons the goal with no motion. Only a
+ felt contact (BumpImu's `bump` / `bump_rear`) earns the 0.20 m escape.
"""
base_telemetry: Out[String]
- bump: Out[Bool] # a stall of the base (moss_adapter stall guard) = a contact: the planner's escape backs off
+ stall: Out[Bool] # a stall of the base: the planner stops and abandons the goal, no motion
TELEMETRY_PERIOD_S = 0.5
@@ -208,9 +223,10 @@ class MossControlCoordinator(ControlCoordinator):
stalls = int(payload.get("stall_count") or 0)
if stalls > getattr(self, "_stalls_seen", 0):
self._stalls_seen = stalls
- _logger.warning(f"base stall #{stalls}: publishing bump (contact) for the planner's escape")
- if getattr(self.bump, "transport", None) is not None:
- self.bump.publish(Bool(data=True))
+ _logger.warning(f"base stall #{stalls}: publishing stall (the planner stops and "
+ "abandons the goal, no motion)")
+ if getattr(self.stall, "transport", None) is not None:
+ self.stall.publish(Bool(data=True))
last_error = None
except Exception as exc: # noqa: BLE001
cause = f"{type(exc).__name__}: {exc}"
@@ -378,12 +394,44 @@ def _wrist_module_class():
from dimos.hardware.sensors.camera.module import CameraModule
cls = type("WristCamera", (CameraModule,),
- {"__doc__": "The arm's UVC camera (dimOS Webcam hardware, cv2 capture).",
- "__module__": __name__, "__qualname__": "WristCamera"})
+ {"__doc__": "The arm's UVC camera (dimOS Webcam hardware, cv2 capture), in a worker of its own.",
+ "__module__": __name__, "__qualname__": "WristCamera",
+ # cv2 capture and the JPEG encode at 5 fps: its own worker, like the RealSense
+ "dedicated_worker": True})
_WRIST_CLASS = cls
return _WRIST_CLASS
+# The RealSense module, in a worker of its own: name -> (module, class) it subclasses.
+_REALSENSE_BASES = {
+ "DedicatedMossRealSense": ("moss_dimos.realsense_imu", "MossRealSense"), # the IMU in the camera's process
+ "DedicatedRealSenseCamera": ("dimos.hardware.sensors.camera.realsense.camera", "RealSenseCamera"), # MOSS_IMU=0
+}
+_REALSENSE_CLASSES: dict = {}
+
+
+def _realsense_module_class(name: str):
+ """The RealSense module class `name` (a key of _REALSENSE_BASES): its base
+ class plus `dedicated_worker = True`, nothing else (the same streams, the
+ same RPCs, the same kwargs). The camera was the one sensor left sharing a
+ worker; under load its depth obstacles and IMU samples starved while the
+ sensor dropped no frame. Built on first use (the camera stack is imported
+ only then, so a coordinator worker never loads it) and exposed as
+ `moss_dimos.blueprints.<name>` through the module __getattr__, so dimOS
+ pickles it by reference into its worker processes."""
+ cls = _REALSENSE_CLASSES.get(name)
+ if cls is None:
+ import importlib
+
+ module_name, base_name = _REALSENSE_BASES[name]
+ base = getattr(importlib.import_module(module_name), base_name)
+ cls = type(name, (base,),
+ {"__doc__": f"{base_name} in a worker process of its own (dedicated_worker).",
+ "__module__": __name__, "__qualname__": name, "dedicated_worker": True})
+ _REALSENSE_CLASSES[name] = cls
+ return cls
+
+
def _wrist_part(index: int):
from functools import partial
from dimos.hardware.sensors.camera.webcam import Webcam
@@ -440,12 +488,17 @@ def _common_parts(ports: dict, profile: RobotProfile) -> list:
from moss_dimos.rplidar_c1 import RPLidarC1
# the rotation prior of the lidar odometry: the RealSense's gyro, read in the camera's own process
- # with the IMU (MOSS_IMU, on by default), so MOSS_GYRO follows MOSS_IMU unless set. Without MOSS_IMU
- # the gyro would come from dimOS's second IMU pipeline, which fails with 'No device connected' on the
- # rover (colour and depth then never start either): refused unless MOSS_GYRO_FORCE=1, an experiment
+ # with the IMU (MOSS_IMU, on by default). OFF unless MOSS_GYRO=1, until its sign is measured on this
+ # robot (tools/gyro_sign_bench.py: slow pivots both ways, the gyro integral against the lidar's yaw).
+ # The axis comes from librealsense's convention, never from a turn: a prior with the wrong sign
+ # seeds every registration with the opposite rotation and paints the room as rotated copies, which
+ # is worse than none. Constant velocity lags a full-power pivot (the map drifts) but never does that.
+ # Without MOSS_IMU the gyro would come from dimOS's second IMU pipeline, which fails with 'No device
+ # connected' on the rover (colour and depth then never start either): refused unless
+ # MOSS_GYRO_FORCE=1, an experiment
has_camera = robot_profile.env_on("MOSS_CAMERA", True)
in_process_imu = has_camera and robot_profile.env_on("MOSS_IMU", True)
- gyro = robot_profile.env_on("MOSS_GYRO", in_process_imu)
+ gyro = robot_profile.env_on("MOSS_GYRO", False)
if gyro and not has_camera:
_logger.warning("MOSS blueprint: MOSS_GYRO needs the RealSense and MOSS_CAMERA is off: no gyro prior")
gyro = False
@@ -458,6 +511,10 @@ def _common_parts(ports: dict, profile: RobotProfile) -> list:
"fails on the rover and takes the camera down): no gyro prior. MOSS_IMU=1 gives it "
"from the camera's own process; MOSS_GYRO_FORCE=1 is the experiment")
gyro = False
+ if in_process_imu:
+ _logger.info("MOSS blueprint: lidar odometry prior: gyro=True (MOSS_GYRO=1)" if gyro else
+ "MOSS blueprint: lidar odometry prior: gyro=False "
+ "(run tools/gyro_sign_bench.py once, then MOSS_GYRO=1)")
# MOSS_DESKEW=1 is an experiment too: kiss-icp's deskew (each point moved by its share of the motion
# prior) dies on the rover at its first thread, and the odometry loop with it
deskew = robot_profile.env_on("MOSS_DESKEW", False)
@@ -465,20 +522,20 @@ def _common_parts(ports: dict, profile: RobotProfile) -> list:
_coordinator_blueprint(_moss_base(address=ports["base"])),
_gamepad_part(),
RPLidarC1.blueprint(port=ports["lidar"], baudrate=LIDAR_BAUDRATE, frame_id="lidar_link"),
- # the rotation prior: the RealSense's gyro when MOSS_GYRO is on (default): a full-power pivot
- # (254 deg/s measured on the floor) turns 25 deg between two scans, more than the constant-velocity
- # prior follows (the map drifted); constant velocity otherwise
+ # the rotation prior: the RealSense's gyro with MOSS_GYRO=1 (a full-power pivot, 254 deg/s measured
+ # on the floor, turns 25 deg between two scans, more than the constant-velocity prior follows);
+ # constant velocity otherwise, the default until the gyro's sign is measured (above)
LidarOdometry.blueprint(use_gyro_prior=gyro, deskew=deskew),
MossCostMap.blueprint(),
]
# MOSS_IMU=1: the IMU is opened inside the camera's own process (MossRealSense) and BumpImu turns
- # its decelerations into contacts on `bump`; the IMU lives on the RealSense, so no camera, no IMU
+ # its decelerations into contacts on `bump` (in front) and `bump_rear` (behind); the IMU lives on
+ # the RealSense, so no camera, no IMU
imu = robot_profile.env_on("MOSS_IMU", True)
if imu and not robot_profile.env_on("MOSS_CAMERA", True):
_logger.warning("MOSS blueprint: MOSS_IMU needs the RealSense and MOSS_CAMERA is off: no IMU contacts")
imu = False
if robot_profile.env_on("MOSS_CAMERA", True):
- from dimos.hardware.sensors.camera.realsense.camera import RealSenseCamera
from dimos.msgs.geometry_msgs.Quaternion import Quaternion
from dimos.msgs.geometry_msgs.Transform import Transform
from dimos.msgs.geometry_msgs.Vector3 import Vector3
@@ -493,16 +550,17 @@ def _common_parts(ports: dict, profile: RobotProfile) -> list:
serial = os.environ.get("MOSS_RS_SERIAL", "").strip()
if serial:
cam_kwargs["serial_number"] = serial
+ # the camera in a worker of its own (_realsense_module_class), with or without the IMU
if imu:
- from moss_dimos.realsense_imu import MossRealSense
cam_kwargs.update(enable_imu=True, imu_hz=IMU_HZ)
- parts.append(MossRealSense.blueprint(**cam_kwargs))
+ parts.append(_realsense_module_class("DedicatedMossRealSense").blueprint(**cam_kwargs))
else:
- parts.append(RealSenseCamera.blueprint(**cam_kwargs))
+ parts.append(_realsense_module_class("DedicatedRealSenseCamera").blueprint(**cam_kwargs))
if imu:
from moss_dimos.bump_imu import BumpImu, bump_settings
knobs = bump_settings()
- _logger.info(f"MOSS blueprint: IMU contacts on bump, forward axis {knobs['axis']}, "
+ _logger.info("MOSS blueprint: IMU contacts on bump (front) and bump_rear (rear), "
+ f"forward axis {knobs['axis']}, "
f"threshold {knobs['threshold']:g} m/s^2, debounce {knobs['debounce_s']:g} s, "
f"csv {knobs['log_path'] or 'off'}")
parts.append(BumpImu.blueprint(**knobs))
@@ -641,10 +699,13 @@ _BUILDERS = {"moss_base_blueprint": build_moss_base,
def __getattr__(name: str):
"""Entry points load `moss_<x>_blueprint` as attributes: build on first
- access, then cache. `WristCamera` is the dynamic camera class (built
+ access, then cache. `WristCamera`, `DedicatedMossRealSense` and
+ `DedicatedRealSenseCamera` are the dynamic camera classes (each built
once, so pickling by reference finds the same object)."""
if name == "WristCamera":
return _wrist_module_class()
+ if name in _REALSENSE_BASES:
+ return _realsense_module_class(name)
builder = _BUILDERS.get(name)
if builder is None:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/moss_dimos/bump_imu.py b/moss_dimos/bump_imu.py
index d464269..821b6cc 100644
--- a/moss_dimos/bump_imu.py
+++ b/moss_dimos/bump_imu.py
@@ -1,14 +1,25 @@
-"""BumpImu: contacts felt by the RealSense's accelerometer, published on `bump`.
+"""BumpImu: contacts felt by the RealSense's accelerometer, published on
+`bump` (a contact in front) or `bump_rear` (a contact behind).
The encoders are a poor bumper: a track that slips keeps turning against a
wall, an oblique contact leaves one track free, and the stall guard needs a
-full second of frozen ticks before it calls a contact. The chassis itself
+full second of frozen ticks before it calls a stall. The chassis itself
says it at once: hitting something while driving is a short, hard
deceleration along the direction of travel. This module reads it on the
camera's IMU (`imu`, published by moss_dimos.realsense_imu.MossRealSense) and
-publishes Bool(True) on `bump`, the stream the coordinator's stall guard and
-the explorer's back-off already publish on: the planner's escape, the
-costmap's contact memory and the sounds react to it the same way.
+publishes Bool(True) on the side of the contact:
+
+ * `bump` in front: the planner's escape backs off 0.20 m in reverse.
+ The explorer's back-off publishes on the same stream; the
+ costmap, the sounds and the lidar odometry listen to it.
+ * `bump_rear` behind: the planner's escape moves 0.20 m FORWARD. A rear
+ contact is not a front wall: the costmap and the sounds do
+ not listen to it.
+
+The two are opposite reflexes. The escape moves away from the contact; a
+contact felt while reversing and answered with another reverse drives the
+rover back into what it just hit. A stall of the base is not published here
+or on either stream: it is inferred, not felt (the coordinator's `stall`).
The rule (ImuContactDetector, pure, benched with known traces):
* forward = one signed accel axis of the frame the camera publishes in
@@ -18,9 +29,16 @@ The rule (ImuContactDetector, pure, benched with known traces):
of the last 0.5 s before it, so gravity, a tilted camera or a slope cancel;
* a contact is |high-pass| >= MOSS_BUMP_ACCEL (default 4.0 m/s^2), with a
non-zero track command younger than 1 s, decelerating AGAINST that command
- (driving forward: <= -threshold; reversing: >= +threshold; pivoting, the
- tracks of opposite signs: either sign);
- * once per contact: nothing for MOSS_BUMP_DEBOUNCE_S (default 0.7 s) after one.
+ (driving forward: <= -threshold, in front; reversing: >= +threshold,
+ behind; pivoting, the tracks of opposite signs: either sign, and the sign
+ gives the side: a deceleration is in front, a forward kick behind);
+ * once per contact, one debounce per side: nothing more on the same side
+ for MOSS_BUMP_DEBOUNCE_S (default 0.7 s). A front contact and a rear one
+ are opposite reflexes, not repeats of each other: the other side counts
+ at once. One exception, which an accelerometer has and a switch would
+ not: a kick of the other sign within REBOUND_S (0.1 s) of a contact is
+ that impact's rebound, whatever the command says by then. It is logged
+ once ("MOSS IMU: ... taken as its rebound"), never published.
The command is the firmware's target_pct from the coordinator's
`base_telemetry` (2 Hz), aged by the time since it arrived plus the
@@ -29,13 +47,23 @@ firmware's own age of that line.
In imu : Imu the camera's accel + gyro (every sample: a plain subscription, not the
latest-only async handler, so a burst of samples is never thinned)
In base_telemetry : String JSON with target_pct [l, r] (percent, + = forward) and firmware_age_s
- Out bump : Bool True on a contact
+ Out bump : Bool True on a contact in front
+ Out bump_rear : Bool True on a contact behind
Each contact is logged as one line, e.g.
- IMU contact: forward -4.8 m/s^2 (threshold 4.0) while commanded L=+70% R=+60%
+ IMU contact: forward -4.8 m/s^2 (threshold 4.0) while commanded L=+70% R=+60%, front contact -> bump
(the cockpit's decision feed matches its start, "IMU contact"). The other
-lines start with "MOSS IMU:": the knobs at start, the first sample, then one
-line a minute with the sample rate and where gravity sits.
+lines start with "MOSS IMU:": the knobs at start, the first sample, and the
+watchdog's (ImuWatchdog). A contact sensor must never go quiet unnoticed:
+when no sample has come for 1 s while the stack runs, one warning says so,
+ MOSS IMU: no sample for 1 s - IMU contacts and gyro prior OFF
+and one line says when the samples resume, at what rate,
+ MOSS IMU: samples back (199 Hz) after 3.2 s quiet
+(a stream that keeps dropping out says it at most once every 5 s, with a
+count of the spells in between). Every 10 s a status line gives the state
+(alive, QUIET, or waiting for the first sample), the sample rate, where
+gravity sits and the contacts so far. All of it goes through the dimOS
+logger, into the run's log.
MOSS_IMU_LOG=<path> appends every sample to a CSV (ts, ax, ay, az, gx, gy,
gz, hp, cmd_l, cmd_r), flushed every 2 s: the signature of real contacts,
@@ -58,7 +86,7 @@ from dimos.core.stream import In, Out
from dimos.msgs.sensor_msgs.Imu import Imu
from dimos.msgs.std_msgs.String import String
from dimos.utils.logging_config import setup_logger
-from dimos_lcm.std_msgs import Bool # the SAME Bool class as the coordinator's and the explorer's bump
+from dimos_lcm.std_msgs import Bool # the SAME Bool class as the explorer's bump and the coordinator's stall
logger = setup_logger()
@@ -70,7 +98,20 @@ WARMUP_S = 0.25 # history the window needs before a high-pass va
COMMAND_MAX_AGE_S = 1.0 # a track command older than this is no command
CSV_FLUSH_S = 2.0
CSV_HEADER = "ts,ax,ay,az,gx,gy,gz,hp,cmd_l,cmd_r\n"
-HEARTBEAT_S = 60.0 # one "IMU alive" line per minute of samples
+QUIET_S = 1.0 # no sample for this long while the stack runs: the stream is quiet
+QUIET_REPEAT_S = 5.0 # at most one "no sample" line this often; the spells in between are counted
+RATE_WINDOW_S = 1.0 # "samples back" measures the rate over this much of the resumed stream
+STATUS_PERIOD_S = 10.0 # one status line this often, quiet or not
+WATCH_PERIOD_S = 0.1 # how often the watchdog thread looks
+FLOWING_S = 2 * WATCH_PERIOD_S # a resumed stream whose last sample is older than this has stopped again
+# An impact rings: right after the hit the accelerometer can feel a kick of the
+# other sign, and by then the telemetry may already carry the escape's
+# reverse. The contact measured on this robot lasted 20 ms (four samples past
+# -4 m/s^2, docs/imu.md): 0.1 s covers it five times over, while two real
+# contacts on opposite sides (a rover wedging into a corner) benched 0.18 s
+# apart stay two. The figure comes from that impact length, not from a
+# recorded rebound: a MOSS_IMU_LOG pivot contact is the recording that sets it.
+REBOUND_S = 0.1
THRESHOLD_MAX = 100.0
DEBOUNCE_MAX_S = 10.0
_AXIS_RE = re.compile(r"^([+-]?)([xyz])$")
@@ -119,6 +160,15 @@ def bump_settings(env: dict | None = None) -> dict:
return out
+def contact_side(direction: int, hp: float) -> str:
+ """"front" or "rear" for a contact against the command: reversing is
+ behind, driving forward in front, and on a pivot the sign of the
+ high-pass decides (a deceleration of the forward axis is in front)."""
+ if direction < 0 or (direction == 0 and hp > 0):
+ return "rear"
+ return "front"
+
+
def command_direction(commanded: tuple[int, int] | None) -> int | None:
"""+1 forward (no track backward), -1 reverse (no track forward), 0 a
pivot (tracks of opposite signs), None no command (None or (0, 0))."""
@@ -139,12 +189,15 @@ def command_direction(commanded: tuple[int, int] | None) -> int | None:
class ImuContactDetector:
"""The contact rule of the module docstring, on raw samples. Pure: no
- clock, no I/O. feed() returns True once per contact; last_hp is the
- high-pass of the last sample (None while the window warms up)."""
+ clock, no I/O. feed() returns True once per contact, its side in
+ last_contact["side"]; last_hp is the high-pass of the last sample (None
+ while the window warms up). A rebound is counted in `rebounds` once per
+ contact, described in last_rebound, and feed() returns False for it."""
def __init__(self, axis: str = DEFAULT_AXIS, threshold: float = DEFAULT_THRESHOLD,
debounce_s: float = DEFAULT_DEBOUNCE_S, window_s: float = WINDOW_S,
- warmup_s: float = WARMUP_S, command_max_age_s: float = COMMAND_MAX_AGE_S) -> None:
+ warmup_s: float = WARMUP_S, command_max_age_s: float = COMMAND_MAX_AGE_S,
+ rebound_s: float = REBOUND_S) -> None:
self.axis = axis
self._index, self._sign = parse_axis(axis)
self.threshold = float(threshold)
@@ -152,13 +205,19 @@ class ImuContactDetector:
self.window_s = float(window_s)
self.warmup_s = float(warmup_s)
self.command_max_age_s = float(command_max_age_s)
+ self.rebound_s = float(rebound_s)
self._window: deque[tuple[float, float]] = deque()
self._sum = 0.0
self._appends = 0
self.last_hp: float | None = None
self.last_contact_ts: float | None = None
self.last_contact: dict | None = None
+ self._last_by_side: dict[str, float] = {} # side -> ts of its last contact
self.contacts = 0
+ self.rebounds = 0
+ self.last_rebound: dict | None = None
+ self._rebound_side: str | None = None # a rebound in progress: its samples are past the threshold
+ self._rebound_of: float | None = None # ts of the contact whose rebound was counted
@classmethod
def from_env(cls, env: dict | None = None) -> "ImuContactDetector":
@@ -203,6 +262,7 @@ class ImuContactDetector:
hp = self._high_pass(ts, value)
self.last_hp = hp
if hp is None or abs(hp) < self.threshold:
+ self._rebound_side = None # whatever rang has ended
return False
try:
fresh = float(command_age_s) <= self.command_max_age_s
@@ -215,18 +275,171 @@ class ImuContactDetector:
return False # driving forward: only a deceleration is a contact
if direction < 0 and hp < self.threshold:
return False # reversing: only a forward kick is a contact
- if self.last_contact_ts is not None and 0.0 <= ts - self.last_contact_ts < self.debounce_s:
+ side = contact_side(direction, hp)
+ of = self._rebound_target(side, ts)
+ if of is not None:
+ self._rebound_side = side
+ if of != self._rebound_of: # counted once per contact, however many samples it lasts
+ self._rebound_of = of
+ self.rebounds += 1
+ self.last_rebound = {"ts": ts, "hp": hp, "commanded": (int(commanded[0]), int(commanded[1])),
+ "side": side, "after_s": ts - of}
+ return False
+ self._rebound_side = None
+ if self._repeats(side, ts):
return False
+ self._last_by_side[side] = ts
self.last_contact_ts = ts
self.contacts += 1
- self.last_contact = {"ts": ts, "hp": hp, "commanded": (int(commanded[0]), int(commanded[1]))}
+ self.last_contact = {"ts": ts, "hp": hp, "commanded": (int(commanded[0]), int(commanded[1])),
+ "side": side}
return True
+ def _rebound_target(self, side: str, ts: float) -> float | None:
+ """The ts of the contact this sample is the rebound of, or None. A
+ rebound is a sample of the other side within rebound_s of that side's
+ last contact, whatever the command; once one has started, its samples
+ stay the rebound while they are past the threshold."""
+ other = "front" if side == "rear" else "rear"
+ last = self._last_by_side.get(other)
+ if last is None:
+ return None
+ if 0.0 <= ts - last < self.rebound_s or (side == self._rebound_side and self._rebound_of == last):
+ return last
+ return None
-def contact_line(hp: float, threshold: float, commanded: tuple[int, int]) -> str:
+ def _repeats(self, side: str, ts: float) -> bool:
+ """True when a contact at ts repeats the last one of the SAME side
+ within debounce_s. One debounce per side: a contact on the other side
+ is never a repeat (past the rebound, it is a new contact)."""
+ last = self._last_by_side.get(side)
+ return last is not None and 0.0 <= ts - last < self.debounce_s
+
+
+def contact_stream(side: str) -> str:
+ """The stream a contact on that side is published on."""
+ return "bump_rear" if side == "rear" else "bump"
+
+
+def contact_line(hp: float, threshold: float, commanded: tuple[int, int], side: str) -> str:
"""The log line of one contact (the cockpit's decision feed reads it)."""
return (f"IMU contact: forward {hp:+.1f} m/s^2 (threshold {threshold:.1f}) "
- f"while commanded L={int(commanded[0]):+d}% R={int(commanded[1]):+d}%")
+ f"while commanded L={int(commanded[0]):+d}% R={int(commanded[1]):+d}%, "
+ f"{side} contact -> {contact_stream(side)}")
+
+
+def rebound_line(hp: float, commanded: tuple[int, int], side: str, after_s: float) -> str:
+ """The log line of a kick taken as the rebound of the last contact: said
+ once, so no felt kick is silent, and kept off the "IMU contact" lines the
+ cockpit reads as contacts."""
+ other = "front" if side == "rear" else "rear"
+ return (f"MOSS IMU: forward {hp:+.1f} m/s^2 while commanded L={int(commanded[0]):+d}% "
+ f"R={int(commanded[1]):+d}%, {after_s:.2f} s after the {other} contact: taken as its rebound, "
+ f"not published on {contact_stream(side)}")
+
+
+class ImuWatchdog:
+ """Says when the imu stream goes quiet and when it comes back, and gives a
+ status line every status_s (module docstring). Pure: the caller passes a
+ monotonic clock. sample() runs on the subscription's thread, tick() on the
+ watchdog's; one lock between them. tick() returns the lines to log, as
+ (level, text) pairs.
+
+ Quiet means no sample for quiet_s after at least one arrived: before the
+ first sample the status line says "waiting" instead (the camera takes a
+ few seconds to start). A quiet spell is said once, at most once per
+ repeat_s (the spells in between are counted in the next line), and its
+ end once the resumed stream has run for rate_window_s and still flows
+ (its last sample younger than flowing_s), with its rate. A burst that has
+ stopped again by then ends with no line: the spell goes on."""
+
+ def __init__(self, quiet_s: float = QUIET_S, repeat_s: float = QUIET_REPEAT_S,
+ rate_window_s: float = RATE_WINDOW_S, status_s: float = STATUS_PERIOD_S,
+ flowing_s: float = FLOWING_S) -> None:
+ self.quiet_s = float(quiet_s)
+ self.repeat_s = float(repeat_s)
+ self.rate_window_s = float(rate_window_s)
+ self.status_s = float(status_s)
+ self.flowing_s = float(flowing_s)
+ self._lock = threading.Lock()
+ self._started: float | None = None
+ self._last: float | None = None # arrival of the last sample
+ self.quiet = False
+ self.spells = 0 # quiet spells since start
+ self._quiet_from: float | None = None # arrival of the last sample before the spell
+ self._spell_said = False # this spell's "no sample" line was logged
+ self._unsaid = 0 # spells not logged since the last "no sample" line
+ self._said_t = -math.inf # when the last "no sample" line was logged
+ self._back: list[float] | None = None # [first, last arrival, count] of the resumed stream
+ self._status_t: float | None = None
+ self._n = 0 # samples since the last status line
+ self._n_mean = 0 # ... of them finite, in the mean accel
+ self._sum = [0.0, 0.0, 0.0]
+
+ def start(self, now: float) -> None:
+ with self._lock:
+ self._started = self._status_t = float(now)
+
+ def sample(self, now: float, accel: tuple) -> None:
+ """One sample arrived at `now`."""
+ with self._lock:
+ self._last = now
+ self._n += 1
+ if all(math.isfinite(v) for v in accel):
+ self._n_mean += 1
+ for i in range(3):
+ self._sum[i] += accel[i]
+ if self.quiet:
+ if self._back is None:
+ self._back = [now, now, 1]
+ else:
+ self._back[1] = now
+ self._back[2] += 1
+
+ def tick(self, now: float, contacts: int = 0) -> list[tuple[str, str]]:
+ lines: list[tuple[str, str]] = []
+ with self._lock:
+ if self._started is None:
+ return lines
+ if not self.quiet and self._last is not None and now - self._last >= self.quiet_s:
+ self.quiet, self._quiet_from, self._back = True, self._last, None
+ self.spells += 1
+ self._spell_said = now - self._said_t >= self.repeat_s
+ if self._spell_said:
+ more = (f" ({self._unsaid} more quiet spell(s) since the last line)" if self._unsaid else "")
+ lines.append(("warning", f"MOSS IMU: no sample for {self.quiet_s:g} s - "
+ f"IMU contacts and gyro prior OFF{more}"))
+ self._said_t, self._unsaid = now, 0
+ else:
+ self._unsaid += 1
+ if self.quiet and self._back is not None and now - self._back[0] >= self.rate_window_s:
+ first, last, count = self._back
+ if now - last > self.flowing_s:
+ self._back = None # a burst that stopped again: the same spell, nothing said
+ else:
+ rate = (count - 1) / (last - first) if last > first else 0.0
+ if self._spell_said:
+ lines.append(("info", f"MOSS IMU: samples back ({rate:.0f} Hz) after "
+ f"{first - self._quiet_from:.1f} s quiet"))
+ self.quiet, self._back = False, None
+ if now - self._status_t >= self.status_s:
+ lines.append(self._status(now, contacts))
+ self._status_t, self._n, self._n_mean, self._sum = now, 0, 0, [0.0, 0.0, 0.0]
+ return lines
+
+ def _status(self, now: float, contacts: int) -> tuple[str, str]:
+ """The periodic line (under the lock): alive while samples arrive."""
+ tail = f"{contacts} contact(s) so far, {self.spells} quiet spell(s)"
+ if self._last is None:
+ return ("warning", f"MOSS IMU: status waiting, no sample {now - self._started:.0f} s after start "
+ "- IMU contacts and gyro prior OFF")
+ if now - self._last >= self.quiet_s:
+ return ("warning", f"MOSS IMU: status QUIET, no sample for {now - self._last:.0f} s "
+ f"- IMU contacts and gyro prior OFF, {tail}")
+ span, n = now - self._status_t, self._n
+ mean = [v / self._n_mean for v in self._sum] if self._n_mean else [math.nan] * 3
+ return ("info", f"MOSS IMU: status alive, {n} samples in {span:.0f} s ({n / span:.0f} Hz), mean accel "
+ f"({mean[0]:+.2f}, {mean[1]:+.2f}, {mean[2]:+.2f}) m/s^2, {tail}")
class ImuCsvLog:
@@ -290,11 +503,13 @@ class ImuCsvLog:
class BumpImu(Module):
- """IMU contacts on `bump`; see the module docstring."""
+ """IMU contacts on `bump` (in front) and `bump_rear` (behind), and the
+ watchdog on the imu stream; see the module docstring."""
imu: In[Imu]
base_telemetry: In[String]
bump: Out[Bool]
+ bump_rear: Out[Bool]
def __init__(self, axis: str | None = None, threshold: float | None = None,
debounce_s: float | None = None, log_path: str | None = None, **kwargs: Any) -> None:
@@ -312,15 +527,20 @@ class BumpImu(Module):
self._command: tuple[tuple[int, int], float] | None = None # (target_pct, monotonic instant it was true)
self._unsubscribe: Any = None
self._samples = 0
- self._beat_ts: float | None = None
- self._beat_samples = 0
- self._beat_sum = [0.0, 0.0, 0.0]
self._error: str | None = None
+ self._watchdog = ImuWatchdog()
+ self._watch_stop = threading.Event()
+ self._watch_thread: threading.Thread | None = None
+ self._watch_error: str | None = None
@property
def detector(self) -> ImuContactDetector:
return self._detector
+ @property
+ def watchdog(self) -> ImuWatchdog:
+ return self._watchdog
+
@rpc
def start(self) -> None:
super().start()
@@ -329,12 +549,26 @@ class BumpImu(Module):
except Exception as exc: # noqa: BLE001 - no imu stream: no IMU contacts, the stack goes on
logger.warning(f"MOSS IMU: cannot subscribe to imu ({type(exc).__name__}: {exc}); no IMU contacts")
d = self._detector
- logger.info(f"MOSS IMU: contacts on, forward axis {d.axis}, threshold {d.threshold:.1f} m/s^2, "
- f"debounce {d.debounce_s:.1f} s, command younger than {d.command_max_age_s:.1f} s, "
- f"csv {self._csv.path if self._csv else 'off'}")
+ logger.info(f"MOSS IMU: contacts on (front on bump, rear on bump_rear), forward axis {d.axis}, "
+ f"threshold {d.threshold:.1f} m/s^2, debounce {d.debounce_s:.1f} s, command younger than "
+ f"{d.command_max_age_s:.1f} s, csv {self._csv.path if self._csv else 'off'}, "
+ f"watchdog: quiet after {self._watchdog.quiet_s:g} s, status every {self._watchdog.status_s:g} s")
+ self._start_watchdog()
+
+ def _start_watchdog(self) -> None:
+ """The watchdog's clock starts now, and its thread unless it runs."""
+ self._watchdog.start(time.monotonic())
+ if self._watch_thread is None:
+ self._watch_stop.clear()
+ self._watch_thread = threading.Thread(target=self._watch_loop, name="moss-imu-watchdog", daemon=True)
+ self._watch_thread.start()
@rpc
def stop(self) -> None:
+ self._watch_stop.set()
+ thread, self._watch_thread = self._watch_thread, None
+ if thread is not None:
+ thread.join(timeout=1.0)
unsubscribe, self._unsubscribe = self._unsubscribe, None
if unsubscribe is not None:
try:
@@ -345,6 +579,26 @@ class BumpImu(Module):
self._csv.close()
super().stop()
+ def _watch_loop(self) -> None:
+ while not self._watch_stop.wait(WATCH_PERIOD_S):
+ self.watch(time.monotonic())
+
+ def watch(self, now: float) -> list[str]:
+ """One look of the watchdog at `now` (monotonic): its lines are logged
+ through the dimOS logger and returned. Never raises: the thread that
+ says a sensor went quiet must not go quiet itself."""
+ try:
+ lines = self._watchdog.tick(now, self._detector.contacts)
+ except Exception as exc: # noqa: BLE001
+ cause = f"{type(exc).__name__}: {exc}"
+ if cause != self._watch_error:
+ self._watch_error = cause
+ logger.warning(f"MOSS IMU: watchdog look failed ({cause})")
+ return []
+ for level, text in lines:
+ (logger.warning if level == "warning" else logger.info)(text)
+ return [text for _, text in lines]
+
async def handle_base_telemetry(self, msg: String) -> None:
try:
doc = json.loads(getattr(msg, "data", "") or "{}")
@@ -372,14 +626,20 @@ class BumpImu(Module):
a, g = msg.linear_acceleration, msg.angular_velocity
accel = (float(a.x), float(a.y), float(a.z))
gyro = (float(g.x), float(g.y), float(g.z))
+ self._watchdog.sample(time.monotonic(), accel)
+ self._first_sample(accel, msg)
commanded, age = self.command_now()
+ rebounds = self._detector.rebounds
contact = self._detector.feed(ts, accel, commanded, command_age_s=age)
if self._csv is not None:
self._csv.add(ts, accel, gyro, self._detector.last_hp,
commanded if age <= self._detector.command_max_age_s else None)
- self._heartbeat(ts, accel, msg)
if contact:
self._publish_contact()
+ elif self._detector.rebounds != rebounds:
+ r = self._detector.last_rebound or {}
+ logger.info(rebound_line(r.get("hp", 0.0), r.get("commanded", (0, 0)), r.get("side", "rear"),
+ r.get("after_s", 0.0)))
return contact
except Exception as exc: # noqa: BLE001 - one bad sample never kills the subscription
cause = f"{type(exc).__name__}: {exc}"
@@ -389,31 +649,23 @@ class BumpImu(Module):
return False
def _publish_contact(self) -> None:
+ """Log first, publish second: a contact that was felt is on the record
+ even when its stream refuses it."""
c = self._detector.last_contact or {}
- logger.warning(contact_line(c.get("hp", 0.0), self._detector.threshold, c.get("commanded", (0, 0))))
- if getattr(self.bump, "transport", None) is None:
+ side = c.get("side", "front")
+ logger.warning(contact_line(c.get("hp", 0.0), self._detector.threshold, c.get("commanded", (0, 0)), side))
+ name = contact_stream(side)
+ out = getattr(self, name)
+ if getattr(out, "transport", None) is None:
return
try:
- self.bump.publish(Bool(data=True))
+ out.publish(Bool(data=True))
except Exception as exc: # noqa: BLE001 - said, not swallowed; the next contact tries again
- logger.warning(f"MOSS IMU: the contact was not published on bump ({type(exc).__name__}: {exc})")
+ logger.warning(f"MOSS IMU: the contact was not published on {name} ({type(exc).__name__}: {exc})")
- def _heartbeat(self, ts: float, accel: tuple, msg: Imu) -> None:
- """The first sample, then one line per HEARTBEAT_S of samples: the IMU
- is alive, at what rate, and where gravity sits."""
+ def _first_sample(self, accel: tuple, msg: Imu) -> None:
+ """The IMU announced alive at its first sample, with where gravity sits."""
self._samples += 1
if self._samples == 1:
logger.info(f"MOSS IMU: first sample in {getattr(msg, 'frame_id', '?')}: accel "
f"({accel[0]:+.2f}, {accel[1]:+.2f}, {accel[2]:+.2f}) m/s^2")
- self._beat_ts = ts
- return
- self._beat_samples += 1
- for i in range(3):
- self._beat_sum[i] += accel[i]
- if self._beat_ts is not None and ts - self._beat_ts >= HEARTBEAT_S:
- span, n = ts - self._beat_ts, self._beat_samples
- mean = [s / n for s in self._beat_sum]
- logger.info(f"MOSS IMU: {n} samples in {span:.0f} s ({n / span:.0f} Hz), mean accel "
- f"({mean[0]:+.2f}, {mean[1]:+.2f}, {mean[2]:+.2f}) m/s^2, "
- f"{self._detector.contacts} contact(s) so far")
- self._beat_ts, self._beat_samples, self._beat_sum = ts, 0, [0.0, 0.0, 0.0]
diff --git a/moss_dimos/costmap2d.py b/moss_dimos/costmap2d.py
index 12cbc53..647740c 100644
--- a/moss_dimos/costmap2d.py
+++ b/moss_dimos/costmap2d.py
@@ -1,74 +1,100 @@
-"""A 2D costmap for MOSS that learns AND unlearns, from the lidar.
+"""A 2D costmap for MOSS that learns AND unlearns, from the lidar and the depth camera.
dimOS's CostMapper turns a 3D voxel map (a set that never forgets) into a
terrain-slope map meant for a walking robot, and its erosion drops any cell
whose four neighbours are unobserved, which erases thin obstacles such as
-table legs. This module replaces it for a rover with a single-plane lidar:
+table legs. This module replaces it with the scored grid of the rover this
+stack comes from, adapted to MOSS's two sensors: a single-plane lidar 0.20 m
+above the floor and a depth camera on the nose, 0.075 m above it.
* the map must REINFORCE, but with a ceiling (HIT_CAP), or a ramp the
rover struggled on becomes a wall after a day;
- * it must UNLEARN what it sees absent again: every lidar ray that passes
- through a cell is a miss, down to FREE_FLOOR, so a chair that was moved
- away fades in a few revolutions;
+ * it must UNLEARN what it sees absent again, down to FREE_FLOOR, so a
+ chair that was moved away fades;
* reinforcement needs new viewpoints: from one spot a cell gets no more
certain than OCCUPIED_AT - 1, so a passer-by hammered from one parked spot
never becomes a wall; a second viewpoint NEW_VIEWPOINT_M away makes it an
obstacle, and a leg seen from twenty positions is solid (up to HIT_CAP);
- * what the body drove over (body_clear) is cleared: that one is a physical
- certainty, not a sensor reading.
-
-Two sensors write here, through one cloud. lidar_odometry publishes each
-revolution in `world` with every lidar return at exactly the profile's
-lidar_height_m, plus the depth camera's obstacle points at their true height
-(the things below the scan plane: a shoe, a step, a chair base; and, like the
-lidar, the legs of whoever walks past). `lidar_returns` tells them apart, and
-each sensor has its own layer. Lidar returns hit their cell on the lidar
-layer; camera points hit their cell on the camera layer under the same
-two-viewpoint rule, so a camera obstacle becomes a wall on approach like a leg
-does, and carve nothing (a camera obstacle proves nothing about the floor in
-front of it). The lidar rays carve the lidar layer all around, and the camera
-layer only inside the camera's view.
-
-The camera layer forgets through the lidar rays and holds what the camera
-keeps seeing. Without the carve, legs the camera saw while somebody walked
-past would stay walls for the rest of the run. The balance, at MOSS's rates:
-
- * where: the camera layer holds what the scan plane misses (a shoe, a
- chair seat, a table top up to 1.30 m, thin dark legs), so a lidar ray
- passing under or beside such a cell is no evidence against it unless the
- camera looks at the cell too. The rays carve the camera layer only in the
- cells inside the depth camera's horizontal field of view from the current
- pose: a cone of CAMERA_HFOV_DEG from the camera on the nose, centred on
- the rover's heading, out to CAMERA_CARVE_MAX_M from the rover. Outside it
- the camera layer is untouched: a table the rover has turned away from
- stays a wall, and a passer-by's legs are forgotten once the rover looks
- back at where they stood;
- * the carve: a ray that crosses a cell takes 1 from it every RAY_EVERY
- revolutions (5 per second with the lidar at 10 Hz), within RAY_MAX_M of
- the rover;
- * the camera: it runs at 5 fps and lidar_odometry attaches its latest
- obstacle points to every revolution for up to 0.5 s, so a cell in view
- takes a camera hit on every revolution (10 per second);
- * a cell the camera hits in a revolution is spared by that revolution's
- carve, and a camera hit from the SAME viewpoint adds 1 while the cell is
- at 0 or above and below OCCUPIED_AT, so what a carve took in a revolution
- the camera missed comes back on the next one. That hit raises a cell to
- OCCUPIED_AT only if the cell became a wall from two viewpoints and was
- not carved back to 0 since (`camera_wall`); any other cell stops at
- OCCUPIED_AT - 1, so one spot still never makes a wall. Below 0 it adds
- nothing: floor the camera layer holds as free (down to FREE_FLOOR) needs
- as many viewpoints to become a wall as on the lidar layer. Above
- OCCUPIED_AT the parked-rover rule holds: a same-viewpoint hit adds nothing.
-
-So a shoe the camera keeps seeing stays a wall, and a camera wall of score s
-that the camera no longer sees while rays cross it inside the camera's view is
-free after s - 1 carves, RAY_EVERY * (s - 1) revolutions: 0.2 s at 2 (two
-viewpoints), 1.8 s at a HIT_CAP of 10. The price: an obstacle inside that view
-that the camera does not see while the rays cross its cell (hidden behind
-something nearer, or a table top nearer than the camera's vertical field of
-view reaches) is forgotten as fast, and becomes a wall again once the camera
-sees it from two viewpoints (NEW_VIEWPOINT_M of motion apart; turning on the
-spot is one viewpoint).
+ * two layers, because the sensors do not see the same things. What the
+ lidar put down, a lidar ray may clear (`lidar_revolution`). What the
+ camera put down (a shoe, a step, a chair base under the scan plane, a
+ table top above it) only the camera may clear: by seeing the floor there
+ (`camera_floor`), or by seeing THROUGH it at low height (`camera_rays`). A
+ lidar ray passing over a shoe says nothing about the shoe;
+ * what the body drove over (body_clear) is cleared on both layers: that one
+ is a physical certainty, not a sensor reading.
+
+The sensors arrive on two clouds. lidar_odometry publishes each revolution in
+`world` with every lidar return at exactly the profile's lidar_height_m, plus
+the depth camera's obstacle points at their true height (`lidar_returns`
+tells them apart), and the bare floor the camera sees on `camera_floor`
+(z = 0), once per depth frame.
+
+Three guards on the camera layer, each one born from a floor run of the
+original rover:
+
+ * thin legs. A cell the camera JUST called an obstacle is deaf to floor
+ samples and to camera rays for LOW_HIT_PROTECT_S. A table leg thinner than
+ a 5 cm cell is seen in one frame and the floor on its own cell in the next
+ (5 cm of quantisation): hit and miss cancelled forever, and a leg was
+ found at -3 after ten real contacts. lidar_odometry's
+ split_floor_and_obstacles only drops floor samples on an obstacle cell of
+ the SAME frame. This takes nothing from the unlearning: an object that is
+ really gone stops being hit, and fades as before once the window is over.
+ * moving objects. A cell takes a camera hit only if the previous depth frame
+ also saw an obstacle within one cell of it. A rolling vacuum or a walking
+ person moves more than a cell between two depth frames and is rarely
+ written; a foot planted for two frames can still mark a cell, and the
+ camera's floor and rays clear it once it is gone. Furniture repeats, and
+ the one cell of tolerance keeps a thin leg that re-projects one cell off.
+ The price is one frame of latency on a new static obstacle. The gate
+ counts DISTINCT depth frames: lidar_odometry attaches the latest frame's
+ obstacle points to every lidar revolution for up to 0.5 s, so a gate run
+ per revolution would compare a frame with itself and always pass, and the
+ rover moving on during those 0.5 s would turn one look into two
+ viewpoints. A cloud whose camera points are the previous cloud's, byte for
+ byte, stamped less than CAMERA_REPEAT_S after it, is that frame again: it
+ writes nothing on the camera layer. The clouds' own stamps (set when
+ lidar_odometry publishes them) measure that, so a costmap handler running
+ late never takes a re-attached frame for a new one.
+ * camera rays. Every cell a camera ray crosses at low height held nothing
+ standing, or the ray would have ended on it: a miss on the camera layer.
+ Floor samples and obstacle points alike: a floor point 3 m ahead proves
+ the low corridor in front of it. The rays start where the camera is (the
+ profile's camera_xyz_base_m, turned by the heading) and stop one cell short
+ of their point.
+
+The carve band (`carve_z_band`). The band of the original was 0.10 to 0.45 m
+for a camera 0.56 m above the floor: a ray crossing a cell inside it proves
+nothing low stands there; a higher ray flies OVER boxes (0.9 m up says nothing
+about a 0.3 m box) and must erase nothing; a lower one grazes the floor it
+ends on. A floor sample's ray drops in a straight line from the camera height
+H to 0 at its range R, so that band is the stretch from
+1 - 0.45 / 0.56 = 20 % to 1 - 0.10 / 0.56 = 82 % of R: not the first fifth,
+where the ray still rides near the lens height over whatever is low, not the
+last 18 %, where it grazes the floor. MOSS's camera sits at
+H = 0.075 m, under that whole band: with 0.10 to 0.45 m no floor ray would
+ever carve, and a ray climbing toward a table top would erase a shoe from
+0.10 m up. So the band is the same two fractions of the camera height
+(CARVE_Z_BAND_OF_CAMERA), read against the profile at call time: 0.013 to
+0.060 m at 0.075 m. A floor ray carves the same stretch of its length as on
+the original; a ray climbing toward anything higher than 6 cm carves nothing.
+
+The camera's floor samples miss the camera layer only. On the original, a
+camera above the scan plane, they missed the lidar layer too; here the camera
+looks UNDER the scan plane, and the floor it sees beneath a sofa's edge or a
+bed frame says nothing about the edge the lidar sees 0.20 m up.
+
+Sensor doctrine: only the lidar and the camera write the map. A contact is a
+reflex (the planner's escape), not a mapper. MOSS_CONTACT_WALL=1 turns MOSS's
+contact memory back on, off by default: a contact on `bump` (a front contact;
+a contact felt while reversing goes out on `bump_rear`, which this module does
+not read) marks a short band just ahead of the body as a wall, and only when
+the odometry says the rover was driving straight forward when it came: at
+least CONTACT_FORWARD_M along its heading over the last CONTACT_MOTION_S,
+turning less than CONTACT_TURN_DEG. A pivot, a reverse, or a back-off asked by
+an explorer standing still writes nothing; every contact on an open map says
+in the log whether it was written.
Mission gate: the map writes only once the mission has started. A rover parked
with a spinning lidar thickens the obstacles around its one viewpoint and
@@ -77,13 +103,14 @@ events: the rover moving MISSION_START_M away from its first pose, or an
`explore_cmd` (the order to explore, which comes just before the first
motion). It then stays open for the rest of the run: the end of an
exploration (`explore_done`, `stop_explore_cmd`) stops the explorer, not the
-map, because the lidar map is MOSS's only obstacle source and a cockpit goal
-or STOP sends `stop_explore_cmd` mid-run.
+map, because a cockpit goal or STOP sends `stop_explore_cmd` mid-run.
Numbers (HIT_CAP, FREE_FLOOR, OCCUPIED_AT, RAY_MAX_M) are a starting point to
-be tested. HIT_CAP, FREE_FLOOR and RAY_MAX_M are read once, at import, from
-MOSS_HIT_CAP, MOSS_FREE_FLOOR and MOSS_RAY_MAX_M: a flight tries other values
-without a code change, and the "costmap up" log line says which ones it runs.
+be tested. HIT_CAP, FREE_FLOOR, OCCUPIED_AT, NEW_VIEWPOINT_M, PUBLISH_EVERY,
+RAY_MAX_M and the contact wall are read once, at import, from MOSS_HIT_CAP,
+MOSS_FREE_FLOOR, MOSS_OCCUPIED_AT, MOSS_NEW_VIEWPOINT_M, MOSS_PUBLISH_EVERY,
+MOSS_RAY_MAX_M and MOSS_CONTACT_WALL: a flight tries other values without a
+code change, and the "costmap up" log line says which ones it runs.
"""
from __future__ import annotations
@@ -91,6 +118,7 @@ from __future__ import annotations
import math
import os
import time
+from collections import deque
from typing import Any
import numpy as np
@@ -106,6 +134,7 @@ from dimos.utils.logging_config import setup_logger
from dimos_lcm.std_msgs import Bool
from moss_dimos.robot_profile import current as _current_profile
+from moss_dimos.robot_profile import env_on
logger = setup_logger()
@@ -131,18 +160,19 @@ def _env_float(name: str, default: float, lo: float, hi: float) -> float:
RESOLUTION_M = 0.05
GRID_SPAN_M = 24.0 # world-fixed square, centred on the first pose
-OCCUPIED_AT = int(round(_env_float("MOSS_OCCUPIED_AT", 1, 1, 10))) # hits before a cell is an obstacle. 1: the first sighting
- # counts (the planner reacts within one revolution; a passer-by is carved back within a second).
- # 2 = the cautious rule, a wall only from two places 10 cm apart (MOSS_OCCUPIED_AT=2)
+OCCUPIED_AT = int(round(_env_float("MOSS_OCCUPIED_AT", 2, 1, 10))) # two hits from two places = an obstacle: whole flights were once
+ # spent walled in by cells painted from one parked spot. 1 makes the first sighting a wall (a faster
+ # block, tried as a flag on the original and never judged in flight; MOSS_OCCUPIED_AT=1)
# The layers are int8: the ceiling stays within 127, and at OCCUPIED_AT or above
# (below it nothing could ever become a wall); the floor stays within [-128, 0].
HIT_CAP = int(round(_env_float("MOSS_HIT_CAP", 10, OCCUPIED_AT, 127))) # ceiling: no cell gets more certain than this.
- # A lower cap unlearns a passer-by faster (a cell at the cap needs HIT_CAP - 1 carves,
- # RAY_EVERY revolutions each, to stop being a wall) and keeps a wall less long once
- # nothing sees it any more.
+ # A lower cap unlearns a passer-by faster (a cell at the cap needs HIT_CAP - OCCUPIED_AT + 1
+ # misses to stop being a wall) and keeps a wall less long once nothing sees it any more.
FREE_FLOOR = int(round(_env_float("MOSS_FREE_FLOOR", -3, -128, 0))) # floor: no cell gets more "free" than this.
# A floor nearer 0 lets a new obstacle on long-seen floor become a wall in fewer hits.
-NEW_VIEWPOINT_M = _env_float("MOSS_NEW_VIEWPOINT_M", 0.05, 0.0, 1.0) # a hit counts only if the rover moved this much since the cell's last hit
+NEW_VIEWPOINT_M = _env_float("MOSS_NEW_VIEWPOINT_M", 0.10, 0.0, 1.0) # a hit counts only if the rover moved this much since the
+ # cell's last hit (MOSS_NEW_VIEWPOINT_M=0.05 with MOSS_OCCUPIED_AT=1 is the faster-block trial)
+LOW_HIT_PROTECT_S = 3.0 # after a camera obstacle hit, that cell's camera layer ignores floor samples and camera rays this long
LIDAR_Z_TOL_M = 1e-6 # lidar returns sit at EXACTLY the profile's lidar_height_m: the tag survives the float32 round trip to 5 nm (see lidar_returns)
PUBLISH_EVERY = int(round(_env_float("MOSS_PUBLISH_EVERY", 2, 1, 20))) # one grid every N revolutions (2 = 5 Hz at 10 Hz). A 24 m grid is ~230 kB and every
# subscriber (planner, explorer, recorder, cockpit) decodes each one; the map
@@ -150,20 +180,50 @@ PUBLISH_EVERY = int(round(_env_float("MOSS_PUBLISH_EVERY", 2, 1, 20))) # one g
RAY_MAX_M = _env_float("MOSS_RAY_MAX_M", 4.0, 0.0, GRID_SPAN_M) # rays are carved (misses) up to this range only:
# a cell farther than RAY_MAX_M from every viewpoint is never unlearned, so a passer-by
# 4.5 m away stays until the rover comes within RAY_MAX_M of where they stood. 0 = no carving.
-RAY_EVERY = 2 # carve on every other revolution; hits are taken on all
-CAMERA_HFOV_DEG = 87.0 # the D455's horizontal field of view: the rays carve the camera layer only inside it
+RAY_EVERY = 2 # lidar rays carve on every other revolution; hits are taken on all
+CARVE_Z_BAND_OF_CAMERA = (0.10 / 0.56, 0.45 / 0.56) # a camera ray carves where it crosses a cell between these two fractions
+ # of the camera's height: the original's 0.10-0.45 m band over its 0.56 m camera, 0.013-0.060 m
+ # on MOSS's 0.075 m (module docstring, carve_z_band)
+CAMERA_REPEAT_S = 1.0 # camera points equal to the previous cloud's, byte for byte, on a cloud stamped this soon after it:
+ # the same depth frame again (lidar_odometry re-attaches one frame for 0.5 s; twice that for jitter)
+CONTACT_WALL = env_on("MOSS_CONTACT_WALL", False) # a contact on `bump` marks the band ahead as a wall (off: contacts are reflexes)
CONTACT_BAND_M = (0.02, 0.20) # a contact marks the band this far beyond the body's front edge, across its width
-CAMERA_CARVE_MAX_M = 3.0 # ...and only this close to the rover. Coupled to lidar_odometry's DEPTH_MAX_M (depth
- # range along the camera's axis) and OBSTACLE_MAX_M (camera obstacles, measured from
- # base_link), both 3.0 m: measured from base_link, a cell within this range ahead of the
- # camera is inside both. Past them the camera reports nothing, so it could not hold a cell.
+CONTACT_MOTION_S = 0.5 # with the contact wall on, a contact writes only if the odometry of the last 0.5 s shows the base
+CONTACT_FORWARD_M = 0.03 # ...advancing at least this far along its heading
+CONTACT_TURN_DEG = 10.0 # ...and turning less than this (3 cm and 10 deg: the motion body_clear waits for)
MISSION_START_M = 0.05 # the map opens when the rover has moved this far from its first pose (or on explore_cmd).
# Measuring the displacement needs no clock: the wait accumulates nothing however
# long it lasts, and the first useful revolution leaves with the rover.
+def carve_z_band(camera_z_m: float | None = None) -> tuple[float, float]:
+ """The heights (m) between which a camera ray crossing a cell carves it:
+ CARVE_Z_BAND_OF_CAMERA times the camera's height above the floor, the
+ profile's camera_xyz_base_m[2] unless given (0.013-0.060 m at 0.075 m).
+ The module docstring has the derivation."""
+ h = _current_profile().camera_xyz_base_m[2] if camera_z_m is None else camera_z_m
+ return CARVE_Z_BAND_OF_CAMERA[0] * h, CARVE_Z_BAND_OF_CAMERA[1] * h
+
+
+def camera_xy(pose_xy: tuple[float, float], yaw: float) -> tuple[float, float]:
+ """Where the camera itself is, from the base pose: the profile's
+ camera_xyz_base_m (read at call time, the same numbers lidar_odometry
+ projects the depth with) turned by the heading.
+
+ Rays cast from the base would open the carve band at the wrong range and
+ sweep beside the cells the camera really looked through: on MOSS the
+ camera is 0.156 m AHEAD of base_link, so a floor sample's ray cast from
+ the base carves three cells right in front of the nose that the camera's
+ own ray crosses above the band. The original rover's costmap kept its
+ camera offset as a constant beside the odometry's, and when the camera
+ moved, the two disagreed: here both read the profile."""
+ cx, cy = _current_profile().camera_xyz_base_m[:2]
+ c, s = math.cos(yaw), math.sin(yaw)
+ return (pose_xy[0] + c * cx - s * cy, pose_xy[1] + s * cx + c * cy)
+
+
class ScoredGrid:
- """One int8 score layer over a fixed world grid, plus where each cell was last hit from."""
+ """Two int8 score layers over a fixed world grid, plus where each cell was last hit from."""
def __init__(self, resolution: float = RESOLUTION_M, span_m: float = GRID_SPAN_M,
centre: tuple[float, float] = (0.0, 0.0)) -> None:
@@ -172,10 +232,14 @@ class ScoredGrid:
self.ox = centre[0] - span_m / 2.0
self.oy = centre[1] - span_m / 2.0
self.lidar = np.zeros((self.n, self.n), dtype=np.int8) # what the lidar saw in its scan plane
- self.camera = np.zeros((self.n, self.n), dtype=np.int8) # what the depth camera saw: hit by it, freed by its floor samples AND carved by the lidar rays inside its view
- self.camera_wall = np.zeros((self.n, self.n), dtype=bool) # camera cells that became a wall from two viewpoints and were not carved back to 0 since
+ self.camera = np.zeros((self.n, self.n), dtype=np.int8) # what the depth camera saw: hit by it, freed only by its floor samples, its rays and the body
self.seen = np.zeros((self.n, self.n), dtype=bool)
self._last_hit_xy = np.full((self.n, self.n, 2), np.nan, dtype=np.float32)
+ # when the camera last called each cell an obstacle (monotonic seconds):
+ # it protects a thin leg for LOW_HIT_PROTECT_S. Runtime only: a
+ # monotonic clock means nothing in another process.
+ self._last_low_hit = np.full((self.n, self.n), -np.inf, dtype=np.float64)
+ self._cam_prev = np.zeros((self.n, self.n), dtype=bool) # camera obstacle cells of the PREVIOUS depth frame (moving-object gate)
# ---- coordinates -------------------------------------------------------
def cell(self, x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
@@ -195,38 +259,22 @@ class ScoredGrid:
moved = np.isnan(last[:, 0]) | (np.hypot(last[:, 0] - from_xy[0], last[:, 1] - from_xy[1]) >= NEW_VIEWPOINT_M)
cur = layer[gy, gx].astype(np.int16)
# An obstacle is REAL when it was seen from two viewpoints: a
- # passer-by hammered from one parked spot must never become a wall.
+ # passer-by hammered from one parked spot must never become a wall
+ # (whole flights were once spent walled in by exactly such cells).
# From one viewpoint a cell rises to OCCUPIED_AT - 1 and no
- # further; the second viewpoint (0.10 m of motion) makes it a wall.
- # Driving toward anything real crosses viewpoints within a metre, so
- # legs and furniture still map on approach.
+ # further; the second viewpoint (NEW_VIEWPOINT_M of motion, 0.10 m)
+ # makes it a wall. Driving toward anything real crosses viewpoints
+ # within a metre, so legs and furniture still map on approach.
# The viewpoint rule bounds the INCREASE, never the value: a
# same-viewpoint hit adds nothing and takes nothing away. Clamping the
# value instead would let one revolution from a parked rover push a
# wall built from twenty viewpoints back below OCCUPIED_AT, and
# occupancy() would publish free floor where the wall stands.
- new = np.where(moved, np.minimum(cur + 1, HIT_CAP), cur)
- took = moved
- if layer is self.camera:
- # The camera layer is carved by the lidar rays, so the camera must
- # be able to hold what it keeps seeing: a same-viewpoint hit adds 1
- # while the cell is at 0 or above and below its ceiling. The
- # ceiling is OCCUPIED_AT for a cell that became a wall from two
- # viewpoints (the hit puts back what the carve took), OCCUPIED_AT
- # - 1 for any other (one spot never makes a wall). Below 0 the hit
- # adds nothing, as on the lidar layer: the hold only undoes a
- # carve, and floor seen free for long still needs new viewpoints.
- # Above OCCUPIED_AT the parked-rover rule holds: a same-viewpoint
- # hit adds nothing and takes nothing away.
- wall = self.camera_wall[gy, gx]
- held = ~moved & (cur >= 0) & (cur < np.where(wall, OCCUPIED_AT, OCCUPIED_AT - 1))
- new = np.where(held, cur + 1, new)
- took = moved | held
- self.camera_wall[gy, gx] = wall | (new >= OCCUPIED_AT)
- layer[gy, gx] = new.astype(np.int8)
+ new = np.where(moved, np.minimum(cur + 1, HIT_CAP), cur).astype(np.int8)
+ layer[gy, gx] = new
self._last_hit_xy[gy[moved], gx[moved]] = from_xy
self.seen[gy, gx] = True
- return int(took.sum())
+ return int(moved.sum())
def _miss(self, layer: np.ndarray, gx: np.ndarray, gy: np.ndarray) -> None:
if len(gx) == 0:
@@ -235,83 +283,142 @@ class ScoredGrid:
new = np.maximum(cur - 1, FREE_FLOOR).astype(np.int8)
layer[gy, gx] = new
self.seen[gy, gx] = True
- if layer is self.camera:
- self.camera_wall[gy, gx] &= new > 0 # carved back to 0: forgotten, one spot no longer holds it
_revs: int = 0
- def lidar_revolution(self, hits_xy: np.ndarray, from_xy: tuple[float, float],
- camera_xy: np.ndarray | None = None, yaw: float | None = None) -> None:
- """World-frame lidar hits of one revolution, seen from `from_xy` with
- the rover heading `yaw`: the cells along each ray (up to just short of
- the hit, RAY_MAX_M at most, every RAY_EVERY-th revolution) take a miss
- on the lidar layer, and those of them inside the camera's view
- (`camera_view`) a miss on the camera layer; the hit cells take a hit
- on the lidar layer. A ray that crosses a cell where the camera saw an
- obstacle, inside the camera's view, carves it like any other cell, so
- what the camera stops seeing is forgotten (the module docstring has
- the balance). Without `yaw` the camera's view is unknown and the
- camera layer is not carved.
-
- `camera_xy` are the camera obstacle points of the same revolution:
- their cells are spared on the camera layer. A ray passing over a cell
- does not erase what the camera sees in it during that revolution;
- without the spare, a second viewpoint that lands on a carving
- revolution loses its hit to the carve and the obstacle never becomes
- a wall on approach."""
+ def lidar_revolution(self, hits_xy: np.ndarray, from_xy: tuple[float, float]) -> None:
+ """World-frame lidar hits of one revolution, seen from `from_xy`:
+ the cells along each ray (up to just short of the hit, RAY_MAX_M at
+ most, every RAY_EVERY-th revolution) take a miss, the hit cells a hit.
+ Lidar layer only: a ray 0.20 m up passes over what the camera holds
+ (a shoe, a chair base), so it is no evidence against it."""
if len(hits_xy) == 0:
return
self._revs += 1
if self._revs % RAY_EVERY == 0:
cells = self._ray_cells(from_xy, hits_xy)
if cells is not None:
- gx, gy = cells
- self._miss(self.lidar, gx, gy)
- if yaw is not None:
- view = self.camera_view(gx, gy, from_xy, yaw)
- gx, gy = gx[view], gy[view]
- if camera_xy is not None and len(camera_xy):
- cx, cy = self.cell(camera_xy[:, 0], camera_xy[:, 1])
- keep = ~np.isin(gy * self.n + gx, cy * self.n + cx)
- gx, gy = gx[keep], gy[keep]
- self._miss(self.camera, gx, gy)
+ self._miss(self.lidar, cells[0], cells[1])
self._hit(self.lidar, hits_xy[:, 0], hits_xy[:, 1], from_xy)
- def camera_view(self, gx: np.ndarray, gy: np.ndarray, from_xy: tuple[float, float], yaw: float) -> np.ndarray:
- """Which cells (gx, gy) lie inside the depth camera's horizontal field
- of view from the pose (from_xy, yaw): the cell centre within
- CAMERA_HFOV_DEG / 2 of the rover's heading, seen from the camera's
- position (the profile's camera_xyz_base_m, read at call time; the
- camera looks along the heading), and within CAMERA_CARVE_MAX_M of the
- rover."""
- cam = _current_profile().camera_xyz_base_m
- c, s = math.cos(yaw), math.sin(yaw)
- cam_x = from_xy[0] + c * cam[0] - s * cam[1]
- cam_y = from_xy[1] + s * cam[0] + c * cam[1]
- xs = self.ox + (gx + 0.5) * self.res
- ys = self.oy + (gy + 0.5) * self.res
- bearing = np.arctan2(ys - cam_y, xs - cam_x) - yaw
- bearing = (bearing + np.pi) % (2 * np.pi) - np.pi
- near = np.hypot(xs - from_xy[0], ys - from_xy[1]) <= CAMERA_CARVE_MAX_M
- return near & (np.abs(bearing) <= math.radians(CAMERA_HFOV_DEG) / 2)
-
- def camera_hits(self, hits_xy: np.ndarray, from_xy: tuple[float, float]) -> int:
- """World-frame obstacle points from the depth camera, seen from `from_xy`:
- a hit on their cells (two-viewpoint rule as for lidar hits, plus the
- same-viewpoint hit that holds a wall the camera keeps seeing at
- OCCUPIED_AT), no ray carved. Returns the number of cells whose score
- took the hit."""
- if len(hits_xy) == 0:
- return 0
- return self._hit(self.camera, hits_xy[:, 0], hits_xy[:, 1], from_xy)
+ def camera_obstacles(self, pts_xy: np.ndarray, from_xy: tuple[float, float],
+ now: float | None = None) -> tuple[int, int]:
+ """One depth frame's obstacle points, seen from `from_xy`: a hit on
+ the camera layer (the two-viewpoint rule as for lidar hits), and the
+ cell is stamped: for the next LOW_HIT_PROTECT_S the floor beside it
+ may not erase it (the thin leg, module docstring).
+
+ MOVING things are never written into the map: a cell only takes a hit
+ if the camera ALSO saw an obstacle within one cell of it in the
+ previous frame. One call per DISTINCT depth frame (MossCostMap keys
+ the calls on the frames); an empty frame clears the memory.
+
+ Returns (cells that took a hit, cells held back by the gate)."""
+ gx, gy = self.cell(pts_xy[:, 0], pts_xy[:, 1])
+ if len(gx) == 0:
+ self._cam_prev[:] = False
+ return 0, 0
+ # NEIGHBOURHOOD repeat, not exact-cell repeat: a THIN standing leg
+ # re-projects a cell off between frames (5 cm of quantisation from a
+ # moving rover), and an exact-cell repeat would filter it out like a
+ # mover. One cell of tolerance keeps every immobile thing; a walker or
+ # a vacuum still jumps further than 10 cm per frame.
+ prev_near = self._cam_prev.copy()
+ prev_near[:-1, :] |= self._cam_prev[1:, :]
+ prev_near[1:, :] |= self._cam_prev[:-1, :]
+ prev_near[:, :-1] |= prev_near[:, 1:]
+ prev_near[:, 1:] |= prev_near[:, :-1]
+ keep = prev_near[gy, gx]
+ self._cam_prev[:] = False
+ self._cam_prev[gy, gx] = True
+ held = int(len(np.unique(gy[~keep] * self.n + gx[~keep])))
+ if not keep.any():
+ return 0, held
+ rx = self.ox + (gx[keep] + 0.5) * self.res
+ ry = self.oy + (gy[keep] + 0.5) * self.res
+ took = self._hit(self.camera, rx, ry, from_xy)
+ self._last_low_hit[gy[keep], gx[keep]] = time.monotonic() if now is None else now
+ return took, held
+
+ def camera_floor(self, pts_xy: np.ndarray, now: float | None = None) -> None:
+ """The camera saw bare floor here: a miss on the camera layer, the
+ sensor's way to forget a shoe that was taken away.
+
+ Except on a cell the camera called an obstacle less than
+ LOW_HIT_PROTECT_S ago: there the floor sample is dropped. A thing
+ thinner than a 5 cm cell is seen in one frame and its floor in the
+ next, and the two cancelled forever.
+
+ The lidar layer is untouched: the camera looks under the scan plane,
+ and floor seen beneath a sofa's edge says nothing about the edge the
+ lidar sees 0.20 m up."""
+ now = time.monotonic() if now is None else now
+ gx, gy = self.cell(pts_xy[:, 0], pts_xy[:, 1])
+ if len(gx) == 0:
+ return
+ flat = np.unique(gy * self.n + gx)
+ gx, gy = flat % self.n, flat // self.n
+ protected = self._last_low_hit[gy, gx] > now - LOW_HIT_PROTECT_S
+ self._miss(self.camera, gx[~protected], gy[~protected])
+
+ def camera_rays(self, pts_xyz: np.ndarray, from_xy: tuple[float, float],
+ now: float | None = None) -> None:
+ """The camera's rays carve the camera layer, symmetric to the lidar's:
+ the map corrects itself every time the camera passes over a spot,
+ instead of a ghost living until somebody clears the map.
+
+ `from_xy` is where the camera is (`camera_xy`), at the profile's
+ camera height. Every cell a ray crosses inside the carve band
+ (`carve_z_band`) held nothing standing, or the ray would have ended
+ on it: a miss. Obstacle endpoints and floor samples alike; a ray stops
+ one cell short of its point and at RAY_MAX_M. Cells the camera called
+ an obstacle less than LOW_HIT_PROTECT_S ago are skipped: a real thing
+ is re-hit every frame, so only what the camera has STOPPED confirming
+ fades. The lidar layer is never touched: only a lidar ray may retract
+ a lidar claim."""
+ if len(pts_xyz) == 0:
+ return
+ now = time.monotonic() if now is None else now
+ h = _current_profile().camera_xyz_base_m[2]
+ lo, hi = carve_z_band(h)
+ dx = pts_xyz[:, 0] - from_xy[0]
+ dy = pts_xyz[:, 1] - from_xy[1]
+ r = np.hypot(dx, dy)
+ keep = r > self.res
+ if not keep.any():
+ return
+ dx, dy, r = dx[keep], dy[keep], r[keep]
+ z_end = pts_xyz[keep, 2]
+ end = np.minimum(r - self.res, RAY_MAX_M) # stop one cell short of the point
+ nmax = int(np.floor(end.max() / self.res))
+ if nmax < 1:
+ return
+ d = (np.arange(1, nmax + 1) * self.res)[None, :]
+ f = d / r[:, None]
+ z = h + (z_end[:, None] - h) * f
+ valid = (d <= end[:, None]) & (z > lo) & (z < hi)
+ if not valid.any():
+ return
+ ux, uy = (dx / r)[:, None], (dy / r)[:, None]
+ xs = (from_xy[0] + ux * d)[valid]
+ ys = (from_xy[1] + uy * d)[valid]
+ gx, gy = self.cell(xs, ys)
+ if len(gx) == 0:
+ return
+ flat = np.unique(gy * self.n + gx)
+ gx, gy = flat % self.n, flat // self.n
+ unprotected = self._last_low_hit[gy, gx] <= now - LOW_HIT_PROTECT_S
+ self._miss(self.camera, gx[unprotected], gy[unprotected])
def contact(self, pose: tuple) -> int:
- """The rover pushed against something its sensors did not map (the stall
- guard fired): the cells of a short band right ahead of the body become a
- wall on the camera layer at once (no viewpoint rule: a contact is a
- physical certainty, like body_clear). The planner then routes around the
- spot instead of driving back into it. Freed like any camera wall: by the
- camera seeing bare floor there, or by the body driving over it."""
+ """The rover pushed against something (MossCostMap.handle_bump, with
+ MOSS_CONTACT_WALL=1 and the rover driving straight forward): the cells
+ of a short band right ahead of the body become a wall on the camera
+ layer at once (no viewpoint rule: a contact is a physical certainty,
+ like body_clear). The planner then routes around the spot instead of
+ driving back into it. Freed like any camera wall: by the camera seeing
+ bare floor there or through it at low height, or by the body driving
+ over it."""
x, y, yaw = pose
c, s = np.cos(yaw), np.sin(yaw)
hx, hy = _current_profile().body_clear_m
@@ -324,21 +431,9 @@ class ScoredGrid:
flat = np.unique(gy * self.n + gx)
gx, gy = flat % self.n, flat // self.n
self.camera[gy, gx] = np.maximum(self.camera[gy, gx], np.int8(OCCUPIED_AT))
- self.camera_wall[gy, gx] = True
self.seen[gy, gx] = True
return int(len(gx))
- def camera_floor(self, floor_xy: np.ndarray) -> None:
- """World-frame bare-floor samples from the depth camera: a miss on the
- camera layer (a shoe that was taken away stops being an obstacle once
- the camera sees the floor where it stood). The lidar layer is untouched."""
- if len(floor_xy) == 0:
- return
- gx, gy = self.cell(floor_xy[:, 0], floor_xy[:, 1])
- if len(gx):
- flat = np.unique(gy * self.n + gx)
- self._miss(self.camera, flat % self.n, flat // self.n)
-
def _ray_cells(self, from_xy: tuple[float, float], hits_xy: np.ndarray):
"""Cells crossed by the rays from `from_xy` to each hit (capped at
RAY_MAX_M), stopping one cell short of the hit; one sample per cell."""
@@ -367,10 +462,10 @@ class ScoredGrid:
def body_clear(self, pose: tuple) -> None:
"""The body IS here: every cell under the profile's body_clear_m
- footprint (half extents around base_link) is certainly free, and seen.
- Without it, cells written before the rover drove over them stay and
- can wall it in. Keep the footprint exact, never wider, so a wall
- right against the body survives."""
+ footprint (half extents around base_link) is certainly free, on both
+ layers, and seen. Without it, cells written before the rover drove
+ over them stay and can wall it in. Keep the footprint exact, never
+ wider, so a wall right against the body survives."""
x, y, yaw = pose
c, s = np.cos(yaw), np.sin(yaw)
hx, hy = _current_profile().body_clear_m
@@ -381,7 +476,6 @@ class ScoredGrid:
if len(gx):
self.lidar[gy, gx] = FREE_FLOOR
self.camera[gy, gx] = FREE_FLOOR
- self.camera_wall[gy, gx] = False
self.seen[gy, gx] = True
# ---- output ------------------------------------------------------------
@@ -415,7 +509,9 @@ def lidar_returns(pts: np.ndarray) -> np.ndarray:
the last bit of a float32. Any other point the cloud carries (a depth
camera's, at its true height) can sit within millimetres of the scan
plane, so the tag is read as one exact value (LIDAR_Z_TOL_M), never as a
- band.
+ band: read as a 5 mm band it once stole every camera point at the scan
+ plane's height, past the moving-object gate and out of the camera rays'
+ reach, and a person's side became a permanent wall.
"""
return np.abs(pts[:, 2] - _current_profile().lidar_height_m) < LIDAR_Z_TOL_M
@@ -424,20 +520,23 @@ class MossCostMap(Module):
"""Replaces dimOS's CostMapper on MOSS.
Ins: `lidar` (the world cloud from lidar_odometry, lidar returns tagged
- with z = profile.lidar_height_m exactly), `odom` (base pose in world),
- `explore_cmd` (the order that opens the map), `explore_done` and
- `stop_explore_cmd` (logged; the map keeps writing).
+ with z = profile.lidar_height_m exactly, the depth camera's obstacle
+ points at their true height), `camera_floor` (the camera's bare floor,
+ z = 0), `odom` (base pose in world), `explore_cmd` (the order that opens
+ the map), `explore_done` and `stop_explore_cmd` (logged; the map keeps
+ writing), `clear_map_cmd` (a fresh grid), `bump` (a front contact: a wall
+ ahead only with MOSS_CONTACT_WALL=1, module docstring).
Out: `global_costmap` (the stream name the planner and the explorer
listen to)."""
lidar: In[PointCloud2]
- camera_floor: In[PointCloud2] # bare floor the depth camera saw (lidar_odometry): frees camera obstacles
+ camera_floor: In[PointCloud2] # bare floor the depth camera saw (lidar_odometry), once per depth frame: frees camera obstacles
odom: In[PoseStamped]
explore_done: In[Bool] # explorer2 found no reachable frontier left: logged, the map keeps writing
stop_explore_cmd: In[Bool] # exploration stopped on request (explore_ctl.py stop, the cockpit): logged, the map keeps writing
explore_cmd: In[Bool] # the order to explore: opens the map before the first motion
clear_map_cmd: In[Bool] # the cockpit's Clear map (explore_ctl.py clear): a fresh grid, the mission gate as it is
- bump: In[Bool] # a contact (the base's stall guard, the explorer's back-off): the band ahead becomes a wall
+ bump: In[Bool] # a front contact: logged; with MOSS_CONTACT_WALL=1 and the rover driving straight forward, the band ahead becomes a wall
global_costmap: Out[OccupancyGrid]
def __init__(self, world_frame: str = "world", **kwargs: Any) -> None:
@@ -445,10 +544,18 @@ class MossCostMap(Module):
self.world_frame = world_frame
self._grid: ScoredGrid | None = None
self._pose_xy: tuple[float, float] | None = None
- self._pose_yaw = 0.0
+ self._pose_yaw = 0.0 # the camera rides on the nose: its rays need the heading
+ self._poses: deque = deque() # (monotonic s, x, y, yaw) of the last CONTACT_MOTION_S, for the contact wall
self._revolutions = 0
- self._camera_pts = 0 # camera obstacle points since the last publish (log only)
- self._camera_cells = 0 # ...and the cells they hit
+ # the depth frame the camera layer last took (moving-object gate): its
+ # points as bytes and the stamp of the cloud that first carried them
+ self._cam_key: bytes | None = None
+ self._cam_key_t = 0.0
+ self._camera_pts = 0 # camera obstacle points of the frames taken since the last publish (log only)
+ self._camera_cells = 0 # ...the cells they hit
+ self._camera_held = 0 # ...the cells the moving-object gate held back
+ self._camera_frames = 0 # ...how many distinct depth frames
+ self._camera_repeats = 0 # ...and how many clouds carried a frame already taken
self._last_clear: tuple | None = None # (x, y, yaw) of the last body_clear
# The pre-mission gate, closed at construction: a rover parked with a
# spinning lidar would write the room it waits in, from one spot. It
@@ -460,13 +567,19 @@ class MossCostMap(Module):
@rpc
def start(self) -> None:
super().start()
+ lo, hi = carve_z_band()
logger.info(f"costmap up: {RESOLUTION_M} m cells, hit cap {HIT_CAP}, free floor {FREE_FLOOR}, "
- f"occupied at {OCCUPIED_AT}, rays carved to {RAY_MAX_M:g} m")
+ f"occupied at {OCCUPIED_AT} (new viewpoint {NEW_VIEWPOINT_M:g} m), rays carved to {RAY_MAX_M:g} m, "
+ f"camera rays carve {lo:.3f}-{hi:.3f} m up, contact wall {'on' if CONTACT_WALL else 'off'}")
async def handle_odom(self, msg: PoseStamped) -> None:
self._pose_xy = (float(msg.position.x), float(msg.position.y))
q = msg.orientation
self._pose_yaw = float(np.arctan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z)))
+ now = time.monotonic()
+ self._poses.append((now, self._pose_xy[0], self._pose_xy[1], self._pose_yaw))
+ while self._poses and now - self._poses[0][0] > CONTACT_MOTION_S:
+ self._poses.popleft()
if self._grid is None:
self._grid = ScoredGrid(centre=self._pose_xy)
logger.info(f"costmap: grid centred on ({self._pose_xy[0]:+.2f}, {self._pose_xy[1]:+.2f})")
@@ -507,7 +620,7 @@ class MossCostMap(Module):
async def handle_explore_done(self, msg: Bool) -> None:
"""explorer2 ran out of reachable frontier. The explorer stops; the map
- keeps writing (the lidar map is the only obstacle source)."""
+ keeps writing."""
if bool(getattr(msg, "data", False)):
logger.info("costmap: exploration complete - map writing continues")
@@ -532,17 +645,46 @@ class MossCostMap(Module):
self._mission_frozen = False
logger.info("costmap: explore_cmd received - map writing OPEN for the mission")
+ def _recent_motion(self, now: float | None = None) -> tuple[float, float]:
+ """How the base moved over the last CONTACT_MOTION_S of odometry
+ before `now`: (metres along the heading it had at the window's start,
+ degrees turned). Less than two poses in the window (the odometry
+ quiet) -> (0, 0)."""
+ now = time.monotonic() if now is None else now
+ poses = [p for p in self._poses if now - p[0] <= CONTACT_MOTION_S]
+ if len(poses) < 2:
+ return 0.0, 0.0
+ _, x0, y0, yaw0 = poses[0]
+ _, x1, y1, yaw1 = poses[-1]
+ forward = (x1 - x0) * math.cos(yaw0) + (y1 - y0) * math.sin(yaw0)
+ turn = math.degrees((yaw1 - yaw0 + math.pi) % (2 * math.pi) - math.pi)
+ return forward, turn
+
async def handle_bump(self, msg: Bool) -> None:
- """A contact: the cells just ahead of the body become a wall at once, so the
- planner routes around what the sensors did not see (a cable, a step, a
- bin edge below the camera's view) instead of driving into it again."""
+ """A front contact. Contacts are reflexes (the planner's escape), so by
+ default nothing is written. With MOSS_CONTACT_WALL=1, a contact felt
+ while driving straight forward (`_recent_motion`) turns the cells
+ just ahead of the body into a wall at once, so the planner routes
+ around what the sensors did not see (a cable, a bin edge below the
+ camera's view) instead of driving into it again. Each contact says in
+ the log whether it was written."""
if not bool(getattr(msg, "data", False)) or self._grid is None or self._pose_xy is None:
return
if self._write_frozen():
return
+ where = (f"costmap: contact at ({self._pose_xy[0]:+.2f}, {self._pose_xy[1]:+.2f}) heading "
+ f"{np.degrees(self._pose_yaw):+.0f} deg")
+ if not CONTACT_WALL:
+ logger.info(f"{where} - not written: contacts are reflexes, only the lidar and the camera write the map "
+ "(MOSS_CONTACT_WALL=1 writes a forward contact)")
+ return
+ forward, turn = self._recent_motion()
+ if forward < CONTACT_FORWARD_M or abs(turn) >= CONTACT_TURN_DEG:
+ logger.info(f"{where} - not written: not driving straight forward ({forward * 100:+.0f} cm along the "
+ f"heading, {turn:+.0f} deg in the last {CONTACT_MOTION_S:g} s)")
+ return
n = self._grid.contact((self._pose_xy[0], self._pose_xy[1], self._pose_yaw))
- logger.info(f"costmap: contact at ({self._pose_xy[0]:+.2f}, {self._pose_xy[1]:+.2f}) heading "
- f"{np.degrees(self._pose_yaw):+.0f} deg: {n} cells ahead marked as a wall")
+ logger.info(f"{where}: {n} cells ahead marked as a wall")
self._publish()
async def handle_clear_map_cmd(self, msg: Bool) -> None:
@@ -554,16 +696,55 @@ class MossCostMap(Module):
return
self._grid = ScoredGrid(centre=self._pose_xy)
self._revolutions = 0
- self._camera_pts = self._camera_cells = 0
+ self._cam_key = None
+ self._camera_pts = self._camera_cells = self._camera_held = self._camera_frames = self._camera_repeats = 0
logger.info(f"costmap: map CLEARED on request - fresh grid centred on ({self._pose_xy[0]:+.2f}, "
f"{self._pose_xy[1]:+.2f}), mission {'open' if not self._mission_frozen else 'not started'}")
+ def _camera_xy(self) -> tuple[float, float]:
+ """The ray origin for everything the camera saw (see camera_xy)."""
+ assert self._pose_xy is not None
+ return camera_xy(self._pose_xy, self._pose_yaw)
+
async def handle_camera_floor(self, msg: PointCloud2) -> None:
if self._grid is None or self._pose_xy is None or self._write_frozen():
return
pts = np.asarray(msg.as_numpy()[0], dtype=np.float64)
if len(pts):
- self._grid.camera_floor(pts[:, :2])
+ now = time.monotonic()
+ self._grid.camera_floor(pts[:, :2], now=now)
+ self._grid.camera_rays(pts, self._camera_xy(), now=now)
+
+ def _camera_frame(self, cam: np.ndarray, stamp: float) -> None:
+ """The camera points of one revolution's cloud (stamped `stamp`, wall
+ seconds), taken once per depth frame: hits through the moving-object
+ gate, then the frame's rays.
+
+ A cloud whose points equal the last frame's, byte for byte, stamped
+ less than CAMERA_REPEAT_S after the cloud that first carried them,
+ carries that frame again (lidar_odometry re-attaches it to every
+ revolution for 0.5 s) and writes nothing. A cloud without camera
+ points means no frame of the last 0.5 s saw an obstacle: the gate
+ forgets, like an empty frame."""
+ if len(cam) == 0:
+ if self._cam_key is not None:
+ self._grid.camera_obstacles(cam[:, :2], self._pose_xy)
+ self._cam_key = None
+ return
+ key = cam.tobytes()
+ if key == self._cam_key and stamp - self._cam_key_t < CAMERA_REPEAT_S:
+ self._camera_repeats += 1
+ return
+ self._cam_key, self._cam_key_t = key, stamp
+ now = time.monotonic()
+ # hits first: they stamp the 3 s protection, so a frame never carves
+ # the very cells it is confirming
+ took, held = self._grid.camera_obstacles(cam[:, :2], self._pose_xy, now=now)
+ self._grid.camera_rays(cam, self._camera_xy(), now=now)
+ self._camera_frames += 1
+ self._camera_pts += len(cam)
+ self._camera_cells += took
+ self._camera_held += held
async def handle_lidar(self, msg: PointCloud2) -> None:
if self._grid is None or self._pose_xy is None or self._write_frozen():
@@ -575,17 +756,18 @@ class MossCostMap(Module):
hits = pts[tag]
if len(hits) == 0:
return # no lidar return on this cloud: not a revolution
- cam = pts[~tag][:, :2]
- self._grid.lidar_revolution(hits[:, :2], self._pose_xy, camera_xy=cam, yaw=self._pose_yaw)
- if len(cam):
- self._camera_cells += self._grid.camera_hits(cam, self._pose_xy)
- self._camera_pts += len(cam)
+ # the cloud's own stamp (lidar_odometry's publish time), else the wall clock
+ self._camera_frame(pts[~tag], float(getattr(msg, "ts", 0.0) or 0.0) or time.time())
+ self._grid.lidar_revolution(hits[:, :2], self._pose_xy)
self._revolutions += 1
if self._revolutions % PUBLISH_EVERY == 0:
if self._camera_pts:
logger.info(f"costmap: camera obstacles: {self._camera_pts} points, {self._camera_cells} cell hits "
- f"over the last {PUBLISH_EVERY} revolutions")
- self._camera_pts = self._camera_cells = 0
+ f"over the last {PUBLISH_EVERY} revolutions ({self._camera_frames} depth frames, "
+ f"{self._camera_repeats} repeats skipped, {self._camera_held} cells held back by the "
+ "moving-object gate)")
+ self._camera_pts = self._camera_cells = self._camera_held = 0
+ self._camera_frames = self._camera_repeats = 0
self._publish()
def _publish(self) -> None:
diff --git a/moss_dimos/moss_adapter.py b/moss_dimos/moss_adapter.py
index cdaa072..e83a3a7 100644
--- a/moss_dimos/moss_adapter.py
+++ b/moss_dimos/moss_adapter.py
@@ -71,6 +71,10 @@ Calibration (env, all optional):
MOSS_PULSE_MIN_PCT duty floor of a non-zero track while pulsing (default 40)
MOSS_PIVOT_PCT every pivot (tracks in opposite directions) is sent at this percent, both tracks (default 100, 0 = as asked)
(no variable) stall guard: a commanded track whose encoder moved < STALL_MIN_TICKS over STALL_S -> 'stop', logged, counted
+ (no variable) feedback loss: telemetry older than TELEMETRY_FRESH_S while a non-zero command is held blinds the
+ stall guard and the IMU contacts (both read the telemetry): warned once, then once per
+ READ_WARN_PERIOD_S with a count, and a recovery line when telemetry comes back; a failing serial
+ read is logged the same way, never once per read
MOSS_MOCK_BUS any value but 0/false/no/off: drive the fake firmware (no motors)
"""
from __future__ import annotations
@@ -103,7 +107,9 @@ KEEPALIVE_S = 0.100 # re-send period, 3x inside the firmware deadman
STALE_S = 0.500 # no fresh write for this long -> "stop", once
REPLY_TIMEOUT_S = 0.150 # the firmware answers within a loop tick (ms)
CONNECT_PROBE_S = 1.000 # the first "status" of a process: reader thread start + first parse on a Jetson take longer than a reply tick
-TELEMETRY_FRESH_S = 1.0 # mode read from telemetry older than this = unknown
+TELEMETRY_FRESH_S = 1.0 # mode read from telemetry older than this = unknown; older while driving = feedback lost
+READ_WARN_PERIOD_S = 5.0 # a lost feedback (telemetry silent while driving, a failing serial read) is warned on
+ # its first occurrence, then once per this period with a count, and its recovery is logged
MOCK_BUS_ENV = "MOSS_MOCK_BUS"
STALL_S = 1.0 # every commanded track frozen for this long = STALLED: the rover is pushing against
# something (no bumper on MOSS: the encoders are the bumper)
@@ -417,6 +423,11 @@ class MossBaseAdapter:
# the mapping geometry: when pulsing, the static-friction floor becomes the duty floor of the pulses
self._map_geometry = replace(self._geometry, min_pct=pulse_min_pct()) if self._pulse_n else self._geometry
self._last_logged = None
+ # feedback loss, logged once then rate-limited (see _note_read_failure, _note_blind)
+ self._read_failures = 0 # consecutive serial reads that raised
+ self._last_read_warn_t = 0.0
+ self._blind_ticks = 0 # consecutive keepalive ticks driving on stale telemetry
+ self._last_blind_warn_t = 0.0
self._reader = None
self._keepalive = None
self._stop_threads = threading.Event()
@@ -457,6 +468,17 @@ class MossBaseAdapter:
with self._lock:
return dict(self._telemetry) if self._telemetry else None
+ @property
+ def read_failure_count(self) -> int:
+ """Consecutive serial reads that raised (0 = healthy)."""
+ return self._read_failures
+
+ @property
+ def blind_count(self) -> int:
+ """Consecutive keepalive ticks that held a non-zero command on telemetry
+ older than TELEMETRY_FRESH_S (0 = the guards can see)."""
+ return self._blind_ticks
+
@property
def telemetry_age_s(self) -> float | None:
"""Seconds since the last telemetry line arrived (same monotonic stamp
@@ -490,6 +512,7 @@ class MossBaseAdapter:
self._ser = None
return False
self._stop_threads.clear()
+ self._read_failures = self._blind_ticks = 0
self._reader = threading.Thread(target=self._read_loop, name="moss-rx", daemon=True)
self._reader.start()
# probe: the firmware answers "status" with one telemetry line
@@ -558,9 +581,10 @@ class MossBaseAdapter:
# the port closed under us (stack stopping): not an error
if self._stop_threads.is_set() or not getattr(ser, "is_open", True):
return
- _log().error(f"MOSS base: serial read failed: {exc!r}")
+ self._note_read_failure(exc)
time.sleep(0.05)
continue
+ self._note_read_success()
if not raw:
continue
line = raw.decode(errors="replace").strip()
@@ -570,7 +594,9 @@ class MossBaseAdapter:
if line.startswith("{"):
try:
self._telemetry = json.loads(line)
- self._telemetry_t = time.monotonic()
+ now = time.monotonic()
+ self._note_telemetry_back(now)
+ self._telemetry_t = now
self._ingest_ticks(self._telemetry)
except (ValueError, TypeError):
pass
@@ -583,6 +609,47 @@ class MossBaseAdapter:
continue
self._reply_cv.notify_all()
+ def _note_read_failure(self, exc: Exception) -> None:
+ """A serial read raised (the port is open, the stack is not stopping):
+ counted, logged on the first failure and then once per
+ READ_WARN_PERIOD_S - a dead port would otherwise write 20 lines a second."""
+ self._read_failures += 1
+ now = time.monotonic()
+ if self._read_failures == 1 or now - self._last_read_warn_t >= READ_WARN_PERIOD_S:
+ self._last_read_warn_t = now
+ _log().error(f"MOSS base: serial read failed on {self._port} "
+ f"({self._read_failures} consecutive): {exc!r}")
+
+ def _note_read_success(self) -> None:
+ if self._read_failures:
+ _log().info(f"MOSS base: serial reads recovered after {self._read_failures} failures")
+ self._read_failures = 0
+
+ def _note_blind(self, now: float) -> None:
+ """Called under the lock every keepalive tick while a non-zero command is
+ held. Telemetry older than TELEMETRY_FRESH_S means the stall guard has no
+ encoder ticks to compare and the IMU contacts no command to qualify a
+ deceleration with: both are blind while the tracks are driven. Counted,
+ warned on the first tick and then once per READ_WARN_PERIOD_S."""
+ age = None if self._telemetry_t is None else now - self._telemetry_t
+ if age is not None and age <= TELEMETRY_FRESH_S:
+ return
+ self._blind_ticks += 1
+ if self._blind_ticks == 1 or now - self._last_blind_warn_t >= READ_WARN_PERIOD_S:
+ self._last_blind_warn_t = now
+ since = "since the connect" if age is None else f"for {age:.1f} s"
+ _log().warning(f"MOSS base: no telemetry from the motor board {since} on {self._port} while "
+ f"driving L={self._want[0]:+d}% R={self._want[1]:+d}% ({self._blind_ticks} consecutive "
+ "ticks) - stall guard and IMU bump blind")
+
+ def _note_telemetry_back(self, now: float) -> None:
+ """Called under the lock when a telemetry line arrives, before its stamp."""
+ if self._blind_ticks:
+ gap = now - self._telemetry_t if self._telemetry_t is not None else 0.0
+ _log().info(f"MOSS base: telemetry recovered after {self._blind_ticks} failures "
+ f"({gap:.1f} s without a line)")
+ self._blind_ticks = 0
+
def _send(self, line: str, expect_status: bool = False, timeout: float | None = None) -> bool:
"""Write one command line and wait for its reply. Called with the lock
held (RLock). True on "OK" (or a telemetry line when expect_status)."""
@@ -760,6 +827,7 @@ class MossBaseAdapter:
self._velocity = (0.0, 0.0, 0.0)
continue
if self._want != (0, 0):
+ self._note_blind(time.monotonic())
if self._stall_check():
continue
# pulsing: the slice of this tick, 'drive 0 0' included (an OFF slice
diff --git a/moss_dimos/recovering_planner.py b/moss_dimos/recovering_planner.py
index b8cd58c..ffb11d2 100644
--- a/moss_dimos/recovering_planner.py
+++ b/moss_dimos/recovering_planner.py
@@ -1,19 +1,25 @@
"""ReplanningAStarPlanner that abandons a goal instead of fighting for it.
-The stuck detector tells the truth; what goes wrong is a scripted reflex on
-top of it. A blind back-off on every "stuck" verdict walks the robot
-backwards, step by step, into whatever is behind it: a recovery manoeuvre
-that creates the crash is worse than none. So this planner has two rules:
-
- * stuck -> STOP and abandon the goal (``cancel_goal`` publishes
- goal_reached=False; the explorer excludes that spot and picks another
- frontier - the pivot toward it is the only motion that follows).
- No scripted motion of any kind.
- * a CONTACT on the ``bump`` stream (on MOSS its producer is the explorer's
- born-cornered back-off) is the one thing still allowed a scripted move:
- away from the contact, 0.20 m, once. A second contact during that escape
- aborts it dead - a contact is never dropped or queued behind a running
- move.
+The detectors tell the truth; what goes wrong is a scripted reflex on top of
+them. A blind back-off on every "stuck" verdict walks the robot backwards,
+step by step, into whatever is behind it (a rover running this planner did
+it in one run: 38 blind reverses and 14 rear hits, all chained by the
+reflex itself): a recovery manoeuvre that creates the crash is worse than
+none. What is left, and it is all of it:
+
+ * stuck, or a stall of the base (``stall``: the base's stall guard, tracks
+ commanded and encoders frozen for a second) -> STOP and abandon the goal
+ (``cancel_goal`` publishes goal_reached=False; the explorer excludes that
+ spot and picks another frontier - the pivot toward it is the only motion
+ that follows). No scripted motion of any kind. A stall is inferred, not
+ felt: a pivot that fails to turn reads the same as a wall, and answering
+ it with a blind move is the loop above.
+ * a CONTACT is the one thing still allowed a scripted move: away from the
+ contact, 0.20 m, once. ``bump`` is a contact in front (the IMU's, or the
+ explorer's born-cornered back-off) and backs off in reverse;
+ ``bump_rear`` is a contact behind (the IMU's, felt while reversing or as a
+ forward kick during a pivot) and moves FORWARD. A second contact during that escape aborts it dead - a
+ contact is never dropped or queued behind a running move.
Paths are planned on clearance_cost_map(), a cost field built from the
active robot profile (moss_dimos.robot_profile) at call time.
@@ -182,7 +188,7 @@ def clearance_cost_map(
class RecoveringGlobalPlanner(GlobalPlanner):
- """Stuck -> stop, abandon the goal. Contact -> one escape move, then abandon."""
+ """Stuck or stall -> stop, abandon the goal. Contact -> one escape move, then abandon."""
escape_distance_m: float = ESCAPE_DISTANCE_M
escape_speed_mps: float = ESCAPE_SPEED_MPS
@@ -315,6 +321,29 @@ class RecoveringGlobalPlanner(GlobalPlanner):
self._path_started_at = float("inf")
self.cancel_goal()
+ def stall(self, trigger: str = "stall") -> bool:
+ """A stall of the base (the stall guard: tracks commanded, encoders
+ frozen): an INFERRED contact, so stop and abandon the goal, no motion
+ of any kind, exactly like a stuck verdict.
+
+ A stall during an escape means the escape itself is pushing into
+ something: it stops dead, and the goal it held is dropped with it.
+ Without a goal or an escape there is nothing to give up (the pad was
+ driving): nothing is cancelled. Returns True when a goal or an escape
+ was given up."""
+ with self._lock:
+ self._held_goal = None
+ escaping = self._escaping
+ if escaping:
+ self._escape_abort.set()
+ has_goal = self._current_goal is not None
+ if escaping:
+ logger.warning("Stall during an escape: stopping dead", trigger=trigger)
+ if not (has_goal or escaping):
+ return False
+ self.abandon_goal(trigger=trigger)
+ return True
+
def escape(self, direction: float, trigger: str) -> bool:
"""Contact escape: the ONE scripted move left. Away from the contact,
escape_distance_m, once, then the goal is abandoned.
@@ -443,12 +472,16 @@ class RecoveringGlobalPlanner(GlobalPlanner):
class RecoveringPlanner(ReplanningAStarPlanner):
"""Drop-in for ReplanningAStarPlanner where stuck = goal abandoned (no
- motion) and a contact on the ``bump`` In triggers the one scripted escape
- move, in reverse. On MOSS the producer of ``bump`` is the explorer's
- born-cornered back-off (Explorer2.bump); any other contact source can
- publish on the same stream."""
+ motion), a stall of the base (``stall`` In) = goal abandoned (no motion),
+ and a contact (``bump`` / ``bump_rear`` In) triggers the one scripted
+ escape move away from the contact: in reverse for ``bump`` (in front: the
+ IMU's contacts and the explorer's born-cornered back-off), FORWARD for
+ ``bump_rear`` (behind: the IMU's contacts felt while reversing, or a
+ forward kick during a pivot)."""
bump: In[Bool]
+ bump_rear: In[Bool]
+ stall: In[Bool]
def __init__(self, **kwargs) -> None: # type: ignore[no-untyped-def]
super().__init__(**kwargs)
@@ -461,7 +494,21 @@ class RecoveringPlanner(ReplanningAStarPlanner):
self._planner.halt(trigger="stop_movement")
async def handle_bump(self, msg: Bool) -> None:
- """Contact ahead: stop, escape 0.20 m in reverse, abandon the goal."""
+ """Front contact: stop, escape 0.20 m in reverse, abandon the goal."""
if getattr(msg, "data", False):
acted = self._planner.escape(direction=-1.0, trigger="bump")
- logger.warning("BUMP received", reflex="escape reverse 0.20 m", acted=acted)
+ logger.warning("BUMP received: front contact", reflex="escape reverse 0.20 m",
+ acted=acted)
+
+ async def handle_bump_rear(self, msg: Bool) -> None:
+ """Rear contact: stop, escape 0.20 m FORWARD, abandon the goal."""
+ if getattr(msg, "data", False):
+ acted = self._planner.escape(direction=+1.0, trigger="bump_rear")
+ logger.warning("BUMP received: rear contact", reflex="escape forward 0.20 m",
+ acted=acted)
+
+ async def handle_stall(self, msg: Bool) -> None:
+ """A stall of the base: stop, abandon the goal, no motion."""
+ if getattr(msg, "data", False):
+ acted = self._planner.stall(trigger="stall")
+ logger.warning("STALL received", reflex="stop, goal abandoned, no motion", acted=acted)
diff --git a/moss_dimos/robot_profile.py b/moss_dimos/robot_profile.py
index bf3b341..66442e3 100644
--- a/moss_dimos/robot_profile.py
+++ b/moss_dimos/robot_profile.py
@@ -4,7 +4,8 @@ The lidar driver, the lidar odometry, the costmap and the planner do not bake
in the rover's dimensions: they read a RobotProfile at call time through
``current()``. The values below are MOSS's, and every one of them can be
overridden by a MOSS_* environment variable (read at call time too, so a
-flight can be re-scaled without a code change).
+flight can be re-scaled without a code change). The speed watchdog
+(tools/speed_guard.py) reads its ceiling, max_speed_mps, from here too.
Frames: base_link IS the lidar's floor projection. The odometry publishes
world->base_link at the lidar's x, y; the costmap body footprint and the
@@ -84,6 +85,7 @@ class RobotProfile:
track_m: float # track centre distance
camera_xyz_base_m: tuple[float, float, float] # depth camera in base_link (lidar_odometry's projection)
camera_pitch_deg: float # pitched DOWN by this much
+ max_speed_mps: float # speed watchdog ceiling (tools/speed_guard.py)
# EVERY value below is a PLACEHOLDER until measured on the rover (CAD nominal
@@ -101,6 +103,13 @@ class RobotProfile:
# MOSS_TRACK_M 0.266 CAD centre distance (moss_adapter reads the same variable)
# MOSS_CAMERA_XYZ_M "0.156 0 0.075" D455F face on the nose, CAD nominal
# MOSS_CAMERA_PITCH_DEG 0.0
+# MOSS_MAX_SPEED_MPS 0.45 body speed beyond which tools/speed_guard.py stops the run:
+# the planner's cruise plus a margin. Cruise = dimOS's
+# LocalPlanner speed 0.55 m/s x tools/moss-fly.sh's
+# NERF_SPEED 0.7 = 0.385 m/s; 0.45 leaves 0.065 m/s (17 %).
+# The watchdog refuses a ceiling at or under the cruise (it
+# would stop every normal run). Once MOSS_MPS_AT_LIMIT is
+# measured, check the cruise really driven stays under it.
MOSS = RobotProfile(
name="moss",
lidar_height_m=0.20,
@@ -116,6 +125,7 @@ MOSS = RobotProfile(
track_m=0.266,
camera_xyz_base_m=(0.156, 0.0, 0.075),
camera_pitch_deg=0.0,
+ max_speed_mps=0.45,
)
# field -> (env var, number of floats; 0 = list of (start, end) pairs)
@@ -133,6 +143,7 @@ _MOSS_ENV = {
"track_m": ("MOSS_TRACK_M", 1),
"camera_xyz_base_m": ("MOSS_CAMERA_XYZ_M", 3),
"camera_pitch_deg": ("MOSS_CAMERA_PITCH_DEG", 1),
+ "max_speed_mps": ("MOSS_MAX_SPEED_MPS", 1),
}
_warned: set[tuple[str, str]] = set()
diff --git a/tools/arm_speed_guard.sh b/tools/arm_speed_guard.sh
new file mode 100755
index 0000000..6a7d58c
--- /dev/null
+++ b/tools/arm_speed_guard.sh
@@ -0,0 +1,104 @@
+#!/usr/bin/env bash
+# Arm the speed watchdog (tools/speed_guard.py) for THIS run, on the rover:
+#
+# tools/arm_speed_guard.sh [RUN_DIR] RUN_DIR: the run's dimOS log dir (tools/moss-fly.sh knows it);
+# without it the watchdog takes the newest run dir
+#
+# NEVER "start one only if pgrep finds none": the previous run's watchdog
+# survives its run (`dimos stop` only sweeps the processes of its own run) and
+# its mere presence would satisfy that check while it tails a log that no
+# longer grows - "speed watchdog armed" on screen, the envelope unenforced on
+# the floor. The handle is the pid file speed_guard.py stamps at startup:
+# kill THAT pid, start a fresh watchdog, then prove the pid file names a
+# process born AFTER that launch. No proof -> non-zero, and the caller must not
+# explore. A ceiling (MOSS_MAX_SPEED_MPS) that is not above the planner's
+# cruise makes the watchdog refuse to start, so arming fails the same way.
+set -u
+cd "$(dirname "$0")/.." || exit 1
+
+PID_FILE="${SPEED_GUARD_PID_FILE:-/tmp/moss_speed_guard.pid}"
+GUARD_PY="${SPEED_GUARD_PY:-tools/speed_guard.py}"
+PYTHON="${SPEED_GUARD_PYTHON:-.venv/bin/python}"
+LOG="${SPEED_GUARD_LOG:-/tmp/moss_speed_guard.log}"
+DEADLINE_S="${SPEED_GUARD_ARM_DEADLINE_S:-15}" # the fresh watchdog must show up within this
+TICK=$(getconf CLK_TCK)
+# the watchdog's STOP rides the run's bus (explore_ctl reads DIMOS_TRANSPORT,
+# then TRANSPORT): the run's setting must reach the python we launch
+BUS="${DIMOS_TRANSPORT:-${TRANSPORT:-lcm}}"
+export DIMOS_TRANSPORT="$BUS" TRANSPORT="$BUS"
+if [ "$#" -gt 0 ] && [ -n "$1" ]; then
+ [ -d "$1" ] || { echo "RUN DIR $1 IS NOT A DIRECTORY - not arming"; exit 1; }
+ export SPEED_GUARD_RUN_DIR="$1"
+fi
+
+alive() { # a zombie still answers kill -0 and still tails nothing: it is not alive
+ local rest state
+ rest=$(cut -d')' -f2- "/proc/$1/stat" 2>/dev/null) || return 1
+ read -r state _ <<<"$rest"
+ [ "$state" != "Z" ]
+}
+
+is_guard() { tr '\0' ' ' < "/proc/$1/cmdline" 2>/dev/null | grep -q "speed_guard\.py"; }
+
+born_s() { # seconds since boot at which pid $1 was born (/proc/<pid>/stat field 22)
+ local rest
+ local -a f
+ rest=$(cut -d')' -f2- "/proc/$1/stat" 2>/dev/null) || return 1
+ read -r -a f <<<"$rest" # f[0] is the state, so field 22 overall is f[19]
+ [ "${#f[@]}" -ge 20 ] || return 1
+ echo $(( f[19] / TICK ))
+}
+
+# 1. retire the previous run's watchdog, by the pid IT left behind
+OLD=$(cat "$PID_FILE" 2>/dev/null || true)
+case "$OLD" in
+ '') ;;
+ *[!0-9]*) echo " $PID_FILE holds no pid ('$OLD') - ignored" ;;
+ *)
+ if ! alive "$OLD"; then
+ echo " previous watchdog (pid $OLD) already gone - stale pid file"
+ elif ! is_guard "$OLD"; then
+ echo " pid $OLD is not a speed guard (pid reused) - NOT killed"
+ else
+ kill "$OLD" 2>/dev/null
+ for _ in $(seq 1 50); do alive "$OLD" || break; sleep 0.1; done
+ if alive "$OLD"; then
+ kill -9 "$OLD" 2>/dev/null
+ for _ in $(seq 1 20); do alive "$OLD" || break; sleep 0.1; done
+ fi
+ if alive "$OLD"; then
+ echo "PREVIOUS WATCHDOG (pid $OLD) WILL NOT DIE - not arming over it"
+ exit 1
+ fi
+ echo " previous watchdog (pid $OLD) retired"
+ fi ;;
+esac
+rm -f "$PID_FILE" # only the NEW watchdog may satisfy the check below
+
+# 2. launch the fresh one, keeping the mark it must postdate
+read -r UP _ < /proc/uptime
+LAUNCH_S="${UP%%.*}" # seconds since boot, taken BEFORE the launch
+nohup "$PYTHON" "$GUARD_PY" > "$LOG" 2>&1 < /dev/null &
+
+# 3. the pid file must now name a live process born after that mark
+NEW=""
+END=$((SECONDS + DEADLINE_S))
+while [ "$SECONDS" -lt "$END" ]; do
+ P=$(cat "$PID_FILE" 2>/dev/null || true)
+ case "$P" in
+ ''|*[!0-9]*) sleep 0.2; continue ;;
+ esac
+ if alive "$P"; then
+ B=$(born_s "$P" || true)
+ if [ -n "$B" ] && [ "$B" -ge "$LAUNCH_S" ]; then NEW="$P"; break; fi
+ fi
+ sleep 0.2
+done
+if [ -z "$NEW" ] || ! alive "$NEW"; then
+ echo "SPEED WATCHDOG DID NOT COME UP: $PID_FILE names no live process born after the launch (${DEADLINE_S} s) - see $LOG"
+ tail -3 "$LOG" 2>/dev/null | sed 's/^/ /'
+ exit 1
+fi
+# the ceiling the watchdog enforces, said the way it reads it (the profile, MOSS_MAX_SPEED_MPS)
+LIMIT=$("$PYTHON" -c 'from moss_dimos import robot_profile; print(robot_profile.current().max_speed_mps)' 2>/dev/null || echo "?")
+echo "speed watchdog armed (stops the run beyond ${LIMIT} m/s) - pid $NEW, born after this launch"
diff --git a/tools/decision_replay.py b/tools/decision_replay.py
new file mode 100644
index 0000000..c6c0a47
--- /dev/null
+++ b/tools/decision_replay.py
@@ -0,0 +1,562 @@
+#!/usr/bin/env python3
+"""Replay a REAL exploration decision out of a recording, cluster by cluster.
+
+ tools/decision_replay.py # the newest exploration run and recording
+ tools/decision_replay.py --rec ~/.local/state/moss/recordings/moss.db \\
+ --log <dimos log dir>/<run>/main.jsonl
+ tools/decision_replay.py ... --decision 10 # only that one, with the full table
+ tools/decision_replay.py ... --decision final # the call that ended the run
+
+`explorer2.next_target` is a pure function of (costmap, pose, state), so the
+recording holds everything a decision was made from. This tool rebuilds that
+input from the dimOS recording and runs the real function over it:
+
+ costmap the `global_costmap` LCM blobs, decoded here rather than through
+ dimOS (so a laptop without dimOS can replay). The layout is checked
+ on every message: 8 byte fingerprint, int32 cell count, int32 pad,
+ 8 byte stamp, frame_id string, 8 byte stamp, float32 resolution,
+ int32 width, int32 height, 7 doubles of origin, then width*height
+ int8 cells. A message whose trailing byte count is not width*height
+ is refused, so a format change cannot pass silently.
+ pose the `odom` row nearest before the decision, quaternion included.
+ state rebuilt by replaying EVERY decision of the run in order, since
+ ExploreState is only ever written by next_target itself (plus the
+ loop's note_failed, which the log reports as "planner gave up" or
+ as a goal timeout that closed too little ground: "... excluded").
+ Decision N therefore sees exactly the memory decision N saw. Each
+ "exploration start" line begins a fresh memory, as the explorer
+ does when exploration is started again in the same run.
+ tuning the explorer's: the profile's clearances (robot_profile.derived)
+ and the distance exponent, goal cap and exploration radius the run
+ logged on its "exploration start" line (MOSS_EXPLORE_DISTANCE_EXP,
+ MOSS_GOAL_MAX_M, MOSS_EXPLORE_RADIUS_M at the time).
+
+Rows and log lines are on one clock: the recorder stamps a row with its
+message's own ts (time.time() on the robot, in the odometry and the costmap)
+and the log lines carry the same machine's wall clock.
+
+The cross-check that this is the real decision and not a reconstruction: the
+goal the replay picks, its path cost and its frontier-cell count are printed
+next to the ones the run logged. They match to the centimetre while the
+scoring has not moved since that run.
+"""
+
+from __future__ import annotations
+
+import argparse
+import bisect
+import json
+import math
+import os
+import re
+import sqlite3
+import struct
+import sys
+from dataclasses import dataclass, replace
+from datetime import datetime, timezone
+
+import numpy as np
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, ROOT)
+
+from moss_dimos import robot_profile # noqa: E402
+from moss_dimos.explorer2 import ( # noqa: E402
+ DEFAULT_TUNING, DIRECTIVE_FRONTIER, Cluster, ExploreState, Tuning,
+ _REVISIT_FADE_POWER, _cells_of, _clusters, _count_clusters, _decided_from, _frontier_mask, _path_cost,
+ _survey, _yaw_of, next_target, unknown_signature,
+)
+
+FREE, UNKNOWN, OCCUPIED = 0, -1, 100
+START_RE = re.compile(r"^exploration start: distance exp ([\d.eE+-]+|inf), cap ([\d.eE+-]+|inf) m, "
+ r"radius ([\d.eE+-]+|inf) m")
+
+
+# --- the recording ---------------------------------------------------------
+
+_FINGERPRINT_LEN = 8
+
+
+def decode_occupancy_grid(blob: bytes) -> tuple[np.ndarray, float, float, float, str]:
+ """One `global_costmap` LCM blob -> (grid HxW int8, resolution, ox, oy, frame_id)."""
+ off = _FINGERPRINT_LEN
+ n_cells = struct.unpack_from(">i", blob, off)[0]
+ off += 8 # count + pad
+ off += 8 # stamp
+ str_len = struct.unpack_from(">i", blob, off)[0]
+ off += 4
+ frame_id = blob[off:off + str_len - 1].decode("ascii")
+ off += str_len
+ off += 8 # stamp again
+ res = struct.unpack_from(">f", blob, off)[0]
+ off += 4
+ width, height = struct.unpack_from(">ii", blob, off)
+ off += 8
+ origin = struct.unpack_from(">7d", blob, off)
+ off += 56
+ cells = len(blob) - off
+ if cells != width * height or n_cells != width * height:
+ raise ValueError(f"costmap blob: {cells} trailing bytes for a "
+ f"{width}x{height} grid ({n_cells} announced)")
+ grid = np.frombuffer(blob, dtype=np.int8, count=width * height, offset=off)
+ return (grid.reshape(height, width).copy(), float(res),
+ float(origin[0]), float(origin[1]), frame_id)
+
+
+class _Grid:
+ """What next_target reads off a costmap. Same attribute names as dimOS's."""
+
+ def __init__(self, grid, res, ox, oy, ts, frame_id="world"):
+ self.grid, self.resolution, self.ts, self.frame_id = grid, res, ts, frame_id
+ self.origin = type("O", (), {"position": type("P", (), {
+ "x": ox, "y": oy, "z": 0.0})()})()
+
+
+class _Pose:
+ def __init__(self, x, y, qz, qw, ts):
+ self.position = type("P", (), {"x": x, "y": y, "z": 0.0})()
+ self.orientation = type("Q", (), {"x": 0.0, "y": 0.0, "z": qz, "w": qw})()
+ self.ts = ts
+
+
+class Recording:
+ """Read-only view of one dimOS recording: costmaps and poses, by timestamp."""
+
+ def __init__(self, path: str) -> None:
+ self.db = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
+ self.costmap_ts = [r[0] for r in self.db.execute(
+ 'select ts from "global_costmap" order by ts')]
+ self.costmap_ids = [r[0] for r in self.db.execute(
+ 'select id from "global_costmap" order by ts')]
+ rows = self.db.execute(
+ 'select ts, pose_x, pose_y, pose_qz, pose_qw from "odom" '
+ 'where pose_x is not null order by ts').fetchall()
+ self.odom_ts = [r[0] for r in rows]
+ self.odom = rows
+
+ def costmap_at(self, t: float) -> _Grid:
+ """The last costmap published at or before `t` - what the loop held."""
+ i = bisect.bisect_right(self.costmap_ts, t) - 1
+ if i < 0:
+ raise LookupError(f"no costmap at or before {t}")
+ blob = self.db.execute('select data from global_costmap_blob where id=?',
+ (self.costmap_ids[i],)).fetchone()[0]
+ grid, res, ox, oy, frame_id = decode_occupancy_grid(blob)
+ return _Grid(grid, res, ox, oy, self.costmap_ts[i], frame_id)
+
+ def pose_at(self, t: float) -> _Pose:
+ i = bisect.bisect_right(self.odom_ts, t) - 1
+ if i < 0:
+ raise LookupError(f"no odometry at or before {t}")
+ ts, x, y, qz, qw = self.odom[i]
+ return _Pose(float(x), float(y), float(qz), float(qw), float(ts))
+
+
+# --- the log ---------------------------------------------------------------
+
+@dataclass
+class LogEvent:
+ t: float # epoch seconds, same clock as the recording rows
+ kind: str # "start" | "goal" | "none" | "wait" | "back_off" | "failed"
+ goal_n: int | None = None
+ xy: tuple[float, float] | None = None
+ path_cost_m: float | None = None
+ info_cells: int | None = None
+ n_clusters: int | None = None
+ elapsed_ms: float | None = None
+ shape: tuple[float, float, float] | None = None # "start": (distance exponent, cap m, radius m)
+ text: str = ""
+
+
+def _epoch(iso: str) -> float:
+ return datetime.fromisoformat(iso.replace("Z", "+00:00")).astimezone(timezone.utc).timestamp()
+
+
+def read_log(path: str) -> list[LogEvent]:
+ """The explorer2 lines of a dimOS jsonl log, in order."""
+ out: list[LogEvent] = []
+ for line in open(path):
+ try:
+ d = json.loads(line)
+ except ValueError:
+ continue
+ if not isinstance(d, dict) or not str(d.get("logger", "")).endswith("explorer2.py"):
+ continue
+ ev, t = d.get("event", ""), _epoch(d["timestamp"])
+ if ev.startswith("exploration start"):
+ m = START_RE.match(ev)
+ out.append(LogEvent(t=t, kind="start", text=ev,
+ shape=tuple(float(g) for g in m.groups()) if m else None))
+ continue
+ if ev.startswith("goal timeout"):
+ # Not a decision, the next line is - but the timeout that closed
+ # less than GOAL_PROGRESS_M excludes the goal (explorer2 calls
+ # note_failed there too), so it IS a write to the memory. Tested
+ # before the "goal N:" branch: it starts with "goal " and carries a
+ # colon, so it would otherwise be parsed as a goal (int("timeout")).
+ if ": excluded" in ev:
+ out.append(LogEvent(t=t, kind="failed", text=ev))
+ continue
+ if ev.startswith("goal ") and ":" in ev:
+ head, rest = ev.split(":", 1)
+ n = int(head.split()[1])
+ xy = rest.split("(")[1].split(")")[0].split(",")
+ out.append(LogEvent(
+ t=t, kind="goal", goal_n=n,
+ xy=(float(xy[0]), float(xy[1])),
+ path_cost_m=float(rest.split("m away")[0].split(")")[1].strip()),
+ info_cells=int(rest.split("frontier cells")[0].split(",")[-1]),
+ n_clusters=int(rest.split("clusters")[0].split(",")[-1]),
+ elapsed_ms=float(rest.split("chosen in")[1].split("ms")[0]),
+ text=ev))
+ elif ev.startswith("exploration complete"):
+ out.append(LogEvent(t=t, kind="none",
+ elapsed_ms=float(ev.split(",")[-1].split("ms")[0]),
+ text=ev))
+ elif ev.startswith("planner gave up"):
+ out.append(LogEvent(t=t, kind="failed", text=ev))
+ elif "waiting" in ev or ev.startswith("starvation escape"):
+ out.append(LogEvent(t=t, kind="wait", text=ev))
+ elif ev.startswith("born cornered"):
+ out.append(LogEvent(t=t, kind="back_off", text=ev))
+ return out
+
+
+def run_tuning(shape: tuple[float, float, float] | None, base: Tuning | None = None) -> Tuning:
+ """The explorer's Tuning for one exploration: its clearances come from the
+ profile (the blueprint passes robot_profile.derived), its distance exponent,
+ goal cap and radius from the run's "exploration start" line; DEFAULT_TUNING
+ for the rest, as the blueprint leaves them."""
+ lethal, pivot = robot_profile.derived()
+ tuning = replace(base or DEFAULT_TUNING, lethal_clearance_m=lethal, pivot_clearance_m=pivot)
+ if shape is not None:
+ exp, cap, radius = shape
+ tuning = replace(tuning, distance_exponent=exp, max_goal_path_m=cap, explore_radius_m=radius)
+ return tuning
+
+
+# --- the decision, opened up ----------------------------------------------
+
+@dataclass
+class Scored:
+ cluster: Cluster
+ reason: str # "" when it competed, otherwise why it did not
+ cost: float = math.inf
+ gain: float = 0.0
+ base: float = 0.0 # gain / (1 + cost) ** distance_exponent
+ probe_mult: float = 1.0
+ forward_mult: float = 1.0
+ revisit_mult: float = 1.0
+ score: float = -math.inf
+
+
+def explain(costmap, pose, state: ExploreState, now: float,
+ tuning: Tuning) -> tuple[list[Scored], dict]:
+ """The same arithmetic next_target does, with every term kept.
+
+ Reads the module's own internals, so it cannot drift from the function it
+ explains: if the scoring changes, this changes with it. The exclusions
+ come in next_target's order (already seen from, outside the exploration
+ radius, recently failed), then the path cost, then the goal cap.
+ """
+ grid = np.asarray(costmap.grid)
+ res = float(costmap.resolution)
+ ox = float(costmap.origin.position.x)
+ oy = float(costmap.origin.position.y)
+ rx, ry = float(pose.position.x), float(pose.position.y)
+ heading = _yaw_of(pose, state.heading)
+
+ # next_target records the anchor and the pose it was called from BEFORE it
+ # excludes anything, so the standing-point rule sees it. Same step here, on a copy.
+ state = state.copy()
+ if state.anchor is None:
+ state.anchor = (rx, ry)
+ half = tuning.observed_radius_m / 2.0
+ if all((rx - px) ** 2 + (ry - py) ** 2 >= half * half for px, py in state.observed):
+ state.observed.append((rx, ry))
+
+ h, w = grid.shape
+ gx0 = int(np.clip(math.floor((rx - ox) / res), 0, w - 1))
+ gy0 = int(np.clip(math.floor((ry - oy) / res), 0, h - 1))
+ survey = _survey(grid, res, (gy0, gx0), tuning)
+ frontier_all = _frontier_mask(survey)
+ min_cells = max(1, int(tuning.min_frontier_perimeter_m / res))
+ on_the_map = _count_clusters(frontier_all, min_cells)
+ decided = _decided_from(state.observed, (h, w), res, (ox, oy), tuning.observed_radius_m)
+ clusters = ([] if survey.seed is None
+ else _clusters(survey, frontier_all, (h, w), res, (ox, oy), tuning, decided,
+ _cells_of(state.observed, (h, w), res, (ox, oy))))
+ costs = (_path_cost(survey.reachable, survey.cell_cost, survey.seed, res)
+ if survey.seed is not None else None)
+
+ radius2 = tuning.failed_goal_radius_m ** 2
+ # mirror next_target's trigger pruning: an exclusion holds only while the
+ # rover is still near where it failed AND the map around the goal has not
+ # changed (triggers, not a clock)
+ moved2 = tuning.failed_goal_moved_m ** 2
+ held_failed = [f for f in state.failed
+ if (rx - f[2]) ** 2 + (ry - f[3]) ** 2 < moved2
+ and unknown_signature(costmap, f[0], f[1], tuning.failed_goal_radius_m) == f[4]]
+ ax, ay = state.anchor
+ out: list[Scored] = []
+ for cluster in clusters:
+ gx, gy = cluster.goal_xy
+ s = Scored(cluster=cluster, reason="")
+ if cluster.retired:
+ s.reason = "already-seen-from"
+ out.append(s)
+ continue
+ if tuning.explore_radius_m > 0 and math.hypot(gx - ax, gy - ay) > tuning.explore_radius_m:
+ s.reason = "outside-radius"
+ out.append(s)
+ continue
+ if any((gx - f[0]) ** 2 + (gy - f[1]) ** 2 < radius2 for f in held_failed):
+ s.reason = "recently-failed"
+ out.append(s)
+ continue
+ gyc, gxc = cluster.goal_yx
+ cost = float(costs[gyc, gxc]) if survey.reachable[gyc, gxc] else math.inf
+ s.cost = cost
+ if not math.isfinite(cost):
+ s.reason = "unreachable"
+ out.append(s)
+ continue
+ s.gain = cluster.gain
+ s.base = cluster.gain / (1.0 + cost) ** tuning.distance_exponent
+ s.probe_mult = tuning.probe_penalty if cluster.probe else 1.0
+ dx, dy = gx - rx, gy - ry
+ span = math.hypot(dx, dy)
+ if span > 0.1:
+ align = max(0.0, math.cos(heading) * dx / span + math.sin(heading) * dy / span)
+ s.forward_mult = 1.0 + tuning.forward_bonus * align
+ older = state.visited[:-1]
+ if older:
+ nearest = min(math.hypot(gx - vx, gy - vy) for vx, vy in older)
+ if nearest < tuning.revisit_radius_m:
+ fade = nearest / tuning.revisit_radius_m
+ s.revisit_mult = fade ** _REVISIT_FADE_POWER
+ s.score = s.base * s.probe_mult * s.forward_mult * s.revisit_mult
+ out.append(s)
+
+ # the goal cap, as next_target applies it: a SAFE cluster within the cap
+ # keeps every cluster beyond it out; only probes within it -> they compete
+ # with the safe clusters beyond it; nothing within it -> everything competes
+ cap = tuning.max_goal_path_m
+ competing = [s for s in out if not s.reason]
+ beyond = {id(s) for s in competing if cap > 0 and s.cost > cap}
+ within = [s for s in competing if id(s) not in beyond]
+ if any(not s.cluster.probe for s in within):
+ dropped = beyond
+ elif within:
+ dropped = {id(s) for s in competing if id(s) in beyond and s.cluster.probe}
+ else:
+ dropped = set()
+ for s in competing:
+ if id(s) in dropped:
+ s.reason = "beyond-cap"
+
+ out.sort(key=lambda s: (bool(s.reason), -s.score, s.reason))
+ info = {"n_clusters": len(clusters), "heading": heading, "on_the_map": on_the_map,
+ "reachable_free_m2": survey.reachable_free_m2,
+ "unknown_m2": float(survey.unknown.sum()) * res * res,
+ "free_m2": float(survey.free.sum()) * res * res,
+ "res": res, "origin": (ox, oy), "shape": (h, w), "pose": (rx, ry)}
+ return out, info
+
+
+# --- printing --------------------------------------------------------------
+
+def print_table(scored: list[Scored], info: dict, chosen, logged: LogEvent | None,
+ top: int = 40) -> None:
+ rx, ry = info["pose"]
+ print(f" pose ({rx:+.2f}, {ry:+.2f}) heading {math.degrees(info['heading']):+.0f} deg "
+ f"grid {info['shape'][1]}x{info['shape'][0]} @ {info['res']} m "
+ f"free {info['free_m2']:.1f} m2, unknown {info['unknown_m2']:.1f} m2")
+ print(f" frontier clusters: {info['on_the_map']} on the map, "
+ f"{info['n_clusters']} reachable from where the body stands, "
+ f"{sum(1 for s in scored if not s.reason)} eligible")
+ print(f" {'#':>2} {'stand at':>16} {'cells':>6} {'gain':>7} {'cost m':>7} "
+ f"{'base':>9} {'probe':>6} {'fwd':>5} {'revis':>6} {'score':>10} why not")
+ for i, s in enumerate(scored[:top], start=1):
+ c = s.cluster
+ gx, gy = c.goal_xy
+ cost = f"{s.cost:7.2f}" if math.isfinite(s.cost) else " inf"
+ score = f"{s.score:10.5f}" if math.isfinite(s.score) else " -"
+ mark = " "
+ if chosen is not None and abs(gx - chosen.position.x) < 1e-6 and \
+ abs(gy - chosen.position.y) < 1e-6:
+ mark = ">"
+ print(f" {mark}{i:>2} ({gx:+6.2f},{gy:+6.2f}) {c.size:6d} {s.gain:7.3f} {cost} "
+ f"{s.base:9.5f} {s.probe_mult:6.2f} {s.forward_mult:5.2f} "
+ f"{s.revisit_mult:6.2f} {score} {s.reason}")
+ if len(scored) > top:
+ print(f" ... {len(scored) - top} more")
+ if chosen is None:
+ print(" -> next_target returned None (exploration would stop here)")
+ else:
+ d = getattr(chosen, "directive", "?")
+ print(f" -> {d} ({chosen.position.x:+.2f}, {chosen.position.y:+.2f})"
+ + (f" score {getattr(chosen, 'score', float('nan')):.5f}"
+ f" cost {getattr(chosen, 'path_cost_m', float('nan')):.2f} m"
+ f" {getattr(chosen, 'info_cells', 0)} cells"
+ if d == DIRECTIVE_FRONTIER else ""))
+ if logged is not None and logged.kind == "goal":
+ print(f" == the run logged: goal {logged.goal_n} "
+ f"({logged.xy[0]:+.2f}, {logged.xy[1]:+.2f}) {logged.path_cost_m} m, "
+ f"{logged.info_cells} cells, {logged.n_clusters} clusters")
+ elif logged is not None and logged.kind == "none":
+ print(f" == the run logged: {logged.text}")
+
+
+# --- the replay ------------------------------------------------------------
+
+def replay(rec: Recording, events: list[LogEvent], tuning: Tuning,
+ stop_after: int | None = None):
+ """Walk every decision of the run through next_target, in order.
+
+ The memory carried forward is the RUN's, not the replay's: the goals the
+ run actually published (from the log) and the poses it actually decided
+ from (from the odometry). Feeding the replay its own choices would be a
+ different run after the first divergence, and then decision N would no
+ longer be the decision that was actually observed. The scoring under test
+ therefore always answers the question the rover was really asked.
+
+ `tuning` is the base; each "exploration start" line resets the memory and
+ sets the tuning that exploration ran with (run_tuning).
+
+ Yields (index, LogEvent, costmap, pose, state_before, target, tuning).
+ """
+ state = ExploreState()
+ current = tuning
+ idx = 0
+ for ev in events:
+ if ev.kind == "start":
+ state = ExploreState()
+ current = run_tuning(ev.shape, tuning)
+ continue
+ if ev.kind == "failed":
+ # The loop's own write, reported by the log line. Same arguments
+ # explorer2._note_failed passes: where the rover STOOD and the
+ # costmap it held, the two reopening triggers of the exclusion.
+ goal = _last_goal(events, ev.t)
+ if goal is not None:
+ stood = rec.pose_at(ev.t)
+ state.note_failed(goal[0], goal[1],
+ (stood.position.x, stood.position.y),
+ rec.costmap_at(ev.t), current.failed_goal_radius_m)
+ continue
+ if ev.kind not in ("goal", "none", "wait", "back_off"):
+ continue
+ t0 = ev.t - (ev.elapsed_ms or 0.0) / 1000.0 - 0.02
+ costmap = rec.costmap_at(t0)
+ pose = rec.pose_at(t0)
+ before = state.copy()
+ asked = state.copy()
+ target = next_target(costmap, pose, asked, now=ev.t, tuning=current)
+ # advance the real memory: the pose is what it is, the goal is the
+ # one the RUN published. The wait streak and the back-off flag are
+ # next_target's own writes (the starvation escape and the once-per-pocket
+ # back-off read them); a goal the run published clears both, as
+ # next_target does when a frontier goes out.
+ state.observed = list(asked.observed)
+ state.heading = asked.heading
+ state.failed = list(asked.failed)
+ state.anchor = asked.anchor
+ state.wait_streak = asked.wait_streak
+ state.back_off_issued = asked.back_off_issued
+ if ev.kind == "goal" and ev.xy is not None:
+ state.visited.append(ev.xy)
+ state.targets_issued += 1
+ state.wait_streak = 0
+ state.back_off_issued = False
+ idx += 1
+ yield idx, ev, costmap, pose, before, target, current
+ if stop_after is not None and idx >= stop_after:
+ return
+
+
+def _last_goal(events: list[LogEvent], t: float):
+ for ev in reversed(events):
+ if ev.kind == "goal" and ev.t < t:
+ return ev.xy
+ return None
+
+
+def main(argv=None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--rec", default=None,
+ help="the recording (default: the newest moss*.db, as tools/run_film.py picks it)")
+ ap.add_argument("--log", default=None,
+ help="the run's main.jsonl (default: the newest exploration run, as tools/run_film.py picks it)")
+ ap.add_argument("--decision", default="all",
+ help="goal number, 'final', or 'all' (default)")
+ ap.add_argument("--top", type=int, default=40, help="clusters listed per decision")
+ args = ap.parse_args(argv)
+
+ if args.rec is None or args.log is None:
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ import run_film
+ args.rec = args.rec or run_film.newest_db()
+ args.log = args.log or run_film.newest_log()
+ if not args.rec or not args.log:
+ print(f"missing input: rec={args.rec} log={args.log}")
+ return 1
+ rec = Recording(args.rec)
+ events = read_log(args.log)
+ decisions = [e for e in events if e.kind in ("goal", "none", "wait", "back_off")]
+ base = run_tuning(None)
+ print(f"recording {args.rec}: "
+ f"{len(rec.costmap_ts)} costmaps, {len(rec.odom_ts)} poses, "
+ f"{len(decisions)} explorer decisions in {args.log}")
+ print(f"tuning: clearances {base.lethal_clearance_m:.2f} / {base.pivot_clearance_m:.2f} m (profile), "
+ f"observed_radius {base.observed_radius_m} m, info_radius {base.info_radius_m} m, "
+ f"probe_penalty {base.probe_penalty}, revisit_radius {base.revisit_radius_m} m; "
+ f"distance exp / cap / radius from each 'exploration start' line")
+
+ want_all = args.decision == "all"
+ want_final = args.decision == "final"
+ want_n = None if (want_all or want_final) else int(args.decision)
+
+ same_goal = n_goals = same_count = 0
+ for idx, ev, costmap, pose, before, target, tuning in replay(rec, events, base):
+ interesting = want_all or (want_final and ev.kind == "none") or \
+ (want_n is not None and ev.goal_n == want_n)
+ if ev.kind == "goal":
+ n_goals += 1
+ if target is not None and getattr(target, "directive", "") == DIRECTIVE_FRONTIER:
+ same_goal += (abs(target.position.x - ev.xy[0]) < 0.011 and
+ abs(target.position.y - ev.xy[1]) < 0.011)
+ same_count += getattr(target, "n_clusters", -1) == ev.n_clusters
+ if not interesting:
+ continue
+ print()
+ print("=" * 110)
+ head = (f"decision {idx}"
+ + (f" (goal {ev.goal_n})" if ev.goal_n else f" ({ev.kind})"))
+ print(f"{head} at {datetime.fromtimestamp(ev.t, timezone.utc):%H:%M:%S} UTC, "
+ f"costmap {costmap.ts - ev.t:+.1f} s, "
+ f"state: {len(before.visited)} goals issued, "
+ f"{len(before.observed)} standing points, {len(before.failed)} failed; "
+ f"distance exp {tuning.distance_exponent:g}, cap {tuning.max_goal_path_m:g} m, "
+ f"radius {tuning.explore_radius_m:g} m")
+ print("=" * 110)
+ scored, info = explain(costmap, pose, before, ev.t, tuning)
+ print_table(scored, info, target, ev, top=args.top)
+
+ print()
+ # Two different claims, and only the first one is a claim about the INPUT:
+ # the cluster count is what the map and the state say, whatever the
+ # scoring then does with them, so it is the check that the decode, the
+ # pose lookup and the rebuilt memory are the ones the run had.
+ # the goal is what the CURRENT scoring picks; it matches the run only
+ # while the scoring has not moved since that run.
+ print(f"decisions whose cluster count matches the run's: {same_count} of {n_goals}")
+ print(f"decisions whose goal matches the run's: {same_goal} of {n_goals}")
+ print("(both are comparisons, not tests: they move as the scoring moves. What is\n"
+ " under test lives in benches/bench_explorer2_cold.py.)")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/gyro_sign_bench.py b/tools/gyro_sign_bench.py
new file mode 100644
index 0000000..c06862c
--- /dev/null
+++ b/tools/gyro_sign_bench.py
@@ -0,0 +1,296 @@
+"""Gyro sign bench: does the RealSense gyro agree with the lidar about turning?
+
+The lidar odometry's rotation prior reads the yaw rate on one axis of the
+camera's frame (LidarOdometry gyro_axis "-y": the level, upright mount on the
+nose). A wrong-sign rotation prior is worse than none, so the prior stays off
+(MOSS_GYRO unset) until this bench has measured the mapping instead of
+guessing it:
+
+ 1. commands a pivot, left then right, until the LIDAR yaw has turned by
+ TURN_DEG (30 deg), the gyro by GYRO_STOP_RATIO x TURN_DEG, or MAX_RUNG_S
+ passed
+ 2. integrates the gyro (mapped axis) over each move
+ 3. reads the lidar odometry yaw over the same window
+ 4. verdict: SAME sign and similar magnitude -> the mapping is right
+ (then MOSS_GYRO=1); OPPOSITE sign -> flip it; garbage -> the mapping
+ axis is wrong.
+
+A rung only counts once the LIDAR SAW the body turn (MIN_TURN_DEG). With no
+such rung the bench measured nothing and refuses to conclude: a run where the
+rover stood still (tracks off the ground, base not armed, the pad's deadman)
+must never validate the mapping.
+
+A rung the lidar did not end, on which the gyro says the body turned past
+TURN_DEG and more than LOST_RATIO times what the lidar saw, is a lidar that
+lost the pivot (or a gyro that over-reads): the bench says INCONCLUSIVE (exit
+3) and never blames the gyro's axes for it. The gyro stop keeps such a rung to
+about GYRO_STOP_RATIO x TURN_DEG of body turn instead of MAX_RUNG_S of pivot.
+
+The lidar yaw must be the lidar's own: with the prior on (MOSS_GYRO=1) every
+registration starts from the gyro under test. Before turning, the bench reads
+the newest run's log; a "prior: gyro=True" line there is a refusal (exit 3).
+
+The rung ends on the lidar's own yaw, not on a clock: the tracks are open loop
+and every pivot goes out at MOSS_PIVOT_PCT (100 % by default) whatever rate is
+asked, so a rung timed for 30 deg at TURN_RAD_S would turn several times that.
+At full power (about 250 deg/s on the floor) the lidar odometry without the
+prior may not follow the turn; launch the stack with a slower pivot for this
+bench (MOSS_PIVOT_PCT=50) and read the deg/s each rung prints.
+
+The gyro is integrated on the samples' own stamps, as the odometry's prior
+integrates them (lidar_odometry handle_imu: 0 < dt < 0.1 s), so the bench
+measures the integral the prior would use.
+
+Known input -> known output, in degrees.
+
+Run on the robot WITH the stack up (imu + odom on the bus, the base armed,
+nothing else commanding: exploration not armed, the pad untouched; MOSS_GYRO
+unset), with room to turn:
+
+ MOSS_PIVOT_PCT=50 tools/moss-fly.sh map
+ .venv/bin/python tools/gyro_sign_bench.py
+"""
+from __future__ import annotations
+
+import glob
+import json
+import math
+import os
+import re
+import threading
+import time
+
+TURN_RAD_S = 0.3
+TURN_DEG = 30.0
+MAX_RUNG_S = 6.0 # a rung that has not turned TURN_DEG by then ends anyway (the verdict then says why)
+GYRO_STOP_RATIO = 3.0 # the gyro has turned this many times TURN_DEG and the lidar has not seen TURN_DEG: stop
+LOST_RATIO = 2.0 # a rung the lidar did not end, gyro past TURN_DEG and over this x the lidar: the lidar lost it
+GYRO_AXIS = "-y" # the mapping under test (LidarOdometry gyro_axis)
+MIN_TURN_DEG = 5.0 # below this the lidar saw no turn: the rung measures nothing
+GYRO_MAX_DT_S = 0.1 # the prior's own gap limit: a longer gap between two samples adds nothing
+
+
+ENDED = {"lidar": "the lidar yaw", "gyro": "the gyro integral", "time": "the time limit"}
+
+
+def verdict(results: list[tuple[str, float, float, str]]) -> tuple[str, int]:
+ """(message, exit code) from the rungs [(label, gyro deg, lidar deg, ended), ...],
+ `ended` being what stopped the rung ("lidar", "gyro" or "time").
+
+ Needs at least ONE rung the lidar credits with a real turn - all() over an
+ empty set is True and used to congratulate a rover that never moved. A rung
+ the lidar lost (see the module docstring) makes the whole run inconclusive.
+ """
+ for label, g, l, ended in results:
+ if ended != "lidar" and abs(g) > TURN_DEG and abs(g) > LOST_RATIO * abs(l):
+ return (f"VERDICT: INCONCLUSIVE - rung {label}: the gyro says {g:+.0f} deg, the lidar {l:+.0f} deg, "
+ f"and the rung ended on {ENDED.get(ended, ended)} before the lidar saw {TURN_DEG:.0f} deg: "
+ f"the lidar odometry did not follow the pivot (relaunch the stack with MOSS_PIVOT_PCT=50) "
+ f"or the gyro over-reads - nothing concluded about the axes", 3)
+ turned = [(g, l) for _, g, l, _ended in results if abs(l) > MIN_TURN_DEG]
+ if not turned:
+ return (f"VERDICT: INCONCLUSIVE - no rung turned the body by more than "
+ f"{MIN_TURN_DEG:.0f} deg of lidar yaw, so nothing was measured "
+ f"(tracks off the ground? base not armed? something else commanding?)", 3)
+ if all(g * l > 0 and 0.5 < abs(g / l) < 2.0 for g, l in turned):
+ return (f"VERDICT: mapping '{GYRO_AXIS}' CORRECT - the gyro may serve as "
+ f"rotation prior ({len(turned)}/{len(results)} rungs measured): MOSS_GYRO=1", 0)
+ if all(g * l < 0 for g, l in turned):
+ flip = GYRO_AXIS[1:] if GYRO_AXIS.startswith("-") else "-" + GYRO_AXIS
+ return (f"VERDICT: SIGN FLIPPED - use '{flip}' (LidarOdometry gyro_axis); keep MOSS_GYRO off until then", 2)
+ return ("VERDICT: axis mapping WRONG or gyro not delivering - check the other axes", 2)
+
+
+def axis_rate(v) -> float:
+ """The mapped yaw rate (rad/s) from an angular velocity with .x .y .z."""
+ val = {"x": v.x, "y": v.y, "z": v.z}[GYRO_AXIS[-1]]
+ return -val if GYRO_AXIS.startswith("-") else val
+
+
+def wrap_deg(a: float) -> float:
+ """An angle difference in radians -> degrees in (-180, 180]."""
+ return math.degrees(math.atan2(math.sin(a), math.cos(a)))
+
+
+PRIOR_RE = re.compile(r"prior: gyro=(True|False)")
+
+
+def newest_run_log(env=None) -> str | None:
+ """The newest dimOS run's main.jsonl, whatever its blueprint: the log root's
+ run dirs plus the log_dir of every run registry entry (a dimOS from a git
+ clone logs under the clone)."""
+ env = os.environ if env is None else env
+ state = os.path.join(env.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"), "dimos")
+ hits = glob.glob(os.path.join(state, "logs", "*", "main.jsonl"))
+ for entry in glob.glob(os.path.join(state, "runs", "*.json")):
+ try:
+ with open(entry) as f:
+ log_dir = json.load(f).get("log_dir")
+ except (OSError, ValueError, AttributeError):
+ continue
+ if isinstance(log_dir, str) and os.path.isfile(os.path.join(log_dir, "main.jsonl")):
+ hits.append(os.path.join(log_dir, "main.jsonl"))
+ hits = sorted(set(hits), key=os.path.getmtime)
+ return hits[-1] if hits else None
+
+
+def prior_check(log: str | None) -> tuple[str, int | None]:
+ """(message, exit code or None to go on) from what the run's log says of the
+ gyro prior: its last "prior: gyro=" line (the blueprint's and the odometry's
+ start lines both carry one)."""
+ if not log:
+ return ("WARNING: no dimOS run log to read the gyro prior's state from - make sure the stack runs "
+ "without MOSS_GYRO", None)
+ state = None
+ try:
+ with open(log, errors="replace") as f:
+ for line in f:
+ m = PRIOR_RE.search(line)
+ if m:
+ state = m.group(1) == "True"
+ except OSError as exc:
+ return (f"WARNING: cannot read {log} ({exc}) - make sure the stack runs without MOSS_GYRO", None)
+ if state is None:
+ return (f"WARNING: {log} says nothing of the gyro prior - make sure the stack runs without MOSS_GYRO", None)
+ if state:
+ return (f"KO: {log} says the gyro prior is ON (MOSS_GYRO=1): every lidar registration starts from the "
+ f"gyro under test, so the lidar yaw is not a witness - relaunch the stack without MOSS_GYRO", 3)
+ return (f"gyro prior OFF in {log}: the lidar yaw is the lidar's own", None)
+
+
+class Bench:
+ """The bus side: the gyro integral and the lidar yaw, fed by LCM callbacks.
+
+ `lc` and `twist` are injectable (the cold bench feeds recorded messages
+ through on_imu / on_odom and records the twists); None = the real bus."""
+
+ def __init__(self, lc=None, twist=None, start: bool = True) -> None:
+ self.gyro_int = 0.0
+ self.last_imu_ts: float | None = None
+ self.yaw: float | None = None
+ self.lock = threading.Lock()
+ self.running = True
+ if lc is None:
+ import lcm as lcmlib
+ lc = lcmlib.LCM()
+ if twist is None:
+ from dimos.core.transport_factory import make_transport
+ from dimos.msgs.geometry_msgs.Twist import Twist
+ twist = make_transport("/cmd_vel", Twist)
+ self.lc = lc
+ self.twist = twist
+ self.lc.subscribe("/imu#sensor_msgs.Imu", self._on_imu)
+ self.lc.subscribe("/odom#geometry_msgs.PoseStamped", self._on_odom)
+ self.thread = threading.Thread(target=self._spin, daemon=True)
+ if start:
+ self.thread.start()
+
+ def _spin(self) -> None:
+ while self.running:
+ self.lc.handle_timeout(100)
+
+ def _on_imu(self, _ch: str, data: bytes) -> None:
+ from dimos.msgs.sensor_msgs.Imu import Imu
+ msg = Imu.lcm_decode(data)
+ self.on_imu(axis_rate(msg.angular_velocity), float(getattr(msg, "ts", 0.0) or time.time()))
+
+ def _on_odom(self, _ch: str, data: bytes) -> None:
+ from dimos.msgs.geometry_msgs.PoseStamped import PoseStamped
+ msg = PoseStamped.lcm_decode(data)
+ self.on_odom(msg.orientation.euler[2])
+
+ def on_imu(self, rate: float, ts: float) -> None:
+ """One gyro sample: the mapped rate (rad/s) at its own stamp (s)."""
+ with self.lock:
+ if self.last_imu_ts is not None:
+ dt = ts - self.last_imu_ts
+ if 0.0 < dt < GYRO_MAX_DT_S:
+ self.gyro_int += rate * dt
+ self.last_imu_ts = ts
+
+ def on_odom(self, yaw: float) -> None:
+ """One lidar odometry pose: its yaw (rad)."""
+ with self.lock:
+ self.yaw = yaw
+
+ def reset(self) -> None:
+ with self.lock:
+ self.gyro_int = 0.0
+ self.last_imu_ts = None
+
+ def snapshot(self) -> tuple[float, float | None]:
+ with self.lock:
+ return self.gyro_int, self.yaw
+
+ def _send(self, wz: float) -> None:
+ from dimos.msgs.geometry_msgs.Twist import Twist
+ self.twist.broadcast(None, Twist(linear=[0.0, 0.0, 0.0], angular=[0.0, 0.0, wz]))
+
+ def turn(self, wz: float, deg: float = TURN_DEG, max_s: float = MAX_RUNG_S,
+ clock=time.monotonic, sleep=time.sleep) -> tuple[float, str]:
+ """Pivot at wz (the command, every 0.1 s) until the lidar yaw has turned
+ by `deg` from where the rung started ("lidar"), the gyro integral by
+ GYRO_STOP_RATIO x `deg` ("gyro": the lidar is not following), or
+ `max_s` passed ("time"); then zero. Returns (seconds, what ended it)."""
+ gyro0, yaw0 = self.snapshot()
+ t0 = clock()
+ ended = "time"
+ while clock() - t0 < max_s:
+ gyro, yaw = self.snapshot()
+ if yaw0 is not None and yaw is not None and abs(wrap_deg(yaw - yaw0)) >= deg:
+ ended = "lidar"
+ break
+ if abs(math.degrees(gyro - gyro0)) >= GYRO_STOP_RATIO * deg:
+ ended = "gyro"
+ break
+ self._send(wz)
+ sleep(0.1)
+ self._send(0.0)
+ return clock() - t0, ended
+
+
+def run_rungs(b: Bench, settle_s: float = 1.0, sleep=time.sleep, **turn_kw) -> list[tuple[str, float, float, str]]:
+ """Left then right: [(label, gyro deg, lidar deg, ended)], each rung measured
+ from its start to settle_s after its stop (the tracks coast, both sensors
+ see it); `ended` is what stopped the pivot (Bench.turn)."""
+ results = []
+ for direction, label in ((+1.0, f"+{TURN_DEG:.0f} deg (left)"),
+ (-1.0, f"-{TURN_DEG:.0f} deg (right)")):
+ b.reset()
+ _, yaw_before = b.snapshot()
+ took, ended = b.turn(direction * TURN_RAD_S, sleep=sleep, **turn_kw)
+ sleep(settle_s)
+ gyro, yaw_after = b.snapshot()
+ lidar = wrap_deg(yaw_after - yaw_before) if yaw_before is not None and yaw_after is not None else 0.0
+ gyro_deg = math.degrees(gyro)
+ results.append((label, gyro_deg, lidar, ended))
+ print(f"{label}: gyro({GYRO_AXIS}) = {gyro_deg:+.1f} deg | lidar yaw = {lidar:+.1f} deg "
+ f"| {abs(lidar) / max(took, 1e-3):.0f} deg/s over {took:.1f} s of command, "
+ f"ended on {ENDED.get(ended, ended)}")
+ return results
+
+
+def main() -> int:
+ message, code = prior_check(newest_run_log())
+ print(message)
+ if code is not None:
+ return code
+ b = Bench()
+ time.sleep(1.5)
+ _, yaw0 = b.snapshot()
+ if yaw0 is None:
+ print("KO: no odom on the bus - is the stack up?")
+ return 1
+ if b.last_imu_ts is None:
+ print("KO: no imu on the bus - is the camera up with its IMU (MOSS_IMU)?")
+ return 1
+
+ results = run_rungs(b)
+ message, code = verdict(results)
+ print(message)
+ b.running = False
+ return code
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/run_film.py b/tools/run_film.py
new file mode 100644
index 0000000..c9cdce8
--- /dev/null
+++ b/tools/run_film.py
@@ -0,0 +1,308 @@
+"""Draw the FILM of a run: trajectory + every event, on the map it built.
+
+Reading a log as event counters hides the behaviour: "35 stuck, 22 bumps"
+read three times over did not show a rover walking backwards across a flat in
+20 cm steps into the rear wall; one picture showed it in five seconds.
+
+So: after EVERY run, draw the run BEFORE talking about it. Presumption of
+stupidity - the picture answers "what did the robot do that was dumb?".
+
+The inputs are the run's recording (odom + global_costmap, written by
+MossRecorder) and its dimOS log (main.jsonl: the goal, abandon, escape and
+contact lines). The film is a PNG written next to the recording, and the
+behavioural verdict is printed.
+
+Run on the robot, or anywhere dimOS and matplotlib are installed (dimOS
+decodes the costmap blobs; `.venv/bin/pip install matplotlib` when the venv
+lacks it - the script says so instead of drawing):
+
+ .venv/bin/python tools/run_film.py # newest exploration run, newest recording
+ .venv/bin/python tools/run_film.py --log <dimos log dir>/<run>/main.jsonl \\
+ --db ~/.local/state/moss/recordings/moss.db \\
+ --out /tmp/film.png
+"""
+from __future__ import annotations
+
+import argparse
+import datetime
+import glob
+import json
+import os
+import re
+import sys
+from pathlib import Path
+
+import numpy as np
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+from moss_dimos import robot_profile # noqa: E402
+
+_DIMOS_STATE = os.path.join(os.environ.get("XDG_STATE_HOME") or "~/.local/state", "dimos")
+# The exploration runs' logs: an installed dimOS writes <state>/dimos/logs/<stamp>-moss-dimos-moss-explore/,
+# a dimOS from a git clone writes under the clone and only the run registry names that dir.
+LOG_GLOB = os.path.join(_DIMOS_STATE, "logs", "*-moss-explore", "main.jsonl")
+RUNS_GLOB = os.path.join(_DIMOS_STATE, "runs", "*.json")
+# MossRecorder's recordings: moss.db (the last run) and the rotated moss.<stamp>.db
+DB_NAME_GLOB = "moss*.db"
+
+# one entry per event family: (regex on the log line, marker, colour, legend label)
+EVENTS = {
+ "goal": (re.compile(r"^goal \d+: \(([\d.\-]+), ([\d.\-]+)\)"), "*", "#2e7d32", "goals chosen"),
+ "abandon": (re.compile(r"^Goal abandoned"), "o", "#c62828", "goals abandoned (stuck)"),
+ "escape": (re.compile(r"^Contact escape"), "P", "#ef6c00", "contact escapes (0.20 m)"),
+ "bump": (re.compile(r"BUMP received"), "v", "#111111", "contacts received"),
+ "arrived": (re.compile(r"^Arrived at goal"), "D", "#1b5e20", "goals reached"),
+ # this robot's own contact sources and back-off, so the film says which
+ # contact was felt (the IMU) and which was inferred (the encoder stall guard)
+ "imu": (re.compile(r"^IMU contact:"), "^", "#6a1b9a", "IMU contacts (felt)"),
+ "stall": (re.compile(r"^MOSS base: STALL #"), "x", "#ad1457", "encoder stalls (inferred)"),
+ "cornered": (re.compile(r"^born cornered"), "s", "#8d6e63", "cornered back-offs"),
+}
+
+# A cornered back-off rides the bump reflex (explorer2: "born cornered", then a
+# publish on bump): the planner answers with "BUMP received: front contact" at
+# once and, once it has reversed, "Contact escape" (direction reverse). Those
+# two lines are the back-off's, not a contact's.
+CORNERED_BUMP_S = 1.0 # the planner's BUMP line follows the cornered line within this
+CORNERED_ESCAPE_S = 6.0 # its escape line follows that BUMP within recovering_planner's ESCAPE_TIMEOUT_S (5 s) + 1 s
+
+
+def parse_ts(s: str) -> float:
+ return datetime.datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp()
+
+
+def newest(pattern: str) -> str | None:
+ hits = sorted(glob.glob(os.path.expanduser(pattern)), key=os.path.getmtime)
+ return hits[-1] if hits else None
+
+
+def newest_log(log_glob: str = LOG_GLOB, runs_glob: str = RUNS_GLOB) -> str | None:
+ """The newest exploration run's main.jsonl: the log root's run dirs, plus the
+ log_dir of every registry entry whose blueprint is moss-explore."""
+ hits = [p for p in glob.glob(os.path.expanduser(log_glob)) if os.path.isfile(p)]
+ for entry in glob.glob(os.path.expanduser(runs_glob)):
+ try:
+ with open(entry) as f:
+ doc = json.load(f)
+ except (OSError, ValueError):
+ continue
+ if not isinstance(doc, dict) or not str(doc.get("blueprint", "")).endswith("moss-explore"):
+ continue
+ path = os.path.join(str(doc.get("log_dir") or ""), "main.jsonl")
+ if os.path.isfile(path):
+ hits.append(path)
+ hits = sorted(set(hits), key=os.path.getmtime)
+ return hits[-1] if hits else None
+
+
+def newest_db(env=None) -> str | None:
+ """The newest recording under <MOSS_STATE_DIR>/recordings (moss.db or a rotated moss.<stamp>.db)."""
+ return newest(str(robot_profile.moss_state_dir(env) / "recordings" / DB_NAME_GLOB))
+
+
+def read_log(path: str):
+ """-> (events {family: [(t, xy or None, detail)]}, t0, t1). Goal lines carry
+ their own xy; `detail` is the escape's direction ("reverse" / "forward"),
+ the abandon's trigger (both from the line's own fields), the contact's side
+ ("front" / "rear", from its words), "reversed" for a cornered back-off whose
+ escape was found, else None.
+
+ A cornered back-off's own planner lines are folded into its cornered row:
+ the first front BUMP within CORNERED_BUMP_S of the cornered line is not a
+ contact, and the first reverse escape within CORNERED_ESCAPE_S of that BUMP
+ is not a contact escape (nor an abandoned goal: no goal was out). A BUMP
+ the planner did not act on (acted=False: it only stopped an escape already
+ running) starts no escape of its own."""
+ events: dict[str, list] = {k: [] for k in EVENTS}
+ t0 = t1 = None
+ pending = None # [index of the cornered row, t of its line, t of its BUMP or None]
+ for line in open(path):
+ try:
+ e = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if not isinstance(e, dict):
+ continue
+ ts = e.get("timestamp")
+ if not ts:
+ continue
+ t = parse_ts(ts)
+ t0 = t if t0 is None else t0
+ t1 = t
+ msg = e.get("event", "")
+ for fam, (rx, *_rest) in EVENTS.items():
+ m = rx.search(msg) if fam == "bump" else rx.match(msg)
+ if not m:
+ continue
+ xy = (float(m.group(1)), float(m.group(2))) if fam == "goal" else None
+ detail = (e.get("direction") if fam == "escape" else e.get("trigger") if fam == "abandon"
+ else ("rear" if "rear" in msg else "front") if fam == "bump" else None)
+ if pending is not None:
+ row, t_corner, t_bump = pending
+ if (fam == "bump" and t_bump is None and detail == "front"
+ and 0.0 <= t - t_corner <= CORNERED_BUMP_S):
+ pending = None if e.get("acted") is False else [row, t_corner, t]
+ continue # the back-off's own bump
+ if (fam == "escape" and t_bump is not None and detail != "forward"
+ and 0.0 <= t - t_bump <= CORNERED_ESCAPE_S):
+ events["cornered"][row] = (events["cornered"][row][0], None, "reversed")
+ pending = None
+ continue # the back-off's own reverse
+ if fam == "cornered":
+ pending = [len(events["cornered"]), t, None]
+ events[fam].append((t, xy, detail))
+ return events, t0, t1
+
+
+def read_db(path: str, t0: float, t1: float):
+ """-> (odom [(t,x,y)], occupied cell centres Nx2) for the run's time window."""
+ import sqlite3
+
+ from dimos.msgs.nav_msgs.OccupancyGrid import OccupancyGrid
+
+ db = sqlite3.connect(f"file:{path}?mode=ro", uri=True)
+ odom = db.execute("SELECT ts, pose_x, pose_y FROM odom WHERE ts BETWEEN ? AND ? "
+ "AND pose_x IS NOT NULL ORDER BY ts", (t0 - 5, t1 + 5)).fetchall()
+ occ = np.zeros((0, 2))
+ row = db.execute("SELECT id FROM global_costmap WHERE ts <= ? ORDER BY ts DESC LIMIT 1",
+ (t1 + 5,)).fetchone()
+ if row:
+ blob = db.execute("SELECT data FROM global_costmap_blob WHERE id=?", (row[0],)).fetchone()[0]
+ g = OccupancyGrid.lcm_decode(blob)
+ ys, xs = np.nonzero(np.asarray(g.grid) == 100)
+ res = float(g.resolution)
+ occ = np.stack([g.origin.position.x + (xs + 0.5) * res,
+ g.origin.position.y + (ys + 0.5) * res], axis=1)
+ db.close()
+ return odom, occ
+
+
+def verdict_lines(events: dict, t0: float, t1: float, dist: float, out: str) -> list[str]:
+ """The behavioural verdict, one string per printed line."""
+ mins = (t1 - t0) / 60.0
+ n = {fam: len(rows) for fam, rows in events.items()}
+ # what is left in "escape" are contact escapes (read_log folded the cornered
+ # back-offs' own): a contact behind the rover escapes forward, the others reverse
+ reverse = sum(1 for _t, _xy, direction in events["escape"] if direction != "forward")
+ cornered = sum(1 for _t, _xy, done in events["cornered"] if done == "reversed")
+ triggers: dict[str, int] = {}
+ for _t, _xy, trigger in events["abandon"]:
+ triggers[str(trigger or "?")] = triggers.get(str(trigger or "?"), 0) + 1
+ lines = [f"THE FILM -> {out}",
+ f" {mins:.1f} min, {dist:.1f} m driven",
+ f" goals: {n['goal']} chosen, {n['arrived']} reached, "
+ f"{n['abandon'] + n['escape']} abandoned (stuck + contact: every escape cancels its goal), "
+ f"{n['escape']} contact escapes, {n['bump']} contacts",
+ f" back-offs: {reverse + cornered} ({reverse} after a contact, {cornered} cornered); "
+ f"{n['escape'] - reverse} forward contact escapes; contacts felt by the IMU {n['imu']}, "
+ f"inferred from an encoder stall {n['stall']}"]
+ if n["cornered"] > cornered:
+ lines.append(f" cornered with no back-off logged: {n['cornered'] - cornered} "
+ "(no planner BUMP and reverse escape followed the cornered line)")
+ if triggers:
+ lines.append(" abandon triggers: " + ", ".join(f"{k} {v}" for k, v in sorted(triggers.items())))
+ per_min = (n["abandon"] + n["bump"]) / max(mins, 0.1)
+ lines.append(f" verdict: {per_min:.1f} stuck/contact events per minute"
+ + (" - LOOK AT THE MAP before any conclusion" if per_min > 1 else ""))
+ return lines
+
+
+def draw(out: str, title: str, odom, occ, events: dict) -> None:
+ """The film: the map's obstacles, the trajectory coloured by time (light ->
+ dark), every event where it happened, the start and the end."""
+ import matplotlib
+ matplotlib.use("Agg")
+ import matplotlib.pyplot as plt
+ from matplotlib.lines import Line2D
+
+ ot = np.array([r[0] for r in odom]); ox = np.array([r[1] for r in odom]); oy = np.array([r[2] for r in odom])
+
+ def pos_at(t):
+ i = int(np.argmin(np.abs(ot - t)))
+ return ox[i], oy[i]
+
+ fig, ax = plt.subplots(figsize=(11, 9))
+ fig.patch.set_facecolor("#fafaf8"); ax.set_facecolor("#fafaf8")
+ if len(occ):
+ ax.scatter(occ[:, 0], occ[:, 1], s=3, c="#555555", marker="s", linewidths=0)
+ tnorm = (ot - ot[0]) / max(ot[-1] - ot[0], 1e-6)
+ for i in range(len(ox) - 1):
+ ax.plot(ox[i:i + 2], oy[i:i + 2], color=plt.cm.Blues(0.25 + 0.7 * tnorm[i]), lw=1.8, zorder=2)
+
+ handles = [Line2D([], [], color="#7da7d9", lw=2, label="trajectory (light -> dark = time)")]
+ if len(occ):
+ handles.append(Line2D([], [], marker="s", color="#555555", ls="none", ms=5, label="obstacles (map)"))
+ for fam, (_rx, mark, colour, label) in EVENTS.items():
+ rows = events[fam]
+ if not rows:
+ continue
+ for t, xy, _detail in rows:
+ x, y = xy if xy else pos_at(t)
+ ax.plot(x, y, marker=mark, ms=9, color=colour, mec="#fafaf8", mew=0.6, ls="none", zorder=6)
+ handles.append(Line2D([], [], marker=mark, color=colour, ls="none", ms=9,
+ label=f"{label} ({len(rows)})"))
+
+ ax.plot(ox[0], oy[0], "o", ms=11, color="#1d4f91", mec="white", mew=1.5, zorder=8)
+ ax.annotate("START", (ox[0], oy[0]), textcoords="offset points", xytext=(8, -14),
+ fontsize=9, color="#1d4f91", weight="bold")
+ ax.plot(ox[-1], oy[-1], "s", ms=11, color="#0d2b52", mec="white", mew=1.5, zorder=8)
+ ax.annotate("END", (ox[-1], oy[-1]), textcoords="offset points", xytext=(8, 8),
+ fontsize=9, color="#0d2b52", weight="bold")
+ ax.set_title(title, fontsize=11, color="#222222")
+ ax.legend(handles=handles, loc="upper left", fontsize=9, framealpha=0.95)
+ ax.set_xlabel("x (m)"); ax.set_ylabel("y (m)")
+ ax.set_aspect("equal"); ax.grid(True, color="#e0e0dc", lw=0.5)
+ for sp in ax.spines.values():
+ sp.set_color("#cccccc")
+ plt.tight_layout()
+ plt.savefig(out, dpi=130, facecolor="#fafaf8")
+ plt.close(fig)
+
+
+def film(log: str, db: str, out: str | None = None) -> tuple[int, list[str]]:
+ """(exit code, printed lines) for one run: the film written to `out`
+ (default: <run dir name>.film.png next to the recording, one per run:
+ the recording itself is renamed when the next run rotates it)."""
+ try:
+ import matplotlib # noqa: F401 the film is drawn with it
+ except ImportError:
+ return 1, ["matplotlib is missing, nothing drawn: .venv/bin/pip install matplotlib"]
+ run = os.path.basename(os.path.dirname(os.path.abspath(log)))
+ out = out or os.path.join(os.path.dirname(os.path.abspath(db)), f"{run}.film.png")
+ events, t0, t1 = read_log(log)
+ if t0 is None:
+ return 1, [f"no dated line in {log} - not a dimOS run log?"]
+ odom, occ = read_db(db, t0, t1)
+ if len(odom) < 2:
+ return 1, [f"no odom rows in {db} for this run's window - wrong db?"]
+ ox = np.array([r[1] for r in odom]); oy = np.array([r[2] for r in odom])
+ dist = float(np.hypot(np.diff(ox), np.diff(oy)).sum())
+ n = {fam: len(rows) for fam, rows in events.items()}
+ title = (f"{run} - {(t1 - t0) / 60.0:.0f} min, "
+ f"{dist:.1f} m - {n['goal']} goals, {n['arrived']} reached, {n['abandon']} stuck, "
+ f"{n['bump']} contacts")
+ draw(out, title, odom, occ, events)
+ return 0, verdict_lines(events, t0, t1, dist, out)
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ ap.add_argument("--log", default=None, help="main.jsonl of the run (default: the newest exploration run)")
+ ap.add_argument("--db", default=None, help="recording db (default: the newest moss*.db in the recordings)")
+ ap.add_argument("--out", default=None, help="output PNG (default: <run dir name>.film.png next to the db)")
+ args = ap.parse_args()
+
+ log = args.log or newest_log()
+ db = args.db or newest_db()
+ if not log or not db:
+ print(f"missing input: log={log} db={db}")
+ return 1
+ code, lines = film(log, db, args.out)
+ for line in lines:
+ print(line)
+ return code
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/speed_guard.py b/tools/speed_guard.py
new file mode 100755
index 0000000..38d0bdf
--- /dev/null
+++ b/tools/speed_guard.py
@@ -0,0 +1,291 @@
+#!/usr/bin/env python3
+"""Speed watchdog: tails the run's dimOS log, computes the body's speed from
+the lidar odometry lines, and stops the run when the body moves faster than
+the profile's ceiling (robot_profile max_speed_mps, 0.45 m/s, overridden by
+MOSS_MAX_SPEED_MPS). It must be running whenever the rover explores
+unattended: tools/arm_speed_guard.sh arms it for one run.
+
+The ceiling is the planner's cruise plus a margin, never below it: a ceiling
+at or under the speed the stack itself commands would stop every normal run.
+Cruise = dimOS LocalPlanner._speed (PLANNER_SPEED_MPS, 0.55 m/s) x the
+launcher's speed scale (MOSS_NERF_SPEED, 0.7 by default in tools/moss-fly.sh)
+= 0.385 m/s. The watchdog refuses to start (exit 1, before its pid file
+exists, so the arm script reports it did not come up) when the ceiling is not
+above that cruise.
+
+Speed is measured between the TIMESTAMPS THE LOG CARRIES, never between the
+moments the lines reach this process: LidarOdometry rate-limits `lidar odom #N`
+(log_every_s = 2.0) and the interval jitters around it, so a wall-clock window
+(0.02 < dt < 2.0) throws away most samples - 183 of the 238 intervals of a
+recorded field log - and can never strike in time. One interval above the
+ceiling is a kill; no cadence is assumed anywhere.
+
+The kill is two steps. First the exploration stop through tools/explore_ctl.py,
+on the run's own bus. Then the stack itself goes down (SPEED_GUARD_STACK_STOP,
+default `tools/moss-fly.sh stop`): the motor board is open loop (PWM percent,
+no speed loop), so a body faster than the ceiling is not something a stopped
+explorer is sure to end; with the stack down the firmware deadman stops the
+tracks 300 ms after the last command.
+
+It guards ONE run: the run dir is frozen at startup (SPEED_GUARD_RUN_DIR, which the
+arm script passes, else the newest run dir) and the pid written to PID_FILE
+(the launcher kills THAT pid, not whatever `pgrep speed_guard` finds). A
+watchdog whose run is over stands down by itself - either a newer run dir
+appeared, or the log it tails stopped growing for IDLE_S. Without this, an
+orphan of the previous run keeps tailing a dead log while everything that
+reads its mere presence as 'armed' lets the live run explore unguarded.
+
+Where dimOS logs a run: an installed dimOS under <state>/dimos/logs/<run>,
+a dimOS from a git clone under the clone; the run registry
+(<state>/dimos/runs/*.json) names the log_dir in both cases, so both are read.
+"""
+import atexit, glob, json, math, os, re, shlex, signal, subprocess, sys, threading, time
+from datetime import datetime
+
+TOOLS = os.path.dirname(os.path.abspath(__file__))
+ROOT = os.path.dirname(TOOLS)
+sys.path.insert(0, TOOLS)
+sys.path.insert(0, ROOT)
+import explore_ctl # noqa: E402 the stop rides the run's bus, same module the launcher uses
+from moss_dimos import robot_profile # noqa: E402
+
+
+def limit_ms(env=None) -> float:
+ """The ceiling in m/s: the profile's max_speed_mps (MOSS_MAX_SPEED_MPS overrides it)."""
+ return robot_profile.current(env).max_speed_mps
+
+
+PLANNER_SPEED_MPS = 0.55 # dimOS LocalPlanner._speed (replanning_a_star/local_planner.py): the follower's cruise
+NERF_SPEED_DEFAULT = 0.7 # tools/moss-fly.sh: NERF_SPEED="${MOSS_NERF_SPEED:-0.7}", passed as --nerf-speed
+
+
+def cruise_mps(env=None) -> float:
+ """The speed the stack commands when the follower is aligned: dimOS's
+ PLANNER_SPEED_MPS times the run's speed scale (MOSS_NERF_SPEED, the
+ launcher's default when unset; dimOS applies it only below 1)."""
+ env = os.environ if env is None else env
+ try:
+ nerf = float(str(env.get("MOSS_NERF_SPEED", "")).strip() or NERF_SPEED_DEFAULT)
+ except ValueError:
+ nerf = NERF_SPEED_DEFAULT
+ return PLANNER_SPEED_MPS * (nerf if 0.0 < nerf < 1.0 else 1.0)
+
+
+def ceiling_refusal(limit: float, cruise: float):
+ """Why this ceiling cannot guard a run (it would stop every normal one),
+ or None when it sits above the commanded cruise."""
+ if limit > cruise:
+ return None
+ return (f"ceiling {limit:g} m/s is not above the planner's cruise {cruise:.3f} m/s "
+ f"({PLANNER_SPEED_MPS:g} m/s x MOSS_NERF_SPEED): every normal run would be stopped - "
+ f"raise MOSS_MAX_SPEED_MPS above {cruise:.3f} or lower MOSS_NERF_SPEED; not armed")
+
+
+LIMIT_MS = limit_ms() # hard envelope, read once per watchdog: beyond = runaway
+DIMOS_STATE = os.path.join(os.environ.get("XDG_STATE_HOME") or "~/.local/state", "dimos")
+LOG_GLOB = os.path.join(DIMOS_STATE, "logs", "*") # an installed dimOS: one dir per run
+RUNS_GLOB = os.path.join(DIMOS_STATE, "runs", "*.json") # the run registry: its log_dir, wherever dimOS logs
+LAUNCH_LOG = "/tmp/moss_fly_launch.log" # tools/moss-fly.sh's launch output, tailed too when present
+IDLE_S = float(os.environ.get("SPEED_GUARD_IDLE_S", "30")) # log silent this long -> the run is over
+POLL_S = float(os.environ.get("SPEED_GUARD_POLL_S", "2")) # how often the stand-down is re-checked
+PID_FILE = os.environ.get("SPEED_GUARD_PID_FILE", "/tmp/moss_speed_guard.pid")
+STACK_STOP = shlex.split(os.environ.get("SPEED_GUARD_STACK_STOP", "tools/moss-fly.sh stop")) # run from the checkout root
+STACK_STOP_TIMEOUT_S = 60.0
+ODOM_RE = re.compile(r"lidar odom #(\d+): x=([+-][\d.]+) y=([+-][\d.]+)")
+TS_RE = re.compile(r'"timestamp":\s*"([^"]+)"')
+
+
+def run_dirs(glob_pat: str = LOG_GLOB, runs_glob: str = RUNS_GLOB) -> list:
+ """The dimos run dirs, oldest mtime first: every dir under the log root,
+ plus every log_dir the run registry names (a dimOS from a git clone logs
+ under the clone, and only its registry entry says where)."""
+ dirs = {os.path.realpath(d) for d in glob.glob(os.path.expanduser(glob_pat)) if os.path.isdir(d)}
+ for entry in glob.glob(os.path.expanduser(runs_glob)):
+ try:
+ with open(entry) as f:
+ log_dir = json.load(f).get("log_dir")
+ except (OSError, ValueError, AttributeError):
+ continue # half-written or foreign file
+ if isinstance(log_dir, str) and os.path.isdir(log_dir):
+ dirs.add(os.path.realpath(log_dir))
+ return sorted(dirs, key=_mtime)
+
+
+def _mtime(path: str) -> float:
+ """mtime, or -1 for a path that vanished since it was listed."""
+ try:
+ return os.path.getmtime(path)
+ except OSError:
+ return -1.0
+
+
+def newest_run(glob_pat: str = LOG_GLOB, runs_glob: str = RUNS_GLOB) -> str:
+ runs = run_dirs(glob_pat, runs_glob)
+ if not runs:
+ sys.exit("no dimos run logs found")
+ return runs[-1]
+
+
+def log_of(run_dir: str) -> str:
+ return os.path.join(run_dir, "main.jsonl")
+
+
+def write_pid_file(path: str = PID_FILE) -> None:
+ """Stamp our pid so the launcher can kill THIS watchdog by pid."""
+ with open(path, "w") as f:
+ f.write(f"{os.getpid()}\n")
+ atexit.register(clear_pid_file, path)
+
+
+def clear_pid_file(path: str = PID_FILE) -> None:
+ """Drop the pid file, but only while it still names us: a newer watchdog
+ that overwrote it must keep its own."""
+ try:
+ if int(open(path).read().strip()) == os.getpid():
+ os.remove(path)
+ except (OSError, ValueError):
+ pass
+
+
+class RunWatch:
+ """Stand-down decision for the ONE run this watchdog guards: a newer run dir
+ means the live run has its own watchdog and we are its orphan; a log that
+ stopped growing for idle_s means the run we guard is over (or dead)."""
+
+ def __init__(self, run_dir: str, idle_s: float = IDLE_S, glob_pat: str = LOG_GLOB,
+ clock=time.time, runs_glob: str = RUNS_GLOB):
+ self.run_dir = os.path.realpath(run_dir)
+ self.log_path = log_of(run_dir)
+ self.idle_s = idle_s
+ self.glob_pat = glob_pat
+ self.runs_glob = runs_glob
+ self.clock = clock
+ self.size = self._size()
+ self.last_growth = clock()
+
+ def _size(self) -> int:
+ try:
+ return os.path.getsize(self.log_path)
+ except OSError:
+ return -1 # no log to grow: the idle limit will retire us
+
+ def reason(self):
+ """Why this watchdog must stand down, or None while it still guards the
+ live run."""
+ # our own dir always competes: a run dir the listing misses (a registry
+ # entry already swept) must not make an OLDER dir look like the newest
+ runs = sorted(set(run_dirs(self.glob_pat, self.runs_glob)) | {self.run_dir}, key=_mtime)
+ if runs[-1] != self.run_dir:
+ return (f"{os.path.basename(runs[-1])} is now the newest run, this process only tails "
+ f"{os.path.basename(self.run_dir)} - the live run is guarded by its own watchdog")
+ size, now = self._size(), self.clock()
+ if size != self.size:
+ self.size, self.last_growth = size, now
+ return None
+ idle = now - self.last_growth
+ if idle >= self.idle_s:
+ return (f"{self.log_path} has not grown for {idle:.0f} s (limit {self.idle_s:g} s) "
+ "- the run it guards is over")
+ return None
+
+
+def supervise(watch: "RunWatch", tail, poll_s: float = POLL_S) -> None:
+ """Kill the tail - and with it the main loop - as soon as this watchdog is
+ no longer the guard of a live run."""
+ while tail.poll() is None:
+ why = watch.reason()
+ if why:
+ print(f"[speed guard] standing down: {why}", flush=True)
+ tail.terminate()
+ return
+ time.sleep(poll_s)
+
+
+def parse_odom(line: str):
+ """(t seconds, x metres, y metres) from an odom log line, or None when the
+ line carries no odom sample or no timestamp to date it with."""
+ m = ODOM_RE.search(line)
+ ts = TS_RE.search(line)
+ if not m or not ts:
+ return None
+ try:
+ t = datetime.fromisoformat(ts.group(1).replace("Z", "+00:00")).timestamp()
+ except ValueError:
+ return None
+ return t, float(m.group(2)), float(m.group(3))
+
+
+class SpeedGuard:
+ """Body speed over consecutive odom lines, dated by the log itself."""
+
+ def __init__(self, limit: float = None):
+ self.limit = LIMIT_MS if limit is None else limit
+ self.prev = None # (t, x, y) of the last dated odom line
+
+ def feed(self, line: str):
+ """Speed in m/s over the interval this line closes, or None when the
+ line closes no interval (not odom, undated, or not after the previous)."""
+ sample = parse_odom(line)
+ if sample is None:
+ return None
+ t, x, y = sample
+ prev, self.prev = self.prev, sample
+ if prev is None or t <= prev[0]:
+ return None
+ return math.hypot(x - prev[1], y - prev[2]) / (t - prev[0])
+
+ def breach(self, line: str):
+ """That speed when it exceeds the envelope, else None."""
+ v = self.feed(line)
+ return v if v is not None and v > self.limit else None
+
+
+def stop_all() -> None:
+ """Exploration stop on the run's bus, then the stack down. Neither failure
+ takes the watchdog down with it."""
+ try:
+ print(f"[speed guard] STOP EXPLORE published on {explore_ctl.publish('stop')}", flush=True)
+ except Exception as e: # a sick bus must not take the watchdog down with it
+ print(f"[speed guard] STOP EXPLORE FAILED: {e}", flush=True)
+ try:
+ r = subprocess.run(STACK_STOP, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
+ text=True, timeout=STACK_STOP_TIMEOUT_S)
+ last = (r.stdout or "").strip().splitlines()[-1:] or ["(no output)"]
+ print(f"[speed guard] STACK STOP ({' '.join(STACK_STOP)}) exit {r.returncode}: {last[0]}", flush=True)
+ except Exception as e: # a launcher that hangs or is missing must not either
+ print(f"[speed guard] STACK STOP FAILED ({' '.join(STACK_STOP)}): {e}", flush=True)
+
+
+def main() -> None:
+ run_dir = os.environ.get("SPEED_GUARD_RUN_DIR", "").strip() or newest_run() # frozen: this watchdog guards THIS run
+ if not os.path.isdir(run_dir):
+ sys.exit(f"SPEED_GUARD_RUN_DIR={run_dir} is not a directory")
+ cruise = cruise_mps()
+ why = ceiling_refusal(LIMIT_MS, cruise)
+ if why:
+ sys.exit(f"[speed guard] {why}") # before the pid file: the arm script sees no watchdog come up
+ path = log_of(run_dir)
+ write_pid_file()
+ watch = RunWatch(run_dir)
+ print(f"[speed guard] watching {path} (limit {LIMIT_MS} m/s, cruise {cruise:.3f} m/s commanded, "
+ f"idle limit {IDLE_S:g} s, pid {os.getpid()} -> {PID_FILE})", flush=True)
+ guard = SpeedGuard()
+ paths = [path] + ([LAUNCH_LOG] if os.path.exists(LAUNCH_LOG) else [])
+ signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) # killed by pid: leave through atexit, pid file and all
+ with subprocess.Popen(["tail", "-Fn0", *paths], stdout=subprocess.PIPE, text=True) as tail:
+ threading.Thread(target=supervise, args=(watch, tail), daemon=True).start()
+ try:
+ for line in tail.stdout:
+ if "BUMP" in line or "bump" in line:
+ print(f"[speed guard] {line.rstrip()}", flush=True)
+ v = guard.breach(line)
+ if v is not None:
+ print(f"[speed guard] {v:.2f} m/s over the {LIMIT_MS} m/s envelope", flush=True)
+ stop_all()
+ finally:
+ tail.terminate() # or the context manager waits forever on a tail nobody killed
+ print(f"[speed guard] stopped watching {path}", flush=True)
+
+
+if __name__ == "__main__":
+ main()