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

explorer: distance exponent (2), goal path cap (3 m, safe-first), exploration radius around the start (launcher: 4 m = one room); costmap: camera layer carved only inside the camera's view (tables keep their walls, passers-by fade), same-spot hold below the wall level, MOSS_HIT_CAP / MOSS_FREE_FLOOR / MOSS_RAY_MAX_M; cockpit: pose at the scan's rate, STALLED badge held 4 s and a stalls row; benches and docs follow

metrox6c1365a9a443
diff --git a/benches/bench_costmap2d_cold.py b/benches/bench_costmap2d_cold.py
index b799202..3c6cba3 100644
--- a/benches/bench_costmap2d_cold.py
+++ b/benches/bench_costmap2d_cold.py
@@ -15,7 +15,10 @@ Known input -> known output, in metres and cells:
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
(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
+ 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 ->
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" ->
@@ -28,6 +31,27 @@ Known input -> known output, in metres and cells:
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
+ 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)
Needs dimOS (the messages are real).
@@ -35,6 +59,8 @@ Run: PYTHONPATH=. .venv/bin/python benches/bench_costmap2d_cold.py
"""
import asyncio
+import copy
+import importlib
import importlib.util
import math
import os
@@ -55,7 +81,7 @@ from dimos_lcm.std_msgs import Bool # noqa: E402
from moss_dimos import costmap2d as cmod # noqa: E402
from moss_dimos.costmap2d import ( # noqa: E402
- FREE_FLOOR, HIT_CAP, MISSION_START_M, OCCUPIED_AT, PUBLISH_EVERY, RESOLUTION_M,
+ FREE_FLOOR, HIT_CAP, MISSION_START_M, OCCUPIED_AT, PUBLISH_EVERY, RAY_EVERY, RESOLUTION_M,
MossCostMap, ScoredGrid, lidar_returns,
)
from moss_dimos.robot_profile import MOSS # noqa: E402
@@ -272,10 +298,15 @@ def test_the_lidar_tag_is_one_exact_height() -> None:
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 survives (camera layer, never carved by a lidar ray)
+ # revolution, and the shoe the camera still sees survives them
for _ in range(6):
- asyncio.run(m2.handle_lidar(_cloud(_lidar_cloud(ROOM))))
- assert m2._grid.value_at(1.5, -0.4) == 100, "lidar rays through the shoe's cell do not erase it"
+ 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
+ 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]])
for _ in range(2):
@@ -283,7 +314,8 @@ def test_the_lidar_tag_is_one_exact_height() -> None:
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
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")
+ "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")
def test_the_map_writes_only_during_the_mission() -> None:
@@ -464,10 +496,367 @@ 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))
+ g.lidar_revolution(hits, (0.01 * i, 0.0), yaw=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) = {ms:.0f} ms")
+ print(f" one revolution (400 rays, 0.5-12 m, carving every other one, camera layer in view) = {ms:.0f} ms")
+
+
+
+# --- the camera layer forgets: lidar rays carve it, the camera holds what it sees ---
+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
+
+
+def _camera_score(g: ScoredGrid, xy: np.ndarray) -> int:
+ gx, gy = g.cell(xy[:, 0], xy[:, 1])
+ return int(g.camera[gy[0], gx[0]])
+
+
+def _in_view(xy: np.ndarray, rover_xy, yaw: float, margin_deg: float = 1.0) -> np.ndarray:
+ """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."""
+ 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)
+ off = (off + 180.0) % 360.0 - 180.0
+ 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)
+
+
+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."""
+ g = fresh()
+ for k in range(viewpoints - 1, -1, -1):
+ g.camera_hits(SHOE, (0.0, SPOT_B[1] + 0.15 * k))
+ 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."""
+ traces = {}
+ for spare in (True, False):
+ g = fresh()
+ trace = []
+ for _ in range(20):
+ _revolution(g, SPOT_B, SHOE, spare=spare)
+ 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
+ # 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)
+ assert _camera_score(g, SHOE) == FREE_FLOOR, _camera_score(g, SHOE)
+ floor_trace = []
+ for _ in range(5): # a phantom seen 5 frames from one parked spot
+ g.camera_hits(SHOE, SPOT_B)
+ 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
+ while g.value_at(*SHOE[0]) != 100:
+ g.camera_hits(SHOE, (0.0, SPOT_B[1] + 0.15 * 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" 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)."""
+ 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)
+ 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"
+ 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"
+ 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)
+ while _camera_score(g, SHOE) > 0:
+ _revolution(g, SPOT_B)
+ for _ in range(10):
+ _revolution(g, SPOT_B, SHOE)
+ 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")
+
+
+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}")
+
+
+def _reload(**env):
+ """costmap2d re-imported with these knobs (and none of the other two)."""
+ for var in ("MOSS_HIT_CAP", "MOSS_FREE_FLOOR", "MOSS_RAY_MAX_M"):
+ os.environ.pop(var, None)
+ os.environ.update(env)
+ return importlib.reload(cmod)
+
+
+def test_the_knobs_are_read_at_import() -> None:
+ """MOSS_HIT_CAP, MOSS_FREE_FLOOR and MOSS_RAY_MAX_M, known input -> known
+ output in revolutions and hits."""
+ try:
+ unlearn = {}
+ for cap in ("10", "4"):
+ mod = _reload(MOSS_HIT_CAP=cap)
+ assert mod.HIT_CAP == int(cap), mod.HIT_CAP
+ for viewpoints in (6, 20):
+ g = mod.ScoredGrid(span_m=6.0)
+ for i in range(viewpoints):
+ g.lidar_revolution(LEG, (0.0, 0.15 * i))
+ assert g.value_at(1.0, 0.0) == 100
+ n = 0
+ while g.value_at(1.0, 0.0) == 100:
+ g.lidar_revolution(np.array([[3.0, 0.0]]), (0.0, 0.0)); n += 1
+ assert n <= 40
+ unlearn[(cap, viewpoints)] = n
+ assert unlearn[("4", 6)] < unlearn[("10", 6)] and unlearn[("4", 20)] < unlearn[("10", 20)], unlearn
+
+ hits_to_wall = {}
+ for floor in ("-3", "-1"):
+ mod = _reload(MOSS_FREE_FLOOR=floor)
+ assert mod.FREE_FLOOR == int(floor), mod.FREE_FLOOR
+ g = mod.ScoredGrid(span_m=6.0)
+ for _ in range(20): # long-seen floor at 1.0 m
+ g.lidar_revolution(np.array([[3.0, 0.0]]), (0.0, 0.0))
+ gx, gy = g.cell(np.array([1.0]), np.array([0.0]))
+ assert g.lidar[gy[0], gx[0]] == int(floor), g.lidar[gy[0], gx[0]]
+ k = 0
+ while g.value_at(1.0, 0.0) != 100: # somebody steps there; the rover drives on
+ k += 1
+ g.lidar_revolution(LEG, (0.0, 0.15 * k))
+ assert k <= 20
+ hits_to_wall[floor] = k
+ assert hits_to_wall["-1"] < hits_to_wall["-3"], hits_to_wall
+
+ far_leg = {}
+ for ray_max in (None, "6"):
+ mod = _reload(**({"MOSS_RAY_MAX_M": ray_max} if ray_max else {}))
+ assert mod.RAY_MAX_M == (float(ray_max) if ray_max else 4.0), mod.RAY_MAX_M
+ g = mod.ScoredGrid(span_m=16.0)
+ leg = np.array([[4.5, 0.0]]) # somebody standing 4.5 m away
+ g.lidar_revolution(leg, (0.0, 0.0)); g.lidar_revolution(leg, (0.0, 0.15))
+ assert g.value_at(4.5, 0.0) == 100
+ n = 0
+ while g.value_at(4.5, 0.0) == 100 and n < 20: # gone: the rays now reach the wall at 6 m
+ g.lidar_revolution(np.array([[6.0, 0.0]]), (0.0, 0.0)); n += 1
+ far_leg[ray_max or "4"] = n if g.value_at(4.5, 0.0) != 100 else None
+ assert far_leg["4"] is None and far_leg["6"] is not None and far_leg["6"] <= 2, far_leg
+
+ odd = {}
+ for var, raw in (("MOSS_HIT_CAP", "ten"), ("MOSS_HIT_CAP", "500"), ("MOSS_HIT_CAP", "1"),
+ ("MOSS_HIT_CAP", "4.4"), ("MOSS_FREE_FLOOR", "2"), ("MOSS_RAY_MAX_M", "-1")):
+ mod = _reload(**{var: raw})
+ odd[(var, raw)] = {"MOSS_HIT_CAP": mod.HIT_CAP, "MOSS_FREE_FLOOR": mod.FREE_FLOOR,
+ "MOSS_RAY_MAX_M": mod.RAY_MAX_M}[var]
+ assert list(odd.values()) == [10, 127, OCCUPIED_AT, 4, 0, 0.0], odd
+ finally:
+ mod = _reload()
+ assert (mod.HIT_CAP, mod.FREE_FLOOR, mod.RAY_MAX_M) == (10, -3, 4.0), "defaults restored"
+ print(f" leg from 6 viewpoints: HIT_CAP 10 -> a wall for {unlearn[('10', 6)]} clear revolutions, "
+ f"MOSS_HIT_CAP=4 -> {unlearn[('4', 6)]}; from 20 viewpoints: {unlearn[('10', 20)]} vs {unlearn[('4', 20)]}")
+ print(f" long-seen floor becomes a wall after {hits_to_wall['-3']} viewpoints at FREE_FLOOR -3, "
+ f"{hits_to_wall['-1']} at MOSS_FREE_FLOOR=-1")
+ print(f" a leg at 4.5 m: never carved with rays to 4 m (20 revolutions), freed after {far_leg['6']} with "
+ f"MOSS_RAY_MAX_M=6; MOSS_HIT_CAP 'ten' / 500 / 1 / 4.4 -> {odd[('MOSS_HIT_CAP', 'ten')]} / "
+ f"{odd[('MOSS_HIT_CAP', '500')]} / {odd[('MOSS_HIT_CAP', '1')]} / {odd[('MOSS_HIT_CAP', '4.4')]}, "
+ 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 ---
+_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:
+ gx, gy = g.cell(xy[:, 0], xy[:, 1])
+ return g.camera[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."""
+ 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)
+ return len(seen)
+
+
+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.
+
+ 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."""
+ g = fresh()
+ 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)
+ 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"
+ 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)
+ 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
+ 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
+
+ # 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]])
+ assert _in_view(legs, (0.0, 0.0), 0.0, margin_deg=-5.0).all() and not _in_view(legs, (0.0, 0.0), math.pi).any()
+ kept = 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))
+ 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
+ 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
+ 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
+ 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):
+ 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_odom(_odom(0.0, 0.15, yaw)))
+ 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
+ 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)
+ gx, gy = g.cell(SHOE[:, 0], SHOE[:, 1])
+ assert g.camera_wall[gy[0], gx[0]], "two viewpoints flag the camera wall"
+ 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
+ right_away = []
+ for _ in range(10): # the last viewpoint, 10 frames
+ g.camera_hits(SHOE, SPOT_B)
+ 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
+ k = 0
+ while _camera_score(g, SHOE) < OCCUPIED_AT - 1:
+ k += 1
+ g.camera_hits(SHOE, (0.0, SPOT_B[1] - 0.15 * k))
+ assert k <= 10
+ 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)
+ 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)")
TESTS = (test_leg_needs_two_viewpoints_and_ray_is_free, test_ramp_hit_from_one_spot_never_becomes_a_wall,
@@ -475,7 +864,10 @@ TESTS = (test_leg_needs_two_viewpoints_and_ray_is_free, test_ramp_hit_from_one_s
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,
test_explore_order_opens_the_map_before_any_motion, test_what_goes_out_on_global_costmap,
- test_the_mission_signals_cross_the_process_boundary, test_revolution_cost)
+ 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)
if __name__ == "__main__":
OK = KO = 0
diff --git a/benches/bench_explorer2_cold.py b/benches/bench_explorer2_cold.py
index 35a66c3..490c9e8 100644
--- a/benches/bench_explorer2_cold.py
+++ b/benches/bench_explorer2_cold.py
@@ -13,14 +13,25 @@ Every check is a known input giving a known output in physical units
F. the end of a run - None exactly when there is nothing left
H. revisits - fresh ground beats ground already worked
I. shut in - pinched is not finished
+ K. how far - the distance exponent (a big frontier across
+ the room does not beat a small one beside
+ the rover), the goal cap (a farther frontier
+ waits while a safe one lies within it, never
+ behind a probe, and never ends a run) and the
+ exploration radius around the first pose
+ (nothing left inside it is the end of a run)
G. purity - the costmap, the pose and the rest of the
state come back untouched, and the function
is deterministic
- J. the loop around it - which goal a bare goal_reached is credited to
+ J. the loop around it - which goal a bare goal_reached is credited to,
+ and the one line that states exp, cap, radius
+ L. the blueprint's knobs - MOSS_EXPLORE_DISTANCE_EXP, MOSS_GOAL_MAX_M,
+ MOSS_EXPLORE_RADIUS_M -> the Explorer2 config
-No robot and no LCM. A to I need numpy and scipy only (the geometry is built on
-the default Tuning, a 0.50 m wide reference body). Only J touches the module
-class, and it skips itself where dimOS is not installed.
+No robot and no LCM. A to I, K and G need numpy and scipy only (the geometry is
+built on the default Tuning, a 0.50 m wide reference body). Only J and L touch
+the module class and the blueprint, and they skip themselves where dimOS is
+not installed.
Run from the repository root: python benches/bench_explorer2_cold.py
"""
@@ -556,6 +567,201 @@ for label, grid_in in (("one door", door(room(), "east", 70, 24)),
t is None and calls < 60, f"{calls} calls, last {t}")
+# ===========================================================================
+print("K. how far: the distance exponent, the goal cap, the exploration radius")
+
+# A hall, 6 x 2 m, walled on three sides. Its east end opens onto 1 m of
+# unknown (the far frontier: 38 cells, the whole width of the hall). Halfway
+# along the north wall, a 0.50 m door into a 1.0 x 0.6 m closet (the near
+# frontier: 8 cells). Heading is taken out of the picture (forward_bonus 0) so
+# every score below is exactly gain / (1 + path) ** exponent.
+#
+# With `bay`, a 1.0 m opening in the south wall (x 2.0 .. 3.0 m) gives onto a
+# 0.10 m strip of unknown, then 0.25 m of seen floor, then a 0.70 m unknown
+# pocket closed by a wall. The pocket's frontier is looked at from that seen
+# floor, which the rover can only reach across the unknown strip: a PROBE.
+def hall(closet=True, bay=False):
+ g = np.full((120, 220), UNKNOWN, dtype=np.int8)
+ g[40:80, 20:140] = FREE # x 1.0 .. 7.0 m, y 2.0 .. 4.0 m
+ g[39:81, 19] = OCCUPIED # west wall
+ g[39, 19:161] = OCCUPIED # south wall, on past the open end
+ g[80, 19:161] = OCCUPIED # north wall, likewise
+ g[39:81, 160] = OCCUPIED # the far pocket's back wall, 1 m out
+ if closet:
+ g[80:93, 57] = OCCUPIED # closet sides, x 2.85 and 3.90 m
+ g[80:93, 78] = OCCUPIED
+ g[93, 57:79] = OCCUPIED # closet back, 0.6 m behind the door
+ g[80, 63:73] = UNKNOWN # the 0.50 m door, x 3.15 .. 3.65 m
+ if bay:
+ g[38:40, 40:60] = UNKNOWN # the opening and the unknown strip, y 1.90 .. 2.00 m
+ g[33:38, 40:60] = FREE # seen floor beyond it, y 1.65 .. 1.90 m
+ g[18:39, 39] = OCCUPIED # bay sides, x 1.95 and 3.00 m
+ g[18:39, 60] = OCCUPIED
+ g[18, 39:61] = OCCUPIED # its back wall, y 0.90 m
+ return g
+
+
+def flat(**kw):
+ return Tuning(forward_bonus=0.0, **kw)
+
+
+hall_cm = Grid(hall())
+start = pose(w_of(50), w_of(60), 0.0) # (2.53, 3.03): 1.2 m from the closet's
+ # viewpoint, 4.5 m from the far end's
+
+linear = next_target(hall_cm, start, ExploreState(), now=100.0,
+ tuning=flat(distance_exponent=1.0, max_goal_path_m=0.0))
+squared = next_target(hall_cm, start, ExploreState(), now=100.0,
+ tuning=flat(distance_exponent=2.0, max_goal_path_m=0.0))
+assert linear is not None and squared is not None
+far_end = (linear.info_gain, linear.path_cost_m)
+closet = (squared.info_gain, squared.path_cost_m)
+for exp in (1.0, 2.0):
+ print(f" exponent {exp:g}: far end gain {far_end[0]:.4f} / (1 + {far_end[1]:.2f} m)^{exp:g} "
+ f"= {far_end[0] / (1 + far_end[1]) ** exp:.5f}, "
+ f"closet gain {closet[0]:.4f} / (1 + {closet[1]:.2f} m)^{exp:g} "
+ f"= {closet[0] / (1 + closet[1]) ** exp:.5f}")
+check("(setup) two clusters, both on seen floor, the far one the bigger",
+ linear.n_clusters == 2 and not linear.probe and not squared.probe
+ and linear.info_cells > squared.info_cells and far_end[0] > closet[0],
+ f"{linear.info_cells} vs {squared.info_cells} cells, gain {far_end[0]:.4f} vs {closet[0]:.4f}")
+check("(setup) the far end is 4.5 m of path away, the closet 1.2 m",
+ abs(far_end[1] - 4.5) < 0.1 and abs(closet[1] - 1.2) < 0.1,
+ f"{far_end[1]:.2f} m, {closet[1]:.2f} m")
+check("exponent 1 (PR #2830's shape): the big far end wins",
+ linear.position.x > w_of(130), f"x = {linear.position.x:.2f} m")
+check("exponent 2: the small closet beside the rover wins",
+ w_of(57) < squared.position.x < w_of(78) and squared.position.y > w_of(70),
+ f"({squared.position.x:.2f}, {squared.position.y:.2f})")
+check("the score handed back is gain / (1 + path) ** exponent, exactly",
+ abs(linear.score - far_end[0] / (1 + far_end[1])) < 1e-12
+ and abs(squared.score - closet[0] / (1 + closet[1]) ** 2) < 1e-12,
+ f"{linear.score:.6f}, {squared.score:.6f}")
+default = next_target(hall_cm, start, ExploreState(), now=100.0)
+check("the defaults (exponent 2, cap 3 m) send the rover to the closet",
+ default is not None and abs(default.path_cost_m - closet[1]) < 1e-9
+ and DEFAULT_TUNING.distance_exponent == 2.0 and DEFAULT_TUNING.max_goal_path_m == 3.0,
+ f"{default.path_cost_m:.2f} m" if default else "None")
+
+capped = next_target(hall_cm, start, ExploreState(), now=100.0,
+ tuning=flat(distance_exponent=1.0, max_goal_path_m=3.0))
+check("cap 3 m, exponent 1: the 4.5 m far end is not a candidate, the closet goes out",
+ capped is not None and abs(capped.path_cost_m - closet[1]) < 1e-9
+ and capped.n_beyond_cap == 1 and capped.beyond_cap is False,
+ f"{capped.path_cost_m:.2f} m, {capped.n_beyond_cap} beyond" if capped else "None")
+roomy = next_target(hall_cm, start, ExploreState(), now=100.0,
+ tuning=flat(distance_exponent=1.0, max_goal_path_m=5.0))
+check("cap 5 m: the 4.5 m far end is a candidate again and wins",
+ roomy is not None and abs(roomy.path_cost_m - far_end[1]) < 1e-9 and roomy.n_beyond_cap == 0)
+
+# The closet mapped, the far end the only frontier left: the cap must not end
+# the run (only None does, and only when nothing is left).
+bare_hall = Grid(hall(closet=False))
+only_far = next_target(bare_hall, start, ExploreState(), now=100.0)
+check("nothing within the cap: the far end still goes out, flagged, the run goes on",
+ only_far is not None and only_far.directive == DIRECTIVE_FRONTIER
+ and only_far.beyond_cap is True and only_far.path_cost_m > 3.0,
+ f"{only_far.path_cost_m:.2f} m, beyond_cap {only_far.beyond_cap}" if only_far else "None")
+nearer = next_target(bare_hall, pose(w_of(90), w_of(60), 0.0), ExploreState(), now=100.0)
+check("and once the rover is within 3 m of it, it is a plain candidate again",
+ nearer is not None and nearer.path_cost_m <= 3.0 and nearer.beyond_cap is False,
+ f"{nearer.path_cost_m:.2f} m" if nearer else "None")
+
+# The cap against the probe penalty. In the hall with the bay and no closet,
+# only the bay's probe lies within 3 m; the far end, safe, lies beyond. The
+# rover faces the bay, so the heading bonus goes to the probe. The defaults
+# throughout, except where probe_penalty is named.
+bay_hall = Grid(hall(closet=False, bay=True))
+facing_bay = pose(w_of(50), w_of(60), -math.pi / 2)
+safe_far = next_target(bay_hall, facing_bay, ExploreState(), now=100.0)
+no_penalty = next_target(bay_hall, facing_bay, ExploreState(), now=100.0,
+ tuning=Tuning(probe_penalty=1.0))
+assert safe_far is not None and no_penalty is not None
+penalised = no_penalty.score * DEFAULT_TUNING.probe_penalty
+print(f" probe {no_penalty.path_cost_m:.2f} m away: {no_penalty.score:.5f}, "
+ f"x {DEFAULT_TUNING.probe_penalty:g} = {penalised:.5f}; "
+ f"safe far end {safe_far.path_cost_m:.2f} m away: {safe_far.score:.5f}")
+check("(setup) the bay's frontier is a probe within the cap, the far end safe beyond it",
+ no_penalty.probe and no_penalty.path_cost_m < 3.0
+ and not safe_far.probe and safe_far.path_cost_m > 3.0,
+ f"probe {no_penalty.probe} at {no_penalty.path_cost_m:.2f} m, "
+ f"far end probe {safe_far.probe} at {safe_far.path_cost_m:.2f} m")
+check("a probe within 3 m, a safe frontier at 4.5 m: under the defaults the safe one goes out",
+ safe_far.position.x > w_of(130) and safe_far.beyond_cap is True
+ and safe_far.n_beyond_cap == 1,
+ f"x = {safe_far.position.x:.2f} m, beyond_cap {safe_far.beyond_cap}, "
+ f"{safe_far.n_beyond_cap} beyond")
+check("the probe penalty decides it, not the cap: at probe_penalty 1 the probe wins",
+ w_of(40) < no_penalty.position.x < w_of(60) and no_penalty.position.y < w_of(38)
+ and penalised < safe_far.score < no_penalty.score,
+ f"({no_penalty.position.x:.2f}, {no_penalty.position.y:.2f})")
+
+# The closet back in: a safe frontier within the cap (1.2 m), the probe within
+# it (1.7 m), and the far end, safe, beyond it (4.5 m).
+both_hall = Grid(hall(closet=True, bay=True))
+near_safe = next_target(both_hall, start, ExploreState(), now=100.0)
+check("a safe frontier within 3 m, a safe one at 4.5 m: under the defaults the near one goes out",
+ near_safe is not None and not near_safe.probe
+ and w_of(57) < near_safe.position.x < w_of(78) and near_safe.position.y > w_of(70)
+ and near_safe.path_cost_m < 3.0 and near_safe.beyond_cap is False
+ and near_safe.n_beyond_cap == 1,
+ f"({near_safe.position.x:.2f}, {near_safe.position.y:.2f}) {near_safe.path_cost_m:.2f} m"
+ if near_safe else "None")
+open_far = next_target(both_hall, start, ExploreState(), now=100.0,
+ tuning=flat(distance_exponent=1.0, max_goal_path_m=0.0))
+held = next_target(both_hall, start, ExploreState(), now=100.0,
+ tuning=flat(distance_exponent=1.0, max_goal_path_m=3.0))
+check("exponent 1: the far end wins with no cap; cap 3 m holds it back for the near safe one",
+ open_far is not None and open_far.position.x > w_of(130)
+ and held is not None and not held.probe and held.beyond_cap is False
+ and w_of(57) < held.position.x < w_of(78) and held.position.y > w_of(70),
+ f"no cap x = {open_far.position.x:.2f} m, cap 3 m "
+ f"({held.position.x:.2f}, {held.position.y:.2f})" if open_far and held else "None")
+
+# The radius. The run starts at (4.03, 2.48): the closet's viewpoint is 1.5 m
+# from there, the far end's 3.0 m.
+anchor_pose = pose(w_of(80), w_of(49), 0.0)
+ax, ay = anchor_pose.position.x, anchor_pose.position.y
+st = ExploreState()
+wide = next_target(hall_cm, anchor_pose, ExploreState(), now=100.0,
+ tuning=flat(max_goal_path_m=0.0))
+assert wide is not None
+d_far = math.hypot(wide.position.x - ax, wide.position.y - ay)
+inside = next_target(hall_cm, anchor_pose, st, now=100.0,
+ tuning=flat(max_goal_path_m=0.0, explore_radius_m=2.0))
+d_near = (math.hypot(inside.position.x - ax, inside.position.y - ay)
+ if inside is not None else float("nan"))
+print(f" from the anchor: far end's target {d_far:.2f} m, closet's {d_near:.2f} m")
+check("(setup) with no radius the far end wins from there, its target 3.0 m from the start",
+ wide.position.x > w_of(130) and abs(d_far - 3.0) < 0.05, f"{d_far:.2f} m")
+check("radius 2 m: the target 3.0 m from the anchor is dropped, the one 1.5 m away kept",
+ inside is not None and abs(d_near - 1.5) < 0.05 and inside.n_outside_radius == 1,
+ f"{d_near:.2f} m, {getattr(inside, 'n_outside_radius', None)} outside")
+check("the anchor is the first pose the run was given",
+ st.anchor == (ax, ay), f"{st.anchor}")
+
+# Later in the same run: the closet is mapped and the rover has driven up the
+# hall, 1.5 m from the far end's target. The radius is still centred where the
+# run began, so the far end stays out, and nothing is left inside it.
+up_hall = pose(w_of(110), w_of(60), 0.0)
+fresh = next_target(bare_hall, up_hall, ExploreState(), now=100.0,
+ tuning=flat(max_goal_path_m=0.0, explore_radius_m=2.0))
+check("(setup) a run STARTING up the hall has the far end inside its 2 m",
+ fresh is not None and fresh.position.x > w_of(130),
+ f"x = {fresh.position.x:.2f} m" if fresh else "None")
+ended = next_target(bare_hall, up_hall, st, now=101.0,
+ tuning=flat(max_goal_path_m=0.0, explore_radius_m=2.0))
+check("only out-of-radius frontiers left -> None: exploration complete",
+ ended is None, str(ended))
+check("an end, not a back-off or a wait, and the anchor did not move",
+ st.last_directive == "" and st.back_off_issued is False and st.anchor == (ax, ay),
+ f"{st.last_directive!r}, {st.back_off_issued}, {st.anchor}")
+unlimited = next_target(bare_hall, up_hall, st.copy(), now=102.0, tuning=flat(max_goal_path_m=0.0))
+check("radius 0 is no limit: the same run, same anchor, goes on to the far end",
+ unlimited is not None and unlimited.position.x > w_of(130),
+ f"x = {unlimited.position.x:.2f} m" if unlimited else "None")
+
+
# ===========================================================================
print("G. purity: nothing but the state's own fields changes")
@@ -579,9 +785,9 @@ check("back_off_issued untouched when nothing was cornered",
st.back_off_issued == before.back_off_issued)
check("heading was refreshed from the pose (0.3 rad)", abs(st.heading - 0.3) < 1e-6,
f"{st.heading}")
-check("visited / observed / targets_issued / last_directive are the only other changes",
- (len(st.visited), len(st.observed), st.targets_issued, st.last_directive)
- == (1, 1, 1, DIRECTIVE_FRONTIER))
+check("visited / observed / targets_issued / last_directive / anchor are the only other changes",
+ (len(st.visited), len(st.observed), st.targets_issued, st.last_directive, st.anchor)
+ == (1, 1, 1, DIRECTIVE_FRONTIER, (here.position.x, here.position.y)))
reopened = ExploreState()
reopened.note_failed(1.0, 2.0, (here.position.x - 5.0, here.position.y), cm) # failed 5 m from here
@@ -630,12 +836,14 @@ else:
STEP_M = 0.4 # what the rover covers per goal: > GOAL_PROGRESS_M
FRONTIER_LEFT = [True] # flipped by `explored()`: next_target then returns None
+ STUB_BEYOND_CAP = [False] # what the stub's target says about the goal cap
def stub_target(costmap, odom, state, **kwargs):
if not FRONTIER_LEFT[0]:
return None # "exploration complete: no reachable frontier left"
t = PoseStamped(ts=0.0, frame_id="world")
t.position.x, t.position.y = STUB_GOAL
+ t.beyond_cap = STUB_BEYOND_CAP[0]
return t
class DoneOut:
@@ -690,7 +898,7 @@ else:
def acts(*fns):
return lambda ex: [f(ex) for f in fns]
- def run_loop(script, wired=True):
+ def run_loop(script, wired=True, tuning=DEFAULT_TUNING):
FRONTIER_LEFT[0] = True
ex = object.__new__(Explorer2)
ex._state = ExploreState()
@@ -698,7 +906,7 @@ else:
ex._last_goal_ok = None
ex._late_answer_owed = False
ex._goal_published_t = 0.0
- ex._tuning = DEFAULT_TUNING
+ ex._tuning = tuning
ex.goal_reached_event = threading.Event()
ex.stop_event = threading.Event()
ex.exploration_active = True
@@ -779,6 +987,110 @@ else:
check("an unwired Out is never published to, and does not crash the loop",
ex.explore_done.sent == [] and ex.exploration_active is False)
+ # -- exp, cap and radius: said once, when exploration starts ----------
+ class Said:
+ """Stands in for the module's logger and keeps every line."""
+
+ def __init__(self):
+ self.lines = []
+
+ def info(self, msg, *args, **kwargs):
+ self.lines.append(str(msg))
+
+ warning = error = debug = info
+
+ real_logger = _explorer2_module.logger
+ said = Said()
+ _explorer2_module.logger = said
+ try:
+ ex, planner, ended = run_loop({1: drove, 2: acts(drove, last)})
+ said_default = list(said.lines)
+ said.lines.clear()
+ ex, planner_r, ended = run_loop({1: acts(explored, gave_up)},
+ tuning=Tuning(explore_radius_m=4.0))
+ said_radius = list(said.lines)
+ said.lines.clear()
+ STUB_BEYOND_CAP[0] = True
+ ex, planner_c, ended = run_loop({1: acts(explored, gave_up)})
+ said_cap = list(said.lines)
+ finally:
+ STUB_BEYOND_CAP[0] = False
+ _explorer2_module.logger = real_logger
+ starts = [line for line in said_default if "exp 2, cap 3 m, radius 0 m" in line]
+ check("one line at the start says 'exp 2, cap 3 m, radius 0 m', and no goal line repeats it",
+ len(planner.goals) == 2 and len(starts) == 1 and said_default[0] == starts[0]
+ and sum("exp " in line for line in said_default) == 1,
+ f"{len(planner.goals)} goals; {said_default[:1]}")
+ check("a radius run says its radius, and its end says 'within 4 m of the start'",
+ any("radius 4 m" in line for line in said_radius[:1])
+ and any("no reachable frontier left within 4 m of the start" in line for line in said_radius),
+ f"{said_radius}")
+ cap_lines = [line for line in said_cap if line.startswith("goal ")]
+ check("a goal beyond the cap says so on its line, and a goal within it does not",
+ len(cap_lines) == 1 and "(beyond the cap: nothing safe within it)" in cap_lines[0]
+ and not any("beyond the cap" in line for line in said_default),
+ f"{cap_lines}")
+
+
+# ===========================================================================
+print("L. the blueprint: three env knobs -> the Explorer2 config")
+# ===========================================================================
+
+if Explorer2 is None:
+ print(" -- skipped: no dimOS here, the blueprint does not import")
+else:
+ import os
+
+ import moss_dimos.blueprints as mb
+ from moss_dimos.explorer2 import Explorer2Config
+
+ check("unset: nothing passed, the explorer keeps its defaults", mb.explorer_env({}) == {})
+ check("'1', '0', ' 4 ' -> exponent 1.0, cap 0.0 m (no limit), radius 4.0 m",
+ mb.explorer_env({"MOSS_EXPLORE_DISTANCE_EXP": "1", "MOSS_GOAL_MAX_M": "0",
+ "MOSS_EXPLORE_RADIUS_M": " 4 "})
+ == {"distance_exponent": 1.0, "max_goal_path_m": 0.0, "explore_radius_m": 4.0})
+ refused = mb.explorer_env({"MOSS_EXPLORE_DISTANCE_EXP": "two", "MOSS_GOAL_MAX_M": "-1",
+ "MOSS_EXPLORE_RADIUS_M": "inf"})
+ check("'two', '-1', 'inf' are refused (warned): the defaults stay", refused == {}, f"{refused}")
+ steep = [mb.explorer_env({"MOSS_EXPLORE_DISTANCE_EXP": raw}) for raw in ("250", "7", "6")]
+ check("an exponent of 250 or 7 is refused (warned), 6 is the largest taken",
+ steep == [{}, {}, {"distance_exponent": 6.0}], f"{steep}")
+ try:
+ overflow = repr(31.0 ** 250)
+ except OverflowError as exc:
+ overflow = f"OverflowError {exc}"
+ check("(why) a float power of 250 raises instead of giving inf, at 6 it is finite",
+ overflow.startswith("OverflowError") and math.isfinite(31.0 ** 6),
+ f"31.0 ** 250: {overflow}")
+ check("the config's defaults are the Tuning's: exponent 2, cap 3 m, radius 0",
+ (Explorer2Config.model_fields["distance_exponent"].default,
+ Explorer2Config.model_fields["max_goal_path_m"].default,
+ Explorer2Config.model_fields["explore_radius_m"].default)
+ == (DEFAULT_TUNING.distance_exponent, DEFAULT_TUNING.max_goal_path_m,
+ DEFAULT_TUNING.explore_radius_m) == (2.0, 3.0, 0.0))
+
+ knobs = {"MOSS_CAMERA": "0", "MOSS_RECORD": "0", "MOSS_WRIST": "0",
+ "MOSS_EXPLORE_DISTANCE_EXP": "1.5", "MOSS_GOAL_MAX_M": "2.5", "MOSS_EXPLORE_RADIUS_M": "4"}
+ saved = {k: os.environ.get(k) for k in knobs}
+ os.environ.update(knobs)
+ try:
+ built = mb.build_moss_explore()
+ finally:
+ for k, v in saved.items():
+ if v is None:
+ os.environ.pop(k, None)
+ else:
+ os.environ[k] = v
+ kw = next(b for b in built.active_blueprints if b.module.__name__ == "Explorer2").kwargs
+ check("moss-explore built with the three set: Explorer2 gets 1.5, 2.5 m, 4 m",
+ (kw.get("distance_exponent"), kw.get("max_goal_path_m"), kw.get("explore_radius_m"))
+ == (1.5, 2.5, 4.0), f"{kw}")
+ cfg = Explorer2Config(**kw)
+ check("and its config holds them", (cfg.distance_exponent, cfg.max_goal_path_m,
+ cfg.explore_radius_m) == (1.5, 2.5, 4.0))
+
print(f"{OK} OK, {KO} KO")
+if not KO:
+ print("TEST PASSED")
sys.exit(1 if KO else 0)
diff --git a/benches/bench_moss_cockpit_cold.py b/benches/bench_moss_cockpit_cold.py
index 08bd4a9..84d2e8c 100644
--- a/benches/bench_moss_cockpit_cold.py
+++ b/benches/bench_moss_cockpit_cold.py
@@ -8,7 +8,9 @@ Every check feeds a value we know and reads back a value in physical units
pixel <-> metre formulas, even downsampling
B. demo server - /, /static, /state.json schema, /map.png (demo size, wall =
WHITE, floor = free colour), /map_meta roundtrip, /scan.json
- (<= 1500 points, every point on a wall, no depth-camera point),
+ (<= 1500 points, every point on a wall, no depth-camera point,
+ the pose on the loop's first leg, at most 0.2 m/s past the pose
+ of a /state.json read right before it), base stalled/stall_count,
/camera.mjpg framing
and its 5 fps cap, POST /cmd/goal|stop|episode|stack, path
traversal refused, bad bodies refused
@@ -16,9 +18,11 @@ Every check feeds a value we know and reads back a value in physical units
cache: OccupancyGrid -> exact PNG pixels, PointCloud2 -> scan
points (and the /pointcloud fallback), the `lidar` cloud split
into lidar returns (z = the profile's lidar height, the stack's
- own override first) and depth-camera points, PoseStamped yaw 90 deg,
- telemetry String -> battery %, Path, explore/goal state, a JPEG
- image passed through byte for byte
+ own override first) and depth-camera points, PoseStamped yaw 90 deg
+ on /state.json and on /scan.json (read per request, never cached
+ with the scan), telemetry String -> battery %, stalled/stall_count
+ (None from telemetry before the stall guard), Path, explore/goal
+ state, a JPEG image passed through byte for byte
D. commands - POST /cmd/* in live mode publish the known bytes on the known
channels (fake LCM handle); explore_ctl's generic publisher and
its start/stop; a run that is not on LCM is refused (503), the
@@ -34,7 +38,13 @@ Every check feeds a value we know and reads back a value in physical units
reading frees its camera slot
H. the real page - tools/moss_cockpit/ served as shipped: index.html, every asset it
and tokens.css reference, the run caption's namespace strip, the
- depth-camera legend element the map writes to
+ depth-camera legend element the map writes to, the STALLED badge
+ and the stalls row; the page's wiring (pose() through freshestPose
+ with the scan's pose and answer time, pollScan stamping each answer,
+ renderBase through the stall latch); node --check app.js, and the
+ page's own pose choice (state vs scan, the younger wins), stall view
+ and stall latch (a stall the 1 Hz read misses still holds the badge
+ 4 s) run in node
F. hygiene - no dimos/serial/torch import, no LAN address in the server
C, D and the run-change checks of G need dimos_lcm (pure python, installed with
@@ -57,6 +67,7 @@ import threading
import time
import types
import datetime as _dt
+import shutil
import signal
import socket
import urllib.error
@@ -298,6 +309,8 @@ b = st["base"]
check("base: battery_v / battery_pct consistent with the 3S gauge",
b and abs(b["battery_pct"] - mc.battery_pct(b["battery_v"])) <= 1 and 10.9 <= b["battery_v"] <= 11.6,
f"{b and b['battery_v']} V {b and b['battery_pct']} %")
+check("demo base: stalled false, stall_count 0 (the stall guard's keys, as the adapter sends them)",
+ b and b.get("stalled") is False and b.get("stall_count") == 0, f"{b and (b.get('stalled'), b.get('stall_count'))}")
check("nav keys", {"exploring", "explore_done", "goal", "goal_reached", "last_cmd_vel"} <= set(st["nav"]))
check("recording keys", {"db", "exists", "size_mb", "episode"} <= set(st["recording"]))
sysm = st["system"]
@@ -333,7 +346,10 @@ check("outside the walls (-5.9, 5.9) -> unknown", pixel_at(-5.9, 5.9) == UNKNOWN
check("next to the wall (-5.35, -4.25) -> a cost colour between free and #8FA6B5",
pixel_at(-5.35, -4.25) not in (FREE, WHITE, UNKNOWN))
+t_before = time.time()
+_, st_fresh = cli.json("/state.json") # right before /scan.json: the two poses are one request apart
code, scan = cli.json("/scan.json")
+t_after = time.time()
pts = scan["points"]
truth = demo.cockpit.world.truth
@@ -346,6 +362,14 @@ def on_wall(x, y):
check("/scan.json: world frame, 1..1500 points", scan["frame"] == "world" and 0 < len(pts) <= 1500,
f"{len(pts)} pts")
+sp, pf = scan.get("pose"), st_fresh["pose"]
+reach = 0.2 * (t_after - t_before) + 0.002 # the demo drives 0.2 m/s; x is rounded to 1 mm on both
+check("demo /scan.json pose {x, y, yaw, age_s}: on the first leg (y -4.25, yaw 0), at or past the x of "
+ "the /state.json read right before it (the rover drives +x), by no more than 0.2 m/s covers "
+ "between the two requests",
+ isinstance(sp, dict) and isinstance(pf, dict) and set(sp) == {"x", "y", "yaw", "age_s"}
+ and abs(sp["y"] + 4.25) < 1e-3 and abs(sp["yaw"]) < 1e-3 and 0.0 <= sp["x"] - pf["x"] <= reach,
+ f"scan {sp} state {pf}, {reach:.3f} m allowed")
check("every scan point lies on a wall cell of the demo map", all(on_wall(x, y) for x, y in pts))
check("demo /scan.json: lidar only -> camera [], camera_n 0, n >= points",
scan.get("camera") == [] and scan.get("camera_n") == 0 and scan.get("n", -1) >= len(pts),
@@ -427,6 +451,9 @@ check("demo: stack map while running -> refused", code == 200 and ans["ok"] is F
cli.post("/cmd/stack", {"action": "stop"})
_, st = cli.json("/state.json")
check("demo: stack stop -> running false, pose null", st["stack"] == {"running": False} and st["pose"] is None)
+_, sc = cli.json("/scan.json")
+check("demo: stack stop -> /scan.json no points, pose null", sc["points"] == [] and sc["pose"] is None,
+ json.dumps(sc)[:120])
code, ans = cli.post("/cmd/stack", {"action": "map"})
_, st = cli.json("/state.json")
check("demo: stack map -> moss-nav running", ans["ok"] and st["stack"]["blueprint"] == "moss-nav")
@@ -485,6 +512,9 @@ else:
code, st = lcli.json("/state.json")
check("live, empty bus: pose null, base null, topics never seen", code == 200 and st["mode"] == "live"
and st["pose"] is None and st["base"] is None and st["topics"]["odom"]["age_s"] is None)
+ code, sc = lcli.json("/scan.json")
+ check("live, empty bus: /scan.json no points, pose null", code == 200 and sc["points"] == []
+ and sc["pose"] is None, json.dumps(sc))
code, _, _ = lcli.get("/map.png")
check("no costmap yet -> /map.png 404", code == 404)
@@ -587,6 +617,29 @@ else:
check("String telemetry 11400 mV -> battery 11.4 V, 50 %, mode off, fw, driver null",
(b["battery_v"], b["battery_pct"], b["mode_name"], b["fw"], b["driver"])
== (11.4, 50, "off", "qtpy-mdd3a-v3", None), json.dumps(b)[:160])
+ check("telemetry without stalled/stall_count (before the stall guard) -> base stalled None, stall_count None",
+ "stalled" in b and "stall_count" in b and b["stalled"] is None and b["stall_count"] is None,
+ json.dumps({k: b.get(k) for k in ("stalled", "stall_count")}))
+ for stalled, count in ((True, 3), (False, 3)):
+ bus.ingest(mc.CHANNELS["base_telemetry"],
+ String(data=json.dumps(dict(tele, ts=time.time(), stalled=stalled, stall_count=count))).lcm_encode())
+ code, st2 = lcli.json("/state.json")
+ b2 = st2["base"]
+ check(f"telemetry stalled {stalled}, stall_count {count} -> base stalled {stalled}, stall_count {count}",
+ (b2["stalled"], b2["stall_count"]) == (stalled, count), json.dumps({k: b2.get(k) for k in ("stalled", "stall_count")}))
+
+ code, sc = lcli.json("/scan.json")
+ sp = sc.get("pose") or {}
+ check("/scan.json pose after the odom messages: (1.25, -0.5), yaw 1.5708, 0 <= age_s < 1 s, keys as /state.json's",
+ set(sp) == set(st["pose"]) == {"x", "y", "yaw", "age_s"} and (sp["x"], sp["y"]) == (1.25, -0.5)
+ and abs(sp["yaw"] - 1.5708) < 1e-4 and 0.0 <= sp["age_s"] < 1.0, json.dumps(sp))
+ bus.ingest(mc.CHANNELS["odom"], PoseStamped(header=hdr("world"), pose=pose_of(2.0, 1.0)).lcm_encode())
+ code, sc2 = lcli.json("/scan.json") # no new cloud: the scan itself comes from the cache
+ cached = live.cockpit._scan_cache[1]
+ check("a new odom message, no new cloud -> /scan.json pose (2.0, 1.0) yaw 0, same points; "
+ "the cached scan carries no pose",
+ (sc2["pose"]["x"], sc2["pose"]["y"], sc2["pose"]["yaw"]) == (2.0, 1.0, 0.0)
+ and sc2["points"] == sc["points"] and "pose" not in cached, json.dumps(sc2["pose"]))
poses = [PoseStamped(header=hdr("world"), pose=pose_of(x, y))
for x, y in ((0.0, 0.0), (0.5, 0.25), (1.0, 1.0))]
@@ -1172,6 +1225,136 @@ check("the run caption strips any dimOS namespace: moss-dimos.moss-explore -> mo
"other-dimos.explore -> explore, moss-nav unchanged",
got == {"moss-dimos.moss-explore": "moss-explore", "other-dimos.explore": "explore", "moss-nav": "moss-nav"},
f"{pattern} {got}")
+check("the STALLED badge sits in the Mode row before #b-mode, hidden until a stall; a Stalls row #b-stalls",
+ bool(re.search(r'<dt>Mode</dt><dd><span class="badge" id="b-stall" hidden>STALLED</span><span id="b-mode">',
+ page_html)) and '<dt>Stalls</dt><dd id="b-stalls">' in page_html)
+check("the badge wears the page's attention colour (--ui-attention, tokens.css)",
+ bool(re.search(r"\.badge \{[^}]*color: var\(--ui-attention\)", page_html))
+ and "--ui-attention:" in (real_page / "tokens.css").read_text())
+poll = re.search(r"var POLL = \{[^}]*\bscan: (\d+)", js)
+check("app.js shows the badge from base.stalled, the count in #b-stalls, and polls /scan.json (and its pose) "
+ "at >= 3 Hz", '$("b-stall").hidden' in js and 'setText("b-stalls"' in js and "stall_count" in js
+ and poll is not None and int(poll.group(1)) <= 334, poll.group(0) if poll else "no POLL.scan")
+
+
+def js_fn(name):
+ """The source of app.js's top-level `function name(...) {...}`, or ""."""
+ m = re.search(r"^function " + name + r"\([\s\S]*?^}$", js, re.M)
+ return m.group(0) if m else ""
+
+
+pose_call = re.search(r"\bfreshestPose\(([^;]*)\);", js_fn("pose"))
+pose_args = [a.strip() for a in pose_call.group(1).split(",")] if pose_call else []
+check("app.js pose() draws from freshestPose(state pose, S.stateAt, scan pose, S.scanAt, now): "
+ "the scan's 3 Hz pose reaches the marker",
+ len(pose_args) == 5 and "S.state.pose" in pose_args[0] and pose_args[1] == "S.stateAt"
+ and "S.scan.pose" in pose_args[2] and pose_args[3] == "S.scanAt" and pose_args[4] == "Date.now()",
+ str(pose_args))
+pose_reads = re.findall(r"S\.(?:state|scan)\.pose\b", js)
+check("app.js reads the state's and the scan's pose only inside pose(), and the map draws through pose()",
+ len(pose_reads) == 2 and len(re.findall(r"S\.(?:state|scan)\.pose\b", js_fn("pose"))) == 2
+ and "var p = pose();" in js_fn("draw"), f"{len(pose_reads)} reads")
+scan_store = re.search(r"\{[^{}]*\bS\.scan = d;[^{}]*\}", js_fn("pollScan"))
+check("app.js pollScan stamps each scan answer it keeps: S.scanAt = Date.now() beside S.scan = d",
+ bool(scan_store) and "S.scanAt = Date.now();" in scan_store.group(0),
+ scan_store.group(0) if scan_store else "no S.scan = d block in pollScan")
+render_base = js_fn("renderBase")
+hold = re.search(r"^var STALL_HOLD_S = (\d+(?:\.\d+)?);", js, re.M)
+check("app.js renderBase feeds the stall latch from base.stall_count and shows the badge through it; "
+ "STALL_HOLD_S >= 4 s",
+ "var now = Date.now();" in render_base
+ and "S.stallLatch = stallLatch(S.stallLatch, b ? b.stall_count : null, now);" in render_base
+ and "var stall = stallView(b, S.stallLatch.until, now);" in render_base
+ and '$("b-stall").hidden = !stall.badge;' in render_base
+ and hold is not None and float(hold.group(1)) >= 4, hold.group(0) if hold else "no STALL_HOLD_S")
+node = shutil.which("node")
+if node is None:
+ print(" -- skipped, no node here: node --check app.js, the page's pose choice and its stall latch")
+else:
+ r = subprocess.run([node, "--check", str(real_page / "app.js")], capture_output=True, text=True, timeout=30)
+ check("node --check app.js", r.returncode == 0, r.stderr.strip()[:200])
+
+ harness = (hold.group(0) if hold else "") + "\n" + js_fn("freshestPose") + "\n" + js_fn("stallLatch") \
+ + "\n" + js_fn("stallView") + "\n" + """
+var T = 100000; // the page's clock, ms
+var P = function (x, age) { return { x: x, y: 1, yaw: 0.5, age_s: age }; };
+// A stall on the floor: telemetry says stalled only from 2.3 s to 2.7 s and stall_count goes
+// 0 -> 1 at 2.3 s; the page reads state at 0, 1, ..., 10 s, as renderBase does. floor = the
+// read times (s) that show the badge.
+var floor = [], latch = { count: null, until: 0 };
+for (var t = 0; t <= 10000; t += 1000) {
+ var base = { stalled: t >= 2300 && t < 2700, stall_count: t >= 2300 ? 1 : 0 };
+ latch = stallLatch(latch, base.stall_count, t);
+ if (stallView(base, latch.until, t).badge) floor.push(t / 1000);
+}
+console.log(JSON.stringify({
+ scanYounger: freshestPose(P(1, 0.2), T - 900, P(2, 0.1), T - 100, T),
+ stateYounger: freshestPose(P(1, 0.1), T - 100, P(2, 0.1), T - 300, T),
+ noScanYet: freshestPose(P(1, 0.3), T - 500, undefined, 0, T),
+ scanSaysNone: freshestPose(P(1, 0.1), T - 900, null, T - 100, T),
+ stateSaysNone: freshestPose(null, T - 100, P(2, 0.1), T - 300, T),
+ scanAfterNone: freshestPose(null, T - 900, P(2, 0.05), T - 100, T),
+ nothing: freshestPose(undefined, 0, undefined, 0, T),
+ stall: stallView({ stalled: true, stall_count: 3 }),
+ cleared: stallView({ stalled: false, stall_count: 3 }),
+ older: stallView({ stalled: null, stall_count: null }),
+ none: stallView(null),
+ floor: floor,
+ firstSeen: stallLatch({ count: null, until: 0 }, 5, T),
+ renewed: stallLatch(stallLatch({ count: 2, until: 0 }, 3, T), 3, T + 2000),
+ acrossGap: stallLatch(stallLatch({ count: 3, until: 0 }, null, T), 4, T + 1000),
+ newRun: stallLatch({ count: 3, until: 0 }, 0, T),
+ afterNewRun: stallLatch(stallLatch({ count: 3, until: 0 }, 0, T), 1, T + 1000),
+ holdEdge: [stallView({ stalled: false, stall_count: 3 }, T + 4000, T + 3999).badge,
+ stallView({ stalled: false, stall_count: 3 }, T + 4000, T + 4000).badge],
+ stalledNoHold: stallView({ stalled: true, stall_count: 3 }, 0, T).badge
+}));
+"""
+ r = subprocess.run([node, "-e", harness], capture_output=True, text=True, timeout=30)
+ try:
+ jr = json.loads(r.stdout)
+ except ValueError:
+ jr = {}
+
+ def at(key, x, age):
+ p = jr.get(key)
+ return isinstance(p, dict) and p.get("x") == x and abs(p.get("age_s", -1) - age) < 1e-9 and p.get("yaw") == 0.5
+
+ check("page pose: state 0.2 s old 0.9 s ago (1.1 s) vs scan 0.1 s old 0.1 s ago (0.2 s) -> the scan's, age 0.2 s",
+ at("scanYounger", 2, 0.2), json.dumps(jr.get("scanYounger")) + r.stderr[:200])
+ check("page pose: state 0.1 s old 0.1 s ago (0.2 s) vs scan 0.1 s old 0.3 s ago (0.4 s) -> the state's",
+ at("stateYounger", 1, 0.2), json.dumps(jr.get("stateYounger")))
+ check("page pose: no scan answer yet -> the state's, aged by its 0.5 s since the answer (0.8 s)",
+ at("noScanYet", 1, 0.8), json.dumps(jr.get("noScanYet")))
+ check("page pose: a later answer with pose null (stack stopped, new run) hides the marker, either source",
+ "scanSaysNone" in jr and jr["scanSaysNone"] is None and "stateSaysNone" in jr and jr["stateSaysNone"] is None
+ and "nothing" in jr and jr["nothing"] is None, json.dumps({k: jr.get(k) for k in ("scanSaysNone", "stateSaysNone", "nothing")}))
+ check("page pose: a scan pose after an older null state -> drawn (odometry is back), age 0.15 s",
+ at("scanAfterNone", 2, 0.15), json.dumps(jr.get("scanAfterNone")))
+ check("page stall view: stalled 3 -> badge + '3'; cleared 3 -> no badge, '3'; older telemetry / none -> no badge, '--'",
+ (jr.get("stall"), jr.get("cleared"), jr.get("older"), jr.get("none"))
+ == ({"badge": True, "count": "3"}, {"badge": False, "count": "3"},
+ {"badge": False, "count": "--"}, {"badge": False, "count": "--"}),
+ json.dumps({k: jr.get(k) for k in ("stall", "cleared", "older", "none")}))
+ check("page stall latch on the floor: stalled only 2.3-2.7 s (no 1 Hz read sees it), count 0 -> 1 "
+ "-> the badge shows at the reads of 3, 4, 5 and 6 s (4 s from the read that saw the count), "
+ "gone at 7 s",
+ jr.get("floor") == [3, 4, 5, 6], json.dumps(jr.get("floor")))
+ check("page stall latch: the first count the page sees (5) only sets the reference, no hold; "
+ "the same count again does not renew the hold (3 at T, still 3 at T+2 s -> ends at T+4 s)",
+ jr.get("firstSeen") == {"count": 5, "until": 0}
+ and jr.get("renewed") == {"count": 3, "until": 100000 + 4000},
+ json.dumps({k: jr.get(k) for k in ("firstSeen", "renewed")}))
+ check("page stall latch: a missing count keeps the reference (3, gap, 4 at T+1 s -> hold to T+5 s); "
+ "a count that went down (new run, 3 -> 0) holds nothing, and 0 -> 1 then holds to T+5 s",
+ jr.get("acrossGap") == {"count": 4, "until": 100000 + 5000}
+ and jr.get("newRun") == {"count": 0, "until": 0}
+ and jr.get("afterNewRun") == {"count": 1, "until": 100000 + 5000},
+ json.dumps({k: jr.get(k) for k in ("acrossGap", "newRun", "afterNewRun")}))
+ check("page stall view with a hold: stalled false, hold ends at T+4 s -> badge at T+3.999 s, none at "
+ "T+4 s; stalled true without a hold -> badge",
+ jr.get("holdEdge") == [True, False] and jr.get("stalledNoHold") is True,
+ json.dumps({k: jr.get(k) for k in ("holdEdge", "stalledNoHold")}))
# ---------------------------------------------------------------------------
print("F. hygiene")
diff --git a/benches/bench_moss_fly_gates_cold.py b/benches/bench_moss_fly_gates_cold.py
index c6f7519..3368248 100644
--- a/benches/bench_moss_fly_gates_cold.py
+++ b/benches/bench_moss_fly_gates_cold.py
@@ -380,7 +380,7 @@ check("one launch: --rerun-open none --nerf-speed 0.5 run moss-dimos.moss-nav --
env_l = run_l[0].split("| ENV ", 1)[1] if run_l and "| ENV " in run_l[0] else ""
for want in (f"MOSS_PORT={qtpy}", f"MOSS_LIDAR_PORT={c1}", "DIMOS_TRANSPORT=lcm",
"TRANSPORT=lcm", "GLIBC_TUNABLES=glibc.rtld.optional_static_tls=4194304", "MOSS_MAX_PCT=100",
- "MOSS_RAMP_MS=5 5", "MOSS_RECORD=1", "MOSS_CAMERA=1", f"MOSS_STATE_DIR={case / 'state'}"):
+ "MOSS_RAMP_MS=5 5", "MOSS_RECORD=1", "MOSS_CAMERA=1", "MOSS_EXPLORE_RADIUS_M=4", f"MOSS_STATE_DIR={case / 'state'}"):
check(f"stack env: {want.split('=')[0]}={want.split('=', 1)[1][-40:]}",
re.search(r"(^| )" + re.escape(want) + r"( |$)", env_l) is not None, env_l[-120:])
check("the launcher does not export ROBOT_PROFILE (MOSS is the only profile)",
diff --git a/docs/cockpit.md b/docs/cockpit.md
index d33b985..4848981 100644
--- a/docs/cockpit.md
+++ b/docs/cockpit.md
@@ -71,7 +71,15 @@ firmware 300 ms after the last drive.
the encoders give metres only once `MOSS_TICKS_PER_M` is set, and no IMU
feeds the odometry;
- the 2D scored costmap (`moss_dimos/costmap2d.py`), where the lidar writes obstacles
- and the depth camera adds the ones below the scan plane;
+ 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);
- the RealSense colour stream at 640x480, 5 fps, carried as JPEG on the bus, and its
depth aligned to colour at the same rate, which `lidar_odometry` turns into obstacle
points from 12 cm (the camera's close-range depth) to 3 m, drawn in amber on the map
@@ -89,6 +97,20 @@ manager (pad input wins over navigation for one second) and Explorer2
(`moss_dimos/explorer2.py`) with the MOSS clearances. The pad is still there,
through the manager.
+Three variables decide how far the explorer sends the rover. They are read when
+`moss-explore` is built; unset keeps the default, and a value that is not a
+number of 0 or more (0 to 6 for the exponent) is refused with a warning (the default stays):
+
+| Env | Default | What it does |
+|---|---|---|
+| `MOSS_EXPLORE_DISTANCE_EXP` | 2 | how hard distance counts: a frontier scores its information over (1 + its path cost in metres) to this power; a metre of unmapped floor counts as 4, a metre hugging a wall up to 2. At 1 a frontier twice as far needs only twice the information to win, so a big frontier across the room beats a small one beside the rover; at 2 it needs four times as much |
+| `MOSS_GOAL_MAX_M` | 3 m | the longest path cost a goal is sent along (0 = no limit), in the same metres as above; a frontier beyond it only waits while a safe one lies within it. A farther frontier waits until the rover is nearer; when nothing nearer is left it goes out anyway, so the cap never ends a run |
+| `MOSS_EXPLORE_RADIUS_M` | 0 in the code; `tools/moss-fly.sh` exports 4 (one room) unless set | the run stays within this distance of where exploration started: a frontier whose goal lies farther is never a candidate, and once nothing is left inside, exploration is complete. Set 4 to keep the rover in one room. A doorway is a frontier like any other: a door the rover must not take has to lie outside the radius Each start of exploration (the start button, after STOP or after a tapped goal) re-centres the radius on where the rover stands then. |
+
+The explorer logs the three values in one line when exploration starts
+(`exploration start: distance exp 2, cap 3 m, radius 0 m`); each goal line
+gives its path cost.
+
`moss-dimos.moss-gamepad` and `moss-dimos.moss-base` are the base alone, with
or without the pad: [base.md](base.md).
@@ -159,6 +181,9 @@ Other variables:
| `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_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 |
## Recording
@@ -223,7 +248,13 @@ Endpoints, for anything else that wants the data: `/state.json`, `/map.png`,
`/scan.json` splits the latest `lidar` cloud by height: `points` (and `n`) are the lidar returns, at
the profile's lidar height; `camera` (and `camera_n`) are the depth camera's obstacle points, at
-their true height, which the page draws in amber. The raw `/pointcloud` fallback has no `camera` key.
+their true height, which the page draws in amber; `pose` is the rover's pose at the
+scan's time (x, y, yaw, age_s), so the page moves the rover marker at the scan's
+rate (3 Hz) rather than the state's (1 Hz). The raw `/pointcloud` fallback has no
+`camera` key. The base panel shows a STALLED badge for at least 4 s whenever the
+base adapter's stall guard fires (a commanded track whose encoder did not move for
+1 s: the tracks stop and the planner backs off), and a `stalls` row counts them
+over the run.
`POST /cmd/{explore,goal,stop,episode,stack}`.
`tools/moss_cockpit.py --demo` serves synthetic data for working on the page
without a robot.
diff --git a/moss_dimos/blueprints.py b/moss_dimos/blueprints.py
index ea96d16..62a25b1 100644
--- a/moss_dimos/blueprints.py
+++ b/moss_dimos/blueprints.py
@@ -252,6 +252,38 @@ LIDAR_BAUDRATE = 460800
CAMERA_WIDTH, CAMERA_HEIGHT, CAMERA_FPS = 640, 480, 5
EXPLORER_MIN_FRONTIER_PERIMETER_M = 0.3 # doorway-sized frontiers stay visible
EXPLORER_GOAL_TIMEOUT_S = 45.0
+# Where the explorer sends the rover, set for the room (docs/cockpit.md):
+# env -> Explorer2 config field, and the largest value accepted. Unset leaves
+# the explorer's own default. The exponent stops at 6: the score is
+# gain / (1 + path cost) ** exponent, and a large float power raises
+# OverflowError instead of giving inf (31.0 ** 250 does), which would end the
+# exploration loop.
+EXPLORER_ENV = (("MOSS_EXPLORE_DISTANCE_EXP", "distance_exponent", 6.0), # 2: distance squared against gain
+ ("MOSS_GOAL_MAX_M", "max_goal_path_m", math.inf), # 3 m of path cost at most, 0 = no limit
+ ("MOSS_EXPLORE_RADIUS_M", "explore_radius_m", math.inf)) # 0 = no limit, 4 for a room
+
+
+def explorer_env(env: dict | None = None) -> dict:
+ """The explorer knobs set in the environment, as Explorer2 config
+ fields. A value that is not a finite number from 0 to its largest
+ (EXPLORER_ENV) is refused with a warning and the explorer keeps its
+ default."""
+ env = os.environ if env is None else env
+ out = {}
+ for name, field_name, largest in EXPLORER_ENV:
+ raw = str(env.get(name, "")).strip()
+ if not raw:
+ continue
+ try:
+ value = float(raw)
+ except ValueError:
+ value = math.nan
+ if not math.isfinite(value) or not 0 <= value <= largest:
+ bound = f"from 0 to {largest:g}" if math.isfinite(largest) else ">= 0"
+ _logger.warning(f"{name}={raw!r} is not a number {bound}: the explorer keeps its default")
+ continue
+ out[field_name] = value
+ return out
def moss_ports(env: dict | None = None) -> dict:
@@ -525,7 +557,8 @@ def build_moss_explore():
tele_cmd_vel_scaling=Twist(Vector3(1.0, 1.0, 0.0), Vector3(0.0, 0.0, 1.0))),
Explorer2.blueprint(min_frontier_perimeter=EXPLORER_MIN_FRONTIER_PERIMETER_M,
goal_timeout=EXPLORER_GOAL_TIMEOUT_S,
- lethal_clearance_m=lethal, pivot_clearance_m=pivot),
+ lethal_clearance_m=lethal, pivot_clearance_m=pivot,
+ **explorer_env()),
]
return _jpeg_camera(autoconnect(*parts)).remappings([
(MossControlCoordinator, "twist_command", "cmd_vel"),
diff --git a/moss_dimos/costmap2d.py b/moss_dimos/costmap2d.py
index fe202fe..d26b785 100644
--- a/moss_dimos/costmap2d.py
+++ b/moss_dimos/costmap2d.py
@@ -20,11 +20,55 @@ table legs. This module replaces it for a rover with a single-plane lidar:
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). `lidar_returns`
-tells them apart. Lidar returns carve their rays free and hit their cell; the
-camera points only hit their cell (a camera obstacle proves nothing about the
-floor in front of it) under the same two-viewpoint rule, so a camera obstacle
-becomes a wall on approach like a leg does.
+(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).
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
@@ -36,12 +80,16 @@ 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.
-Numbers (HIT_CAP, FREE_FLOOR, OCCUPIED_AT) are a starting point to be tested.
+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.
"""
from __future__ import annotations
import math
+import os
import time
from typing import Any
@@ -61,18 +109,51 @@ from moss_dimos.robot_profile import current as _current_profile
logger = setup_logger()
+
+def _env_float(name: str, default: float, lo: float, hi: float) -> float:
+ """A number from the environment, read once at import. Unset or empty ->
+ `default`; not a number -> `default`, said in the log; outside [lo, hi]
+ -> the nearest bound, said in the log."""
+ raw = os.environ.get(name, "").strip()
+ if not raw:
+ return default
+ try:
+ value = float(raw)
+ except ValueError:
+ logger.warning(f"costmap: {name}={raw!r} is not a number - using {default}")
+ return default
+ if not lo <= value <= hi:
+ bounded = hi if value > hi else lo # below lo, or nan
+ logger.warning(f"costmap: {name}={raw!r} is outside [{lo}, {hi}] - using {bounded}")
+ return bounded
+ return value
+
+
RESOLUTION_M = 0.05
GRID_SPAN_M = 24.0 # world-fixed square, centred on the first pose
-HIT_CAP = 10 # ceiling: no cell gets more certain than this
-FREE_FLOOR = -3 # floor: no cell gets more "free" than this
OCCUPIED_AT = 2 # two hits from two places = an obstacle
+# 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.
+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 = 0.10 # a hit counts only if the rover moved this much since the cell's last hit
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 = 5 # one grid every 5 revolutions (~2 Hz at 10 Hz). A 24 m grid is ~230 kB and every
# subscriber (planner, explorer, recorder, cockpit) decodes each one; the map
# QUALITY does not depend on this rate (the odometry gives it).
-RAY_MAX_M = 4.0 # rays are carved (misses) up to this range only: 12 m rays in 2.5 cm steps cost ~230 ms per revolution
+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
+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.
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.
@@ -88,7 +169,8 @@ 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 below that plane: hit by it, freed by its floor samples, never carved by a lidar ray
+ 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.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)
@@ -120,11 +202,28 @@ class ScoredGrid:
# 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).astype(np.int8)
- layer[gy, gx] = new
+ 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)
self._last_hit_xy[gy[moved], gx[moved]] = from_xy
self.seen[gy, gx] = True
- return int(moved.sum())
+ return int(took.sum())
def _miss(self, layer: np.ndarray, gx: np.ndarray, gy: np.ndarray) -> None:
if len(gx) == 0:
@@ -133,26 +232,72 @@ 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]) -> 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."""
+ 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."""
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:
- self._miss(self.lidar, cells[0], cells[1])
+ 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._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), no ray carved.
- Returns the number of cells that took a hit."""
+ 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)
@@ -210,6 +355,7 @@ 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 ------------------------------------------------------------
@@ -286,7 +432,8 @@ class MossCostMap(Module):
@rpc
def start(self) -> None:
super().start()
- logger.info(f"costmap up: {RESOLUTION_M} m cells, hit cap {HIT_CAP}, free floor {FREE_FLOOR}, occupied at {OCCUPIED_AT}")
+ 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")
async def handle_odom(self, msg: PoseStamped) -> None:
self._pose_xy = (float(msg.position.x), float(msg.position.y))
@@ -374,10 +521,10 @@ class MossCostMap(Module):
hits = pts[tag]
if len(hits) == 0:
return # no lidar return on this cloud: not a revolution
- self._grid.lidar_revolution(hits[:, :2], self._pose_xy)
- cam = pts[~tag]
+ 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[:, :2], self._pose_xy)
+ self._camera_cells += self._grid.camera_hits(cam, self._pose_xy)
self._camera_pts += len(cam)
self._revolutions += 1
if self._revolutions % PUBLISH_EVERY == 0:
diff --git a/moss_dimos/explorer2.py b/moss_dimos/explorer2.py
index bcb8d0c..8314dff 100644
--- a/moss_dimos/explorer2.py
+++ b/moss_dimos/explorer2.py
@@ -13,7 +13,7 @@ Strategy: information gain per path cost, taken from dimensionalOS/dimos
PR #2830. What is reused verbatim from that PR, and what is not:
reused the objective shape, multiplicative instead of the old weighted sum:
- score = info_gain / (1 + path_cost)
+ score = info_gain / (1 + path_cost) (here to a power: see below)
score *= 1 + 0.5 * heading_alignment (its only numeric weight)
score *= revisit_fade (linear there, inside a radius)
reused info gain = frontier cluster cell count, normalised by
@@ -29,6 +29,11 @@ PR #2830. What is reused verbatim from that PR, and what is not:
dropped its info_gain_threshold / num_no_gain_attempts self-stop, and the
loop's "10 consecutive failures" give-up. Both are timers, and a
timer can end a run with valid clusters still on the map.
+ changed the path cost is raised to Tuning.distance_exponent, 2 by default
+ (1 is the PR's own shape). To the first power a frontier twice as
+ far only needs twice the gain to win, so a big frontier at the other
+ end of a room beats a small one beside the rover, and the rover
+ crosses the room for it. Squared, it needs four times the gain.
changed path cost is ONE Dijkstra from the robot over the whole traversable
grid instead of one A* per cluster: same currency, N clusters for
the price of one search.
@@ -52,6 +57,15 @@ PR #2830. What is reused verbatim from that PR, and what is not:
unfinished business rather than a revisit (see next_target).
added a cluster reachable only across unmapped ground is a PROBE and is
ranked behind every safe frontier (Tuning.probe_penalty).
+ added a goal cap (Tuning.max_goal_path_m): a frontier whose path cost is
+ over the cap waits while a safe frontier lies within it. With only
+ probes within the cap, the safe frontiers beyond it compete again,
+ under the probe penalty; with nothing within it, the best beyond
+ it goes out. An exploration radius (Tuning.explore_radius_m): a
+ frontier is not a candidate while its target lies farther than the
+ radius from the first pose of the run, and a map with nothing left
+ inside it is an explored map: set to a room's size, the rover stays
+ in the room it started in.
added a viewpoint the robot has already decided from is never handed out
again (Tuning.observed_radius_m): driving to a spot it is already at
reveals nothing. That is geometry, not a counter, and it is what
@@ -228,6 +242,32 @@ class Tuning:
standoff_max_m: float = 1.00
# Scoring.
+ # How hard distance counts against information:
+ # score = gain / (1 + path cost) ** distance_exponent
+ # 1 is PR #2830's shape, under which a frontier twice as far needs only
+ # twice the gain to win, so a big frontier across the room beats a small
+ # one beside the rover. At 2 it needs four times the gain. A shape, like
+ # _REVISIT_FADE_POWER, but the operator's to set (MOSS_EXPLORE_DISTANCE_EXP):
+ # how far the rover may go for more map is a choice made for the room.
+ distance_exponent: float = 2.0
+ # The highest path cost a goal is sent at (0 = no limit), in the metres of
+ # _path_cost: a metre of unknown counts as unknown_cost_factor metres, a
+ # metre in the band too tight to pivot in up to 1 + pivot_cost_factor. A
+ # frontier beyond it waits for THIS decision only, and only while a safe
+ # frontier lies within it: once the rover is nearer it comes back. When
+ # only probes lie within the cap, the safe frontiers beyond it compete
+ # with them, and the probe penalty weighs the two as it would with no cap
+ # (probes beyond it still wait). When nothing lies within it, the
+ # best of the rest goes out: dropping them all would end a run with
+ # frontiers still within reach, and only `None` ends a run, only when
+ # nothing is left.
+ max_goal_path_m: float = 3.0
+ # The area the run stays in, in metres around the anchor (the first pose of
+ # the run, ExploreState.anchor); 0 = no limit. A frontier is not a
+ # candidate while its target lies farther than this from the anchor, and a
+ # map with nothing left inside the radius is an explored map: the run ends
+ # as it ends on a fully explored map. 4 m is a room.
+ explore_radius_m: float = 0.0
forward_bonus: float = 0.5 # PR #2830's momentum weight, on the real heading
revisit_radius_m: float = 1.0 # within 1 m of a goal already published this
# run, the score fades as the square of the
@@ -291,6 +331,8 @@ class ExploreState:
back_off_issued set when a back-off goes out, cleared when a frontier does
last_directive what it just returned ("" if None)
targets_issued count of frontier targets handed out
+ anchor set once, from the first pose it is given: the centre
+ of Tuning.explore_radius_m
Nothing else in the process is touched: no globals, no costmap writes.
"""
@@ -306,6 +348,9 @@ class ExploreState:
last_directive: str = ""
targets_issued: int = 0
wait_streak: int = 0 # consecutive WAITs; WAIT_REOPEN_POLLS triggers the starvation escape
+ # Where the run started: the first pose next_target is given, never moved
+ # afterwards. A fresh ExploreState is a fresh run, so a fresh anchor.
+ anchor: tuple[float, float] | None = None
def note_failed(self, x: float, y: float, robot_xy: tuple[float, float],
costmap: Any, radius_m: float = DEFAULT_TUNING.failed_goal_radius_m) -> None:
@@ -879,8 +924,9 @@ def next_target(costmap: Any, pose: Any, state: ExploreState, *,
left to look at and no exclusion is holding anything back - either the
map holds no frontier cluster at all, or every one it holds has already
been looked straight at from where the rover stood, or nowhere the body
- can stand can see it. No counters, no attempt limits, no timers; a rover
- that is merely shut in gets a back-off, not a None.
+ can stand can see it, or its target lies outside the exploration radius.
+ No counters, no attempt limits, no timers; a rover that is merely shut
+ in gets a back-off, not a None.
"""
now = time.monotonic() if now is None else float(now)
grid = np.asarray(costmap.grid)
@@ -893,6 +939,8 @@ def next_target(costmap: Any, pose: Any, state: ExploreState, *,
rx, ry_world = float(pose.position.x), float(pose.position.y)
heading = _yaw_of(pose, state.heading)
state.heading = heading
+ if state.anchor is None:
+ state.anchor = (rx, ry_world)
# This pose has just had a lidar revolution. Record it once per half-radius
# so the list stays short over a long run.
half = tuning.observed_radius_m / 2.0
@@ -979,9 +1027,11 @@ def next_target(costmap: Any, pose: Any, state: ExploreState, *,
# --- temporary exclusions ----------------------------------------------
radius2 = tuning.failed_goal_radius_m ** 2
+ ax, ay = state.anchor
eligible: list[Cluster] = []
n_blocked = 0
n_seen_from = 0
+ n_outside = 0
for cluster in clusters:
gx, gy = cluster.goal_xy
if cluster.retired:
@@ -991,14 +1041,20 @@ def next_target(costmap: Any, pose: Any, state: ExploreState, *,
# then asked to look.
n_seen_from += 1
continue
+ if tuning.explore_radius_m > 0 and math.hypot(gx - ax, gy - ay) > tuning.explore_radius_m:
+ # Its target lies outside the area this run stays in: not a
+ # candidate for this decision.
+ n_outside += 1
+ continue
if any((gx - f[0]) ** 2 + (gy - f[1]) ** 2 < radius2 for f in state.failed):
n_blocked += 1
else:
eligible.append(cluster)
if not eligible and not n_blocked:
- # Every cluster is one the rover has already stood at and looked from.
- # Nothing reachable is worth going to: that is the end of the run.
+ # Every cluster is one the rover has already stood at and looked from,
+ # or lies outside the exploration radius. Nothing reachable is worth
+ # going to: that is the end of the run.
state.last_directive = ""
return None
@@ -1020,21 +1076,20 @@ def next_target(costmap: Any, pose: Any, state: ExploreState, *,
directive=DIRECTIVE_WAIT, wait_s=0.0,
reopened_xy=reopened,
n_clusters=len(clusters), n_excluded=n_blocked,
- n_already_seen_from=n_seen_from, n_on_the_map=on_the_map)
+ n_already_seen_from=n_seen_from, n_outside_radius=n_outside,
+ n_on_the_map=on_the_map)
# --- score (information gain per path cost, PR #2830) -----------------
costs = _path_cost(survey.reachable, survey.cell_cost, survey.seed, res)
- best: Cluster | None = None
- best_score = -math.inf
- best_cost = math.inf
+ scored: list[tuple[Cluster, float, float]] = [] # (cluster, score, path cost)
for cluster in eligible:
gy, gx = cluster.goal_yx
cost = float(costs[gy, gx]) if survey.reachable[gy, gx] else math.inf
if not math.isfinite(cost):
# Unreachable: PR #2830's -inf, dropped rather than published.
continue
- score = cluster.gain / (1.0 + cost)
+ score = cluster.gain / (1.0 + cost) ** tuning.distance_exponent
if cluster.probe:
score *= tuning.probe_penalty
@@ -1069,8 +1124,36 @@ def next_target(costmap: Any, pose: Any, state: ExploreState, *,
if nearest < tuning.revisit_radius_m:
score *= (nearest / tuning.revisit_radius_m) ** _REVISIT_FADE_POWER
+ scored.append((cluster, score, cost))
+
+ # --- the goal cap (Tuning.max_goal_path_m) -----------------------------
+ # Which clusters compete, by where they lie against the cap:
+ # a SAFE cluster within it the ones within it compete; every one
+ # beyond it waits for this decision
+ # only PROBES within it they compete with the SAFE clusters
+ # beyond it, under the probe penalty; the
+ # probes beyond it wait
+ # nothing within it every cluster beyond it competes: the cap
+ # never ends a run with frontiers in reach
+ cap = tuning.max_goal_path_m
+ beyond = [cap > 0 and cost > cap for _, _, cost in scored]
+ n_beyond_cap = sum(beyond)
+ within = [entry for entry, out in zip(scored, beyond) if not out]
+ if any(not cluster.probe for cluster, _, _ in within):
+ pool = within
+ elif within:
+ pool = [entry for entry, out in zip(scored, beyond) if not out or not entry[0].probe]
+ else:
+ pool = scored
+
+ best: Cluster | None = None
+ best_score = -math.inf
+ best_cost = math.inf
+ for cluster, score, cost in pool:
if score > best_score:
best, best_score, best_cost = cluster, score, cost
+ # The goal lies beyond the cap: nothing safe was within it.
+ beyond_cap = best is not None and cap > 0 and best_cost > cap
if best is None:
# Clusters exist but none is reachable from where the body can stand.
@@ -1087,9 +1170,10 @@ def next_target(costmap: Any, pose: Any, state: ExploreState, *,
path_cost_m=best_cost, info_cells=best.size, info_gain=best.gain,
centroid_xy=best.centroid_xy, look_at_xy=best.look_at_xy,
on_frontier=best.on_frontier, probe=best.probe,
- in_sight=best.in_sight,
+ in_sight=best.in_sight, beyond_cap=beyond_cap,
n_clusters=len(clusters), n_excluded=n_blocked,
- n_already_seen_from=n_seen_from, n_on_the_map=on_the_map)
+ n_already_seen_from=n_seen_from, n_outside_radius=n_outside,
+ n_beyond_cap=n_beyond_cap, n_on_the_map=on_the_map)
# ===========================================================================
@@ -1137,6 +1221,9 @@ if HAVE_DIMOS: # pragma: no cover - needs the dimOS stack
footprint_clear_m: float = DEFAULT_TUNING.footprint_clear_m
observed_radius_m: float = DEFAULT_TUNING.observed_radius_m
forward_bonus: float = DEFAULT_TUNING.forward_bonus
+ distance_exponent: float = DEFAULT_TUNING.distance_exponent
+ max_goal_path_m: float = DEFAULT_TUNING.max_goal_path_m
+ explore_radius_m: float = DEFAULT_TUNING.explore_radius_m
revisit_radius_m: float = DEFAULT_TUNING.revisit_radius_m
failed_goal_radius_m: float = DEFAULT_TUNING.failed_goal_radius_m
failed_goal_moved_m: float = DEFAULT_TUNING.failed_goal_moved_m
@@ -1191,6 +1278,9 @@ if HAVE_DIMOS: # pragma: no cover - needs the dimOS stack
footprint_clear_m=self.config.footprint_clear_m,
observed_radius_m=self.config.observed_radius_m,
forward_bonus=self.config.forward_bonus,
+ distance_exponent=self.config.distance_exponent,
+ max_goal_path_m=self.config.max_goal_path_m,
+ explore_radius_m=self.config.explore_radius_m,
revisit_radius_m=self.config.revisit_radius_m,
failed_goal_radius_m=self.config.failed_goal_radius_m,
failed_goal_moved_m=self.config.failed_goal_moved_m,
@@ -1221,6 +1311,10 @@ if HAVE_DIMOS: # pragma: no cover - needs the dimOS stack
def _run_exploration_loop(self) -> None: # type: ignore[override]
self._state = ExploreState()
state = self._state
+ tuning = self._tuning
+ logger.info(f"exploration start: distance exp {tuning.distance_exponent:g}, "
+ f"cap {tuning.max_goal_path_m:g} m, radius {tuning.explore_radius_m:g} m "
+ "(0 = no limit; the radius is centred on the first pose)")
while self.exploration_active and not self.stop_event.is_set():
if self.latest_costmap is None or self.latest_odometry is None:
self.stop_event.wait(0.5)
@@ -1228,11 +1322,13 @@ if HAVE_DIMOS: # pragma: no cover - needs the dimOS stack
costmap: OccupancyGrid = self.latest_costmap
t0 = time.perf_counter()
- target = next_target(costmap, self.latest_odometry, state, tuning=self._tuning)
+ target = next_target(costmap, self.latest_odometry, state, tuning=tuning)
elapsed_ms = (time.perf_counter() - t0) * 1000.0
if target is None:
- logger.info(f"exploration complete: no reachable frontier left "
+ within = (f" within {tuning.explore_radius_m:g} m of the start"
+ if tuning.explore_radius_m > 0 else "")
+ logger.info(f"exploration complete: no reachable frontier left{within} "
f"({state.targets_issued} targets, {elapsed_ms:.0f} ms)")
# said on the bus BEFORE the loop exits: consumers learn the
# end at this instant, not whenever someone notices the
@@ -1288,7 +1384,8 @@ if HAVE_DIMOS: # pragma: no cover - needs the dimOS stack
self.goal_request.publish(goal)
logger.info(
f"goal {state.targets_issued}: ({goal.position.x:.2f}, {goal.position.y:.2f}) "
- f"{getattr(target, 'path_cost_m', float('nan')):.1f} m away, "
+ f"{getattr(target, 'path_cost_m', float('nan')):.1f} m away"
+ f"{' (beyond the cap: nothing safe within it)' if getattr(target, 'beyond_cap', False) else ''}, "
f"{getattr(target, 'info_cells', 0)} frontier cells, "
f"{getattr(target, 'n_clusters', 0)} clusters, chosen in {elapsed_ms:.0f} ms")
@@ -1336,6 +1433,7 @@ if HAVE_DIMOS: # pragma: no cover - needs the dimOS stack
return {"visited": list(self._state.visited),
"failed": list(self._state.failed),
"heading": self._state.heading,
+ "anchor": self._state.anchor,
"targets_issued": self._state.targets_issued,
"last_directive": self._state.last_directive}
diff --git a/tools/moss-fly.sh b/tools/moss-fly.sh
index f26671a..eb204e8 100755
--- a/tools/moss-fly.sh
+++ b/tools/moss-fly.sh
@@ -68,6 +68,11 @@ if [ "${MOSS_PULSE_MS:-0}" != "0" ]; then export MOSS_RAMP_MS="${MOSS_RAMP_MS:-1
export MOSS_STATE_DIR="${MOSS_STATE_DIR:-$HOME/.local/state/moss}"
export MOSS_RECORD="${MOSS_RECORD:-1}"
export MOSS_CAMERA="${MOSS_CAMERA:-1}"
+# the explorer stays within this distance of where exploration started: 4 m = one room
+# (the rover does not go through a door it was not meant to take); 0 = no limit, for
+# open ground. The other explorer knobs (MOSS_GOAL_MAX_M, MOSS_EXPLORE_DISTANCE_EXP)
+# keep their code defaults: see docs/cockpit.md
+export MOSS_EXPLORE_RADIUS_M="${MOSS_EXPLORE_RADIUS_M:-4}"
NERF_SPEED="${MOSS_NERF_SPEED:-0.5}"
COCKPIT_PORT="${MOSS_COCKPIT_PORT:-8904}"
PREFLIGHT_JSON="$MOSS_STATE_DIR/preflight.json" # served by the cockpit as /preflight.json
diff --git a/tools/moss_cockpit.py b/tools/moss_cockpit.py
index d36313b..7f98275 100644
--- a/tools/moss_cockpit.py
+++ b/tools/moss_cockpit.py
@@ -27,7 +27,9 @@ Endpoints (all Cache-Control: no-store; a failing request never kills the server
GET /state.json stack, pose, topic rates, base, nav, recording, system
GET /map.png /map_meta latest /global_costmap as a PNG + the pixel <-> metre contract
GET /scan.json latest lidar points, world frame (fallback: lidar frame), and
- apart the depth camera's obstacle points the same cloud carries
+ apart the depth camera's obstacle points the same cloud carries;
+ plus the pose read at the request, as /state.json's (the page
+ polls the scan at 3 Hz, so its robot marker moves at 3 Hz)
GET /path.json planner path
GET /log.json?n=40 tail of the running stack's main.jsonl
GET /preflight.json the last saved flight check
@@ -396,6 +398,7 @@ def base_view(t: dict, age_s: float | None) -> dict:
mv = t.get("bus_mV")
volts = round(mv / 1000.0, 2) if isinstance(mv, (int, float)) else None
mode = t.get("mode")
+ stalled, stalls = t.get("stalled"), t.get("stall_count")
return {
"fw": t.get("fw"), "driver": t.get("driver"),
"mode": mode, "mode_name": MODE_NAMES.get(mode, "unknown") if mode is not None else None,
@@ -406,6 +409,10 @@ def base_view(t: dict, age_s: float | None) -> dict:
"ticks": t.get("ticks"), "target_pct": t.get("target_pct"), "output_pct": t.get("output_pct"),
"ramp_ms": t.get("ramp_ms"),
"firmware_age_s": t.get("firmware_age_s"), "mock": t.get("mock"),
+ # the base's stall guard (a commanded track whose encoder did not move for 1 s: stop,
+ # counted); telemetry published before the guard existed has neither key -> None
+ "stalled": None if stalled is None else bool(stalled),
+ "stall_count": stalls if isinstance(stalls, int) and not isinstance(stalls, bool) else None,
"age_s": None if age_s is None else round(age_s, 2),
}
@@ -983,6 +990,15 @@ class Cockpit:
def launch(self) -> dict:
return self.launcher.status()
+ def scan_doc(self) -> dict:
+ """/scan.json: the latest scan (an empty one without a cloud) plus the pose read now,
+ the same document /state.json gives under "pose". A copy: the cached scan never
+ carries a pose, so a scan served again from the cache still gets the newest pose."""
+ doc = self.scan()
+ doc = dict(doc) if doc is not None else {"frame": None, "stamp": None, "points": []}
+ doc["pose"] = self.pose()
+ return doc
+
# --- live: the stack's bus ----------------------------------------------------------
@@ -1046,6 +1062,9 @@ class LiveCockpit(Cockpit):
return {"x": round(pose["x"], 3), "y": round(pose["y"], 3), "yaw": round(pose["yaw"], 4),
"age_s": round(now - mono, 2)}
+ def pose(self) -> dict | None:
+ return self._pose(time.monotonic())
+
def _base(self, now: float) -> dict | None:
t, mono = self.bus.decoded("base_telemetry", lambda raw: json.loads(decode_string(raw)))
if not isinstance(t, dict):
@@ -1601,11 +1620,10 @@ class DemoCockpit(Cockpit):
"reason": "drive" if drive else "boot", "bus_mV": int(volts * 1000), "ina_ok": True,
"ticks": [int(w.travelled * 1000), int(w.travelled * 1000)],
"target_pct": [pct, pct], "output_pct": [pct, pct], "ramp_ms": [5, 5],
- "firmware_age_s": 0.1, "mock": True}
+ "firmware_age_s": 0.1, "mock": True, "stalled": False, "stall_count": 0}
return {
"ts": now, "mode": self.mode, "stack": stack,
- "pose": ({"x": round(w.x, 3), "y": round(w.y, 3), "yaw": round(w.yaw, 4), "age_s": 0.05}
- if running else None),
+ "pose": self._pose_doc(),
"topics": topics,
"base": base_view(telemetry, 0.3) if running else None,
"nav": {"exploring": self.exploring and running, "explore_done": self.explore_done,
@@ -1620,6 +1638,17 @@ class DemoCockpit(Cockpit):
"launch": {"running": False, "action": self._launch_action},
}
+ def _pose_doc(self) -> dict | None:
+ w = self.world
+ return ({"x": round(w.x, 3), "y": round(w.y, 3), "yaw": round(w.yaw, 4), "age_s": 0.05}
+ if self.stack["running"] else None)
+
+ def pose(self) -> dict | None:
+ """The pose as of the last tick: scan_doc ticks through scan(), so the scan's
+ points and this pose come from the same instant."""
+ with self._lock:
+ return self._pose_doc()
+
def map(self):
self._tick()
with self._lock:
@@ -1809,8 +1838,7 @@ class Handler(BaseHTTPRequestHandler):
else:
self._json(200, got[1])
elif path == "/scan.json":
- doc = self.cockpit.scan()
- self._json(200, doc if doc is not None else {"frame": None, "stamp": None, "points": []})
+ self._json(200, self.cockpit.scan_doc())
elif path == "/path.json":
self._json(200, self.cockpit.path())
elif path == "/log.json":
diff --git a/tools/moss_cockpit/app.js b/tools/moss_cockpit/app.js
index 0775847..a120cb6 100644
--- a/tools/moss_cockpit/app.js
+++ b/tools/moss_cockpit/app.js
@@ -4,6 +4,7 @@
* field has no internet). Contract: tools/moss_cockpit.py.
*
* GET /state.json 1 Hz GET /scan.json 3 Hz GET /path.json 1 Hz
+ * (both state and scan carry the pose: the robot marker takes the younger one, 3 Hz)
* GET /map_meta 1 Hz, then /map.png only when map_meta.stamp changed
* GET /log.json 0.5 Hz GET /preflight.json on load and after a check
* GET /launch.json while a stack command runs
@@ -23,15 +24,16 @@ var EP_FULL_S = 300; // the bottom progress line is full after 5 min of
var RUN_FULL_S = 1800; // ... or after 30 min of run when no episode records
var CAM_RETRY_MS = 3000; // reconnect the MJPEG stream this long after it ended or failed, forever
var CAM_GRACE_MS = 6000; // a stream younger than this is not judged dead (first frame wait + a state poll)
+var STALL_HOLD_S = 4; // the STALLED badge stays up at least this long after the stall count goes up
var DEPTH_COLOR = "rgba(255,193,94,.95)"; // amber: depth-camera obstacles, apart from the mint lidar scan
var S = {
online: false, state: null,
- meta: null, mapImg: null, mapStamp: null, scan: null, path: null,
+ meta: null, mapImg: null, mapStamp: null, scan: null, scanAt: 0, path: null,
preflight: null, launchBusy: false, launchAction: null,
view: { scale: 40, x: -3, y: 3 }, fitted: false,
pendingGoal: null, camPaused: false, camOk: false, camAt: 0, camLost: null, pfAll: false,
- stateAt: 0
+ stateAt: 0, stallLatch: { count: null, until: 0 }
};
function $(id) { return document.getElementById(id); }
@@ -190,9 +192,37 @@ function setTrack(barId, valId, v) {
setText(valId, (typeof v === "number") ? String(Math.round(v)) : "--");
}
+// The base's stall guard (a commanded track whose encoder did not move for 1 s stops it) sets
+// `stalled` and adds one to `stall_count`. The base clears `stalled` on its next accepted
+// command, which can come before the page's 1 Hz read of the 2 Hz telemetry, so the badge is
+// latched on the counter: when stall_count goes up, the badge holds STALL_HOLD_S from the
+// moment the page sees it, whatever `stalled` says. latch = {count, until}: the last count
+// seen and the page time (ms) the hold ends. The first count the page sees, and a count that
+// went down (a new run), only set the reference, with no hold. A missing count (no telemetry,
+// or telemetry from before the guard) keeps the last one, so a stall across a gap still holds.
+function stallLatch(latch, count, nowMs) {
+ var last = latch ? latch.count : null, until = latch ? latch.until : 0;
+ if (typeof count !== "number" || !isFinite(count)) return { count: last, until: until };
+ if (typeof last === "number" && count > last) until = nowMs + STALL_HOLD_S * 1000;
+ return { count: count, until: until };
+}
+
+// The STALLED badge shows while `stalled` is true or the latch holds (holdUntil, page ms);
+// the row counts the stalls of the run. Telemetry from before the guard carries neither key:
+// no badge, "--".
+function stallView(b, holdUntil, nowMs) {
+ return { badge: (!!b && b.stalled === true) || nowMs < holdUntil,
+ count: b && typeof b.stall_count === "number" && isFinite(b.stall_count) ? String(b.stall_count) : "--" };
+}
+
function renderBase() {
var b = S.state && S.state.base;
var sec = $("mod-base");
+ var now = Date.now();
+ S.stallLatch = stallLatch(S.stallLatch, b ? b.stall_count : null, now);
+ var stall = stallView(b, S.stallLatch.until, now);
+ $("b-stall").hidden = !stall.badge;
+ setText("b-stalls", stall.count);
if (!b) {
setText("base-title", S.online ? "No telemetry." : "Cockpit offline.");
setText("b-volt", "--"); setText("b-pct", "--"); meter("b-meter", 0);
@@ -490,7 +520,27 @@ function drawGrid() {
ctx.stroke();
}
-function pose() { return S.state && S.state.pose; }
+// The robot's pose comes with /state.json (1 Hz) and with /scan.json (3 Hz). Each age_s is
+// the server's at its answer; the time since that answer (ms in *At) is added, and the younger
+// pose (the more recent odometry message) is the one drawn. A pose of null says "no pose"
+// (a stopped stack, a new run): from the later answer it hides the marker, whatever the other
+// answer still holds; undefined is "no answer yet". Returns {x, y, yaw, age_s} or null.
+function freshestPose(statePose, stateAt, scanPose, scanAt, nowMs) {
+ function aged(p, at) {
+ if (!p || typeof p.x !== "number" || typeof p.y !== "number") return null;
+ var age = (typeof p.age_s === "number" ? p.age_s : 0) + Math.max(0, (nowMs - at) / 1000);
+ return { x: p.x, y: p.y, yaw: p.yaw, age_s: age };
+ }
+ if (statePose === null && stateAt >= scanAt) return null;
+ if (scanPose === null && scanAt > stateAt) return null;
+ var a = aged(statePose, stateAt), b = aged(scanPose, scanAt);
+ return b && (!a || b.age_s < a.age_s) ? b : a;
+}
+
+function pose() {
+ return freshestPose(S.state ? S.state.pose : undefined, S.stateAt,
+ S.scan ? S.scan.pose : undefined, S.scanAt, Date.now());
+}
// key: "points" (lidar returns, the default) or "camera" (depth-camera obstacle points)
function scanWorld(key) {
@@ -566,7 +616,7 @@ function draw() {
if (nav && nav.goal) ring(nav.goal.x, nav.goal.y, false);
if (S.pendingGoal) ring(S.pendingGoal.x, S.pendingGoal.y, true);
- // pose: white triangle pointing along yaw
+ // pose: white triangle pointing along yaw (the younger of the two poses, freshestPose)
var p = pose();
if (p && typeof p.x === "number") {
var cx = sx(p.x), cy = sy(p.y), a = -(p.yaw || 0), L = 15, B = 8;
@@ -617,7 +667,7 @@ function pollMeta() {
function pollScan() {
return fetchJSON("/scan.json").then(function (d) {
- if (d && !d.__missing && d.points) { S.scan = d; requestDraw(); }
+ if (d && !d.__missing && d.points) { S.scan = d; S.scanAt = Date.now(); requestDraw(); }
}, function () {});
}
diff --git a/tools/moss_cockpit/index.html b/tools/moss_cockpit/index.html
index 206400d..01ccddd 100644
--- a/tools/moss_cockpit/index.html
+++ b/tools/moss_cockpit/index.html
@@ -133,6 +133,10 @@
.tbar > i.rev { background: var(--moss-white); }
.tracks .mid { text-align: center; }
.tracks .mid .kicker { font-size: 11.5px; }
+ /* STALLED, next to the mode: the attention colour, outlined (the base stopped itself) */
+ .badge { display: inline-block; margin-right: 8px; padding: 1px 6px; border-radius: 4px; font-weight: 600;
+ font-size: 11.5px; letter-spacing: .1em; line-height: 1.3; vertical-align: 1px;
+ color: var(--ui-attention); box-shadow: inset 0 0 0 1.5px currentColor; }
/* ---- map pane ---- */
#map-wrap { position: relative; flex: 1 1 auto; min-height: 320px; overflow: hidden; }
@@ -318,7 +322,8 @@
<div class="track r"><div class="tbar"><i id="t-r"></i></div><div class="lbl"><b id="t-rv" class="num">0</b><span>RIGHT %</span></div></div>
</div>
<dl class="kv">
- <dt>Mode</dt><dd id="b-mode">--</dd>
+ <dt>Mode</dt><dd><span class="badge" id="b-stall" hidden>STALLED</span><span id="b-mode">--</span></dd>
+ <dt>Stalls</dt><dd id="b-stalls">--</dd>
<dt>Ticks L / R</dt><dd id="b-ticks">--</dd>
<dt>Firmware</dt><dd id="b-fw">--</dd>
<dt>Telemetry age</dt><dd id="b-age">--</dd>