Repository navigation
Expand file tree
/
Copy pathexploration_loop.py
More file actions
842 lines (744 loc) · 38.4 KB
/
Copy pathexploration_loop.py
File metadata and controls
842 lines (744 loc) · 38.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
"""Main autonomous exploration orchestrator.
Wires together frontier detection, goal selection, path planning, waypoint
navigation, SLAM, and OctoMap to drive a robot through an unknown
environment without human input.
The loop repeats: sense -> detect frontiers -> select goal -> plan path
-> navigate -> until no reachable frontiers remain or max steps reached.
Supports two modes:
- run(): Full autonomous loop for single-robot exploration.
- step_once(): Single-step mode for multi-robot coordination (Coordinator calls).
"""
import logging
import time
from itertools import islice
from dataclasses import dataclass
from typing import Callable, TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from src.slam.protocol import SLAMProtocol
from src.slam.octomap_builder import OctoMapBuilder
from src.bridge.sensor_types import BridgeProtocol, SensorFrame
@dataclass
class StepMetrics:
"""Metrics returned from ExplorationLoop.step_once()."""
frontiers: int
coverage: float
terminated: bool
voxels: int
rescan_triggered: bool
error: str | None = None
from src.exploration.config import ExplorationConfig
from src.exploration.blocked_navigation import BlockedNavigation
from src.exploration.coverage_tracker import CoverageTracker, ExplorationResult
from src.exploration.frontier_detector import FrontierDetector
from src.exploration.floor_filter import FloorFilter, FloorTracker
from src.exploration.goal_selector import GoalSelector
from src.exploration.occupancy_grid import project_voxels_to_2d
from src.exploration.path_planner import PathPlanner
from src.exploration.progress_monitor import ProgressMonitor
from src.exploration.route_preview import preview_route, preview_recovery_endpoint
from src.exploration.skills.executor import SkillExecutionResult, SkillExecutor
from src.exploration.skills.library import create_default_skill_registry
from src.exploration.skills.recorder import SkillOutcomeRecorder
from src.exploration.skills.selector import GatedSkillSelector, SkillSelectorConfig
from src.exploration.skills.state import SkillStateEncoder
from src.exploration.skills.types import SkillOutcomeVector, SkillTermination
from src.control.waypoint_runner import WaypointRunner
logger = logging.getLogger(__name__)
class StuckRecovery:
"""Reverse-then-turn recovery when robot is physically stuck.
When triggered: first reverses for a simulated-time interval to back away
from the obstacle, then turns through a fixed angle with randomized direction.
This gets the robot clear of furniture/walls before choosing a new heading.
"""
def __init__(
self,
turn_angle: float = np.pi * 0.75, # 135 degrees -- bigger turn to escape corners
angular_speed: float = 1.5,
reverse_speed: float = 1.0, # faster reverse
reverse_duration_s: float = 0.25,
rng: np.random.Generator | None = None,
) -> None:
self._turn_angle = turn_angle
self._angular_speed = angular_speed
self._reverse_speed = reverse_speed
if any(not np.isfinite(v) or v <= 0 for v in
(turn_angle, angular_speed, reverse_speed, reverse_duration_s)):
raise ValueError("Recovery parameters must be finite and positive")
self._reverse_duration_s = reverse_duration_s
self._rng = rng
self._remaining_turn: float = 0.0
self._remaining_reverse: float = 0.0
self._active: bool = False
self._phase: str = "idle" # "reverse" or "turn"
def trigger(self) -> None:
"""Start a reverse-then-turn recovery."""
self._remaining_reverse = self._reverse_duration_s
direction = 1.0 if (self._rng.random() if self._rng is not None else np.random.random()) > 0.5 else -1.0
self._remaining_turn = self._turn_angle * direction
self._active = True
self._phase = "reverse"
def step(self, dt: float) -> tuple[float, float, float] | None:
"""Get recovery velocity command (vx, vy, omega), or None if complete.
Returns:
(vx, vy, omega) while recovery is active, None when done.
"""
if not np.isfinite(dt) or dt <= 0:
raise ValueError("Recovery interval must be finite and positive")
if not self._active:
return None
if self._phase == "reverse":
duration = min(dt, self._remaining_reverse)
self._remaining_reverse = max(0.0, self._remaining_reverse - dt)
if self._remaining_reverse <= 1e-12:
self._phase = "turn"
return (-self._reverse_speed * duration / dt, 0.0, 0.0)
if abs(self._remaining_turn) <= 1e-12:
self._active = False
self._phase = "idle"
return None
# Scale the last command to the remaining angle, avoiding overshoot
# and sign oscillation for coarse or irregular sensor intervals.
turn = float(np.clip(self._remaining_turn / dt,
-self._angular_speed, self._angular_speed))
self._remaining_turn -= turn * dt
return (0.0, 0.0, turn)
@property
def is_active(self) -> bool:
return self._active
def cancel(self) -> None:
"""Cancel an unsafe proposal; a clearance rejection is not progress."""
self._active = False
self._phase = "idle"
self._remaining_turn = self._remaining_reverse = 0.
class ExplorationLoop:
"""Autonomous exploration loop orchestrator.
Manages the full exploration cycle: sense the environment via bridge/SLAM,
detect frontiers, select goals, plan paths, and navigate until termination.
Supports two operating modes:
- run(): Full lifecycle -- calls bridge.start/step/set_velocity.
- step_once(): Per-frame processing -- caller manages bridge lifecycle.
Args:
bridge: Simulation bridge providing start/step/set_velocity/stop.
slam: SLAM pipeline for pose estimation and cloud accumulation.
octomap: OctoMap builder for voxel occupancy tracking.
config: Exploration configuration (uses defaults if None).
"""
def __init__(
self,
bridge: BridgeProtocol,
slam: "SLAMProtocol",
octomap: "OctoMapBuilder",
config: ExplorationConfig | None = None,
streaming_viz: object | None = None,
intrinsics: object | None = None,
recovery_rng: np.random.Generator | None = None,
frame_dt: float | None = None,
):
self._bridge = bridge
self._slam = slam
self._octomap = octomap
self._config = config or ExplorationConfig()
from src.control.motion_clearance import MotionClearanceGuard
self._motion_guard = MotionClearanceGuard(self._config)
self._blocked = BlockedNavigation(self._config)
self._recovery_checks = {}
self._route_checks = []
self._recovery_route_checks = {}
self._route_goals = []
self._last_observation_time = None
self._navigation_pose = np.eye(4)
self._execution_radius = self._config.planning_radius(0., self._config.voxel_resolution)
self._streaming_viz = streaming_viz
self._intrinsics = intrinsics
self._floor_filter = FloorTracker(FloorFilter(
camera_height_m=self._config.floor_camera_height_m,
height_tolerance_m=self._config.floor_height_tolerance_m,
distance_tolerance_m=self._config.floor_distance_tolerance_m,
))
self._observed_floor_cells: set[tuple[int, int]] = set()
self._frontier_detector = FrontierDetector(
resolution=self._config.voxel_resolution,
min_cluster_size=self._config.min_cluster_size,
)
self._goal_selector = GoalSelector(strategy=self._config.goal_strategy)
self._path_planner = PathPlanner(allow_unknown=False, clearance_radius=self._config.planning_radius(
0., self._config.voxel_resolution))
self._coverage_tracker = CoverageTracker(
voxel_resolution=self._config.voxel_resolution,
)
# Per-step state (shared between run() and step_once())
self._robot_positions: list[np.ndarray] = []
self._current_waypoint_runner: WaypointRunner | None = None
self._bootstrap_complete = False
self._navigation_exhausted = False
self._last_rescan_pos = np.zeros(3, dtype=np.float64)
self._last_voxel_count = 0
self._progress = ProgressMonitor(self._config.stuck_timeout_s,
self._config.stuck_distance_m,
self._config.stuck_angle_rad)
self._last_command = (np.zeros(2), 0.0)
if frame_dt is not None and (not np.isfinite(frame_dt) or frame_dt <= 0):
raise ValueError("Frame interval must be finite and positive")
self._frame_dt = frame_dt
self._previous_sim_time: float | None = None
self._planning_attempts: list[tuple[str, bool]] = []
self._selection_latency_ms: list[float] = []
self._planning_sequence = 0
self._goal_id: str | None = None
self._last_coverage = 0.0
self._last_bbox_coverage = 0.0
self._last_frontier_count = 0
self.last_tracking_status: str = "ok"
self._skill_registry = create_default_skill_registry() if self._config.skill_learning_enabled else None
self._skill_selector = (
GatedSkillSelector(
SkillSelectorConfig(
min_confidence=self._config.skill_learning_min_confidence,
min_dwell_steps=self._config.skill_learning_min_dwell_steps,
max_failures_before_baseline=self._config.skill_learning_max_failures_before_baseline,
)
)
if self._config.skill_learning_enabled
else None
)
self._skill_executor = SkillExecutor() if self._config.skill_learning_enabled else None
self._skill_state_encoder = SkillStateEncoder() if self._config.skill_learning_enabled else None
self._skill_recorder = (
SkillOutcomeRecorder(run_id="local", selector_version="gated-v1", skill_library_version="default-v1")
if self._config.skill_learning_enabled
else None
)
self._last_skill_trace_id: str | None = None
@property
def frontier_detector(self) -> FrontierDetector:
return self._frontier_detector
@property
def measurement_state(self) -> dict:
"""Detached decision diagnostics; no evaluator state enters navigation."""
return {"recovering": self._blocked.state == "recovering",
"navigation": {**self._blocked.snapshot(), "recovery_checks": dict(self._recovery_checks),
"route_checks": list(self._route_checks),
"recovery_route_checks": dict(self._recovery_route_checks)},
"navigation_exhausted": self._navigation_exhausted,
"goal_id": self._goal_id if self._current_waypoint_runner is not None
and not self._current_waypoint_runner.is_complete else None,
"planning_attempts": tuple(self._planning_attempts),
"selection_latency_ms": tuple(self._selection_latency_ms),
"tracking_status": self.last_tracking_status,
"motion_clearance": {"reason": self._motion_guard.last.reason,
"scale": self._motion_guard.last.scale,
"clearance_m": self._motion_guard.last.clearance_m,
"stopping_clear": self._motion_guard.last.stopping_clear,
"radius_m": self._execution_radius}}
@property
def slam_backend_type(self) -> type:
return type(self._slam)
@property
def observed_floor_xy(self) -> np.ndarray:
"""Observed floor supports planning free space, never evaluation coverage."""
cells = np.asarray(sorted(self._observed_floor_cells), dtype=float).reshape(-1, 2)
return (cells + .5) * self._config.voxel_resolution
def planning_grid(self, occupied=None):
"""Use the same observed obstacle/floor map for navigation and coordination."""
return project_voxels_to_2d(
self._octomap.get_occupied_voxels() if occupied is None else occupied,
self._config.voxel_resolution, self._config.z_min, self._config.z_max,
robot_positions=np.array(self._robot_positions), observed_free_xy=self.observed_floor_xy,
)
@property
def frontier_resolution(self) -> float:
return self._frontier_detector._resolution
@property
def last_coverage(self) -> float:
return self._coverage_tracker._last_coverage
@property
def config(self) -> ExplorationConfig:
return self._config
def set_waypoint_target(self, waypoints: list[np.ndarray]) -> None:
"""Set a new waypoint sequence for the robot to follow."""
self._current_waypoint_runner = WaypointRunner(
waypoints,
linear_speed=self._config.linear_speed,
angular_speed=self._config.angular_speed,
heading_tolerance_rad=self._config.forward_heading_tolerance_rad,
)
self._bootstrap_complete = True
self._navigation_exhausted = False
self._blocked = BlockedNavigation(self._config)
self._goal_id = ",".join(format(float(v), ".9g") for v in waypoints[-1])
def skill_trace_jsonl(self) -> str:
"""Return skill-learning decision/outcome traces as JSONL when enabled."""
if self._skill_recorder is None:
return ""
return self._skill_recorder.to_jsonl()
# ------------------------------------------------------------------
# Extracted helpers (called only from step_once)
# ------------------------------------------------------------------
def _update_slam(self, frame: SensorFrame) -> tuple[np.ndarray, np.ndarray]:
"""Process frame through SLAM and OctoMap.
Returns:
(pose, current_pos) -- 4x4 pose matrix and (3,) position vector.
"""
result = self._slam.process_frame(frame)
self.last_tracking_status: str = result.tracking_status.value
self.last_slam_metrics: dict = result.metrics
# Emit crash_fallback WS message when a subprocess backend returns LOST
if (result.tracking_status.value == "lost"
and hasattr(self._slam, '_bridge')
and self._streaming_viz is not None
and hasattr(self._streaming_viz, '_message_queue')):
backend_name = type(self._slam).__name__
self._streaming_viz._message_queue.append({
"type": "crash_fallback",
"payload": {
# Phase 2 (DET-MODELS-05): backward-compat default.
# Phase 5 (DET-MODELS-06) adds a "detector" emission path.
"subsystem": "slam",
"crashed_backend": backend_name,
"fallback_backend": "icp",
},
})
# Actually swap to ICP backend so exploration continues
try:
from src.slam.registry import SLAMRegistry
import src.slam.backends # noqa: F401
fallback_kwargs = {}
if self._intrinsics is not None:
fallback_kwargs["intrinsics"] = self._intrinsics
self._slam = SLAMRegistry.create("icp", **fallback_kwargs)
logger.info("Swapped crashed %s to ICP fallback", backend_name)
except Exception as exc:
logger.error("Failed to create ICP fallback: %s", exc)
pose = result.pose
current_pos = pose[:3, 3].copy()
# Insert this frame's cloud directly into OctoMap (not the global accumulator)
if len(result.points) > 0:
if self.last_tracking_status == "ok":
self._last_observation_time = frame.sim_time
points = result.points
if self._config.ground_filter:
acquiring_floor = self._floor_filter.plane is None
floor = self._floor_filter.mask(points, current_pos)
if (acquiring_floor or self._floor_filter.reacquired) and self._floor_filter.plane is not None:
normal, offset = self._floor_filter.plane
self._octomap.remove_plane_inliers(
normal, offset, self._config.floor_distance_tolerance_m)
cells = np.unique(np.floor(points[floor, :2] / self._config.voxel_resolution).astype(int), axis=0)
self._observed_floor_cells.update(map(tuple, cells))
points = points[~floor]
if len(points):
self._octomap.insert_scan(points, current_pos)
return pose, current_pos
def _check_stuck(
self, step: int, pose: np.ndarray, sim_time: float,
) -> None:
"""Enter the bounded blocked policy when accepted motion makes no progress."""
if self._navigation_exhausted:
# Includes scans that raised before step_once could record a stop
# command. An invalid route must not trigger motion via recovery.
self._progress.reset()
self._last_command = (np.zeros(2), 0.0)
return
if self._progress.update(pose, sim_time, *self._last_command):
logger.warning("[Step %d] No commanded progress for %.2f s. Blocking.",
step, self._config.stuck_timeout_s)
self._blocked.block("commanded_no_progress", sim_time)
self._progress.reset()
self._current_waypoint_runner = None
self._goal_id = None
def _should_rescan(
self, step: int, current_pos: np.ndarray, force_rescan: bool,
) -> bool:
"""Evaluate whether a frontier rescan should be triggered."""
config = self._config
# Don't rescan in first 30 steps -- drive forward to build initial
# map data before frontier detection has enough to work with
min_scan_step = 30
should_rescan = force_rescan and step >= min_scan_step
if not should_rescan and step >= min_scan_step:
dist_from_last_scan = float(np.linalg.norm(current_pos - self._last_rescan_pos))
voxel_delta = self._octomap.num_occupied - self._last_voxel_count
waypoint_done = (
self._current_waypoint_runner is None
or self._current_waypoint_runner.is_complete
)
if (dist_from_last_scan > config.rescan_distance_m
or voxel_delta > config.rescan_voxel_delta
or waypoint_done):
should_rescan = True
return should_rescan
def _evaluate_frontiers(
self,
current_pos: np.ndarray,
pose: np.ndarray,
score_fn: Callable[[np.ndarray], float] | None,
guard_state: dict | None = None,
) -> tuple[int, bool]:
"""Detect frontiers, select a goal, and plan a path.
Returns:
(frontier_count, terminated) -- number of frontiers found and
whether exploration should terminate.
"""
# A scan replaces the route. Invalidate it before any operation that
# might fail, and stay idle unless this scan installs a valid new path.
self._bootstrap_complete = True
self._navigation_exhausted = True
self._current_waypoint_runner = None
self._goal_id = None
self._route_goals = []
config = self._config
occupied = self._octomap.get_occupied_voxels()
grid_2d = self.planning_grid(occupied)
frontiers = self._frontier_detector.detect(
occupied,
grid_2d=grid_2d,
)
frontier_count = len(frontiers)
terminated = False
effective_score_fn = score_fn
skill_execution: SkillExecutionResult | None = None
selected_skill_id: str | None = None
path: list[np.ndarray] | None = None
if (self._skill_registry is not None
and self._skill_selector is not None
and self._skill_executor is not None
and self._skill_state_encoder is not None
and self._skill_recorder is not None):
state = self._skill_state_encoder.encode(
coverage_pct=self._last_coverage,
previous_coverage_pct=self._last_coverage,
robot_position=current_pos,
frontiers=frontiers,
is_stuck=self._blocked.since is not None,
no_progress_steps=self._progress.no_progress_steps,
blocked_path_count=0,
recent_skill_ids=(),
recent_termination_reasons=(),
)
proposals, gates = self._skill_registry.proposals_for(state)
decision = self._skill_selector.select(state, proposals=proposals, gates=gates)
selected_skill_id = decision.selected_skill_id
self._last_skill_trace_id = self._skill_recorder.record_decision(
scenario="local",
seed=0,
robot_ids=(state.robot_id,),
state=state,
gates=gates,
decision=decision,
)
skill_execution = self._skill_executor.apply(decision)
if not self._config.skill_learning_shadow_mode:
effective_score_fn = skill_execution.score_fn if skill_execution.score_fn is not None else score_fn
if not frontiers:
if self._path_planner.start_is_blocked(current_pos, grid_2d):
self._blocked.block("blocked_start", self._previous_sim_time or 0.)
else:
terminated = True
self._blocked.state, self._blocked.reason = "exhausted", "no_frontiers"
self._blocked.since = None
else:
# Cluster centroids rank regions; actual frontier cells are targets.
goal = None
selection_start = time.perf_counter()
reachable = self._path_planner.reachable_mask(current_pos, grid_2d)
candidates = list(islice((candidate for candidate in self._goal_selector.navigation_candidates(
frontiers, pose, grid_2d, reachable, effective_score_fn)
if np.linalg.norm(candidate[:2] - current_pos[:2]) >= config.waypoint_arrival_threshold),
config.planning_candidate_limit))
self._selection_latency_ms.append((time.perf_counter() - selection_start) * 1000)
self._route_goals = candidates
for candidate in candidates:
planned_path = self._path_planner.plan(current_pos, candidate, grid_2d)
self._planning_sequence += 1
self._planning_attempts.append((str(self._planning_sequence), planned_path is not None))
if planned_path is not None:
runner = self._executable_runner(planned_path, guard_state)
if runner is None:
continue
goal, path = candidate, planned_path
break
if goal is None or path is None:
reason = ("blocked_start" if self._path_planner.start_is_blocked(current_pos, grid_2d)
else "no_executable_route" if self._route_checks else "no_reachable_route")
self._blocked.block(reason, self._previous_sim_time or 0.)
else:
self._blocked.installed(pose)
self._goal_id = ",".join(format(float(v), ".9g") for v in goal)
self._current_waypoint_runner = runner
self._last_rescan_pos = current_pos.copy()
self._last_voxel_count = self._octomap.num_occupied
# Update coverage
previous_coverage = self._last_coverage
cov, bbox_cov = self._coverage_tracker.update(
self._octomap.get_occupied_voxels(), frontier_count,
)
if self._skill_recorder is not None and self._last_skill_trace_id:
path_succeeded = path is not None
fallback_used = bool(skill_execution.fallback_used) if skill_execution is not None else True
if fallback_used:
termination = SkillTermination.BASELINE_FALLBACK
elif path_succeeded:
termination = SkillTermination.SUCCESS
else:
termination = SkillTermination.FAILURE
outcome = SkillOutcomeVector(
coverage_gain=max(0.0, cov - previous_coverage),
frontier_delta=0.0,
path_length=float(len(path)) if path is not None else 0.0,
command_effort=0.0,
safety_events=0,
recovery_events=0,
duplicate_coverage_delta=0.0,
connectivity_delta=0.0,
map_quality_delta=0.0,
future_affordance_gain=0.0,
termination=termination,
fallback_used=fallback_used,
)
self._skill_recorder.record_outcome(self._last_skill_trace_id, outcome)
if (self._skill_selector is not None
and selected_skill_id is not None
and selected_skill_id != "baseline"):
self._skill_selector.record_termination(selected_skill_id, termination)
self._last_coverage = cov
self._last_bbox_coverage = bbox_cov
self._last_frontier_count = frontier_count
self._navigation_exhausted = terminated
return frontier_count, terminated
def _executable_runner(self, path, state, *, guard=None, record=True):
"""Try both travel directions within the existing candidate budget."""
options = []
for reverse in (False, True):
runner = WaypointRunner(
path, linear_speed=(min(self._config.linear_speed, self._config.recovery_reverse_speed_mps)
if reverse else self._config.linear_speed),
angular_speed=self._config.angular_speed,
heading_tolerance_rad=self._config.forward_heading_tolerance_rad,
# Frontier members can be only just beyond the rescan exclusion
# radius. A full 30 cm arrival ball would finish those paths
# before useful walking. Approach to one observed map cell;
# this does not alter obstacle inflation or execution clearance.
arrival_threshold=(self._config.waypoint_arrival_threshold if state is None else
min(self._config.waypoint_arrival_threshold, state['grid'].resolution)),
reverse=reverse)
if state is None:
return runner
result = preview_route(self._motion_guard if guard is None else guard, runner, state,
progress_m=self._config.navigation_resume_distance_m)
if record:
self._route_checks.append(dict(goal=np.asarray(path[-1]).tolist(), reverse=reverse,
reason=result.reason, admissible=result.admissible,
translation_m=result.translation_m, steps=result.steps))
if result.admissible:
options.append((result.steps, reverse, runner))
return min(options, key=lambda item: item[:2])[2] if options else None
# ------------------------------------------------------------------
# Main per-step entry point
# ------------------------------------------------------------------
def step_once(
self, frame: SensorFrame, step: int,
score_fn: Callable[[np.ndarray], float] | None = None,
) -> tuple[np.ndarray, float, StepMetrics]:
"""Gate every exploration command, including bootstrap and recovery."""
linear, angular, metrics = self._step_once_proposal(frame, step, score_fn)
decision = self._motion_guard.filter(
linear, angular, **self._guard_state(frame))
if decision.scale == 0 and (np.linalg.norm(linear) > .01 or abs(angular) > .01):
# A rejected route/recovery must not keep issuing the same motion or
# trigger blind reverse from the lack of commanded progress.
self._current_waypoint_runner = None
self._goal_id = None
self._progress.reset()
if decision.reason != "initial_velocity_observation":
self._bootstrap_complete = True
self._blocked.execution_rejections += 1
if self._blocked.state == "recovering":
self._blocked.recovery_outcome = "execution_rejected"
self._blocked.block("execution_" + decision.reason, frame.sim_time)
metrics.terminated = self._navigation_exhausted or self._blocked.state == "failed"
self._last_command = (decision.linear.copy(), float(decision.angular))
return decision.linear, decision.angular, metrics
def _guard_state(self, frame):
return dict(pose=self._navigation_pose, sim_time=frame.sim_time,
observation_time=self._last_observation_time, grid=self.planning_grid(),
radius=self._execution_radius,
calibration_valid=(frame.body_from_camera is not None
and frame.collision_radius_m is not None
and np.isfinite(frame.collision_radius_m) and frame.collision_radius_m > 0),
tracking_ok=self.last_tracking_status == "ok")
def _blocked_proposal(self, frame):
"""Bounded motion choices; preview does not authorize later execution."""
action = self._blocked.next_action(frame.sim_time)
if action == "recover":
# A second attempt prefers a different primitive. Unsupported lateral
# motion is never proposed. No map cells or dimensions are changed.
candidates = [(-self._config.recovery_reverse_speed_mps, 0., 0.),
(0., 0., .5), (0., 0., -.5), (.2, 0., 0.)]
if self._blocked.recoveries > 1:
candidates = candidates[1:] + candidates[:1]
state = self._guard_state(frame)
self._recovery_checks = {}
self._recovery_route_checks = {}
admitted = []
for command in candidates:
result = self._motion_guard.preview(np.array(command[:2]), command[2], **state)
self._recovery_checks[str(command)] = result.reason
if result.scale > 0:
admitted.append(command)
selected = None
for command in admitted:
endpoint, reason = preview_recovery_endpoint(self._motion_guard, command, state)
self._recovery_route_checks[str(command)] = reason
if endpoint is None:
continue
forecast_guard, forecast_state = endpoint
# Four endpoints, at most four goals each, two travel modes.
# The ordinary candidate/retry/deadline limits are unchanged.
planner = PathPlanner(allow_unknown=False, clearance_radius=self._execution_radius)
self._recovery_route_checks[str(command)] = "no_predicted_route"
for goal in self._route_goals[:4]:
path = planner.plan(forecast_state['pose'][:3, 3], goal, state['grid'])
if path is not None and self._executable_runner(
path, forecast_state, guard=forecast_guard, record=False) is not None:
self._recovery_route_checks[str(command)] = "predicted_navigation"
selected = command
break
if selected is not None:
break
if admitted:
# A bounded sensing probe can reveal a new route even when the
# frozen map cannot predict one. It is not labeled an escape.
self._blocked.start_recovery(selected or admitted[0], self._navigation_pose, frame.sim_time)
else:
self._blocked.recovery_outcome = "no_safe_motion"
self._blocked.fail("no_safe_recovery")
if self._blocked.state == "recovering":
command = self._blocked.command
return np.array(command[:2]), command[2]
return np.zeros(2), 0.
def _step_once_proposal(
self,
frame: SensorFrame,
step: int,
score_fn: Callable[[np.ndarray], float] | None = None,
) -> tuple[np.ndarray, float, StepMetrics]:
"""Process one exploration step without owning the bridge lifecycle.
Multi-robot entry point: Coordinator calls this per-robot per-step.
Does NOT call bridge.start/step/set_velocity (caller manages those).
Returns:
(linear_vel, angular_vel, metrics) -- velocity commands and
StepMetrics. Coordinator uses metrics.rescan_triggered for merges.
"""
config = self._config
# a. Update SLAM and OctoMap
self._planning_attempts = []
self._route_checks = []
self._selection_latency_ms = []
if not np.isfinite(frame.sim_time):
raise ValueError("Exploration sensor time must be finite")
if self._previous_sim_time is not None:
elapsed = frame.sim_time - self._previous_sim_time
if elapsed <= 0:
raise ValueError("Exploration sensor times must increase")
self._frame_dt = elapsed
self._previous_sim_time = frame.sim_time
camera_pose, _ = self._update_slam(frame)
# Mapping and floor filtering use the camera origin. Navigation uses
# the body origin and forward axis, derived only from fixed calibration.
pose = frame.body_pose_from_camera(camera_pose)
self._navigation_pose = pose.copy()
current_pos = pose[:3, 3].copy()
self._robot_positions.append(current_pos)
# Enclose the fixed camera mount at every heading. Its 3D offset norm
# also bounds horizontal reach when the body pitches or rolls.
camera_offset = 0. if frame.body_from_camera is None else float(
np.linalg.norm(frame.body_from_camera[:3, 3]))
calibrated_radius = frame.collision_radius_m or 0.
self._execution_radius = config.planning_radius(
camera_offset, config.voxel_resolution, calibrated_radius)
self._path_planner.set_clearance_radius(self._execution_radius)
self._blocked.observe(pose, frame.sim_time,
navigation_translation=np.linalg.norm(self._last_command[0]) > .01)
if self._blocked.state in {"blocked", "recovering", "failed"}:
self._current_waypoint_runner = None
self._goal_id = None
self._progress.reset()
linear, angular = self._blocked_proposal(frame)
return linear, angular, StepMetrics(
self._last_frontier_count, self._last_coverage,
self._blocked.state == "failed", self._octomap.num_occupied, False)
retry = self._blocked.state == "replanning"
# b. Stuck detection and recovery
self._check_stuck(step, pose, frame.sim_time)
if self._blocked.state == "blocked":
return np.zeros(2), 0., StepMetrics(
self._last_frontier_count, self._last_coverage, False,
self._octomap.num_occupied, False)
# c. Check re-evaluation trigger
should_rescan = retry or self._should_rescan(step, current_pos, False)
# d. Frontier re-evaluation
linear_vel = np.zeros(2, dtype=np.float64)
angular_vel = 0.0
terminated = self._navigation_exhausted
frontier_count = self._last_frontier_count
if should_rescan:
frontier_count, terminated = self._evaluate_frontiers(
current_pos, pose, score_fn, guard_state=self._guard_state(frame),
)
# e. Execute navigation
if (not terminated and self._current_waypoint_runner is not None
and not self._current_waypoint_runner.is_complete):
# A rescan already replaces the path above. Do not discard the
# newly planned route on that same frame (including the first scan).
linear_vel, angular_vel = self._current_waypoint_runner.get_velocity(pose)
elif not terminated and not self._bootstrap_complete and self._current_waypoint_runner is None:
# Drive forward only for initial map acquisition, never as a
# fallback after an unsuccessful scan or an invalidated route.
linear_vel = np.array([config.linear_speed * 0.5, 0.0], dtype=np.float64)
angular_vel = 0.0
# f. Periodic logging
if step % config.log_interval_steps == 0:
self._coverage_tracker.log(
step, self._last_coverage, self._last_bbox_coverage,
self._last_frontier_count,
)
# g. Attribute the next pose interval to this command.
self._last_command = (linear_vel.copy(), float(angular_vel))
metrics = StepMetrics(
frontiers=frontier_count,
coverage=self._last_coverage,
terminated=terminated,
voxels=self._octomap.num_occupied,
rescan_triggered=should_rescan,
)
return linear_vel, angular_vel, metrics
def run(self) -> ExplorationResult:
"""Run the full autonomous exploration loop.
Returns:
ExplorationResult with final coverage metrics, step count,
termination reason, and coverage history.
"""
config = self._config
frame = self._bridge.start()
terminated_reason = "max_steps"
for step in range(config.max_steps):
linear_vel, angular_vel, metrics = self.step_once(frame, step)
self._bridge.set_velocity(linear_vel, angular_vel)
if metrics.terminated and step >= 50:
# Determine specific termination reason from frontier state
if self._blocked.state == "failed":
terminated_reason = "navigation_failed"
elif metrics.frontiers == 0:
terminated_reason = "no_frontiers"
else:
terminated_reason = "all_unreachable"
break
# Step simulation
frame = self._bridge.step()
else:
# Loop completed without break -- max_steps reached
terminated_reason = "max_steps"
logger.info("Max steps (%d) reached. Exploration terminated.", config.max_steps)
step = config.max_steps - 1
return self._coverage_tracker.result(step + 1, terminated_reason)