jizhuochen commited on
Commit
803c4cb
·
verified ·
1 Parent(s): 4f220a4

Add case 05: false forward-left occupancy and historical-reference ablation

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +15 -4
  2. cases/20261026_goal1012_05/README.md +174 -0
  3. cases/20261026_goal1012_05/SHA256SUMS +101 -0
  4. cases/20261026_goal1012_05/archives/CROSS_source.tar.gz +3 -0
  5. cases/20261026_goal1012_05/archives/capture.tar +3 -0
  6. cases/20261026_goal1012_05/archives/reference_map.tar +3 -0
  7. cases/20261026_goal1012_05/archives/run_core.tar.gz +3 -0
  8. cases/20261026_goal1012_05/archives/vggt_frames_000.tar +3 -0
  9. cases/20261026_goal1012_05/archives/vggt_frames_001.tar +3 -0
  10. cases/20261026_goal1012_05/archives/vggt_frames_002.tar +3 -0
  11. cases/20261026_goal1012_05/archives/vggt_metadata.tar.gz +3 -0
  12. cases/20261026_goal1012_05/archives/vggt_views.tar +3 -0
  13. cases/20261026_goal1012_05/code/lite3_ROS/LICENSE +21 -0
  14. cases/20261026_goal1012_05/code/lite3_ROS/scripts/capture_stretch_cross.py +131 -0
  15. cases/20261026_goal1012_05/code/lite3_ROS/scripts/diagnose_stretch_bev_blockage.py +420 -0
  16. cases/20261026_goal1012_05/code/lite3_ROS/scripts/diagnose_stretch_bev_region.py +193 -0
  17. cases/20261026_goal1012_05/code/lite3_ROS/scripts/inspect_stretch_vggt_debug.py +98 -0
  18. cases/20261026_goal1012_05/code/lite3_ROS/scripts/live_stretch_cross_nav.py +992 -0
  19. cases/20261026_goal1012_05/code/lite3_ROS/scripts/monitor_stretch_transport.py +74 -0
  20. cases/20261026_goal1012_05/code/lite3_ROS/scripts/replay_stretch_cross_nav.py +164 -0
  21. cases/20261026_goal1012_05/code/lite3_ROS/scripts/view_stretch_cross_nav_live_run.py +69 -0
  22. cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_capture_format.py +15 -0
  23. cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_control.py +249 -0
  24. cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_geometry.py +39 -0
  25. cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_handoff.py +528 -0
  26. cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_learned.py +55 -0
  27. cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_recovery.py +222 -0
  28. cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_replay.py +250 -0
  29. cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_routing.py +162 -0
  30. cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_survey.py +290 -0
  31. cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_transport.py +80 -0
  32. cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_vggt_debug.py +237 -0
  33. cases/20261026_goal1012_05/code/lite3_ROS/web_console/__init__.py +0 -0
  34. cases/20261026_goal1012_05/code/lite3_ROS/web_console/cross_run.py +116 -0
  35. cases/20261026_goal1012_05/code/lite3_ROS/web_console/static/cross_nav.css +3 -0
  36. cases/20261026_goal1012_05/code/lite3_ROS/web_console/static/cross_nav_live.html +26 -0
  37. cases/20261026_goal1012_05/code/lite3_ROS/web_console/static/cross_nav_live.js +233 -0
  38. cases/20261026_goal1012_05/code/lite3_ROS/web_console/static/vendor/plotly.min.js +0 -0
  39. cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_control.py +259 -0
  40. cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_footprint.py +87 -0
  41. cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_geometry.py +99 -0
  42. cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_learned.py +57 -0
  43. cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_recovery.py +393 -0
  44. cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_replay.py +226 -0
  45. cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_report.py +352 -0
  46. cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_survey.py +169 -0
  47. cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_viewer.py +178 -0
  48. cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_transport.py +24 -0
  49. cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_vggt_debug.py +401 -0
  50. cases/20261026_goal1012_05/code/stretch_ai/LICENSE +202 -0
README.md CHANGED
@@ -23,6 +23,7 @@ Both supervised runs were recorded on **2026-10-26 (Asia/Singapore)** toward ref
23
  |---|---|---:|---:|---|
24
  | **20261026_goal1012_02** | Measured-depth checks reject all local graph attachments during a head survey | 680 | 380 | [Evidence, download and replay](cases/20261026_goal1012_02/README.md) |
25
  | **20261026_goal1012_03** | Transient false BEV occupancy triggers the added path guard; a separate braking handoff bug stops the survey | 500 | 240 | [Evidence, download and replay](cases/20261026_goal1012_03/README.md) |
 
26
 
27
  Each case is self-contained, including original RGB/depth, odometry and image-time transforms, exact
28
  VGGT input tensors and numeric outputs, BEV replay, planner evidence, the reference map, recorded
@@ -52,10 +53,19 @@ cases/
52
  reports/
53
  tools/
54
  post_run_fixes/ # later changes, explicitly separate from recorded source
 
 
 
 
 
 
 
 
 
55
  ```
56
 
57
  Archives always belong to their containing case. Archive/member SHA-256 hashes and extraction paths
58
- are in each case's `manifest.json`. Case 03 also includes a file-level `SHA256SUMS`.
59
  The cases include identical reference-map/source archives so either can be downloaded independently.
60
  Pretrained model weights are referenced by repository/revision/hash in the case provenance.
61
 
@@ -64,7 +74,7 @@ Pretrained model weights are referenced by repository/revision/hash in the case
64
  ```python
65
  from huggingface_hub import snapshot_download
66
 
67
- case_id = "20261026_goal1012_03" # or "20261026_goal1012_02"
68
  snapshot_download(
69
  repo_id="jizhuochen/CROSS_nav_debug",
70
  repo_type="dataset",
@@ -76,12 +86,13 @@ snapshot_download(
76
  Change into the downloaded case folder, then run its verifier/unpacker:
77
 
78
  ```bash
79
- cd CROSS_nav_debug/cases/20261026_goal1012_03
80
  python tools/unpack.py --output extracted
81
  ```
82
 
83
  Case 02 needs approximately **3.5 GB** for download plus **3.5 GB** for extraction; case 03 needs
84
- approximately **2.3 GB** for each. Replay and saved-output inspection need no robot or GPU.
 
85
 
86
  ## Layout migration
87
 
 
23
  |---|---|---:|---:|---|
24
  | **20261026_goal1012_02** | Measured-depth checks reject all local graph attachments during a head survey | 680 | 380 | [Evidence, download and replay](cases/20261026_goal1012_02/README.md) |
25
  | **20261026_goal1012_03** | Transient false BEV occupancy triggers the added path guard; a separate braking handoff bug stops the survey | 500 | 240 | [Evidence, download and replay](cases/20261026_goal1012_03/README.md) |
26
+ | **20261026_goal1012_05** | False forward-left occupancy despite survey floor evidence; historical-reference lifting ablation; complete head survey followed by a separate depth-attachment stop | 749 | 376 | [Evidence, download and replay](cases/20261026_goal1012_05/README.md) |
27
 
28
  Each case is self-contained, including original RGB/depth, odometry and image-time transforms, exact
29
  VGGT input tensors and numeric outputs, BEV replay, planner evidence, the reference map, recorded
 
53
  reports/
54
  tools/
55
  post_run_fixes/ # later changes, explicitly separate from recorded source
56
+ 20261026_goal1012_05/
57
+ README.md
58
+ archives/
59
+ code/
60
+ environment/
61
+ manifest.json
62
+ previews/
63
+ reports/
64
+ tools/
65
  ```
66
 
67
  Archives always belong to their containing case. Archive/member SHA-256 hashes and extraction paths
68
+ are in each case's `manifest.json`. Cases 03 and 05 also include file-level `SHA256SUMS`.
69
  The cases include identical reference-map/source archives so either can be downloaded independently.
70
  Pretrained model weights are referenced by repository/revision/hash in the case provenance.
71
 
 
74
  ```python
75
  from huggingface_hub import snapshot_download
76
 
77
+ case_id = "20261026_goal1012_05" # or "20261026_goal1012_02" / "20261026_goal1012_03"
78
  snapshot_download(
79
  repo_id="jizhuochen/CROSS_nav_debug",
80
  repo_type="dataset",
 
86
  Change into the downloaded case folder, then run its verifier/unpacker:
87
 
88
  ```bash
89
+ cd CROSS_nav_debug/cases/20261026_goal1012_05
90
  python tools/unpack.py --output extracted
91
  ```
92
 
93
  Case 02 needs approximately **3.5 GB** for download plus **3.5 GB** for extraction; case 03 needs
94
+ approximately **2.3 GB** for each; case 05 needs approximately **3.6 GB** to download and **3.7 GB** to extract.
95
+ Replay and saved-output inspection need no robot or GPU.
96
 
97
  ## Layout migration
98
 
cases/20261026_goal1012_05/README.md ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Case 20261026_goal1012_05: false forward-left occupancy driven by historical reference lifting
2
+
3
+ Supervised Stretch run on **2026-10-26, Asia/Singapore**, toward reference-map keyframe **1012**.
4
+ Reference mapping sequence: Record3D `2026-10-22--15-48-58`.
5
+
6
+ ## Finding
7
+
8
+ The final displayed BEV contains a false obstacle in the nearby forward-left patch. At capture
9
+ frame **747**, selected cells A and B lie on floor seen during the robot's head survey, but receive
10
+ high occupancy after the camera returns to its driving view. A controlled offline ablation shows
11
+ that explicitly lifting the historical phone references into the BEV head strongly contributes.
12
+
13
+ ![Current RGB, survey floor evidence, BEV and native map memory](reports/bev_diagnosis/region_analysis.png)
14
+
15
+ | Evidence | Cell A | Cell B |
16
+ |---|---:|---:|
17
+ | BEV row, column | 190, 190 | 189, 189 |
18
+ | Forward / left from robot base | 0.475 / 0.475 m | 0.525 / 0.525 m |
19
+ | Current occupancy | **0.883898** | **0.947792** |
20
+ | Current predicted observability | 0.733810 | 0.640831 |
21
+ | Raw head occupancy at the corresponding position | 0.883943 | 0.947565 |
22
+ | Separate native accumulated occupancy | 0.511303 | 0.592291 |
23
+ | Survey frames with nearby floor returns and no elevated returns in the projected patch | **22** | **21** |
24
+ | Latest floor frame | 639 | 638 |
25
+ | Latest floor height range over base origin | −31.4 to −20.8 mm | −31.1 to −14.0 mm |
26
+ | Latest floor depth pixels / nearby returns | 49 / 49 | 49 / 49 |
27
+
28
+ Cell A was predicted only **0.017629 occupied** at frame 634 during the floor survey; it rises to
29
+ 0.883898 in frame 747 at the same odometry-world location. Its latest direct floor observation was
30
+ **27.06 s** earlier; cell B's was 27.33 s earlier. The current ground projections are outside the
31
+ camera image: A is approximately `(−92, 976)` in the 480 × 640 image. Positive historical depth rays
32
+ also indicate free space at sampled column heights from **0.12 through 1.32 m for A**, and through
33
+ **1.20 m for B**, without matching surface returns at those samples. These are discrete historical
34
+ measurements, not continuous clearance certificates or a claim that all furniture farther left is absent.
35
+
36
+ The saved camera-to-base reprojection reproduces with **zero maximum absolute difference**.
37
+ The high value is present in the raw learned head output. The web viewer shows this current
38
+ reprojected BEV; it does not render a cached phone-mapping occupancy grid. Native planner map
39
+ memory is separate and retains lower occupancy at these cells, below its 0.6 blocking threshold.
40
+
41
+ ## Historical-reference ablation
42
+
43
+ The actual input group contains the current robot RGB and six phone references:
44
+ **799, 798, 800, 797, 803, 527**. Recent robot floor-survey frames are not members of this group.
45
+
46
+ ![Exact input-view group for frame 747](previews/00000747/input_views.jpg)
47
+
48
+ The offline experiment recomputes transformer features once from those exact seven tensors,
49
+ retains the **recorded depth, confidence, camera-pose encoding, metric scale, gravity and TF**,
50
+ then changes only which views the BEV head explicitly lifts/uses:
51
+
52
+ | BEV-head mask | Occupancy at A | Observability at A |
53
+ |---|---:|---:|
54
+ | All seven recorded views | **0.884494** | 0.734061 |
55
+ | Current robot view only; all phone lifting disabled | **0.045817** | 0.015535 |
56
+ | Drop one phone reference at a time | 0.872603–0.891582 | See detailed report |
57
+
58
+ This is strong evidence that historical reference lifting collectively drives the false patch.
59
+ No single reference's removal fixes it. The current-only result also reports that the cell is
60
+ unobserved; its low occupancy is **not** permission to drive through unseen space.
61
+
62
+ All seven images remain in the transformer context in this experiment. The result does not isolate
63
+ pure geometric lifting from other head use of those reference views, identify one historical
64
+ chair/person, prove the scene's exact change since mapping, or remove every learned
65
+ appearance prior. Original intermediate transformer tokens were not archived, so feature recomputation
66
+ is near but not bit-identical: the baseline occupancy differs from the recording by 0.000596 at A,
67
+ with maximum 0.005352 across the raw occupancy grid. Repeated baseline maximum base-grid difference
68
+ is 0.001892, much smaller than the 0.838676 ablation effect at A. Numeric results and grids are under
69
+ `reports/bev_diagnosis/reference_ablation/`.
70
+
71
+ An earlier exploratory rerun using recomputed geometry is retained there with a
72
+ `recomputed_geometry_` prefix. The primary report uses the exact recorded geometry described above.
73
+ All ablations are explicitly **offline counterfactuals**, separate from original `vggt_debug` outputs.
74
+ Runtime thresholds, model predictions and navigation policy were not changed by this investigation.
75
+
76
+ ## Run outcome and separate final stop
77
+
78
+ The robot travelled **5.10 m in 100.91 s**, completing all six survey views in **39.06 s** with zero
79
+ head-action cancellations, 534 renewals from fresh robot feedback, and zero nonzero base requests
80
+ during the survey. This run used the installed timing fix; it is part of the recorded adapter source.
81
+
82
+ After resuming briefly, it stopped with `no global route; navigation ended`, still localized and
83
+ **13.78 m** camera-XY distance from the goal. The adapter's measured-depth attachment veto rejected
84
+ all nearby graph connections. Rechecking final frame 747 with the retained obstacle memory saved at
85
+ frame 742 finds **ten points in the 20–23 cm rear band of the starting footprint**, outside the 20 cm
86
+ self mask but inside the 23 cm collision rectangle. That memory alone rejects all **13** nearby
87
+ permanent keyframe candidates at path fraction zero. Their physical/noise/self-observation origin
88
+ has not been established. This final stop is separate from the selected false learned-occupancy cells.
89
+
90
+ Relay exit was verified with code 0, streaming head control was restored, and a four-second TF audit
91
+ found less than 0.015 mm base translation. This case documents a successful survey and subsequent
92
+ failure, not arrival at keyframe 1012.
93
+
94
+ ## Contents and download
95
+
96
+ - **749** original RGB/depth pairs, image-time intrinsics, odometry, camera/base TF and head joints.
97
+ - **376** actual VGGT passes, **497** unique exact lossless input tensors, **2,633** view references.
98
+ - **377** debug frame manifests, including one processing frame without a model pass; no outputs fabricated.
99
+ - **376** original occupancy/observability/uncertainty replay sets, raw head and consumed BEV arrays.
100
+ - Native planner accumulators, routes, footprint evidence, commands, timing, robot state and shutdown audit.
101
+ - Complete reference map and final native query map, with their lossless image/descriptor stores.
102
+ - Frozen native CROSS and actual pre-run adapter source; offline analysis and ablation tools.
103
+ - Numeric diagnosis, annotated figure, CSV timeline and independently labeled counterfactual grids.
104
+
105
+ ```python
106
+ from huggingface_hub import snapshot_download
107
+
108
+ snapshot_download(
109
+ repo_id="jizhuochen/CROSS_nav_debug",
110
+ repo_type="dataset",
111
+ allow_patterns="cases/20261026_goal1012_05/**",
112
+ local_dir="CROSS_nav_debug",
113
+ )
114
+ ```
115
+
116
+ ```bash
117
+ cd CROSS_nav_debug/cases/20261026_goal1012_05
118
+ python tools/unpack.py --output extracted
119
+ ```
120
+
121
+ The nine archives total **3.61 GB**. Allow approximately another 3.7 GB for extraction.
122
+ Each case has independent reference-map/source archives. `manifest.json` verifies archive and member
123
+ SHA-256 hashes; `SHA256SUMS` covers the published case files.
124
+
125
+ ## Repeat the diagnosis or inspect the run
126
+
127
+ Use a Python environment with NumPy, OpenCV and Matplotlib for the diagnosis. Replay and input
128
+ inspection need NumPy/OpenCV. They require no robot or GPU. Recorded package versions are provenance,
129
+ not a portable environment installer.
130
+
131
+ ```bash
132
+ python tools/diagnose_bev_region.py \
133
+ --run extracted/runs/stretch_cross_nav_live_20261026_goal1012_05 \
134
+ --frame 747 --output repeated_region_diagnosis
135
+
136
+ python code/lite3_ROS/scripts/inspect_stretch_vggt_debug.py \
137
+ --debug extracted/runs/stretch_cross_nav_live_20261026_goal1012_05/vggt_debug \
138
+ --frame 747 --output inspection_747
139
+
140
+ python code/lite3_ROS/scripts/view_stretch_cross_nav_live_run.py \
141
+ --run extracted/runs/stretch_cross_nav_live_20261026_goal1012_05 --port 8088
142
+ ```
143
+
144
+ Open <http://127.0.0.1:8088> and select **Replay recording**. The saved-run viewer cannot arm motion.
145
+
146
+ The separately recorded attachment condition can be checked without a model:
147
+
148
+ ```bash
149
+ python tools/analyze_attachment.py --extracted extracted --frame 747 --evidence-frame 742
150
+ ```
151
+
152
+ Repeating the GPU ablation additionally requires the native CROSS environment and the documented
153
+ pretrained backbone/navigation heads under the chosen CROSS checkout's `models/VGGT-Omega-CROSS/`:
154
+
155
+ ```bash
156
+ python tools/ablate_bev_references.py \
157
+ --run extracted/runs/stretch_cross_nav_live_20261026_goal1012_05 \
158
+ --cross-root /path/to/CROSS --adapter-root code/lite3_ROS \
159
+ --frame 747 --output repeated_reference_ablation
160
+ ```
161
+
162
+ The original numeric ablation results can be inspected without loading a model.
163
+
164
+ ## Provenance
165
+
166
+ Native CROSS revision: `4781371e6f4db4241be0a0df7c238436680ee268`, unchanged for this investigation.
167
+ Checkpoint repository/revision/hashes are in `reports/vggt_provenance.json`; weights from
168
+ [Jamie-nus/VGGT-Omega-CROSS](https://huggingface.co/Jamie-nus/VGGT-Omega-CROSS) are not duplicated.
169
+
170
+ RGB/depth, model arrays and native stores are byte-identical to the recording. Sharing copies of
171
+ text have credentials, private network addresses and local absolute paths removed or made portable.
172
+ Three checkpoint paths in query-map metadata were made portable; all 50 numerical arrays were
173
+ verified unchanged. Recorded source is distinguished from later offline analysis. No new recording
174
+ license is asserted; source retains its included upstream licenses.
cases/20261026_goal1012_05/SHA256SUMS ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 5601d10711cb431a43ccb8075170175d09a3dae4715c223aedcc2d36b1523b2d README.md
2
+ c3dd418506684ae4b05b49daeeb6456509d1542621911e0029fa6c420d75c64b archives/CROSS_source.tar.gz
3
+ 4a6dec652cc53d8db40188df5d72870d974e17ff282f42ee96bd5ea205e691b4 archives/capture.tar
4
+ 3876fa21325aea0a41dba3f647a8645815ed9f431c3e3e399e8a3f3d47768200 archives/reference_map.tar
5
+ 71ab36b2cf266ea5054737b3dddf94b17fe4b2a16651173dc62d7ba752dc1049 archives/run_core.tar.gz
6
+ dfe5cbec1b39558d5ce92503447663b744944da8bd4994ec0d1cb7908a371c84 archives/vggt_frames_000.tar
7
+ 74a02595997103e82261b734e8afa42a7b4693f8cd1caec407c3534988ce7d76 archives/vggt_frames_001.tar
8
+ 94113852d76817332b7bea586fead14ee6b229c438dc8c87c31e658d786ab114 archives/vggt_frames_002.tar
9
+ 7802f06f457281e0153170f2f8614c2a940dfc886bf6aa2a5b8eed614e458550 archives/vggt_metadata.tar.gz
10
+ 935373a868f7cba2a3325fde2d1eb61f69325a55763873021c2253fb535d0ff1 archives/vggt_views.tar
11
+ 49a6e137748b934e2f78b15cf74704fd8fdcb26107c5d210d783648287345750 code/lite3_ROS/LICENSE
12
+ 7e861070432a0da598c7e4974397c162df0582df0c94da41dd6e09efc7efcf27 code/lite3_ROS/scripts/capture_stretch_cross.py
13
+ 4cad1fbc6612c000da3be953ad8ef3cabf62e6eb09ebf615d17fafe5a0167768 code/lite3_ROS/scripts/diagnose_stretch_bev_blockage.py
14
+ fd63aaa56167b49042caa4fb0d432b68edd5ef8ffe91929192b86b33ff2c33a4 code/lite3_ROS/scripts/diagnose_stretch_bev_region.py
15
+ 5445e49f09b7891d3ecf962aba966bf748dd50cba931df0382e1d416db1f04f3 code/lite3_ROS/scripts/inspect_stretch_vggt_debug.py
16
+ b6efe176c7cc9b0cda4fb62d9e308338e01c24cd0ceb0b9c852ea4b0734e56ec code/lite3_ROS/scripts/live_stretch_cross_nav.py
17
+ 1290eafa6369623d9d36fcbd7c240b92dbee54efbd9372b1fc64732a2fa9b90e code/lite3_ROS/scripts/monitor_stretch_transport.py
18
+ 17ebc68ab1e30bc0601d1eb2f212e449dd3036d4a0dce7d48662431693ef4967 code/lite3_ROS/scripts/replay_stretch_cross_nav.py
19
+ 7b9b7ac8ebdcb8884808a4cf34b4ef0fdf5ee2b042f0ffd81fca16d4e4fefbb9 code/lite3_ROS/scripts/view_stretch_cross_nav_live_run.py
20
+ 23cd5d206ea6e42850dc750d6712ff305b9896d9c09d0924e3c86a1131690c90 code/lite3_ROS/tests/test_stretch_capture_format.py
21
+ 7a3c08f8a2032d7fe367b49e7b97fcd6d564ad80991e608675fcc336b01017e3 code/lite3_ROS/tests/test_stretch_nav_control.py
22
+ 235a2d70fa9a747de21c4478f5676d43211c1451188e83829c085432a5d11310 code/lite3_ROS/tests/test_stretch_nav_geometry.py
23
+ bee61e6ce0677ffda2efa836dc14c44ffb0a0adbf4b10b0841de43e73569f6c9 code/lite3_ROS/tests/test_stretch_nav_handoff.py
24
+ b15144072cf25d495fc432d9b0f22abfe40996cf07e0be5e8e47beef0026055b code/lite3_ROS/tests/test_stretch_nav_learned.py
25
+ 9ddca6a3f18124eec96edee4558fa568ed7a583c1a6dc20dc709987e9a8d76ce code/lite3_ROS/tests/test_stretch_nav_recovery.py
26
+ b18a7a46290b231b23c611ea34f22c2d542846d4d9e1dd9185086744a81608a9 code/lite3_ROS/tests/test_stretch_nav_replay.py
27
+ f706d7715b2dec1f755997c5c98d1c7d0f93475da23ba026c91b7c080b36138b code/lite3_ROS/tests/test_stretch_nav_routing.py
28
+ 0373c6ca335999d054caeaf1099c24d42a56e97f0e4b7b098a6bf9368b6a163d code/lite3_ROS/tests/test_stretch_nav_survey.py
29
+ a37f95cbb179efb7e72d0f29fe49a06a2e53c48ae7b3d6e686c4b68e59a816d7 code/lite3_ROS/tests/test_stretch_transport.py
30
+ 3581f52fa7653cbfdb852f07654dcc5f0f0395133c9d3a81d789a7d3f7f57fda code/lite3_ROS/tests/test_stretch_vggt_debug.py
31
+ e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 code/lite3_ROS/web_console/__init__.py
32
+ 96cbcccde95c2b6da8d4cc9cc237ecbdff6604218e59845e92429df9e38ba43b code/lite3_ROS/web_console/cross_run.py
33
+ 522597d97ddbf997e7f80246a6c6ea17e11e66435db1669a4ac9fddf8b9b2be2 code/lite3_ROS/web_console/static/cross_nav.css
34
+ 7837119d23b87b5776017dfc86f8aa121327ab4611c15ee409e7866425e325e3 code/lite3_ROS/web_console/static/cross_nav_live.html
35
+ d8daea837482d5ea105e4e5e21dc483d4343401568fefbad6f6536ec015422db code/lite3_ROS/web_console/static/cross_nav_live.js
36
+ 3b6e15d45dbb7fca5bd2094291e961ddc5472cd887009e6009a56dab668d721f code/lite3_ROS/web_console/static/vendor/plotly.min.js
37
+ 09b48f8e6b31d2ab018f12f359ce4db23b35c9d53cd065d6fadfbac55544cb93 code/lite3_ROS/web_console/stretch_nav_control.py
38
+ 670f0d2a352f836915a0dd8af22ba3f9268fad8fba0ff16c375f76dd759018c0 code/lite3_ROS/web_console/stretch_nav_footprint.py
39
+ 0851f120f415788483d6ef52c4bdb8afd14d9651a1ad4acb87ae19489dd1b3ad code/lite3_ROS/web_console/stretch_nav_geometry.py
40
+ 75facca8ee2cbf17055298bc44301fd9c6c6313e133e7c6a5bedc36ab667710c code/lite3_ROS/web_console/stretch_nav_learned.py
41
+ 189a52c4987f9fd042253ba263b9cd6bcb24a4c79badc46aa43a0cba902d215e code/lite3_ROS/web_console/stretch_nav_recovery.py
42
+ 8a8b4c95878343eae73605474aa818cb7e283b13c3155b2d2492ddf1c5832570 code/lite3_ROS/web_console/stretch_nav_replay.py
43
+ 15318ba6d6e7b574c0ba50d49db1ebdbd03c44ff0c0f5e33ff3fb69462d3c4fc code/lite3_ROS/web_console/stretch_nav_report.py
44
+ 6725df9d6b83a9bbaf6d7f93d30d0ff16988d5317f6fba1fa958aca720d63e9c code/lite3_ROS/web_console/stretch_nav_survey.py
45
+ 8fdacb65956c47aff77d8f6a19a72960c117a7d89c7a6429f4cf7288dd2b272b code/lite3_ROS/web_console/stretch_nav_viewer.py
46
+ dde3814d364392aab6078402199a743b9653cb3b90ebfb5bd2932463930379a2 code/lite3_ROS/web_console/stretch_transport.py
47
+ c9372443e127bbce7e6b7a0a920607c4115cdfa4b3ba0eb98cd1f9a8d282e16b code/lite3_ROS/web_console/stretch_vggt_debug.py
48
+ 980c4c38bfef6167490f632ac7f39438bc32b14e00d3ad95147f862066ac496a code/stretch_ai/LICENSE
49
+ 741574f7529734e5492a50ccd51e190a975f67f864fe8ec92c66063d9ed77fcb code/stretch_ai/scripts/capture_lingbot_rgbd_ros2.py
50
+ 3838bb9e7bab6f71b1e10bc2f24c10f614f671897fbfdf1d5545db1ba952184b code/stretch_ai/scripts/depth_nav_control.py
51
+ ea99cdb412cc962f5e1cf72ed0dd255eb177024f1a7169349af5b78746386815 code/stretch_ai/scripts/depth_nav_debug.py
52
+ c3ead5fbff583e23f5c0ef26afe123e8137c870dc1250b96ea309f453b753e46 code/stretch_ai/scripts/depth_nav_footprint.py
53
+ 9ad308cb8123eb819747136140dacd1e1a7571604412c764080935d71aa4fcc5 code/stretch_ai/scripts/depth_nav_live.py
54
+ b4634c91e7113318e2322782e3070c018d59971b8cadc89f56b3933c14f3bb58 code/stretch_ai/scripts/depth_nav_memory.py
55
+ c90128690eb85ddf883dcd48ab61980e8a2799c57368521925325daec3bdf44d code/stretch_ai/scripts/depth_nav_robot_relay.py
56
+ 86a32af7fe5b740fd56a146571e3ae80fd99674c101f4c8143b13ff3e701d3ae code/stretch_ai/scripts/depth_nav_trajectories.py
57
+ 03f7f193be8bbae5b03508a1d05f11d58ee2344bbf4ac3d59a945b8f2edaf19b code/stretch_ai/scripts/depth_only_path_planner.py
58
+ 221d420a595a2ab6d6561b25d60d342867d02a0dcf0f16927fd898bc5c5578af code/stretch_ai/scripts/lingbot_depth_eval.py
59
+ a80afef0149ff5e7f3ceeece04c71db212aaee1403e531aaf695ee616120feb9 code/stretch_ai/scripts/lingbot_depth_geometry.py
60
+ 55787d89d8da689b57e10a47477b93e2ae75d29a5c0feee03816845af5e9cb99 code/stretch_ai/scripts/lingbot_depth_model.py
61
+ 7e362f18cbe8b27f6bd8a2cc6c6a858ef9adab9328ff29a12a7de8efb125eaf6 code/stretch_ai/scripts/lingbot_depth_sequence.py
62
+ 690816adfed07da9aafb39f55a71c49b5e89998e9905a33904884cb2b3e8b91c code/stretch_ai/scripts/lingbot_voxel_map.py
63
+ 032592ce282329eb7537a355fe096ccc3ab8eb6108ea932f62cffc252f38ddd1 environment/gpu.txt
64
+ 6a6229b3e2ca8ea0b17a5d0d3346baa3fba732cf56322b1bf14527a87705cea9 environment/map_metadata_sanitization.json
65
+ 9f6cf1a536b4287a65458ae087b1a4531d2fec1a73eda5b27908189ec596fb59 environment/package_validation.json
66
+ a1a25eb20977a72f4ac346c77a936fa5d46e5701b53968db49b73185f3675b29 environment/pip_freeze.txt
67
+ 372e5c3211d1d89eb2b2a8cb859318de6f15220cf698d3b66cfbcd51827a028f environment/provenance.json
68
+ 6b88f85ba6878da27c2344e063fff4fda22d98ba3482a5680a540320be993c8d environment/source_provenance.json
69
+ bf08abe65e2a3dd0ab87d648daca029b6fccbe5921f319f6811ffafbf9d19447 manifest.json
70
+ 2ef9102f39e71e009e5e2d520714be27838b4f02392a13527e6a5a1072fd4fab previews/00000747/bev_stages.png
71
+ 6b471e1c4e4d0b061f6feae099fed888b19c9d9bd124a5efbe7ab3d10b7e0064 previews/00000747/input_views.jpg
72
+ 2d3bb50b275181d8101909e4782acd113d985cb16dd3e7691ad7e44500f9174b previews/00000747/manifest.json
73
+ d3261dd3e93363573304889605cbd81c3f8ad0df69522e072be1da16fd423991 previews/00000747/predicted_depth.jpg
74
+ 3f2a22d9a811a371467f067ad42dea9306d6ca33675113059376f44fe61044b6 previews/rgb_00000574.jpg
75
+ 5021b57d94747c3ec68a92c890c500d8dbafa8f84302f64764692d10a42ff2d8 previews/rgb_00000627.jpg
76
+ 41a119b9f73e899178e9df291ee0f3e1274722b4d963f890bbca7de62bcf5b04 previews/rgb_00000708.jpg
77
+ a5b189f15f22cff8c02a535dfb511e50a8eed7855fe3e14fc828838854514fc6 previews/rgb_00000730.jpg
78
+ 68ac018c1520de6c0fe59c3bad2ffadf0217bb5fc9d26021113ee5cbcf3c2c44 previews/rgb_00000747.jpg
79
+ 6dbd717673bc85f4e84074189ef6d846408cc22a18e5697b79bd94f820ba486b reports/attachment_recheck_747.json
80
+ 3e0c997ce1afd2c23dbb8a3b6ebed2ca2e4b6cb51a2cf15104c8c50fc4a2bf3e reports/bev_diagnosis/bev_overview.jpg
81
+ 3f3584df7eb8358abb2d9f1feb74d29c105c8346f445f94052f030bcbe5e88b4 reports/bev_diagnosis/diagnosis_stdout.log
82
+ f51bcd30505943678f2eef7bb4d92c2acfa9aefae2fde248da86faa984751709 reports/bev_diagnosis/occupancy_timeline.csv
83
+ de1bfa68797606388c854795452d2b004c4f970e260354b56810ceb8c1eaabd8 reports/bev_diagnosis/reference_ablation/head_mask_outputs.npz
84
+ d27c74eb80db253e3f082a45058b5d182e7c7cfb30e8b2a314e7e1b443bb12b7 reports/bev_diagnosis/reference_ablation/recomputed_geometry_head_mask_outputs.npz
85
+ c6abf6652889ea316411366df32c95e91d0ea68772703e1df3cdef78d1f7a0fa reports/bev_diagnosis/reference_ablation/recomputed_geometry_report.json
86
+ 23e18837a11c22d98dfe529438a0bb9bea8eb5052cb801dc57fb340b8c767b5b reports/bev_diagnosis/reference_ablation/report.json
87
+ 7dba4803fb68eaf6c2cc21231de967e33e4ed8505647b2b0fda30c8b6e2c53f5 reports/bev_diagnosis/region_analysis.png
88
+ e5426064c3618af3de6f3d8cddd174d4d526a6ebf3e54b40e6be953376d70075 reports/bev_diagnosis/region_report.json
89
+ 8bd3efb512db0cb0af79ebf9e8583b35ba204b949a123ea32d26e39fbb5da2a0 reports/events.jsonl
90
+ 4f94c9d7f5056a057f7135cddc487cbd1dd6dbfe4b9872aa270c39aef2b3b31e reports/observations.jsonl
91
+ 9c0aa8c80abcd19fecd7e1c7ebd5625589ca31a3485c579e561d70715b43f782 reports/recording_validation.json
92
+ 7cda24b9b0b0ea413c7b12ad463be3422893613465c2503eb35ec9f7669fcdda reports/resolved_bev_config.json
93
+ c12cf47ad229e57334cfc09b40364a87ef611c404c512b4274c9c37e70dce691 reports/robot_relay_close.json
94
+ 57839abd8587ec641810a9f1d0469bc1554c93ae11cdd4ddfa709a5d0b432390 reports/stop_audit.json
95
+ 9afea9b7e214f61f538af275594537d96f5e854642c09d0ed976666e3a030555 reports/summary.json
96
+ f5348a69f87ff8631d510307e93b44473bba5cccd81b967454606a337630268f reports/vggt_index.jsonl
97
+ e699148a36a85eb93762475186cc20486fbca3f519469d86c31a3753ea3b9235 reports/vggt_provenance.json
98
+ 78fe2343a74e73794e9123bf016549a96c87ac4545e08c328ebdb0cdf699c9b4 tools/ablate_bev_references.py
99
+ bc28cc2c49952142cb68ed5daf6b94e52c75c3dafaecdf3728016823f6bbce1f tools/analyze_attachment.py
100
+ fd63aaa56167b49042caa4fb0d432b68edd5ef8ffe91929192b86b33ff2c33a4 tools/diagnose_bev_region.py
101
+ a6ce163de4ef4f52ded94f91f2aa5b64385ceebacd2bb5fb16dba950017f3b8d tools/unpack.py
cases/20261026_goal1012_05/archives/CROSS_source.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3dd418506684ae4b05b49daeeb6456509d1542621911e0029fa6c420d75c64b
3
+ size 28251800
cases/20261026_goal1012_05/archives/capture.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a6dec652cc53d8db40188df5d72870d974e17ff282f42ee96bd5ea205e691b4
3
+ size 124999680
cases/20261026_goal1012_05/archives/reference_map.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3876fa21325aea0a41dba3f647a8645815ed9f431c3e3e399e8a3f3d47768200
3
+ size 208558080
cases/20261026_goal1012_05/archives/run_core.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71ab36b2cf266ea5054737b3dddf94b17fe4b2a16651173dc62d7ba752dc1049
3
+ size 367815430
cases/20261026_goal1012_05/archives/vggt_frames_000.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfe5cbec1b39558d5ce92503447663b744944da8bd4994ec0d1cb7908a371c84
3
+ size 733143040
cases/20261026_goal1012_05/archives/vggt_frames_001.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:74a02595997103e82261b734e8afa42a7b4693f8cd1caec407c3534988ce7d76
3
+ size 729374720
cases/20261026_goal1012_05/archives/vggt_frames_002.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94113852d76817332b7bea586fead14ee6b229c438dc8c87c31e658d786ab114
3
+ size 597340160
cases/20261026_goal1012_05/archives/vggt_metadata.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7802f06f457281e0153170f2f8614c2a940dfc886bf6aa2a5b8eed614e458550
3
+ size 9396
cases/20261026_goal1012_05/archives/vggt_views.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:935373a868f7cba2a3325fde2d1eb61f69325a55763873021c2253fb535d0ff1
3
+ size 819107840
cases/20261026_goal1012_05/code/lite3_ROS/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 DeepRoboticsLab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
cases/20261026_goal1012_05/code/lite3_ROS/scripts/capture_stretch_cross.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Record timestamped Stretch observations through an unarmed temporary relay.
3
+
4
+ Only SUB sockets are opened on the PC. No arm, mode, joint or velocity requests are sent.
5
+ Place a STOP file in the output directory or use Ctrl+C to finish and close our relay.
6
+ """
7
+ import argparse
8
+ import json
9
+ from pathlib import Path
10
+ import signal
11
+ import sys
12
+ import time
13
+ from types import SimpleNamespace
14
+
15
+ import numpy as np
16
+
17
+
18
+ def json_value(value):
19
+ if isinstance(value, np.ndarray):
20
+ return value.tolist()
21
+ if isinstance(value, np.generic):
22
+ return value.item()
23
+ raise TypeError(f'Cannot serialize {type(value).__name__}')
24
+
25
+
26
+ def atomic_json(path, data):
27
+ temporary = path.with_suffix('.json.tmp')
28
+ temporary.write_text(json.dumps(data, indent=2, allow_nan=False, default=json_value) + '\n')
29
+ temporary.replace(path)
30
+
31
+
32
+ def main():
33
+ import zmq
34
+
35
+ parser = argparse.ArgumentParser(description=__doc__)
36
+ parser.add_argument('--robot-ip', default='192.0.2.2')
37
+ parser.add_argument('--stretch-root', type=Path, default=Path('/workspace/stretch_ai'))
38
+ parser.add_argument('--output', type=Path, required=True)
39
+ parser.add_argument('--fps', type=float, default=4.)
40
+ args = parser.parse_args()
41
+ output = args.output.resolve()
42
+ output.mkdir(parents=True, exist_ok=False)
43
+ for name in ('rgb', 'depth'):
44
+ (output / name).mkdir()
45
+ sys.path.insert(0, str(args.stretch_root / 'scripts'))
46
+ from depth_nav_live import RobotRelayProcess
47
+
48
+ options = SimpleNamespace(robot_ip=args.robot_ip, ssh_user='hello-robot', container=None,
49
+ world_frame='odom', plan_hz=args.fps,
50
+ relay_max_frame_age=.8, command_ttl=.3)
51
+ relay = RobotRelayProcess(options, output)
52
+ context = zmq.Context()
53
+ observations = context.socket(zmq.SUB)
54
+ observations.setsockopt(zmq.SUBSCRIBE, b'')
55
+ observations.setsockopt(zmq.CONFLATE, 1)
56
+ observations.setsockopt(zmq.LINGER, 0)
57
+ observations.connect(f'tcp://{args.robot_ip}:4511')
58
+ states = context.socket(zmq.SUB)
59
+ states.setsockopt(zmq.SUBSCRIBE, b'')
60
+ states.setsockopt(zmq.CONFLATE, 1)
61
+ states.setsockopt(zmq.LINGER, 0)
62
+ states.connect(f'tcp://{args.robot_ip}:4513')
63
+ stopped = False
64
+
65
+ def stop(*_):
66
+ nonlocal stopped
67
+ stopped = True
68
+
69
+ signal.signal(signal.SIGTERM, stop)
70
+ signal.signal(signal.SIGINT, stop)
71
+ state = {'status': 'starting', 'frames': 0, 'world_frame': 'odom',
72
+ 'robot_ip': args.robot_ip, 'robot_commands_sent': 0, 'armed': False}
73
+ started, last_frame, first_stamp = time.monotonic(), -1, None
74
+ error = None
75
+ atomic_json(output / 'capture.json', state)
76
+ try:
77
+ relay.start()
78
+ state.update(status='recording', relay_directory=relay.directory, container=relay.container)
79
+ with (output / 'observations.jsonl').open('w', buffering=1) as log:
80
+ while not stopped and not (output / 'STOP').exists():
81
+ if relay.process is not None and relay.process.poll() is not None:
82
+ raise RuntimeError('Our temporary observation relay exited; inspect robot_relay.log')
83
+ if states.poll(0):
84
+ robot = states.recv_pyobj()
85
+ if robot.get('armed'):
86
+ raise RuntimeError('Relay unexpectedly armed; passive capture aborted')
87
+ state['robot_status'] = {key: robot.get(key) for key in
88
+ ('healthy', 'armed', 'reason', 'capture_error', 'base_pose', 'sensor_age')}
89
+ if not observations.poll(250):
90
+ state['elapsed_s'] = time.monotonic() - started
91
+ atomic_json(output / 'capture.json', state)
92
+ continue
93
+ packet = observations.recv_pyobj()
94
+ if packet['frame_id'] <= last_frame:
95
+ continue
96
+ if packet['world_frame'] != 'odom':
97
+ raise ValueError('Capture requires continuous odom TF')
98
+ last_frame = packet['frame_id']
99
+ index = state['frames']
100
+ stem = f'{index:08d}'
101
+ (output / 'rgb' / f'{stem}.jpg').write_bytes(np.asarray(packet['rgb_jpg'], np.uint8).tobytes())
102
+ (output / 'depth' / f'{stem}.png').write_bytes(np.asarray(packet['depth_png'], np.uint8).tobytes())
103
+ row = {key: value.tolist() if isinstance(value, np.ndarray) else value
104
+ for key, value in packet.items() if key not in ('rgb_jpg', 'depth_png')}
105
+ first_stamp = row['sensor_stamp'] if first_stamp is None else first_stamp
106
+ row.update(frame_idx=index, relative_time_s=row['sensor_stamp'] - first_stamp,
107
+ received_monotonic=time.monotonic(), received_unix_s=time.time())
108
+ log.write(json.dumps(row, allow_nan=False, default=json_value) + '\n')
109
+ atomic_json(output / 'latest.json', row)
110
+ state.update(frames=index + 1, latest_frame=index, duration_s=row['relative_time_s'],
111
+ elapsed_s=time.monotonic() - started)
112
+ atomic_json(output / 'capture.json', state)
113
+ if index % 20 == 0:
114
+ print(f"Recorded {index + 1} RGB-D/TF observations; {row['relative_time_s']:.1f}s; passive", flush=True)
115
+ except BaseException as exc:
116
+ error = str(exc)
117
+ state.update(status='failed', error=error)
118
+ raise
119
+ finally:
120
+ relay.close()
121
+ observations.close()
122
+ states.close()
123
+ context.term()
124
+ if error is None:
125
+ state['status'] = 'completed'
126
+ state['elapsed_s'] = time.monotonic() - started
127
+ atomic_json(output / 'capture.json', state)
128
+
129
+
130
+ if __name__ == '__main__':
131
+ main()
cases/20261026_goal1012_05/code/lite3_ROS/scripts/diagnose_stretch_bev_blockage.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Trace a recorded BEV footprint rejection and compare it with depth and map memory.
3
+
4
+ Read-only offline analysis: no robot connection, model inference or policy changes.
5
+ """
6
+
7
+ import argparse
8
+ import csv
9
+ import json
10
+ import math
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ import cv2
15
+ import numpy as np
16
+
17
+ ROOT = Path(__file__).resolve().parents[1]
18
+ sys.path.insert(0, str(ROOT if (ROOT / "web_console").is_dir() else ROOT / "code/lite3_ROS"))
19
+ from web_console.stretch_nav_control import depth_obstacles, wrap # noqa: E402
20
+ from web_console.stretch_nav_geometry import body_to_world, world_to_body # noqa: E402
21
+ from web_console.stretch_nav_learned import reproject_bev # noqa: E402
22
+ from web_console.stretch_nav_recovery import rectangle_path_clear # noqa: E402
23
+ from web_console.stretch_nav_report import clean_json # noqa: E402
24
+ from web_console.stretch_vggt_debug import load_debug_frame # noqa: E402
25
+
26
+
27
+ def rectangle_samples(path, half=0.23, horizon=1.2):
28
+ """Same rotation/translation samples as the recorded rectangular guard."""
29
+ path = np.vstack([[0.0, 0.0], np.asarray(path, float).reshape(-1, 2)])
30
+ offsets = np.array(np.meshgrid(np.linspace(-half, half, 11), np.linspace(-half, half, 11))).reshape(2, -1).T
31
+ travelled, heading = 0.0, 0.0
32
+ for index, (a, b) in enumerate(zip(path[:-1], path[1:])):
33
+ distance = float(np.linalg.norm(b - a))
34
+ if distance < 1e-5:
35
+ continue
36
+ yaw = math.atan2(*(b - a)[::-1])
37
+ samples = [("rotate", a, angle) for angle in np.linspace(heading, heading + wrap(yaw - heading), 8)]
38
+ samples += [
39
+ ("translate", a + t * (b - a), yaw)
40
+ for t in np.linspace(
41
+ 0.0, min(1.0, max(0.0, horizon - travelled) / distance), max(2, int(distance / 0.04) + 1)
42
+ )
43
+ ]
44
+ for stage, center, angle in samples:
45
+ c, s = math.cos(angle), math.sin(angle)
46
+ yield index, stage, center, angle, offsets @ np.array([[c, s], [-s, c]]) + center
47
+ travelled, heading = travelled + distance, yaw
48
+ if travelled >= horizon:
49
+ break
50
+
51
+
52
+ def trace_rectangle(path, grid):
53
+ probability = np.asarray(grid["prob"]).copy()
54
+ n, res = len(probability), float(grid["res"])
55
+ axis = (n / 2 - np.arange(n) - 0.5) * res
56
+ probability[(abs(axis[:, None]) <= 0.23) & (abs(axis[None, :]) <= 0.23)] = 0.0
57
+ first, all_cells = None, set()
58
+ for segment, stage, center, angle, points in rectangle_samples(path):
59
+ rc = np.floor(n / 2 - points / res).astype(int)
60
+ inside = ((rc >= 0) & (rc < n)).all(1)
61
+ if not inside.all():
62
+ if first is None:
63
+ first = {
64
+ "reason": "outside grid",
65
+ "segment": segment,
66
+ "stage": stage,
67
+ "center_body_xy": center,
68
+ "yaw_rad": angle,
69
+ "cells": [],
70
+ }
71
+ continue
72
+ blocked = (probability[rc[:, 0], rc[:, 1]] > 0.6) & (grid["obs"][rc[:, 0], rc[:, 1]] > 0.5)
73
+ cells = np.unique(rc[blocked], axis=0)
74
+ all_cells.update(map(tuple, cells))
75
+ if len(cells) and first is None:
76
+ first = {
77
+ "reason": "learned occupancy",
78
+ "segment": segment,
79
+ "stage": stage,
80
+ "center_body_xy": center,
81
+ "yaw_rad": angle,
82
+ "cells": cells.tolist(),
83
+ }
84
+ result = {"clear": first is None, "first_contact": first, "all_blocking_cells": sorted(all_cells)}
85
+ assert result["clear"] == rectangle_path_clear(path, grid), (
86
+ "Diagnostic disagrees with recorded guard implementation"
87
+ )
88
+ return result
89
+
90
+
91
+ def project_ground(point_xy, source):
92
+ camera, K = np.asarray(source["camera_pose"]), np.asarray(source["camera_K"])
93
+ ground = np.r_[point_xy, np.asarray(source["base_pose_matrix"])[2, 3]]
94
+ camera_point = (ground - camera[:3, 3]) @ camera[:3, :3]
95
+ pixel = (K @ camera_point)[:2] / camera_point[2]
96
+ return pixel, camera_point
97
+
98
+
99
+ def depth_at_ground(run, source, point_xy):
100
+ pixel, camera_point = project_ground(point_xy, source)
101
+ depth = cv2.imread(str(run / "capture/depth" / f"{source['frame_idx']:08d}.png"), cv2.IMREAD_UNCHANGED)
102
+ if depth is None:
103
+ raise FileNotFoundError("Recorded depth missing")
104
+ result = {
105
+ "frame": source["frame_idx"],
106
+ "time_s": source["relative_time_s"],
107
+ "pixel_uv": pixel,
108
+ "expected_ground_depth_m": camera_point[2],
109
+ "inside_image": False,
110
+ }
111
+ u, v = np.rint(pixel).astype(int)
112
+ if camera_point[2] <= 0 or not (3 <= u < depth.shape[1] - 3 and 3 <= v < depth.shape[0] - 3):
113
+ return result
114
+ result["inside_image"] = True
115
+ patch = depth[v - 3 : v + 4, u - 3 : u + 4].astype(float) / 1000.0
116
+ vv, uu = np.mgrid[v - 3 : v + 4, u - 3 : u + 4]
117
+ valid = (patch > 0.1) & (patch < 3.0)
118
+ if not valid.any():
119
+ return result
120
+ K, camera = np.asarray(source["camera_K"]), np.asarray(source["camera_pose"])
121
+ z = patch[valid]
122
+ pc = np.column_stack([(uu[valid] - K[0, 2]) * z / K[0, 0], (vv[valid] - K[1, 2]) * z / K[1, 1], z])
123
+ points = pc @ camera[:3, :3].T + camera[:3, 3]
124
+ nearby = np.linalg.norm(points[:, :2] - point_xy, axis=1) <= 0.10
125
+ result.update(valid_depth_pixels=int(valid.sum()), nearby_returns=int(nearby.sum()))
126
+ if nearby.any():
127
+ height = points[nearby, 2] - np.asarray(source["base_pose_matrix"])[2, 3]
128
+ result.update(
129
+ median_height_m=float(np.median(height)),
130
+ min_height_m=float(height.min()),
131
+ max_height_m=float(height.max()),
132
+ floor_returns=int((abs(height) <= 0.08).sum()),
133
+ elevated_returns=int((height > 0.12).sum()),
134
+ median_depth_m=float(np.median(z[nearby])),
135
+ )
136
+ return result
137
+
138
+
139
+ def column_free_space(run, rows, point_xy):
140
+ """Positive ray evidence at sampled heights; exclude missing/long-range depth."""
141
+ heights = np.arange(0.12, 1.801, 0.12)
142
+ result = [{"height_m": float(z), "free_frames": [], "surface_frames": []} for z in heights]
143
+ for source in rows:
144
+ camera, K = np.asarray(source["camera_pose"]), np.asarray(source["camera_K"])
145
+ depth = cv2.imread(str(run / "capture/depth" / f"{source['frame_idx']:08d}.png"), -1).astype(float) / 1000.0
146
+ points = np.column_stack([np.repeat(np.asarray(point_xy)[None], len(heights), axis=0), heights])
147
+ pc = (points - camera[:3, 3]) @ camera[:3, :3]
148
+ uv = (pc @ K.T)[:, :2] / pc[:, 2:3]
149
+ for index, (u, v) in enumerate(np.rint(uv).astype(int)):
150
+ if pc[index, 2] <= 0 or not (0 <= u < depth.shape[1] and 0 <= v < depth.shape[0]):
151
+ continue
152
+ measured = depth[v, u]
153
+ if not 0.1 < measured < 10.0:
154
+ continue
155
+ residual = measured - pc[index, 2]
156
+ if residual > 0.08:
157
+ result[index]["free_frames"].append(source["frame_idx"])
158
+ elif abs(residual) <= 0.08:
159
+ result[index]["surface_frames"].append(source["frame_idx"])
160
+ return {
161
+ "method": "Measured depth exceeds expected optical depth by >8 cm at projected column samples; "
162
+ "only finite recorded depth between 0.1 and 10 m is used.",
163
+ "samples": result,
164
+ "note": "Discrete historical ray evidence, not a continuous collision certificate.",
165
+ }
166
+
167
+
168
+ def map_probability(state, point_xy):
169
+ world = state["world"]
170
+ row, col = np.floor((point_xy - world["o"]) / world["c"]["res"]).astype(int)[::-1]
171
+ den = float(world["den"][row, col])
172
+ return {
173
+ "row": int(row),
174
+ "column": int(col),
175
+ "weight": den,
176
+ "observability_sum": float(world["seen"][row, col]),
177
+ "occupancy": float(world["num"][row, col] / max(den, 1e-6)),
178
+ "block_threshold": world["c"]["block_p"],
179
+ "bump_count": len(state.get("bumps", [])),
180
+ }
181
+
182
+
183
+ def sampled(array, uv):
184
+ xy = np.asarray([[uv]], np.float32)
185
+ return float(cv2.remap(np.asarray(array, np.float32), xy[:, :, 0], xy[:, :, 1], cv2.INTER_LINEAR)[0, 0])
186
+
187
+
188
+ def draw_report(run, raw, frame, debug, cell, timeline, depth_history, output):
189
+ import matplotlib
190
+
191
+ matplotlib.use("Agg")
192
+ import matplotlib.pyplot as plt
193
+ from matplotlib.patches import Polygon, Rectangle
194
+
195
+ grid = debug["outputs"]["body_grid"]
196
+ observation = debug["outputs"]["observation"]
197
+ base = np.asarray(raw[frame]["base_pose_matrix"])
198
+ point = np.asarray(cell["world_xy"])
199
+ floor_rows = [x for x in depth_history if x.get("floor_returns", 0) >= 3]
200
+ earlier = max([x for x in floor_rows if 20 <= x["pixel_uv"][1] <= 600] or floor_rows, key=lambda x: x["frame"])
201
+ fig, axes = plt.subplots(2, 3, figsize=(17, 10), constrained_layout=True)
202
+ for axis, index, label in [
203
+ (axes[0, 0], frame, "Trigger frame"),
204
+ (axes[0, 1], earlier["frame"], "Same world location seen earlier"),
205
+ ]:
206
+ rgb = cv2.cvtColor(cv2.imread(str(run / "capture/rgb" / f"{index:08d}.jpg")), cv2.COLOR_BGR2RGB)
207
+ axis.imshow(rgb)
208
+ pixel, _ = project_ground(point, raw[index])
209
+ if 0 <= pixel[0] < rgb.shape[1] and 0 <= pixel[1] < rgb.shape[0]:
210
+ axis.scatter(*pixel, s=180, marker="o", facecolors="none", edgecolors="lime", linewidths=2)
211
+ else:
212
+ axis.annotate(
213
+ "Flagged ground cell is below this image",
214
+ xy=(np.clip(pixel[0], 0, rgb.shape[1] - 1), rgb.shape[0] - 8),
215
+ xytext=(12, rgb.shape[0] - 90),
216
+ color="white",
217
+ fontsize=9,
218
+ bbox={"facecolor": "black", "alpha": 0.8},
219
+ arrowprops={"arrowstyle": "->", "color": "red"},
220
+ )
221
+ axis.set_title(f"{label}: {index}")
222
+ axis.axis("off")
223
+
224
+ n, res = len(grid["prob"]), 0.05
225
+ extent = (n * res / 2, -n * res / 2, -n * res / 2, n * res / 2)
226
+ axis = axes[0, 2]
227
+ image = axis.imshow(grid["prob"], extent=extent, origin="upper", cmap="RdYlGn_r", vmin=0, vmax=1)
228
+ axis.contour(grid["obs"], levels=[0.5], extent=extent, origin="upper", colors="gray", linewidths=0.5)
229
+ axis.set_title("Current learned BEV: occupancy; gray = obs 0.5")
230
+ world = debug["outputs"]["planner_state"]["world"]
231
+ rr, cc = np.mgrid[:n, :n]
232
+ local = np.column_stack([(n / 2 - rr.ravel() - 0.5) * res, (n / 2 - cc.ravel() - 0.5) * res])
233
+ world_xy = body_to_world(local, base)
234
+ vu = ((world_xy - world["o"]) / world["c"]["res"] - 0.5).astype(np.float32)
235
+ probability = world["num"] / np.maximum(world["den"], 1e-6)
236
+ history_grid = cv2.remap(probability, vu[:, 0].reshape(n, n), vu[:, 1].reshape(n, n), cv2.INTER_LINEAR)
237
+ axes[1, 2].imshow(history_grid, extent=extent, origin="upper", cmap="RdYlGn_r", vmin=0, vmax=1)
238
+ axes[1, 2].set_title("Native map memory: low occupancy at X")
239
+ path = np.asarray(observation["native_local_path_body"])
240
+ for axis in [axes[0, 2], axes[1, 2]]:
241
+ axis.plot(path[:, 1], path[:, 0], color="blue", label="native path")
242
+ axis.scatter(cell["body_xy"][1], cell["body_xy"][0], c="black", marker="x", s=85, label="first blocking cell")
243
+ axis.add_patch(Rectangle((-0.23, -0.23), 0.46, 0.46, fill=False, color="black", linewidth=1.5))
244
+ contact = cell["contact"]
245
+ c, s = np.cos(contact["yaw_rad"]), np.sin(contact["yaw_rad"])
246
+ corners = np.array([[-0.23, -0.23], [-0.23, 0.23], [0.23, 0.23], [0.23, -0.23]])
247
+ corners = corners @ np.array([[c, s], [-s, c]]) + contact["center_body_xy"]
248
+ axis.add_patch(Polygon(corners[:, ::-1], fill=False, edgecolor="purple", label="first rejected footprint"))
249
+ axis.set(xlim=(1.3, -1.3), ylim=(-0.4, 2.1), xlabel="Left [m]", ylabel="Forward [m]")
250
+ axis.set_aspect("equal")
251
+ axis.legend(fontsize=7, loc="upper left")
252
+ fig.colorbar(image, ax=[axes[0, 2], axes[1, 2]], label="Occupancy prediction", shrink=0.6)
253
+
254
+ axis = axes[1, 0]
255
+ axis.plot([x["time_s"] for x in timeline], [x["current_occupancy"] for x in timeline], "o-", label="current BEV")
256
+ axis.plot(
257
+ [x["time_s"] for x in timeline], [x["fused_occupancy"] for x in timeline], ".-", label="native map memory"
258
+ )
259
+ axis.axhline(0.6, color="red", linestyle="--", label="occupancy threshold")
260
+ axis.set(
261
+ xlabel="Capture-relative time [s]",
262
+ ylabel="Occupancy at same world point",
263
+ ylim=(0, 1),
264
+ title="Transient rise in the current BEV",
265
+ )
266
+ axis.legend(fontsize=8)
267
+ axis.grid(alpha=0.2)
268
+ axis = axes[1, 1]
269
+ depth_rows = [x for x in depth_history if x.get("nearby_returns", 0)]
270
+ axis.plot(
271
+ [x["time_s"] for x in depth_rows], [x["median_height_m"] for x in depth_rows], ".", label="measured height"
272
+ )
273
+ axis.axhline(0.12, color="red", linestyle="--", label="depth guard obstacle height")
274
+ axis.axhspan(-0.08, 0.08, color="green", alpha=0.15, label="floor comparison band")
275
+ axis.set(
276
+ xlabel="Capture-relative time [s]",
277
+ ylabel="Height over base origin [m]",
278
+ ylim=(-0.12, 0.3),
279
+ title="Depth returns at that location agree with floor",
280
+ )
281
+ axis.legend(fontsize=8)
282
+ axis.grid(alpha=0.2)
283
+ fig.suptitle(f"Frame {frame}: false-occupancy evidence and the local adapter survey trigger", fontsize=15)
284
+ fig.savefig(output / "blockage_analysis.png", dpi=150)
285
+ plt.close(fig)
286
+
287
+
288
+ def main():
289
+ parser = argparse.ArgumentParser(description=__doc__)
290
+ parser.add_argument("--run", type=Path, required=True)
291
+ parser.add_argument("--frame", type=int, default=494)
292
+ parser.add_argument("--output", type=Path, required=True)
293
+ args = parser.parse_args()
294
+ run, output, frame = args.run.resolve(), args.output.resolve(), args.frame
295
+ output.mkdir(parents=True, exist_ok=True)
296
+ raw = {x["frame_idx"]: x for x in map(json.loads, (run / "capture/observations.jsonl").read_text().splitlines())}
297
+ debug = load_debug_frame(run / "vggt_debug", frame)
298
+ result = debug["outputs"]
299
+ observation, grid = result["observation"], {**result["body_grid"], "res": result["consumed_bev"]["res"]}
300
+ trace = trace_rectangle(observation["native_local_path_body"], grid)
301
+ if trace["clear"] or not trace["first_contact"]["cells"]:
302
+ raise ValueError("Selected frame has no learned occupancy rejection")
303
+ rc = np.array(trace["first_contact"]["cells"][0])
304
+ body = (len(grid["prob"]) / 2 - rc - 0.5) * grid["res"]
305
+ world_point = body_to_world([body], np.asarray(raw[frame]["base_pose_matrix"]))[0]
306
+ cell = {
307
+ "row": int(rc[0]),
308
+ "column": int(rc[1]),
309
+ "body_xy": body,
310
+ "world_xy": world_point,
311
+ "probability": grid["prob"][tuple(rc)],
312
+ "observability": grid["obs"][tuple(rc)],
313
+ "error_score": grid["err"][tuple(rc)],
314
+ "contact": trace["first_contact"],
315
+ }
316
+ counterfactual = {**grid, "prob": grid["prob"].copy()}
317
+ counterfactual["prob"][tuple(rc)] = 0.0
318
+ history = [
319
+ depth_at_ground(run, row, world_point)
320
+ for index, row in sorted(raw.items())
321
+ if index <= frame and raw[frame]["relative_time_s"] - row["relative_time_s"] <= 20.0
322
+ ]
323
+ timeline = []
324
+ for path in sorted((run / "vggt_debug/frames").glob("*/frame.json")):
325
+ index = int(path.parent.name)
326
+ if (
327
+ index > frame + 2
328
+ or index not in raw
329
+ or raw[frame]["relative_time_s"] - raw[index]["relative_time_s"] > 20.0
330
+ ):
331
+ continue
332
+ data = load_debug_frame(run / "vggt_debug", index)
333
+ out = data.get("outputs", {})
334
+ if not out.get("body_grid") or not out.get("planner_state", {}).get("world"):
335
+ continue
336
+ base = np.asarray(raw[index]["base_pose_matrix"])
337
+ local = world_to_body(world_point, base)
338
+ pixel = (len(grid["prob"]) / 2 - local / grid["res"] - 0.5)[::-1]
339
+ g = out["body_grid"]
340
+ timeline.append(
341
+ {
342
+ "frame": index,
343
+ "time_s": raw[index]["relative_time_s"],
344
+ "current_occupancy": sampled(g["prob"], pixel),
345
+ "current_observability": sampled(g["obs"], pixel),
346
+ "fused_occupancy": map_probability(out["planner_state"], world_point)["occupancy"],
347
+ }
348
+ )
349
+ bev = result["consumed_bev"]
350
+ recomputed = reproject_bev(
351
+ bev["prob"],
352
+ bev["observability"],
353
+ bev["uncertainty"],
354
+ bev["R_bev_from_cam"],
355
+ np.asarray(raw[frame]["camera_pose"]),
356
+ np.asarray(raw[frame]["base_pose_matrix"]),
357
+ grid["res"],
358
+ )
359
+ source_uv = grid["base_pixel_to_camera_pixel"] @ np.r_[rc[::-1], 1.0]
360
+ raw_head = debug["passes"][0]["head_calls"][0]["outputs"]
361
+ with np.load(run / "footprint_evidence" / f"{frame:08d}.npz", allow_pickle=False) as evidence:
362
+ memory = evidence["measured_obstacles_odom"].copy()
363
+ depth = cv2.imread(str(run / "capture/depth" / f"{frame:08d}.png"), cv2.IMREAD_UNCHANGED).astype(float) / 1000
364
+ current_obstacles = depth_obstacles(depth, raw[frame]["camera_K"], raw[frame]["camera_pose"])
365
+ floors = [x for x in history if x.get("floor_returns", 0) >= 3 and x.get("elevated_returns") == 0]
366
+ report = {
367
+ "run": run.name,
368
+ "capture_frame": frame,
369
+ "native_planner_status": observation["native_planner_status"],
370
+ "native_status_meaning": "6 = valid episode-map route",
371
+ "recorded_rectangle_clear": observation["rectangle_clear"],
372
+ "trace": trace,
373
+ "first_blocking_cell": cell,
374
+ "native_accumulated_map_at_cell": map_probability(result["planner_state"], world_point),
375
+ "raw_head_occupancy_at_same_cell": sampled(raw_head["prob"], source_uv),
376
+ "counterfactual_one_cell_removed": {
377
+ "rectangle_clear": rectangle_path_clear(observation["native_local_path_body"], counterfactual),
378
+ "note": "Offline attribution test only; the recorded/runtime prediction and thresholds are unchanged.",
379
+ },
380
+ "base_reprojection_max_absolute_difference": float(abs(recomputed["prob"] - grid["prob"]).max()),
381
+ "thresholds": {"occupancy": 0.6, "observability": 0.5},
382
+ "current_image_projection": depth_at_ground(run, raw[frame], world_point),
383
+ "floor_history_observations": len(floors),
384
+ "latest_floor_observation": max(floors, key=lambda x: x["frame"]),
385
+ "nearby_elevated_returns_current": int((np.linalg.norm(current_obstacles - world_point, axis=1) <= 0.1).sum()),
386
+ "nearby_elevated_returns_remembered": int((np.linalg.norm(memory - world_point, axis=1) <= 0.1).sum()),
387
+ "all_depth_history": history,
388
+ "occupancy_timeline": timeline,
389
+ "column_free_space": column_free_space(run, [raw[x["frame"]] for x in history], world_point),
390
+ "vggt_inputs": [
391
+ {"role": v["role"], "reference": v.get("reference"), "asset": v["asset"]}
392
+ for v in debug["passes"][0]["views"]
393
+ ],
394
+ "finding": "A transient current-frame occupancy prediction triggers the added rectangular path guard, "
395
+ "while native map-memory planning still supplies a route. The first rejected cell is below "
396
+ "the current image and agrees with floor in recent RGB-D history. This strongly supports "
397
+ "a false obstacle at that cell; it does not certify every part of the physical route.",
398
+ }
399
+ (output / "report.json").write_text(json.dumps(clean_json(report), indent=2, allow_nan=False) + "\n")
400
+ with (output / "occupancy_timeline.csv").open("w", newline="") as f:
401
+ writer = csv.DictWriter(f, fieldnames=list(timeline[0]))
402
+ writer.writeheader()
403
+ writer.writerows(timeline)
404
+ draw_report(run, raw, frame, debug, cell, timeline, history, output)
405
+ print(
406
+ json.dumps(
407
+ clean_json(
408
+ {
409
+ k: v
410
+ for k, v in report.items()
411
+ if k not in {"all_depth_history", "occupancy_timeline", "column_free_space", "vggt_inputs"}
412
+ }
413
+ ),
414
+ indent=2,
415
+ )
416
+ )
417
+
418
+
419
+ if __name__ == "__main__":
420
+ main()
cases/20261026_goal1012_05/code/lite3_ROS/scripts/diagnose_stretch_bev_region.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare arbitrary saved BEV cells with survey depth, raw heads and planner memory; no hardware."""
2
+
3
+ import argparse
4
+ import csv
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import cv2
10
+ import numpy as np
11
+
12
+ ROOT = Path(__file__).resolve().parents[1]
13
+ sys.path.insert(0, str(ROOT if (ROOT / 'web_console').is_dir() else ROOT / 'code/lite3_ROS'))
14
+ from scripts.diagnose_stretch_bev_blockage import ( # noqa: E402
15
+ column_free_space,
16
+ depth_at_ground,
17
+ map_probability,
18
+ project_ground,
19
+ sampled,
20
+ )
21
+ from web_console.stretch_nav_geometry import body_to_world, world_to_body # noqa: E402
22
+ from web_console.stretch_nav_learned import reproject_bev # noqa: E402
23
+ from web_console.stretch_nav_report import clean_json # noqa: E402
24
+ from web_console.stretch_vggt_debug import load_debug_frame # noqa: E402
25
+
26
+
27
+ def timeline(run, raw, cells, begin, end):
28
+ result = []
29
+ for path in sorted((run / 'vggt_debug/frames').glob('*/frame.json')):
30
+ index = int(path.parent.name)
31
+ if index > end or raw[index]['relative_time_s'] < begin:
32
+ continue
33
+ data = json.loads(path.read_text())
34
+ metadata = data.get('outputs', {})
35
+ if not metadata.get('body_grid') or not metadata.get('planner_state'):
36
+ continue
37
+ with np.load(path.parent / 'arrays.npz', allow_pickle=False) as archive:
38
+ cache = {}
39
+
40
+ def unpack(value):
41
+ if isinstance(value, dict):
42
+ if 'npz_key' in value:
43
+ key = value['npz_key']
44
+ if key not in cache:
45
+ cache[key] = archive[key]
46
+ return cache[key]
47
+ return {k: unpack(v) for k, v in value.items()}
48
+ if isinstance(value, list):
49
+ return [unpack(v) for v in value]
50
+ return value
51
+
52
+ grid = unpack(metadata['body_grid'])
53
+ state = unpack(metadata['planner_state'])
54
+ n, res = len(grid['prob']), .05
55
+ for cell in cells:
56
+ body = world_to_body(cell['world_xy'], np.asarray(raw[index]['base_pose_matrix']))
57
+ rc = np.floor(n / 2 - body / res).astype(int)
58
+ if not ((rc >= 0) & (rc < n)).all():
59
+ continue
60
+ result.append({'frame': index, 'time_s': raw[index]['relative_time_s'], 'cell': cell['label'],
61
+ 'current_occupancy': float(grid['prob'][tuple(rc)]),
62
+ 'current_observability': float(grid['obs'][tuple(rc)]),
63
+ 'fused_occupancy': map_probability(state, cell['world_xy'])['occupancy']})
64
+ return result
65
+
66
+
67
+ def figure(run, raw, debug, cells, curve, output):
68
+ import matplotlib
69
+
70
+ matplotlib.use('Agg')
71
+ import matplotlib.pyplot as plt
72
+ from matplotlib.patches import Rectangle
73
+
74
+ frame = debug['capture_frame']
75
+ floor_views = [row for row in cells[0]['depth_history'] if row.get('floor_returns', 0) >= 40]
76
+ selected = max(floor_views, key=lambda row: min(row['pixel_uv'][0], 480 - row['pixel_uv'][0],
77
+ row['pixel_uv'][1], 640 - row['pixel_uv'][1]))['frame']
78
+ fig, axes = plt.subplots(2, 3, figsize=(17, 10), constrained_layout=True)
79
+ for axis, index, title in ((axes[0, 0], frame, 'Current RGB'),
80
+ (axes[0, 1], selected, 'Survey RGB: same fixed world cells')):
81
+ rgb = cv2.cvtColor(cv2.imread(str(run / 'capture/rgb' / f'{index:08d}.jpg')), cv2.COLOR_BGR2RGB)
82
+ axis.imshow(rgb)
83
+ for cell in cells:
84
+ uv, _ = project_ground(cell['world_xy'], raw[index])
85
+ if 0 <= uv[0] < rgb.shape[1] and 0 <= uv[1] < rgb.shape[0]:
86
+ axis.scatter(*uv, s=170, facecolors='none', edgecolors='lime', linewidths=2)
87
+ axis.annotate(cell['label'], uv + [8, -8], color='lime', weight='bold')
88
+ axis.set_title(f'{title}, frame {index}')
89
+ axis.axis('off')
90
+ axes[0, 0].text(.02, .98, 'A and B ground centres are outside this view', transform=axes[0, 0].transAxes,
91
+ va='top', color='white', bbox={'facecolor': 'black', 'alpha': .7})
92
+ grid = debug['outputs']['body_grid']
93
+ half, res = len(grid['prob']) * .05 / 2, .05
94
+ extent = (half, -half, -half, half)
95
+ axes[0, 2].imshow(grid['prob'], extent=extent, origin='upper', cmap='RdYlGn_r', vmin=0, vmax=1)
96
+ axes[0, 2].set(xlim=(3., -3.), ylim=(-.5, 5.), title='Current BEV: forward-left red patch',
97
+ xlabel='Left [m]', ylabel='Forward [m]')
98
+ world = debug['outputs']['planner_state']['world']
99
+ n = len(grid['prob'])
100
+ rr, cc = np.mgrid[:n, :n]
101
+ local = np.column_stack([(n / 2 - rr.ravel() - .5) * res, (n / 2 - cc.ravel() - .5) * res])
102
+ xy = body_to_world(local, np.asarray(raw[frame]['base_pose_matrix']))
103
+ uv = ((xy - world['o']) / world['c']['res'] - .5).astype(np.float32)
104
+ fused = cv2.remap(world['num'] / np.maximum(world['den'], 1e-6),
105
+ uv[:, 0].reshape(n, n), uv[:, 1].reshape(n, n), cv2.INTER_LINEAR)
106
+ for axis, values, title in ((axes[1, 0], grid['prob'], 'Current occupancy: detailed near field'),
107
+ (axes[1, 1], fused, 'Separate native planner memory')):
108
+ axis.imshow(values, extent=extent, origin='upper', cmap='RdYlGn_r', vmin=0, vmax=1)
109
+ axis.set(xlim=(1.5, -.3), ylim=(-.3, 1.5), title=title, xlabel='Left [m]', ylabel='Forward [m]')
110
+ for axis in (axes[0, 2], axes[1, 0], axes[1, 1]):
111
+ axis.add_patch(Rectangle((-.23, -.23), .46, .46, fill=False, color='black', linewidth=1.5))
112
+ for cell in cells:
113
+ fwd, left = cell['body_xy']
114
+ axis.scatter(left, fwd, marker='x', color='black', s=60)
115
+ axis.annotate(cell['label'], (left + .025, fwd + .025), weight='bold')
116
+ axis.set_aspect('equal')
117
+ for label, style in (('A', '-'), ('B', '--')):
118
+ points = [x for x in curve if x['cell'] == label]
119
+ axes[1, 2].plot([x['time_s'] for x in points], [x['current_occupancy'] for x in points],
120
+ style, label=f'{label}: current')
121
+ axes[1, 2].plot([x['time_s'] for x in points], [x['fused_occupancy'] for x in points],
122
+ style, alpha=.6, label=f'{label}: fused memory')
123
+ axes[1, 2].axhline(.6, color='red', linewidth=.8, label='blocking threshold')
124
+ axes[1, 2].set(xlabel='Capture-relative time [s]', ylabel='Occupancy', ylim=(0, 1),
125
+ title='Same fixed world cells through the survey')
126
+ axes[1, 2].legend(fontsize=8)
127
+ axes[1, 2].grid(alpha=.2)
128
+ fig.suptitle('Frame 747: false occupancy in the nearby forward-left patch', fontsize=15)
129
+ fig.savefig(output / 'region_analysis.png', dpi=150)
130
+ plt.close(fig)
131
+
132
+
133
+ def main():
134
+ parser = argparse.ArgumentParser(description=__doc__)
135
+ parser.add_argument('--run', type=Path, required=True)
136
+ parser.add_argument('--frame', type=int, default=747)
137
+ parser.add_argument('--output', type=Path, required=True)
138
+ args = parser.parse_args()
139
+ run, output, frame = args.run.resolve(), args.output.resolve(), args.frame
140
+ output.mkdir(parents=True, exist_ok=True)
141
+ raw = {r['frame_idx']: r for r in map(json.loads,
142
+ (run / 'capture/observations.jsonl').read_text().splitlines())}
143
+ debug = load_debug_frame(run / 'vggt_debug', frame)
144
+ grid, bev = debug['outputs']['body_grid'], debug['outputs']['consumed_bev']
145
+ history = [r for r in raw.values() if r['frame_idx'] <= frame and
146
+ r['relative_time_s'] >= raw[frame]['relative_time_s'] - 60.]
147
+ recomputed = reproject_bev(bev['prob'], bev['observability'], bev['uncertainty'],
148
+ bev['R_bev_from_cam'], raw[frame]['camera_pose'], raw[frame]['base_pose_matrix'], bev['res'])
149
+ cells = []
150
+ for label, rc in (('A', (190, 190)), ('B', (189, 189))):
151
+ body = (len(grid['prob']) / 2 - np.asarray(rc) - .5) * bev['res']
152
+ xy = body_to_world([body], np.asarray(raw[frame]['base_pose_matrix']))[0]
153
+ depth_history = [depth_at_ground(run, source, xy) for source in history]
154
+ floors = [row for row in depth_history if row.get('floor_returns', 0) >= 3 and
155
+ row.get('elevated_returns', 0) == 0]
156
+ if not floors:
157
+ raise ValueError('No supporting floor observation at selected cell')
158
+ uv = grid['base_pixel_to_camera_pixel'] @ [rc[1], rc[0], 1.]
159
+ raw_head = debug['passes'][0]['head_calls'][0]['outputs']
160
+ cells.append({'label': label, 'row': rc[0], 'column': rc[1], 'body_xy': body,
161
+ 'world_xy': xy, 'current_occupancy': float(grid['prob'][rc]),
162
+ 'observability': float(grid['obs'][rc]), 'error_score': float(grid['err'][rc]),
163
+ 'raw_head_occupancy': sampled(raw_head['prob'], uv),
164
+ 'native_memory': map_probability(debug['outputs']['planner_state'], xy),
165
+ 'current_floor_projection': depth_history[-1], 'floor_observations': len(floors),
166
+ 'latest_floor_observation': floors[-1], 'depth_history': depth_history,
167
+ 'column_free_space': column_free_space(run, history, xy)})
168
+ curve = timeline(run, raw, cells, history[0]['relative_time_s'], frame)
169
+ report = {'run': run.name, 'capture_frame': frame,
170
+ 'display_provenance': 'The viewer uses the current reprojected VGGT BEV. '
171
+ 'Native planner WorldMap memory is separate.',
172
+ 'reprojection_max_abs_difference': float(abs(recomputed['prob'] - grid['prob']).max()),
173
+ 'cells': cells, 'occupancy_timeline': curve,
174
+ 'vggt_input_views': debug['passes'][0]['views'],
175
+ 'finding': 'The selected nearby forward-left cells have high current learned occupancy despite positive '
176
+ 'survey floor and free-space ray evidence. This supports a false-occupancy diagnosis at these '
177
+ 'cells, without declaring the entire left-hand furniture row absent.',
178
+ 'stop_relationship': 'The eventual fatal stop was the separate measured-depth graph-attachment veto. '
179
+ 'These selected cells are not asserted to have caused that stop.'}
180
+ (output / 'region_report.json').write_text(json.dumps(clean_json(report), indent=2, allow_nan=False) + '\n')
181
+ with (output / 'occupancy_timeline.csv').open('w', newline='') as stream:
182
+ writer = csv.DictWriter(stream, fieldnames=list(curve[0]))
183
+ writer.writeheader()
184
+ writer.writerows(curve)
185
+ figure(run, raw, debug, cells, curve, output)
186
+ print(json.dumps(clean_json({'frame': frame, 'reprojection_difference': report['reprojection_max_abs_difference'],
187
+ 'cells': [{k: c[k] for k in ('label', 'body_xy', 'current_occupancy', 'observability',
188
+ 'raw_head_occupancy', 'native_memory', 'floor_observations',
189
+ 'latest_floor_observation')} for c in cells]}), indent=2))
190
+
191
+
192
+ if __name__ == '__main__':
193
+ main()
cases/20261026_goal1012_05/code/lite3_ROS/scripts/inspect_stretch_vggt_debug.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Export one saved VGGT input group, depth views and BEV stages without a GPU."""
3
+
4
+ import argparse
5
+ import json
6
+ import math
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import cv2
11
+ import numpy as np
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ sys.path.insert(0, str(ROOT))
15
+ from web_console.stretch_vggt_debug import load_debug_frame, load_debug_view, write_npz # noqa: E402
16
+
17
+
18
+ def sheet(images, labels, *, width=256, height=342, columns=4):
19
+ columns = min(columns, len(images))
20
+ rows = math.ceil(len(images) / columns)
21
+ canvas = np.full((rows * (height + 48), columns * width, 3), 24, np.uint8)
22
+ for index, (image, label) in enumerate(zip(images, labels)):
23
+ y, x = divmod(index, columns)
24
+ y, x = y * (height + 48), x * width
25
+ h, w = image.shape[:2]
26
+ scale = min(width / w, height / h)
27
+ resized = cv2.resize(image, (max(1, round(w * scale)), max(1, round(h * scale))))
28
+ ox, oy = x + (width - resized.shape[1]) // 2, y + 42 + (height - resized.shape[0]) // 2
29
+ canvas[oy:oy + resized.shape[0], ox:ox + resized.shape[1]] = resized
30
+ cv2.putText(canvas, label[:42], (x + 6, y + 24), cv2.FONT_HERSHEY_SIMPLEX, .43, (235, 235, 235), 1)
31
+ return canvas
32
+
33
+
34
+ def probability_image(array):
35
+ p = np.clip(np.nan_to_num(np.asarray(array, float), nan=.5), 0, 1)
36
+ return np.stack((np.full_like(p, 80), 200 * (1 - p) + 35, 210 * p + 25), -1).astype(np.uint8)
37
+
38
+
39
+ def export_frame(directory, number, output, pass_index=0):
40
+ data = load_debug_frame(directory, number)
41
+ if not data['passes']:
42
+ raise ValueError('No VGGT inference occurred on this frame; choose a frame with passes in index.jsonl')
43
+ call = data['passes'][pass_index]
44
+ views = call['views']
45
+ inputs = [load_debug_view(directory, view['asset']) for view in views]
46
+ images = [(np.clip(image.transpose(1, 2, 0), 0, 1) * 255).round().astype(np.uint8)[..., ::-1]
47
+ for image in inputs]
48
+ labels = [f"{view['index']} {view['role']}" +
49
+ (f" kf {view['reference'].get('id', view['reference'].get('keyframe_id'))}"
50
+ if 'reference' in view else '') for view in views]
51
+ output = Path(output)
52
+ output.mkdir(parents=True, exist_ok=True)
53
+ cv2.imwrite(str(output / 'input_views.jpg'), sheet(images, labels))
54
+ write_npz(output / 'model_inputs.npz', {'images': np.stack(inputs)})
55
+ prediction = call.get('prediction', {})
56
+ depth = prediction.get('depth')
57
+ if depth is not None and len(depth):
58
+ colored = []
59
+ for view in depth:
60
+ finite = view[np.isfinite(view) & (view > 0)]
61
+ upper = np.percentile(finite, 98) if len(finite) else 1.
62
+ scaled = np.clip(np.nan_to_num(view / max(upper, 1e-9)), 0, 1)
63
+ colored.append(cv2.applyColorMap((255 * scaled).astype(np.uint8), cv2.COLORMAP_TURBO))
64
+ cv2.imwrite(str(output / 'predicted_depth.jpg'), sheet(colored, labels[:len(colored)]))
65
+ out = data.get('outputs', {})
66
+ head = call.get('head_calls', [])
67
+ stages = [('raw head: camera BEV', head[0]['outputs'] if head else None),
68
+ ('consumed: camera BEV', out.get('consumed_bev')),
69
+ ('robot base BEV', out.get('body_grid'))]
70
+ tiles, names = [], []
71
+ for stage, value in stages:
72
+ if not value:
73
+ continue
74
+ for key, alias in (('prob', 'prob'), ('observability', 'obs'), ('uncertainty', 'err')):
75
+ if value.get(key, value.get(alias)) is not None:
76
+ layer = value.get(key, value.get(alias))
77
+ tiles.append(probability_image(1 - layer if key == 'observability' else layer))
78
+ names.append(f'{stage}: {key}')
79
+ if tiles:
80
+ cv2.imwrite(str(output / 'bev_stages.png'), sheet(tiles, names, width=300, height=300, columns=3))
81
+ metadata = json.loads((Path(directory) / 'frames' / f'{number:08d}' / 'frame.json').read_text())
82
+ (output / 'manifest.json').write_text(json.dumps(metadata, indent=2) + '\n')
83
+ return {'capture_frame': number, 'pass_index': pass_index, 'views': len(views), 'output': str(output.resolve())}
84
+
85
+
86
+ def main():
87
+ parser = argparse.ArgumentParser(description=__doc__)
88
+ parser.add_argument('--debug', type=Path, required=True)
89
+ parser.add_argument('--frame', type=int, required=True)
90
+ parser.add_argument('--pass-index', type=int, default=0)
91
+ parser.add_argument('--output', type=Path)
92
+ args = parser.parse_args()
93
+ output = args.output or args.debug / 'inspection' / f'{args.frame:08d}'
94
+ print(json.dumps(export_frame(args.debug, args.frame, output, args.pass_index), indent=2))
95
+
96
+
97
+ if __name__ == '__main__':
98
+ main()
cases/20261026_goal1012_05/code/lite3_ROS/scripts/live_stretch_cross_nav.py ADDED
@@ -0,0 +1,992 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Live native CROSS navigation with explicit browser handoff and expiring control.
3
+
4
+ Starts in passive teleop mode. Only Start navigation may switch mode/arm the
5
+ robot. Stop/failure ends this run and closes its temporary robot relay.
6
+ """
7
+ # Local imports follow the repository-path bootstrap for direct execution.
8
+ # ruff: noqa: E402
9
+ import argparse
10
+ import json
11
+ import math
12
+ import os
13
+ import pickle
14
+ import secrets
15
+ import signal
16
+ import sys
17
+ import threading
18
+ import time
19
+ import uuid
20
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
21
+ from pathlib import Path
22
+ from types import SimpleNamespace
23
+ from urllib.parse import parse_qs, urlsplit
24
+
25
+ import cv2
26
+ import numpy as np
27
+ import zmq
28
+
29
+ ROOT = Path(__file__).resolve().parents[1]
30
+ sys.path.insert(0, str(ROOT))
31
+ from web_console.cross_run import RunArtifacts, matrix
32
+ from web_console.stretch_nav_control import (
33
+ DEFAULT_MAX_PLAN_AGE,
34
+ DEFAULT_PLAN_HOLD_SECONDS,
35
+ PlanWait,
36
+ attachment_clear,
37
+ competing_controllers,
38
+ depth_obstacles,
39
+ depth_veto,
40
+ execution_gate,
41
+ remaining_path,
42
+ stationary_head_command,
43
+ wrap,
44
+ )
45
+ from web_console.stretch_nav_footprint import command_footprint_report, depth_support
46
+ from web_console.stretch_nav_geometry import body_to_world, world_to_body
47
+ from web_console.stretch_nav_learned import learned_png, reproject_bev
48
+ from web_console.stretch_nav_recovery import (
49
+ CornerObserver,
50
+ CorrectionRecovery,
51
+ MeasuredObstacleMemory,
52
+ camera_in_base,
53
+ clear_goal_cache,
54
+ rectangle_path_clear,
55
+ route_subgoal,
56
+ )
57
+ from web_console.stretch_nav_replay import ReplayService, save_bev_frame
58
+ from web_console.stretch_nav_report import SavedRoute, clean_json, positions, save_json
59
+ from web_console.stretch_nav_survey import HeadSurvey
60
+ from web_console.stretch_transport import camera_transport_diagnostics
61
+ from web_console.stretch_vggt_debug import VggtDebugRecorder, model_provenance, planner_snapshot
62
+
63
+
64
+ def warmup_native_navigation():
65
+ """Compile native grid searches before opening any robot transport."""
66
+ try:
67
+ import numba
68
+ except ImportError as exc:
69
+ raise RuntimeError('Live navigation requires CROSS nav dependencies: install CROSS[nav] in this environment') from exc
70
+ from cross_nav.plan import _dijkstra
71
+ from cross_nav.policy.bev_policy import _astar, astar
72
+
73
+ search = _astar()
74
+ if not hasattr(search, 'signatures') or not hasattr(_dijkstra, 'signatures'):
75
+ raise RuntimeError('Live navigation requires CROSS nav dependencies: install CROSS[nav] in this environment')
76
+ started = time.perf_counter()
77
+ ok = np.ones((8, 8), dtype=bool)
78
+ cost = np.ones((8, 8), dtype=np.float64)
79
+ astar(ok, cost, [4, 4], [4, 6])
80
+ _dijkstra(ok, 4, 4, cost, False, True)
81
+ return {'numba_version': numba.__version__, 'warmup_s': time.perf_counter() - started,
82
+ 'astar_signatures': [str(value) for value in search.signatures],
83
+ 'dijkstra_signatures': [str(value) for value in _dijkstra.signatures]}
84
+
85
+
86
+ class LiveState:
87
+ def __init__(self, args):
88
+ self.args = args
89
+ self.lock = threading.RLock()
90
+ self.done = threading.Event()
91
+ self.token = secrets.token_urlsafe(24)
92
+ self.session = uuid.uuid4().hex
93
+ self.packet = self.plan = self.robot = None
94
+ self.plan_epoch = 0
95
+ self.observation_requested = False
96
+ self.observation_reason = ''
97
+ self.last_control = {}
98
+ self.robot_received = self.heartbeat = -math.inf
99
+ self.phase, self.reason = 'teleop', 'Loading models; teleop remains in control'
100
+ self.commanded = 0.
101
+ self.motion_commands = 0
102
+ self.relay_ever_requested = False
103
+ self.processed = 0
104
+ self.conflicts = []
105
+ self.images = {}
106
+ self.last_json = {}
107
+ self.replay = ReplayService(args.output)
108
+ self.events = (args.output / 'events.jsonl').open('a', buffering=1)
109
+
110
+ def event(self, kind, **data):
111
+ with self.lock:
112
+ self.events.write(json.dumps(clean_json({'type': kind, 'time_unix': time.time(), **data})) + '\n')
113
+
114
+ def finish(self, reason):
115
+ with self.lock:
116
+ self.phase, self.reason = 'stopped', reason
117
+ self.done.set()
118
+ self.event('stop', reason=reason)
119
+
120
+ def gate(self):
121
+ if self.phase == 'stopped':
122
+ return 'session ended'
123
+ if self.conflicts:
124
+ return 'Close competing base controller: ' + ', '.join(f"{c['client']} (PID {c['pid']})" for c in self.conflicts)
125
+ return execution_gate(self.plan, self.robot, now=time.monotonic(),
126
+ robot_received=self.robot_received, heartbeat=self.heartbeat, state='preparing',
127
+ max_plan_age=self.args.max_plan_age)
128
+
129
+ def snapshot(self):
130
+ with self.lock:
131
+ return clean_json({'phase': self.phase, 'reason': self.reason,
132
+ 'ready': self.phase == 'teleop' and not self.gate(), 'gate': self.gate(),
133
+ 'goal_keyframe': self.args.goal, 'processed': self.processed,
134
+ 'robot': self.robot, 'motion_commands': self.motion_commands,
135
+ 'frame': self.last_json, 'control': self.last_control, 'token': self.token,
136
+ 'capture_frame': self.packet['frame_idx'] if self.packet is not None else None,
137
+ 'v_max': self.args.max_v, 'w_max': self.args.max_w,
138
+ 'max_plan_age_s': self.args.max_plan_age, 'competing_controllers': self.conflicts,
139
+ 'replay_available': self.phase == 'stopped' and (self.args.output / 'final_status.json').is_file()})
140
+
141
+
142
+ class Handler(BaseHTTPRequestHandler):
143
+ def log_message(self, *_):
144
+ pass
145
+
146
+ def send(self, code, body, mime='application/json'):
147
+ body = body if isinstance(body, bytes) else json.dumps(clean_json(body), allow_nan=False).encode()
148
+ self.send_response(code)
149
+ self.send_header('Content-Type', mime)
150
+ self.send_header('Content-Length', str(len(body)))
151
+ self.send_header('Cache-Control', 'no-store')
152
+ self.send_header('X-Content-Type-Options', 'nosniff')
153
+ self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; worker-src 'self' blob:; frame-ancestors 'none'")
154
+ self.end_headers()
155
+ try:
156
+ self.wfile.write(body)
157
+ except (BrokenPipeError, ConnectionResetError):
158
+ pass
159
+
160
+ def do_GET(self):
161
+ state = self.server.state
162
+ path = self.path.split('?', 1)[0]
163
+ assets = {'/': ('cross_nav_live.html', 'text/html; charset=utf-8'),
164
+ '/cross_nav_live.js': ('cross_nav_live.js', 'text/javascript'),
165
+ '/cross_nav.css': ('cross_nav.css', 'text/css'),
166
+ '/vendor/plotly.min.js': ('vendor/plotly.min.js', 'text/javascript')}
167
+ try:
168
+ if path in assets:
169
+ file, mime = assets[path]
170
+ return self.send(200, (ROOT / 'web_console/static' / file).read_bytes(), mime)
171
+ if path == '/api/status':
172
+ return self.send(200, state.snapshot())
173
+ if path == '/api/map':
174
+ return self.send(200, state.map_data)
175
+ if path.startswith('/api/replay/'):
176
+ if state.phase != 'stopped':
177
+ return self.send(409, {'error': 'Replay becomes available after the run ends'})
178
+ query = parse_qs(urlsplit(self.path).query)
179
+ key = query.get('run', [None])[0]
180
+ if path == '/api/replay/runs':
181
+ return self.send(200, {'runs': state.replay.listing(), 'current_run': state.replay.current.name})
182
+ archive = state.replay.get(key)
183
+ if path == '/api/replay/manifest':
184
+ return self.send(200, archive.manifest())
185
+ if path == '/api/replay/map':
186
+ return self.send(200, json.loads((archive.root / 'map.json').read_text()))
187
+ if path == '/api/replay/frame':
188
+ result = archive.frame(int(query.get('index', ['0'])[0]))
189
+ result['token'] = state.token
190
+ return self.send(200, result)
191
+ if path in ('/api/replay/rgb', '/api/replay/bev'):
192
+ number = int(query['frame'][0])
193
+ layer = query.get('layer', [None])[0] if path.endswith('/bev') else None
194
+ if path.endswith('/bev') and layer is None:
195
+ raise ValueError('BEV layer required')
196
+ return self.send(200, archive.image(number, layer), 'image/png' if layer else 'image/jpeg')
197
+ return self.send(404, {'error': 'Unknown replay action'})
198
+ with state.lock:
199
+ if path == '/api/rgb.jpg' and state.packet is not None:
200
+ data = np.asarray(state.packet['rgb_jpg'], np.uint8).tobytes()
201
+ return self.send(200, data, 'image/jpeg')
202
+ if path.startswith('/api/bev/') and path.split('/')[-1] in state.images:
203
+ return self.send(200, state.images[path.split('/')[-1]], 'image/png')
204
+ return self.send(404, {'error': 'Data not available yet'})
205
+ except (OSError, ValueError, KeyError, IndexError) as exc:
206
+ self.send(404, {'error': str(exc)})
207
+
208
+ def do_POST(self):
209
+ state = self.server.state
210
+ expected = f'http://127.0.0.1:{self.server.server_port}'
211
+ if self.headers.get('X-Session') != state.token or self.headers.get('Origin') not in (None, expected):
212
+ return self.send(403, {'error': 'Invalid viewer session or origin'})
213
+ with state.lock:
214
+ if self.path == '/api/heartbeat':
215
+ state.heartbeat = time.monotonic()
216
+ return self.send(200, {'ok': True})
217
+ if self.path == '/api/start':
218
+ if state.phase != 'teleop':
219
+ return self.send(409, {'error': 'A run can be started once; Stop ends the session'})
220
+ reason = state.gate()
221
+ if reason:
222
+ return self.send(409, {'error': reason})
223
+ state.phase, state.reason = 'preparing', 'Browser requested navigation handoff'
224
+ state.event('start_requested', goal=state.args.goal)
225
+ return self.send(202, {'phase': state.phase})
226
+ if self.path == '/api/stop':
227
+ state.finish('Stopped by operator; temporary relay will close')
228
+ return self.send(200, {'phase': 'stopped'})
229
+ return self.send(404, {'error': 'Unknown action'})
230
+
231
+
232
+ def capture_loop(state, relay):
233
+ context = zmq.Context()
234
+ sub = context.socket(zmq.SUB)
235
+ sub.setsockopt(zmq.SUBSCRIBE, b'')
236
+ sub.setsockopt(zmq.CONFLATE, 1)
237
+ sub.setsockopt(zmq.LINGER, 0)
238
+ sub.connect(f'tcp://{state.args.robot_ip}:4511')
239
+ root = state.args.output / 'capture'
240
+ for name in ('rgb', 'depth'):
241
+ (root / name).mkdir(parents=True, exist_ok=True)
242
+ first, last, count, previous_received = None, -1, 0, None
243
+ try:
244
+ with (root / 'observations.jsonl').open('a', buffering=1) as log, \
245
+ (root / 'transport.jsonl').open('a', buffering=1) as timing_log:
246
+ while not state.done.is_set():
247
+ if relay.process.poll() is not None:
248
+ raise RuntimeError('Owned robot relay exited')
249
+ if not sub.poll(200):
250
+ continue
251
+ recv_started = time.monotonic()
252
+ payload = sub.recv()
253
+ recv_finished = time.monotonic()
254
+ packet = pickle.loads(payload)
255
+ received = time.monotonic()
256
+ with state.lock:
257
+ timing = camera_transport_diagnostics(packet, state.robot, state.robot_received, received)
258
+ timing.update(wire_bytes=len(payload), recv_call_s=recv_finished - recv_started,
259
+ deserialize_s=received - recv_finished,
260
+ receive_gap_s=received - previous_received if previous_received is not None else None)
261
+ previous_received = received
262
+ if packet['world_frame'] != 'odom':
263
+ raise ValueError('Continuous odom frame required')
264
+ if packet['frame_id'] <= last:
265
+ continue
266
+ last = packet['frame_id']
267
+ first = packet['sensor_stamp'] if first is None else first
268
+ row = {k: v for k, v in packet.items() if k not in ('rgb_jpg', 'depth_png')}
269
+ row['camera_in_base'] = camera_in_base(packet['camera_pose'], packet['base_pose_matrix'])
270
+ for stamp_name in ('camera_tf_stamp', 'base_tf_stamp'):
271
+ if stamp_name in packet and abs(packet[stamp_name] - packet['sensor_stamp']) > .025:
272
+ raise ValueError('Camera/base TF is not synchronized to its image')
273
+ row.update(frame_idx=count, relative_time_s=packet['sensor_stamp'] - first,
274
+ received_monotonic=received, received_unix_s=time.time(), transport=timing)
275
+ write_started = time.monotonic()
276
+ stem = f'{count:08d}'
277
+ (root / 'rgb' / f'{stem}.jpg').write_bytes(np.asarray(packet['rgb_jpg'], np.uint8).tobytes())
278
+ (root / 'depth' / f'{stem}.png').write_bytes(np.asarray(packet['depth_png'], np.uint8).tobytes())
279
+ log.write(json.dumps(clean_json(row), allow_nan=False) + '\n')
280
+ save_json(root / 'latest.json', row)
281
+ with state.lock:
282
+ state.packet = {**packet, **row}
283
+ phase, commands = state.phase, state.motion_commands
284
+ count += 1
285
+ save_json(root / 'capture.json', {'status': 'recording', 'frames': count,
286
+ 'phase': phase, 'nonzero_motion_commands': commands, 'world_frame': 'odom'})
287
+ timing_log.write(json.dumps(clean_json({'frame_idx': count - 1,
288
+ 'frame_id': packet['frame_id'], 'received_unix_s': row['received_unix_s'],
289
+ **timing, 'record_and_publish_s': time.monotonic() - write_started,
290
+ 'capture_metrics': packet.get('capture_metrics')}), allow_nan=False) + '\n')
291
+ except BaseException as exc:
292
+ state.finish('Capture error: ' + str(exc))
293
+ state.event('capture_error', error=str(exc))
294
+ finally:
295
+ save_json(root / 'capture.json', {'status': 'completed', 'frames': count,
296
+ 'nonzero_motion_commands': state.motion_commands, 'world_frame': 'odom'})
297
+ sub.close()
298
+ context.term()
299
+
300
+
301
+ def control_loop(state):
302
+ """Independent 20 Hz owner of the robot-local lease. Never waits for inference."""
303
+ from cross_nav.policy.robot import pure_pursuit
304
+
305
+ context = zmq.Context()
306
+ status = context.socket(zmq.SUB)
307
+ status.setsockopt(zmq.SUBSCRIBE, b'')
308
+ status.setsockopt(zmq.CONFLATE, 1)
309
+ status.setsockopt(zmq.LINGER, 0)
310
+ status.connect(f'tcp://{state.args.robot_ip}:4513')
311
+ commands = context.socket(zmq.PUSH)
312
+ commands.setsockopt(zmq.SNDHWM, 1)
313
+ commands.setsockopt(zmq.IMMEDIATE, 1)
314
+ commands.setsockopt(zmq.LINGER, 0)
315
+ commands.connect(f'tcp://{state.args.robot_ip}:4512')
316
+ mode = context.socket(zmq.PUB)
317
+ mode.setsockopt(zmq.LINGER, 0)
318
+ mode.connect(f'tcp://{state.args.robot_ip}:4402')
319
+ sequence, previous, last_tick, next_mode, prepare_started = 0, None, time.monotonic(), 0., None
320
+ plan_wait = PlanWait(timeout=state.args.plan_hold_seconds)
321
+ next_scan = 0.
322
+ scan_started, scan_angle, scan_previous = None, 0., None
323
+ scan_origin = None
324
+ control_epoch = 0
325
+ veto_since, progress_origin, progress_at = None, None, None
326
+
327
+ def send(command):
328
+ try:
329
+ commands.send_json(command, flags=zmq.NOBLOCK)
330
+ except zmq.Again:
331
+ return False
332
+ return True
333
+
334
+ try:
335
+ with (state.args.output / 'commands.jsonl').open('a', buffering=1) as log, \
336
+ (state.args.output / 'robot_status.jsonl').open('a', buffering=1) as robot_log:
337
+ while not state.done.is_set():
338
+ now = time.monotonic()
339
+ if now >= next_scan:
340
+ with state.lock:
341
+ state.conflicts = competing_controllers()
342
+ next_scan = now + 1.
343
+ if status.poll(0):
344
+ robot = status.recv_pyobj()
345
+ robot_log.write(json.dumps(clean_json({'received_unix': time.time(),
346
+ 'received_monotonic': time.monotonic(), **robot})) + '\n')
347
+ with state.lock:
348
+ state.robot, state.robot_received = robot, time.monotonic()
349
+ with state.lock:
350
+ robot, robot_at, plan, phase, heartbeat = (state.robot, state.robot_received,
351
+ state.plan, state.phase, state.heartbeat)
352
+ epoch = state.plan_epoch
353
+ if epoch != control_epoch:
354
+ scan_started, scan_angle, scan_origin, scan_previous = None, 0., None, None
355
+ veto_since, progress_origin, progress_at = None, None, None
356
+ control_epoch = epoch
357
+ # Process scanning, deserialization or waiting for the GIL can
358
+ # take time. Gate this snapshot using the current clock.
359
+ now = time.monotonic()
360
+ v, w = 0., 0.
361
+ head_target = None
362
+ head_feedback = None
363
+ footprint_report = None
364
+ requested_velocity = [0., 0.]
365
+ depth_blocked = learned_blocked = False
366
+ queued = None
367
+ reason = 'Teleop owns control; no arm/mode/velocity requests'
368
+ if phase in ('preparing', 'active'):
369
+ if state.conflicts:
370
+ state.finish('Competing base controller detected; navigation ended')
371
+ break
372
+ gate = execution_gate(plan, robot, now=now, robot_received=robot_at,
373
+ heartbeat=heartbeat, state=phase, max_plan_age=state.args.max_plan_age)
374
+ if gate == 'goal reached':
375
+ state.finish('Goal keyframe reached (camera XY within 0.4 m; heading not enforced)')
376
+ break
377
+ recovering = gate == 'map correction recovery' and now < plan.get('recovery_deadline', 0.)
378
+ holding = phase == 'active' and robot is not None and (recovering or plan_wait.holds(gate, now))
379
+ if gate and not holding:
380
+ state.finish(gate + '; navigation ended')
381
+ break
382
+ if robot.get('armed') and robot.get('session') != state.session:
383
+ raise RuntimeError('Relay is owned by another session')
384
+ if phase == 'active' and not robot.get('armed'):
385
+ raise RuntimeError('Navigation lease lost; no automatic re-arm')
386
+ if phase == 'active' and not gate:
387
+ head_feedback, _ = stationary_head_command(plan, robot, now=now, robot_received=robot_at)
388
+ if head_feedback is not None:
389
+ # The view target/anchor/deadline is fixed by the planner.
390
+ # Keep its head action alive using fresh source feedback,
391
+ # regardless of VGGT cadence, with no base movement.
392
+ sequence += 1
393
+ head_target = head_feedback['head_target']
394
+ if scan_started is None:
395
+ scan_started, scan_origin = now, np.asarray(robot['base_pose'], float)[:2].copy()
396
+ if now - scan_started > 260.:
397
+ raise RuntimeError('Observation recovery exhausted without forward progress')
398
+ with state.lock:
399
+ if epoch != state.plan_epoch or state.done.is_set():
400
+ head_feedback = None
401
+ head_target = None
402
+ command = {'type': 'velocity', 'session': state.session, 'seq': sequence,
403
+ 'frame_id': robot['frame_id'], 'ttl': .3, 'v': 0., 'w': 0.}
404
+ if head_feedback is not None:
405
+ command.update(head_feedback)
406
+ queued = send(command)
407
+ reason = ('Head survey: ' + (plan.get('survey_label') or 'observing')
408
+ if plan.get('stationary_survey') else
409
+ 'Corner observation: ' + plan.get('corner_phase', 'look'))
410
+ progress_at = now
411
+ previous = np.asarray(robot['base_pose'], float).copy()
412
+ elif holding:
413
+ # Renew only zero velocity using fresh camera evidence. An old
414
+ # path never receives extra execution time during this hold.
415
+ sequence += 1
416
+ queued = send({'type': 'velocity', 'session': state.session, 'seq': sequence,
417
+ 'frame_id': robot['frame_id'], 'ttl': .3, 'v': 0., 'w': 0.})
418
+ reason = 'Holding at zero: ' + gate
419
+ previous = np.asarray(robot['base_pose'], float).copy()
420
+ elif phase == 'preparing':
421
+ prepare_started = prepare_started or now
422
+ if now - prepare_started > 15.:
423
+ raise RuntimeError('Navigation mode/lease preparation timed out')
424
+ if robot.get('control_mode') != 'navigation':
425
+ if now >= next_mode:
426
+ mode.send_pyobj({'control_mode': 'navigation', 'step': int(robot['bridge_step']) + 1})
427
+ next_mode = now + 1.
428
+ reason = 'Switching base to navigation mode; joints unchanged'
429
+ elif not robot.get('healthy'):
430
+ reason = 'Waiting for healthy robot TF and camera'
431
+ elif not robot.get('armed'):
432
+ state.relay_ever_requested = True
433
+ send({'type': 'arm', 'session': state.session})
434
+ reason = 'Arming expiring robot-local velocity lease'
435
+ else:
436
+ with state.lock:
437
+ state.phase = 'active'
438
+ reason = 'Navigation active'
439
+ else:
440
+ pose = np.asarray(robot['base_pose'], float)
441
+ if previous is not None:
442
+ dt = now - last_tick
443
+ if np.linalg.norm(pose[:2] - previous[:2]) > .2 + .2 * dt or abs(wrap(pose[2] - previous[2])) > .3 + .4 * dt:
444
+ raise RuntimeError('Odom discontinuity')
445
+ if not robot.get('armed'):
446
+ raise RuntimeError('Navigation lease lost; no automatic re-arm')
447
+ path = remaining_path(plan['path_odom'], pose)
448
+ head_target = plan.get('head_target')
449
+ if plan.get('observation_hold'):
450
+ v, w = 0., float(np.clip(plan.get('scan_w', 0.),
451
+ -min(.15, state.args.max_w), min(.15, state.args.max_w)))
452
+ reason = ('Head survey: ' + (plan.get('survey_label') or 'observing')
453
+ if plan.get('stationary_survey') else 'Corner observation: ' + plan.get('corner_phase', 'look'))
454
+ elif plan.get('planner_status') == 2:
455
+ _, w = pure_pursuit(path, v_max=state.args.max_v, w_max=min(.15, state.args.max_w))
456
+ v, reason = 0., 'Guarded native no-route scan'
457
+ else:
458
+ v, w = pure_pursuit(path, v_max=state.args.max_v * plan.get('speed_scale', 1.),
459
+ w_max=state.args.max_w, lookahead=plan.get('lookahead', .4))
460
+ reason = 'Following CROSS local plan'
461
+ v *= min(1., max(0., plan['goal_distance'] - .4) / .6)
462
+ if progress_origin is None or np.linalg.norm(pose[:2] - progress_origin) > .05:
463
+ progress_origin, progress_at = pose[:2].copy(), now
464
+ if plan.get('observation_hold'):
465
+ progress_at = now
466
+ # Scan budgets follow physical odometry and do not reset
467
+ # merely because the planner briefly changes status.
468
+ scanning = plan.get('observation_hold') or plan.get('planner_status') == 2
469
+ if scan_origin is not None and np.linalg.norm(pose[:2] - scan_origin) > .2:
470
+ scan_started, scan_angle, scan_origin = None, 0., None
471
+ if scanning:
472
+ if scan_started is None:
473
+ scan_started, scan_origin = now, pose[:2].copy()
474
+ if scan_previous is not None:
475
+ scan_angle += abs(wrap(pose[2] - scan_previous))
476
+ if now - scan_started > 260. or scan_angle > np.deg2rad(100):
477
+ raise RuntimeError('Observation recovery exhausted without forward progress')
478
+ scan_previous = pose[2]
479
+ requested_velocity = [float(v), float(w)]
480
+ depth_blocked = depth_veto(plan['depth_obstacles'], pose, v, w)
481
+ if plan.get('footprint_grid') is not None:
482
+ footprint_report = command_footprint_report(
483
+ plan['footprint_grid'], plan['planning_base'], pose, v, w)
484
+ learned_blocked = not footprint_report['clear']
485
+ if (depth_blocked or learned_blocked) and abs(v) + abs(w) > 1e-8:
486
+ v, w = 0., 0.
487
+ reason = ('Measured-depth veto' if depth_blocked else 'Learned-footprint veto') + ': obstacle in command footprint'
488
+ veto_since = now if veto_since is None else veto_since
489
+ else:
490
+ veto_since = None
491
+ if not plan.get('observation_hold') and (
492
+ (veto_since is not None and now - veto_since > 1.) or now - progress_at > 10.
493
+ ):
494
+ with state.lock:
495
+ state.observation_requested = True
496
+ state.observation_reason = ('measured depth' if depth_blocked else
497
+ 'learned footprint' if learned_blocked else 'no odometry progress')
498
+ sequence += 1
499
+ with state.lock:
500
+ # A correction can arrive after this thread took its
501
+ # snapshot. Never send its now-invalid path command.
502
+ if epoch != state.plan_epoch or state.done.is_set():
503
+ v, w, head_target = 0., 0., None
504
+ reason = 'Holding at zero: route generation changed'
505
+ command = {'type': 'velocity', 'session': state.session, 'seq': sequence,
506
+ 'frame_id': plan['frame_id'], 'ttl': .3, 'v': float(v), 'w': float(w)}
507
+ if head_target is not None:
508
+ command['head_target'] = head_target
509
+ queued = send(command)
510
+ if queued:
511
+ with state.lock:
512
+ state.motion_commands += int(abs(v) + abs(w) > 1e-8)
513
+ # Relay-published velocity, rather than a queued
514
+ # PC request, drives the native bump expectation.
515
+ state.commanded += max(0., robot.get('v', 0.)) * min(.1, now - last_tick)
516
+ previous = pose.copy()
517
+ last_tick = now
518
+ with state.lock:
519
+ if not state.done.is_set():
520
+ state.reason = reason
521
+ control = {'phase': phase, 'reason': reason, 'v': float(v), 'w': float(w),
522
+ 'time_unix': time.time(), 'sequence': sequence,
523
+ 'plan_frame_id': plan.get('frame_id') if plan else None,
524
+ 'plan_capture_frame': plan.get('capture_frame') if plan else None, 'command_queued': queued,
525
+ 'plan_input_age_s': now - plan['input_received'] if plan else None,
526
+ 'plan_build_age_s': now - plan.get('published', now) if plan else None,
527
+ 'robot_state_age_s': now - robot_at, 'max_plan_age_s': state.args.max_plan_age,
528
+ 'holding_for_plan': phase == 'active' and reason.startswith('Holding'),
529
+ 'plan_epoch': epoch, 'relay_sequence': robot.get('accepted_sequence') if robot else None,
530
+ 'head_target': head_target,
531
+ 'head_control_source': 'fresh_robot_feedback' if head_feedback is not None else 'plan',
532
+ 'head_evidence_frame_id': head_feedback['frame_id'] if head_feedback is not None else None,
533
+ 'requested_velocity': requested_velocity, 'requested_pose': robot.get('base_pose') if robot else None,
534
+ 'depth_blocked': depth_blocked, 'learned_blocked': learned_blocked,
535
+ 'footprint': footprint_report,
536
+ 'relay_reason': robot.get('reason') if robot else None,
537
+ 'relay_velocity': [robot.get('v'), robot.get('w')] if robot else None,
538
+ 'nonzero_motion_commands': state.motion_commands}
539
+ log.write(json.dumps(clean_json(control), allow_nan=False) + '\n')
540
+ with state.lock:
541
+ state.last_control = clean_json(control)
542
+ save_json(state.args.output / 'control.json', control)
543
+ state.done.wait(.05)
544
+ except BaseException as exc:
545
+ state.finish('Control error: ' + str(exc))
546
+ state.event('control_error', error=str(exc))
547
+ finally:
548
+ if state.relay_ever_requested:
549
+ for _ in range(3):
550
+ send({'type': 'stop', 'session': state.session})
551
+ time.sleep(.03)
552
+ final_control = {'phase': state.phase, 'reason': state.reason, 'v': 0., 'w': 0.,
553
+ 'time_unix': time.time(), 'sequence': sequence, 'stop_requested': state.relay_ever_requested,
554
+ 'nonzero_motion_commands': state.motion_commands}
555
+ save_json(state.args.output / 'control.json', final_control)
556
+ with (state.args.output / 'commands.jsonl').open('a') as log:
557
+ log.write(json.dumps(final_control) + '\n')
558
+ for socket in (status, commands, mode):
559
+ socket.close()
560
+ context.term()
561
+
562
+
563
+ def run_mapping(state):
564
+ from cross.core.config import load_config
565
+ from cross.core.types import Camera
566
+ from cross.pipeline import add_session_args, finish_session_args, mode_config_files, session_factory
567
+ from cross_nav.policy.bev_policy import BEVPlannerPolicy, Episode
568
+
569
+ args = state.args
570
+ while state.packet is None and not state.done.wait(.1):
571
+ pass
572
+ if state.done.is_set():
573
+ return
574
+ with state.lock:
575
+ initial = state.packet
576
+ rgb = cv2.imdecode(np.asarray(initial['rgb_jpg'], np.uint8), cv2.IMREAD_COLOR)
577
+ camera_config = Camera(K=np.asarray(initial['camera_K']), frame_width=rgb.shape[1], frame_height=rgb.shape[0])
578
+ parser = argparse.ArgumentParser()
579
+ add_session_args(parser)
580
+ options = parser.parse_args(['--mode', 'mono', '--odometry', 'external', '--mono-estimator', 'ff'])
581
+ finish_session_args(options)
582
+ heads = args.cross_root / 'models/VGGT-Omega-CROSS/nav'
583
+ occupancy, visibility = heads / 'cross_nav_occupancy.pt', heads / 'cross_nav_observability.pt'
584
+ overrides = ['pose_est.ff.checkpoint=finetuned', 'pose_est.obs_max_interval_steps=1',
585
+ f'pose_est.ff.nav_bev_head={occupancy}', f'pose_est.ff.nav_bev_visibility={visibility}',
586
+ f'pose_est.ff.nav_bev_visibility_gravity={occupancy}', 'mapping.loop_closure.async_pgo=False']
587
+ config = load_config(*mode_config_files('mono', 'external', 'ff'), sets=overrides)
588
+ artifacts = RunArtifacts(args.output / 'mapping', {'mode': 'mono', 'odometry': 'external',
589
+ 'dataset': str(args.output / 'capture'), 'loaded_map': str(args.map_run / 'map.pkl'),
590
+ 'goal_keyframe': args.goal, 'config_overrides': overrides, 'max_v': args.max_v, 'max_w': args.max_w,
591
+ 'max_plan_age_s': args.max_plan_age, 'plan_hold_seconds': args.plan_hold_seconds,
592
+ 'checkpoint_provenance': json.loads((heads / 'provenance.json').read_text())})
593
+ session = debug_archive = None
594
+ mapping_error = None
595
+ try:
596
+ session = artifacts.wrap_factory(session_factory(options, camera_config, config))()
597
+ session.load_map(args.map_run / 'map.pkl')
598
+ pe = session.mapper.pose_est
599
+ if args.vggt_debug:
600
+ debug_archive = VggtDebugRecorder(args.vggt_debug_dir or args.output / 'vggt_debug', {
601
+ 'origin': 'live_recorded', 'cross_root': str(args.cross_root),
602
+ 'map_run': str(args.map_run), 'config_overrides': overrides,
603
+ 'resolved_config': json.loads((args.output / 'mapping/resolved_config.json').read_text()),
604
+ 'camera_catalog': clean_json(session.mapper.cameras), 'session_camera_id': session.mapper.cam_id,
605
+ 'checkpoint_provenance': artifacts.metadata['checkpoint_provenance'],
606
+ **model_provenance(args.cross_root),
607
+ }, on_error=lambda exc: state.finish('VGGT debug archive error: ' + str(exc)))
608
+ debug_archive.attach(pe)
609
+ route_planner = SavedRoute(args.map_run / 'map.pkl')
610
+ bev_config = json.loads((args.cross_root / 'cross_nav/configs/policy/bev_planner_vfin2.json').read_text())
611
+ bev_config.update(backbone=str(args.cross_root / 'models/VGGT-Omega-CROSS/vggt_omega_cross_1b_512.pt'),
612
+ occupancy=str(occupancy), visibility=str(visibility), visibility_gravity=str(occupancy))
613
+ # Match the 46 cm execution footprint. Never shrink inflation to invent
614
+ # clearance in a narrow passage; also check the oriented rectangle.
615
+ bev_config['planner']['radius'] = .23
616
+ bev_config['map'].update(radius=.23, retry_radii=[])
617
+ save_json(args.output / 'resolved_bev_config.json', bev_config)
618
+ if debug_archive:
619
+ save_json(debug_archive.root / 'planner_config.json', bev_config)
620
+ policy = BEVPlannerPolicy(bev_config, predictor=pe.backend.nav)
621
+ episode = Episode()
622
+ recovery, corners = CorrectionRecovery(), CornerObserver()
623
+ survey = HeadSurvey()
624
+ obstacle_memory = MeasuredObstacleMemory()
625
+ evidence_directory = args.output / 'footprint_evidence'
626
+ evidence_directory.mkdir()
627
+ last_evidence = -math.inf
628
+ neutral_mount, previous_goal = None, None
629
+ prior, last, streak, previous_alignment = None, -1, 0, None
630
+ trajectory, previous_expected = [], 0.
631
+ with (args.output / 'observations.jsonl').open('a', buffering=1) as log:
632
+ while not state.done.is_set():
633
+ with state.lock:
634
+ raw = state.packet
635
+ phase, cumulative = state.phase, state.commanded
636
+ if raw is None or raw['frame_idx'] <= last:
637
+ state.done.wait(.03)
638
+ continue
639
+ index, camera, base = raw['frame_idx'], np.asarray(raw['camera_pose']), np.asarray(raw['base_pose_matrix'])
640
+ mount = camera_in_base(camera, base)
641
+ if neutral_mount is None:
642
+ neutral_mount = mount.copy()
643
+ rgb = cv2.cvtColor(cv2.imdecode(np.asarray(raw['rgb_jpg'], np.uint8), cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB)
644
+ pe.set_gravity(camera[:3, :3].T @ [0., 0., 1.])
645
+ passes = pe._n_passes
646
+ started = time.monotonic()
647
+ if debug_archive:
648
+ debug_archive.begin_frame(raw)
649
+ session.process({'rgb': rgb, 'frame_idx': index, 'timestamp': raw['sensor_stamp'],
650
+ 'delta_pose': None if prior is None else np.linalg.inv(prior) @ camera})
651
+ prior, last = camera, index
652
+ c0, best, weights = session.belief(matrix)
653
+ localized = bool(session.localized())
654
+ streak = streak + 1 if localized else 0
655
+ diagnostics = session.mapper.last_step_diagnostics
656
+ audit = [{'id': int(a['keyframe_id']), 'score': float(a['retrieval_score']),
657
+ 'verified': bool(a['verified']), 'loaded': bool(a['loaded'])}
658
+ for a in diagnostics.get('retrieval_audit', [])]
659
+ fresh = pe._n_passes != passes and pe.last_bev is not None
660
+ bev = pe.last_bev if fresh else None
661
+ grid = planner_debug = None
662
+ record = {'frame_idx': index, 'time_s': raw['relative_time_s'], 'localized': localized,
663
+ 'localized_streak': streak, 'weights': weights, 'retrieval': audit,
664
+ 'camera_display': None, 'global_route': [], 'local_path_display': [],
665
+ 'goal_keyframe': args.goal, 'route_ids': [], 'goal_distance': None,
666
+ 'planner_name': 'Waiting for committed map pose', 'n_views': 0, 'trajectory': trajectory[-1500:]}
667
+ plan = None if localized else {'input_received': raw['received_monotonic'],
668
+ 'localized': False, 'localized_streak': 0, 'goal_distance': 0.}
669
+ if bev is not None:
670
+ grid = reproject_bev(bev['prob'], bev['observability'], bev['uncertainty'],
671
+ bev['R_bev_from_cam'], camera, base, bev['res'])
672
+ images = {f'{layer}.png': learned_png(grid['prob'], grid['obs'], grid['err'], layer)
673
+ for layer in ('occupancy', 'visibility', 'uncertainty')}
674
+ save_bev_frame(args.output, int(index), images)
675
+ with state.lock:
676
+ state.images = images
677
+ record.update(n_views=bev['n_views'], scale_source=bev['scale_source'],
678
+ bev_size=bev['size'], bev_res=bev['res'], gravity_head_deg=bev['gravity_head_deg'])
679
+ if localized and bev is not None:
680
+ alignment = c0 @ np.linalg.inv(camera)
681
+ with state.lock:
682
+ active = state.phase == 'active'
683
+ was_pending = recovery.pending
684
+ correction = recovery.update(previous_alignment if active else None, alignment, base, time.monotonic())
685
+ if correction['started']:
686
+ survey.cancel()
687
+ route_planner.reset_attachment()
688
+ clear_goal_cache(episode)
689
+ corners.reset()
690
+ previous_goal = None
691
+ with state.lock:
692
+ state.plan_epoch += 1
693
+ state.plan = {'input_received': raw['received_monotonic'], 'localized': True,
694
+ 'localized_streak': streak, 'goal_distance': 0., 'recovery_pending': True,
695
+ 'recovery_deadline': correction['deadline']}
696
+ state.event('map_correction_recovery_started', frame_idx=index,
697
+ previous_alignment=previous_alignment, alignment=alignment,
698
+ base_pose_matrix=base, weights=weights, **correction)
699
+ if was_pending and not recovery.pending:
700
+ corners.restore_neutral(base, time.monotonic())
701
+ state.event('map_correction_recovery_complete', frame_idx=index, **correction)
702
+ record.update(map_correction_at_base_m=correction['distance_m'],
703
+ map_correction_angle_deg=correction['rotation_deg'], correction_recovery=correction,
704
+ camera_in_base=mount, neutral_camera_in_base=neutral_mount)
705
+ previous_alignment = alignment
706
+ inverse_alignment = np.linalg.inv(alignment)
707
+ depth = cv2.imdecode(np.asarray(raw['depth_png'], np.uint8), cv2.IMREAD_UNCHANGED).astype(float) / 1000
708
+ obstacles = depth_obstacles(depth, raw['camera_K'], camera)
709
+ obstacle_memory.observing(survey.active, raw['received_monotonic'])
710
+ obstacles = obstacle_memory.update(obstacles, raw['received_monotonic'], base[:2, 3])
711
+ reference_camera = base @ neutral_mount
712
+ def can_attach(_keyframe_id, point_map):
713
+ point_odom = positions(inverse_alignment, [point_map])[0]
714
+ target_base_xy = base[:2, 3] + point_odom[:2] - reference_camera[:2, 3]
715
+ return attachment_clear(obstacles, raw['base_pose'], target_base_xy)
716
+ # Head panning must not move the virtual camera used for
717
+ # graph attachment or change camera->base goal conversion.
718
+ route = route_planner.route(alignment @ reference_camera, args.goal, can_attach=can_attach)
719
+ ids = route['ids']
720
+ route_map = np.asarray(route['positions']).reshape(-1, 3)
721
+ goal_map = route_planner.matrices[args.goal][:3, 3]
722
+ goal_odom = positions(inverse_alignment, [goal_map])[0]
723
+ goal_distance = float(np.linalg.norm(goal_odom[:2] - reference_camera[:2, 3]))
724
+ route_odom = positions(inverse_alignment, route_map)
725
+ offset = reference_camera[:2, 3] - base[:2, 3]
726
+ hint = route_subgoal(route_odom[:, :2] - offset, base, goal_odom[:2] - offset)
727
+ with state.lock:
728
+ joint = state.robot.get('joint_positions', []) if state.robot else []
729
+ image_head = raw.get('head_joints')
730
+ if image_head is not None and len(joint) >= 11:
731
+ joint = np.asarray(joint, float).copy()
732
+ joint[9:11] = image_head
733
+ elif active and (hint['corner'] is not None or corners.phase != 'cruise' or survey.active):
734
+ raise ValueError('Timestamped head joint feedback missing; refusing camera scan')
735
+
736
+ def start_survey(reason):
737
+ if image_head is None:
738
+ raise ValueError('Timestamped head joint feedback missing; refusing camera survey')
739
+ if not survey.start(base, mount, neutral_mount, joint, time.monotonic(), reason):
740
+ return False
741
+ clear_goal_cache(episode)
742
+ corners.reset()
743
+ with state.lock:
744
+ state.plan_epoch += 1
745
+ if state.plan is not None:
746
+ state.plan = {**state.plan, 'observation_hold': True, 'stationary_survey': True,
747
+ 'scan_w': 0., 'head_target': None, 'survey_label': survey.snapshot()['label']}
748
+ state.event('head_survey_started', frame_idx=index, reason=reason,
749
+ pass_number=survey.passes, targets=survey.targets)
750
+ return True
751
+
752
+ observation = {'phase': 'cruise', 'target': hint['target'], 'hold': False,
753
+ 'head_target': None, 'scan_w': 0., 'speed_scale': 1., 'lookahead': .4}
754
+ if active and not recovery.pending:
755
+ with state.lock:
756
+ request_observation = state.observation_requested
757
+ request_reason = state.observation_reason
758
+ state.observation_requested = False
759
+ if request_observation:
760
+ start_survey(request_reason or 'stuck')
761
+ if survey.active:
762
+ count = len(survey.views)
763
+ was_braking = survey.braking
764
+ observation = survey.update(base, mount, joint, index, time.monotonic())
765
+ if was_braking and not survey.braking:
766
+ state.event('head_survey_base_stopped', frame_idx=index,
767
+ pass_number=survey.passes, base_pose_matrix=base)
768
+ if len(survey.views) > count:
769
+ state.event('head_survey_view', pass_number=survey.passes, **survey.views[-1])
770
+ if observation.get('survey_complete'):
771
+ clear_goal_cache(episode)
772
+ corners.reset()
773
+ state.event('head_survey_complete', frame_idx=index, pass_number=survey.passes)
774
+ else:
775
+ observation = corners.update(hint, base, mount, neutral_mount, joint,
776
+ {**grid, 'res': bev['res']}, time.monotonic())
777
+ target_base = observation['target']
778
+ if previous_goal is not None and np.linalg.norm(target_base - previous_goal) > .6:
779
+ clear_goal_cache(episode)
780
+ previous_goal = np.asarray(target_base).copy()
781
+ goal_body = world_to_body(target_base, base)
782
+ cat = {'prob': grid['prob'][None], 'obs': grid['obs'][None], 'err': grid['err'][None],
783
+ 'log_scale': np.array([bev['log_scale']]), 'odometry': np.array([bev['scale_source'] == 'anchors']),
784
+ 'up_head_deg': np.array([bev['gravity_head_deg']]), 'n_views': np.array([bev['n_views']])}
785
+ paths, debug = policy.plan_maps(cat, goal_body[None], [episode],
786
+ [{'ep': state.session, 'odom': raw['base_pose'], 'expect': max(0., cumulative - previous_expected)}], [True])
787
+ planner_debug = debug[0]
788
+ previous_expected = cumulative
789
+ path = paths[0]
790
+ code = int(debug[0]['status'])
791
+ native_path, native_code = path.copy(), code
792
+ rectangle_clear = rectangle_path_clear(path, {**grid, 'res': bev['res']})
793
+ if not rectangle_clear and not observation['hold']:
794
+ # Request observation rather than executing a route that
795
+ # clears a centre point but clips a rectangular corner.
796
+ code = 2
797
+ side = 1. if goal_body[1] >= 0 else -1.
798
+ path = np.tile([0., side * .3], (len(path), 1))
799
+ if active and not recovery.pending and code == 2 and not observation['hold']:
800
+ if start_survey('native no route' if rectangle_clear else 'learned path footprint'):
801
+ observation = survey.update(base, mount, joint, index, time.monotonic())
802
+ if observation['hold']:
803
+ path = np.zeros_like(path)
804
+ with state.lock:
805
+ control = state.last_control
806
+ control_report = control.get('footprint')
807
+ footprint_diagnostics = depth_support(control_report, obstacles) if control_report else None
808
+ if footprint_diagnostics is not None:
809
+ footprint_diagnostics['command_capture_frame'] = control.get('plan_capture_frame')
810
+ for cell in footprint_diagnostics['cells'] + footprint_diagnostics.get('self_cells', []):
811
+ cell['display_body_xy'] = world_to_body(cell['world_xy'], base).tolist()
812
+ evidence = None
813
+ if active and (survey.active or control.get('learned_blocked') or control.get('depth_blocked')) and (
814
+ time.monotonic() - last_evidence >= 1.
815
+ ):
816
+ last_evidence = time.monotonic()
817
+ evidence = f'footprint_evidence/{index:08d}.npz'
818
+ np.savez_compressed(args.output / evidence, **grid, res=bev['res'],
819
+ base=base, camera=camera, measured_obstacles_odom=obstacles,
820
+ native_path_body=native_path, native_planner_status=native_code)
821
+ path_odom = body_to_world(path, base)
822
+ path_odom_with_origin = np.vstack([base[:2, 3], path_odom])
823
+ plan = {'input_received': raw['received_monotonic'], 'localized': True,
824
+ 'localized_streak': streak, 'frame_id': raw['frame_id'],
825
+ 'capture_frame': index,
826
+ 'route_ids': ids, 'path_odom': path_odom_with_origin, 'planner_status': code,
827
+ 'published': time.monotonic(),
828
+ 'goal_distance': goal_distance, 'arrived': goal_distance <= .4,
829
+ 'depth_obstacles': obstacles, 'recovery_pending': recovery.pending,
830
+ 'footprint_grid': {**grid, 'res': bev['res']}, 'planning_base': base,
831
+ 'recovery_deadline': correction['deadline'], 'epoch': state.plan_epoch,
832
+ 'observation_hold': observation['hold'], 'head_target': observation['head_target'],
833
+ 'head_anchor': observation.get('head_anchor'),
834
+ 'head_deadline': observation.get('head_deadline'),
835
+ 'stationary_survey': observation['phase'].startswith('survey'),
836
+ 'survey_label': observation.get('survey_label'),
837
+ 'corner_phase': observation['phase'], 'scan_w': observation['scan_w'],
838
+ 'scan_authorized': code == 2, 'speed_scale': observation['speed_scale'],
839
+ 'lookahead': observation['lookahead']}
840
+ camera_display = positions(state.display, [c0[:3, 3]])[0]
841
+ trajectory.append(camera_display.tolist())
842
+ names = ['goal route', 'local waypoint', 'no route / scan', 'near goal',
843
+ 'remembered route', 'relaxed route', 'episode-map route']
844
+ record.update(camera_display=camera_display, global_route=positions(state.display, route_map),
845
+ local_path_display=positions(state.display @ alignment, np.column_stack([path_odom, np.zeros(len(path_odom))])),
846
+ local_path_body=path, goal_body=goal_body, goal_distance=goal_distance,
847
+ route_ids=ids, route_cost_m=route.get('cost_m'), route_attachment=route.get('attachment'),
848
+ corner_observation=observation, rectangle_clear=rectangle_clear,
849
+ head_survey=survey.snapshot(), footprint_diagnostics=footprint_diagnostics,
850
+ footprint_evidence=evidence, native_local_path_body=native_path,
851
+ native_planner_status=native_code,
852
+ planner_name=names[code], blind_zone=bool(debug[0]['blind_zone']),
853
+ trajectory=trajectory[-1500:], native_map_camera=c0)
854
+ record['compute_s'] = time.monotonic() - started
855
+ record['input_age_at_publish_s'] = time.monotonic() - raw['received_monotonic']
856
+ if debug_archive:
857
+ debug_archive.finish_frame(
858
+ observation={key: value for key, value in record.items() if key != 'trajectory'},
859
+ consumed_bev=bev, body_grid=grid, planner_debug=planner_debug,
860
+ planner_state=planner_snapshot(episode) if planner_debug is not None else None)
861
+ record['vggt_debug_frame'] = f'frames/{index:08d}/frame.json'
862
+ with state.lock:
863
+ state.plan, state.last_json = plan, clean_json(record)
864
+ state.processed += 1
865
+ save_json(args.output / 'latest_plan.json', record)
866
+ log.write(json.dumps(clean_json(record), allow_nan=False) + '\n')
867
+ if state.processed % 20 == 1:
868
+ print(json.dumps({'processed': state.processed, 'frame': index, 'localized': localized,
869
+ 'streak': streak, 'views': record['n_views'], 'phase': phase}), flush=True)
870
+ artifacts.metadata.update(nonzero_motion_commands=state.motion_commands, stop_reason=state.reason)
871
+ session.release()
872
+ artifacts.finish()
873
+ except BaseException as exc:
874
+ mapping_error = exc
875
+ state.finish('Mapping/planning error: ' + str(exc))
876
+ artifacts.finish(exc)
877
+ raise
878
+ finally:
879
+ if debug_archive:
880
+ debug_archive.close(mapping_error)
881
+
882
+
883
+ def main():
884
+ p = argparse.ArgumentParser(description=__doc__)
885
+ p.add_argument('--robot-ip', default='192.0.2.2')
886
+ p.add_argument('--cross-root', type=Path, default=Path('/workspace/CROSS'))
887
+ p.add_argument('--stretch-root', type=Path, default=Path('/workspace/stretch_ai'))
888
+ p.add_argument('--map-run', type=Path, required=True)
889
+ p.add_argument('--output', type=Path, required=True)
890
+ p.add_argument('--goal', type=int, default=1012)
891
+ p.add_argument('--port', type=int, default=8088)
892
+ p.add_argument('--max-v', type=float, default=.10)
893
+ p.add_argument('--max-w', type=float, default=.25)
894
+ p.add_argument('--max-plan-age', type=float, default=DEFAULT_MAX_PLAN_AGE,
895
+ help='Driving-plan evidence age in seconds (default: 2.0; range: 0.4–3.0)')
896
+ p.add_argument('--plan-hold-seconds', type=float, default=DEFAULT_PLAN_HOLD_SECONDS,
897
+ help='Wait at zero for a fresh plan/status in seconds (default: 8.0; range: 0–15)')
898
+ p.add_argument('--vggt-debug', action=argparse.BooleanOptionalAction, default=True,
899
+ help='Save every VGGT input group and numeric output in a separate debug archive (default: enabled)')
900
+ p.add_argument('--vggt-debug-dir', type=Path, help='Debug archive directory; default: OUTPUT/vggt_debug')
901
+ args = p.parse_args()
902
+ if not 0 < args.max_v <= .10 or not 0 < args.max_w <= .25:
903
+ raise ValueError('Initial live test is limited to 0.10 m/s and 0.25 rad/s')
904
+ if not .4 <= args.max_plan_age <= 3. or not 0. <= args.plan_hold_seconds <= 15.:
905
+ raise ValueError('Plan evidence must expire within 0.4–3.0 s; zero-velocity hold at most 15 s')
906
+ args.output, args.map_run = args.output.resolve(), args.map_run.resolve()
907
+ if args.vggt_debug_dir is not None:
908
+ args.vggt_debug_dir = args.vggt_debug_dir.resolve()
909
+ args.cross_root, args.stretch_root = args.cross_root.resolve(), args.stretch_root.resolve()
910
+ required = [args.cross_root / 'cross_nav/configs/policy/bev_planner_vfin2.json',
911
+ args.cross_root / 'models/VGGT-Omega-CROSS/vggt_omega_cross_1b_512.pt',
912
+ args.cross_root / 'models/VGGT-Omega-CROSS/nav/cross_nav_occupancy.pt',
913
+ args.cross_root / 'models/VGGT-Omega-CROSS/nav/cross_nav_observability.pt']
914
+ for file in required:
915
+ if not file.is_file():
916
+ raise FileNotFoundError(f'Required navigation file is missing: {file}')
917
+ graph = json.loads((args.map_run / 'graph.json').read_text())
918
+ nodes = [n for n in graph['nodes'] if not n['temporary']]
919
+ if args.goal not in {n['id'] for n in nodes}:
920
+ raise ValueError('Goal must be a permanent reference map keyframe')
921
+ sys.path[:0] = [str(args.cross_root), str(args.stretch_root / 'scripts')]
922
+ planner_runtime = warmup_native_navigation()
923
+ # Detect an occupied viewer port before creating a run or touching the robot.
924
+ server = ThreadingHTTPServer(('127.0.0.1', args.port), Handler)
925
+ try:
926
+ args.output.mkdir(parents=True, exist_ok=False)
927
+ state = LiveState(args)
928
+ except BaseException:
929
+ server.server_close()
930
+ raise
931
+ source = json.loads((args.map_run / 'run.json').read_text())
932
+ state.display = np.asarray(source['T_display_from_map'])
933
+ state.map_data = {'nodes': [{'id': n['id'], 'position': positions(state.display, [np.asarray(n['pose'])[:3, 3]])[0].tolist()}
934
+ for n in nodes], 'goal': args.goal}
935
+ save_json(args.output / 'map.json', state.map_data)
936
+ save_json(args.output / 'planner_runtime.json', planner_runtime)
937
+ server.daemon_threads = True
938
+ server.state = state
939
+ threading.Thread(target=server.serve_forever, daemon=True).start()
940
+ print(f'Live CROSS handoff: http://127.0.0.1:{args.port} — passive until Start navigation', flush=True)
941
+ shutdown = threading.Event()
942
+ def interrupt(*_):
943
+ shutdown.set()
944
+ state.finish('Process interrupted by operator')
945
+ signal.signal(signal.SIGINT, interrupt)
946
+ signal.signal(signal.SIGTERM, interrupt)
947
+ from depth_nav_live import RobotRelayProcess
948
+ relay = RobotRelayProcess(SimpleNamespace(robot_ip=args.robot_ip, ssh_user='hello-robot', container=None,
949
+ world_frame='odom', plan_hz=4., relay_max_frame_age=args.max_plan_age, command_ttl=.3,
950
+ enable_head=True), args.output)
951
+ threads = []
952
+ try:
953
+ relay.start()
954
+ for target in (capture_loop, control_loop):
955
+ t = threading.Thread(target=target, args=(state, relay) if target is capture_loop else (state,), daemon=True)
956
+ t.start()
957
+ threads.append(t)
958
+ os.chdir(args.cross_root)
959
+ run_mapping(state)
960
+ except BaseException as exc:
961
+ state.finish('Live pipeline error: ' + str(exc))
962
+ state.event('pipeline_error', error=str(exc))
963
+ import traceback
964
+ traceback.print_exc()
965
+ finally:
966
+ state.done.set()
967
+ for t in threads:
968
+ t.join(timeout=2.)
969
+ relay_closed = relay.close()
970
+ if relay_closed is False:
971
+ state.reason += '; robot relay shutdown could not be verified'
972
+ # This runner retains only the review UI after stopping. Do not retain
973
+ # the pipeline's model-reuse cache and several GB of GPU memory.
974
+ if 'cross.pipeline' in sys.modules:
975
+ cache = getattr(sys.modules['cross.pipeline'], '_MODEL_CACHE', None)
976
+ if cache is not None:
977
+ cache.clear()
978
+ import gc
979
+ gc.collect()
980
+ import torch
981
+ torch.cuda.empty_cache()
982
+ save_json(args.output / 'final_status.json', state.snapshot())
983
+ print(f'Live session ended; relay shutdown verified={relay_closed is not False}. Viewer remains available.', flush=True)
984
+ # Retain the local review page after the run ends. A new run uses a new directory.
985
+ while not shutdown.wait(1.):
986
+ pass
987
+ server.shutdown()
988
+ server.server_close()
989
+
990
+
991
+ if __name__ == '__main__':
992
+ main()
cases/20261026_goal1012_05/code/lite3_ROS/scripts/monitor_stretch_transport.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Read-only TCP, interface and host-load samples during a Stretch run."""
3
+
4
+ import argparse
5
+ import inspect
6
+ import json
7
+ import shlex
8
+ import subprocess
9
+ import time
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from pathlib import Path
12
+
13
+
14
+ def snapshot():
15
+ import os
16
+ import subprocess
17
+ import time
18
+ from pathlib import Path
19
+
20
+ result = {'unix_s': time.time(), 'monotonic_s': time.monotonic(), 'load': os.getloadavg()}
21
+ for name in ('net/dev', 'pressure/cpu', 'pressure/io', 'stat'):
22
+ try:
23
+ result[name] = Path('/proc', name).read_text()
24
+ except OSError as exc:
25
+ result[name] = str(exc)
26
+ # TCP memory and congestion statistics distinguish stale bytes already in
27
+ # the kernel from application-level ZMQ queues. No robot commands are sent.
28
+ for key, command in (
29
+ ('tcp', ['ss', '-tinm', ('( sport >= :4401 and sport <= :4513 ) or '
30
+ '( dport >= :4401 and dport <= :4513 )')]),
31
+ ('routes', ['ip', 'route']),
32
+ ('wireless', ['cat', '/proc/net/wireless']),
33
+ ):
34
+ try:
35
+ completed = subprocess.run(command, capture_output=True, text=True, timeout=2, check=False)
36
+ result[key] = completed.stdout or completed.stderr
37
+ except (OSError, subprocess.TimeoutExpired) as exc:
38
+ result[key] = str(exc)
39
+ return result
40
+
41
+
42
+ def main():
43
+ parser = argparse.ArgumentParser(description=__doc__)
44
+ parser.add_argument('--robot-ip', default='192.0.2.2')
45
+ parser.add_argument('--output', type=Path, required=True)
46
+ parser.add_argument('--duration', type=float, default=900.)
47
+ parser.add_argument('--interval', type=float, default=1.)
48
+ args = parser.parse_args()
49
+ if args.duration <= 0 or args.interval < .5:
50
+ raise ValueError('Duration must be positive and interval at least 0.5 s')
51
+ remote_code = inspect.getsource(snapshot) + '\nimport json\nprint(json.dumps(snapshot()))\n'
52
+ ssh = ['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=2',
53
+ f'hello-robot@{args.robot_ip}', shlex.join(['python3', '-c', remote_code])]
54
+
55
+ def remote():
56
+ try:
57
+ completed = subprocess.run(ssh, capture_output=True, text=True, timeout=4, check=False)
58
+ return json.loads(completed.stdout) if completed.returncode == 0 else {'error': completed.stderr}
59
+ except (OSError, subprocess.TimeoutExpired, ValueError) as exc:
60
+ return {'error': str(exc)}
61
+
62
+ args.output.parent.mkdir(parents=True, exist_ok=True)
63
+ started = time.monotonic()
64
+ with args.output.open('x', buffering=1) as log, ThreadPoolExecutor(max_workers=2) as pool:
65
+ while time.monotonic() - started < args.duration:
66
+ tick = time.monotonic()
67
+ local_future, remote_future = pool.submit(snapshot), pool.submit(remote)
68
+ log.write(json.dumps({'received_unix_s': time.time(),
69
+ 'pc': local_future.result(), 'robot': remote_future.result()}) + '\n')
70
+ time.sleep(max(0., args.interval - (time.monotonic() - tick)))
71
+
72
+
73
+ if __name__ == '__main__':
74
+ main()
cases/20261026_goal1012_05/code/lite3_ROS/scripts/replay_stretch_cross_nav.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Replay saved Stretch RGB/odometry through native CROSS with its trained BEV heads.
3
+
4
+ No robot/network/control interface is opened. The reference map is read-only.
5
+ """
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import sys
12
+ import time
13
+
14
+ import cv2
15
+ import numpy as np
16
+
17
+ ROOT = Path(__file__).resolve().parents[1]
18
+ sys.path.insert(0, str(ROOT))
19
+ from web_console.cross_run import RunArtifacts, matrix
20
+ from web_console.stretch_nav_learned import learned_png, reproject_bev
21
+ from web_console.stretch_nav_replay import save_bev_frame
22
+ from web_console.stretch_nav_report import clean_json, save_json
23
+ from web_console.stretch_vggt_debug import VggtDebugRecorder, model_provenance
24
+
25
+
26
+ def main():
27
+ p = argparse.ArgumentParser(description=__doc__)
28
+ for name in ('capture', 'probe', 'map-run', 'output'):
29
+ p.add_argument('--' + name, type=Path, required=True)
30
+ p.add_argument('--cross-root', type=Path, default=Path('/workspace/CROSS'))
31
+ p.add_argument('--heads', type=Path)
32
+ p.add_argument('--archive-run', type=Path, help='Backfill missing playback BEVs in this stopped live run')
33
+ p.add_argument('--skip-numeric-bevs', action='store_true', help='Save playback images without extra numeric BEV copies')
34
+ p.add_argument('--vggt-debug', action='store_true', help='Archive recomputed VGGT input groups and numeric outputs')
35
+ p.add_argument('--vggt-debug-dir', type=Path, help='Debug directory; default: OUTPUT/vggt_debug')
36
+ args = p.parse_args()
37
+ capture, probe, map_run, output = [getattr(args, n).resolve() for n in ('capture', 'probe', 'map_run', 'output')]
38
+ debug_path = (args.vggt_debug_dir or output / 'vggt_debug').resolve()
39
+ cross_root = args.cross_root.resolve()
40
+ heads = (args.heads or cross_root / 'models/VGGT-Omega-CROSS/nav').resolve()
41
+ occupancy, visibility = heads / 'cross_nav_occupancy.pt', heads / 'cross_nav_observability.pt'
42
+ source_rows = json.loads((probe / 'observations.json').read_text())
43
+ archive = args.archive_run.resolve() if args.archive_run else None
44
+ if archive is not None:
45
+ if capture != archive / 'capture':
46
+ raise ValueError('Playback archive must own the selected capture')
47
+ status = json.loads((archive / 'final_status.json').read_text())
48
+ if status['phase'] != 'stopped':
49
+ raise ValueError('Playback backfill requires a stopped run')
50
+ raw = {r['frame_idx']: r for r in map(json.loads, (capture / 'observations.jsonl').read_text().splitlines())}
51
+ os.chdir(cross_root)
52
+ sys.path.insert(0, str(cross_root))
53
+ from cross.core.config import load_config
54
+ from cross.core.types import Camera
55
+ from cross.pipeline import add_session_args, finish_session_args, mode_config_files, session_factory
56
+ first = raw[source_rows[0]['capture_frame']]
57
+ image = cv2.imread(str(capture / 'rgb' / f"{first['frame_idx']:08d}.jpg"))
58
+ h, w = image.shape[:2]
59
+ camera = Camera(K=np.asarray(first['camera_K']), frame_width=w, frame_height=h)
60
+ parser = argparse.ArgumentParser()
61
+ add_session_args(parser)
62
+ options = parser.parse_args(['--mode', 'mono', '--odometry', 'external', '--mono-estimator', 'ff'])
63
+ finish_session_args(options)
64
+ overrides = ['pose_est.ff.checkpoint=finetuned', 'pose_est.obs_max_interval_steps=1',
65
+ f'pose_est.ff.nav_bev_head={occupancy}', f'pose_est.ff.nav_bev_visibility={visibility}',
66
+ f'pose_est.ff.nav_bev_visibility_gravity={occupancy}']
67
+ if archive is not None:
68
+ overrides = json.loads((archive / 'mapping/run.json').read_text())['config_overrides']
69
+ config = load_config(*mode_config_files('mono', 'external', mono_estimator='ff'), sets=overrides)
70
+ artifacts = RunArtifacts(output, {'mode': 'mono', 'odometry': 'external', 'dataset': str(capture),
71
+ 'loaded_map': str(map_run / 'map.pkl'), 'source_probe': str(probe), 'robot_commands_sent': 0,
72
+ 'learned_bev_heads_available': True, 'config_overrides': overrides,
73
+ 'depth_used_for_inference': False, 'gravity_source': 'recorded odom camera TF',
74
+ 'checkpoint_provenance': json.loads((heads / 'provenance.json').read_text())})
75
+ (output / 'bevs').mkdir()
76
+ session, prior, observed = None, None, []
77
+ debug_archive = replay_error = None
78
+ try:
79
+ session = artifacts.wrap_factory(session_factory(options, camera, config))()
80
+ session.load_map(map_run / 'map.pkl')
81
+ estimator = session.mapper.pose_est
82
+ if args.vggt_debug:
83
+ debug_archive = VggtDebugRecorder(debug_path, {
84
+ 'origin': 'recomputed_from_capture', 'source_capture': str(capture),
85
+ 'source_probe': str(probe), 'config_overrides': overrides,
86
+ 'checkpoint_provenance': artifacts.metadata['checkpoint_provenance'],
87
+ 'resolved_config': json.loads((output / 'resolved_config.json').read_text()),
88
+ 'camera_catalog': clean_json(session.mapper.cameras), 'session_camera_id': session.mapper.cam_id,
89
+ **model_provenance(cross_root),
90
+ })
91
+ debug_archive.attach(estimator)
92
+ for source in source_rows:
93
+ index = source['capture_frame']
94
+ row = raw[index]
95
+ pose = np.asarray(row['camera_pose'], dtype=float)
96
+ rgb = cv2.cvtColor(cv2.imread(str(capture / 'rgb' / f'{index:08d}.jpg')), cv2.COLOR_BGR2RGB)
97
+ estimator.set_gravity(pose[:3, :3].T @ np.array([0., 0., 1.]))
98
+ passes = estimator._n_passes
99
+ started = time.perf_counter()
100
+ if debug_archive:
101
+ debug_archive.begin_frame(row)
102
+ session.process({'rgb': rgb, 'timestamp': row['sensor_stamp'], 'frame_idx': index,
103
+ 'delta_pose': None if prior is None else np.linalg.inv(prior) @ pose})
104
+ prior = pose
105
+ c0, best, weights = session.belief(matrix)
106
+ diagnostic = session.mapper.last_step_diagnostics
107
+ audit = [{'keyframe_id': int(a['keyframe_id']), 'score': float(a['retrieval_score']),
108
+ 'verified': bool(a['verified']), 'loaded': bool(a['loaded'])}
109
+ for a in diagnostic.get('retrieval_audit', [])]
110
+ bev = estimator.last_bev if estimator._n_passes != passes else None
111
+ metadata = {k: v for k, v in (bev or {}).items()
112
+ if k not in ('prob', 'observability', 'uncertainty')}
113
+ grid = None
114
+ if bev is not None:
115
+ for key in ('prob', 'observability', 'uncertainty'):
116
+ array = np.asarray(bev[key], dtype=np.float32)
117
+ if array.shape != (400, 400) or not np.isfinite(array).all():
118
+ raise ValueError(f'Invalid learned {key} on frame {index}')
119
+ if not args.skip_numeric_bevs:
120
+ np.savez_compressed(output / 'bevs' / f'{index:08d}.npz',
121
+ prob=bev['prob'], obs=bev['observability'], err=bev['uncertainty'],
122
+ R_bev_from_cam=bev['R_bev_from_cam'], up_cam=bev['up_cam'])
123
+ if archive is not None or debug_archive:
124
+ grid = reproject_bev(bev['prob'], bev['observability'], bev['uncertainty'],
125
+ bev['R_bev_from_cam'], pose, np.asarray(row['base_pose_matrix']), bev['res'])
126
+ if archive is not None:
127
+ images = {f'{name}.png': learned_png(grid['prob'], grid['obs'], grid['err'], name)
128
+ for name in ('occupancy', 'visibility', 'uncertainty')}
129
+ save_bev_frame(archive, int(index), images, source='reconstructed', only_missing=True)
130
+ record = {'capture_frame': index, 'timestamp': row['sensor_stamp'],
131
+ 'localized': bool(session.localized()), 'map_pose': c0, 'best_pose': best,
132
+ 'weights': weights, 'retrieval': audit, 'camera_pose_odom': pose,
133
+ 'base_pose_odom': row['base_pose'], 'bev_fresh': bev is not None,
134
+ 'bev': metadata, 'process_s': time.perf_counter() - started}
135
+ if debug_archive:
136
+ debug_archive.finish_frame(observation=record, consumed_bev=bev, body_grid=grid)
137
+ observed.append(record)
138
+ artifacts.records[-1].update(localized=record['localized'], retrieval_audit=audit)
139
+ save_json(output / 'observations.json', observed)
140
+ print(json.dumps({'processed':len(observed), 'total':len(source_rows), 'frame':index,
141
+ 'localized':record['localized'], 'fresh_bev':bev is not None,
142
+ 'scale_source':metadata.get('scale_source'), 'n_views':metadata.get('n_views'),
143
+ 'process_s':record['process_s']}), flush=True)
144
+ session.release()
145
+ artifacts.finish()
146
+ except BaseException as exc:
147
+ replay_error = exc
148
+ artifacts.finish(exc)
149
+ raise
150
+ finally:
151
+ if debug_archive:
152
+ debug_archive.close(replay_error)
153
+ summary = {'processed_frames': len(observed), 'localized_frames': sum(r['localized'] for r in observed),
154
+ 'fresh_bev_frames': sum(r['bev_fresh'] for r in observed),
155
+ 'distinct_verified_map_keyframes': sorted({a['keyframe_id'] for r in observed
156
+ for a in r['retrieval'] if a['loaded'] and a['verified']}),
157
+ 'robot_commands_sent': 0, 'ground_truth_available': False,
158
+ 'reference_map_sha256': hashlib.sha256((map_run / 'map.pkl').read_bytes()).hexdigest()}
159
+ save_json(output / 'result.json', summary)
160
+ print(json.dumps(summary), flush=True)
161
+
162
+
163
+ if __name__ == '__main__':
164
+ main()
cases/20261026_goal1012_05/code/lite3_ROS/scripts/view_stretch_cross_nav_live_run.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Review a stopped live run. Opens no robot transport or model and cannot arm."""
3
+ import argparse
4
+ from http.server import ThreadingHTTPServer
5
+ import json
6
+ from pathlib import Path
7
+ import secrets
8
+ import sys
9
+ import threading
10
+
11
+ import numpy as np
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ sys.path.insert(0, str(ROOT))
15
+ from scripts.live_stretch_cross_nav import Handler
16
+ from web_console.stretch_nav_replay import ReplayService
17
+
18
+
19
+ class Review:
20
+ def __init__(self, directory):
21
+ self.root = Path(directory).resolve()
22
+ self.replay = ReplayService(self.root)
23
+ snapshot = self.root / 'review.json'
24
+ if not snapshot.is_file():
25
+ snapshot = self.root / 'final_status.json'
26
+ self.data = json.loads(snapshot.read_text())
27
+ self.data.update(phase='stopped', ready=False, gate='Saved run; motion controls disabled', review=True,
28
+ replay_available=True)
29
+ self.phase = 'stopped'
30
+ self.token = secrets.token_urlsafe(24)
31
+ self.lock = threading.RLock()
32
+ self.map_data = json.loads((self.root / 'map.json').read_text())
33
+ archive = self.replay.get()
34
+ self.images = {}
35
+ for name in ('occupancy', 'visibility', 'uncertainty'):
36
+ path = self.root / 'review_bev' / f'{name}.png'
37
+ if path.is_file():
38
+ self.images[f'{name}.png'] = path.read_bytes()
39
+ elif archive.bev_ids:
40
+ self.images[f'{name}.png'] = archive.image(archive.bev_ids[-1], name)
41
+ self.packet = ({'rgb_jpg': np.frombuffer(archive.image(archive.raw_ids[-1]), np.uint8)}
42
+ if archive.raw_ids else None)
43
+
44
+ def snapshot(self):
45
+ return {**self.data, 'token': self.token}
46
+
47
+ def finish(self, _):
48
+ pass
49
+
50
+
51
+ def main():
52
+ p = argparse.ArgumentParser(description=__doc__)
53
+ p.add_argument('--run', type=Path, required=True)
54
+ p.add_argument('--port', type=int, default=8088)
55
+ args = p.parse_args()
56
+ server = ThreadingHTTPServer(('127.0.0.1', args.port), Handler)
57
+ server.daemon_threads = True
58
+ server.state = Review(args.run)
59
+ print(f'Saved live-run review: http://127.0.0.1:{args.port} (motion disabled)', flush=True)
60
+ try:
61
+ server.serve_forever()
62
+ except KeyboardInterrupt:
63
+ pass
64
+ finally:
65
+ server.server_close()
66
+
67
+
68
+ if __name__ == '__main__':
69
+ main()
cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_capture_format.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ import numpy as np
4
+
5
+ from scripts.capture_stretch_cross import atomic_json
6
+
7
+
8
+ def test_nested_robot_status_and_numpy_scalars_serialize(tmp_path):
9
+ path = tmp_path / 'capture.json'
10
+ state = {'robot_status': {'base_pose': np.array([1., 2., .3]), 'armed': np.bool_(False)},
11
+ 'frames': np.int64(7)}
12
+ atomic_json(path, state)
13
+ assert json.loads(path.read_text()) == {
14
+ 'robot_status': {'base_pose': [1., 2., .3], 'armed': False}, 'frames': 7}
15
+ assert not path.with_suffix('.json.tmp').exists()
cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_control.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from web_console.stretch_nav_control import (
5
+ PlanWait,
6
+ alignment_correction,
7
+ attachment_clear,
8
+ competing_controllers,
9
+ depth_veto,
10
+ execution_gate,
11
+ remaining_path,
12
+ stationary_head_command,
13
+ )
14
+
15
+
16
+ def planar_transform(angle=0., x=0., y=0.):
17
+ c, s = np.cos(angle), np.sin(angle)
18
+ return np.array([[c, -s, 0., x], [s, c, 0., y], [0., 0., 1., 0.], [0., 0., 0., 1.]])
19
+
20
+
21
+ def test_small_map_rotation_about_distant_robot_does_not_look_like_position_jump():
22
+ base = planar_transform(x=20., y=10.)
23
+ angle = np.deg2rad(2.3)
24
+ corrected = base @ planar_transform(angle) @ np.linalg.inv(base)
25
+ assert np.linalg.norm(corrected[:3, 3]) > .5 # The former origin-based check stopped here.
26
+ distance, rotation = alignment_correction(np.eye(4), corrected, base)
27
+ assert distance == pytest.approx(0., abs=1e-12)
28
+ assert rotation == pytest.approx(angle)
29
+
30
+
31
+ def test_map_correction_is_independent_of_odom_origin():
32
+ previous = planar_transform(.3, 1., 2.)
33
+ current = planar_transform(.32, 1.1, 2.2)
34
+ base = planar_transform(.7, 12., 8.)
35
+ expected = alignment_correction(previous, current, base)
36
+ rebase = planar_transform(-.8, 100., -200.)
37
+ actual = alignment_correction(previous @ np.linalg.inv(rebase), current @ np.linalg.inv(rebase), rebase @ base)
38
+ np.testing.assert_allclose(actual, expected, atol=1e-12)
39
+
40
+
41
+ @pytest.mark.parametrize('translation,angle', [(.51, 0.), (0., np.deg2rad(26))])
42
+ def test_real_map_pose_jump_still_exceeds_stop_limits(translation, angle):
43
+ base = planar_transform(x=20., y=10.)
44
+ corrected = planar_transform(x=translation) @ base @ planar_transform(angle) @ np.linalg.inv(base)
45
+ distance, rotation = alignment_correction(np.eye(4), corrected, base)
46
+ assert distance > .5 or rotation > np.deg2rad(25)
47
+
48
+
49
+ @pytest.mark.parametrize('bad', [np.full((4, 4), np.nan), np.eye(3)])
50
+ def test_invalid_alignment_is_rejected(bad):
51
+ with pytest.raises(ValueError, match='Invalid map alignment'):
52
+ alignment_correction(np.eye(4), bad, np.eye(4))
53
+
54
+
55
+ def valid_inputs():
56
+ plan = {'input_received': 9.8, 'localized': True, 'localized_streak': 3,
57
+ 'route_ids': [1, 2], 'planner_status': 0,
58
+ 'goal_distance': 2., 'path_odom': [[0., 0.], [1., 0.]]}
59
+ robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True,
60
+ 'healthy': True, 'latched': False}
61
+ return plan, robot
62
+
63
+
64
+ def test_teleop_never_passes_execution_gate():
65
+ p, r = valid_inputs()
66
+ assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9, state='teleop')
67
+ assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9) == ''
68
+
69
+
70
+ @pytest.mark.parametrize('field,value', [('localized', False), ('localized_streak', 2),
71
+ ('input_received', 7.9), ('input_received', np.nan),
72
+ ('route_ids', []), ('planner_status', 2), ('path_odom', []), ('goal_distance', np.nan)])
73
+ def test_bad_plan_blocks_commands(field, value):
74
+ p, r = valid_inputs()
75
+ p[field] = value
76
+ assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9)
77
+
78
+
79
+ @pytest.mark.parametrize('verified_at', [None, 7., -np.inf])
80
+ def test_committed_localization_can_bridge_map_match_gaps(verified_at):
81
+ p, r = valid_inputs()
82
+ # Accept both new plans with no verification clock and older recorded plans.
83
+ if verified_at is not None:
84
+ p['verified_at'] = verified_at
85
+ assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9) == ''
86
+ # Only new sensor/plan evidence keeps execution alive during a longer gap.
87
+ p['input_received'] = 39.8
88
+ assert execution_gate(p, r, now=40., robot_received=39.9, heartbeat=39.9) == ''
89
+ p['localized'] = False
90
+ assert execution_gate(p, r, now=40., robot_received=39.9, heartbeat=39.9) == (
91
+ 'waiting for stable committed localization')
92
+
93
+
94
+ @pytest.mark.parametrize('field,value', [('is_runstopped', True), ('is_homed', False),
95
+ ('posture_ok', False), ('latched', True), ('healthy', False)])
96
+ def test_unavailable_robot_blocks_commands(field, value):
97
+ p, r = valid_inputs()
98
+ r[field] = value
99
+ assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9)
100
+
101
+
102
+ def test_stale_browser_and_status_block_commands():
103
+ p, r = valid_inputs()
104
+ assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=4.)
105
+ assert execution_gate(p, r, now=10., robot_received=9., heartbeat=9.9)
106
+
107
+
108
+ def test_follow_path_drops_passed_prefix_and_rotates_into_current_base():
109
+ result = remaining_path([[0., 0.], [0., 1.], [0., 2.]], [0., .6, np.pi / 2])
110
+ np.testing.assert_allclose(result[:, 0], [0., .4, 1.4], atol=1e-8)
111
+ np.testing.assert_allclose(result[:, 1], 0., atol=1e-8)
112
+
113
+
114
+ def test_depth_guard_vetoes_swept_body_but_ignores_off_path_returns():
115
+ obstacle = np.array([[.30, -.01], [.30, 0.], [.30, .01]])
116
+ assert depth_veto(obstacle, [0., 0., 0.], .1, 0.)
117
+ assert not depth_veto(obstacle + [0., 1.], [0., 0., 0.], .1, 0.)
118
+
119
+
120
+ def test_attachment_rejects_measured_wall_between_base_and_nearby_keyframe():
121
+ obstacle = np.array([[.35, -.01], [.35, 0.], [.35, .01]])
122
+ assert not attachment_clear(obstacle, [0., 0., 0.], [.5, 0.])
123
+ assert attachment_clear(obstacle, [0., 0., 0.], [-.5, 0.])
124
+
125
+
126
+ def test_attachment_handles_sideways_connection_and_robot_self_mask():
127
+ obstacle = np.array([[0., .35], [.01, .35], [-.01, .35], [0., 0.]])
128
+ assert not attachment_clear(obstacle, [0., 0., np.pi / 2], [0., .5])
129
+ assert attachment_clear(obstacle, [0., 0., np.pi / 2], [0., -.5])
130
+
131
+
132
+ def test_relaxed_plan_limit_still_expires():
133
+ p, r = valid_inputs()
134
+ p['input_received'] = 8.1
135
+ assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9) == ''
136
+ p['input_received'] = 7.9
137
+ assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9)
138
+
139
+
140
+ def test_plan_wait_recovers_transient_gaps_but_ends_sustained_gap():
141
+ wait = PlanWait(timeout=3.)
142
+ assert wait.holds('sensor/plan evidence stale', 10.)
143
+ assert wait.holds('sensor/plan evidence stale', 12.9)
144
+ assert not wait.holds('sensor/plan evidence stale', 13.1)
145
+ assert not wait.holds('', 14.)
146
+ assert wait.since is None
147
+ assert wait.holds('sensor/plan evidence stale', 20.)
148
+
149
+
150
+ def stationary_inputs():
151
+ plan, robot = valid_inputs()
152
+ plan.update(input_received=5., frame_id=1, observation_hold=True, stationary_survey=True,
153
+ head_target=[.5, -1.05], head_anchor=np.eye(4), head_deadline=25., scan_w=0.)
154
+ robot.update(frame_id=100, sensor_age=.08, tf_age=.02, base_pose=[0., 0., 0.],
155
+ joint_positions=np.zeros(11), head_enabled=True)
156
+ return plan, robot
157
+
158
+
159
+ def test_stationary_head_uses_current_sensor_evidence_even_when_vggt_is_late():
160
+ plan, robot = stationary_inputs()
161
+ # The driving image expired long ago; the latest source image is fresh.
162
+ command, fault = stationary_head_command(plan, robot, now=10., robot_received=9.95)
163
+ assert not fault and command == {'frame_id': 100, 'head_target': [.5, -1.05], 'v': 0., 'w': 0.}
164
+ assert execution_gate(plan, robot, now=10., robot_received=9.95, heartbeat=9.9) == ''
165
+ plan['observation_hold'] = False
166
+ assert execution_gate(plan, robot, now=10., robot_received=9.95, heartbeat=9.9) == 'sensor/plan evidence stale'
167
+
168
+
169
+ def test_stationary_scan_can_complete_without_a_global_attachment_but_cannot_drive():
170
+ plan, robot = stationary_inputs()
171
+ plan['route_ids'] = []
172
+ assert execution_gate(plan, robot, now=10., robot_received=9.95, heartbeat=9.9) == ''
173
+ plan.update(observation_hold=False, input_received=9.8)
174
+ assert execution_gate(plan, robot, now=10., robot_received=9.95, heartbeat=9.9) == 'no global route'
175
+
176
+
177
+ @pytest.mark.parametrize('change', ['rotation', 'deadline', 'bad_deadline', 'sensor', 'tf', 'joints', 'base', 'head'])
178
+ def test_head_only_renewal_cannot_hide_expiry_missing_feedback_or_base_motion(change):
179
+ plan, robot = stationary_inputs()
180
+ if change == 'rotation':
181
+ plan['scan_w'] = .1
182
+ elif change == 'deadline':
183
+ plan['head_deadline'] = 9.9
184
+ elif change == 'bad_deadline':
185
+ plan['head_deadline'] = np.inf
186
+ elif change == 'sensor':
187
+ robot['sensor_age'] = .8
188
+ elif change == 'tf':
189
+ robot['tf_age'] = .6
190
+ elif change == 'joints':
191
+ robot['joint_positions'] = np.zeros(9)
192
+ elif change == 'base':
193
+ robot['base_pose'] = [.06, 0., 0.]
194
+ elif change == 'head':
195
+ robot['head_enabled'] = False
196
+ assert execution_gate(plan, robot, now=10., robot_received=9.95, heartbeat=9.9)
197
+
198
+
199
+ @pytest.mark.parametrize('field,value', [('is_runstopped', True), ('healthy', False), ('latched', True)])
200
+ def test_stationary_head_does_not_override_stop_or_health_faults(field, value):
201
+ plan, robot = stationary_inputs()
202
+ robot[field] = value
203
+ assert execution_gate(plan, robot, now=10., robot_received=9.95, heartbeat=9.9)
204
+ robot[field] = not value
205
+ assert execution_gate(plan, robot, now=10., robot_received=9.95, heartbeat=4.) == 'viewer heartbeat expired'
206
+
207
+
208
+ def test_relaxed_browser_and_status_limits_allow_jitter_and_still_expire():
209
+ plan, robot = valid_inputs()
210
+ assert execution_gate(plan, robot, now=10., robot_received=9.6, heartbeat=7.) == ''
211
+ assert execution_gate(plan, robot, now=10., robot_received=9.49, heartbeat=7.) == 'robot status stale'
212
+ assert execution_gate(plan, robot, now=10., robot_received=9.9, heartbeat=4.9) == 'viewer heartbeat expired'
213
+
214
+
215
+ def test_default_wait_tolerates_a_longer_compute_gap_at_zero():
216
+ wait = PlanWait()
217
+ assert wait.holds('sensor/plan evidence stale', 10.)
218
+ assert wait.holds('sensor/plan evidence stale', 17.9)
219
+ assert not wait.holds('sensor/plan evidence stale', 18.1)
220
+
221
+
222
+ def test_corner_rotation_waits_for_new_geometry_while_stationary_survey_cannot_reanchor():
223
+ plan, robot = stationary_inputs()
224
+ plan['stationary_survey'] = False
225
+ robot['base_pose'] = [0., 0., .2]
226
+ assert execution_gate(plan, robot, now=10., robot_received=9.95, heartbeat=9.9) == (
227
+ 'head observation feedback unavailable')
228
+ # A new processed corner view accounts for the permitted base rotation.
229
+ plan['head_anchor'] = planar_transform(.2)
230
+ assert execution_gate(plan, robot, now=10., robot_received=9.95, heartbeat=9.9) == ''
231
+ plan.update(stationary_survey=True, head_anchor=np.eye(4))
232
+ assert execution_gate(plan, robot, now=10., robot_received=9.95, heartbeat=9.9) == (
233
+ 'base moved during head observation')
234
+
235
+
236
+ @pytest.mark.parametrize('reason', ['viewer heartbeat expired',
237
+ 'waiting for stable committed localization', 'robot state/camera/TF unavailable', 'robot stop latched'])
238
+ def test_plan_wait_never_treats_other_faults_as_transient(reason):
239
+ assert not PlanWait().holds(reason, 10.)
240
+
241
+
242
+ def test_known_teleop_process_detected_without_matching_our_live_adapter(tmp_path):
243
+ for pid, args in [(100, ['python', '/app/teleop.py', '--robot-ip', '192.0.2.1']),
244
+ (101, ['python', '/app/live_stretch_cross_nav.py']),
245
+ (102, ['bash', '-c', 'python teleop.py'])]:
246
+ directory = tmp_path / str(pid)
247
+ directory.mkdir()
248
+ (directory / 'cmdline').write_bytes(b'\0'.join(a.encode() for a in args))
249
+ assert competing_controllers(tmp_path) == [{'pid': 100, 'client': 'teleop.py'}]
cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_geometry.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from web_console.stretch_nav_geometry import body_to_world, measured_bev, world_to_body
5
+
6
+
7
+ def test_body_goal_transform_handles_yaw_and_offset():
8
+ base = np.array([[0., -1, 0, 4], [1, 0, 0, 2], [0, 0, 1, 0], [0, 0, 0, 1]])
9
+ points = np.array([[2., 1.], [0., -1.]])
10
+ world = body_to_world(points, base)
11
+ np.testing.assert_allclose(world, [[3, 4], [5, 2]])
12
+ np.testing.assert_allclose([world_to_body(p, base) for p in world], points, atol=1e-12)
13
+
14
+
15
+ def test_missing_depth_stays_unknown_instead_of_becoming_free():
16
+ K = np.array([[40., 0, 30], [0, 40, 20], [0, 0, 1]])
17
+ camera = np.array([[0., 0, 1, 0], [-1, 0, 0, 0], [0, -1, 0, 1], [0, 0, 0, 1]])
18
+ result = measured_bev(np.zeros((40, 60)), K, camera, np.eye(4), size=80)
19
+ assert result['observed_cells'] == 0
20
+ assert result['occupied_cells'] == 0
21
+ assert (result['prob'] == .5).all()
22
+
23
+
24
+ def test_elevated_surface_blocks_without_marking_occluded_floor_free():
25
+ K = np.array([[40., 0, 30], [0, 40, 20], [0, 0, 1]])
26
+ camera = np.array([[0., 0, 1, 0], [-1, 0, 0, 0], [0, -1, 0, 1], [0, 0, 0, 1]])
27
+ result = measured_bev(np.ones((40, 60)), K, camera, np.eye(4), size=100)
28
+ assert result['occupied_cells'] > 0
29
+ # Ground 2m ahead would project into the wall, whose measured depth is 1m.
30
+ row, col = int(50 - 2 / .05), 50
31
+ assert result['obs'][row, col] == 0
32
+ assert result['prob'][row, col] == pytest.approx(.5)
33
+
34
+
35
+ def test_geometry_rejects_nonfinite_transforms():
36
+ camera = np.eye(4)
37
+ camera[0, 3] = np.nan
38
+ with pytest.raises(ValueError, match='Nonfinite'):
39
+ measured_bev(np.ones((20, 20)), np.eye(3), camera, np.eye(4))
cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_handoff.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exercise command transport with fake sockets; these tests cannot reach hardware."""
2
+ import importlib.util
3
+ import sys
4
+ import threading
5
+ import time
6
+ from pathlib import Path
7
+ from types import SimpleNamespace
8
+
9
+ import numpy as np
10
+ import pytest
11
+
12
+
13
+ def load_adapter():
14
+ path = Path(__file__).resolve().parents[1] / 'scripts/live_stretch_cross_nav.py'
15
+ spec = importlib.util.spec_from_file_location('stretch_live_adapter', path)
16
+ module = importlib.util.module_from_spec(spec)
17
+ spec.loader.exec_module(module)
18
+ return module
19
+
20
+
21
+ class Socket:
22
+ def __init__(self):
23
+ self.sent = []
24
+
25
+ def setsockopt(self, *_):
26
+ pass
27
+
28
+ def connect(self, *_):
29
+ pass
30
+
31
+ def poll(self, *_):
32
+ return False
33
+
34
+ def close(self):
35
+ pass
36
+
37
+ def send_json(self, command, **_):
38
+ self.sent.append(command)
39
+
40
+ def send_pyobj(self, command):
41
+ self.sent.append(command)
42
+
43
+
44
+ class Context:
45
+ def __init__(self):
46
+ self.sockets = []
47
+
48
+ def socket(self, *_):
49
+ result = Socket()
50
+ self.sockets.append(result)
51
+ return result
52
+
53
+ def term(self):
54
+ pass
55
+
56
+
57
+ def setup(monkeypatch, tmp_path):
58
+ module = load_adapter()
59
+ context = Context()
60
+ monkeypatch.setattr(module.zmq, 'Context', lambda: context)
61
+ monkeypatch.setattr(module, 'competing_controllers', lambda: [])
62
+ monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(
63
+ pure_pursuit=lambda *_a, **_k: (_ for _ in ()).throw(AssertionError('Must not follow a path'))))
64
+ args = SimpleNamespace(output=tmp_path, robot_ip='unreachable.invalid', goal=1012, max_v=.1, max_w=.25, max_plan_age=1.2, plan_hold_seconds=3.)
65
+ state = module.LiveState(args)
66
+ return module, state, context
67
+
68
+
69
+ def test_passive_loop_never_sends_arm_mode_stop_or_velocity(monkeypatch, tmp_path):
70
+ module, state, context = setup(monkeypatch, tmp_path)
71
+ # Complete several real control ticks before ending the fake session.
72
+ timer = threading.Timer(.18, state.done.set)
73
+ timer.start()
74
+ module.control_loop(state)
75
+ timer.join()
76
+ assert len(context.sockets) == 3
77
+ assert all(not socket.sent for socket in context.sockets)
78
+ assert state.motion_commands == 0
79
+
80
+
81
+ def test_loss_of_localization_sends_stop_only(monkeypatch, tmp_path):
82
+ module, state, context = setup(monkeypatch, tmp_path)
83
+ state.phase = 'active'
84
+ state.relay_ever_requested = True
85
+ state.heartbeat = state.robot_received = time.monotonic()
86
+ state.robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True,
87
+ 'healthy': True, 'latched': False}
88
+ state.plan = {'input_received': time.monotonic(), 'goal_distance': 2., 'localized': False}
89
+ module.control_loop(state)
90
+ assert state.phase == 'stopped'
91
+ commands = [command for socket in context.sockets for command in socket.sent]
92
+ assert len(commands) == 3
93
+ assert all(command['type'] == 'stop' for command in commands)
94
+ assert state.motion_commands == 0
95
+
96
+
97
+ def test_browser_disconnect_stops_without_motion(monkeypatch, tmp_path):
98
+ module, state, context = setup(monkeypatch, tmp_path)
99
+ state.phase = 'active'
100
+ state.relay_ever_requested = True
101
+ state.heartbeat = time.monotonic() - 6.
102
+ module.control_loop(state)
103
+ assert state.phase == 'stopped'
104
+ assert all(c['type'] == 'stop' for socket in context.sockets for c in socket.sent)
105
+ assert 'heartbeat' in state.reason
106
+
107
+
108
+ def test_brief_plan_gap_sends_zero_then_resumes_only_with_fresh_plan(monkeypatch, tmp_path):
109
+ module, state, context = setup(monkeypatch, tmp_path)
110
+ monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=lambda *_a, **_k: (.08, 0.)))
111
+ state.phase = 'active'
112
+ state.relay_ever_requested = True
113
+ now = time.monotonic()
114
+ state.heartbeat = state.robot_received = now
115
+ state.robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True, 'healthy': True,
116
+ 'latched': False, 'armed': True, 'session': state.session, 'frame_id': 1, 'base_pose': [0., 0., 0.]}
117
+ state.plan = {'input_received': now - 1.3, 'goal_distance': 2., 'localized': True,
118
+ 'localized_streak': 3, 'route_ids': [1, 2],
119
+ 'planner_status': 0, 'path_odom': [[0., 0.], [1., 0.]], 'frame_id': 1,
120
+ 'depth_obstacles': np.empty((0, 2))}
121
+ fresh = threading.Timer(.075, lambda: state.plan.update(input_received=time.monotonic()))
122
+ end = threading.Timer(.23, lambda: state.finish('End simulated run'))
123
+ fresh.start()
124
+ end.start()
125
+ module.control_loop(state)
126
+ fresh.join()
127
+ end.join()
128
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
129
+ assert commands[0]['v'] == commands[0]['w'] == 0.
130
+ assert any(c['v'] > 0 for c in commands)
131
+ assert all(c['ttl'] == .3 for c in commands)
132
+ import json
133
+ assert json.loads((tmp_path / 'control.json').read_text())['v'] == 0.
134
+
135
+
136
+ @pytest.mark.parametrize('has_old_verification_clock', [False, True])
137
+ def test_map_match_gap_continues_fresh_local_plan(monkeypatch, tmp_path, has_old_verification_clock):
138
+ module, state, context = setup(monkeypatch, tmp_path)
139
+ monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=lambda *_a, **_k: (.08, 0.)))
140
+ state.phase = 'active'
141
+ state.relay_ever_requested = True
142
+ now = time.monotonic()
143
+ state.heartbeat = state.robot_received = now
144
+ state.robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True, 'healthy': True,
145
+ 'latched': False, 'armed': True, 'session': state.session, 'frame_id': 1, 'base_pose': [0., 0., 0.]}
146
+ state.plan = {'input_received': now, 'goal_distance': 2., 'localized': True,
147
+ 'localized_streak': 3, 'route_ids': [1, 2],
148
+ 'planner_status': 0, 'path_odom': [[0., 0.], [1., 0.]], 'frame_id': 1,
149
+ 'depth_obstacles': np.empty((0, 2))}
150
+ if has_old_verification_clock:
151
+ state.plan['verified_at'] = now - 30.
152
+ end = threading.Timer(.18, lambda: state.finish('End simulated visual gap'))
153
+ end.start()
154
+ module.control_loop(state)
155
+ end.join()
156
+ commands = [c for socket in context.sockets for c in socket.sent]
157
+ velocity = [c for c in commands if c['type'] == 'velocity']
158
+ assert velocity and all(c['v'] == .08 and c['w'] == 0. for c in velocity)
159
+ assert all(c['ttl'] == .3 for c in velocity)
160
+ assert [c['type'] for c in commands[-3:]] == ['stop', 'stop', 'stop']
161
+ assert state.reason == 'End simulated visual gap'
162
+
163
+
164
+ def test_sustained_plan_gap_never_executes_stale_path(monkeypatch, tmp_path):
165
+ module, state, context = setup(monkeypatch, tmp_path)
166
+ state.args.plan_hold_seconds = .08
167
+ state.phase = 'active'
168
+ state.relay_ever_requested = True
169
+ now = time.monotonic()
170
+ state.heartbeat = state.robot_received = now
171
+ state.robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True, 'healthy': True,
172
+ 'latched': False, 'armed': True, 'session': state.session, 'frame_id': 1, 'base_pose': [0., 0., 0.]}
173
+ state.plan = {'input_received': now - 1.3, 'goal_distance': 2.}
174
+ module.control_loop(state)
175
+ assert state.phase == 'stopped'
176
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
177
+ assert commands and all(c['v'] == c['w'] == 0. for c in commands)
178
+
179
+
180
+ def test_competing_teleop_blocks_mode_switch_and_arm(monkeypatch, tmp_path):
181
+ module, state, context = setup(monkeypatch, tmp_path)
182
+ monkeypatch.setattr(module, 'competing_controllers', lambda: [{'pid': 123, 'client': 'teleop.py'}])
183
+ state.phase = 'preparing'
184
+ module.control_loop(state)
185
+ assert state.phase == 'stopped'
186
+ assert 'Competing' in state.reason
187
+ assert all(not socket.sent for socket in context.sockets)
188
+
189
+
190
+ def test_time_spent_scanning_controllers_counts_toward_plan_expiry(monkeypatch, tmp_path):
191
+ module, state, context = setup(monkeypatch, tmp_path)
192
+ clock = [10.]
193
+ monkeypatch.setattr(module.time, 'monotonic', lambda: clock[0])
194
+ def slow_scan():
195
+ clock[0] = 13.
196
+ return []
197
+ monkeypatch.setattr(module, 'competing_controllers', slow_scan)
198
+ state.phase = 'active'
199
+ state.relay_ever_requested = True
200
+ state.args.plan_hold_seconds = 0.
201
+ state.heartbeat = state.robot_received = 13.
202
+ state.robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True,
203
+ 'healthy': True, 'latched': False}
204
+ state.plan = {'input_received': 10., 'goal_distance': 2., 'localized': True,
205
+ 'localized_streak': 3, 'route_ids': [1, 2], 'planner_status': 0,
206
+ 'path_odom': [[0., 0.], [1., 0.]]}
207
+ module.control_loop(state)
208
+ assert state.reason == 'sensor/plan evidence stale; navigation ended'
209
+ assert state.motion_commands == 0
210
+ assert all(c['type'] == 'stop' for socket in context.sockets for c in socket.sent)
211
+
212
+
213
+ def test_planner_warmup_compiles_both_searches_without_robot_transport(monkeypatch):
214
+ module = load_adapter()
215
+ calls = []
216
+ def dijkstra(*args):
217
+ calls.append('dijkstra')
218
+ dijkstra.signatures.append('compiled')
219
+ dijkstra.signatures = []
220
+ search = SimpleNamespace(signatures=[])
221
+ def astar(*args):
222
+ calls.append('astar')
223
+ search.signatures.append('compiled')
224
+ monkeypatch.setitem(sys.modules, 'numba', SimpleNamespace(__version__='test'))
225
+ monkeypatch.setitem(sys.modules, 'cross_nav.plan', SimpleNamespace(_dijkstra=dijkstra))
226
+ monkeypatch.setitem(sys.modules, 'cross_nav.policy.bev_policy', SimpleNamespace(_astar=lambda: search, astar=astar))
227
+ monkeypatch.setattr(module.zmq, 'Context', lambda: (_ for _ in ()).throw(AssertionError('No transport during warmup')))
228
+ result = module.warmup_native_navigation()
229
+ assert calls == ['astar', 'dijkstra']
230
+ assert result['astar_signatures'] == result['dijkstra_signatures'] == ['compiled']
231
+
232
+
233
+ def test_unaccelerated_planner_is_rejected_before_handoff(monkeypatch):
234
+ module = load_adapter()
235
+ monkeypatch.setitem(sys.modules, 'numba', SimpleNamespace(__version__='test'))
236
+ monkeypatch.setitem(sys.modules, 'cross_nav.plan', SimpleNamespace(_dijkstra=lambda *_: None))
237
+ monkeypatch.setitem(sys.modules, 'cross_nav.policy.bev_policy',
238
+ SimpleNamespace(_astar=lambda: (lambda *_: None), astar=lambda *_: None))
239
+ with pytest.raises(RuntimeError, match='requires CROSS nav dependencies'):
240
+ module.warmup_native_navigation()
241
+
242
+
243
+ def active_plan(state):
244
+ now = time.monotonic()
245
+ state.phase, state.relay_ever_requested = 'active', True
246
+ state.heartbeat = state.robot_received = now
247
+ state.robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True, 'healthy': True,
248
+ 'latched': False, 'armed': True, 'session': state.session, 'frame_id': 1,
249
+ 'base_pose': [0., 0., 0.], 'head_enabled': True}
250
+ state.plan = {'input_received': now, 'goal_distance': 2., 'localized': True,
251
+ 'localized_streak': 3, 'route_ids': [1, 2], 'planner_status': 0,
252
+ 'path_odom': [[0., 0.], [1., 0.]], 'frame_id': 1,
253
+ 'depth_obstacles': np.empty((0, 2))}
254
+
255
+
256
+ def test_correction_recovery_keeps_lease_at_zero_then_resumes(monkeypatch, tmp_path):
257
+ module, state, context = setup(monkeypatch, tmp_path)
258
+ active_plan(state)
259
+ monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=lambda *_a, **_k: (.08, 0.)))
260
+ state.plan.update(recovery_pending=True, recovery_deadline=time.monotonic() + 12.)
261
+ fresh = threading.Timer(.075, lambda: state.plan.update(recovery_pending=False))
262
+ end = threading.Timer(.20, lambda: state.finish('End recovery simulation'))
263
+ fresh.start()
264
+ end.start()
265
+ module.control_loop(state)
266
+ fresh.join()
267
+ end.join()
268
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
269
+ assert commands[0]['v'] == commands[0]['w'] == 0.
270
+ assert any(c['v'] > 0 for c in commands)
271
+
272
+
273
+ def test_brief_robot_status_gap_holds_zero_until_fresh_status_returns(monkeypatch, tmp_path):
274
+ module, state, context = setup(monkeypatch, tmp_path)
275
+ active_plan(state)
276
+ state.robot_received = time.monotonic() - .6
277
+ monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=lambda *_a, **_k: (.08, 0.)))
278
+ def refresh():
279
+ state.robot_received = time.monotonic()
280
+ state.plan['input_received'] = time.monotonic()
281
+ fresh = threading.Timer(.075, refresh)
282
+ end = threading.Timer(.20, lambda: state.finish('End status gap simulation'))
283
+ fresh.start()
284
+ end.start()
285
+ module.control_loop(state)
286
+ fresh.join()
287
+ end.join()
288
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
289
+ assert commands[0]['v'] == commands[0]['w'] == 0.
290
+ assert any(c['v'] > 0 for c in commands)
291
+
292
+
293
+ def test_sustained_robot_status_gap_stops_without_executing_a_path(monkeypatch, tmp_path):
294
+ module, state, context = setup(monkeypatch, tmp_path)
295
+ active_plan(state)
296
+ state.args.plan_hold_seconds = .08
297
+ state.robot_received = time.monotonic() - .6
298
+ module.control_loop(state)
299
+ assert state.phase == 'stopped' and 'robot status stale' in state.reason
300
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
301
+ assert commands and all(c['v'] == c['w'] == 0. for c in commands)
302
+
303
+
304
+ def test_pose_correction_racing_control_snapshot_cannot_execute_old_route(monkeypatch, tmp_path):
305
+ module, state, context = setup(monkeypatch, tmp_path)
306
+ active_plan(state)
307
+ def corrected(*_a, **_k):
308
+ state.plan_epoch += 1
309
+ return .1, 0.
310
+ monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=corrected))
311
+ end = threading.Timer(.12, lambda: state.finish('End correction race'))
312
+ end.start()
313
+ module.control_loop(state)
314
+ end.join()
315
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
316
+ assert commands and all(c['v'] == c['w'] == 0. for c in commands)
317
+
318
+
319
+ def test_corner_observation_sends_head_target_with_zero_base_translation(monkeypatch, tmp_path):
320
+ module, state, context = setup(monkeypatch, tmp_path)
321
+ active_plan(state)
322
+ state.plan.update(observation_hold=True, head_target=[-1.2, -.4], scan_w=0., corner_phase='look')
323
+ end = threading.Timer(.12, lambda: state.finish('End head scan simulation'))
324
+ end.start()
325
+ module.control_loop(state)
326
+ end.join()
327
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
328
+ assert commands and all(c['v'] == c['w'] == 0. and c['head_target'] == [-1.2, -.4] for c in commands)
329
+
330
+
331
+ def test_native_scan_is_rotation_only_even_if_pursuit_requests_translation(monkeypatch, tmp_path):
332
+ module, state, context = setup(monkeypatch, tmp_path)
333
+ active_plan(state)
334
+ state.plan.update(planner_status=2, scan_authorized=True)
335
+ monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=lambda *_a, **_k: (.08, .1)))
336
+ end = threading.Timer(.12, lambda: state.finish('End native scan simulation'))
337
+ end.start()
338
+ module.control_loop(state)
339
+ end.join()
340
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
341
+ assert commands and all(c['v'] == 0. and c['w'] == .1 for c in commands)
342
+
343
+
344
+ def test_learned_veto_does_not_block_stationary_yaw_pitch_survey(monkeypatch, tmp_path):
345
+ module, state, context = setup(monkeypatch, tmp_path)
346
+ active_plan(state)
347
+ monkeypatch.setattr(module, 'command_footprint_report', lambda *_a, **_k: {
348
+ 'clear': False, 'reason': 'learned occupancy', 'cells': [], 'blocking_cell_count': 1})
349
+ state.plan.update(observation_hold=True, stationary_survey=True, head_target=[-.7, -1.05],
350
+ scan_w=0., corner_phase='survey', survey_label='right floor',
351
+ footprint_grid={'prob': np.ones((20, 20)), 'obs': np.ones((20, 20)), 'res': .05},
352
+ planning_base=np.eye(4))
353
+ end = threading.Timer(.12, lambda: state.finish('End yaw/pitch simulation'))
354
+ end.start()
355
+ module.control_loop(state)
356
+ end.join()
357
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
358
+ assert commands and all(c['v'] == c['w'] == 0. and c['head_target'] == [-.7, -1.05] for c in commands)
359
+ assert state.last_control['learned_blocked']
360
+ assert state.last_control['reason'] == 'Head survey: right floor'
361
+
362
+
363
+ def test_survey_transition_with_null_label_holds_then_accepts_fresh_head_target(monkeypatch, tmp_path):
364
+ module, state, context = setup(monkeypatch, tmp_path)
365
+ active_plan(state)
366
+ # Mapping invalidates the driving plan before publishing its first survey
367
+ # view. The old plan contains an explicit null label and no head target.
368
+ state.plan.update(observation_hold=True, stationary_survey=True, head_target=None,
369
+ scan_w=0., survey_label=None)
370
+ ticks = [0]
371
+
372
+ def tick(_seconds):
373
+ ticks[0] += 1
374
+ if ticks[0] == 1:
375
+ state.plan = {**state.plan, 'survey_label': 'front floor', 'head_target': [-.05, -1.05]}
376
+ if ticks[0] >= 3:
377
+ state.done.set()
378
+ return state.done.is_set()
379
+
380
+ monkeypatch.setattr(state.done, 'wait', tick)
381
+ module.control_loop(state)
382
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
383
+ assert ticks[0] == 3 and state.phase == 'active'
384
+ assert commands and all(c['v'] == c['w'] == 0. for c in commands)
385
+ assert 'head_target' not in commands[0]
386
+ assert commands[-1]['head_target'] == [-.05, -1.05]
387
+ assert state.last_control['reason'] == 'Head survey: front floor'
388
+
389
+
390
+ def test_persistent_learned_veto_requests_observation_without_executing_path(monkeypatch, tmp_path):
391
+ module, state, context = setup(monkeypatch, tmp_path)
392
+ active_plan(state)
393
+ monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=lambda *_a, **_k: (.08, 0.)))
394
+ clock = [time.monotonic()]
395
+ monkeypatch.setattr(module.time, 'monotonic', lambda: clock[0])
396
+ state.plan.update(footprint_grid={'prob': np.ones((20, 20)), 'obs': np.ones((20, 20)), 'res': .05},
397
+ planning_base=np.eye(4))
398
+ ticks = [0]
399
+ def tick(_seconds):
400
+ ticks[0] += 1
401
+ clock[0] += .1
402
+ state.heartbeat = state.robot_received = state.plan['input_received'] = clock[0]
403
+ if ticks[0] >= 15:
404
+ state.done.set()
405
+ return state.done.is_set()
406
+ monkeypatch.setattr(state.done, 'wait', tick)
407
+ module.control_loop(state)
408
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
409
+ assert commands and all(c['v'] == c['w'] == 0. for c in commands)
410
+ assert state.observation_requested and state.observation_reason == 'learned footprint'
411
+ assert state.last_control['footprint']['blocking_cell_count'] > 0
412
+
413
+
414
+ def fresh_head_plan(state):
415
+ active_plan(state)
416
+ now = time.monotonic()
417
+ state.robot.update(frame_id=100, sensor_age=.08, tf_age=.02, joint_positions=np.zeros(11))
418
+ state.plan.update(input_received=now - 4., frame_id=1, observation_hold=True, stationary_survey=True,
419
+ head_target=[.5, -1.05], scan_w=0., survey_label='left floor',
420
+ head_anchor=np.eye(4), head_deadline=now + 20.)
421
+
422
+
423
+ def test_stationary_head_renews_with_new_source_frames_without_vggt_updates(monkeypatch, tmp_path):
424
+ module, state, context = setup(monkeypatch, tmp_path)
425
+ fresh_head_plan(state)
426
+ ticks = [0]
427
+
428
+ def tick(_seconds):
429
+ ticks[0] += 1
430
+ state.robot_received = state.heartbeat = time.monotonic()
431
+ state.robot['frame_id'] += 1
432
+ if ticks[0] == 4:
433
+ state.done.set()
434
+ return state.done.is_set()
435
+
436
+ monkeypatch.setattr(state.done, 'wait', tick)
437
+ module.control_loop(state)
438
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
439
+ assert [c['frame_id'] for c in commands] == [100, 101, 102, 103]
440
+ assert all(c['v'] == c['w'] == 0. and c['head_target'] == [.5, -1.05] for c in commands)
441
+ assert state.motion_commands == 0
442
+ assert state.last_control['head_control_source'] == 'fresh_robot_feedback'
443
+
444
+
445
+ def test_head_observation_deadline_never_renews_with_fresh_status(monkeypatch, tmp_path):
446
+ module, state, context = setup(monkeypatch, tmp_path)
447
+ fresh_head_plan(state)
448
+ deadline = state.plan['head_deadline']
449
+ clock = [time.monotonic()]
450
+ monkeypatch.setattr(module.time, 'monotonic', lambda: clock[0])
451
+ ticks = [0]
452
+
453
+ def tick(_seconds):
454
+ ticks[0] += 1
455
+ clock[0] = deadline + .01
456
+ state.robot_received = state.heartbeat = clock[0]
457
+ return False
458
+
459
+ monkeypatch.setattr(state.done, 'wait', tick)
460
+ module.control_loop(state)
461
+ assert state.phase == 'stopped' and 'head observation deadline expired' in state.reason
462
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
463
+ assert len(commands) == 1 and commands[0]['v'] == commands[0]['w'] == 0.
464
+ assert state.plan['head_deadline'] == deadline
465
+
466
+
467
+ def test_head_renewal_cannot_resume_driving_until_a_fresh_plan_arrives(monkeypatch, tmp_path):
468
+ module, state, context = setup(monkeypatch, tmp_path)
469
+ fresh_head_plan(state)
470
+ monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot',
471
+ SimpleNamespace(pure_pursuit=lambda *_a, **_k: (.08, 0.)))
472
+ ticks = [0]
473
+
474
+ def tick(_seconds):
475
+ ticks[0] += 1
476
+ state.robot_received = state.heartbeat = time.monotonic()
477
+ if ticks[0] == 1:
478
+ state.plan.update(observation_hold=False, head_target=None)
479
+ elif ticks[0] == 2:
480
+ state.plan.update(input_received=time.monotonic(), frame_id=100)
481
+ elif ticks[0] == 3:
482
+ state.done.set()
483
+ return state.done.is_set()
484
+
485
+ monkeypatch.setattr(state.done, 'wait', tick)
486
+ module.control_loop(state)
487
+ commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
488
+ assert [c['v'] for c in commands] == [0., 0., .08]
489
+ assert commands[0]['head_target'] == [.5, -1.05]
490
+ assert 'head_target' not in commands[1] and 'head_target' not in commands[2]
491
+
492
+
493
+ @pytest.mark.parametrize('fault', ['stop', 'runstop', 'camera', 'status', 'base', 'correction'])
494
+ def test_head_renewal_cancels_on_stop_lost_feedback_motion_or_correction(monkeypatch, tmp_path, fault):
495
+ module, state, context = setup(monkeypatch, tmp_path)
496
+ fresh_head_plan(state)
497
+ ticks = [0]
498
+
499
+ def tick(_seconds):
500
+ ticks[0] += 1
501
+ if ticks[0] == 1:
502
+ if fault == 'stop':
503
+ state.finish('Stopped by operator')
504
+ elif fault == 'runstop':
505
+ state.robot['is_runstopped'] = True
506
+ elif fault == 'camera':
507
+ state.robot['sensor_age'] = 1.
508
+ elif fault == 'status':
509
+ state.robot_received = time.monotonic() - 1.
510
+ elif fault == 'base':
511
+ state.robot['base_pose'] = [.06, 0., 0.]
512
+ elif fault == 'correction':
513
+ state.plan_epoch += 1
514
+ state.plan = {'input_received': time.monotonic(), 'goal_distance': 0., 'localized': True,
515
+ 'localized_streak': 3, 'recovery_pending': True,
516
+ 'recovery_deadline': time.monotonic() + 12.}
517
+ if ticks[0] >= 3:
518
+ state.done.set()
519
+ return state.done.is_set()
520
+
521
+ monkeypatch.setattr(state.done, 'wait', tick)
522
+ module.control_loop(state)
523
+ commands = [c for socket in context.sockets for c in socket.sent]
524
+ velocity = [c for c in commands if c['type'] == 'velocity']
525
+ assert velocity[0]['head_target'] == [.5, -1.05]
526
+ assert all('head_target' not in c for c in velocity[1:])
527
+ assert all(c['v'] == c['w'] == 0. for c in velocity)
528
+ assert all(c['type'] == 'stop' for c in commands[-3:])
cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_learned.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from web_console.stretch_nav_learned import reproject_bev
5
+
6
+
7
+ def camera_pose(yaw=0., x=0., y=0.):
8
+ c, s = np.cos(yaw), np.sin(yaw)
9
+ world_yaw = np.array([[c, -s, 0.], [s, c, 0.], [0., 0., 1.]])
10
+ pose = np.eye(4)
11
+ # Level optical camera looks along base +X, optical right is base -Y.
12
+ pose[:3, :3] = world_yaw @ np.array([[0., 0., 1.], [-1., 0., 0.], [0., -1., 0.]])
13
+ pose[:3, 3] = [x, y, .7]
14
+ return pose
15
+
16
+
17
+ R_BEV_CAMERA = np.array([[1., 0., 0.], [0., 0., 1.], [0., -1., 0.]])
18
+
19
+
20
+ def test_camera_offset_moves_obstacle_into_base_grid():
21
+ prob = np.zeros((64, 64), np.float32)
22
+ prob[30, 31] = .83
23
+ result = reproject_bev(prob, np.ones_like(prob), prob / 2,
24
+ R_BEV_CAMERA, camera_pose(x=.2, y=.1), np.eye(4), .1)
25
+ assert result['prob'][28, 30] == pytest.approx(.83)
26
+ assert result['err'][28, 30] == pytest.approx(.415)
27
+ assert result['obs'][-1, -1] == 0.
28
+ assert result['prob'][-1, -1] == .5
29
+ assert result['err'][-1, -1] == 1.
30
+
31
+
32
+ def test_camera_pan_rotates_grid_into_base_heading():
33
+ prob = np.zeros((64, 64), np.float32)
34
+ prob[26, 31] = .72
35
+ result = reproject_bev(prob, np.ones_like(prob), np.zeros_like(prob),
36
+ R_BEV_CAMERA, camera_pose(yaw=np.pi / 2), np.eye(4), .1)
37
+ assert result['prob'][32, 26] == pytest.approx(.72)
38
+
39
+
40
+ def test_base_and_camera_rotated_together_preserve_grid():
41
+ rng = np.random.default_rng(123)
42
+ prob = rng.random((64, 64), dtype=np.float32)
43
+ base = np.eye(4)
44
+ base[:2, :2] = [[0., -1.], [1., 0.]]
45
+ result = reproject_bev(prob, np.ones_like(prob), np.zeros_like(prob),
46
+ R_BEV_CAMERA, camera_pose(yaw=np.pi / 2), base, .1)
47
+ np.testing.assert_allclose(result['prob'], prob)
48
+
49
+
50
+ def test_invalid_learned_transform_rejected():
51
+ p = np.zeros((8, 8))
52
+ bad = np.eye(4)
53
+ bad[0, 0] = np.nan
54
+ with pytest.raises(ValueError):
55
+ reproject_bev(p, p, p, R_BEV_CAMERA, bad, np.eye(4), .1)
cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_recovery.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Synthetic camera motion, map corrections and occluded corners; no hardware."""
2
+
3
+ from types import SimpleNamespace
4
+
5
+ import numpy as np
6
+ import pytest
7
+
8
+ from web_console.stretch_nav_control import alignment_correction
9
+ from web_console.stretch_nav_recovery import (
10
+ CornerObserver,
11
+ CorrectionRecovery,
12
+ MeasuredObstacleMemory,
13
+ camera_in_base,
14
+ clear_goal_cache,
15
+ rectangle_command_clear,
16
+ rectangle_path_clear,
17
+ route_subgoal,
18
+ )
19
+
20
+
21
+ def transform(yaw=0.0, xy=(0.0, 0.0)):
22
+ c, s = np.cos(yaw), np.sin(yaw)
23
+ t = np.eye(4)
24
+ t[:2, :2] = [[c, -s], [s, c]]
25
+ t[:2, 3] = xy
26
+ return t
27
+
28
+
29
+ def mount(yaw=0.0):
30
+ # Both orientation and camera centre move about the head joint.
31
+ camera = np.eye(4)
32
+ camera[:3, :3] = [[0, 0, 1], [-1, 0, 0], [0, -1, 0]]
33
+ camera[:3, 3] = [0.1, 0.0, 0.7]
34
+ return transform(yaw) @ camera
35
+
36
+
37
+ def grid():
38
+ return {"prob": np.zeros((200, 200)), "obs": np.ones((200, 200)), "res": 0.05}
39
+
40
+
41
+ def test_dynamic_head_extrinsic_does_not_create_a_map_correction():
42
+ base = transform(0.4, (10.0, 7.0))
43
+ alignment = transform(0.2, (3.0, -2.0))
44
+ neutral = mount()
45
+ attached = []
46
+ for pan in [0.0, -0.5, -1.3, 0.4]:
47
+ camera = base @ mount(pan)
48
+ cross_camera = alignment @ camera
49
+ recovered = cross_camera @ np.linalg.inv(camera)
50
+ np.testing.assert_allclose(camera_in_base(camera, base), mount(pan), atol=1e-12)
51
+ distance, angle = alignment_correction(alignment, recovered, base)
52
+ assert distance < 1e-10 and angle < 1e-7
53
+ attached.append(recovered @ base @ neutral)
54
+ np.testing.assert_allclose(attached, np.tile(attached[0], (4, 1, 1)), atol=1e-12)
55
+ # A fixed extrinsic would falsely interpret the same pan as robot motion.
56
+ wrong = (alignment @ base @ mount(-1.3)) @ np.linalg.inv(base @ neutral)
57
+ assert alignment_correction(alignment, wrong, base)[1] > 1.0
58
+
59
+
60
+ def test_large_correction_holds_and_automatically_recovers_after_fresh_samples():
61
+ recovery = CorrectionRecovery()
62
+ corrected = transform(0.04, (1.05, 0.0))
63
+ result = recovery.update(np.eye(4), corrected, np.eye(4), 10.0)
64
+ assert result["started"] and result["pending"]
65
+ for now in [10.3, 10.6]:
66
+ assert recovery.update(corrected, corrected, np.eye(4), now)["pending"]
67
+ assert not recovery.update(corrected, corrected, np.eye(4), 10.9)["pending"]
68
+
69
+
70
+ def test_repeated_position_flips_do_not_extend_recovery_indefinitely():
71
+ recovery = CorrectionRecovery()
72
+ a, b = np.eye(4), transform(xy=(1.0, 0.0))
73
+ recovery.update(a, b, a, 0.0)
74
+ for t in range(1, 13):
75
+ recovery.update(b if t % 2 else a, a if t % 2 else b, a, float(t))
76
+ with pytest.raises(RuntimeError, match="did not settle"):
77
+ recovery.update(a, b, a, 12.1)
78
+
79
+
80
+ def test_goal_cache_reset_preserves_obstacle_memory_and_scale():
81
+ world, bumps = object(), [np.array([1.0, 2.0])]
82
+ episode = SimpleNamespace(
83
+ world=world, bumps=bumps, log_scale=0.6, route=np.ones((3, 2)), route_age=3, no_route=4, side=-1.0, expect=0.1
84
+ )
85
+ clear_goal_cache(episode)
86
+ assert episode.route is None and episode.expect == 0
87
+ assert episode.world is world and episode.bumps is bumps and episode.log_scale == 0.6
88
+
89
+
90
+ def test_right_corner_subgoal_stays_before_the_bend():
91
+ hint = route_subgoal([[0.25, 0.0], [0.6, 0.0], [1.0, 0.0], [1.0, -0.5], [1.0, -1.5]], np.eye(4), [1.0, -1.5])
92
+ assert hint["corner"] is not None
93
+ assert hint["target"][0] < hint["corner"][0]
94
+ assert hint["target"][1] == pytest.approx(0.0)
95
+ assert hint["outgoing"][1] < 0
96
+
97
+
98
+ def test_straight_route_uses_arc_length_not_a_distant_overlapping_node():
99
+ hint = route_subgoal([[0.5, 0.0], [1.0, 0.0], [2.0, 0.0]], np.eye(4), [2.0, 0.0])
100
+ assert hint["corner"] is None
101
+ np.testing.assert_allclose(hint["target"], [1.5, 0.0])
102
+
103
+
104
+ def test_sideways_graph_attachment_is_not_mistaken_for_an_aisle_bend():
105
+ # Independent synthetic trail resembling an off-centre mapping camera.
106
+ route = [[0.16, -0.48], [0.47, -0.66], [0.54, -0.78], [0.58, -0.91], [0.58, -1.04], [0.53, -1.48], [0.53, -2.0]]
107
+ hint = route_subgoal(route, np.eye(4), route[-1])
108
+ assert hint["corner"] is not None and hint["corner"][1] < -0.7
109
+ assert hint["outgoing"][1] < -0.9
110
+ assert 0.0 < hint["target"][0] < 0.4 and hint["target"][1] == pytest.approx(0.0)
111
+
112
+
113
+ def test_depth_memory_survives_a_camera_pan_and_expires_in_odom():
114
+ memory = MeasuredObstacleMemory(horizon=12.0)
115
+ obstacle = np.array([[0.3, 0.0], [0.3, 0.01], [0.3, -0.01]])
116
+ memory.update(obstacle, 0.0, [0.0, 0.0])
117
+ retained = memory.update(np.empty((0, 2)), 5.0, [0.0, 0.0])
118
+ assert len(retained) >= 3 # Preserve enough returns for the hard veto.
119
+ assert len(memory.update(np.empty((0, 2)), 12.1, [0.0, 0.0])) == 0
120
+
121
+
122
+ def test_look_and_return_require_settled_images_before_advance():
123
+ observer = CornerObserver()
124
+ joint = np.zeros(11)
125
+ joint[10] = -0.4
126
+ hint = {"target": np.zeros(2), "corner": np.array([0.3, 0.0]), "outgoing": np.array([0.0, -1.0])}
127
+ result = observer.update(hint, np.eye(4), mount(), mount(), joint, grid(), 0.0)
128
+ assert result["hold"] and result["phase"] == "look" and result["head_target"][0] < -1.0
129
+ for i, pan in enumerate([-0.5, -1.0, -np.pi / 2, -np.pi / 2, -np.pi / 2]):
130
+ joint[9] = pan
131
+ result = observer.update(hint, np.eye(4), mount(pan), mount(), joint, grid(), i + 1.0)
132
+ assert result["hold"]
133
+ assert observer.phase == "return"
134
+ assert result["coverage"] == 1.0
135
+ for i in range(3):
136
+ joint[9] = 0.0
137
+ result = observer.update(hint, np.eye(4), mount(), mount(), joint, grid(), 6.0 + i)
138
+ assert observer.phase == "advance"
139
+ result = observer.update(hint, np.eye(4), mount(), mount(), joint, grid(), 9.0)
140
+ assert not result["hold"] and result["speed_scale"] == 0.5
141
+
142
+
143
+ def test_scan_waits_for_head_limit_before_requesting_base_rotation():
144
+ observer = CornerObserver()
145
+ joint = np.zeros(11)
146
+ joint[10] = -0.4
147
+ hint = {"target": np.zeros(2), "corner": np.array([0.3, 0.0]), "outgoing": np.array([0.0, 1.0])}
148
+ result = observer.update(hint, np.eye(4), mount(), mount(), joint, grid(), 0.0)
149
+ assert result["head_target"][0] == 0.65 and result["scan_w"] == 0.0
150
+ joint[9] = 0.65
151
+ result = observer.update(hint, np.eye(4), mount(0.65), mount(), joint, grid(), 1.0)
152
+ assert result["scan_w"] == 0.15 and result["hold"]
153
+
154
+
155
+ def test_recovery_interrupted_pan_returns_to_neutral_before_translation():
156
+ observer = CornerObserver()
157
+ observer.restore_neutral(np.eye(4), 10.0)
158
+ joint = np.zeros(11)
159
+ joint[9:11] = [-1.2, -0.4]
160
+ hint = {"target": np.array([1.0, 0.0]), "corner": None}
161
+ result = observer.update(hint, np.eye(4), mount(-1.2), mount(), joint, grid(), 10.5)
162
+ assert result["hold"] and result["phase"] == "return"
163
+ assert result["head_target"][0] == pytest.approx(0.0)
164
+
165
+
166
+ def test_blocked_approach_can_observe_before_reaching_the_waypoint():
167
+ observer = CornerObserver()
168
+ joint = np.zeros(11)
169
+ joint[10] = -0.4
170
+ hint = {"target": np.array([0.6, 0.0]), "corner": np.array([0.9, 0.0]), "outgoing": np.array([0.0, -1.0])}
171
+ result = observer.update(hint, np.eye(4), mount(), mount(), joint, grid(), 0.0)
172
+ assert result["phase"] == "approach" and not result["hold"]
173
+ result = observer.update(hint, np.eye(4), mount(), mount(), joint, grid(), 2.0, force_observation=True)
174
+ assert result["phase"] == "look" and result["hold"]
175
+
176
+
177
+ def test_unseen_branch_never_becomes_approved_after_a_head_scan():
178
+ observer = CornerObserver()
179
+ joint = np.zeros(11)
180
+ joint[10] = -0.4
181
+ hint = {"target": np.zeros(2), "corner": np.array([0.1, 0.0]), "outgoing": np.array([0.0, -1.0])}
182
+ unseen = grid()
183
+ unseen["obs"][:] = 0.0
184
+ observer.update(hint, np.eye(4), mount(), mount(), joint, unseen, 0.0)
185
+ for i in range(3):
186
+ joint[9] = -np.pi / 2
187
+ observer.update(hint, np.eye(4), mount(-np.pi / 2), mount(), joint, unseen, i + 1.0)
188
+ for i in range(2):
189
+ joint[9] = 0.0
190
+ observer.update(hint, np.eye(4), mount(), mount(), joint, unseen, i + 4.0)
191
+ with pytest.raises(RuntimeError, match="remains occluded"):
192
+ observer.update(hint, np.eye(4), mount(), mount(), joint, unseen, 6.0)
193
+
194
+
195
+ def test_rectangle_rejects_obstacle_that_a_20cm_circle_would_miss():
196
+ g = grid()
197
+ # Centreline x=.5, return at x=.5,y=.225 clips the 46 cm body.
198
+ g["prob"][int(100 - 0.5 / 0.05), int(100 - 0.225 / 0.05)] = 1.0
199
+ assert not rectangle_path_clear([[0.5, 0.0], [1.0, 0.0]], g)
200
+ assert rectangle_path_clear([[0.5, 0.0], [1.0, 0.0]], grid())
201
+
202
+
203
+ def test_pure_rotation_checks_sweeping_corners_of_the_body():
204
+ g = grid()
205
+ # Outside the stationary body, within its corners' swept circle.
206
+ g["prob"][int(100 - 0.30 / 0.05), 100] = 1.0
207
+ assert rectangle_command_clear(g, np.eye(4), np.zeros(3), 0.0, 0.0)
208
+ assert not rectangle_command_clear(g, np.eye(4), np.zeros(3), 0.0, 0.7)
209
+
210
+
211
+ def test_command_footprint_uses_planning_frame_after_base_motion():
212
+ g = grid()
213
+ g["prob"][int(100 - 0.5 / 0.05), 100] = 1.0
214
+ base = transform(np.pi / 2, (4.0, 2.0))
215
+ assert rectangle_command_clear(g, base, [4.0, 2.0, np.pi / 2], 0.1, 0.0)
216
+ assert not rectangle_command_clear(g, base, [4.0, 2.25, np.pi / 2], 0.1, 0.0)
217
+
218
+
219
+ @pytest.mark.parametrize("bad", [np.eye(3), np.full((4, 4), np.nan), np.diag([2.0, 1.0, 1.0, 1.0])])
220
+ def test_invalid_dynamic_extrinsic_rejected(bad):
221
+ with pytest.raises(ValueError):
222
+ camera_in_base(bad, np.eye(4))
cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_replay.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Historical frames, asset confinement and HTTP replay use synthetic recordings."""
2
+
3
+ import http.client
4
+ import json
5
+ import threading
6
+ from http.server import ThreadingHTTPServer
7
+
8
+ import cv2
9
+ import numpy as np
10
+ import pytest
11
+
12
+ from scripts.view_stretch_cross_nav_live_run import Handler, Review
13
+ from web_console.stretch_nav_replay import LAYERS, ReplayArchive, ReplayService, read_rows, save_bev_frame
14
+
15
+
16
+ def jsonl(path, rows):
17
+ path.parent.mkdir(parents=True, exist_ok=True)
18
+ path.write_text("".join(json.dumps(row) + "\n" for row in rows))
19
+
20
+
21
+ @pytest.fixture
22
+ def recording(tmp_path):
23
+ root = tmp_path / "stretch_cross_nav_live_synthetic"
24
+ (root / "capture/rgb").mkdir(parents=True)
25
+ (root / "review_bev").mkdir()
26
+ status = {"phase": "stopped", "reason": "Goal reached", "goal_keyframe": 7, "frame": {"frame_idx": 30}}
27
+ for name in ("review.json", "final_status.json"):
28
+ (root / name).write_text(json.dumps(status))
29
+ (root / "map.json").write_text(json.dumps({"nodes": [], "goal": 7}))
30
+ raw = [{"frame_idx": number, "relative_time_s": time, "received_unix_s": 100 + time,
31
+ "sensor_stamp": 900 + time, "head_joints": [time / 10, -0.4]}
32
+ for number, time in [(10, 0.0), (20, 2.0), (30, 5.0)]]
33
+ jsonl(root / "capture/observations.jsonl", raw)
34
+ (root / "capture/latest.json").write_text(json.dumps(raw[-1]))
35
+ for row in raw:
36
+ cv2.imwrite(str(root / f"capture/rgb/{row['frame_idx']:08d}.jpg"),
37
+ np.full((24, 32, 3), row["frame_idx"], np.uint8))
38
+ plans = [{"frame_idx": number, "time_s": time, "localized": True, "bev_size": 16, "bev_res": 0.05,
39
+ "trajectory": [[1, 0, 0]] if number == 20 else [[1, 0, 0], [2, 0, 0]],
40
+ "global_route": [], "local_path_display": [], "goal_distance": 1.0}
41
+ for number, time in [(20, 2), (30, 5)]]
42
+ jsonl(root / "observations.jsonl", plans)
43
+ jsonl(root / "commands.jsonl", [
44
+ {"time_unix": 100, "phase": "teleop", "reason": "Teleop"},
45
+ {"time_unix": 101, "phase": "active", "reason": "Following path", "nonzero_motion_commands": 4},
46
+ {"time_unix": 105.5, "phase": "stopped", "reason": "Goal reached"},
47
+ ])
48
+ jsonl(root / "robot_status.jsonl", [
49
+ {"received_unix": 100, "head_action_state": "idle", "joint_positions": [0.0] * 11},
50
+ {"received_unix": 104, "head_action_state": "moving", "joint_positions": [9.0] * 11},
51
+ {"received_unix": 106, "head_action_state": "future", "joint_positions": [99.0] * 11},
52
+ ])
53
+ jsonl(root / "events.jsonl", [
54
+ {"time_unix": 101, "type": "start_requested"},
55
+ {"time_unix": 105.5, "type": "stop", "reason": "Goal reached"},
56
+ {"time_unix": 200, "type": "stop", "reason": "Later review shutdown"},
57
+ ])
58
+ for frame in (20, 30):
59
+ images = {f"{layer}.png": cv2.imencode(".png", np.full((16, 16, 3), frame, np.uint8))[1].tobytes()
60
+ for layer in LAYERS}
61
+ save_bev_frame(root, frame, images, source="recorded" if frame == 30 else "reconstructed")
62
+ if frame == 30:
63
+ for name, data in images.items():
64
+ (root / "review_bev" / name).write_bytes(data)
65
+ return root
66
+
67
+
68
+ def test_timeline_uses_recorded_time_and_preserves_bev_provenance(recording):
69
+ manifest = ReplayArchive(recording).manifest()
70
+ assert [row["time_s"] for row in manifest["frames"]] == [0, 2, 5]
71
+ assert manifest["recorded_bev_frames"] == manifest["reconstructed_bev_frames"] == 1
72
+ assert manifest["start_index"] == 0
73
+ assert len(manifest["events"]) == 2 # Later server shutdown is not part of the run.
74
+
75
+
76
+ def test_prefirst_frame_does_not_leak_future_map_bev_control_or_pose(recording):
77
+ frame = ReplayArchive(recording).frame(0)
78
+ assert frame["frame"]["trajectory"] == []
79
+ assert frame["replay"]["bev_urls"] == {} and frame["replay"]["bev_frame"] is None
80
+ assert frame["recorded_phase"] == "teleop"
81
+ assert frame["robot"]["head_action_state"] == "idle"
82
+ assert frame["processed"] == 0
83
+
84
+
85
+ def test_historical_map_and_image_time_head_pose_are_selected_without_future_state(recording):
86
+ archive = ReplayArchive(recording)
87
+ early, later = archive.frame(1), archive.frame(2)
88
+ assert len(early["frame"]["trajectory"]) == 1 and len(later["frame"]["trajectory"]) == 2
89
+ assert early["replay"]["bev_frame"] == 20 and early["replay"]["bev_source"] == "reconstructed"
90
+ assert early["robot"]["joint_positions"][9:11] == [0.2, -0.4]
91
+ assert later["robot"]["head_action_state"] == "moving"
92
+ assert later["recorded_phase"] == "active" and later["phase"] == "stopped"
93
+ assert not later["ready"] and later["gate"] == "Replay; motion controls disabled"
94
+ assert early["motion_commands"] == 4 # PC receive time, not the offset sensor clock.
95
+
96
+
97
+ def test_sparse_legacy_bev_is_not_shown_before_its_saved_frame(recording):
98
+ import shutil
99
+ shutil.rmtree(recording / "replay")
100
+ archive = ReplayArchive(recording)
101
+ assert archive.frame(1)["replay"]["bev_frame"] is None
102
+ assert archive.frame(2)["replay"]["bev_frame"] == 30
103
+
104
+
105
+ def test_rgb_and_bev_assets_remain_confined_to_their_recording(recording, tmp_path):
106
+ archive = ReplayArchive(recording)
107
+ outside = tmp_path / "private.jpg"
108
+ outside.write_bytes(b"private")
109
+ image = recording / "capture/rgb/00000020.jpg"
110
+ image.unlink()
111
+ image.symlink_to(outside)
112
+ with pytest.raises(ValueError, match="escaped"):
113
+ archive.image(20)
114
+ with pytest.raises(KeyError):
115
+ archive.image(999)
116
+ with pytest.raises(KeyError):
117
+ archive.image(20, "../../private")
118
+ with pytest.raises(KeyError):
119
+ archive.frame(-1)
120
+
121
+
122
+ def test_bev_symlink_escape_is_rejected_when_loading_archive(recording, tmp_path):
123
+ outside = tmp_path / "private.png"
124
+ outside.write_bytes(b"private")
125
+ image = recording / "replay/bev/00000020/occupancy.png"
126
+ image.unlink()
127
+ image.symlink_to(outside)
128
+ with pytest.raises(ValueError, match="escaped"):
129
+ ReplayArchive(recording)
130
+
131
+
132
+ def test_backfill_does_not_overwrite_original_recorded_images(recording):
133
+ original = (recording / "replay/bev/00000030/occupancy.png").read_bytes()
134
+ save_bev_frame(recording, 30, {f"{name}.png": b"replacement" for name in LAYERS},
135
+ source="reconstructed", only_missing=True)
136
+ assert (recording / "replay/bev/00000030/occupancy.png").read_bytes() == original
137
+ assert ReplayArchive(recording).frame(2)["replay"]["bev_source"] == "recorded"
138
+
139
+
140
+ def test_partial_bev_without_commit_metadata_is_ignored(recording):
141
+ (recording / "replay/bev/00000020/meta.json").unlink()
142
+ assert ReplayArchive(recording).frame(1)["replay"]["bev_frame"] is None
143
+
144
+
145
+ def test_committed_backfill_invalidates_a_cached_manifest(recording):
146
+ service = ReplayService(recording)
147
+ assert service.get().manifest()["bev_frames"] == 2
148
+ images = {f"{layer}.png": (recording / "review_bev" / f"{layer}.png").read_bytes() for layer in LAYERS}
149
+ save_bev_frame(recording, 10, images)
150
+ assert service.get().manifest()["bev_frames"] == 3
151
+ assert service.get().frame(0)["replay"]["bev_frame"] == 10
152
+
153
+
154
+ def test_failed_bev_write_never_commits_a_complete_frame(recording, monkeypatch):
155
+ from pathlib import Path
156
+ original = Path.write_bytes
157
+ def fail_on_visibility(path, data):
158
+ if path.name == "visibility.png.tmp":
159
+ raise OSError("Synthetic disk failure")
160
+ return original(path, data)
161
+ monkeypatch.setattr(Path, "write_bytes", fail_on_visibility)
162
+ with pytest.raises(OSError, match="Synthetic"):
163
+ save_bev_frame(recording, 10, {f"{layer}.png": b"image" for layer in LAYERS})
164
+ assert not (recording / "replay/bev/00000010/meta.json").exists()
165
+ assert ReplayArchive(recording).frame(0)["replay"]["bev_frame"] is None
166
+
167
+
168
+ def test_incomplete_final_jsonl_row_is_tolerated_but_corruption_is_not(tmp_path):
169
+ path = tmp_path / "rows.jsonl"
170
+ path.write_text('{"frame":1}\n{"frame":')
171
+ assert read_rows(path) == [{"frame": 1}]
172
+ path.write_text('{"frame":\n{"frame":2}\n')
173
+ with pytest.raises(json.JSONDecodeError):
174
+ read_rows(path)
175
+
176
+
177
+ def test_run_selection_is_allowlisted_and_excludes_escaped_or_unfinished_runs(recording, tmp_path):
178
+ service = ReplayService(recording)
179
+ assert service.listing()[0]["id"] == recording.name
180
+ with pytest.raises(KeyError):
181
+ service.get("../private")
182
+ outside = tmp_path / "outside"
183
+ outside.mkdir()
184
+ (tmp_path / "stretch_cross_nav_live_escape").symlink_to(outside.parent)
185
+ assert len(service.listing()) == 1
186
+ (recording / "final_status.json").write_text('{"phase":"active"}')
187
+ assert service.listing() == []
188
+ with pytest.raises(ValueError, match="stopped"):
189
+ ReplayArchive(recording)
190
+
191
+
192
+ def test_saved_server_serves_replay_and_cannot_arm_motion(recording):
193
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
194
+ server.daemon_threads = True
195
+ server.state = Review(recording)
196
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
197
+ thread.start()
198
+ client = http.client.HTTPConnection("127.0.0.1", server.server_port)
199
+ try:
200
+ for url, status in [
201
+ ("/api/replay/runs", 200), ("/api/replay/manifest", 200),
202
+ ("/api/replay/frame?index=1", 200), ("/api/replay/rgb?frame=20", 200),
203
+ ("/api/replay/bev?frame=20&layer=occupancy", 200),
204
+ ("/api/replay/bev?frame=20", 404), ("/api/replay/frame?index=-1", 404),
205
+ ("/api/replay/rgb?frame=../private", 404), ("/api/replay/map?run=../private", 404),
206
+ ]:
207
+ client.request("GET", url)
208
+ response = client.getresponse()
209
+ response.read()
210
+ assert response.status == status, url
211
+ client.request("POST", "/api/start", body="{}", headers={"X-Session": server.state.token,
212
+ "Origin": f"http://127.0.0.1:{server.server_port}"})
213
+ response = client.getresponse()
214
+ response.read()
215
+ assert response.status == 409 and server.state.phase == "stopped"
216
+ finally:
217
+ client.close()
218
+ server.shutdown()
219
+ server.server_close()
220
+ thread.join(timeout=3)
221
+
222
+
223
+ def test_future_recording_reopens_without_a_manual_review_export(recording):
224
+ import shutil
225
+ (recording / "review.json").unlink()
226
+ shutil.rmtree(recording / "review_bev")
227
+ (recording / "capture/latest.json").unlink()
228
+ state = Review(recording)
229
+ assert state.snapshot()["phase"] == "stopped"
230
+ assert state.packet["rgb_jpg"].tobytes().startswith(b"\xff\xd8")
231
+ assert set(state.images) == {f"{name}.png" for name in LAYERS}
232
+
233
+
234
+ def test_replay_is_unavailable_during_live_navigation(recording):
235
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
236
+ server.state = Review(recording)
237
+ server.state.phase = "active"
238
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
239
+ thread.start()
240
+ client = http.client.HTTPConnection("127.0.0.1", server.server_port)
241
+ try:
242
+ client.request("GET", "/api/replay/manifest")
243
+ response = client.getresponse()
244
+ response.read()
245
+ assert response.status == 409
246
+ finally:
247
+ client.close()
248
+ server.shutdown()
249
+ server.server_close()
250
+ thread.join(timeout=3)
cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_routing.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Route attachment on synthetic graphs; no CROSS checkout, map or robot needed."""
2
+ from types import SimpleNamespace
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from web_console.stretch_nav_report import SavedRoute
8
+
9
+
10
+ def pose(x=0., y=0.):
11
+ result = np.eye(4)
12
+ result[:2, 3] = [x, y]
13
+ return result
14
+
15
+
16
+ class NativeGraph:
17
+ def __init__(self, edges):
18
+ self.edges = edges
19
+ self.reads = 0
20
+
21
+ def _get_neighbors(self, key):
22
+ return [b for a, b in self.edges if a == key]
23
+
24
+ def _get_edge_cost(self, a, b):
25
+ self.reads += 1
26
+ return self.edges[a, b]
27
+
28
+
29
+ class NativePlanning:
30
+ def __init__(self, owner, edges, plans):
31
+ self.owner = owner
32
+ self.planner = NativeGraph(edges)
33
+ self.plans = plans
34
+ self.goal = None
35
+
36
+ def set_goal(self, *, goal_kf_id):
37
+ self.goal = goal_kf_id
38
+
39
+ def plan_to_goal(self, *, algorithm):
40
+ assert algorithm == 'astar'
41
+ ids = self.plans[self.owner.current]
42
+ assert ids[-1] == self.goal
43
+ return {'detailed_path': ids, 'detail_level': 'backbone',
44
+ 'detailed_cost': sum(self.planner.edges[a, b] for a, b in zip(ids, ids[1:]))}
45
+
46
+
47
+ def route_fixture(short_cost=7.42, long_cost=33.88):
48
+ route = SavedRoute.__new__(SavedRoute)
49
+ route.matrices = {1: pose(.1916), 2: pose(.1951), 3: pose(-4.), 9: pose(4., 4.)}
50
+ route.permanent = {key: SimpleNamespace(id=key) for key in route.matrices}
51
+ route.current = 1
52
+ # Two visits overlap spatially, but following recording order gives different
53
+ # costs to the same goal. Plans are fixed independently of the selection code.
54
+ edges = {(1, 3): 10., (3, 9): long_cost - 10., (2, 9): short_cost}
55
+ route.planning = NativePlanning(route, edges, {1: [1, 3, 9], 2: [2, 9], 3: [3, 9]})
56
+ route.attachment_radius, route.switch_margin = .75, .25
57
+ route._goal, route._cost_to_goal, route._previous_ids = None, {}, ()
58
+ return route
59
+
60
+
61
+ def test_remaining_distance_beats_millimetres_of_nearest_frame_advantage():
62
+ route = route_fixture()
63
+ result = route.route(pose(), 9)
64
+ assert result['attachment']['nearest_keyframe'] == 1
65
+ assert result['ids'] == [2, 9]
66
+ assert result['cost_m'] == pytest.approx(7.42)
67
+ assert result['attachment']['total_m'] == pytest.approx(7.6151)
68
+
69
+
70
+ def test_repeated_nearest_visit_switches_do_not_reset_to_long_loop():
71
+ route = route_fixture()
72
+ # Repeated visits flip the nearest keyframe while both remain local.
73
+ for x in [0., .193, .4, .193, 0.] * 20:
74
+ result = route.route(pose(x), 9)
75
+ assert result['ids'] == [2, 9]
76
+ assert result['cost_m'] < 8.
77
+
78
+
79
+ def test_valid_short_route_remains_candidate_as_another_visit_gets_closer():
80
+ route = route_fixture()
81
+ route.matrices[1] = pose(.30)
82
+ route.matrices[2] = pose(-.56)
83
+ # A nearest+0.25 m filter used to drop frame 2 here and select the long loop.
84
+ for x in [0., .005, .01, 0.]:
85
+ result = route.route(pose(x), 9)
86
+ assert result['ids'] == [2, 9]
87
+ assert result['attachment']['distance_m'] < route.attachment_radius
88
+
89
+
90
+ def test_continuity_keeps_route_when_total_costs_differ_by_only_centimetres():
91
+ route = route_fixture(short_cost=7.45, long_cost=10.01)
92
+ # Use independent direct edges of nearly equal cost.
93
+ route.planning.planner.edges = {(1, 9): 7.42, (2, 9): 7.45}
94
+ route.planning.plans[1] = [1, 9]
95
+ route._set_goal(9)
96
+ route._previous_ids = (2, 9)
97
+ result = route.route(pose(), 9)
98
+ assert result['start_keyframe'] == 2
99
+ assert result['attachment']['selected_on_previous_route']
100
+
101
+
102
+ def test_continuity_never_preserves_long_route_against_substantial_saving():
103
+ route = route_fixture()
104
+ route._set_goal(9)
105
+ route._previous_ids = (1, 3, 9)
106
+ assert route.route(pose(), 9)['start_keyframe'] == 2
107
+
108
+
109
+ def test_blocked_attachment_cannot_win_on_remaining_distance():
110
+ route = route_fixture()
111
+ result = route.route(pose(), 9, can_attach=lambda key, _point: key != 2)
112
+ assert result['start_keyframe'] == 1
113
+ assert result['attachment']['connection_check'] == 'measured_depth'
114
+
115
+
116
+ def test_no_clear_local_attachment_returns_no_route():
117
+ result = route_fixture().route(pose(), 9, can_attach=lambda *_: False)
118
+ assert result['status'] == 'no_local_graph_attachment'
119
+ assert not result['ids']
120
+
121
+
122
+ def test_distant_node_with_short_route_does_not_allow_teleporting_to_goal():
123
+ result = route_fixture().route(pose(20.), 9)
124
+ assert result['status'] == 'no_local_graph_attachment'
125
+ assert not result['ids']
126
+
127
+
128
+ def test_disconnected_nearest_node_does_not_hide_connected_local_start():
129
+ route = route_fixture()
130
+ del route.planning.planner.edges[1, 3]
131
+ assert route.route(pose(), 9)['ids'] == [2, 9]
132
+
133
+
134
+ def test_cost_to_go_is_cached_and_goal_change_resets_continuity():
135
+ route = route_fixture()
136
+ route.route(pose(), 9)
137
+ reads = route.planning.planner.reads
138
+ route.route(pose(.01), 9)
139
+ assert route.planning.planner.reads == reads
140
+ result = route.route(pose(), 1)
141
+ assert result['ids'] == [1]
142
+ assert route._cost_to_goal == {1: 0.}
143
+ assert not result['attachment']['selected_on_previous_route']
144
+
145
+
146
+ def test_goal_attachment_retains_singleton_route_for_final_approach():
147
+ route = route_fixture()
148
+ result = route.route(pose(4., 4.), 9)
149
+ assert result['status'] == 'route_found'
150
+ assert result['ids'] == [9]
151
+ assert result['cost_m'] == 0.
152
+
153
+
154
+ def test_local_attachment_cost_decreases_while_approaching_goal():
155
+ route = route_fixture()
156
+ totals = [route.route(pose(x, 4.), 9)['attachment']['total_m'] for x in [3.4, 3.6, 3.8, 4.]]
157
+ assert all(b < a for a, b in zip(totals, totals[1:]))
158
+
159
+
160
+ def test_invalid_pose_is_rejected():
161
+ with pytest.raises(ValueError, match='Invalid committed camera pose'):
162
+ route_fixture().route(np.full((4, 4), np.nan), 9)
cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_nav_survey.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Blocked starts, settled yaw/pitch observations and footprint evidence; no hardware."""
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from web_console.stretch_nav_control import depth_veto
7
+ from web_console.stretch_nav_footprint import command_footprint_report, depth_support
8
+ from web_console.stretch_nav_recovery import (
9
+ CornerObserver,
10
+ MeasuredObstacleMemory,
11
+ camera_in_base,
12
+ rectangle_path_clear,
13
+ )
14
+ from web_console.stretch_nav_survey import HeadSurvey
15
+
16
+
17
+ def camera(pan=0.0, tilt=-0.4):
18
+ c, s = np.cos(pan), np.sin(pan)
19
+ yaw = np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])
20
+ c, s = np.cos(-tilt), np.sin(-tilt)
21
+ pitch = np.array([[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]])
22
+ mount = np.eye(4)
23
+ mount[:3, :3] = yaw @ pitch @ np.array([[0, 0, 1], [-1, 0, 0], [0, -1, 0]])
24
+ mount[:3, 3] = [0.04 * np.cos(pan), 0.04 * np.sin(pan), 1.3]
25
+ return mount
26
+
27
+
28
+ def joints(pan=0.0, tilt=-0.4):
29
+ values = np.zeros(11)
30
+ values[9:11] = [pan, tilt]
31
+ return values
32
+
33
+
34
+ def empty_grid():
35
+ return {"prob": np.zeros((200, 200)), "obs": np.ones((200, 200)), "res": 0.05}
36
+
37
+
38
+ def complete_survey(survey, now=0.0, frame=0):
39
+ while survey.active:
40
+ target = [0.0, -0.4] if survey.braking else survey.targets[survey.index][1]
41
+ result = survey.update(np.eye(4), camera(*target), joints(*target), frame, now)
42
+ assert result["hold"] and result["scan_w"] == 0.0
43
+ now, frame = now + 0.25, frame + 1
44
+ return now, result
45
+
46
+
47
+ def stop_base(survey, base=None):
48
+ base = np.eye(4) if base is None else base
49
+ for frame, now in enumerate([0., .35, .70]):
50
+ result = survey.update(base, camera(), joints(), frame, now)
51
+ if frame < 2:
52
+ assert result['head_target'] is None and result['hold'] and result['scan_w'] == 0.
53
+ assert not survey.braking
54
+
55
+
56
+ def test_stuck_forward_goal_gets_distinct_yaw_and_pitch_views_before_neutral_return():
57
+ survey = HeadSurvey()
58
+ assert survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "learned footprint")
59
+ targets = np.array([target for _, target in survey.targets])
60
+ assert targets[:, 0].min() < -0.6 and targets[:, 0].max() > 0.5
61
+ assert targets[:, 1].min() < -1.0
62
+ np.testing.assert_allclose(targets[-1], [0.0, -0.4])
63
+ _, result = complete_survey(survey)
64
+ assert result["survey_complete"] and result["hold"]
65
+ assert len(survey.views) == 6 and survey.snapshot()["settled_views"] == 6
66
+
67
+
68
+ def test_duplicate_frames_or_moving_head_do_not_complete_a_view():
69
+ survey = HeadSurvey()
70
+ survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "blocked")
71
+ target = survey.targets[0][1]
72
+ for now in [0.0, 0.5, 1.0, 1.5]:
73
+ survey.update(np.eye(4), camera(*target), joints(*target), 1, now)
74
+ assert survey.index == 0
75
+ for frame, tilt in enumerate([-0.6, -0.8, -1.0], 2):
76
+ survey.update(np.eye(4), camera(tilt=tilt), joints(tilt=tilt), frame, 2.0 + frame / 10)
77
+ assert survey.index == 0
78
+
79
+
80
+ def test_joint_reaching_without_settled_camera_tf_does_not_count():
81
+ survey = HeadSurvey()
82
+ survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "blocked")
83
+ target = survey.targets[0][1]
84
+ for frame in range(6):
85
+ survey.update(np.eye(4), camera(0.1 * frame, target[1]), joints(*target), frame, frame * 0.5)
86
+ assert not survey.views
87
+
88
+
89
+ def test_settled_head_with_action_offset_counts_the_actual_image_time_extrinsic():
90
+ survey = HeadSurvey()
91
+ survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "blocked")
92
+ stop_base(survey)
93
+ target = np.array(survey.targets[0][1])
94
+ # A successful hardware action can settle about three degrees short. The
95
+ # resulting view is useful, and its measured extrinsic must be retained.
96
+ actual = target + [0.04, 0.054]
97
+ actual_mount = camera(*actual)
98
+ for frame, now in enumerate([1.0, 1.25, 1.75], 3):
99
+ result = survey.update(np.eye(4), actual_mount, joints(*actual), frame, now)
100
+ assert result["hold"] and result["scan_w"] == 0.0
101
+ assert survey.index == 1 and len(survey.views) == 1
102
+ np.testing.assert_allclose(survey.views[0]["head_joints"], actual)
103
+ np.testing.assert_allclose(survey.views[0]["camera_in_base"], actual_mount)
104
+ assert not np.allclose(actual_mount, camera(*target))
105
+
106
+
107
+ def test_stationary_camera_far_from_head_target_does_not_complete_a_view():
108
+ survey = HeadSurvey()
109
+ survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "blocked")
110
+ actual = np.array(survey.targets[0][1]) + [0.0, 0.08]
111
+ for frame in range(6):
112
+ survey.update(np.eye(4), camera(*actual), joints(*actual), frame, frame * 0.5)
113
+ assert survey.index == 0 and not survey.views
114
+
115
+
116
+ def test_survey_is_bounded_and_only_progress_allows_more_passes():
117
+ survey = HeadSurvey()
118
+ for start in [0.0, 15.0]:
119
+ survey.start(np.eye(4), camera(), camera(), joints(), start, "blocked")
120
+ now, _ = complete_survey(survey, start)
121
+ assert not survey.start(np.eye(4), camera(), camera(), joints(), now, "blocked") # Cooldown.
122
+ with pytest.raises(RuntimeError, match="two passes"):
123
+ survey.start(np.eye(4), camera(), camera(), joints(), now + 4.0, "blocked")
124
+ base = np.eye(4)
125
+ base[0, 3] = 0.21
126
+ assert survey.start(base, camera(), camera(), joints(), now + 4.0, "blocked")
127
+ assert survey.passes == 1
128
+
129
+
130
+ def test_survey_times_out_without_fresh_settled_frames():
131
+ survey = HeadSurvey()
132
+ survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "blocked")
133
+ stop_base(survey)
134
+ with pytest.raises(RuntimeError, match="timed out"):
135
+ survey.update(np.eye(4), camera(), joints(), 3, 20.8)
136
+
137
+
138
+ def test_slower_head_turn_has_time_to_settle_with_its_frozen_anchor_and_deadline():
139
+ survey = HeadSurvey()
140
+ survey.start(np.eye(4), camera(), camera(), joints(), 0., 'blocked')
141
+ stop_base(survey)
142
+ result = survey.update(np.eye(4), camera(tilt=-.8), joints(tilt=-.8), 3, 12.8)
143
+ assert result['head_deadline'] == pytest.approx(20.7)
144
+ np.testing.assert_array_equal(result['head_anchor'], survey.base)
145
+ target = survey.targets[0][1]
146
+ for frame, now in enumerate([13., 13.4, 13.9], 4):
147
+ survey.update(np.eye(4), camera(*target), joints(*target), frame, now)
148
+ assert len(survey.views) == 1
149
+
150
+
151
+ def test_external_base_motion_aborts_stationary_survey():
152
+ survey = HeadSurvey()
153
+ survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "blocked")
154
+ stop_base(survey)
155
+ base = np.eye(4)
156
+ base[0, 3] = 0.1
157
+ with pytest.raises(RuntimeError, match="Base moved"):
158
+ survey.update(base, camera(), joints(), 3, 1.0)
159
+
160
+
161
+ def test_survey_waits_for_braking_then_anchors_to_the_stopped_pose():
162
+ survey = HeadSurvey()
163
+ survey.start(np.eye(4), camera(), camera(), joints(), 0., 'blocked while driving')
164
+ # Image age plus physical deceleration creates 10.5 cm of legitimate
165
+ # movement after the triggering image, as observed in the hardware run.
166
+ for frame, (now, x) in enumerate([(0., 0.), (.25, .046), (.5, .073),
167
+ (.75, .092), (1., .105), (1.3, .107), (1.7, .107)]):
168
+ base = np.eye(4)
169
+ base[0, 3] = x
170
+ result = survey.update(base, camera(), joints(), frame, now)
171
+ assert result['hold'] and result['scan_w'] == 0.
172
+ if now < 1.7:
173
+ assert survey.braking and result['head_target'] is None
174
+ assert not survey.braking and result['head_target'] is not None
175
+ assert survey.base[0, 3] == pytest.approx(.107)
176
+ assert not survey.views # Braking frames cannot count as head observations.
177
+ base[0, 3] += .051
178
+ with pytest.raises(RuntimeError, match='Base moved'):
179
+ survey.update(base, camera(), joints(), 7, 2.)
180
+
181
+
182
+ def test_duplicate_frames_cannot_establish_base_standstill():
183
+ survey = HeadSurvey()
184
+ survey.start(np.eye(4), camera(), camera(), joints(), 0., 'blocked')
185
+ for now in [0., 1., 2.]:
186
+ result = survey.update(np.eye(4), camera(), joints(), 1, now)
187
+ assert survey.braking and result['head_target'] is None
188
+
189
+
190
+ def test_base_keeps_creeping_during_braking_never_starts_head_motion():
191
+ survey = HeadSurvey()
192
+ survey.start(np.eye(4), camera(), camera(), joints(), 0., 'blocked')
193
+ for frame in range(20):
194
+ base = np.eye(4)
195
+ base[0, 3] = .008 * frame
196
+ result = survey.update(base, camera(), joints(), frame, .25 * frame)
197
+ assert result['head_target'] is None
198
+ with pytest.raises(RuntimeError, match='braking timed out'):
199
+ survey.update(base, camera(), joints(), 21, 6.01)
200
+
201
+
202
+ def test_excess_motion_during_braking_still_aborts():
203
+ survey = HeadSurvey()
204
+ survey.start(np.eye(4), camera(), camera(), joints(), 0., 'blocked')
205
+ base = np.eye(4)
206
+ base[0, 3] = .201
207
+ with pytest.raises(RuntimeError, match='braking envelope'):
208
+ survey.update(base, camera(), joints(), 1, .5)
209
+
210
+
211
+ def test_cancelled_downward_scan_restores_pitch_and_yaw_after_correction():
212
+ observer = CornerObserver()
213
+ observer.restore_neutral(np.eye(4), 1.0)
214
+ result = observer.update({"target": np.array([1.0, 0.0]), "corner": None}, np.eye(4),
215
+ camera(-0.7, -1.05), camera(), joints(-0.7, -1.05), empty_grid(), 1.1)
216
+ np.testing.assert_allclose(result["head_target"], [0.0, -0.4], atol=1e-10)
217
+ for i in range(3):
218
+ observer.update({"target": np.array([1.0, 0.0]), "corner": None}, np.eye(4),
219
+ camera(0.0, -1.05), camera(), joints(0.0, -1.05), empty_grid(), 1.2 + i)
220
+ assert observer.phase == "return" # Yaw is restored but pitch is still wrong.
221
+
222
+
223
+ def test_camera_tf_compensation_holds_for_combined_pitch_and_yaw():
224
+ base = np.eye(4)
225
+ base[:2, 3] = [4.0, 2.0]
226
+ alignment = np.eye(4)
227
+ alignment[:2, 3] = [-2.0, 7.0]
228
+ for pan, tilt in [(0.0, -0.4), (0.55, -1.05), (-0.7, -1.05), (-0.7, -0.4)]:
229
+ actual = base @ camera(pan, tilt)
230
+ recovered = (alignment @ actual) @ np.linalg.inv(actual)
231
+ np.testing.assert_allclose(camera_in_base(actual, base), camera(pan, tilt), atol=1e-12)
232
+ np.testing.assert_allclose(recovered @ base @ camera(), alignment @ base @ camera(), atol=1e-12)
233
+
234
+
235
+ def test_depth_obstacles_survive_a_long_survey_and_its_return():
236
+ memory = MeasuredObstacleMemory()
237
+ obstacle = np.array([[0.3, 0.0], [0.3, 0.01], [0.3, -0.01]])
238
+ memory.update(obstacle, 0.0, [0.0, 0.0])
239
+ memory.observing(True, 1.0)
240
+ assert len(memory.update(np.empty((0, 2)), 35.0, [0.0, 0.0])) >= 3
241
+ memory.observing(False, 36.0)
242
+ assert len(memory.update(np.empty((0, 2)), 40.0, [0.0, 0.0])) >= 3
243
+ assert not len(memory.update(np.empty((0, 2)), 48.1, [0.0, 0.0]))
244
+
245
+
246
+ def test_own_body_prediction_is_logged_without_locking_the_robot_in_place():
247
+ grid = empty_grid()
248
+ grid["prob"][100, 100] = 0.9
249
+ report = command_footprint_report(grid, np.eye(4), np.zeros(3), 0.1, 0.0)
250
+ assert report["clear"] and report["ignored_current_body_cell_count"] == 1
251
+ assert report["self_cells"][0]["probability"] == 0.9
252
+ unsupported = depth_support(report, np.empty((0, 2)))
253
+ assert unsupported["depth_supported_cells"] == 0
254
+ assert unsupported["self_cells"][0]["nearest_depth_return_m"] is None
255
+ assert rectangle_path_clear([[0.5, 0.0], [1.0, 0.0]], grid)
256
+ assert grid["prob"][100, 100] == 0.9 # Original prediction is not overwritten.
257
+
258
+
259
+ def test_missing_depth_never_clears_a_prediction_in_newly_swept_space():
260
+ grid = empty_grid()
261
+ grid["prob"][94, 100] = 0.9 # 27.5 cm ahead, beyond the current body.
262
+ report = command_footprint_report(grid, np.eye(4), np.zeros(3), 0.1, 0.0)
263
+ unsupported = depth_support(report, np.empty((0, 2)))
264
+ assert not unsupported["clear"] and unsupported["depth_supported_cells"] == 0
265
+ assert not rectangle_path_clear([[0.5, 0.0]], grid)
266
+
267
+
268
+ def test_measured_depth_veto_is_preserved_at_the_existing_body_edge():
269
+ points = np.array([[0.215, 0.0], [0.215, 0.01], [0.215, -0.01]])
270
+ assert depth_veto(points, np.zeros(3), 0.1, 0.0)
271
+
272
+
273
+ def test_report_depth_support_uses_world_frame_and_preserves_guard_decision():
274
+ grid = empty_grid()
275
+ grid["prob"][93, 100] = 0.95
276
+ base = np.eye(4)
277
+ base[:2, 3] = [4.0, 7.0]
278
+ report = command_footprint_report(grid, base, [4.0, 7.0, 0.0], 0.15, 0.0)
279
+ assert not report["clear"] and report["sweep_time_s"] > 0.0
280
+ point = report["cells"][0]["world_xy"]
281
+ result = depth_support(report, np.tile(point, (3, 1)))
282
+ assert result["depth_supported_cells"] == 1
283
+ assert result["cells"][0]["nearby_depth_returns"] == 3
284
+
285
+
286
+ def test_unknown_predictions_do_not_become_learned_obstacles():
287
+ grid = empty_grid()
288
+ grid["prob"][:] = 1.0
289
+ grid["obs"][:] = 0.0
290
+ assert command_footprint_report(grid, np.eye(4), np.zeros(3), 0.1, 0.0)["clear"]
cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_transport.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from web_console.stretch_transport import camera_transport_diagnostics
2
+
3
+
4
+ def test_transport_age_uses_robot_clock_despite_large_pc_clock_offset():
5
+ packet = {'frame_id': 40, 'sensor_stamp': 900., 'sensor_age': .06}
6
+ robot = {'frame_id': 52, 'ros_now_s': 903.}
7
+ result = camera_transport_diagnostics(packet, robot, 1200., 1200.02)
8
+ assert result['source_frame_gap'] == 12
9
+ assert abs(result['source_age_via_status_s'] - 3.02) < 1e-9
10
+ assert abs(result['post_publish_delay_via_status_s'] - 2.96) < 1e-9
11
+
12
+
13
+ def test_old_status_does_not_produce_a_transport_age():
14
+ result = camera_transport_diagnostics({'frame_id': 5, 'sensor_stamp': 10.},
15
+ {'frame_id': 6, 'ros_now_s': 11.}, 100., 101.)
16
+ assert 'source_age_via_status_s' not in result
17
+
18
+
19
+ def test_old_relay_and_missing_status_remain_compatible():
20
+ packet = {'frame_id': 5, 'sensor_stamp': 10., 'sensor_age': .03}
21
+ assert camera_transport_diagnostics(packet, None, 0., 1.) == {'source_age_at_send_s': .03}
22
+ result = camera_transport_diagnostics(packet, {'frame_id': 6}, 1., 1.1)
23
+ assert result['source_frame_gap'] == 1
24
+ assert 'source_age_via_status_s' not in result
25
+
26
+
27
+ def test_receiver_records_timing_and_preserves_image_bytes(monkeypatch, tmp_path):
28
+ import importlib.util
29
+ import json
30
+ import pickle
31
+ from pathlib import Path
32
+ from types import SimpleNamespace
33
+
34
+ import numpy as np
35
+
36
+ path = Path(__file__).resolve().parents[1] / 'scripts/live_stretch_cross_nav.py'
37
+ spec = importlib.util.spec_from_file_location('camera_transport_live_test', path)
38
+ module = importlib.util.module_from_spec(spec)
39
+ spec.loader.exec_module(module)
40
+ state = module.LiveState(SimpleNamespace(output=tmp_path, robot_ip='unreachable.invalid'))
41
+ packet = {'world_frame': 'odom', 'frame_id': 7, 'sensor_stamp': 1000., 'sensor_age': .05,
42
+ 'camera_pose': np.eye(4), 'base_pose_matrix': np.eye(4),
43
+ 'camera_tf_stamp': 1000., 'base_tf_stamp': 1000.,
44
+ 'rgb_jpg': np.frombuffer(b'exact-rgb', dtype=np.uint8),
45
+ 'depth_png': np.frombuffer(b'exact-depth', dtype=np.uint8)}
46
+ payload = pickle.dumps(packet)
47
+
48
+ class Socket:
49
+ calls = 0
50
+
51
+ def setsockopt(self, *_):
52
+ pass
53
+
54
+ def connect(self, *_):
55
+ pass
56
+
57
+ def poll(self, *_):
58
+ self.calls += 1
59
+ if self.calls > 1:
60
+ state.done.set()
61
+ return False
62
+ return True
63
+
64
+ def recv(self):
65
+ return payload
66
+
67
+ def close(self):
68
+ pass
69
+
70
+ monkeypatch.setattr(module.zmq, 'Context', lambda: SimpleNamespace(socket=lambda *_: Socket(), term=lambda: None))
71
+ module.capture_loop(state, SimpleNamespace(process=SimpleNamespace(poll=lambda: None)))
72
+ root = tmp_path / 'capture'
73
+ assert (root / 'rgb/00000000.jpg').read_bytes() == b'exact-rgb'
74
+ assert (root / 'depth/00000000.png').read_bytes() == b'exact-depth'
75
+ timing = json.loads((root / 'transport.jsonl').read_text())
76
+ assert timing['wire_bytes'] == len(payload)
77
+ assert timing['deserialize_s'] >= 0
78
+ assert timing['record_and_publish_s'] >= 0
79
+ assert state.packet['sensor_stamp'] == 1000.
80
+ assert state.phase == 'teleop'
cases/20261026_goal1012_05/code/lite3_ROS/tests/test_stretch_vggt_debug.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Synthetic inference, buffer reuse and disk failures; no checkpoints or robot."""
2
+
3
+ import hashlib
4
+ import json
5
+ import threading
6
+ from types import SimpleNamespace
7
+
8
+ import numpy as np
9
+ import pytest
10
+ import torch
11
+
12
+ from scripts.inspect_stretch_vggt_debug import export_frame
13
+ from web_console import stretch_vggt_debug as debug
14
+
15
+
16
+ class Head:
17
+ size, res = 8, .05
18
+
19
+ def __call__(self, tokens, pts, patch_hw, dino, depth, conf, pose_enc, hw, log_scale,
20
+ up_cam=None, views=None):
21
+ self.result = {'prob': torch.full((8, 8), .1234567), 'observability': torch.ones(8, 8),
22
+ 'uncertainty': torch.zeros(8, 8), 'up_cam': torch.tensor([0., -1., 0.]),
23
+ 'up_head': torch.tensor([0., -1., 0.]), 'log_scale': log_scale, 'res': self.res}
24
+ return self.result
25
+
26
+
27
+ class Backend:
28
+ def __init__(self):
29
+ self.nav = Head()
30
+ self.depth = torch.zeros(2, 4, 6)
31
+ self.counter = 0
32
+ self.calib_focal = .91
33
+ self.last_nav = None
34
+
35
+ def infer(self, images, n_depth=None, focal=None):
36
+ self.counter += 1
37
+ self.depth.fill_(self.counter)
38
+ self.last_nav = {'pose_enc': torch.ones(1, len(images), 9)}
39
+ self.result = SimpleNamespace(c2w=np.tile(np.eye(4), (len(images), 1, 1)),
40
+ K=np.tile(np.eye(3), (len(images), 1, 1)), depth=self.depth,
41
+ depth_conf=torch.ones_like(self.depth), hw=(4, 6),
42
+ covis=np.ones((len(images), len(images))), log_scale=.3)
43
+ return self.result
44
+
45
+
46
+ class Estimator:
47
+ def __init__(self):
48
+ self.backend = Backend()
49
+ self._R_model_to_cam = np.eye(4)
50
+ self._cameras = None
51
+
52
+ def estimate_pose(self, ref_image, ref_depth, curr_image, curr_depth, odom_anchor=None,
53
+ ref_rel_poses=None, ref_cam_ids=None, **kwargs):
54
+ images = torch.stack([curr_image, ref_image[0]])
55
+ pred = self.backend.infer(images, n_depth=None, focal=.8)
56
+ out = self.backend.nav({}, 5, (1, 1), None, pred.depth, pred.depth_conf,
57
+ self.backend.last_nav['pose_enc'], (4, 6), .3,
58
+ up_cam=np.array([0., -1., 0.]), views=np.array([True, False]))
59
+ self.last_bev = {'prob': out['prob'].half().numpy(), 'observability': out['observability'].numpy(),
60
+ 'uncertainty': out['uncertainty'].numpy()}
61
+ self.last_info = {'view_tags': ['curr_L', 'ref0_L'], 'c2w_metric': pred.c2w, 'valid': True}
62
+ self.last_result = (torch.zeros(1, 7), np.ones(1, bool), torch.ones(1))
63
+ return self.last_result
64
+
65
+
66
+ def image():
67
+ return torch.linspace(-.01, 1.02, 72).reshape(3, 4, 6)
68
+
69
+
70
+ def run_frame(recorder, estimator, number=1):
71
+ recorder.begin_frame({'frame_idx': number, 'camera_pose': np.eye(4), 'head_joints': [0., -.4]})
72
+ value = image()
73
+ result = estimator.estimate_pose(value[None], None, value, None,
74
+ odom_anchor={'T_prev_curr': np.eye(4), 'image': value},
75
+ ref_rel_poses=[(0, 1, np.eye(4))])
76
+ assert result is estimator.last_result
77
+ recorder.finish_frame(observation={'retrieval': [{'id': 42, 'loaded': True, 'verified': False}]},
78
+ consumed_bev=estimator.last_bev,
79
+ body_grid={'prob': np.ones((8, 8)), 'obs': np.ones((8, 8)), 'err': np.zeros((8, 8))})
80
+
81
+
82
+ def test_hooks_preserve_predictions_and_capture_exact_inputs_and_full_precision_head(tmp_path):
83
+ reference = Estimator()
84
+ expected = reference.estimate_pose(image()[None], None, image(), None)
85
+ estimator = Estimator()
86
+ recorder = debug.VggtDebugRecorder(tmp_path / 'debug', {'origin': 'synthetic'})
87
+ recorder.attach(estimator)
88
+ run_frame(recorder, estimator)
89
+ for actual, value in zip(estimator.last_result, expected):
90
+ np.testing.assert_array_equal(np.asarray(actual), np.asarray(value))
91
+ assert isinstance(estimator.backend.nav, debug._RecordingHead)
92
+ recorder.close()
93
+ assert isinstance(estimator.backend.nav, Head)
94
+ assert 'infer' not in vars(estimator.backend) and 'estimate_pose' not in vars(estimator)
95
+ record = debug.load_debug_frame(recorder.root, 1)
96
+ call = record['passes'][0]
97
+ assert call['infer_args'] == {'n_depth': None, 'focal': .8}
98
+ assert call['effective_calib_focal'] == .91
99
+ assert call['views'][1]['reference']['id'] == 42
100
+ np.testing.assert_array_equal(debug.load_debug_view(recorder.root, call['views'][0]['asset']), image().numpy())
101
+ assert call['head_calls'][0]['outputs']['prob'].dtype == np.float32
102
+ assert record['outputs']['consumed_bev']['prob'].dtype == np.float16
103
+ np.testing.assert_array_equal(call['head_calls'][0]['inputs']['views'], [True, False])
104
+ status = json.loads((recorder.root / 'status.json').read_text())
105
+ assert status['frames'] == status['passes'] == status['unique_views'] == 1
106
+
107
+
108
+ def test_reused_output_buffers_and_shared_reference_assets_survive_later_passes(tmp_path):
109
+ estimator = Estimator()
110
+ recorder = debug.VggtDebugRecorder(tmp_path / 'debug')
111
+ recorder.attach(estimator)
112
+ run_frame(recorder, estimator, 1)
113
+ run_frame(recorder, estimator, 2)
114
+ estimator.backend.depth.fill_(99)
115
+ recorder.close()
116
+ first, second = [debug.load_debug_frame(recorder.root, number) for number in (1, 2)]
117
+ np.testing.assert_array_equal(first['passes'][0]['prediction']['depth'], 1)
118
+ np.testing.assert_array_equal(second['passes'][0]['prediction']['depth'], 2)
119
+ assert len(list((recorder.root / 'views').glob('*.npz'))) == 1
120
+
121
+
122
+ def test_interrupted_inference_retains_its_inputs_and_error(tmp_path):
123
+ estimator = Estimator()
124
+ def fail(_images, n_depth=None, focal=None):
125
+ raise ValueError('synthetic inference failure')
126
+ estimator.backend.infer = fail
127
+ recorder = debug.VggtDebugRecorder(tmp_path / 'debug')
128
+ recorder.attach(estimator)
129
+ recorder.begin_frame({'frame_idx': 3})
130
+ with pytest.raises(ValueError, match='synthetic inference failure'):
131
+ estimator.estimate_pose(image()[None], None, image(), None)
132
+ recorder.close('synthetic inference failure')
133
+ data = debug.load_debug_frame(recorder.root, 3)
134
+ assert data['interrupted'] == data['passes'][0]['inference_error'] == 'synthetic inference failure'
135
+ np.testing.assert_array_equal(debug.load_debug_view(recorder.root, data['passes'][0]['views'][0]['asset']),
136
+ image().numpy())
137
+
138
+
139
+ def test_background_disk_failure_is_explicit_and_does_not_commit_partial_frame(monkeypatch, tmp_path):
140
+ errors = []
141
+ def fail(*_args, **_kwargs):
142
+ raise OSError('synthetic disk full')
143
+ monkeypatch.setattr(debug, 'write_npz', fail)
144
+ estimator = Estimator()
145
+ recorder = debug.VggtDebugRecorder(tmp_path / 'debug', on_error=errors.append)
146
+ recorder.attach(estimator)
147
+ run_frame(recorder, estimator)
148
+ recorder.pending.join()
149
+ with pytest.raises(RuntimeError, match='synthetic disk full'):
150
+ recorder.check()
151
+ with pytest.raises(RuntimeError, match='synthetic disk full'):
152
+ recorder.close()
153
+ assert len(errors) == 1
154
+ assert not list((recorder.root / 'frames').glob('*/frame.json'))
155
+ assert json.loads((recorder.root / 'status.json').read_text())['status'] == 'failed'
156
+
157
+
158
+ def test_full_queue_is_explicit_and_close_flushes_the_retained_frame(monkeypatch, tmp_path):
159
+ entered, release = threading.Event(), threading.Event()
160
+ original = debug.VggtDebugRecorder._write
161
+ def paused(self, job):
162
+ entered.set()
163
+ assert release.wait(5)
164
+ original(self, job)
165
+ monkeypatch.setattr(debug.VggtDebugRecorder, '_write', paused)
166
+ recorder = debug.VggtDebugRecorder(tmp_path / 'debug', max_pending=1)
167
+ estimator = Estimator()
168
+ recorder.attach(estimator)
169
+ try:
170
+ run_frame(recorder, estimator, 1)
171
+ assert entered.wait(2)
172
+ run_frame(recorder, estimator, 2)
173
+ with pytest.raises(RuntimeError, match='cannot keep up'):
174
+ run_frame(recorder, estimator, 3)
175
+ finally:
176
+ release.set()
177
+ recorder.close()
178
+ rows = (recorder.root / 'index.jsonl').read_text().splitlines()
179
+ assert [json.loads(line)['capture_frame'] for line in rows] == [1, 2, 3]
180
+
181
+
182
+ def test_inspector_exports_input_group_and_bev_stages_without_a_model(tmp_path):
183
+ recorder = debug.VggtDebugRecorder(tmp_path / 'debug')
184
+ estimator = Estimator()
185
+ recorder.attach(estimator)
186
+ run_frame(recorder, estimator)
187
+ recorder.close()
188
+ result = export_frame(recorder.root, 1, tmp_path / 'inspection')
189
+ assert result['views'] == 2
190
+ assert all((tmp_path / 'inspection' / name).is_file() for name in
191
+ ('input_views.jpg', 'predicted_depth.jpg', 'bev_stages.png', 'model_inputs.npz', 'manifest.json'))
192
+ with np.load(tmp_path / 'inspection/model_inputs.npz', allow_pickle=False) as arrays:
193
+ np.testing.assert_array_equal(arrays['images'][0], image().numpy())
194
+
195
+
196
+ def test_object_arrays_and_asset_traversal_are_rejected(tmp_path):
197
+ with pytest.raises(TypeError, match='Object arrays'):
198
+ debug.snapshot(np.array([object()], dtype=object))
199
+ with pytest.raises(ValueError, match='asset'):
200
+ debug.load_debug_view(tmp_path, '../escape')
201
+
202
+
203
+ def test_planner_memory_snapshot_preserves_fusion_evidence_before_buffer_reuse(tmp_path):
204
+ world = SimpleNamespace(o=np.array([1., 2.]), num=np.ones((8, 8)), den=np.full((8, 8), 2.),
205
+ seen=np.full((8, 8), .7), c={'res': .1, 'block_p': .6})
206
+ episode = SimpleNamespace(world=world, pose=np.zeros(3), bumps=[[1., 2.]], route=None)
207
+ recorder = debug.VggtDebugRecorder(tmp_path / 'debug')
208
+ recorder.begin_frame({'frame_idx': 4})
209
+ recorder.finish_frame(planner_state=debug.planner_snapshot(episode))
210
+ world.num[:] = 99
211
+ recorder.close()
212
+ saved = debug.load_debug_frame(recorder.root, 4)['outputs']['planner_state']['world']
213
+ np.testing.assert_array_equal(saved['num'], 1.)
214
+ np.testing.assert_array_equal(saved['den'], 2.)
215
+ np.testing.assert_array_equal(saved['seen'], .7)
216
+ assert saved['c']['block_p'] == .6
217
+
218
+
219
+ def test_bfloat16_snapshot_preserves_numeric_values_exactly():
220
+ value = torch.tensor([.12345, 2000., 1e-8], dtype=torch.bfloat16)
221
+ saved = debug.snapshot(value)
222
+ assert saved.dtype == np.float32
223
+ np.testing.assert_array_equal(saved, value.float().numpy())
224
+
225
+
226
+ def test_checkpoint_provenance_records_revision_and_hashes_of_actual_files(monkeypatch, tmp_path):
227
+ monkeypatch.setattr(debug.subprocess, 'run', lambda *_a, **_kw: SimpleNamespace(stdout='abc123\n'))
228
+ root = tmp_path / 'cross'
229
+ heads = root / 'models/VGGT-Omega-CROSS/nav'
230
+ heads.mkdir(parents=True)
231
+ names = ('vggt_omega_cross_1b_512.pt', 'nav/cross_nav_occupancy.pt', 'nav/cross_nav_observability.pt')
232
+ for name in names:
233
+ (heads.parent / name).write_bytes(name.encode())
234
+ provenance = debug.model_provenance(root)
235
+ assert provenance['cross_git_revision'] == 'abc123'
236
+ for name in names:
237
+ assert provenance['checkpoints'][name]['sha256'] == hashlib.sha256(name.encode()).hexdigest()
cases/20261026_goal1012_05/code/lite3_ROS/web_console/__init__.py ADDED
File without changes
cases/20261026_goal1012_05/code/lite3_ROS/web_console/cross_run.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Retain native CROSS maps and trajectories without editing the CROSS checkout."""
2
+
3
+ import json
4
+ import time
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+
9
+
10
+ def matrix(pose):
11
+ return pose.matrix().detach().cpu().numpy()
12
+
13
+
14
+ class RunArtifacts:
15
+ def __init__(self, directory, metadata):
16
+ self.directory = Path(directory).resolve()
17
+ self.directory.mkdir(parents=True, exist_ok=False)
18
+ self.metadata = {**metadata, "status": "running", "has_ground_truth": False}
19
+ self.records = []
20
+ self.session = None
21
+ self.original_release = None
22
+ self.started = time.perf_counter()
23
+ self.write_status()
24
+
25
+ def write_status(self):
26
+ path = self.directory / "run.json"
27
+ temporary = path.with_suffix(".json.tmp")
28
+ temporary.write_text(json.dumps(self.metadata, indent=2, allow_nan=False) + "\n")
29
+ temporary.replace(path)
30
+
31
+ def wrap_factory(self, factory):
32
+ def make():
33
+ from cross.core.config import config_to_dict
34
+
35
+ session = self.session = factory()
36
+ process, self.original_release = session.process, session.release
37
+ config = config_to_dict(session.mapper.config)
38
+ (self.directory / "resolved_config.json").write_text(json.dumps(config, indent=2) + "\n")
39
+
40
+ def record(frame):
41
+ started = time.perf_counter()
42
+ result = process(frame)
43
+ _, best, weights = session.belief(matrix)
44
+ estimate = getattr(session, "last_estimate", None)
45
+ diagnostics = getattr(estimate, "diagnostics", {})
46
+ row = {
47
+ "frame_idx": int(frame["frame_idx"]), "timestamp": float(frame["timestamp"]),
48
+ "pose": np.asarray(best).tolist(), "weights": np.asarray(weights).tolist(),
49
+ "process_s": time.perf_counter() - started,
50
+ "frontend_valid": bool(diagnostics.get("valid", True)),
51
+ "imu_samples_provided": len(frame.get("imu", [])),
52
+ }
53
+ self.records.append(row)
54
+ return result
55
+
56
+ def save_release():
57
+ try:
58
+ self.save(session)
59
+ finally:
60
+ self.release()
61
+
62
+ session.process, session.release = record, save_release
63
+ return session
64
+ return make
65
+
66
+ def save(self, session):
67
+ session.save_map(self.directory / "map.pkl")
68
+ manager = session.hypothesis_manager
69
+ times = np.array([r["timestamp"] for r in self.records])
70
+ nodes = []
71
+ for key, node in manager.nodes.items():
72
+ stamp = getattr(node, "timestamp", None)
73
+ row = {"id": int(key), "pose": matrix(node.pose_mu[0]).tolist(), "temporary": bool(node.temporary)}
74
+ if stamp is not None and len(times) and np.isfinite(stamp):
75
+ index = int(np.argmin(np.abs(times - float(stamp))))
76
+ row.update(timestamp=float(stamp), frame_idx=self.records[index]["frame_idx"])
77
+ nodes.append(row)
78
+ visual = [{"hypothesis": int(hid), "source": int(a), "target": int(b), "factors": len(factors)}
79
+ for hid, hypothesis in manager.hypotheses.items()
80
+ for (a, b), factors in hypothesis.visual_edges.items()]
81
+ graph = {"nodes": nodes, "odometry_edges": [list(map(int, edge)) for edge in manager.odom_edges],
82
+ "visual_edges": visual}
83
+ (self.directory / "graph.json").write_text(json.dumps(graph, indent=2, allow_nan=False) + "\n")
84
+ self.write_trajectory("trajectory.jsonl")
85
+ frontend = getattr(session, "frontend", None)
86
+ service = getattr(frontend, "service", None)
87
+ self.metadata.update(
88
+ frames_processed=len(self.records), keyframes=len(nodes),
89
+ permanent_keyframes=sum(not node["temporary"] for node in nodes),
90
+ odometry_edges=len(graph["odometry_edges"]), visual_edge_pairs=len(visual),
91
+ map_saved=True, valid_frontend_frames=sum(r["frontend_valid"] for r in self.records),
92
+ )
93
+ if service is not None:
94
+ self.metadata["inertial_frontend_service"] = dict(service.stats)
95
+ if frontend is not None and hasattr(frontend, "stats"):
96
+ self.metadata["inertial_frontend"] = dict(frontend.stats)
97
+ self.write_status()
98
+
99
+ def write_trajectory(self, filename):
100
+ with (self.directory / filename).open("w") as stream:
101
+ for record in self.records:
102
+ stream.write(json.dumps(record, allow_nan=False) + "\n")
103
+
104
+ def release(self):
105
+ if self.original_release:
106
+ release, self.original_release = self.original_release, None
107
+ release()
108
+
109
+ def finish(self, error=None):
110
+ self.metadata.update(status="failed" if error else "completed", frames_processed=len(self.records),
111
+ wall_seconds=time.perf_counter() - self.started)
112
+ if error:
113
+ self.metadata["error"] = str(error)
114
+ self.write_trajectory("trajectory.partial.jsonl")
115
+ self.write_status()
116
+ self.release()
cases/20261026_goal1012_05/code/lite3_ROS/web_console/static/cross_nav.css ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ :root{color-scheme:dark;--bg:#0c1720;--panel:#13232f;--line:#2b414f;--text:#e6eff1;--muted:#98afbd;--mint:#72dec0;--amber:#f3c77c}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:14px/1.5 system-ui,-apple-system,sans-serif}header{padding:21px 32px;display:flex;align-items:center;justify-content:space-between;gap:20px;border-bottom:1px solid var(--line);background:#11212c}header>div{display:flex;align-items:center;gap:30px}h1,h2,h3,p{margin:0}h1{font-size:25px;font-weight:650;letter-spacing:-.5px}h2{font-size:18px;font-weight:620}h3{font-size:14px;font-weight:630}.eyebrow{font-size:10px;letter-spacing:1.8px;color:var(--muted);display:block;margin-bottom:5px}header .eyebrow{margin:0;color:#b2cccf}.badge{font-size:10px;border:1px solid var(--line);border-radius:18px;padding:5px 9px;white-space:nowrap;color:var(--muted)}.passive{color:var(--mint);border-color:#355b51}main{max-width:1800px;margin:auto;padding:25px 28px}.summary{display:flex;justify-content:space-between;gap:20px;align-items:center;margin-bottom:22px}.summary h2{font-size:24px;letter-spacing:-.3px}.summary p{color:var(--muted);margin-top:4px}.metrics{display:flex;gap:40px}.metrics>div{display:flex;flex-direction:column;text-align:right}.metrics strong{font-size:28px;line-height:1.2}.metrics span{font-size:11px;color:var(--muted);margin-top:5px}.notice{display:flex;gap:18px;align-items:center;padding:13px 17px;border:1px solid #67543a;border-radius:8px;background:#28271f;color:#e7cfaa;margin-bottom:22px;font-size:12px}.notice b{white-space:nowrap;color:var(--amber)}.workspace{display:grid;grid-template-columns:255px minmax(370px,1.35fr) minmax(280px,1fr);gap:18px;align-items:stretch}.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;overflow:hidden}.card-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:18px 18px 10px}.card-head h2{font-size:17px}.card-head .eyebrow{font-size:9px}.stages{grid-row:span 2;padding:20px 17px}.stage{display:flex;gap:12px;margin:21px 0}.step{display:grid;place-items:center;flex:0 0 28px;height:28px;border-radius:7px;color:var(--mint);background:#1b3d3c;font-size:11px}.step.amber{background:#443a2b;color:var(--amber)}.stage p{font-size:12px;color:var(--mint);margin-top:3px}.stage small{display:block;font-size:10px;color:var(--muted);margin-top:2px}.divider{border-top:1px solid var(--line);margin:22px 0 17px}.goal-row{display:flex;gap:8px;margin:10px 0}.goal-row input{min-width:0;width:100%}.help{font-size:11px;color:var(--muted);line-height:1.6}.check{display:flex;gap:7px;align-items:center;margin-top:11px;font-size:12px}input[type=checkbox],input[type=range]{accent-color:var(--mint)}button,select,input[type=number]{font:inherit;background:#1a303e;color:var(--text);border:1px solid #3c5667;border-radius:6px;padding:7px 10px}button{cursor:pointer;font-size:11px;white-space:nowrap}button:hover{border-color:var(--mint);color:var(--mint)}button:disabled{opacity:.5;cursor:wait}.primary{color:var(--mint);border-color:#4f9c8b;background:#1c423f}.buttons{display:flex;gap:6px}.buttons button{padding:6px 9px}.quiet{color:var(--muted)}#global-map{height:420px;min-width:0;width:100%}.map-caption{padding:0 18px 15px}.image-card{display:flex;flex-direction:column}#robot-rgb{display:block;max-height:360px;min-height:220px;width:100%;object-fit:contain;background:#0e1b25}.image-meta{padding:11px 17px;display:flex;align-items:center;justify-content:space-between;color:var(--muted);font-size:11px}.image-card>.help{padding:0 17px 15px}.bev-wrap{padding:0 17px;display:flex;justify-content:center}#bev{width:100%;max-width:430px;aspect-ratio:1;background:#0f1e29;border-radius:6px}.bev-card>.help{padding:8px 18px 18px}.legend{display:flex;flex-wrap:wrap;gap:7px 15px;padding:12px 18px 0;font-size:10px;color:var(--muted)}.legend i{display:inline-block;width:7px;height:7px;margin-right:5px;border-radius:2px}.free{background:#3fc09f}.obstacle{background:#ef6e69}.unknown{background:#213140}.path{background:#b1e8ff}.references{min-width:0}#reference-images{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:9px;padding:8px 16px}figure{margin:0;min-width:0}figure img{width:100%;height:140px;object-fit:contain;border-radius:5px;background:#0c1720}figcaption{font-size:10px;color:var(--muted);margin-top:5px}figcaption b{color:var(--text);font-weight:550}.references>.help{padding:8px 17px 17px}.details{grid-column:2/4}.details dl{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:17px 25px;padding:10px 20px 18px;margin:0}.details dt{font-size:10px;letter-spacing:.7px;text-transform:uppercase;color:var(--muted)}.details dd{margin:4px 0 0;font-size:13px}.details>.help{padding:0 20px 18px}.timeline{margin-top:18px;padding:14px 17px;display:flex;gap:18px;align-items:center}.timeline>div{flex:1;min-width:100px}.timeline label{font-size:11px;color:var(--muted);display:block;margin-bottom:7px}.timeline input{width:100%;margin:0}.timeline>span{font-size:11px;white-space:nowrap;color:var(--muted)}footer{color:#809baa;font-size:10px;padding:17px 2px}#build-state{font-size:11px;color:var(--amber);margin-top:10px}#error{padding:14px;border:1px solid #bd6262;background:#3a2025;margin-bottom:15px;border-radius:6px}button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--mint);outline-offset:3px}@media(min-width:1450px){#global-map{height:475px}#robot-rgb{max-height:410px}figure img{height:165px}}@media(max-width:1150px){.workspace{grid-template-columns:235px minmax(0,1fr)}.stages{grid-row:span 3}.image-card{grid-column:2}#robot-rgb{max-height:320px}.bev-card,.references{grid-column:2}.details{grid-column:1/3}.metrics{gap:20px}.summary h2{font-size:21px}.metrics strong{font-size:23px}}@media(max-width:700px){header{padding:17px;align-items:flex-start}header>div{display:block}header .eyebrow{margin-bottom:6px}h1{font-size:21px}header .badge{font-size:8px;padding:5px 7px;white-space:normal;max-width:115px;text-align:center}main{padding:18px 12px}.summary{display:block}.metrics{margin-top:20px;justify-content:space-between;gap:10px}.metrics>div{text-align:left}.metrics span{font-size:9px}.notice{display:block}.notice b{display:block;margin-bottom:5px}.workspace{display:flex;flex-direction:column}.stages{order:0}.map-card{order:1}.image-card{order:2}.bev-card{order:3}.references{order:4}.details{order:5}.stage{margin:15px 0}.details dl{grid-template-columns:repeat(2,minmax(0,1fr))}#global-map{height:370px}.card-head{padding:15px 14px 10px}.card-head h2{font-size:15px}.timeline{gap:10px;flex-wrap:wrap}.timeline>div{min-width:200px;order:0;flex-basis:75%}.timeline>span{order:1}.timeline #stop-capture{margin-left:auto;order:2}figure img{height:130px}.references #reference-images{gap:7px;padding:8px 12px}}
2
+
3
+ .notice label{display:flex;align-items:center;gap:10px;white-space:nowrap}.notice>span{flex:1}.notice select{max-width:230px}@media(max-width:900px){.notice{flex-wrap:wrap}.notice>span{flex-basis:100%}.notice label{white-space:normal}}
cases/20261026_goal1012_05/code/lite3_ROS/web_console/static/cross_nav_live.html ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Live Stretch · CROSS navigation</title><link rel="stylesheet" href="/cross_nav.css"><script defer src="/vendor/plotly.min.js"></script><script defer src="/cross_nav_live.js"></script><style>
3
+ #global-map{height:550px}.live-controls{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin:18px 0}.stop{background:#a33a43;color:white;border-color:#ed7f88;font-weight:750;padding:14px 25px}.start{padding:14px 25px}.live-status{flex:1;min-width:240px}.live-status strong{display:block;font-size:18px}.live-meta{display:flex;gap:24px;flex-wrap:wrap;margin:12px 0;color:var(--muted)}.live-images{display:grid;grid-template-columns:1fr 1fr;gap:16px}.live-images img{width:100%;max-height:480px;object-fit:contain;background:#0a141e}.live-grid{display:grid;grid-template-columns:1.15fr 1fr;gap:18px}.card{padding:20px}.live-card h2{margin-bottom:14px}#bev{max-width:100%;display:block;margin:auto}#plan-note{margin-top:10px}.pill{border:1px solid var(--line);border-radius:5px;padding:4px 8px;font-size:12px}.live-layer{display:flex;gap:14px;flex-wrap:wrap;margin-top:10px}.live-layer label{display:flex;gap:6px;align-items:center}#rgb{height:450px;width:100%;object-fit:contain;background:#0b1822}.live-help{max-width:1000px}.notice{align-items:center}@media(max-width:950px){.live-grid{grid-template-columns:1fr}#global-map{height:430px}.live-images{grid-template-columns:1fr}header>div{gap:8px;flex-wrap:wrap}}
4
+ .replay-panel{margin:16px 0;display:grid;gap:14px}.replay-panel[hidden],#handoff-note[hidden]{display:none}.replay-toolbar{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.replay-toolbar select{max-width:420px}.replay-timeline{display:flex;align-items:center;gap:14px}.replay-timeline input{flex:1;min-width:100px}.replay-clock{font-variant-numeric:tabular-nums;white-space:nowrap}.replay-notes{margin:0;color:var(--muted)}@media(max-width:700px){.replay-toolbar select{max-width:100%}.replay-timeline{flex-wrap:wrap}}
5
+ </style></head><body>
6
+ <header><div><span class="eyebrow">STRETCH / CROSS · LIVE</span><h1 id="page-title">Teleop → navigation</h1></div><span class="badge" id="phase">CONNECTING</span></header>
7
+ <main>
8
+ <section class="summary"><div><span class="eyebrow">PHONE REFERENCE MAP</span><h2>Goal keyframe <span id="goal">1012</span></h2><p>2026-10-22 · 15:48:58 · learned BEV + graph routing</p></div><div class="metrics"><div><strong id="count">0</strong><span>processed observations</span></div><div><strong id="distance">—</strong><span>camera distance to goal</span></div><div><strong id="commands">0</strong><span>motion commands sent</span></div></div></section>
9
+ <div class="notice live-help" id="handoff-note"><b>Operator handoff</b><span>Teleop until the pose is committed and Start navigation becomes available. Close the teleop client completely, then click Start navigation. Keep this page open. Stop navigation ends the run and releases the temporary relay. Goal arrival checks position within 0.4 m; final heading is not enforced.</span></div>
10
+ <div id="error" role="alert" hidden></div>
11
+ <div class="live-controls"><div class="live-status"><strong id="state-title">Loading observations</strong><span id="reason">Teleop remains in control</span></div><button id="start" class="primary start" disabled>Start navigation to 1012</button><button id="stop" class="stop">Stop navigation / end run</button><button id="replay-open" class="primary" disabled>Replay recording</button><button id="export">Save current result</button></div>
12
+ <section class="card replay-panel" id="replay-panel" hidden aria-label="Recorded run playback">
13
+ <div class="replay-toolbar"><strong>Recorded run</strong><select id="replay-run" aria-label="Recording"></select><button id="replay-close">Close replay</button></div>
14
+ <div class="replay-toolbar"><button id="replay-prev" aria-label="Previous RGB frame">◀ Frame</button><button id="replay-play" class="primary">Play</button><button id="replay-next" aria-label="Next RGB frame">Frame ▶</button><label>Speed <select id="replay-speed"><option value="0.5">0.5×</option><option value="1" selected>1×</option><option value="2">2×</option><option value="4">4×</option></select></label><select id="replay-event" aria-label="Jump to recorded event"><option value="">Jump to event…</option></select></div>
15
+ <div class="replay-timeline"><input id="replay-seek" type="range" min="0" max="0" value="0" step="1" aria-label="Seek replay"><output id="replay-clock" class="replay-clock">00:00 / 00:00</output></div>
16
+ <p class="replay-notes" id="replay-note">RGB, map and occupancy playback. Motion controls are disabled.</p>
17
+ </section>
18
+ <div class="live-meta"><span id="localization">Localization pending</span><span id="route">Graph route pending</span><span>Speed limit: 0.10 m/s · 0.25 rad/s</span></div>
19
+ <div class="live-grid">
20
+ <section class="card live-card"><div class="card-head"><div><span class="eyebrow">GLOBAL MAP</span><h2>Pose, route & local path</h2></div><div class="buttons"><button id="top">Top</button><button id="reset">3D / reset</button></div></div><div id="global-map"></div><div class="live-layer"><label><input type="checkbox" data-layer="map" checked>Phone map</label><label><input type="checkbox" data-layer="route" checked>Graph route</label><label><input type="checkbox" data-layer="track" checked>CROSS camera path</label><label><input type="checkbox" data-layer="local" checked>Local plan</label></div><p class="help">Drag to rotate · scroll to zoom. Camera poses and floor-projected local paths use the same map alignment.</p></section>
21
+ <section class="card live-card"><span class="eyebrow" id="rgb-label">LIVE ROBOT RGB</span><h2>Camera observation</h2><img id="rgb" alt="Current Stretch camera RGB"><p class="help" id="frame-note">Waiting for camera</p></section>
22
+ <section class="card live-card"><div class="card-head"><div><span class="eyebrow">LEARNED BEV</span><h2>Occupancy & local planning</h2></div><div class="buttons"><select id="bev-range" aria-label="BEV view range"><option value="10">20 m view</option><option value="3">6 m view</option><option value="1.5">3 m near field</option></select><select id="layer" aria-label="BEV layer"><option value="occupancy">Occupancy</option><option value="visibility">Observability</option><option value="uncertainty">Occupancy error</option></select></div></div><canvas id="bev" width="600" height="600"></canvas><div class="legend" id="legend"></div><p class="help" id="plan-note">BEVs appear after a VGGT pass. The local plan appears after map commitment.</p></section>
23
+ <section class="card live-card"><span class="eyebrow">CURRENT RUN</span><h2>Localization & handoff</h2><dl id="details"></dl><p class="help">The local route comes from native cross_nav. Swept-footprint checks use learned occupancy and measured depth. A blocked start triggers a stationary head survey. Nearby depth returns support an obstacle prediction; missing returns do not prove free space. This is the first supervised drive test; keep the robot run-stop within reach.</p><p class="help">To resume manual testing after Stop, wait for the relay to close and start a new run. After a brief plan gap, an active run continues only with a fresh valid plan. A stopped run never re-arms automatically.</p></section>
24
+ </div>
25
+ <footer id="page-footer">Live RGB + odometry · trained occupancy/observability heads · phone map preserved · controls require this local page</footer>
26
+ </main></body></html>
cases/20261026_goal1012_05/code/lite3_ROS/web_console/static/cross_nav_live.js ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ const el=id=>document.getElementById(id);
3
+ let state=null,liveState=null,map=null,drawn=-1,polling=false,plotReady=false;
4
+ const replay={active:false,manifest:null,index:0,playing:false,run:null,anchorTime:0,anchorWall:0,generation:0,busy:false,pending:null};
5
+ const initial={eye:{x:1.35,y:-1.65,z:1.2},up:{x:0,y:0,z:1}};
6
+ const colors={map:'#688a9a',route:'#e9bd7c',track:'#72dec0',local:'#b1e8ff'};
7
+ async function api(path,body){const options=body===undefined?{}:{method:'POST',headers:{'X-Session':liveState?.token||state?.token,'Content-Type':'application/json'},body:JSON.stringify(body),keepalive:true};const response=await fetch(path,options),data=await response.json();if(!response.ok)throw Error(data.error||response.status);return data;}
8
+ function trace(points,name,layer,extra={}){const p=points||[];return {type:'scatter3d',mode:'lines',name,x:p.map(x=>x[0]),y:p.map(x=>x[1]),z:p.map(x=>x[2]),line:{color:colors[layer],width:layer==='map'?2:5},visible:document.querySelector(`[data-layer=${layer}]`).checked,meta:{layer},...extra};}
9
+ async function drawMap(){const f=state.frame;if(!map)return;const data=[trace(map.nodes.map(n=>n.position),'Phone camera keyframes','map'),trace(f.global_route,'Graph route','route'),trace(f.trajectory,'CROSS camera path','track'),trace(f.local_path_display,'Local plan on floor','local')];const goal=map.nodes.find(n=>n.id===state.goal_keyframe);if(goal)data.push(trace([goal.position],`Goal ${state.goal_keyframe}`,'route',{mode:'markers',marker:{size:7,color:'#f3c77c',symbol:'diamond'}}));if(f.camera_display)data.push(trace([f.camera_display],'Robot camera','track',{mode:'markers',marker:{size:6,color:'#72dec0'}}));const layout={paper_bgcolor:'#13232f',font:{family:'system-ui',color:'#98afbd'},showlegend:false,margin:{t:0,b:0,l:0,r:0},uirevision:'live-map',scene:{aspectmode:'data',dragmode:'orbit',camera:el('global-map')._fullLayout?.scene?._scene?.getCamera()||initial,xaxis:{title:'X (m)',gridcolor:'#2b414f'},yaxis:{title:'Y (m)',gridcolor:'#2b414f'},zaxis:{title:'Z · up (m)',gridcolor:'#2b414f'}}};await Plotly.react(el('global-map'),data,layout,{responsive:true,scrollZoom:true,displayModeBar:false});plotReady=true;}
10
+ function drawBEV() {
11
+ const f=state?.frame;
12
+ if(!f?.bev_size||(state.playback&&!state.replay.bev_urls[el('layer').value])){
13
+ const ctx=el('bev').getContext('2d');ctx.fillStyle='#0f1e29';ctx.fillRect(0,0,600,600);
14
+ ctx.fillStyle='#a9bfcb';ctx.font='16px system-ui';ctx.textAlign='center';
15
+ ctx.fillText('No saved BEV at this time',300,300);el('legend').replaceChildren();return;
16
+ }
17
+ const layer=el('layer').value,ctx=el('bev').getContext('2d'),img=new Image();
18
+ img.onload=()=>{
19
+ if(state.frame!==f)return;
20
+ const pad=36,size=528,fullHalf=f.bev_size*f.bev_res/2;
21
+ const half=Math.min(fullHalf,Number(el('bev-range').value));
22
+ const p=x=>[pad+size*(.5-x[1]/(2*half)),pad+size*(.5-x[0]/(2*half))];
23
+ ctx.fillStyle='#0f1e29';ctx.fillRect(0,0,600,600);ctx.imageSmoothingEnabled=false;
24
+ const sourceSize=img.width*half/fullHalf,sourceStart=(img.width-sourceSize)/2;
25
+ ctx.drawImage(img,sourceStart,sourceStart,sourceSize,sourceSize,pad,pad,size,size);
26
+ ctx.save();ctx.beginPath();ctx.rect(pad,pad,size,size);ctx.clip();
27
+ ctx.strokeStyle='#98afbd30';const step=half<=1.5?.25:half<=3?.5:1;
28
+ for(let i=-half;i<=half;i+=step){
29
+ ctx.beginPath();ctx.moveTo(...p([i,-half]));ctx.lineTo(...p([i,half]));
30
+ ctx.moveTo(...p([-half,i]));ctx.lineTo(...p([half,i]));ctx.stroke();
31
+ }
32
+ if(f.local_path_body?.length){
33
+ ctx.strokeStyle='#b1e8ff';ctx.lineWidth=3;ctx.beginPath();ctx.moveTo(...p([0,0]));
34
+ for(const x of f.local_path_body)ctx.lineTo(...p(x));ctx.stroke();
35
+ }
36
+ const body=p([.23,.23]),bodySize=size*.46/(2*half);
37
+ ctx.strokeStyle='white';ctx.lineWidth=2;ctx.strokeRect(...body,bodySize,bodySize);
38
+ for(const cell of [...(f.footprint_diagnostics?.self_cells||[]),...(f.footprint_diagnostics?.cells||[])]){
39
+ const xy=cell.display_body_xy||cell.grid_body_xy,point=p(xy),width=Math.max(4,size*f.bev_res/(2*half));
40
+ ctx.fillStyle=(f.footprint_diagnostics?.self_cells||[]).includes(cell)?'#9aafbf':cell.depth_supported?'#ff6868':'#ffa63d';
41
+ ctx.fillRect(point[0]-width/2,point[1]-width/2,width,width);
42
+ }
43
+ const origin=p([0,0]);ctx.fillStyle='white';ctx.beginPath();ctx.arc(...origin,3,0,Math.PI*2);ctx.fill();
44
+ if(f.goal_body){ctx.fillStyle='#f3c77c';ctx.beginPath();ctx.arc(...p(f.goal_body),5,0,Math.PI*2);ctx.fill();}
45
+ ctx.restore();ctx.fillStyle='#a9bfcb';ctx.font='12px system-ui';ctx.textAlign='center';
46
+ ctx.fillText(`FORWARD +${half} m`,300,20);ctx.fillText(`LEFT +${half} m`,90,585);
47
+ ctx.fillText(`RIGHT −${half} m`,505,585);
48
+ };
49
+ img.src=state.playback?state.replay.bev_urls[layer]:`/api/bev/${layer}.png?t=${f.frame_idx}`;
50
+ const palette={occupancy:[['#37b794','0 free'],['#debe60','0.5'],['#e95b65','1 occupied']],
51
+ visibility:[['#192a3c','0 unseen'],['#ade2ff','1 observed']],
52
+ uncertainty:[['#192a3c','0 low error'],['#ffae4c','1 high error']]}[layer];
53
+ el('legend').replaceChildren();
54
+ for(const [color,label]of [...palette,['white','Robot footprint'],['#b1e8ff','Local path'],
55
+ ['#9aafbf','Own-body prediction (excluded)'],['#ffa63d','Learned blocking cell'],['#ff6868','Blocker with nearby depth returns']]){
56
+ const span=document.createElement('span'),mark=document.createElement('i');mark.style.background=color;
57
+ span.append(mark,document.createTextNode(label));el('legend').append(span);
58
+ }
59
+ }
60
+ function details() {
61
+ const f=state.frame,survey=f.head_survey,diagnostic=f.footprint_diagnostics;
62
+ const joint=state.robot?.joint_positions;
63
+ const cells=diagnostic?.cells||[],supported=cells.filter(c=>c.depth_supported).length;
64
+ const rows=[
65
+ ['Map pose',f.localized?`Committed · ${f.localized_streak} consecutive observations`:'Tentative · continue teleop'],
66
+ ['Map matches',(f.retrieval||[]).filter(a=>a.loaded&&a.verified).map(a=>a.id).join(', ')||'No verified map views'],
67
+ ['Local planner',f.planner_name||'Loading'],
68
+ ['Pose recovery',f.correction_recovery?.pending?`Holding · ${f.correction_recovery.stable_samples} stable views`:'Ready'],
69
+ ['Head survey',survey?.active?`Pass ${survey.pass} · view ${survey.view}/${survey.total} · ${survey.label}`:
70
+ survey?.settled_views?`${survey.settled_views} settled views completed`:'Idle'],
71
+ ['Corner observation',f.corner_observation?`${f.corner_observation.phase} · ${Math.round(100*(f.corner_observation.coverage||0))}% branch visibility`:'Cruise'],
72
+ ['Head pan / tilt',joint?.length>=11?`${(joint[9]*180/Math.PI).toFixed(1)}° / ${(joint[10]*180/Math.PI).toFixed(1)}°`:'Unavailable'],
73
+ ['Head action',state.robot?.head_action_state||'Unavailable'],
74
+ ['Footprint veto',state.control?.learned_blocked?'Learned occupancy':state.control?.depth_blocked?'Measured depth':'No veto reported'],
75
+ ['Own-body predictions',`${diagnostic?.ignored_current_body_cell_count||0} excluded from learned veto`],
76
+ ['Blocking cells',cells.length?`${diagnostic.blocking_cell_count} cells · ${supported}/${cells.length} shown cells have nearby depth returns`:'No blocking cells reported'],
77
+ ['Last relay velocity',state.robot?.v==null?'Unavailable':`${state.robot.v.toFixed(3)} m/s · ${(state.robot.w||0).toFixed(3)} rad/s`],
78
+ ['Handoff gate',state.ready?'Ready for explicit Start':state.gate],
79
+ ['Plan age limit',`${state.max_plan_age_s||.8} s · 0.3 s command expiry`],
80
+ ['Blind-zone fallback',f.blind_zone?'Assumed support used':'Not used'],
81
+ ['Inference',`${f.n_views||0} views · ${(f.compute_s||0).toFixed(2)} s`],
82
+ ['Goal arrival','Neutral camera XY within 0.4 m; heading not enforced'],
83
+ [state.playback?'Recorded phase':'Run state',state.playback?state.recorded_phase:state.phase]
84
+ ];
85
+ el('details').replaceChildren();
86
+ for(const [key,value]of rows){
87
+ const div=document.createElement('div'),dt=document.createElement('dt'),dd=document.createElement('dd');
88
+ dt.textContent=key;dd.textContent=value;div.append(dt,dd);el('details').append(div);
89
+ }
90
+ }
91
+ function showError(error){el('error').textContent=error.message||String(error);el('error').hidden=false;}
92
+ function clockText(seconds){const n=Math.max(0,Math.floor(seconds));return `${Math.floor(n/60).toString().padStart(2,'0')}:${(n%60).toString().padStart(2,'0')}`;}
93
+ async function render(next,force=false){
94
+ state=next;const recorded=Boolean(state.playback),f=state.frame||{};
95
+ el('phase').textContent=recorded?'REPLAY':state.phase.toUpperCase();
96
+ el('phase').style.color=state.phase==='active'&&!recorded?'#72dec0':'#f3c77c';
97
+ el('page-title').textContent=recorded?'Navigation replay':'Teleop → navigation';
98
+ document.title=recorded?'Recorded Stretch navigation':state.review?'Saved Stretch navigation run':'Live Stretch navigation';
99
+ el('handoff-note').hidden=Boolean(state.review||recorded);
100
+ el('page-footer').textContent=recorded||state.review?'Saved RGB, map and BEV · robot motion controls disabled':
101
+ 'Live RGB + odometry · trained occupancy/observability heads · phone map preserved';
102
+ el('rgb-label').textContent=recorded||state.review?'RECORDED HEAD RGB':'LIVE ROBOT RGB';
103
+ el('goal').textContent=state.goal_keyframe;el('start').textContent=`Start navigation to ${state.goal_keyframe}`;
104
+ el('start').disabled=recorded||!state.ready;el('stop').disabled=recorded||state.phase==='stopped';
105
+ el('replay-open').disabled=liveState?.phase!=='stopped'||liveState?.replay_available===false;
106
+ el('replay-open').textContent=recorded?'Restart replay':'Replay recording';
107
+ el('count').textContent=state.processed;el('commands').textContent=state.motion_commands;
108
+ el('state-title').textContent=recorded?`Replay · recorded ${state.recorded_phase}`:
109
+ ({teleop:state.ready?'Ready for navigation handoff':'Teleop / relocalizing',preparing:'Preparing navigation',active:'CROSS navigation active',stopped:'Run stopped'})[state.phase];
110
+ el('reason').textContent=state.reason;
111
+ el('distance').textContent=f.goal_distance==null?'—':`${f.goal_distance.toFixed(2)} m`;
112
+ el('localization').textContent=f.localized?`Committed · streak ${f.localized_streak}`:'Localization pending';
113
+ el('route').textContent=f.route_ids?.length?`${f.route_ids.length} route keyframes · ${f.route_cost_m?.toFixed(1)} m graph route`:'Graph route pending';
114
+ if(recorded){
115
+ el('rgb').src=state.replay.rgb_url;
116
+ el('frame-note').textContent=`RGB frame ${state.replay.frame_idx} · map frame ${state.replay.map_frame??'pending'} · ${clockText(state.replay.time_s)}`;
117
+ }else if(state.capture_frame!=null){
118
+ el('rgb').src=`/api/rgb.jpg?t=${Date.now()}`;
119
+ el('frame-note').textContent=state.review?'Saved RGB · robot connections disabled':`Latest RGB · processed frame ${f.frame_idx??'pending'}`;
120
+ }
121
+ details();const key=`${recorded?replay.run:'current'}:${f.frame_idx}:${state.replay?.bev_frame??''}`;
122
+ if(force||drawn!==key){
123
+ drawn=key;
124
+ const provenance=recorded?(state.replay.bev_source==='reconstructed'?' · reconstructed offline':state.replay.bev_frame!=null?' · recorded':' · no BEV saved yet'):'';
125
+ el('plan-note').textContent=f.bev_size?`${f.bev_size*f.bev_res} × ${f.bev_size*f.bev_res} m · base frame · ${f.planner_name}${provenance}`:'Waiting for learned BEV';
126
+ drawBEV();await drawMap();
127
+ }
128
+ }
129
+ async function poll(){
130
+ if(polling)return;polling=true;
131
+ try{
132
+ const next=await api('/api/status');liveState=next;
133
+ if(replay.active&&next.phase!=='stopped'){
134
+ pauseReplay();replay.active=false;replay.pending=null;replay.generation++;
135
+ el('replay-panel').hidden=true;map=null;drawn=-1;
136
+ }
137
+ if(!map)map=await api('/api/map');
138
+ if(!replay.active)await render(next);
139
+ if(!replay.active&&next.phase!=='stopped')await api('/api/heartbeat',{});
140
+ el('error').hidden=true;
141
+ }catch(error){showError(error);el('start').disabled=true;}
142
+ finally{polling=false;}
143
+ }
144
+ function pauseReplay(){replay.playing=false;el('replay-play').textContent='Play';}
145
+ function playReplay(){
146
+ if(!replay.active||!replay.manifest?.frames.length)return;
147
+ if(replay.index>=replay.manifest.frames.length-1)requestReplayFrame(0);
148
+ replay.anchorTime=replay.manifest.frames[replay.index].time_s;replay.anchorWall=performance.now();
149
+ replay.playing=true;el('replay-play').textContent='Pause';
150
+ }
151
+ function updateReplayControls(){
152
+ const m=replay.manifest;if(!m)return;
153
+ el('replay-seek').value=replay.index;
154
+ el('replay-clock').textContent=`${clockText(m.frames[replay.index]?.time_s||0)} / ${clockText(m.duration_s)}`;
155
+ el('replay-prev').disabled=replay.index<=0;el('replay-next').disabled=replay.index>=m.frames.length-1;
156
+ const b=state?.replay;
157
+ const note=b?.bev_frame==null?'No occupancy has been saved by this point.':
158
+ `BEV frame ${b.bev_frame} · ${b.bev_source==='reconstructed'?'reconstructed offline from recorded input':'recorded during the run'} · age ${Math.max(0,b.time_s-b.bev_time_s).toFixed(2)} s.`;
159
+ el('replay-note').textContent=`${m.frames.length} RGB frames · ${m.bev_frames} saved BEVs · motion controls disabled. ${note}${replay.index===m.frames.length-1?' Outcome: '+m.outcome:''}`;
160
+ }
161
+ async function requestReplayFrame(index){
162
+ if(!replay.active||!replay.manifest?.frames.length)return;
163
+ replay.index=Math.max(0,Math.min(replay.manifest.frames.length-1,index));
164
+ replay.pending=replay.index;updateReplayControls();
165
+ if(replay.busy)return;
166
+ replay.busy=true;const generation=replay.generation;
167
+ try{
168
+ while(replay.active&&generation===replay.generation&&replay.pending!==null){
169
+ const wanted=replay.pending;replay.pending=null;
170
+ const data=await api(`/api/replay/frame?run=${encodeURIComponent(replay.run)}&index=${wanted}`);
171
+ if(!replay.active||generation!==replay.generation)break;
172
+ if(replay.pending!==null&&replay.pending!==wanted)continue;
173
+ await render(data);updateReplayControls();
174
+ }
175
+ }catch(error){pauseReplay();showError(error);}
176
+ finally{
177
+ replay.busy=false;
178
+ if(replay.active&&replay.pending!==null)requestReplayFrame(replay.pending);
179
+ }
180
+ }
181
+ async function loadReplay(run,autoplay=true){
182
+ pauseReplay();const generation=++replay.generation;replay.pending=null;replay.run=run;
183
+ const manifest=await api(`/api/replay/manifest?run=${encodeURIComponent(run)}`);
184
+ if(generation!==replay.generation)return;replay.manifest=manifest;
185
+ if(!replay.manifest.frames.length)throw Error('This recording has no saved RGB frames');
186
+ const savedMap=await api(`/api/replay/map?run=${encodeURIComponent(run)}`);
187
+ if(generation!==replay.generation)return;map=savedMap;drawn=-1;
188
+ el('replay-seek').max=replay.manifest.frames.length-1;
189
+ el('replay-event').replaceChildren(new Option('Jump to event…',''));
190
+ for(const event of replay.manifest.events)el('replay-event').add(new Option(`${clockText(event.time_s)} · ${event.label}`,event.index));
191
+ replay.active=true;el('replay-run').value=run;el('replay-panel').hidden=false;
192
+ await requestReplayFrame(replay.manifest.start_index);if(autoplay)playReplay();
193
+ }
194
+ async function openReplay(){
195
+ if(liveState?.phase!=='stopped')return;
196
+ try{
197
+ const listing=await api('/api/replay/runs');
198
+ el('replay-run').replaceChildren();
199
+ for(const run of listing.runs)el('replay-run').add(new Option(run.id,run.id));
200
+ const key=listing.runs.find(r=>r.id===replay.run)?.id||listing.current_run||listing.runs[0]?.id;
201
+ if(!key)throw Error('No completed recordings are available yet');
202
+ el('replay-run').value=key;await loadReplay(key);
203
+ }catch(error){showError(error);}
204
+ }
205
+ async function closeReplay(){
206
+ pauseReplay();replay.active=false;replay.pending=null;replay.generation++;
207
+ el('replay-panel').hidden=true;map=await api('/api/map');drawn=-1;await render(liveState,true);
208
+ }
209
+ setInterval(()=>{
210
+ if(!replay.active||!replay.playing)return;
211
+ const m=replay.manifest,target=replay.anchorTime+(performance.now()-replay.anchorWall)/1000*Number(el('replay-speed').value);
212
+ let low=0,high=m.frames.length;
213
+ while(low<high){const mid=(low+high)>>1;if(m.frames[mid].time_s<=target)low=mid+1;else high=mid;}
214
+ const index=Math.max(0,low-1);if(index!==replay.index)requestReplayFrame(index);
215
+ if(target>=m.duration_s)pauseReplay();
216
+ },80);
217
+ el('start').onclick=async()=>{if(replay.active)return;el('start').disabled=true;try{await api('/api/start',{});await poll();}catch(e){el('error').textContent=e.message;el('error').hidden=false;}};
218
+ el('stop').onclick=async()=>{if(replay.active)return;try{await api('/api/stop',{});await poll();}catch(e){el('error').textContent=e.message;el('error').hidden=false;}};
219
+ el('layer').onchange=drawBEV;
220
+ el('bev-range').onchange=drawBEV;
221
+ el('top').onclick=()=>Plotly.relayout(el('global-map'),{'scene.camera':{eye:{x:0,y:0,z:2.7},up:{x:0,y:1,z:0}}});el('reset').onclick=()=>Plotly.relayout(el('global-map'),{'scene.camera':initial});
222
+ document.querySelectorAll('[data-layer]').forEach(input=>input.onchange=()=>{if(!plotReady)return;const plot=el('global-map'),ids=plot.data.map((t,i)=>t.meta?.layer===input.dataset.layer?i:-1).filter(i=>i>=0);Plotly.relayout(plot,{'scene.camera':plot._fullLayout.scene._scene.getCamera()}).then(()=>Plotly.restyle(plot,{visible:input.checked},ids));});
223
+ el('export').onclick=()=>{const url=URL.createObjectURL(new Blob([JSON.stringify(state,null,2)],{type:'application/json'})),a=document.createElement('a');a.href=url;a.download='stretch-cross-live.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
224
+ el('replay-open').onclick=openReplay;
225
+ el('replay-close').onclick=()=>closeReplay().catch(showError);
226
+ el('replay-run').onchange=()=>loadReplay(el('replay-run').value).catch(showError);
227
+ el('replay-play').onclick=()=>replay.playing?pauseReplay():playReplay();
228
+ el('replay-prev').onclick=()=>{pauseReplay();requestReplayFrame(replay.index-1);};
229
+ el('replay-next').onclick=()=>{pauseReplay();requestReplayFrame(replay.index+1);};
230
+ el('replay-seek').oninput=()=>{pauseReplay();requestReplayFrame(Number(el('replay-seek').value));};
231
+ el('replay-event').onchange=()=>{if(el('replay-event').value!==''){pauseReplay();requestReplayFrame(Number(el('replay-event').value));}};
232
+ el('replay-speed').onchange=()=>{if(replay.playing)playReplay();};
233
+ poll();setInterval(poll,650);
cases/20261026_goal1012_05/code/lite3_ROS/web_console/static/vendor/plotly.min.js ADDED
The diff for this file is too large to render. See raw diff
 
cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_control.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Execution gates and transforms for the live Stretch/CROSS adapter, without I/O."""
2
+ import math
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+
8
+ DEFAULT_MAX_PLAN_AGE = 2.0
9
+ DEFAULT_PLAN_HOLD_SECONDS = 8.0
10
+ HEAD_VIEW_TIMEOUT = 20.0
11
+ HEAD_SURVEY_TIMEOUT = 120.0
12
+
13
+
14
+ def wrap(angle):
15
+ return math.atan2(math.sin(angle), math.cos(angle))
16
+
17
+
18
+ def alignment_correction(previous, current, base):
19
+ """Map-pose correction at the current base, independent of the odom origin.
20
+
21
+ Alignment translations describe the coordinate origin. A small rotation
22
+ about a distant robot can move that origin substantially without moving
23
+ the estimated robot position. Compare both alignments at the same base.
24
+ """
25
+ previous, current, base = [np.asarray(value, dtype=float) for value in (previous, current, base)]
26
+ if any(value.shape != (4, 4) or not np.isfinite(value).all() for value in (previous, current, base)):
27
+ raise ValueError('Invalid map alignment or base transform')
28
+ before, after = previous @ base, current @ base
29
+ distance = float(np.linalg.norm(after[:3, 3] - before[:3, 3]))
30
+ rotation = previous[:3, :3].T @ current[:3, :3]
31
+ angle = float(np.arccos(np.clip((np.trace(rotation) - 1.) / 2., -1., 1.)))
32
+ return distance, angle
33
+
34
+
35
+ def stationary_head_command(plan, robot, *, now, robot_received):
36
+ """Renew a bounded head-only observation from current robot feedback.
37
+
38
+ Its target, frozen odometry anchor and deadline still come from planning.
39
+ Renewing never changes that deadline, advances a view, or permits driving.
40
+ The returned frame ID is checked against source time by the existing relay.
41
+ """
42
+ if (not plan or not plan.get('observation_hold') or plan.get('head_target') is None
43
+ or plan.get('head_deadline') is None):
44
+ return None, ''
45
+ if plan.get('scan_w', 0.) != 0.:
46
+ return None, '' # Any base rotation still needs a fresh driving plan.
47
+ try:
48
+ deadline = float(plan['head_deadline'])
49
+ target = np.asarray(plan['head_target'], float)
50
+ anchor = np.asarray(plan['head_anchor'], float)
51
+ pose = np.asarray(robot['base_pose'], float)
52
+ joint = np.asarray(robot['joint_positions'], float)
53
+ status_age = now - robot_received
54
+ sensor_age, tf_age = float(robot['sensor_age']), float(robot['tf_age'])
55
+ frame_id = int(robot['frame_id'])
56
+ except (KeyError, TypeError, ValueError, OverflowError):
57
+ return None, 'head observation feedback unavailable'
58
+ if (not np.isfinite(deadline) or target.shape != (2,) or anchor.shape != (4, 4)
59
+ or not np.isfinite(target).all() or not np.isfinite(anchor).all()
60
+ or not -2.8 <= target[0] <= .65 or not -1.4 <= target[1] <= 0.):
61
+ return None, 'invalid head observation request'
62
+ if now >= deadline:
63
+ return None, 'head observation deadline expired'
64
+ if (pose.shape != (3,) or joint.ndim != 1 or len(joint) < 11
65
+ or not np.isfinite(pose).all() or not np.isfinite(joint).all()
66
+ or not np.isfinite([status_age, sensor_age, tf_age]).all()
67
+ or not 0. <= status_age <= .5 or not -.02 <= sensor_age + status_age < .75
68
+ or not -.02 <= tf_age + status_age < .5 or frame_id < 0):
69
+ return None, 'head observation feedback unavailable'
70
+ yaw = math.atan2(anchor[1, 0], anchor[0, 0])
71
+ if np.linalg.norm(pose[:2] - anchor[:2, 3]) > .05 or abs(wrap(pose[2] - yaw)) > math.radians(5):
72
+ # A directed corner look can follow a permitted base rotation. Hold
73
+ # until its next image supplies the updated pose/extrinsic. A survey
74
+ # has a confirmed stationary origin and must not re-anchor that way.
75
+ return None, ('base moved during head observation' if plan.get('stationary_survey') else
76
+ 'head observation feedback unavailable')
77
+ if robot.get('head_enabled') is not True:
78
+ return None, 'leased head control unavailable'
79
+ return {'frame_id': frame_id, 'head_target': target.tolist(), 'v': 0., 'w': 0.}, ''
80
+
81
+
82
+ def execution_gate(plan, robot, *, now, robot_received, heartbeat, state='active',
83
+ max_plan_age=DEFAULT_MAX_PLAN_AGE):
84
+ """Require fresh planning evidence and CROSS's stable map commitment.
85
+
86
+ CROSS carries its committed pose through map-match gaps using odometry.
87
+ Retrieval verification is diagnostic, not a separate execution deadline.
88
+ The PC plan-age gate starts at receipt. Independently, the robot lease
89
+ validates full source-image age, including transport and compute time.
90
+ A bounded stationary head target instead uses current sensor/TF/joint
91
+ feedback; it cannot authorize base movement or mark a view as settled.
92
+ """
93
+ if state not in ('preparing', 'active'):
94
+ return 'teleop owns control'
95
+ if now - heartbeat > 5.:
96
+ return 'viewer heartbeat expired'
97
+ if robot is None or now - robot_received > .5:
98
+ return 'robot status stale'
99
+ if robot.get('is_runstopped') is not False or robot.get('is_homed') is not True:
100
+ return 'robot run-stopped or unhomed'
101
+ if not robot.get('posture_ok'):
102
+ return 'arm must already be retracted'
103
+ if robot.get('latched'):
104
+ return 'robot stop latched'
105
+ if robot.get('head_error'):
106
+ return 'head observation fault: ' + str(robot['head_error'])
107
+ if state == 'active' and not robot.get('healthy'):
108
+ return 'robot state/camera/TF unavailable'
109
+ if plan is None:
110
+ return 'sensor/plan evidence stale'
111
+ if not np.isfinite([plan['input_received'], plan.get('goal_distance', math.nan)]).all():
112
+ return 'invalid plan timing or goal'
113
+ head_only = (plan.get('observation_hold') and plan.get('head_target') is not None
114
+ and plan.get('head_deadline') is not None and plan.get('scan_w', 0.) == 0.)
115
+ if not head_only and now - plan['input_received'] > max_plan_age:
116
+ return 'sensor/plan evidence stale'
117
+ if not plan.get('localized') or plan.get('localized_streak', 0) < 3:
118
+ return 'waiting for stable committed localization'
119
+ if plan.get('recovery_pending'):
120
+ return 'map correction recovery'
121
+ if plan.get('arrived') and now - plan['input_received'] <= max_plan_age:
122
+ return 'goal reached'
123
+ head_command, head_fault = stationary_head_command(plan, robot, now=now, robot_received=robot_received)
124
+ if head_fault:
125
+ return head_fault
126
+ if head_command is not None:
127
+ return ''
128
+ if now - plan['input_received'] > max_plan_age:
129
+ return 'sensor/plan evidence stale'
130
+ if not plan.get('route_ids'):
131
+ return 'no global route'
132
+ if plan.get('observation_hold'):
133
+ if plan.get('head_target') is not None and robot.get('head_enabled') is not True:
134
+ return 'leased head control unavailable'
135
+ return ''
136
+ if plan.get('planner_status') == 2 and plan.get('scan_authorized'):
137
+ return ''
138
+ if plan.get('planner_status') == 2 or len(plan.get('path_odom', [])) < 2:
139
+ return 'no executable local path'
140
+ return ''
141
+
142
+
143
+ @dataclass
144
+ class PlanWait:
145
+ """Hold at zero through a short perception gap, without re-arming the lease.
146
+
147
+ Physical faults and lost localization never qualify for a transient hold.
148
+ A brief missing status stream also permits only zero velocity. An active
149
+ run can continue only after fresh robot status and its current plan pass
150
+ the full gate again. Sustained gaps end the run.
151
+ """
152
+ timeout: float = DEFAULT_PLAN_HOLD_SECONDS
153
+ since: float | None = None
154
+
155
+ def holds(self, reason, now):
156
+ if reason not in ('sensor/plan evidence stale', 'no executable local path', 'robot status stale',
157
+ 'head observation feedback unavailable'):
158
+ self.since = None
159
+ return False
160
+ if self.since is None:
161
+ self.since = now
162
+ return now - self.since < self.timeout
163
+
164
+
165
+ def competing_controllers(proc_root='/proc'):
166
+ """Identify known local base clients that publish even while their keys are up."""
167
+ found = []
168
+ for entry in Path(proc_root).iterdir():
169
+ if not entry.name.isdecimal():
170
+ continue
171
+ try:
172
+ args = (entry / 'cmdline').read_bytes().split(b'\0')
173
+ words = [a.decode(errors='replace') for a in args if a]
174
+ except (OSError, PermissionError):
175
+ continue
176
+ if not words or not Path(words[0]).name.startswith('python'):
177
+ continue
178
+ for word in words[1:]:
179
+ if (Path(word).name in ('teleop.py', 'manual_teleop.py', 'depth_nav_live.py')
180
+ or word == 'stretch.app.manual_teleop'):
181
+ found.append({'pid': int(entry.name), 'client': Path(word).name})
182
+ break
183
+ return found
184
+
185
+
186
+ def remaining_path(path_world, pose):
187
+ """Trim a saved odom path at the nearest segment and return forward/left."""
188
+ points = np.asarray(path_world, dtype=float).reshape(-1, 2)
189
+ pose = np.asarray(pose, dtype=float)
190
+ if len(points) < 2 or not np.isfinite(points).all() or not np.isfinite(pose).all():
191
+ return np.empty((0, 2))
192
+ delta = np.diff(points, axis=0)
193
+ t = np.clip(np.sum((pose[:2] - points[:-1]) * delta, axis=1)
194
+ / np.maximum(np.sum(delta ** 2, axis=1), 1e-9), 0., 1.)
195
+ projected = points[:-1] + t[:, None] * delta
196
+ k = int(np.argmin(np.linalg.norm(projected - pose[:2], axis=1)))
197
+ ahead = np.vstack([projected[k], points[k + 1:]]) - pose[:2]
198
+ c, s = np.cos(pose[2]), np.sin(pose[2])
199
+ return ahead @ np.array([[c, -s], [s, c]])
200
+
201
+
202
+ def depth_obstacles(depth, K, camera, base_z=0.):
203
+ """Current measured returns for a short-horizon veto, separate from CROSS planning."""
204
+ depth, K, camera = map(np.asarray, (depth, K, camera))
205
+ vv, uu = np.mgrid[0:depth.shape[0]:3, 0:depth.shape[1]:3]
206
+ z = depth[::3, ::3]
207
+ valid = np.isfinite(z) & (z > .12) & (z < 3.)
208
+ if valid.sum() < 100:
209
+ raise ValueError('insufficient measured depth for execution guard')
210
+ z, uu, vv = z[valid], uu[valid], vv[valid]
211
+ pc = np.column_stack([(uu - K[0, 2]) * z / K[0, 0],
212
+ (vv - K[1, 2]) * z / K[1, 1], z])
213
+ world = pc @ camera[:3, :3].T + camera[:3, 3]
214
+ return world[(world[:, 2] > base_z + .12) & (world[:, 2] < base_z + 1.8), :2]
215
+
216
+
217
+ def depth_veto(points_world, pose, v, w, *, horizon=1., half_width=.23, half_length=.23):
218
+ """Veto a 1 s swept rectangle when measured points intersect it.
219
+
220
+ The starting footprint is excluded as a robot self mask. This is a veto of
221
+ known returns, not evidence that unobserved near-field space is free.
222
+ """
223
+ points, pose = np.asarray(points_world), np.asarray(pose)
224
+ c, s = np.cos(pose[2]), np.sin(pose[2])
225
+ local = (points - pose[:2]) @ np.array([[c, -s], [s, c]])
226
+ local = local[(np.abs(local[:, 0]) > .20) | (np.abs(local[:, 1]) > .20)]
227
+ for t in np.linspace(0., horizon, 16):
228
+ theta = w * t
229
+ center = np.array([v * t, 0.]) if abs(w) < 1e-6 else np.array([
230
+ v / w * np.sin(theta), v / w * (1. - np.cos(theta))])
231
+ c, s = np.cos(theta), np.sin(theta)
232
+ relative = (local - center) @ np.array([[c, -s], [s, c]])
233
+ inside = (np.abs(relative[:, 0]) <= half_length) & (np.abs(relative[:, 1]) <= half_width)
234
+ if inside.sum() >= 3:
235
+ return True
236
+ return False
237
+
238
+
239
+ def attachment_clear(points_world, pose, target_xy):
240
+ """Reject a straight local attachment intersecting measured obstacle returns.
241
+
242
+ Use the execution guard's footprint and robot self mask. Unknown space is
243
+ left to the native local planner; this check only vetoes measured returns.
244
+ """
245
+ points, pose, target = map(np.asarray, (points_world, pose, target_xy))
246
+ if not all(np.isfinite(value).all() for value in (points, pose, target)):
247
+ raise ValueError('Invalid attachment geometry')
248
+ c, s = np.cos(pose[2]), np.sin(pose[2])
249
+ rotation = np.array([[c, -s], [s, c]])
250
+ local = (points - pose[:2]) @ rotation
251
+ local = local[(np.abs(local[:, 0]) > .20) | (np.abs(local[:, 1]) > .20)]
252
+ end = (target - pose[:2]) @ rotation
253
+ steps = max(2, int(np.ceil(np.linalg.norm(end) / .025)) + 1)
254
+ for fraction in np.linspace(0., 1., steps):
255
+ relative = local - fraction * end
256
+ inside = (np.abs(relative[:, 0]) <= .23) & (np.abs(relative[:, 1]) <= .23)
257
+ if inside.sum() >= 3:
258
+ return False
259
+ return True
cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_footprint.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Explain the learned command-footprint veto without changing its thresholds."""
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+
7
+
8
+ def command_footprint_report(grid, planning_base, pose, v, w, horizon=1.0, max_cells=12):
9
+ """Use the execution guard's exact sweep; return its first blocking cells.
10
+
11
+ Cell centres are reported in the planning base and continuous odom frames.
12
+ Learned predictions under the image-time body are excluded, matching native
13
+ cross_nav's own-footprint rule. Newly swept space and the separate measured
14
+ depth veto retain their checks. Ignored predictions remain in diagnostics.
15
+ """
16
+ prob, obs = np.asarray(grid["prob"]), np.asarray(grid["obs"])
17
+ n, res = len(prob), float(grid["res"])
18
+ if prob.shape != (n, n) or obs.shape != prob.shape or res <= 0:
19
+ raise ValueError("Invalid command footprint grid")
20
+ offsets = np.array(np.meshgrid(np.linspace(-0.23, 0.23, 11), np.linspace(-0.23, 0.23, 11))).reshape(2, -1).T
21
+ yaw = math.atan2(planning_base[1, 0], planning_base[0, 0])
22
+ c, s = math.cos(yaw), math.sin(yaw)
23
+ world_to_plan = np.array([[c, -s], [s, c]])
24
+ c, s = math.cos(pose[2]), math.sin(pose[2])
25
+ world_to_robot = np.array([[c, -s], [s, c]])
26
+ ignored = set()
27
+
28
+ def cells_at(indices):
29
+ cells = []
30
+ for row, col in indices:
31
+ body_xy = (n / 2 - np.array([row, col]) - 0.5) * res
32
+ point = body_xy @ world_to_plan.T + planning_base[:2, 3]
33
+ cells.append({
34
+ "row": int(row), "column": int(col), "grid_body_xy": body_xy.tolist(),
35
+ "world_xy": point.tolist(), "probability": float(prob[row, col]),
36
+ "observability": float(obs[row, col]),
37
+ "uncertainty": float(grid["err"][row, col]) if "err" in grid else None,
38
+ })
39
+ return cells
40
+
41
+ def result(clear, reason, blocked=(), t=None):
42
+ return {"clear": clear, "reason": reason, "sweep_time_s": t,
43
+ "blocking_cell_count": len(blocked), "cells": cells_at(blocked[:max_cells]),
44
+ "ignored_current_body_cell_count": len(ignored),
45
+ "self_cells": cells_at(sorted(ignored)[:min(4, max_cells)])}
46
+
47
+ for t in np.linspace(0.0, horizon, 16):
48
+ angle = w * t
49
+ center = (
50
+ np.array([v * t, 0.0])
51
+ if abs(w) < 1e-6
52
+ else np.array([v / w * math.sin(angle), v / w * (1.0 - math.cos(angle))])
53
+ )
54
+ c, s = math.cos(angle), math.sin(angle)
55
+ local = offsets @ np.array([[c, s], [-s, c]]) + center
56
+ world = local @ world_to_robot.T + pose[:2]
57
+ fl = (world - planning_base[:2, 3]) @ world_to_plan
58
+ rc = np.floor(n / 2 - fl / res).astype(int)
59
+ if ((rc < 0) | (rc >= n)).any():
60
+ return result(False, "outside learned grid", t=float(t))
61
+ occupied = (prob[rc[:, 0], rc[:, 1]] > 0.6) & (obs[rc[:, 0], rc[:, 1]] > 0.5)
62
+ centres = (n / 2 - rc - 0.5) * res
63
+ # Freeze this exemption at the image-time planning base. Moving into
64
+ # a predicted obstacle after that image must never mask the obstacle.
65
+ own_body = (np.abs(centres) <= 0.23).all(1)
66
+ ignored.update(map(tuple, rc[occupied & own_body]))
67
+ if (occupied & ~own_body).any():
68
+ blocked = np.unique(rc[occupied & ~own_body], axis=0)
69
+ return result(False, "learned occupancy", blocked, float(t))
70
+ return result(True, "clear")
71
+
72
+
73
+ def depth_support(report, points_world):
74
+ """Label nearby measured returns; absence of returns is not free-space proof."""
75
+ points = np.asarray(points_world, float).reshape(-1, 2)
76
+ def support(cells):
77
+ result = []
78
+ for cell in cells:
79
+ distances = np.linalg.norm(points - cell["world_xy"], axis=1)
80
+ count = int((distances <= 0.10).sum())
81
+ result.append({**cell, "nearby_depth_returns": count, "depth_supported": count >= 3,
82
+ "nearest_depth_return_m": float(distances.min()) if len(distances) else None})
83
+ return result
84
+ cells = support(report["cells"])
85
+ return {**report, "cells": cells, "self_cells": support(report.get("self_cells", [])),
86
+ "depth_supported_cells": sum(c["depth_supported"] for c in cells),
87
+ "depth_note": "Nearby obstacle returns only; no returns does not establish free space"}
cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_geometry.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Measured-depth BEV baseline for passive CROSS planner inspection.
2
+
3
+ This is explicitly not CROSS's learned occupancy or observability head. Floor
4
+ height is an odometry-frame prior. The output probabilities are fixed planning
5
+ encodings, not calibrated predictions or proof of safe execution.
6
+ """
7
+ import cv2
8
+ import numpy as np
9
+
10
+
11
+ def body_yaw(transform):
12
+ return float(np.arctan2(transform[1, 0], transform[0, 0]))
13
+
14
+
15
+ def body_to_world(points, base):
16
+ yaw = body_yaw(base)
17
+ rotation = np.array([[np.cos(yaw), -np.sin(yaw)], [np.sin(yaw), np.cos(yaw)]])
18
+ return np.asarray(points) @ rotation.T + base[:2, 3]
19
+
20
+
21
+ def world_to_body(point, base):
22
+ yaw = body_yaw(base)
23
+ rotation = np.array([[np.cos(yaw), -np.sin(yaw)], [np.sin(yaw), np.cos(yaw)]])
24
+ return (np.asarray(point)[:2] - base[:2, 3]) @ rotation
25
+
26
+
27
+ def measured_bev(depth, K, camera, base, *, size=200, res=.05, max_depth=3.,
28
+ floor_z=0., obstacle_min=.2, obstacle_max=1.6):
29
+ """Robot-centered (rows forward, columns right) occupancy encoding and visibility.
30
+
31
+ Floor visibility is tested against the current depth image, including
32
+ occlusion. Elevated returns set occupancy directly. Unobserved cells stay
33
+ unknown. Actual base/camera transforms account for head pan, tilt and offset.
34
+ """
35
+ depth = np.asarray(depth, dtype=float)
36
+ K, camera, base = [np.asarray(value, dtype=float) for value in (K, camera, base)]
37
+ if depth.ndim != 2 or K.shape != (3, 3) or camera.shape != (4, 4) or base.shape != (4, 4):
38
+ raise ValueError('Invalid depth or calibrated transforms')
39
+ if not np.isfinite(np.r_[K.ravel(), camera.ravel(), base.ravel(), floor_z]).all():
40
+ raise ValueError('Nonfinite geometry')
41
+ rr, cc = np.mgrid[:size, :size]
42
+ fl = np.stack([(size / 2 - rr - .5) * res, (size / 2 - cc - .5) * res], -1)
43
+ xy = body_to_world(fl.reshape(-1, 2), base)
44
+ ground = np.column_stack([xy, np.full(len(xy), floor_z)])
45
+ ground_camera = (ground - camera[:3, 3]) @ camera[:3, :3]
46
+ z = ground_camera[:, 2]
47
+ forward = (z > .1) & (z <= max_depth)
48
+ denominator = np.where(forward, z, 1.)
49
+ u = np.rint(K[0, 0] * ground_camera[:, 0] / denominator + K[0, 2]).astype(int)
50
+ v = np.rint(K[1, 1] * ground_camera[:, 1] / denominator + K[1, 2]).astype(int)
51
+ h, w = depth.shape
52
+ inside = forward & (u >= 0) & (u < w) & (v >= 0) & (v < h)
53
+ sample = np.full(len(xy), np.nan)
54
+ sample[inside] = depth[v[inside], u[inside]]
55
+ visible = inside & np.isfinite(sample) & (sample > .1) & (sample <= max_depth)
56
+ visible &= sample >= z - .08
57
+ observed = visible.reshape(size, size).astype(np.float32)
58
+ probability = np.where(observed > 0, .01, .5).astype(np.float32)
59
+
60
+ vv, uu = np.mgrid[0:h:3, 0:w:3]
61
+ zz = depth[::3, ::3]
62
+ valid = np.isfinite(zz) & (zz > .1) & (zz <= max_depth)
63
+ zz, uu, vv = zz[valid], uu[valid], vv[valid]
64
+ pc = np.column_stack([(uu - K[0, 2]) * zz / K[0, 0],
65
+ (vv - K[1, 2]) * zz / K[1, 1], zz])
66
+ points = pc @ camera[:3, :3].T + camera[:3, 3]
67
+ height = points[:, 2] - floor_z
68
+ yaw = body_yaw(base)
69
+ d = points[:, :2] - base[:2, 3]
70
+ forward_xy = d[:, 0] * np.cos(yaw) + d[:, 1] * np.sin(yaw)
71
+ left_xy = -d[:, 0] * np.sin(yaw) + d[:, 1] * np.cos(yaw)
72
+ row = np.floor(size / 2 - forward_xy / res).astype(int)
73
+ col = np.floor(size / 2 - left_xy / res).astype(int)
74
+ in_grid = (row >= 0) & (row < size) & (col >= 0) & (col < size)
75
+ obstacle = ((height >= obstacle_min) & (height <= obstacle_max)) | (height < -.2)
76
+ selected = in_grid & obstacle
77
+ probability[row[selected], col[selected]] = .99
78
+ observed[row[selected], col[selected]] = 1.
79
+ heights = np.full((size, size), -np.inf, np.float32)
80
+ np.maximum.at(heights, (row[in_grid], col[in_grid]), height[in_grid])
81
+ return {'prob': probability, 'obs': observed, 'height': heights, 'res': res,
82
+ 'points_odom': points[::max(1, len(points) // 2500)],
83
+ 'source': 'measured_depth_geometry', 'floor_z_odom': float(floor_z),
84
+ 'occupied_cells': int((probability > .6).sum()),
85
+ 'observed_cells': int((observed > .5).sum())}
86
+
87
+
88
+ def bev_png(probability, observed, layer='occupancy'):
89
+ p, v = np.asarray(probability), np.asarray(observed)
90
+ image = np.full((*p.shape, 3), (33, 49, 64), np.uint8)
91
+ if layer == 'occupancy':
92
+ image[v > .5] = (63, 192, 159)
93
+ image[p > .6] = (239, 110, 105)
94
+ else:
95
+ image[v > .5] = (68, 166, 218)
96
+ success, encoded = cv2.imencode('.png', image[..., ::-1])
97
+ if not success:
98
+ raise OSError('Could not encode BEV')
99
+ return encoded.tobytes()
cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_learned.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Place native camera-centred CROSS BEVs in the recorded robot base frame."""
2
+ import cv2
3
+ import numpy as np
4
+
5
+ from .stretch_nav_geometry import body_yaw
6
+
7
+
8
+ def reproject_bev(prob, obs, err, rotation_bev_camera, camera, base, res):
9
+ """Resample at cell centres, preserving probabilities and unknown borders.
10
+
11
+ Native axes are right/forward/up at the camera. The planner consumes a grid
12
+ centred on the base, with rows forward and columns right of the base heading.
13
+ Both frames use recorded odom up; camera height therefore cancels in XY.
14
+ """
15
+ arrays = [np.asarray(a, dtype=np.float32) for a in (prob, obs, err)]
16
+ n = arrays[0].shape[0]
17
+ if any(a.shape != (n, n) or not np.isfinite(a).all() for a in arrays):
18
+ raise ValueError('Learned BEV layers must be finite matching square grids')
19
+ camera, base, rotation = map(np.asarray, (camera, base, rotation_bev_camera))
20
+ if not all(np.isfinite(a).all() for a in (camera, base, rotation)) or res <= 0:
21
+ raise ValueError('Invalid learned BEV transform or resolution')
22
+ yaw = body_yaw(base)
23
+ # Destination pixel (column, row) -> base forward/left -> odom -> camera BEV.
24
+ dst = np.array([[0., 0.], [n - 1., 0.], [0., n - 1.]], np.float32)
25
+ forward = (n / 2 - dst[:, 1] - .5) * res
26
+ left = (n / 2 - dst[:, 0] - .5) * res
27
+ world = np.column_stack([
28
+ base[0, 3] + np.cos(yaw) * forward - np.sin(yaw) * left,
29
+ base[1, 3] + np.sin(yaw) * forward + np.cos(yaw) * left,
30
+ np.full(3, camera[2, 3]),
31
+ ])
32
+ native = (world - camera[:3, 3]) @ camera[:3, :3] @ rotation.T
33
+ src = np.column_stack([native[:, 0] / res + n / 2 - .5,
34
+ n / 2 - native[:, 1] / res - .5]).astype(np.float32)
35
+ affine = cv2.getAffineTransform(dst, src)
36
+ warped = [cv2.warpAffine(a, affine, (n, n),
37
+ flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP, borderMode=cv2.BORDER_CONSTANT,
38
+ borderValue=border) for a, border in zip(arrays, (.5, 0., 1.))]
39
+ return {'prob': warped[0], 'obs': warped[1], 'err': warped[2],
40
+ 'base_pixel_to_camera_pixel': affine}
41
+
42
+
43
+ def learned_png(prob, obs, err, layer):
44
+ """Continuous, explicitly separate occupancy/observability/error scales."""
45
+ values = {'occupancy': prob, 'visibility': obs, 'uncertainty': err}[layer]
46
+ palette = {
47
+ 'occupancy': [(55, 183, 148), (222, 190, 96), (233, 91, 101)],
48
+ 'visibility': [(25, 42, 60), (48, 128, 182), (173, 226, 255)],
49
+ 'uncertainty': [(25, 42, 60), (155, 112, 70), (255, 174, 76)],
50
+ }[layer]
51
+ p = np.clip(np.asarray(values, dtype=np.float32), 0., 1.)
52
+ image = np.stack([np.interp(p, [0., .5, 1.], np.array(palette)[:, channel])
53
+ for channel in range(3)], axis=-1).astype(np.uint8)
54
+ success, encoded = cv2.imencode('.png', image[..., ::-1])
55
+ if not success:
56
+ raise OSError('Could not encode learned BEV')
57
+ return encoded.tobytes()
cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_recovery.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Odometry-frame recovery and corner observation for the Stretch adapter.
2
+
3
+ No hardware or CROSS imports. A moving head changes the observation transform,
4
+ never the neutral camera reference used to attach the base to the saved route.
5
+ """
6
+
7
+ import math
8
+ from collections import deque
9
+ from dataclasses import dataclass
10
+
11
+ import numpy as np
12
+
13
+ from .stretch_nav_control import HEAD_VIEW_TIMEOUT, alignment_correction, wrap
14
+ from .stretch_nav_geometry import world_to_body
15
+
16
+
17
+ def camera_in_base(camera, base):
18
+ """T_base_camera from the two TF poses at the *image* timestamp."""
19
+ camera, base = np.asarray(camera, float), np.asarray(base, float)
20
+ for value in (camera, base):
21
+ if value.shape != (4, 4) or not np.isfinite(value).all():
22
+ raise ValueError("Invalid timestamped camera/base TF")
23
+ if (
24
+ not np.allclose(value[3], [0, 0, 0, 1], atol=1e-5)
25
+ or not np.allclose(value[:3, :3].T @ value[:3, :3], np.eye(3), atol=1e-4)
26
+ or np.linalg.det(value[:3, :3]) < 0.99
27
+ ):
28
+ raise ValueError("Non-rigid camera/base TF")
29
+ return np.linalg.inv(base) @ camera
30
+
31
+
32
+ def camera_yaw(camera_base):
33
+ forward = np.asarray(camera_base)[:3, 2]
34
+ if np.linalg.norm(forward[:2]) < 0.2:
35
+ raise ValueError("Camera points too vertically for a corner scan")
36
+ return math.atan2(forward[1], forward[0])
37
+
38
+
39
+ def camera_pitch(camera_base):
40
+ forward = np.asarray(camera_base)[:3, 2]
41
+ if not np.isfinite(forward).all() or np.linalg.norm(forward) < 0.9:
42
+ raise ValueError("Invalid camera direction")
43
+ return math.atan2(forward[2], np.linalg.norm(forward[:2]))
44
+
45
+
46
+ def clear_goal_cache(episode):
47
+ """Discard goal-specific routes, retaining occupancy, bumps and metric scale."""
48
+ episode.route, episode.route_age = None, 0
49
+ episode.no_route, episode.side, episode.expect = 0, 0.0, 0.0
50
+
51
+
52
+ class MeasuredObstacleMemory:
53
+ """Short odometry-frame depth history, so a pan does not erase the front.
54
+
55
+ This veto retains known returns for 12 seconds. Native occupancy memory
56
+ remains separate; retained moving-object returns may delay a command.
57
+ """
58
+
59
+ def __init__(self, horizon=12.0):
60
+ self.horizon, self.frames = horizon, deque()
61
+ self.preserve_from = None
62
+
63
+ def observing(self, active, now):
64
+ """Keep pre-scan returns throughout a stationary survey and its exit."""
65
+ if active and self.preserve_from is None:
66
+ self.preserve_from = now - self.horizon
67
+ elif not active and self.preserve_from is not None:
68
+ if self.frames:
69
+ self.frames = deque([(now, np.vstack([p for _, p in self.frames]))])
70
+ self.preserve_from = None
71
+
72
+ def update(self, points, now, origin):
73
+ points = np.asarray(points, float).reshape(-1, 2)
74
+ if not np.isfinite(points).all():
75
+ raise ValueError("Nonfinite measured obstacle history")
76
+ if len(points):
77
+ cells, counts = np.unique(np.round(points / 0.02), axis=0, return_counts=True)
78
+ points = np.repeat(cells, np.minimum(counts, 3), axis=0) * 0.02
79
+ self.frames.append((now, points))
80
+ cutoff = now - self.horizon if self.preserve_from is None else self.preserve_from
81
+ while self.frames and self.frames[0][0] < cutoff:
82
+ self.frames.popleft()
83
+ combined = np.vstack([p for _, p in self.frames])
84
+ combined = combined[np.linalg.norm(combined - np.asarray(origin)[:2], axis=1) < 3.5]
85
+ cells, counts = np.unique(np.round(combined / 0.02), axis=0, return_counts=True)
86
+ return np.repeat(cells, np.minimum(counts, 3), axis=0) * 0.02
87
+
88
+
89
+ @dataclass
90
+ class CorrectionRecovery:
91
+ timeout: float = 12.0
92
+ pending: bool = False
93
+ since: float = 0.0
94
+ stable_since: float = 0.0
95
+ samples: int = 0
96
+ anchor: object = None
97
+
98
+ def update(self, previous, current, base, now):
99
+ """Hold after a large correction, then require a coherent new alignment.
100
+
101
+ Compare at the current base to avoid odom-origin artifacts. The anchor
102
+ also catches a succession of small corrections that add up to drift.
103
+ """
104
+ distance, angle = (0.0, 0.0) if previous is None else alignment_correction(previous, current, base)
105
+ large = distance > 0.5 or angle > math.radians(25)
106
+ started = large and not self.pending
107
+ if started:
108
+ self.pending, self.since = True, now
109
+ self.anchor, self.stable_since, self.samples = np.asarray(current).copy(), now, 0
110
+ if self.pending:
111
+ if now - self.since > self.timeout:
112
+ raise RuntimeError("Map pose correction did not settle within 12 s")
113
+ spread, turn = alignment_correction(self.anchor, current, base)
114
+ if large or distance > 0.12 or angle > math.radians(5) or spread > 0.20 or turn > math.radians(8):
115
+ self.anchor, self.stable_since, self.samples = np.asarray(current).copy(), now, 0
116
+ else:
117
+ self.samples += 1
118
+ if self.samples >= 3 and now - self.stable_since >= 0.6:
119
+ self.pending = False
120
+ return {
121
+ "started": started,
122
+ "large": large,
123
+ "pending": self.pending,
124
+ "distance_m": distance,
125
+ "rotation_deg": math.degrees(angle),
126
+ "deadline": self.since + self.timeout,
127
+ "stable_samples": self.samples,
128
+ }
129
+
130
+
131
+ def route_subgoal(route_xy, base, goal_xy, lookahead=1.5):
132
+ """Arc-length subgoal, stopping short of an upcoming sharp bend."""
133
+ xy = np.asarray(route_xy, float).reshape(-1, 2)
134
+ origin = np.asarray(base)[:2, 3]
135
+ if not len(xy):
136
+ xy = np.asarray(goal_xy, float)[None, :2]
137
+ xy = np.vstack([origin, xy])
138
+ xy = xy[np.r_[True, np.linalg.norm(np.diff(xy, axis=0), axis=1) > 0.03]]
139
+ if len(xy) == 1:
140
+ return {"target": xy[0], "corner": None}
141
+ arc = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(xy, axis=0), axis=1))]
142
+
143
+ def at(d):
144
+ return np.array([np.interp(d, arc, xy[:, k]) for k in (0, 1)])
145
+
146
+ # Sample over a finite baseline: adjacent camera poses alone give noisy
147
+ # curvature. Include the bend's actual location, rather than cutting it.
148
+ bends = []
149
+ for distance in np.arange(0.35, min(arc[-1] - 0.35, 1.8), 0.05):
150
+ if distance - 0.3 < arc[1]:
151
+ continue # The base->first-camera connector is not an aisle bend.
152
+ point = at(distance)
153
+ before, after = point - at(distance - 0.3), at(distance + 0.35) - point
154
+ angle = math.atan2(before[0] * after[1] - before[1] * after[0], np.dot(before, after))
155
+ if abs(angle) >= math.radians(40):
156
+ bends.append((abs(angle), distance, point, angle))
157
+ elif bends:
158
+ break # Only the first bend, not a sharper turn much farther away.
159
+ if bends:
160
+ _, distance, point, angle = max(bends, key=lambda v: v[0])
161
+ after = at(min(arc[-1], distance + 0.6)) - point
162
+ approach = at(max(0.0, distance - 0.30))
163
+ body_corner = world_to_body(point, base)
164
+ if abs(math.atan2(body_corner[1], body_corner[0])) > math.radians(30):
165
+ # The recorded camera trail may lie to one side of the base. Peek
166
+ # from the incoming aisle before asking for lateral displacement.
167
+ forward = base[:2, 0] / np.linalg.norm(base[:2, 0])
168
+ approach = origin + max(0.0, body_corner[0] - 0.30) * forward
169
+ return {
170
+ "target": approach,
171
+ "corner": point,
172
+ "outgoing": after / np.linalg.norm(after),
173
+ "angle_deg": math.degrees(angle),
174
+ }
175
+ return {"target": at(min(lookahead, arc[-1])), "corner": None}
176
+
177
+
178
+ def observed_branch(grid, base, corner, outgoing):
179
+ """Fraction of a short branch strip seen in the current learned BEV."""
180
+ p = np.asarray(corner) + np.linspace(0.1, 0.7, 7)[:, None] * np.asarray(outgoing)
181
+ lateral = np.array([-outgoing[1], outgoing[0]])
182
+ p = (p[:, None] + np.array([-0.15, 0.0, 0.15])[None, :, None] * lateral).reshape(-1, 2)
183
+ fl = np.array([world_to_body(v, base) for v in p])
184
+ n = len(grid["obs"])
185
+ rc = np.floor(n / 2 - fl / grid["res"]).astype(int)
186
+ inside = ((rc >= 0) & (rc < n)).all(1)
187
+ seen = np.zeros(len(p), bool)
188
+ seen[inside] = grid["obs"][rc[inside, 0], rc[inside, 1]] > 0.5
189
+ return float(seen.mean())
190
+
191
+
192
+ class CornerObserver:
193
+ """Approach -> look -> return -> advance; at most two short peeks.
194
+
195
+ Only processed, settled camera TF views count. The control thread keeps
196
+ zero base velocity for look/return, except a bounded, guarded scan rotation
197
+ when the desired view is outside the head's joint limits.
198
+ """
199
+
200
+ def __init__(self):
201
+ self.phase = "cruise"
202
+ self.corner = self.outgoing = self.approach = None
203
+ self.since = 0.0
204
+ self.count = self.peeks = 0
205
+ self.coverage = 0.0
206
+ self.view_coverages = []
207
+ self.previous_mount = None
208
+ self.done_at = None
209
+ self.scan_only = False
210
+ self.scan_cooldown = -math.inf
211
+
212
+ def reset(self):
213
+ self.__init__()
214
+
215
+ def restore_neutral(self, base, now):
216
+ """A correction may interrupt a scan with the head still turned."""
217
+ self.reset()
218
+ self.phase, self.since, self.scan_only = "return", now, True
219
+ self.corner = self.approach = base[:2, 3].copy()
220
+ self.outgoing = base[:2, 0].copy()
221
+
222
+ def update(self, hint, base, mount, neutral, joint, grid, now, *, no_route=False, force_observation=False):
223
+ target = hint["target"]
224
+ yaw = math.atan2(base[1, 0], base[0, 0])
225
+ origin = base[:2, 3]
226
+ result = {
227
+ "phase": self.phase,
228
+ "target": target,
229
+ "hold": False,
230
+ "head_target": None,
231
+ "scan_w": 0.0,
232
+ "coverage": self.coverage,
233
+ "speed_scale": 1.0,
234
+ "lookahead": 0.4,
235
+ }
236
+ if force_observation and self.phase == "advance":
237
+ self.phase, self.approach = "approach", origin.copy()
238
+ if self.phase == "advance":
239
+ if np.dot(origin - self.corner, self.outgoing) > 0.4 or np.linalg.norm(origin - self.done_at) > 1.0:
240
+ self.phase = "cruise"
241
+ else:
242
+ result.update(phase="advance", speed_scale=0.5, lookahead=0.22)
243
+ # Retain the bend as an intermediate waypoint until passed.
244
+ result["target"] = self.corner + 0.65 * self.outgoing
245
+ return result
246
+ if self.phase == "cruise":
247
+ if hint["corner"] is not None:
248
+ self.corner, self.outgoing = hint["corner"].copy(), hint["outgoing"].copy()
249
+ self.approach = target.copy()
250
+ self.phase, self.peeks, self.scan_only = "approach", 0, False
251
+ self.coverage = 0.0
252
+ elif no_route and now >= self.scan_cooldown:
253
+ direction = target - origin
254
+ if np.linalg.norm(direction) < 0.1:
255
+ return result
256
+ self.corner, self.outgoing = origin.copy(), direction / np.linalg.norm(direction)
257
+ self.approach = origin.copy()
258
+ self.phase, self.scan_only = "approach", True
259
+ self.coverage = 0.0
260
+ else:
261
+ return result
262
+ if self.phase == "approach":
263
+ if force_observation:
264
+ self.approach = origin.copy()
265
+ result.update(phase="approach", target=self.approach, speed_scale=0.5, lookahead=0.22)
266
+ if np.linalg.norm(origin - self.approach) > (0.04 if self.peeks else 0.16):
267
+ return result
268
+ self.phase, self.since, self.count = "look", now, 0
269
+ self.view_coverages = []
270
+ self.coverage = 0.0
271
+ self.previous_mount = None
272
+ if self.phase in ("look", "return"):
273
+ if now - self.since > HEAD_VIEW_TIMEOUT:
274
+ raise RuntimeError("Corner camera scan timed out; no unobserved advance")
275
+ joint = np.asarray(joint, float)
276
+ if len(joint) < 11 or not np.isfinite(joint).all():
277
+ raise ValueError("Head joint feedback unavailable for corner observation")
278
+ desired = (
279
+ wrap(math.atan2(self.outgoing[1], self.outgoing[0]) - yaw)
280
+ if self.phase == "look"
281
+ else camera_yaw(neutral)
282
+ )
283
+ error = wrap(desired - camera_yaw(mount))
284
+ pan = joint[9] + error
285
+ clamped = float(np.clip(pan, -2.8, 0.65))
286
+ tilt = joint[10]
287
+ if self.phase == "return":
288
+ tilt += camera_pitch(neutral) - camera_pitch(mount)
289
+ result.update(
290
+ phase=self.phase,
291
+ hold=True,
292
+ head_target=[clamped, float(np.clip(tilt, -1.4, 0.0))],
293
+ head_anchor=np.asarray(base).copy(),
294
+ head_deadline=self.since + HEAD_VIEW_TIMEOUT,
295
+ speed_scale=0.5,
296
+ lookahead=0.22,
297
+ target=self.approach,
298
+ )
299
+ # Head first. Base rotation is allowed only after the limited head
300
+ # position is reached; the independent footprint veto still applies.
301
+ if abs(pan - clamped) > 0.10 and abs(joint[9] - clamped) < 0.08:
302
+ result["scan_w"] = math.copysign(0.15, error)
303
+ settled = (
304
+ self.previous_mount is not None and np.linalg.norm(mount[:3, 3] - self.previous_mount[:3, 3]) < 0.005
305
+ )
306
+ if settled:
307
+ _, moved = alignment_correction(self.previous_mount, mount, np.eye(4))
308
+ settled = moved < math.radians(1)
309
+ self.previous_mount = mount.copy()
310
+ pitch_ready = self.phase != "return" or abs(camera_pitch(neutral) - camera_pitch(mount)) < math.radians(4)
311
+ self.count = self.count + 1 if settled and abs(error) < math.radians(6) and pitch_ready else 0
312
+ if self.phase == "look" and self.count:
313
+ self.view_coverages.append(observed_branch(grid, base, self.corner, self.outgoing))
314
+ self.view_coverages = self.view_coverages[-2:]
315
+ self.coverage = min(self.view_coverages)
316
+ if self.count >= 2:
317
+ if self.phase == "look":
318
+ self.phase, self.count, self.since = "return", 0, now
319
+ elif self.scan_only:
320
+ self.phase, self.scan_cooldown = "cruise", now + 12.0
321
+ elif self.coverage >= 0.5:
322
+ self.phase, self.done_at = "advance", origin.copy()
323
+ elif self.peeks < 2 and np.linalg.norm(self.corner - origin) > 0.14:
324
+ # A closer, short approach followed by another stationary
325
+ # look. Native planning + rectangle checks must clear it.
326
+ self.approach = origin + 0.12 * (self.corner - origin) / np.linalg.norm(self.corner - origin)
327
+ self.peeks += 1
328
+ self.phase = "approach"
329
+ else:
330
+ raise RuntimeError("Corner remains occluded after bounded peeks; reposition required")
331
+ self.previous_mount = None
332
+ result["coverage"] = self.coverage
333
+ return result
334
+
335
+
336
+ def rectangle_command_clear(grid, planning_base, pose, v, w, horizon=1.0):
337
+ """Actual 1 s swept square, including pure rotation, in the learned grid."""
338
+ from .stretch_nav_footprint import command_footprint_report
339
+
340
+ return command_footprint_report(grid, planning_base, pose, v, w, horizon, max_cells=0)["clear"]
341
+
342
+
343
+ def rectangle_path_clear(path, grid, half_width=0.23, half_length=0.23, horizon=1.2):
344
+ """Check an oriented swept body against observed learned occupancy.
345
+
346
+ Unknown is not relabelled free here. The native visibility planner handles
347
+ observation requests, while measured depth remains a separate hard veto.
348
+ """
349
+ path = np.vstack([[0.0, 0.0], np.asarray(path, float).reshape(-1, 2)])
350
+ if not np.isfinite(path).all():
351
+ return False
352
+ offsets = (
353
+ np.array(np.meshgrid(np.linspace(-half_length, half_length, 11), np.linspace(-half_width, half_width, 11)))
354
+ .reshape(2, -1)
355
+ .T
356
+ )
357
+ travelled, heading = 0.0, 0.0
358
+ n, res = len(grid["prob"]), grid["res"]
359
+ # Match native cross_nav: the robot already occupies this area. Keep the
360
+ # original prediction intact for diagnostics and for all newly swept cells.
361
+ probability = np.asarray(grid["prob"]).copy()
362
+ axis = (n / 2 - np.arange(n) - 0.5) * res
363
+ probability[(np.abs(axis[:, None]) <= half_length) & (np.abs(axis[None, :]) <= half_width)] = 0.0
364
+ for a, b in zip(path[:-1], path[1:]):
365
+ d = float(np.linalg.norm(b - a))
366
+ if d < 1e-5:
367
+ continue
368
+ yaw = math.atan2(*(b - a)[::-1])
369
+ for angle in np.linspace(heading, heading + wrap(yaw - heading), 8):
370
+ c, s = math.cos(angle), math.sin(angle)
371
+ points = offsets @ np.array([[c, s], [-s, c]]) + a
372
+ rc = np.floor(n / 2 - points / res).astype(int)
373
+ inside = ((rc >= 0) & (rc < n)).all(1)
374
+ if (
375
+ not inside.all()
376
+ or ((probability[rc[:, 0], rc[:, 1]] > 0.6) & (grid["obs"][rc[:, 0], rc[:, 1]] > 0.5)).any()
377
+ ):
378
+ return False
379
+ count = max(2, int(d / 0.04) + 1)
380
+ for t in np.linspace(0.0, min(1.0, max(0.0, horizon - travelled) / d), count):
381
+ c, s = math.cos(yaw), math.sin(yaw)
382
+ points = offsets @ np.array([[c, s], [-s, c]]) + a + t * (b - a)
383
+ rc = np.floor(n / 2 - points / res).astype(int)
384
+ inside = ((rc >= 0) & (rc < n)).all(1)
385
+ if (
386
+ not inside.all()
387
+ or ((probability[rc[:, 0], rc[:, 1]] > 0.6) & (grid["obs"][rc[:, 0], rc[:, 1]] > 0.5)).any()
388
+ ):
389
+ return False
390
+ travelled, heading = travelled + d, yaw
391
+ if travelled >= horizon:
392
+ break
393
+ return True
cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_replay.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Disk-backed, read-only playback of Stretch navigation recordings."""
2
+
3
+ import json
4
+ import math
5
+ from bisect import bisect_right
6
+ from pathlib import Path
7
+ from urllib.parse import urlencode
8
+
9
+ LAYERS = ("occupancy", "visibility", "uncertainty")
10
+
11
+
12
+ def save_bev_frame(directory, frame, images, *, source="recorded", only_missing=False):
13
+ """Commit already encoded layers together; meta.json marks a complete frame."""
14
+ if not isinstance(frame, int) or frame < 0 or source not in ("recorded", "reconstructed"):
15
+ raise ValueError("Invalid replay BEV frame")
16
+ root = Path(directory) / "replay" / "bev" / f"{frame:08d}"
17
+ if only_missing and (root / "meta.json").is_file():
18
+ return
19
+ if any(not isinstance(images.get(f"{name}.png"), bytes) for name in LAYERS):
20
+ raise ValueError("All three encoded BEV layers are required")
21
+ root.mkdir(parents=True, exist_ok=True)
22
+ for name in LAYERS:
23
+ path = root / f"{name}.png"
24
+ temporary = path.with_suffix(".png.tmp")
25
+ temporary.write_bytes(images[path.name])
26
+ temporary.replace(path)
27
+ path = root / "meta.json"
28
+ temporary = path.with_suffix(".json.tmp")
29
+ temporary.write_text(json.dumps({"frame_idx": frame, "source": source}) + "\n")
30
+ temporary.replace(path)
31
+ marker = root.parent.parent / "last_bev.json"
32
+ temporary = marker.with_suffix(".json.tmp")
33
+ temporary.write_text(json.dumps({"frame_idx": frame, "source": source}) + "\n")
34
+ temporary.replace(marker)
35
+
36
+
37
+ def read_rows(path):
38
+ """An in-flight last JSONL line may be incomplete; earlier corruption is an error."""
39
+ if not path.is_file():
40
+ return []
41
+ lines = path.read_text().splitlines(keepends=True)
42
+ rows = []
43
+ for index, line in enumerate(lines):
44
+ if not line.strip():
45
+ continue
46
+ try:
47
+ rows.append(json.loads(line))
48
+ except json.JSONDecodeError:
49
+ if index == len(lines) - 1 and not line.endswith("\n"):
50
+ break
51
+ raise
52
+ return rows
53
+
54
+
55
+ def confined(root, relative):
56
+ path = (root / relative).resolve()
57
+ if not path.is_relative_to(root):
58
+ raise ValueError("Replay asset escaped its recording")
59
+ return path
60
+
61
+
62
+ class ReplayArchive:
63
+ def __init__(self, directory):
64
+ self.root = Path(directory).resolve()
65
+ status = self.root / "final_status.json"
66
+ if not status.is_file():
67
+ status = self.root / "review.json"
68
+ self.base = json.loads(status.read_text())
69
+ if self.base.get("phase") != "stopped":
70
+ raise ValueError("Replay requires a stopped recording")
71
+ self.raw = read_rows(self.root / "capture/observations.jsonl")
72
+ self.raw_ids = [int(row["frame_idx"]) for row in self.raw]
73
+ self.raw_by_id = dict(zip(self.raw_ids, self.raw))
74
+ self.times = [float(row["relative_time_s"]) for row in self.raw]
75
+ if not all(math.isfinite(t) for t in self.times) or self.times != sorted(self.times):
76
+ raise ValueError("Invalid recording timeline")
77
+ if self.raw_ids != sorted(set(self.raw_ids)):
78
+ raise ValueError("Invalid recording frame order")
79
+ self.plans = read_rows(self.root / "observations.jsonl")
80
+ self.plan_ids = [row["frame_idx"] for row in self.plans]
81
+ if self.plan_ids != sorted(set(self.plan_ids)):
82
+ raise ValueError("Invalid recorded plan order")
83
+ self.controls = sorted(read_rows(self.root / "commands.jsonl"), key=lambda row: row["time_unix"])
84
+ self.control_times = [row["time_unix"] for row in self.controls]
85
+ self.robots = sorted(read_rows(self.root / "robot_status.jsonl"), key=lambda row: row["received_unix"])
86
+ self.robot_times = [row["received_unix"] for row in self.robots]
87
+ self.events = read_rows(self.root / "events.jsonl")
88
+ self.bevs = {}
89
+ for path in (self.root / "replay/bev").glob("*/meta.json"):
90
+ if not path.parent.name.isdecimal():
91
+ continue
92
+ index = int(path.parent.name)
93
+ if index not in self.raw_by_id:
94
+ continue
95
+ meta = json.loads(confined(self.root, path.relative_to(self.root)).read_text())
96
+ if all(confined(self.root, path.parent.relative_to(self.root) / f"{name}.png").is_file()
97
+ for name in LAYERS):
98
+ self.bevs[index] = {"path": path.parent.relative_to(self.root), "source": meta["source"]}
99
+ # Older sessions kept only the last displayed BEV. Never show it early.
100
+ last_bev = next((p for p in reversed(self.plans) if p.get("bev_size")), None)
101
+ if last_bev and last_bev["frame_idx"] not in self.bevs and all(
102
+ confined(self.root, Path("review_bev") / f"{name}.png").is_file() for name in LAYERS
103
+ ):
104
+ self.bevs[last_bev["frame_idx"]] = {"path": Path("review_bev"), "source": "recorded"}
105
+ self.bev_ids = sorted(self.bevs)
106
+
107
+ @staticmethod
108
+ def latest(rows, keys, value):
109
+ index = bisect_right(keys, value) - 1
110
+ return rows[index] if index >= 0 else None
111
+
112
+ def manifest(self):
113
+ received = [r.get("received_unix_s", -math.inf) for r in self.raw]
114
+ markers = []
115
+ start = 0
116
+ for event in self.events:
117
+ if not received:
118
+ break
119
+ if event['time_unix'] > received[-1] + 1.0:
120
+ continue # Exclude later review-server shutdown events.
121
+ index = max(0, min(len(self.raw) - 1, bisect_right(received, event["time_unix"]) - 1))
122
+ if event["type"] == "start_requested":
123
+ start = index
124
+ markers.append({"index": index, "time_s": self.times[index], "type": event["type"],
125
+ "label": event.get("reason", event["type"].replace("_", " "))})
126
+ return {
127
+ "run": self.root.name, "frames": [{"frame_idx": i, "time_s": t} for i, t in zip(self.raw_ids, self.times)],
128
+ "outcome": self.base.get("reason", "Run ended"),
129
+ "duration_s": self.times[-1] if self.times else 0.0, "start_index": start, "events": markers,
130
+ "bev_frames": len(self.bev_ids), "processed_frames": len(self.plans),
131
+ "recorded_bev_frames": sum(m["source"] == "recorded" for m in self.bevs.values()),
132
+ "reconstructed_bev_frames": sum(m["source"] == "reconstructed" for m in self.bevs.values()),
133
+ }
134
+
135
+ def frame(self, index):
136
+ if index < 0 or index >= len(self.raw):
137
+ raise KeyError("Unknown replay index")
138
+ raw = self.raw[index]
139
+ number = raw["frame_idx"]
140
+ plan = self.latest(self.plans, self.plan_ids, number)
141
+ plan = dict(plan) if plan else {"frame_idx": None, "trajectory": [], "global_route": [],
142
+ "local_path_display": [], "planner_name": "Before first processed observation"}
143
+ stamp = raw.get("received_unix_s", -math.inf)
144
+ control = self.latest(self.controls, self.control_times, stamp) or {}
145
+ robot = dict(self.latest(self.robots, self.robot_times, stamp) or {})
146
+ if raw.get("head_joints") is not None:
147
+ joint = list(robot.get("joint_positions", [0.0] * 11))
148
+ if len(joint) >= 11:
149
+ joint[9:11] = raw["head_joints"]
150
+ robot["joint_positions"] = joint
151
+ bev_index = bisect_right(self.bev_ids, number) - 1
152
+ bev = self.bev_ids[bev_index] if bev_index >= 0 else None
153
+ if bev is not None:
154
+ source_plan = self.latest(self.plans, self.plan_ids, bev) or {}
155
+ plan.update(bev_size=source_plan.get("bev_size", 400), bev_res=source_plan.get("bev_res", 0.05))
156
+ query = {"run": self.root.name}
157
+ replay = {
158
+ "index": index, "time_s": raw["relative_time_s"], "frame_idx": number,
159
+ "map_frame": plan["frame_idx"], "bev_frame": bev,
160
+ "bev_time_s": self.raw_by_id[bev]["relative_time_s"] if bev is not None else None,
161
+ "bev_source": self.bevs[bev]["source"] if bev is not None else None,
162
+ "rgb_url": "/api/replay/rgb?" + urlencode({**query, "frame": number}),
163
+ "bev_urls": {name: "/api/replay/bev?" + urlencode({**query, "frame": bev, "layer": name})
164
+ for name in LAYERS} if bev is not None else {},
165
+ }
166
+ return {
167
+ **{key: self.base.get(key) for key in ("goal_keyframe", "max_plan_age_s", "v_max", "w_max")},
168
+ "phase": "stopped", "ready": False, "review": True, "playback": True,
169
+ "gate": "Replay; motion controls disabled", "recorded_phase": control.get("phase", "teleop"),
170
+ "reason": control.get("reason", "Recorded observations"), "frame": plan, "robot": robot,
171
+ "control": control, "replay": replay, "capture_frame": number,
172
+ "processed": bisect_right(self.plan_ids, number),
173
+ "motion_commands": control.get("nonzero_motion_commands", 0),
174
+ }
175
+
176
+ def image(self, number, layer=None):
177
+ if layer is None:
178
+ if number not in self.raw_by_id:
179
+ raise KeyError("Unknown recorded RGB frame")
180
+ relative = Path("capture/rgb") / f"{number:08d}.jpg"
181
+ else:
182
+ if layer not in LAYERS or number not in self.bevs:
183
+ raise KeyError("Unknown recorded BEV frame or layer")
184
+ relative = self.bevs[number]["path"] / f"{layer}.png"
185
+ return confined(self.root, relative).read_bytes()
186
+
187
+
188
+ class ReplayService:
189
+ """Only completed recordings in the current run's parent are selectable."""
190
+
191
+ def __init__(self, current):
192
+ self.current = Path(current).resolve()
193
+ self.parent = self.current.parent
194
+ self.cache = {}
195
+
196
+ def directories(self):
197
+ result = {}
198
+ for path in [self.current, *self.parent.glob("stretch_cross_nav_live_*")]:
199
+ root = path.resolve()
200
+ if root.parent != self.parent or not (root / "map.json").is_file():
201
+ continue
202
+ status = root / "final_status.json"
203
+ if not status.is_file():
204
+ status = root / "review.json"
205
+ if not status.is_file():
206
+ continue
207
+ data = json.loads(status.read_text())
208
+ capture = root / "capture/observations.jsonl"
209
+ if data.get("phase") == "stopped" and capture.is_file() and capture.stat().st_size > 0:
210
+ result[root.name] = (root, data)
211
+ return result
212
+
213
+ def listing(self):
214
+ return [{"id": key, "goal_keyframe": data.get("goal_keyframe"), "reason": data.get("reason")}
215
+ for key, (_, data) in sorted(self.directories().items(), reverse=True)]
216
+
217
+ def get(self, key=None):
218
+ key = key or self.current.name
219
+ root, _ = self.directories()[key]
220
+ # A backfill can add images while the read-only page is open.
221
+ signature = tuple((root / name).stat().st_mtime_ns if (root / name).exists() else 0
222
+ for name in ("capture/observations.jsonl", "observations.jsonl", "replay/bev",
223
+ "replay/last_bev.json"))
224
+ if key not in self.cache or self.cache[key][0] != signature:
225
+ self.cache[key] = (signature, ReplayArchive(root))
226
+ return self.cache[key][1]
cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_report.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Saved native CROSS relocalization, native graph routing and learned or geometric BEV planning."""
2
+ import heapq
3
+ import json
4
+ from pathlib import Path
5
+ from types import SimpleNamespace
6
+
7
+ import cv2
8
+ import numpy as np
9
+
10
+ from .stretch_nav_geometry import body_to_world, body_yaw, measured_bev, bev_png, world_to_body
11
+ from .stretch_nav_learned import reproject_bev, learned_png
12
+
13
+
14
+ def clean_json(value):
15
+ if isinstance(value, dict):
16
+ return {str(k): clean_json(v) for k, v in value.items()}
17
+ if isinstance(value, (list, tuple)):
18
+ return [clean_json(v) for v in value]
19
+ if isinstance(value, np.ndarray):
20
+ return clean_json(value.tolist())
21
+ if isinstance(value, np.generic):
22
+ return clean_json(value.item())
23
+ if isinstance(value, float) and not np.isfinite(value):
24
+ return None
25
+ return value
26
+
27
+
28
+ def save_json(path, data):
29
+ temporary = path.with_suffix('.json.tmp')
30
+ temporary.write_text(json.dumps(clean_json(data), indent=2, allow_nan=False) + '\n')
31
+ temporary.replace(path)
32
+
33
+
34
+ def positions(transform, points):
35
+ points = np.asarray(points, dtype=float).reshape(-1, 3)
36
+ return points @ transform[:3, :3].T + transform[:3, 3]
37
+
38
+
39
+ class SavedRoute:
40
+ """Feed saved native pose/odometry records to CROSS's unmodified PlanningSystem.
41
+
42
+ Choose a local attachment by connection distance plus remaining native graph
43
+ cost. Keep the previous route when competing routes have nearly equal cost.
44
+ No new visual or geometric shortcut edges are invented by this adapter.
45
+ """
46
+ def __init__(self, map_path, *, attachment_radius=.75, switch_margin=.25):
47
+ from cross.db.store import read_map
48
+ from cross.core.types import Edge, EdgeType
49
+ from cross.core.planning_system import PlanningSystem
50
+
51
+ data = read_map(map_path)
52
+ records = list(data['db_data']['keyframes']) + list(data['hypo_data']['temp_keyframes'])
53
+ nodes = {int(r['id']): SimpleNamespace(id=int(r['id']), temporary=bool(r['temporary']),
54
+ pose_mu=r['pose_mu'].cpu(), pose_charts=r.get('pose_charts')) for r in records}
55
+ edges = {tuple(key): Edge(mean=r['mean'].cpu(), std=r['std'].cpu(), type=EdgeType[r['type']])
56
+ for key, r in data['hypo_data']['odom_edges'].items()}
57
+ adjacency = {}
58
+ for a, b in edges:
59
+ adjacency.setdefault(a, set()).add(b)
60
+ adjacency.setdefault(b, set()).add(a)
61
+ manager = SimpleNamespace(nodes=nodes, odom_edges=edges, proximity_edges={}, proximity_adjacency={},
62
+ chart_aware=bool(data.get('coordinate_charts_version')), odom_adjacency=lambda: adjacency)
63
+ self.permanent = {k: v for k, v in nodes.items() if not v.temporary}
64
+ self.matrices = {k: v.pose_mu[0].matrix().numpy() for k, v in nodes.items()}
65
+ self.current = next(iter(self.permanent))
66
+ system = SimpleNamespace(device='cpu', hypothesis_manager=manager,
67
+ get_current_kf=lambda: {'closest_perm_node': nodes[self.current]})
68
+ self.planning = PlanningSystem(system, config={'use_temporary_keyframes': False})
69
+ self.attachment_radius = attachment_radius
70
+ self.switch_margin = switch_margin
71
+ if not np.isfinite([attachment_radius, switch_margin]).all() or (
72
+ attachment_radius <= 0 or switch_margin < 0
73
+ ):
74
+ raise ValueError('Invalid route attachment limits')
75
+ self._goal = None
76
+ self._cost_to_goal = {}
77
+ self._previous_ids = ()
78
+
79
+ def reset_attachment(self):
80
+ """Forget route continuity after a global localization correction."""
81
+ self._previous_ids = ()
82
+
83
+ def _set_goal(self, goal_id):
84
+ if goal_id not in self.permanent:
85
+ raise ValueError('Goal must be an original permanent keyframe')
86
+ if goal_id == self._goal:
87
+ return
88
+ # The saved graph is immutable. Compute cost-to-go once per goal using
89
+ # exactly the neighbors and edge weights used by native CROSS planning.
90
+ # Reverse edges also handle directed graphs without assuming symmetry.
91
+ native = self.planning.planner
92
+ reverse = {key: [] for key in self.permanent}
93
+ for key in self.permanent:
94
+ for neighbor in native._get_neighbors(key):
95
+ if neighbor not in reverse:
96
+ continue
97
+ cost = native._get_edge_cost(key, neighbor)
98
+ if cost < 0 or np.isnan(cost):
99
+ raise ValueError('Invalid native planning edge cost')
100
+ if np.isfinite(cost):
101
+ reverse[neighbor].append((key, cost))
102
+ costs, queue = {goal_id: 0.}, [(0., goal_id)]
103
+ while queue:
104
+ cost, key = heapq.heappop(queue)
105
+ if cost > costs[key]:
106
+ continue
107
+ for neighbor, weight in reverse[key]:
108
+ candidate = cost + weight
109
+ if candidate < costs.get(neighbor, np.inf):
110
+ costs[neighbor] = candidate
111
+ heapq.heappush(queue, (candidate, neighbor))
112
+ self.planning.set_goal(goal_kf_id=goal_id)
113
+ self._goal, self._cost_to_goal, self._previous_ids = goal_id, costs, ()
114
+
115
+ def route(self, camera_pose, goal_id, *, can_attach=None):
116
+ """Select a bounded local start; optional predicate checks its connection.
117
+
118
+ ``can_attach(keyframe_id, map_position)`` may veto an attachment using
119
+ current measured obstacles. Local planning still decides how to move.
120
+ """
121
+ camera_pose = np.asarray(camera_pose, dtype=float)
122
+ if camera_pose.shape != (4, 4) or not np.isfinite(camera_pose).all():
123
+ raise ValueError('Invalid committed camera pose')
124
+ self._set_goal(int(goal_id))
125
+ distances = {key: float(np.linalg.norm(self.matrices[key][:3, 3] - camera_pose[:3, 3]))
126
+ for key in self.permanent}
127
+ nearest = min(distances, key=distances.get)
128
+ # All bounded local starts compete on total cost. A window relative to
129
+ # the nearest frame can discard a valid short route at an overlapping
130
+ # visit, even though its attachment remains close and unobstructed.
131
+ radius = self.attachment_radius
132
+ candidates = []
133
+ for key, distance in distances.items():
134
+ remaining = self._cost_to_goal.get(key, np.inf)
135
+ if distance > radius or not np.isfinite(remaining):
136
+ continue
137
+ if can_attach is not None and not can_attach(key, self.matrices[key][:3, 3]):
138
+ continue
139
+ candidates.append((distance + remaining, distance, key))
140
+ diagnostics = {'nearest_keyframe': nearest, 'nearest_distance_m': distances[nearest],
141
+ 'attachment_limit_m': radius, 'candidate_count': len(candidates),
142
+ 'connection_check': 'measured_depth' if can_attach is not None else 'map_distance_only',
143
+ 'switch_margin_m': self.switch_margin}
144
+ if not candidates:
145
+ self._previous_ids = ()
146
+ return {'status': 'no_local_graph_attachment', 'start_keyframe': None,
147
+ 'ids': [], 'positions': [], 'attachment': diagnostics}
148
+ best = min(candidates)
149
+ previous = set(self._previous_ids)
150
+ continuing = [candidate for candidate in candidates if candidate[2] in previous]
151
+ if continuing:
152
+ keep = min(continuing)
153
+ if keep[0] <= best[0] + self.switch_margin:
154
+ best = keep
155
+ total, distance, self.current = best
156
+ # Native backbone expansion has no segment to expand for [goal]. Keep
157
+ # that valid singleton so the live controller can approach/declare arrival.
158
+ result = ({'detailed_path': [self.current], 'detailed_cost': 0., 'detail_level': 'backbone'}
159
+ if self.current == self._goal else self.planning.plan_to_goal(algorithm='astar'))
160
+ if not result or not result.get('detailed_path'):
161
+ self._previous_ids = ()
162
+ return {'status': 'no_graph_route', 'start_keyframe': self.current,
163
+ 'ids': [], 'positions': [], 'attachment': diagnostics}
164
+ ids = result['detailed_path']
165
+ self._previous_ids = tuple(ids)
166
+ diagnostics.update(distance_m=distance, remaining_m=result['detailed_cost'],
167
+ total_m=distance + result['detailed_cost'],
168
+ selection_total_m=total,
169
+ best_candidate_total_m=min(candidates)[0], selected_on_previous_route=self.current in previous)
170
+ return {'status': 'route_found', 'start_keyframe': self.current, 'ids': ids,
171
+ 'positions': [self.matrices[k][:3, 3] for k in ids],
172
+ 'cost_m': result['detailed_cost'], 'algorithm': 'native CROSS A*',
173
+ 'attachment': diagnostics,
174
+ 'start_rule': 'local connection distance + remaining native graph cost, with route continuity',
175
+ 'detail_level': result['detail_level']}
176
+
177
+
178
+ def build_report(capture, probe, map_run, output, goal_id=None):
179
+ from cross_nav.policy.bev_policy import BEVPlannerPolicy, Episode
180
+
181
+ capture, probe, map_run, output = map(Path, (capture, probe, map_run, output))
182
+ output.mkdir(parents=True, exist_ok=True)
183
+ (output / 'frames').mkdir(exist_ok=True)
184
+ save_json(output / 'state.json', {'status': 'building', 'robot_commands_sent': 0})
185
+ rows = json.loads((probe / 'observations.json').read_text())
186
+ learned = (probe / 'bevs').is_dir()
187
+ size, resolution = (400, .05) if learned else (200, .05)
188
+ raw_rows = {r['frame_idx']: r for r in map(json.loads, (capture / 'observations.jsonl').read_text().splitlines())}
189
+ source_run = json.loads((map_run / 'run.json').read_text())
190
+ source_graph = json.loads((map_run / 'graph.json').read_text())
191
+ display = np.asarray(source_run['T_display_from_map'])
192
+ route_planner = SavedRoute(map_run / 'map.pkl')
193
+ committed = [row for row in rows if row['localized']]
194
+ if not committed:
195
+ raise ValueError('No committed native relocalization observations')
196
+ final = committed[-1]
197
+ final_raw = raw_rows[final['capture_frame']]
198
+ final_map_camera = np.asarray(final['map_pose'])
199
+ final_odom_camera = np.asarray(final_raw['camera_pose'])
200
+ final_base = np.asarray(final_raw['base_pose_matrix'])
201
+ T_map_odom = final_map_camera @ np.linalg.inv(final_odom_camera)
202
+ if goal_id is None:
203
+ nearest_id = min(route_planner.permanent, key=lambda k: np.linalg.norm(
204
+ route_planner.matrices[k][:3, 3] - final_map_camera[:3, 3]))
205
+ candidates = []
206
+ for key in route_planner.permanent:
207
+ point = route_planner.matrices[key][:3, 3]
208
+ point_odom = positions(np.linalg.inv(T_map_odom), [point])[0]
209
+ fl = world_to_body(point_odom, final_base)
210
+ if 1.5 <= np.linalg.norm(fl) <= 4.5 and fl[0] > .5:
211
+ # Repeated visits can be nearby in space but far along the graph.
212
+ candidates.append((np.linalg.norm(fl - [3., 0.]) + .02 * abs(key - nearest_id), key))
213
+ goal_id = min(candidates)[1] if candidates else min(route_planner.permanent,
214
+ key=lambda k: np.linalg.norm(route_planner.matrices[k][:3, 3] - final_map_camera[:3, 3]))
215
+ if int(goal_id) not in route_planner.permanent:
216
+ raise ValueError('Goal must be an original permanent map keyframe')
217
+
218
+ # Native CPU policy consumes cached network predictions or the geometric baseline.
219
+ cross_root = Path('/workspace/CROSS')
220
+ config = json.loads((cross_root / 'cross_nav/configs/policy/bev_planner_vfin2.json').read_text())
221
+ for field in ('backbone', 'occupancy', 'visibility', 'visibility_gravity'):
222
+ config[field] = None
223
+ policy = BEVPlannerPolicy(config, predictor=SimpleNamespace(size=size, res=resolution))
224
+ episode = Episode()
225
+ selected = sorted(set(np.linspace(0, len(rows) - 1, 25).astype(int).tolist()
226
+ + [i for i, row in enumerate(rows) if row['localized']]))
227
+ frames, trajectory = [], []
228
+ for number, row_index in enumerate(selected):
229
+ row = rows[row_index]
230
+ index = row['capture_frame']
231
+ raw = raw_rows[index]
232
+ camera, base = np.asarray(raw['camera_pose']), np.asarray(raw['base_pose_matrix'])
233
+ depth = cv2.imread(str(capture / 'depth' / f'{index:08d}.png'), cv2.IMREAD_UNCHANGED).astype(float) / 1000
234
+ geometry = measured_bev(depth, raw['camera_K'], camera, base)
235
+ frame_dir = output / 'frames' / f'{index:08d}'
236
+ frame_dir.mkdir(exist_ok=True)
237
+ np.savez_compressed(frame_dir / 'geometry.npz', prob=geometry['prob'], obs=geometry['obs'],
238
+ height=geometry['height'], K=raw['camera_K'], T_odom_camera=camera, T_odom_base=base)
239
+ bev_meta = row.get('bev', {})
240
+ fresh = bool(row.get('bev_fresh', False)) if learned else True
241
+ if learned:
242
+ if fresh:
243
+ with np.load(probe / 'bevs' / f'{index:08d}.npz') as native:
244
+ planned_bev = reproject_bev(native['prob'], native['obs'], native['err'],
245
+ native['R_bev_from_cam'], camera, base, resolution)
246
+ else:
247
+ planned_bev = {'prob': np.full((size, size), .5, np.float32),
248
+ 'obs': np.zeros((size, size), np.float32),
249
+ 'err': np.ones((size, size), np.float32)}
250
+ np.savez_compressed(frame_dir / 'learned_base.npz', **planned_bev)
251
+ for layer in ('occupancy', 'visibility', 'uncertainty'):
252
+ (frame_dir / f'{layer}.png').write_bytes(learned_png(
253
+ planned_bev['prob'], planned_bev['obs'], planned_bev['err'], layer))
254
+ else:
255
+ planned_bev = {**geometry, 'err': np.zeros((size, size), np.float32)}
256
+ for layer in ('occupancy', 'visibility'):
257
+ (frame_dir / f'{layer}.png').write_bytes(bev_png(geometry['prob'], geometry['obs'], layer))
258
+ map_camera = np.asarray(row['map_pose'])
259
+ graph_route = {'status': 'waiting_for_committed_pose', 'ids': [], 'positions': []}
260
+ goal_body = np.array([2., 0.])
261
+ global_positions = []
262
+ local_goal_kind = 'local 2 m forward demo; map localization pending'
263
+ if row['localized']:
264
+ alignment = map_camera @ np.linalg.inv(camera)
265
+ graph_route = route_planner.route(map_camera, goal_id)
266
+ global_positions = positions(display, graph_route['positions'])
267
+ route_points_odom = positions(np.linalg.inv(alignment), graph_route['positions'])
268
+ if len(route_points_odom):
269
+ distances = np.linalg.norm(route_points_odom[:, :2] - base[:2, 3], axis=1)
270
+ eligible = np.flatnonzero(distances >= 1.5)
271
+ target = route_points_odom[eligible[0] if len(eligible) else -1]
272
+ goal_body = world_to_body(target, base)
273
+ local_goal_kind = 'subgoal on native CROSS graph route'
274
+ trajectory.append(positions(display, [map_camera[:3, 3]])[0])
275
+ maps = {'prob': planned_bev['prob'][None], 'obs': planned_bev['obs'][None],
276
+ 'err': planned_bev['err'][None], 'log_scale': np.array([bev_meta.get('log_scale', 0.)]),
277
+ 'odometry': np.array([bev_meta.get('scale_source') == 'anchors']),
278
+ 'up_head_deg': np.array([bev_meta.get('gravity_head_deg', 0.)]),
279
+ 'n_views': np.array([bev_meta.get('n_views', 1)]), 'fresh': np.array([fresh])}
280
+ # Zero actual commanded travel: passive pushing must not create fictitious bump events.
281
+ odom = np.array([*base[:2, 3], body_yaw(base)])
282
+ paths, details = policy.plan_maps(maps, goal_body[None], [episode],
283
+ [{'ep': 'passive', 'odom': odom, 'expect': 0.}], [True])
284
+ debug = details[0]
285
+ local_path = paths[0]
286
+ local_display = []
287
+ camera_display = None
288
+ if row['localized']:
289
+ alignment = map_camera @ np.linalg.inv(camera)
290
+ path_odom_xy = body_to_world(local_path, base)
291
+ path_odom = np.column_stack([path_odom_xy, np.zeros(len(path_odom_xy))])
292
+ local_display = positions(display @ alignment, path_odom)
293
+ camera_display = positions(display, [map_camera[:3, 3]])[0]
294
+ matches = sorted(row['retrieval'], key=lambda r: r['score'], reverse=True)[:6]
295
+ status_names = ['goal route', 'local waypoint', 'no route / scan', 'near-goal approach',
296
+ 'remembered route', 'relaxed local route', 'episode-map route']
297
+ record = {'frame_idx': index, 'time_s': raw['relative_time_s'], 'localized': row['localized'],
298
+ 'weights': row['weights'], 'retrieval': matches, 'graph_route': graph_route,
299
+ 'global_route_display': global_positions, 'local_path_body': local_path,
300
+ 'local_path_display': local_display, 'camera_display': camera_display,
301
+ 'goal_body': goal_body, 'goal_kind': local_goal_kind, 'goal_keyframe': int(goal_id),
302
+ 'planner_status': status_names[int(debug['status'])], 'planner_status_code': int(debug['status']),
303
+ 'blind_zone_assumed': bool(debug['blind_zone']), 'vis_threshold': debug['vis_threshold'],
304
+ 'bev_source': 'cross_shared_vggt_heads' if learned else 'measured_depth_geometry',
305
+ 'learned_bev_heads_available': learned, 'bev_fresh': fresh, 'bev_metadata': bev_meta,
306
+ 'robot_commands_sent': 0, 'bev_size': size, 'bev_resolution_m': resolution,
307
+ 'floor_z_odom': 0., 'camera_height_m': float(camera[2, 3]),
308
+ 'occupied_cells': int((planned_bev['prob'] > .6).sum()),
309
+ 'observed_cells': int((planned_bev['obs'] > .5).sum()),
310
+ 'measured_depth_occupied_cells': geometry['occupied_cells'],
311
+ 'occupancy_range': [planned_bev['prob'].min(), planned_bev['prob'].max()],
312
+ 'observability_range': [planned_bev['obs'].min(), planned_bev['obs'].max()],
313
+ 'camera_K': raw['camera_K'], 'T_odom_camera': camera, 'T_odom_base': base,
314
+ 'native_map_camera_pose': map_camera if row['localized'] else None,
315
+ 'point_cloud_odom': geometry['points_odom'],
316
+ 'retrieval_note': 'Native last-step diagnostics; may carry between backend observation frames.'}
317
+ save_json(frame_dir / 'frame.json', record)
318
+ frames.append({'id': index, 'time_s': raw['relative_time_s'], 'localized': row['localized']})
319
+ save_json(output / 'state.json', {'status': 'building', 'frames_ready': number + 1,
320
+ 'frames_total': len(selected), 'robot_commands_sent': 0})
321
+ nodes = [{'id': node['id'], 'position': positions(display, [np.asarray(node['pose'])[:3, 3]])[0],
322
+ 'frame_idx': node.get('frame_idx')} for node in source_graph['nodes'] if not node['temporary']]
323
+ map_data = {'nodes': nodes, 'trajectory': trajectory, 'goal_keyframe': int(goal_id),
324
+ 'recording': '2026-10-22--15-48-58', 'coordinates': source_run['coordinates']}
325
+ save_json(output / 'map.json', map_data)
326
+ manifest = {'status': 'ready', 'capture': str(capture.resolve()), 'probe': str(probe.resolve()),
327
+ 'map_run': str(map_run.resolve()), 'phone_dataset': source_run['dataset'], 'frames': frames,
328
+ 'default_frame': len(frames) - 1, 'goal_keyframe': int(goal_id),
329
+ 'native_probe_result': json.loads((probe / 'result.json').read_text()),
330
+ 'learned_bev_heads_available': learned,
331
+ 'bev_source': 'cross_shared_vggt_heads' if learned else 'measured_depth_geometry',
332
+ 'bev_size': size, 'bev_resolution_m': resolution,
333
+ 'checkpoint_provenance': json.loads((probe / 'run.json').read_text()).get('checkpoint_provenance') if learned else None,
334
+ 'native_local_planner': 'cross_nav.policy.bev_policy.BEVPlannerPolicy.plan_maps',
335
+ 'native_graph_planner': 'cross.core.planning_system.PlanningSystem (A*)',
336
+ 'raw_depth_max_m': 3., 'robot_commands_sent': 0,
337
+ 'notes': (["Trained occupancy and observability heads read CROSS's shared VGGT pass.",
338
+ 'RGB and external camera odometry only; raw depth is a separate comparison.',
339
+ 'Recorded camera TF supplies gravity and camera-to-base reprojection.',
340
+ 'Occupancy error and observability are distinct learned confidence outputs.',
341
+ 'The native nav service observation cadence (obs_max_interval_steps=1) is enabled.',
342
+ 'Plans are passive inspection results, with no robot commands.',
343
+ 'The local planner uses its native circular footprint and recovery rules; no physical drive test.']
344
+ if learned else ['The occupancy/observability navigation heads are not used in this comparison.',
345
+ 'BEV probabilities are geometric encodings, not learned/calibrated confidence.',
346
+ 'The floor is assumed at odom Z=0; camera pan/tilt/offset come from timestamped TF.',
347
+ 'Plans are passive inspection results, with no robot commands.',
348
+ 'The local planner uses its native circular footprint and recovery rules; no physical drive test.'])}
349
+ save_json(output / 'manifest.json', manifest)
350
+ save_json(output / 'state.json', {'status': 'ready', 'frames_ready': len(frames),
351
+ 'goal_keyframe': int(goal_id), 'robot_commands_sent': 0})
352
+ return manifest
cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_survey.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stationary yaw/pitch observations for blocked Stretch navigation; no I/O."""
2
+
3
+ import math
4
+
5
+ import numpy as np
6
+
7
+ from .stretch_nav_control import HEAD_SURVEY_TIMEOUT, HEAD_VIEW_TIMEOUT, alignment_correction, wrap
8
+ from .stretch_nav_recovery import camera_pitch, camera_yaw
9
+
10
+ HEAD_TARGET_TOLERANCE_RAD = math.radians(4)
11
+
12
+
13
+ class HeadSurvey:
14
+ """Observe floor and both sides, then restore the driving camera pose.
15
+
16
+ Targets are frozen from image-time joint/TF feedback. Only distinct,
17
+ settled processed images count. First hold zero base velocity and wait
18
+ for fresh standstill observations before anchoring or moving the head.
19
+ No survey result requests base motion.
20
+ At most two passes are allowed until the base moves 20 cm; the enclosing
21
+ controller has an independent 260 s/100 degree recovery budget.
22
+ """
23
+
24
+ def __init__(self):
25
+ self.active = False
26
+ self.braking = False
27
+ self.brake_reference = self.brake_stable_since = None
28
+ self.brake_frame, self.brake_count = -1, 0
29
+ self.origin = self.base = None
30
+ self.passes = self.index = 0
31
+ self.targets = []
32
+ self.views = []
33
+ self.started = self.since = self.next_allowed = 0.0
34
+ self.previous_mount = self.stable_since = None
35
+ self.last_frame = -1
36
+ self.count = 0
37
+ self.reason = ""
38
+
39
+ def cancel(self):
40
+ self.active = False
41
+ self.braking = False
42
+ self.next_allowed = 0.0
43
+
44
+ def start(self, base, mount, neutral, joint, now, reason):
45
+ if self.active:
46
+ return False
47
+ joint = np.asarray(joint, float)
48
+ if joint.ndim != 1 or len(joint) < 11 or not np.isfinite(joint).all():
49
+ raise ValueError("Timestamped head joint feedback unavailable for survey")
50
+ base = np.asarray(base, float)
51
+ if self.origin is None or np.linalg.norm(base[:2, 3] - self.origin) > 0.2:
52
+ self.origin, self.passes = base[:2, 3].copy(), 0
53
+ if now < self.next_allowed:
54
+ return False
55
+ if self.passes >= 2:
56
+ raise RuntimeError("Head survey exhausted two passes without forward progress; footprint remains blocked")
57
+ pan = float(np.clip(joint[9] + wrap(camera_yaw(neutral) - camera_yaw(mount)), -2.8, 0.65))
58
+ tilt = float(np.clip(joint[10] + camera_pitch(neutral) - camera_pitch(mount), -1.4, 0.0))
59
+ # Look far enough down to inspect the otherwise hidden near floor.
60
+ down_pitch = max(-1.25, min(-1.05, camera_pitch(neutral) - 0.45))
61
+ down = float(np.clip(joint[10] + down_pitch - camera_pitch(mount), -1.4, 0.0))
62
+ left, right = min(0.65, pan + 0.55), max(-2.8, pan - 0.70)
63
+ self.targets = [
64
+ ("front floor", [pan, down]),
65
+ ("left floor", [left, down]),
66
+ ("right floor", [right, down]),
67
+ ("right surroundings", [right, tilt]),
68
+ ("left surroundings", [left, tilt]),
69
+ ("return to driving view", [pan, tilt]),
70
+ ]
71
+ self.base = base.copy()
72
+ self.passes += 1
73
+ self.index, self.count, self.last_frame = 0, 0, -1
74
+ self.started = self.since = now
75
+ self.previous_mount = self.stable_since = None
76
+ self.views, self.reason, self.active = [], reason, True
77
+ # The triggering image predates the zero-velocity request. Let the
78
+ # base decelerate, then anchor to a newly observed stationary pose.
79
+ self.braking = True
80
+ self.brake_reference = self.brake_stable_since = None
81
+ self.brake_frame, self.brake_count = -1, 0
82
+ return True
83
+
84
+ def snapshot(self):
85
+ return {
86
+ "active": self.active,
87
+ "braking": self.braking,
88
+ "pass": self.passes,
89
+ "view": min(self.index + 1, len(self.targets)),
90
+ "total": len(self.targets),
91
+ "label": ("waiting for base to stop" if self.braking else
92
+ self.targets[min(self.index, len(self.targets) - 1)][0] if self.targets else "idle"),
93
+ "settled_views": len(self.views),
94
+ "reason": self.reason,
95
+ }
96
+
97
+ def update(self, base, mount, joint, frame, now):
98
+ if not self.active:
99
+ raise RuntimeError("No active head survey")
100
+ if self.braking:
101
+ distance, angle = alignment_correction(self.base, base, np.eye(4))
102
+ if distance > 0.20 or angle > math.radians(20):
103
+ raise RuntimeError("Base exceeded head-survey braking envelope")
104
+ if now - self.started > 6.0:
105
+ raise RuntimeError("Head survey braking timed out waiting for base standstill")
106
+ if frame > self.brake_frame:
107
+ moved, turned = ((math.inf, math.inf) if self.brake_reference is None else
108
+ alignment_correction(self.brake_reference, base, np.eye(4)))
109
+ if moved > .005 or turned > math.radians(1):
110
+ self.brake_reference = np.asarray(base).copy()
111
+ self.brake_stable_since, self.brake_count = now, 1
112
+ else:
113
+ self.brake_count += 1
114
+ self.brake_frame = frame
115
+ if self.brake_count >= 3 and now - self.brake_stable_since >= .6:
116
+ self.base = np.asarray(base).copy()
117
+ self.braking, self.since = False, now
118
+ if self.braking:
119
+ return {"phase": "survey_braking", "target": self.base[:2, 3].copy(),
120
+ "hold": True, "head_target": None, "scan_w": 0.0,
121
+ "coverage": 0.0, "speed_scale": 0.5, "lookahead": .22,
122
+ "survey_complete": False, "survey_label": "waiting for base to stop"}
123
+ distance, angle = alignment_correction(self.base, base, np.eye(4))
124
+ if distance > 0.05 or angle > math.radians(5):
125
+ raise RuntimeError("Base moved during stationary head survey")
126
+ if now - self.started > HEAD_SURVEY_TIMEOUT or now - self.since > HEAD_VIEW_TIMEOUT:
127
+ raise RuntimeError("Head survey timed out waiting for settled camera observations")
128
+ joint = np.asarray(joint, float)
129
+ if len(joint) < 11 or not np.isfinite(joint).all():
130
+ raise ValueError("Timestamped head joint feedback unavailable for survey")
131
+ label, target = self.targets[self.index]
132
+ complete = False
133
+ if frame > self.last_frame:
134
+ # Successful hardware actions can settle a few degrees short of
135
+ # their targets. Use the same four-degree allowance as the corner
136
+ # pitch return; geometry uses the measured image-time camera TF.
137
+ reached = np.max(np.abs(joint[9:11] - target)) < HEAD_TARGET_TOLERANCE_RAD
138
+ settled = False
139
+ if self.previous_mount is not None:
140
+ moved, turned = alignment_correction(self.previous_mount, mount, np.eye(4))
141
+ settled = moved < 0.005 and turned < math.radians(1)
142
+ self.previous_mount, self.last_frame = np.asarray(mount).copy(), frame
143
+ if reached and settled:
144
+ self.count += 1
145
+ self.stable_since = now if self.stable_since is None else self.stable_since
146
+ else:
147
+ self.count, self.stable_since = 0, None
148
+ if self.count >= 2 and now - self.stable_since >= 0.4:
149
+ self.views.append({"label": label, "frame_idx": int(frame), "head_joints": joint[9:11].tolist(),
150
+ "camera_in_base": np.asarray(mount).tolist()})
151
+ self.index += 1
152
+ self.since, self.count = now, 0
153
+ self.stable_since = self.previous_mount = None
154
+ if self.index == len(self.targets):
155
+ self.active, complete, self.next_allowed = False, True, now + 3.0
156
+ return {
157
+ "phase": "survey_return" if label == "return to driving view" else "survey",
158
+ "target": self.base[:2, 3].copy(),
159
+ "hold": True,
160
+ "head_target": target,
161
+ "head_anchor": self.base.copy(),
162
+ "head_deadline": min(self.since + HEAD_VIEW_TIMEOUT, self.started + HEAD_SURVEY_TIMEOUT),
163
+ "scan_w": 0.0,
164
+ "coverage": 0.0,
165
+ "speed_scale": 0.5,
166
+ "lookahead": 0.22,
167
+ "survey_complete": complete,
168
+ "survey_label": label,
169
+ }
cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_nav_viewer.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Loopback-only saved pipeline viewer; its actions never send robot commands."""
2
+ import argparse
3
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
4
+ import json
5
+ from pathlib import Path
6
+ import secrets
7
+ import subprocess
8
+ import threading
9
+
10
+ ROOT = Path(__file__).resolve().parents[1]
11
+ STATIC = ROOT / 'web_console/static'
12
+
13
+
14
+ class Report:
15
+ def __init__(self, directory, comparison=None):
16
+ self.root = Path(directory).resolve()
17
+ kind = 'learned' if self.manifest()['learned_bev_heads_available'] else 'depth'
18
+ self.sources = {kind: self.root}
19
+ if comparison:
20
+ self.sources['depth'] = Path(comparison).resolve()
21
+ self.source = next(iter(self.sources))
22
+ self.token = secrets.token_urlsafe(24)
23
+ self.worker = None
24
+ self.lock = threading.Lock()
25
+
26
+ def manifest(self):
27
+ return json.loads((self.root / 'manifest.json').read_text())
28
+
29
+ def frame(self, index):
30
+ if index not in {row['id'] for row in self.manifest()['frames']}:
31
+ raise KeyError('Unknown saved frame')
32
+ return self.root / 'frames' / f'{index:08d}'
33
+
34
+ def status(self):
35
+ state = json.loads((self.root / 'state.json').read_text())
36
+ manifest = self.manifest()
37
+ capture = json.loads((Path(manifest['capture']) / 'capture.json').read_text())
38
+ return {**state, 'manifest': manifest, 'capture': capture, 'token': self.token,
39
+ 'version': (self.root / 'manifest.json').stat().st_mtime_ns,
40
+ 'source': self.source, 'sources': list(self.sources),
41
+ 'replanning': self.worker is not None and self.worker.poll() is None}
42
+
43
+ def select_source(self, source):
44
+ with self.lock:
45
+ if source not in self.sources:
46
+ raise ValueError('Unknown BEV report')
47
+ if self.worker is not None and self.worker.poll() is None:
48
+ raise ValueError('Wait for the current replan to finish')
49
+ self.source, self.root = source, self.sources[source]
50
+
51
+ def replan(self, goal):
52
+ nodes = json.loads((self.root / 'map.json').read_text())['nodes']
53
+ if isinstance(goal, bool) or goal not in {n['id'] for n in nodes}:
54
+ raise ValueError('Choose an original permanent keyframe')
55
+ with self.lock:
56
+ if self.worker is not None and self.worker.poll() is None:
57
+ raise ValueError('A replan is already running')
58
+ manifest = self.manifest()
59
+ command = ['/workspace/miniforge3/envs/cross_latest/bin/python', '-u',
60
+ str(ROOT / 'scripts/build_stretch_nav_report.py'), '--capture', manifest['capture'],
61
+ '--probe', manifest['probe'], '--map-run', manifest['map_run'], '--output', str(self.root),
62
+ '--goal-id', str(goal)]
63
+ with (self.root / 'replan.log').open('ab') as log:
64
+ self.worker = subprocess.Popen(command, cwd=ROOT, stdin=subprocess.DEVNULL,
65
+ stdout=log, stderr=subprocess.STDOUT)
66
+
67
+
68
+ class Handler(BaseHTTPRequestHandler):
69
+ def log_message(self, *_):
70
+ pass
71
+
72
+ def send(self, code, value, content_type='application/json'):
73
+ if not isinstance(value, bytes):
74
+ value = json.dumps(value, allow_nan=False).encode()
75
+ self.send_response(code)
76
+ self.send_header('Content-Type', content_type)
77
+ self.send_header('Content-Length', str(len(value)))
78
+ self.send_header('Cache-Control', 'no-store')
79
+ self.send_header('X-Content-Type-Options', 'nosniff')
80
+ self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-eval'; "
81
+ "style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; worker-src 'self' blob:; "
82
+ "connect-src 'self'; frame-ancestors 'none'")
83
+ self.end_headers()
84
+ try:
85
+ self.wfile.write(value)
86
+ except (BrokenPipeError, ConnectionResetError):
87
+ pass
88
+
89
+ def do_GET(self):
90
+ report = self.server.report
91
+ path = self.path.split('?', 1)[0]
92
+ assets = {'/': ('cross_nav.html', 'text/html; charset=utf-8'),
93
+ '/cross_nav.js': ('cross_nav.js', 'text/javascript; charset=utf-8'),
94
+ '/cross_nav.css': ('cross_nav.css', 'text/css; charset=utf-8'),
95
+ '/vendor/plotly.min.js': ('vendor/plotly.min.js', 'text/javascript; charset=utf-8')}
96
+ try:
97
+ if path in assets:
98
+ file, mime = assets[path]
99
+ return self.send(200, (STATIC / file).read_bytes(), mime)
100
+ if path == '/api/status':
101
+ return self.send(200, report.status())
102
+ if path == '/api/map':
103
+ return self.send(200, (report.root / 'map.json').read_bytes())
104
+ parts = path.strip('/').split('/')
105
+ if len(parts) == 3 and parts[:2] == ['api', 'frame']:
106
+ return self.send(200, (report.frame(int(parts[2])) / 'frame.json').read_bytes())
107
+ if len(parts) == 4 and parts[:2] == ['api', 'bev'] and parts[3] in (
108
+ 'occupancy.png', 'visibility.png', 'uncertainty.png'):
109
+ return self.send(200, (report.frame(int(parts[2])) / parts[3]).read_bytes(), 'image/png')
110
+ if len(parts) == 4 and parts[:2] == ['api', 'image']:
111
+ manifest = report.manifest()
112
+ if parts[2] == 'robot':
113
+ index = int(parts[3])
114
+ report.frame(index)
115
+ file = Path(manifest['capture']) / 'rgb' / f'{index:08d}.jpg'
116
+ elif parts[2] == 'phone':
117
+ node = next(n for n in json.loads((report.root / 'map.json').read_text())['nodes']
118
+ if n['id'] == int(parts[3]))
119
+ file = Path(manifest['phone_dataset']) / 'rgb' / f"{node['frame_idx']:08d}.jpg"
120
+ else:
121
+ raise KeyError('Unknown image source')
122
+ return self.send(200, file.read_bytes(), 'image/jpeg')
123
+ if path == '/api/live.jpg':
124
+ capture = Path(report.manifest()['capture'])
125
+ latest = json.loads((capture / 'latest.json').read_text())
126
+ return self.send(200, (capture / 'rgb' / f"{latest['frame_idx']:08d}.jpg").read_bytes(), 'image/jpeg')
127
+ return self.send(404, {'error': 'Not found'})
128
+ except (KeyError, OSError, StopIteration):
129
+ self.send(404, {'error': 'Saved pipeline data unavailable'})
130
+ except (ValueError, TypeError) as exc:
131
+ self.send(400, {'error': str(exc)})
132
+
133
+ def do_POST(self):
134
+ report = self.server.report
135
+ if self.headers.get('X-Session') != report.token:
136
+ return self.send(403, {'error': 'Invalid viewer session'})
137
+ expected = f'http://127.0.0.1:{self.server.server_port}'
138
+ if self.headers.get('Origin') not in (None, expected):
139
+ return self.send(403, {'error': 'Wrong origin'})
140
+ try:
141
+ length = int(self.headers.get('Content-Length', 0))
142
+ if not 0 <= length <= 2048:
143
+ raise ValueError('Request too large')
144
+ data = json.loads(self.rfile.read(length) or b'{}')
145
+ if self.path == '/api/goal':
146
+ report.replan(data.get('goal_keyframe'))
147
+ return self.send(202, {'status': 'replanning', 'robot_commands_sent': 0})
148
+ if self.path == '/api/source':
149
+ report.select_source(data.get('source'))
150
+ return self.send(200, {'source': report.source, 'robot_commands_sent': 0})
151
+ if self.path == '/api/stop-capture':
152
+ (Path(report.manifest()['capture']) / 'STOP').touch()
153
+ return self.send(200, {'status': 'capture_stop_requested', 'robot_commands_sent': 0})
154
+ self.send(404, {'error': 'Unknown action'})
155
+ except (ValueError, TypeError) as exc:
156
+ self.send(400, {'error': str(exc)})
157
+
158
+
159
+ def main(argv=None):
160
+ parser = argparse.ArgumentParser(description=__doc__)
161
+ parser.add_argument('--report', type=Path, required=True)
162
+ parser.add_argument('--comparison', type=Path)
163
+ parser.add_argument('--port', type=int, default=8087)
164
+ args = parser.parse_args(argv)
165
+ server = ThreadingHTTPServer(('127.0.0.1', args.port), Handler)
166
+ server.daemon_threads = True
167
+ server.report = Report(args.report, args.comparison)
168
+ print(f'Stretch / CROSS pipeline: http://127.0.0.1:{args.port}', flush=True)
169
+ try:
170
+ server.serve_forever()
171
+ except KeyboardInterrupt:
172
+ pass
173
+ finally:
174
+ server.server_close()
175
+
176
+
177
+ if __name__ == '__main__':
178
+ main()
cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_transport.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Camera timing diagnostics. These estimates never grant a control lease."""
2
+
3
+ import math
4
+
5
+
6
+ def camera_transport_diagnostics(packet, robot, robot_received, received):
7
+ result = {'source_age_at_send_s': packet.get('sensor_age')}
8
+ if not robot:
9
+ return result
10
+ status_age = received - robot_received
11
+ result['status_local_age_s'] = status_age
12
+ if robot.get('frame_id') is not None:
13
+ result['source_frame_gap'] = robot['frame_id'] - packet['frame_id']
14
+ # Both source stamps use the robot's ROS clock. Avoid comparing clocks on
15
+ # different hosts. Unknown status transit time makes this a lower bound
16
+ # under a steady ROS clock, rather than an exact one-way network latency.
17
+ ros_now = robot.get('ros_now_s')
18
+ stamp = packet.get('sensor_stamp')
19
+ if ros_now is not None and stamp is not None and 0 <= status_age < .5:
20
+ age = ros_now + status_age - stamp
21
+ if math.isfinite(age):
22
+ result['source_age_via_status_s'] = age
23
+ result['post_publish_delay_via_status_s'] = age - packet.get('sensor_age', 0.)
24
+ return result
cases/20261026_goal1012_05/code/lite3_ROS/web_console/stretch_vggt_debug.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lossless, disk-backed VGGT inference archives without changing CROSS source."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import hashlib
7
+ import inspect
8
+ import json
9
+ import math
10
+ import queue
11
+ import subprocess
12
+ import threading
13
+ import time
14
+ import zipfile
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+
19
+
20
+ def model_provenance(cross_root):
21
+ root = Path(cross_root).resolve()
22
+ revision = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"],
23
+ check=True, capture_output=True, text=True).stdout.strip()
24
+ files = {}
25
+ for name in ("vggt_omega_cross_1b_512.pt", "nav/cross_nav_occupancy.pt", "nav/cross_nav_observability.pt"):
26
+ path = root / "models/VGGT-Omega-CROSS" / name
27
+ digest = hashlib.sha256()
28
+ with path.open("rb") as stream:
29
+ for block in iter(lambda: stream.read(8 * 1024 * 1024), b""):
30
+ digest.update(block)
31
+ files[name] = {"bytes": path.stat().st_size, "sha256": digest.hexdigest()}
32
+ return {"cross_git_revision": revision, "checkpoints": files}
33
+
34
+
35
+ def snapshot(value):
36
+ """Own CPU copies: CUDA-graph outputs and planner buffers are reused."""
37
+ if isinstance(value, np.ndarray):
38
+ if value.dtype.hasobject:
39
+ raise TypeError("Object arrays are not permitted in VGGT debug archives")
40
+ return value.copy()
41
+ if hasattr(value, "detach"):
42
+ tensor = value.detach().cpu()
43
+ # Every bfloat16 value is represented exactly by float32.
44
+ if str(tensor.dtype) == "torch.bfloat16":
45
+ tensor = tensor.float()
46
+ return tensor.numpy().copy()
47
+ if isinstance(value, np.generic):
48
+ return value.item()
49
+ if isinstance(value, dict):
50
+ return {str(key): snapshot(item) for key, item in value.items()}
51
+ if isinstance(value, (tuple, list)):
52
+ return [snapshot(item) for item in value]
53
+ if value is None or isinstance(value, (str, bool, int, float)):
54
+ return value
55
+ raise TypeError(f"Unsupported VGGT debug value: {type(value).__name__}")
56
+
57
+
58
+ def atomic_json(path, data):
59
+ temporary = path.with_suffix(path.suffix + ".tmp")
60
+ temporary.write_text(json.dumps(data, indent=2, allow_nan=False) + "\n")
61
+ temporary.replace(path)
62
+
63
+
64
+ def write_npz(path, arrays):
65
+ """Fast, lossless ZIP compression; no pickle and no reduced precision."""
66
+ temporary = path.with_suffix(path.suffix + ".tmp")
67
+ with zipfile.ZipFile(temporary, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=1) as archive:
68
+ for key, array in arrays.items():
69
+ with archive.open(key + ".npy", "w", force_zip64=True) as stream:
70
+ np.lib.format.write_array(stream, np.asarray(array), allow_pickle=False)
71
+ temporary.replace(path)
72
+
73
+
74
+ def pack(value, arrays, name="data"):
75
+ if isinstance(value, np.ndarray):
76
+ key = name.replace("/", "_")
77
+ if key in arrays:
78
+ raise ValueError(f"Duplicate archive array key: {key}")
79
+ arrays[key] = value
80
+ return {"npz_key": key, "shape": list(value.shape), "dtype": str(value.dtype)}
81
+ if isinstance(value, dict):
82
+ return {key: pack(item, arrays, f"{name}.{key}") for key, item in value.items()}
83
+ if isinstance(value, list):
84
+ return [pack(item, arrays, f"{name}.{index}") for index, item in enumerate(value)]
85
+ if isinstance(value, float) and not math.isfinite(value):
86
+ return {"nonfinite": str(value)}
87
+ return value
88
+
89
+
90
+ class _RecordingHead:
91
+ def __init__(self, original, recorder):
92
+ self.original, self.recorder = original, recorder
93
+ self.signature = inspect.signature(original)
94
+
95
+ def __getattr__(self, name):
96
+ return getattr(self.original, name)
97
+
98
+ def __call__(self, *args, **kwargs):
99
+ result = self.original(*args, **kwargs)
100
+ recorder = self.recorder
101
+ if recorder.current is not None:
102
+ started = time.perf_counter()
103
+ if recorder.active_pass is None:
104
+ raise RuntimeError("BEV prediction has no matching recorded VGGT pass")
105
+ bound = self.signature.bind(*args, **kwargs)
106
+ bound.apply_defaults()
107
+ keys = ("pts", "patch_hw", "hw", "log_scale", "up_cam", "views")
108
+ recorder.active_pass["head_calls"].append({
109
+ "inputs": snapshot({key: bound.arguments.get(key) for key in keys}),
110
+ "outputs": snapshot(result),
111
+ })
112
+ recorder.copy_s += time.perf_counter() - started
113
+ return result
114
+
115
+
116
+ class VggtDebugRecorder:
117
+ """Archive every actual pass, with bounded asynchronous compression.
118
+
119
+ Hooks delegate unchanged and return the original objects. No robot or
120
+ network transport is imported. A full queue or write failure is explicit;
121
+ a live caller can close navigation rather than silently lose debug data.
122
+ """
123
+
124
+ def __init__(self, directory, metadata=None, *, on_error=None, max_pending=8):
125
+ if max_pending < 1:
126
+ raise ValueError("VGGT debug queue must have a positive bound")
127
+ self.root = Path(directory).resolve()
128
+ self.root.mkdir(parents=True, exist_ok=False)
129
+ (self.root / "views").mkdir()
130
+ (self.root / "frames").mkdir()
131
+ self.on_error = on_error
132
+ self.pending = queue.Queue(maxsize=max_pending)
133
+ self.error = None
134
+ self.run_error = None
135
+ self.closed = False
136
+ self.current = self.active_pass = None
137
+ self.hooks = []
138
+ self.assets = set()
139
+ self.frames = self.passes = self.bytes = 0
140
+ self.write_s = self.copy_s = 0.0
141
+ self.submitted = set()
142
+ self.started = time.time()
143
+ atomic_json(self.root / "run.json", {
144
+ "schema_version": 1, "created_unix": self.started, "metadata": metadata or {},
145
+ "input_encoding": "Exact per-view CHW tensors; shared content-addressed lossless NPZ assets",
146
+ "bfloat16_storage": "Converted losslessly to float32; original dtype recorded on inference inputs",
147
+ "outputs": "Geometry predictions, raw float BEV-head outputs, consumed BEV, base grid and planner state",
148
+ "intermediate_transformer_tokens_saved": False,
149
+ "write_policy": "Bounded asynchronous lossless compression; no sampling or silent drops",
150
+ })
151
+ self._status("running")
152
+ self.worker = threading.Thread(target=self._worker, name="vggt-debug-writer", daemon=True)
153
+ self.worker.start()
154
+
155
+ def _status(self, phase):
156
+ atomic_json(self.root / "status.json", {
157
+ "status": phase, "frames": self.frames, "passes": self.passes,
158
+ "unique_views": len(self.assets), "bytes": self.bytes,
159
+ "write_s": self.write_s, "snapshot_s": self.copy_s,
160
+ "queued_frames": self.pending.qsize(), "error": str(self.error) if self.error else None,
161
+ "run_error": self.run_error,
162
+ })
163
+
164
+ def check(self):
165
+ if self.error is not None:
166
+ raise RuntimeError(f"VGGT debug archive failed: {self.error}") from self.error
167
+ if self.closed:
168
+ raise RuntimeError("VGGT debug archive is closed")
169
+
170
+ def attach(self, estimator):
171
+ import torch
172
+
173
+ self.check()
174
+ backend = estimator.backend
175
+ if not callable(getattr(backend, "infer", None)) or not callable(getattr(backend, "nav", None)):
176
+ raise ValueError("VGGT debug capture requires a backend with infer() and an enabled BEV head")
177
+ original_infer = backend.infer
178
+ infer_signature = inspect.signature(original_infer)
179
+ original_estimate = estimator.estimate_pose
180
+ estimate_signature = inspect.signature(original_estimate)
181
+ run = json.loads((self.root / "run.json").read_text())
182
+ run["runtime"] = {"torch": str(torch.__version__), "cuda": torch.version.cuda,
183
+ "backend": type(backend).__name__, "estimator": type(estimator).__name__,
184
+ "cuda_graphs": bool(getattr(backend, "cuda_graphs", False)),
185
+ "compiled": bool(getattr(backend, "_compiled", False))}
186
+ atomic_json(self.root / "run.json", run)
187
+
188
+ @functools.wraps(original_infer)
189
+ def infer(images, *args, **kwargs):
190
+ if self.current is None:
191
+ return original_infer(images, *args, **kwargs)
192
+ started = time.perf_counter()
193
+ self.active_pass = {"images": snapshot(images), "image_dtype": str(images.dtype), "head_calls": []}
194
+ self.current["passes"].append(self.active_pass)
195
+ self.copy_s += time.perf_counter() - started
196
+ try:
197
+ result = original_infer(images, *args, **kwargs)
198
+ except BaseException as exc:
199
+ self.active_pass["inference_error"] = str(exc)
200
+ raise
201
+ started = time.perf_counter()
202
+ try:
203
+ bound = infer_signature.bind(images, *args, **kwargs)
204
+ bound.apply_defaults()
205
+ names = ("c2w", "K", "depth", "depth_conf", "hw", "covis", "log_scale")
206
+ prediction = {name: getattr(result, name, None) for name in names}
207
+ nav = getattr(backend, "last_nav", None)
208
+ self.active_pass.update({
209
+ "infer_args": snapshot({key: bound.arguments.get(key) for key in ("n_depth", "focal")}),
210
+ "effective_calib_focal": snapshot(getattr(backend, "calib_focal", None)),
211
+ "prediction": snapshot(prediction),
212
+ "pose_encoding": snapshot(nav.get("pose_enc")) if nav else None,
213
+ })
214
+ finally:
215
+ self.copy_s += time.perf_counter() - started
216
+ return result
217
+
218
+ @functools.wraps(original_estimate)
219
+ def estimate(*args, **kwargs):
220
+ if self.current is None:
221
+ return original_estimate(*args, **kwargs)
222
+ begin = len(self.current["passes"])
223
+ bound = estimate_signature.bind(*args, **kwargs)
224
+ bound.apply_defaults()
225
+ anchor = bound.arguments.get("odom_anchor")
226
+ context = {key: bound.arguments.get(key) for key in ("ref_rel_poses", "ref_cam_ids")}
227
+ context["source_context"] = bound.arguments.get("kwargs", {})
228
+ context["odom_anchor"] = ({key: value for key, value in anchor.items()
229
+ if key not in ("image", "extra_images")} if anchor else None)
230
+ result = original_estimate(*args, **kwargs)
231
+ calls = self.current["passes"][begin:]
232
+ for index, call in enumerate(calls):
233
+ call["estimate_context"] = snapshot(context)
234
+ call["estimator_info"] = snapshot(getattr(estimator, "last_info", {})) if index == 0 else {}
235
+ call["principal_point_rotation"] = snapshot(getattr(estimator, "_R_model_to_cam", None))
236
+ call["camera_calibrations"] = snapshot(getattr(estimator, "_cameras", None))
237
+ if index == 0:
238
+ poses, valid, confidence = result
239
+ call["relative_pose_result"] = snapshot({
240
+ "poses": poses.matrix() if hasattr(poses, "matrix") else poses,
241
+ "valid": valid, "confidence": confidence,
242
+ })
243
+ return result
244
+
245
+ self._replace(backend, "infer", infer)
246
+ self._replace(estimator, "estimate_pose", estimate)
247
+ self._replace(backend, "nav", _RecordingHead(backend.nav, self))
248
+
249
+ def _replace(self, owner, name, replacement):
250
+ self.hooks.append((owner, name, name in vars(owner), vars(owner).get(name)))
251
+ setattr(owner, name, replacement)
252
+
253
+ def begin_frame(self, raw):
254
+ self.check()
255
+ if self.current is not None:
256
+ raise RuntimeError("Previous VGGT debug frame was not completed")
257
+ number = int(raw["frame_idx"])
258
+ if number < 0 or number in self.submitted:
259
+ raise ValueError("VGGT debug frame IDs must be unique and nonnegative")
260
+ self.current = {"capture_frame": number, "source": snapshot({key: value for key, value in raw.items()
261
+ if key not in ("rgb_jpg", "depth_png")}), "passes": []}
262
+ self.active_pass = None
263
+
264
+ def finish_frame(self, **outputs):
265
+ self.check()
266
+ if self.current is None:
267
+ raise RuntimeError("No current VGGT debug frame")
268
+ started = time.perf_counter()
269
+ self.current["outputs"] = snapshot(outputs)
270
+ self.copy_s += time.perf_counter() - started
271
+ job, self.current, self.active_pass = self.current, None, None
272
+ try:
273
+ self.pending.put_nowait(job)
274
+ except queue.Full as exc:
275
+ self.current = job
276
+ raise RuntimeError("VGGT debug writer cannot keep up; no frames were silently dropped") from exc
277
+ self.submitted.add(job["capture_frame"])
278
+
279
+ def _view(self, image):
280
+ image = np.ascontiguousarray(image)
281
+ digest = hashlib.sha256(str((image.dtype.str, image.shape)).encode() + image.tobytes()).hexdigest()
282
+ if digest not in self.assets:
283
+ path = self.root / "views" / f"{digest}.npz"
284
+ write_npz(path, {"image": image})
285
+ self.bytes += path.stat().st_size
286
+ self.assets.add(digest)
287
+ return {"asset": digest, "shape": list(image.shape), "dtype": str(image.dtype)}
288
+
289
+ def _write(self, job):
290
+ started = time.perf_counter()
291
+ number = job["capture_frame"]
292
+ directory = self.root / "frames" / f"{number:08d}"
293
+ directory.mkdir()
294
+ audit = job.get("outputs", {}).get("observation", {}).get("retrieval", [])
295
+ for call in job["passes"]:
296
+ images = call.pop("images")
297
+ tags = call.get("estimator_info", {}).get("view_tags", [])
298
+ call["views"] = []
299
+ for index, image in enumerate(images):
300
+ tag = tags[index] if index < len(tags) else f"view_{index}"
301
+ view = {"index": index, "role": tag, **self._view(image)}
302
+ if tag.startswith("ref") and tag.endswith("_L"):
303
+ reference = int(tag[3:-2])
304
+ if reference < len(audit):
305
+ view["reference"] = audit[reference]
306
+ call["views"].append(view)
307
+ arrays = {}
308
+ data = pack(job, arrays)
309
+ write_npz(directory / "arrays.npz", arrays)
310
+ # This JSON is the completion marker, written after all referenced assets.
311
+ atomic_json(directory / "frame.json", data)
312
+ with (self.root / "index.jsonl").open("a") as stream:
313
+ stream.write(json.dumps({"capture_frame": number, "passes": len(job["passes"]),
314
+ "file": f"frames/{number:08d}/frame.json"}) + "\n")
315
+ self.frames += 1
316
+ self.passes += len(job["passes"])
317
+ self.bytes += sum(path.stat().st_size for path in directory.iterdir())
318
+ self.write_s += time.perf_counter() - started
319
+ self._status("running")
320
+
321
+ def _worker(self):
322
+ while True:
323
+ job = self.pending.get()
324
+ try:
325
+ if job is None:
326
+ return
327
+ if self.error is None:
328
+ self._write(job)
329
+ except BaseException as exc:
330
+ self.error = exc
331
+ if self.on_error:
332
+ try:
333
+ self.on_error(exc)
334
+ except Exception as callback_error:
335
+ self.error = RuntimeError(f"{exc}; archive error callback also failed: {callback_error}")
336
+ finally:
337
+ self.pending.task_done()
338
+
339
+ def close(self, error=None):
340
+ if self.closed:
341
+ return
342
+ self.run_error = str(error) if error else None
343
+ # Retain an interrupted inference and whatever outputs were available.
344
+ if self.current is not None:
345
+ job, self.current = self.current, None
346
+ job["interrupted"] = str(error) if error else "Frame interrupted before completion"
347
+ self.pending.put(job)
348
+ for owner, name, existed, value in reversed(self.hooks):
349
+ if existed:
350
+ setattr(owner, name, value)
351
+ else:
352
+ delattr(owner, name)
353
+ self.hooks.clear()
354
+ self.active_pass = None
355
+ self.pending.put(None)
356
+ self.worker.join()
357
+ self.closed = True
358
+ self._status("failed" if self.error else "closed")
359
+ if self.error is not None:
360
+ raise RuntimeError(f"VGGT debug archive failed: {self.error}") from self.error
361
+
362
+
363
+ def planner_snapshot(episode):
364
+ result = {key: getattr(episode, key, None) for key in
365
+ ("pose", "expect", "bumps", "route", "route_age", "no_route", "side", "log_scale", "n_bumps")}
366
+ world = getattr(episode, "world", None)
367
+ result["world"] = ({key: getattr(world, key) for key in ("o", "num", "den", "seen", "c")}
368
+ if world is not None else None)
369
+ return result
370
+
371
+
372
+ def load_debug_frame(directory, number):
373
+ root = Path(directory).resolve()
374
+ frame = root / "frames" / f"{int(number):08d}"
375
+ if int(number) < 0 or frame.resolve().parent != (root / "frames").resolve():
376
+ raise ValueError("Invalid debug frame")
377
+ data = json.loads((frame / "frame.json").read_text())
378
+ with np.load(frame / "arrays.npz", allow_pickle=False) as archive:
379
+ def unpack(value):
380
+ if isinstance(value, dict):
381
+ if "npz_key" in value:
382
+ array = archive[value["npz_key"]].copy()
383
+ if list(array.shape) != value["shape"] or str(array.dtype) != value["dtype"]:
384
+ raise ValueError("VGGT debug array metadata mismatch")
385
+ return array
386
+ return {key: unpack(item) for key, item in value.items()}
387
+ if isinstance(value, list):
388
+ return [unpack(item) for item in value]
389
+ return value
390
+ return unpack(data)
391
+
392
+
393
+ def load_debug_view(directory, asset):
394
+ if len(asset) != 64 or any(char not in "0123456789abcdef" for char in asset):
395
+ raise ValueError("Invalid VGGT view asset")
396
+ root = Path(directory).resolve()
397
+ path = root / "views" / f"{asset}.npz"
398
+ if path.resolve().parent != (root / "views").resolve():
399
+ raise ValueError("VGGT view asset escapes archive")
400
+ with np.load(path, allow_pickle=False) as archive:
401
+ return archive["image"].copy()
cases/20261026_goal1012_05/code/stretch_ai/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2024 Hello Robot, Inc.
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.