Add Stretch navigation debug case with VGGT tensors, sensor recording and replay
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- README.md +194 -0
- SHA256SUMS +98 -0
- archives/CROSS_source.tar.gz +3 -0
- archives/capture.tar +3 -0
- archives/reference_map.tar +3 -0
- archives/run_core.tar.gz +3 -0
- archives/vggt_frames_000.tar +3 -0
- archives/vggt_frames_001.tar +3 -0
- archives/vggt_frames_002.tar +3 -0
- archives/vggt_metadata.tar.gz +3 -0
- archives/vggt_views.tar +3 -0
- code/lite3_ROS/LICENSE +21 -0
- code/lite3_ROS/scripts/capture_stretch_cross.py +131 -0
- code/lite3_ROS/scripts/inspect_stretch_vggt_debug.py +98 -0
- code/lite3_ROS/scripts/live_stretch_cross_nav.py +936 -0
- code/lite3_ROS/scripts/monitor_stretch_transport.py +74 -0
- code/lite3_ROS/scripts/replay_stretch_cross_nav.py +164 -0
- code/lite3_ROS/scripts/view_stretch_cross_nav_live_run.py +69 -0
- code/lite3_ROS/tests/test_stretch_capture_format.py +15 -0
- code/lite3_ROS/tests/test_stretch_nav_control.py +156 -0
- code/lite3_ROS/tests/test_stretch_nav_geometry.py +39 -0
- code/lite3_ROS/tests/test_stretch_nav_handoff.py +410 -0
- code/lite3_ROS/tests/test_stretch_nav_learned.py +55 -0
- code/lite3_ROS/tests/test_stretch_nav_recovery.py +222 -0
- code/lite3_ROS/tests/test_stretch_nav_replay.py +250 -0
- code/lite3_ROS/tests/test_stretch_nav_routing.py +162 -0
- code/lite3_ROS/tests/test_stretch_nav_survey.py +215 -0
- code/lite3_ROS/tests/test_stretch_transport.py +80 -0
- code/lite3_ROS/tests/test_stretch_vggt_debug.py +237 -0
- code/lite3_ROS/web_console/__init__.py +0 -0
- code/lite3_ROS/web_console/cross_run.py +116 -0
- code/lite3_ROS/web_console/static/cross_nav.css +3 -0
- code/lite3_ROS/web_console/static/cross_nav_live.html +26 -0
- code/lite3_ROS/web_console/static/cross_nav_live.js +233 -0
- code/lite3_ROS/web_console/static/vendor/plotly.min.js +0 -0
- code/lite3_ROS/web_console/stretch_nav_control.py +191 -0
- code/lite3_ROS/web_console/stretch_nav_footprint.py +87 -0
- code/lite3_ROS/web_console/stretch_nav_geometry.py +99 -0
- code/lite3_ROS/web_console/stretch_nav_learned.py +57 -0
- code/lite3_ROS/web_console/stretch_nav_recovery.py +391 -0
- code/lite3_ROS/web_console/stretch_nav_replay.py +226 -0
- code/lite3_ROS/web_console/stretch_nav_report.py +352 -0
- code/lite3_ROS/web_console/stretch_nav_survey.py +131 -0
- code/lite3_ROS/web_console/stretch_nav_viewer.py +178 -0
- code/lite3_ROS/web_console/stretch_transport.py +24 -0
- code/lite3_ROS/web_console/stretch_vggt_debug.py +401 -0
- code/stretch_ai/LICENSE +202 -0
- code/stretch_ai/scripts/capture_lingbot_rgbd_ros2.py +176 -0
- code/stretch_ai/scripts/depth_nav_control.py +363 -0
- code/stretch_ai/scripts/depth_nav_debug.py +539 -0
README.md
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
pretty_name: CROSS navigation debug — Stretch head survey and graph attachment
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
tags:
|
| 6 |
+
- robotics
|
| 7 |
+
- navigation
|
| 8 |
+
- vggt
|
| 9 |
+
- rgb-d
|
| 10 |
+
- odometry
|
| 11 |
+
- debugging
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# CROSS navigation debug
|
| 15 |
+
|
| 16 |
+
A self-contained recording of a supervised Stretch navigation run on **2026-10-26 (Asia/Singapore)**,
|
| 17 |
+
targeting phone-map keyframe **1012**, including the exact VGGT inputs and outputs.
|
| 18 |
+
|
| 19 |
+
**Observed failure:** during a left/down head survey, localization remained committed, but the local
|
| 20 |
+
Stretch adapter's measured-depth check rejected every nearby connection to the reference map graph.
|
| 21 |
+
The adapter then stopped with `no global route; navigation ended`.
|
| 22 |
+
This dataset does **not** establish a bug in native CROSS or its learned BEV head. It includes those
|
| 23 |
+
outputs, the adapter and the depth evidence so their interaction can be investigated.
|
| 24 |
+
|
| 25 |
+
| Item | Included |
|
| 26 |
+
|---|---|
|
| 27 |
+
| Run | `stretch_cross_nav_live_20261026_goal1012_02` |
|
| 28 |
+
| Actual navigation | 114.44 s; 7.88 m odometry distance; goal not reached |
|
| 29 |
+
| Final camera XY distance to goal | 5.56 m |
|
| 30 |
+
| Sensor recording | 680 synchronized RGB + aligned depth frames, intrinsics, odometry, camera/base TF, timestamped head joints |
|
| 31 |
+
| Published processing records | 381, with 380 actual VGGT inference passes |
|
| 32 |
+
| VGGT inputs | 429 unique lossless tensors, referenced 2,662 times across the input groups |
|
| 33 |
+
| BEV replay | 380 original occupancy/observability/uncertainty image sets |
|
| 34 |
+
| Numeric outputs | VGGT predictions, raw navigation heads, consumed camera BEV, base BEV and native planner memory |
|
| 35 |
+
| Reference map | Record3D `2026-10-22--15-48-58`, including native map and its image/descriptor store |
|
| 36 |
+
| Additional evidence | Measured obstacles, footprint snapshots, routes, retrieval results, control commands, robot status, transport timings, resolved configs and shutdown audit |
|
| 37 |
+
| Source | Native CROSS commit `4781371e6f4db4241be0a0df7c238436680ee268`, local adapter, relay, inspector, replay viewer and relevant tests |
|
| 38 |
+
|
| 39 |
+
The recording uses RGB and external odometry for CROSS. Measured robot depth is used separately by
|
| 40 |
+
the adapter's execution/attachment checks. There is no separate raw IMU stream in this case.
|
| 41 |
+
The phone map and robot odometry are estimates, not ground truth.
|
| 42 |
+
|
| 43 |
+
## Start with the failure frames
|
| 44 |
+
|
| 45 |
+
Indices below are **capture frame indices**, not reference-map keyframe IDs or robot source-frame IDs.
|
| 46 |
+
Robot source-frame ID is capture index + 1 in this run.
|
| 47 |
+
|
| 48 |
+
| Frame | Capture-relative time | Observation |
|
| 49 |
+
|---|---:|---|
|
| 50 |
+
| 639 | 159.88 s | Stationary head survey starts after a learned-path footprint veto |
|
| 51 |
+
| 661 | 165.35 s | Front/down view accepted as settled; left/down target begins |
|
| 52 |
+
| 675 | 168.89 s | Still localized; seven graph attachments survive the depth check |
|
| 53 |
+
| 677 | 169.39 s | Still localized; zero attachments survive; exact obstacle evidence saved |
|
| 54 |
+
| 679 | 169.89 s | Final observation; localized, nearest map keyframe 1057 about 0.183 m away, zero attachments |
|
| 55 |
+
|
| 56 |
+
The attachment radius is 0.75 m. Empty attachments are produced by the local adapter before its
|
| 57 |
+
execution gate stops navigation. `tools/analyze_attachment.py` rechecks the recorded depth veto
|
| 58 |
+
without loading a model or executing robot commands. Whether the returns are physical obstacles,
|
| 59 |
+
robot self observations, depth noise or accumulated old returns remains to be diagnosed.
|
| 60 |
+
|
| 61 |
+
The earlier multi-second camera lag did **not** recur in this case. Estimated source age at PC
|
| 62 |
+
receipt was 83 ms median / 131 ms p95. The source-age estimate is a lower bound based on a recent
|
| 63 |
+
robot status sample, not a subtraction of wall clocks across computers.
|
| 64 |
+
|
| 65 |
+
VGGT's seven input views at failure frame 677:
|
| 66 |
+
|
| 67 |
+

|
| 68 |
+
|
| 69 |
+
Raw head output, consumed camera BEV, and reprojected robot-base BEV at the same frame:
|
| 70 |
+
|
| 71 |
+

|
| 72 |
+
|
| 73 |
+
Additional input/depth/BEV previews are in [`previews/`](previews).
|
| 74 |
+
Small reports are directly browsable in [`reports/`](reports/stretch_cross_nav_live_20261026_goal1012_02).
|
| 75 |
+
|
| 76 |
+
## Download and inspect
|
| 77 |
+
|
| 78 |
+
```bash
|
| 79 |
+
hf download jizhuochen/CROSS_nav_debug --repo-type dataset --local-dir CROSS_nav_debug
|
| 80 |
+
cd CROSS_nav_debug
|
| 81 |
+
python tools/unpack.py --output extracted
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
The unpacker verifies every archive's SHA-256, validates the individual run/map members and extracts
|
| 85 |
+
into a new directory, including CROSS's validated relative package alias. Approximately 3.5 GB is
|
| 86 |
+
downloaded; allow another 3.5 GB for extraction.
|
| 87 |
+
Use a Python environment with `numpy` and `opencv-python` for the viewer/inspector. The full recorded
|
| 88 |
+
environment is in `environment/pip_freeze.txt`; it is a version record, not a portable installer.
|
| 89 |
+
|
| 90 |
+
Replay the recorded RGB, map/route, and BEV with zoom/rotation and layer controls:
|
| 91 |
+
|
| 92 |
+
```bash
|
| 93 |
+
python code/lite3_ROS/scripts/view_stretch_cross_nav_live_run.py \
|
| 94 |
+
--run extracted/runs/stretch_cross_nav_live_20261026_goal1012_02 --port 8088
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
Open <http://127.0.0.1:8088> and click **Replay recording**. This viewer opens no robot connection,
|
| 98 |
+
loads no model and cannot arm navigation.
|
| 99 |
+
|
| 100 |
+
Export exact model input tensors, an input contact sheet, predicted depth and the BEV stages:
|
| 101 |
+
|
| 102 |
+
```bash
|
| 103 |
+
python code/lite3_ROS/scripts/inspect_stretch_vggt_debug.py \
|
| 104 |
+
--debug extracted/runs/stretch_cross_nav_live_20261026_goal1012_02/vggt_debug \
|
| 105 |
+
--frame 677 --output inspection_677
|
| 106 |
+
|
| 107 |
+
python tools/analyze_attachment.py --extracted extracted --frame 677
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
## Data layout
|
| 111 |
+
|
| 112 |
+
The nine archives are independent download units; the VGGT numeric frames are split into three
|
| 113 |
+
shards of at most about 700 MiB. Extract **all** archives to obtain the complete case.
|
| 114 |
+
|
| 115 |
+
```text
|
| 116 |
+
archives/
|
| 117 |
+
run_core.tar.gz # run/query map, replay BEVs, logs, footprint evidence, configs
|
| 118 |
+
capture.tar # exact recorded JPEG RGB and uint16 PNG depth, raw observations
|
| 119 |
+
vggt_metadata.tar.gz # run provenance, frame index, planner config, writer status
|
| 120 |
+
vggt_views.tar # lossless content-addressed VGGT input tensors
|
| 121 |
+
vggt_frames_000.tar # per-frame manifest + numeric outputs (three shards)
|
| 122 |
+
vggt_frames_001.tar
|
| 123 |
+
vggt_frames_002.tar
|
| 124 |
+
reference_map.tar # original phone map and complete .store sidecar
|
| 125 |
+
CROSS_source.tar.gz # frozen native source, with upstream license
|
| 126 |
+
code/ # local adapter/relay/replay/inspection source and tests
|
| 127 |
+
environment/ # versions, GPU information, source provenance
|
| 128 |
+
reports/ # directly browsable diagnostic logs and summaries
|
| 129 |
+
previews/ # selected VGGT input groups, depth and BEV stages
|
| 130 |
+
manifest.json # archive/member sizes, SHA-256 hashes, extraction paths
|
| 131 |
+
SHA256SUMS # checksums for every published file other than this checksum file
|
| 132 |
+
tools/ # verified extraction and offline attachment diagnosis
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
Extraction creates `runs/<run-id>/`, `maps/record3d_mapping_20261022_154858/` and `source/CROSS/`.
|
| 136 |
+
|
| 137 |
+
### VGGT archive schema
|
| 138 |
+
|
| 139 |
+
`vggt_debug/frames/<capture-index>/frame.json` describes each call and references arrays in the
|
| 140 |
+
same directory's `arrays.npz`. Each actual call records its view order/roles, reference IDs where
|
| 141 |
+
available, and links to `vggt_debug/views/<sha256>.npz`.
|
| 142 |
+
|
| 143 |
+
These are the exact RGB CHW floating-point tensors **after CROSS preprocessing**. References may
|
| 144 |
+
be retrieved map/session keyframes or an accepted anchor; they are not necessarily adjacent video
|
| 145 |
+
frames. Repeated inputs are deduplicated without JPEG recompression or clipping resize overshoot.
|
| 146 |
+
One processing record has zero model passes and is not assigned another frame's predictions.
|
| 147 |
+
|
| 148 |
+
Outputs include the model's camera poses/intrinsics, depth/confidence, covisibility and scale
|
| 149 |
+
fields where returned; raw occupancy/observability/uncertainty heads and gravity/metric fields;
|
| 150 |
+
the actual BEV consumed by navigation; base-frame reprojection; and planner world-map accumulators
|
| 151 |
+
and configuration. The source includes `load_debug_frame` and `load_debug_view` to restore the
|
| 152 |
+
manifest/NPZ structure without pickle.
|
| 153 |
+
|
| 154 |
+
### Geometry and timing
|
| 155 |
+
|
| 156 |
+
Saved RGB and aligned depth are 480 pixels wide by 640 high after the relay's 90-degree clockwise
|
| 157 |
+
rotation. Intrinsics and the optical transform were rotated consistently. Depth PNG values are
|
| 158 |
+
uint16 millimetres. `camera_pose` is `T_odom_camera`, `base_pose_matrix` is `T_odom_base`, and
|
| 159 |
+
`camera_in_base` is `T_base_camera`. All three are homogeneous 4x4 transforms.
|
| 160 |
+
Camera/base TF and head joints are associated with the source image timestamp. Head pan/tilt
|
| 161 |
+
changes therefore use the measured image-time extrinsic, not the requested head target.
|
| 162 |
+
|
| 163 |
+
The reference map has its own coordinate system; use the saved map alignment/display transforms
|
| 164 |
+
rather than assuming its axes match robot odometry. Source sensor stamps use the robot clock;
|
| 165 |
+
receipt timestamps use the PC clock. `capture/transport.jsonl`, `robot_status.jsonl` and
|
| 166 |
+
`network.jsonl` retain the measurements needed to distinguish those stages.
|
| 167 |
+
|
| 168 |
+
## Reproduction scope and provenance
|
| 169 |
+
|
| 170 |
+
Native CROSS source was unchanged. The local adapter adds route attachment, remaining-route cost,
|
| 171 |
+
head surveying, measured-depth/footprint vetoes and command freshness checks. These policies and
|
| 172 |
+
the final execution gate are included in `code/lite3_ROS/`; the robot-side lease and head action
|
| 173 |
+
handoff are included in `code/stretch_ai/`. The Git HEAD of the adapter alone is insufficient:
|
| 174 |
+
its relevant local source was uncommitted and is included directly.
|
| 175 |
+
|
| 176 |
+
The configured maximum base speeds were 0.10 m/s and 0.25 rad/s, source evidence expired after
|
| 177 |
+
1.2 s, and the execution footprint was 0.46 m wide. This case does not validate completion of all
|
| 178 |
+
six survey views or arrival at the goal.
|
| 179 |
+
|
| 180 |
+
The recorded model outputs can be inspected entirely offline. Re-running a model needs the native
|
| 181 |
+
CROSS environment and the pretrained files from
|
| 182 |
+
[Jamie-nus/VGGT-Omega-CROSS](https://huggingface.co/Jamie-nus/VGGT-Omega-CROSS).
|
| 183 |
+
Their repository revision and individual SHA-256 hashes are in
|
| 184 |
+
`reports/stretch_cross_nav_live_20261026_goal1012_02/vggt_provenance.json`.
|
| 185 |
+
The checkpoint weights are not duplicated in this dataset.
|
| 186 |
+
|
| 187 |
+
Arrays, RGB/depth images and native image/descriptor stores are byte-identical to the source recording.
|
| 188 |
+
Sharing copies of text metadata/source have session credentials, local absolute paths and private
|
| 189 |
+
interface addresses removed or replaced with portable/documentation values. Numerical transforms,
|
| 190 |
+
timestamps, commands and predictions are preserved. Three model paths inside the query map's config
|
| 191 |
+
were also made portable; every numerical map column was verified byte-identical. The original and
|
| 192 |
+
shared map-container hashes are recorded in `environment/map_metadata_sanitization.json`.
|
| 193 |
+
Source files retain their upstream licenses;
|
| 194 |
+
no additional recording license is asserted here.
|
SHA256SUMS
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
e97427af55a3cb4e014152ed6a512e5827ba5cd84daf38b0aafe25ce77a2917e README.md
|
| 2 |
+
c3dd418506684ae4b05b49daeeb6456509d1542621911e0029fa6c420d75c64b archives/CROSS_source.tar.gz
|
| 3 |
+
de8a67ce4a2f83967e3115038c128c270568475139b2bc5ae12f067e92db0417 archives/capture.tar
|
| 4 |
+
3876fa21325aea0a41dba3f647a8645815ed9f431c3e3e399e8a3f3d47768200 archives/reference_map.tar
|
| 5 |
+
afbd7f8dd07e62358316abd6d6fe8535376c28ddca90dbb1fa3dc363e79c551e archives/run_core.tar.gz
|
| 6 |
+
a53a2227a4b83fb50fd1bcec93130898312c19501c76ea848cf8b0528638b8c8 archives/vggt_frames_000.tar
|
| 7 |
+
e8eaf555b391a5583eb22dbacd49b347cfa7a20f0536738942c9bee2352364d5 archives/vggt_frames_001.tar
|
| 8 |
+
591ad815693b373535d3a41dd5c936adc6b31824e62942c14fb102cd7e5aa6a4 archives/vggt_frames_002.tar
|
| 9 |
+
4f348ad90455e177818d9b542f15e1feed0100a7082117fd9f5bf0b4ba92dd38 archives/vggt_metadata.tar.gz
|
| 10 |
+
179fc2cfea7987908b4d71c743d9c9bcba2e7bfc3a195cf24258a7e7ce79caf0 archives/vggt_views.tar
|
| 11 |
+
49a6e137748b934e2f78b15cf74704fd8fdcb26107c5d210d783648287345750 code/lite3_ROS/LICENSE
|
| 12 |
+
7e861070432a0da598c7e4974397c162df0582df0c94da41dd6e09efc7efcf27 code/lite3_ROS/scripts/capture_stretch_cross.py
|
| 13 |
+
5445e49f09b7891d3ecf962aba966bf748dd50cba931df0382e1d416db1f04f3 code/lite3_ROS/scripts/inspect_stretch_vggt_debug.py
|
| 14 |
+
bd96b963b13835dd45b3f3125e2893b8562971443782b29b1f86e6cf06c51fb8 code/lite3_ROS/scripts/live_stretch_cross_nav.py
|
| 15 |
+
1290eafa6369623d9d36fcbd7c240b92dbee54efbd9372b1fc64732a2fa9b90e code/lite3_ROS/scripts/monitor_stretch_transport.py
|
| 16 |
+
17ebc68ab1e30bc0601d1eb2f212e449dd3036d4a0dce7d48662431693ef4967 code/lite3_ROS/scripts/replay_stretch_cross_nav.py
|
| 17 |
+
7b9b7ac8ebdcb8884808a4cf34b4ef0fdf5ee2b042f0ffd81fca16d4e4fefbb9 code/lite3_ROS/scripts/view_stretch_cross_nav_live_run.py
|
| 18 |
+
23cd5d206ea6e42850dc750d6712ff305b9896d9c09d0924e3c86a1131690c90 code/lite3_ROS/tests/test_stretch_capture_format.py
|
| 19 |
+
a92a704acfb8c5fa19fdd695114877da2b5ca315282782e518da50d22b24b942 code/lite3_ROS/tests/test_stretch_nav_control.py
|
| 20 |
+
235a2d70fa9a747de21c4478f5676d43211c1451188e83829c085432a5d11310 code/lite3_ROS/tests/test_stretch_nav_geometry.py
|
| 21 |
+
3dca0e20341b3b69c755022b144c81b0565cad1f47ea7d05b7b6d4d8d59ba09d code/lite3_ROS/tests/test_stretch_nav_handoff.py
|
| 22 |
+
b15144072cf25d495fc432d9b0f22abfe40996cf07e0be5e8e47beef0026055b code/lite3_ROS/tests/test_stretch_nav_learned.py
|
| 23 |
+
9ddca6a3f18124eec96edee4558fa568ed7a583c1a6dc20dc709987e9a8d76ce code/lite3_ROS/tests/test_stretch_nav_recovery.py
|
| 24 |
+
b18a7a46290b231b23c611ea34f22c2d542846d4d9e1dd9185086744a81608a9 code/lite3_ROS/tests/test_stretch_nav_replay.py
|
| 25 |
+
f706d7715b2dec1f755997c5c98d1c7d0f93475da23ba026c91b7c080b36138b code/lite3_ROS/tests/test_stretch_nav_routing.py
|
| 26 |
+
cd219a565a5336cad8ab3dbe78c58cb5283f34fb7b966ab834d4982cccac3f4e code/lite3_ROS/tests/test_stretch_nav_survey.py
|
| 27 |
+
a37f95cbb179efb7e72d0f29fe49a06a2e53c48ae7b3d6e686c4b68e59a816d7 code/lite3_ROS/tests/test_stretch_transport.py
|
| 28 |
+
3581f52fa7653cbfdb852f07654dcc5f0f0395133c9d3a81d789a7d3f7f57fda code/lite3_ROS/tests/test_stretch_vggt_debug.py
|
| 29 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 code/lite3_ROS/web_console/__init__.py
|
| 30 |
+
96cbcccde95c2b6da8d4cc9cc237ecbdff6604218e59845e92429df9e38ba43b code/lite3_ROS/web_console/cross_run.py
|
| 31 |
+
522597d97ddbf997e7f80246a6c6ea17e11e66435db1669a4ac9fddf8b9b2be2 code/lite3_ROS/web_console/static/cross_nav.css
|
| 32 |
+
7837119d23b87b5776017dfc86f8aa121327ab4611c15ee409e7866425e325e3 code/lite3_ROS/web_console/static/cross_nav_live.html
|
| 33 |
+
d8daea837482d5ea105e4e5e21dc483d4343401568fefbad6f6536ec015422db code/lite3_ROS/web_console/static/cross_nav_live.js
|
| 34 |
+
3b6e15d45dbb7fca5bd2094291e961ddc5472cd887009e6009a56dab668d721f code/lite3_ROS/web_console/static/vendor/plotly.min.js
|
| 35 |
+
fd175e65c176cac29a608d8e3457df0dc69d0b41f692ac511ea38eecbec67a4b code/lite3_ROS/web_console/stretch_nav_control.py
|
| 36 |
+
670f0d2a352f836915a0dd8af22ba3f9268fad8fba0ff16c375f76dd759018c0 code/lite3_ROS/web_console/stretch_nav_footprint.py
|
| 37 |
+
0851f120f415788483d6ef52c4bdb8afd14d9651a1ad4acb87ae19489dd1b3ad code/lite3_ROS/web_console/stretch_nav_geometry.py
|
| 38 |
+
75facca8ee2cbf17055298bc44301fd9c6c6313e133e7c6a5bedc36ab667710c code/lite3_ROS/web_console/stretch_nav_learned.py
|
| 39 |
+
b04985fb1dd67d3127a4b1d52e8571d9a9b5278d289909f6bedc464348ead7fa code/lite3_ROS/web_console/stretch_nav_recovery.py
|
| 40 |
+
8a8b4c95878343eae73605474aa818cb7e283b13c3155b2d2492ddf1c5832570 code/lite3_ROS/web_console/stretch_nav_replay.py
|
| 41 |
+
15318ba6d6e7b574c0ba50d49db1ebdbd03c44ff0c0f5e33ff3fb69462d3c4fc code/lite3_ROS/web_console/stretch_nav_report.py
|
| 42 |
+
7b9c6018f60f9cb69e0c3209807730e02dc3d645ceedd7d1e5a16527d1845137 code/lite3_ROS/web_console/stretch_nav_survey.py
|
| 43 |
+
8fdacb65956c47aff77d8f6a19a72960c117a7d89c7a6429f4cf7288dd2b272b code/lite3_ROS/web_console/stretch_nav_viewer.py
|
| 44 |
+
dde3814d364392aab6078402199a743b9653cb3b90ebfb5bd2932463930379a2 code/lite3_ROS/web_console/stretch_transport.py
|
| 45 |
+
c9372443e127bbce7e6b7a0a920607c4115cdfa4b3ba0eb98cd1f9a8d282e16b code/lite3_ROS/web_console/stretch_vggt_debug.py
|
| 46 |
+
980c4c38bfef6167490f632ac7f39438bc32b14e00d3ad95147f862066ac496a code/stretch_ai/LICENSE
|
| 47 |
+
741574f7529734e5492a50ccd51e190a975f67f864fe8ec92c66063d9ed77fcb code/stretch_ai/scripts/capture_lingbot_rgbd_ros2.py
|
| 48 |
+
3838bb9e7bab6f71b1e10bc2f24c10f614f671897fbfdf1d5545db1ba952184b code/stretch_ai/scripts/depth_nav_control.py
|
| 49 |
+
ea99cdb412cc962f5e1cf72ed0dd255eb177024f1a7169349af5b78746386815 code/stretch_ai/scripts/depth_nav_debug.py
|
| 50 |
+
c3ead5fbff583e23f5c0ef26afe123e8137c870dc1250b96ea309f453b753e46 code/stretch_ai/scripts/depth_nav_footprint.py
|
| 51 |
+
9ad308cb8123eb819747136140dacd1e1a7571604412c764080935d71aa4fcc5 code/stretch_ai/scripts/depth_nav_live.py
|
| 52 |
+
b4634c91e7113318e2322782e3070c018d59971b8cadc89f56b3933c14f3bb58 code/stretch_ai/scripts/depth_nav_memory.py
|
| 53 |
+
c90128690eb85ddf883dcd48ab61980e8a2799c57368521925325daec3bdf44d code/stretch_ai/scripts/depth_nav_robot_relay.py
|
| 54 |
+
86a32af7fe5b740fd56a146571e3ae80fd99674c101f4c8143b13ff3e701d3ae code/stretch_ai/scripts/depth_nav_trajectories.py
|
| 55 |
+
03f7f193be8bbae5b03508a1d05f11d58ee2344bbf4ac3d59a945b8f2edaf19b code/stretch_ai/scripts/depth_only_path_planner.py
|
| 56 |
+
221d420a595a2ab6d6561b25d60d342867d02a0dcf0f16927fd898bc5c5578af code/stretch_ai/scripts/lingbot_depth_eval.py
|
| 57 |
+
a80afef0149ff5e7f3ceeece04c71db212aaee1403e531aaf695ee616120feb9 code/stretch_ai/scripts/lingbot_depth_geometry.py
|
| 58 |
+
55787d89d8da689b57e10a47477b93e2ae75d29a5c0feee03816845af5e9cb99 code/stretch_ai/scripts/lingbot_depth_model.py
|
| 59 |
+
7e362f18cbe8b27f6bd8a2cc6c6a858ef9adab9328ff29a12a7de8efb125eaf6 code/stretch_ai/scripts/lingbot_depth_sequence.py
|
| 60 |
+
690816adfed07da9aafb39f55a71c49b5e89998e9905a33904884cb2b3e8b91c code/stretch_ai/scripts/lingbot_voxel_map.py
|
| 61 |
+
032592ce282329eb7537a355fe096ccc3ab8eb6108ea932f62cffc252f38ddd1 environment/gpu.txt
|
| 62 |
+
0708446d8e711385c863f786140b6fd652a190b51996337e9d383f90b435d91c environment/map_metadata_sanitization.json
|
| 63 |
+
a356da246ff7accf3b5d70291af194283a4a0ee7597a7fad7d1bcbbc42cf58ca environment/package_validation.json
|
| 64 |
+
a1a25eb20977a72f4ac346c77a936fa5d46e5701b53968db49b73185f3675b29 environment/pip_freeze.txt
|
| 65 |
+
372e5c3211d1d89eb2b2a8cb859318de6f15220cf698d3b66cfbcd51827a028f environment/provenance.json
|
| 66 |
+
fc7336eeaa5742ec7efb4992b0ec69bdfc2958842cd70697b2095c284f5c2a0f manifest.json
|
| 67 |
+
468878cb4d630572fc329124ebbb7605b1f7a8b4f0d4085b560f213b8d63b041 previews/00000639/bev_stages.png
|
| 68 |
+
c511a8ec01080bdfbacea7ac7588f1444d731207d5c8b102968549acaf890919 previews/00000639/input_views.jpg
|
| 69 |
+
9000cce2c9559440ae71f2f7dc060833551a9f1db5a770b871dbb7f74045357e previews/00000639/manifest.json
|
| 70 |
+
bc522a97a003e7ddc4865f34bce426e49a304a2927d6f269794615baa5679dcd previews/00000639/predicted_depth.jpg
|
| 71 |
+
819f072d6633fa81d4c7e982d4be595f7032bd4fbc85fae30c52e81e25b33895 previews/00000661/bev_stages.png
|
| 72 |
+
62f088a3a6036fb982661bc2155374a2040ce88e4339fbf95883010a65770648 previews/00000661/input_views.jpg
|
| 73 |
+
672acf70114d1ce6daa7a35db0be56626893b0f3f8c5af847aa48d64909c82c5 previews/00000661/manifest.json
|
| 74 |
+
b357b896f4a88467727fe3b5359f287681ff587fe64cb7dec2cebdff5452a5ae previews/00000661/predicted_depth.jpg
|
| 75 |
+
0af1e69225ddfd72af3ef2fe8e72372455e8994512f867a7d052674ee561bfa1 previews/00000675/bev_stages.png
|
| 76 |
+
e544c382af38e2be2a3afb5caaf6d03c337f5b9593038431f45630b5f37e82f1 previews/00000675/input_views.jpg
|
| 77 |
+
e41074441c24d09571d0f45b0cd138fff9f693912e501c35eaf404f6a6b3ee82 previews/00000675/manifest.json
|
| 78 |
+
ce984e80fa4db5b1a07a44e35859cf0a1d3fd634ae0cc5cb80d55012895d292b previews/00000675/predicted_depth.jpg
|
| 79 |
+
82284933280f515528500f623cdaccb642dde780c20d79dfbd528085b4c5981e previews/00000677/bev_stages.png
|
| 80 |
+
e29732687f29b4cf1524bb4702b8268a0a3a3a20e23125df209b90ef67206a95 previews/00000677/input_views.jpg
|
| 81 |
+
c43e354b0981c59d2bb7bcd4df6e86de0fc677a61c8d564b34e7150a07f2ab21 previews/00000677/manifest.json
|
| 82 |
+
fcc8e24d72ad8075b8549b3f3300929949c8599391aadc35aaf498eff00e2465 previews/00000677/predicted_depth.jpg
|
| 83 |
+
eed6c9c4833a365424f3a458c29dbfaf1eb6b540a64482b2e0d28b0bcc4a22f9 previews/00000679/bev_stages.png
|
| 84 |
+
a4a13fc1b431c5156dd02bb0ffc9859df0d1f6a28b1b5946047a9997fb8282ed previews/00000679/input_views.jpg
|
| 85 |
+
b7d0a352938fac7ac91105c1de055d07fe6f95cb402f6cef04a66c0e447700d9 previews/00000679/manifest.json
|
| 86 |
+
bbcce73232fb26a9c355ebf3fc34c57c288b64773ae35d74d74635932cd4e46a previews/00000679/predicted_depth.jpg
|
| 87 |
+
cfb8a01ca341bc569fcb5b705c65fc6abe6037c59af4081f7f6871c988aa612e reports/stretch_cross_nav_live_20261026_goal1012_02/attachment_recheck_677.json
|
| 88 |
+
0ca8f075c93b12f217cb1c2fb33da71440cb0f9f90bf6faca14b44e098399fbb reports/stretch_cross_nav_live_20261026_goal1012_02/events.jsonl
|
| 89 |
+
e6217b3684ec4a811ca17334383b01d972f427737e289ec8e47db55c060d8f06 reports/stretch_cross_nav_live_20261026_goal1012_02/observations.jsonl
|
| 90 |
+
1f52f5ab6c9bb5bf1286e8fd4ad63c8cefe04b7dba735e4e2ad8225ae05e3d03 reports/stretch_cross_nav_live_20261026_goal1012_02/recording_validation.json
|
| 91 |
+
7cda24b9b0b0ea413c7b12ad463be3422893613465c2503eb35ec9f7669fcdda reports/stretch_cross_nav_live_20261026_goal1012_02/resolved_bev_config.json
|
| 92 |
+
a0757b71bb1b6aabc84112af4096dbb6b7b0b1613847994d03347eddf3de30f9 reports/stretch_cross_nav_live_20261026_goal1012_02/robot_relay_close.json
|
| 93 |
+
91560292266b5a8a9b729dc581d32efc604ce0511a1d2fcf8317ee57e1e8f292 reports/stretch_cross_nav_live_20261026_goal1012_02/stop_audit.json
|
| 94 |
+
88853550fed8b33883ffb84b9e92ab64313c3c8fd6453e8d40e3772ed5c3ec52 reports/stretch_cross_nav_live_20261026_goal1012_02/summary.json
|
| 95 |
+
7786d1b64351eba77c1c35d2c45045f416cb03938d36575c3ea9cb2d0a9e43b8 reports/stretch_cross_nav_live_20261026_goal1012_02/vggt_index.jsonl
|
| 96 |
+
b54449df6550926b70d7d6e9928b883dabab0bc494baedbf8ded7da797bc7422 reports/stretch_cross_nav_live_20261026_goal1012_02/vggt_provenance.json
|
| 97 |
+
8f71c7695c695101660353dccf0a238b838ca7f916674eb6fd4a85f6a97fed6b tools/analyze_attachment.py
|
| 98 |
+
a6ce163de4ef4f52ded94f91f2aa5b64385ceebacd2bb5fb16dba950017f3b8d tools/unpack.py
|
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
|
archives/capture.tar
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:de8a67ce4a2f83967e3115038c128c270568475139b2bc5ae12f067e92db0417
|
| 3 |
+
size 101621760
|
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
|
archives/run_core.tar.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:afbd7f8dd07e62358316abd6d6fe8535376c28ddca90dbb1fa3dc363e79c551e
|
| 3 |
+
size 301342914
|
archives/vggt_frames_000.tar
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a53a2227a4b83fb50fd1bcec93130898312c19501c76ea848cf8b0528638b8c8
|
| 3 |
+
size 732129280
|
archives/vggt_frames_001.tar
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e8eaf555b391a5583eb22dbacd49b347cfa7a20f0536738942c9bee2352364d5
|
| 3 |
+
size 730736640
|
archives/vggt_frames_002.tar
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:591ad815693b373535d3a41dd5c936adc6b31824e62942c14fb102cd7e5aa6a4
|
| 3 |
+
size 582993920
|
archives/vggt_metadata.tar.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4f348ad90455e177818d9b542f15e1feed0100a7082117fd9f5bf0b4ba92dd38
|
| 3 |
+
size 9428
|
archives/vggt_views.tar
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:179fc2cfea7987908b4d71c743d9c9bcba2e7bfc3a195cf24258a7e7ce79caf0
|
| 3 |
+
size 776048640
|
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.
|
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()
|
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()
|
code/lite3_ROS/scripts/live_stretch_cross_nav.py
ADDED
|
@@ -0,0 +1,936 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import argparse
|
| 8 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 9 |
+
import json
|
| 10 |
+
import math
|
| 11 |
+
import os
|
| 12 |
+
import pickle
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import secrets
|
| 15 |
+
import signal
|
| 16 |
+
import sys
|
| 17 |
+
import threading
|
| 18 |
+
import time
|
| 19 |
+
from types import SimpleNamespace
|
| 20 |
+
import uuid
|
| 21 |
+
from urllib.parse import parse_qs, urlsplit
|
| 22 |
+
|
| 23 |
+
import cv2
|
| 24 |
+
import numpy as np
|
| 25 |
+
import zmq
|
| 26 |
+
|
| 27 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 28 |
+
sys.path.insert(0, str(ROOT))
|
| 29 |
+
from web_console.cross_run import RunArtifacts, matrix
|
| 30 |
+
from web_console.stretch_nav_control import (PlanWait, attachment_clear,
|
| 31 |
+
competing_controllers, depth_obstacles, depth_veto,
|
| 32 |
+
execution_gate, remaining_path, wrap)
|
| 33 |
+
from web_console.stretch_nav_geometry import body_to_world, world_to_body
|
| 34 |
+
from web_console.stretch_nav_footprint import command_footprint_report, depth_support
|
| 35 |
+
from web_console.stretch_nav_learned import learned_png, reproject_bev
|
| 36 |
+
from web_console.stretch_nav_report import SavedRoute, clean_json, positions, save_json
|
| 37 |
+
from web_console.stretch_nav_replay import ReplayService, save_bev_frame
|
| 38 |
+
from web_console.stretch_nav_recovery import (CorrectionRecovery, CornerObserver, MeasuredObstacleMemory, camera_in_base,
|
| 39 |
+
clear_goal_cache, rectangle_path_clear, route_subgoal)
|
| 40 |
+
from web_console.stretch_nav_survey import HeadSurvey
|
| 41 |
+
from web_console.stretch_vggt_debug import VggtDebugRecorder, model_provenance, planner_snapshot
|
| 42 |
+
from web_console.stretch_transport import camera_transport_diagnostics
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def warmup_native_navigation():
|
| 46 |
+
"""Compile native grid searches before opening any robot transport."""
|
| 47 |
+
try:
|
| 48 |
+
import numba
|
| 49 |
+
except ImportError as exc:
|
| 50 |
+
raise RuntimeError('Live navigation requires CROSS nav dependencies: install CROSS[nav] in this environment') from exc
|
| 51 |
+
from cross_nav.plan import _dijkstra
|
| 52 |
+
from cross_nav.policy.bev_policy import _astar, astar
|
| 53 |
+
|
| 54 |
+
search = _astar()
|
| 55 |
+
if not hasattr(search, 'signatures') or not hasattr(_dijkstra, 'signatures'):
|
| 56 |
+
raise RuntimeError('Live navigation requires CROSS nav dependencies: install CROSS[nav] in this environment')
|
| 57 |
+
started = time.perf_counter()
|
| 58 |
+
ok = np.ones((8, 8), dtype=bool)
|
| 59 |
+
cost = np.ones((8, 8), dtype=np.float64)
|
| 60 |
+
astar(ok, cost, [4, 4], [4, 6])
|
| 61 |
+
_dijkstra(ok, 4, 4, cost, False, True)
|
| 62 |
+
return {'numba_version': numba.__version__, 'warmup_s': time.perf_counter() - started,
|
| 63 |
+
'astar_signatures': [str(value) for value in search.signatures],
|
| 64 |
+
'dijkstra_signatures': [str(value) for value in _dijkstra.signatures]}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class LiveState:
|
| 68 |
+
def __init__(self, args):
|
| 69 |
+
self.args = args
|
| 70 |
+
self.lock = threading.RLock()
|
| 71 |
+
self.done = threading.Event()
|
| 72 |
+
self.token = secrets.token_urlsafe(24)
|
| 73 |
+
self.session = uuid.uuid4().hex
|
| 74 |
+
self.packet = self.plan = self.robot = None
|
| 75 |
+
self.plan_epoch = 0
|
| 76 |
+
self.observation_requested = False
|
| 77 |
+
self.observation_reason = ''
|
| 78 |
+
self.last_control = {}
|
| 79 |
+
self.robot_received = self.heartbeat = -math.inf
|
| 80 |
+
self.phase, self.reason = 'teleop', 'Loading models; teleop remains in control'
|
| 81 |
+
self.commanded = 0.
|
| 82 |
+
self.motion_commands = 0
|
| 83 |
+
self.relay_ever_requested = False
|
| 84 |
+
self.processed = 0
|
| 85 |
+
self.conflicts = []
|
| 86 |
+
self.images = {}
|
| 87 |
+
self.last_json = {}
|
| 88 |
+
self.replay = ReplayService(args.output)
|
| 89 |
+
self.events = (args.output / 'events.jsonl').open('a', buffering=1)
|
| 90 |
+
|
| 91 |
+
def event(self, kind, **data):
|
| 92 |
+
with self.lock:
|
| 93 |
+
self.events.write(json.dumps(clean_json({'type': kind, 'time_unix': time.time(), **data})) + '\n')
|
| 94 |
+
|
| 95 |
+
def finish(self, reason):
|
| 96 |
+
with self.lock:
|
| 97 |
+
self.phase, self.reason = 'stopped', reason
|
| 98 |
+
self.done.set()
|
| 99 |
+
self.event('stop', reason=reason)
|
| 100 |
+
|
| 101 |
+
def gate(self):
|
| 102 |
+
if self.phase == 'stopped':
|
| 103 |
+
return 'session ended'
|
| 104 |
+
if self.conflicts:
|
| 105 |
+
return 'Close competing base controller: ' + ', '.join(f"{c['client']} (PID {c['pid']})" for c in self.conflicts)
|
| 106 |
+
return execution_gate(self.plan, self.robot, now=time.monotonic(),
|
| 107 |
+
robot_received=self.robot_received, heartbeat=self.heartbeat, state='preparing',
|
| 108 |
+
max_plan_age=self.args.max_plan_age)
|
| 109 |
+
|
| 110 |
+
def snapshot(self):
|
| 111 |
+
with self.lock:
|
| 112 |
+
return clean_json({'phase': self.phase, 'reason': self.reason,
|
| 113 |
+
'ready': self.phase == 'teleop' and not self.gate(), 'gate': self.gate(),
|
| 114 |
+
'goal_keyframe': self.args.goal, 'processed': self.processed,
|
| 115 |
+
'robot': self.robot, 'motion_commands': self.motion_commands,
|
| 116 |
+
'frame': self.last_json, 'control': self.last_control, 'token': self.token,
|
| 117 |
+
'capture_frame': self.packet['frame_idx'] if self.packet is not None else None,
|
| 118 |
+
'v_max': self.args.max_v, 'w_max': self.args.max_w,
|
| 119 |
+
'max_plan_age_s': self.args.max_plan_age, 'competing_controllers': self.conflicts,
|
| 120 |
+
'replay_available': self.phase == 'stopped' and (self.args.output / 'final_status.json').is_file()})
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class Handler(BaseHTTPRequestHandler):
|
| 124 |
+
def log_message(self, *_):
|
| 125 |
+
pass
|
| 126 |
+
|
| 127 |
+
def send(self, code, body, mime='application/json'):
|
| 128 |
+
body = body if isinstance(body, bytes) else json.dumps(clean_json(body), allow_nan=False).encode()
|
| 129 |
+
self.send_response(code)
|
| 130 |
+
self.send_header('Content-Type', mime)
|
| 131 |
+
self.send_header('Content-Length', str(len(body)))
|
| 132 |
+
self.send_header('Cache-Control', 'no-store')
|
| 133 |
+
self.send_header('X-Content-Type-Options', 'nosniff')
|
| 134 |
+
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'")
|
| 135 |
+
self.end_headers()
|
| 136 |
+
try:
|
| 137 |
+
self.wfile.write(body)
|
| 138 |
+
except (BrokenPipeError, ConnectionResetError):
|
| 139 |
+
pass
|
| 140 |
+
|
| 141 |
+
def do_GET(self):
|
| 142 |
+
state = self.server.state
|
| 143 |
+
path = self.path.split('?', 1)[0]
|
| 144 |
+
assets = {'/': ('cross_nav_live.html', 'text/html; charset=utf-8'),
|
| 145 |
+
'/cross_nav_live.js': ('cross_nav_live.js', 'text/javascript'),
|
| 146 |
+
'/cross_nav.css': ('cross_nav.css', 'text/css'),
|
| 147 |
+
'/vendor/plotly.min.js': ('vendor/plotly.min.js', 'text/javascript')}
|
| 148 |
+
try:
|
| 149 |
+
if path in assets:
|
| 150 |
+
file, mime = assets[path]
|
| 151 |
+
return self.send(200, (ROOT / 'web_console/static' / file).read_bytes(), mime)
|
| 152 |
+
if path == '/api/status':
|
| 153 |
+
return self.send(200, state.snapshot())
|
| 154 |
+
if path == '/api/map':
|
| 155 |
+
return self.send(200, state.map_data)
|
| 156 |
+
if path.startswith('/api/replay/'):
|
| 157 |
+
if state.phase != 'stopped':
|
| 158 |
+
return self.send(409, {'error': 'Replay becomes available after the run ends'})
|
| 159 |
+
query = parse_qs(urlsplit(self.path).query)
|
| 160 |
+
key = query.get('run', [None])[0]
|
| 161 |
+
if path == '/api/replay/runs':
|
| 162 |
+
return self.send(200, {'runs': state.replay.listing(), 'current_run': state.replay.current.name})
|
| 163 |
+
archive = state.replay.get(key)
|
| 164 |
+
if path == '/api/replay/manifest':
|
| 165 |
+
return self.send(200, archive.manifest())
|
| 166 |
+
if path == '/api/replay/map':
|
| 167 |
+
return self.send(200, json.loads((archive.root / 'map.json').read_text()))
|
| 168 |
+
if path == '/api/replay/frame':
|
| 169 |
+
result = archive.frame(int(query.get('index', ['0'])[0]))
|
| 170 |
+
result['token'] = state.token
|
| 171 |
+
return self.send(200, result)
|
| 172 |
+
if path in ('/api/replay/rgb', '/api/replay/bev'):
|
| 173 |
+
number = int(query['frame'][0])
|
| 174 |
+
layer = query.get('layer', [None])[0] if path.endswith('/bev') else None
|
| 175 |
+
if path.endswith('/bev') and layer is None:
|
| 176 |
+
raise ValueError('BEV layer required')
|
| 177 |
+
return self.send(200, archive.image(number, layer), 'image/png' if layer else 'image/jpeg')
|
| 178 |
+
return self.send(404, {'error': 'Unknown replay action'})
|
| 179 |
+
with state.lock:
|
| 180 |
+
if path == '/api/rgb.jpg' and state.packet is not None:
|
| 181 |
+
data = np.asarray(state.packet['rgb_jpg'], np.uint8).tobytes()
|
| 182 |
+
return self.send(200, data, 'image/jpeg')
|
| 183 |
+
if path.startswith('/api/bev/') and path.split('/')[-1] in state.images:
|
| 184 |
+
return self.send(200, state.images[path.split('/')[-1]], 'image/png')
|
| 185 |
+
return self.send(404, {'error': 'Data not available yet'})
|
| 186 |
+
except (OSError, ValueError, KeyError, IndexError) as exc:
|
| 187 |
+
self.send(404, {'error': str(exc)})
|
| 188 |
+
|
| 189 |
+
def do_POST(self):
|
| 190 |
+
state = self.server.state
|
| 191 |
+
expected = f'http://127.0.0.1:{self.server.server_port}'
|
| 192 |
+
if self.headers.get('X-Session') != state.token or self.headers.get('Origin') not in (None, expected):
|
| 193 |
+
return self.send(403, {'error': 'Invalid viewer session or origin'})
|
| 194 |
+
with state.lock:
|
| 195 |
+
if self.path == '/api/heartbeat':
|
| 196 |
+
state.heartbeat = time.monotonic()
|
| 197 |
+
return self.send(200, {'ok': True})
|
| 198 |
+
if self.path == '/api/start':
|
| 199 |
+
if state.phase != 'teleop':
|
| 200 |
+
return self.send(409, {'error': 'A run can be started once; Stop ends the session'})
|
| 201 |
+
reason = state.gate()
|
| 202 |
+
if reason:
|
| 203 |
+
return self.send(409, {'error': reason})
|
| 204 |
+
state.phase, state.reason = 'preparing', 'Browser requested navigation handoff'
|
| 205 |
+
state.event('start_requested', goal=state.args.goal)
|
| 206 |
+
return self.send(202, {'phase': state.phase})
|
| 207 |
+
if self.path == '/api/stop':
|
| 208 |
+
state.finish('Stopped by operator; temporary relay will close')
|
| 209 |
+
return self.send(200, {'phase': 'stopped'})
|
| 210 |
+
return self.send(404, {'error': 'Unknown action'})
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def capture_loop(state, relay):
|
| 214 |
+
context = zmq.Context()
|
| 215 |
+
sub = context.socket(zmq.SUB)
|
| 216 |
+
sub.setsockopt(zmq.SUBSCRIBE, b'')
|
| 217 |
+
sub.setsockopt(zmq.CONFLATE, 1)
|
| 218 |
+
sub.setsockopt(zmq.LINGER, 0)
|
| 219 |
+
sub.connect(f'tcp://{state.args.robot_ip}:4511')
|
| 220 |
+
root = state.args.output / 'capture'
|
| 221 |
+
for name in ('rgb', 'depth'):
|
| 222 |
+
(root / name).mkdir(parents=True, exist_ok=True)
|
| 223 |
+
first, last, count, previous_received = None, -1, 0, None
|
| 224 |
+
try:
|
| 225 |
+
with (root / 'observations.jsonl').open('a', buffering=1) as log, \
|
| 226 |
+
(root / 'transport.jsonl').open('a', buffering=1) as timing_log:
|
| 227 |
+
while not state.done.is_set():
|
| 228 |
+
if relay.process.poll() is not None:
|
| 229 |
+
raise RuntimeError('Owned robot relay exited')
|
| 230 |
+
if not sub.poll(200):
|
| 231 |
+
continue
|
| 232 |
+
recv_started = time.monotonic()
|
| 233 |
+
payload = sub.recv()
|
| 234 |
+
recv_finished = time.monotonic()
|
| 235 |
+
packet = pickle.loads(payload)
|
| 236 |
+
received = time.monotonic()
|
| 237 |
+
with state.lock:
|
| 238 |
+
timing = camera_transport_diagnostics(packet, state.robot, state.robot_received, received)
|
| 239 |
+
timing.update(wire_bytes=len(payload), recv_call_s=recv_finished - recv_started,
|
| 240 |
+
deserialize_s=received - recv_finished,
|
| 241 |
+
receive_gap_s=received - previous_received if previous_received is not None else None)
|
| 242 |
+
previous_received = received
|
| 243 |
+
if packet['world_frame'] != 'odom':
|
| 244 |
+
raise ValueError('Continuous odom frame required')
|
| 245 |
+
if packet['frame_id'] <= last:
|
| 246 |
+
continue
|
| 247 |
+
last = packet['frame_id']
|
| 248 |
+
first = packet['sensor_stamp'] if first is None else first
|
| 249 |
+
row = {k: v for k, v in packet.items() if k not in ('rgb_jpg', 'depth_png')}
|
| 250 |
+
row['camera_in_base'] = camera_in_base(packet['camera_pose'], packet['base_pose_matrix'])
|
| 251 |
+
for stamp_name in ('camera_tf_stamp', 'base_tf_stamp'):
|
| 252 |
+
if stamp_name in packet and abs(packet[stamp_name] - packet['sensor_stamp']) > .025:
|
| 253 |
+
raise ValueError('Camera/base TF is not synchronized to its image')
|
| 254 |
+
row.update(frame_idx=count, relative_time_s=packet['sensor_stamp'] - first,
|
| 255 |
+
received_monotonic=received, received_unix_s=time.time(), transport=timing)
|
| 256 |
+
write_started = time.monotonic()
|
| 257 |
+
stem = f'{count:08d}'
|
| 258 |
+
(root / 'rgb' / f'{stem}.jpg').write_bytes(np.asarray(packet['rgb_jpg'], np.uint8).tobytes())
|
| 259 |
+
(root / 'depth' / f'{stem}.png').write_bytes(np.asarray(packet['depth_png'], np.uint8).tobytes())
|
| 260 |
+
log.write(json.dumps(clean_json(row), allow_nan=False) + '\n')
|
| 261 |
+
save_json(root / 'latest.json', row)
|
| 262 |
+
with state.lock:
|
| 263 |
+
state.packet = {**packet, **row}
|
| 264 |
+
phase, commands = state.phase, state.motion_commands
|
| 265 |
+
count += 1
|
| 266 |
+
save_json(root / 'capture.json', {'status': 'recording', 'frames': count,
|
| 267 |
+
'phase': phase, 'nonzero_motion_commands': commands, 'world_frame': 'odom'})
|
| 268 |
+
timing_log.write(json.dumps(clean_json({'frame_idx': count - 1,
|
| 269 |
+
'frame_id': packet['frame_id'], 'received_unix_s': row['received_unix_s'],
|
| 270 |
+
**timing, 'record_and_publish_s': time.monotonic() - write_started,
|
| 271 |
+
'capture_metrics': packet.get('capture_metrics')}), allow_nan=False) + '\n')
|
| 272 |
+
except BaseException as exc:
|
| 273 |
+
state.finish('Capture error: ' + str(exc))
|
| 274 |
+
state.event('capture_error', error=str(exc))
|
| 275 |
+
finally:
|
| 276 |
+
save_json(root / 'capture.json', {'status': 'completed', 'frames': count,
|
| 277 |
+
'nonzero_motion_commands': state.motion_commands, 'world_frame': 'odom'})
|
| 278 |
+
sub.close()
|
| 279 |
+
context.term()
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def control_loop(state):
|
| 283 |
+
"""Independent 20 Hz owner of the robot-local lease. Never waits for inference."""
|
| 284 |
+
from cross_nav.policy.robot import pure_pursuit
|
| 285 |
+
|
| 286 |
+
context = zmq.Context()
|
| 287 |
+
status = context.socket(zmq.SUB)
|
| 288 |
+
status.setsockopt(zmq.SUBSCRIBE, b'')
|
| 289 |
+
status.setsockopt(zmq.CONFLATE, 1)
|
| 290 |
+
status.setsockopt(zmq.LINGER, 0)
|
| 291 |
+
status.connect(f'tcp://{state.args.robot_ip}:4513')
|
| 292 |
+
commands = context.socket(zmq.PUSH)
|
| 293 |
+
commands.setsockopt(zmq.SNDHWM, 1)
|
| 294 |
+
commands.setsockopt(zmq.IMMEDIATE, 1)
|
| 295 |
+
commands.setsockopt(zmq.LINGER, 0)
|
| 296 |
+
commands.connect(f'tcp://{state.args.robot_ip}:4512')
|
| 297 |
+
mode = context.socket(zmq.PUB)
|
| 298 |
+
mode.setsockopt(zmq.LINGER, 0)
|
| 299 |
+
mode.connect(f'tcp://{state.args.robot_ip}:4402')
|
| 300 |
+
sequence, previous, last_tick, next_mode, prepare_started = 0, None, time.monotonic(), 0., None
|
| 301 |
+
plan_wait = PlanWait(timeout=state.args.plan_hold_seconds)
|
| 302 |
+
next_scan = 0.
|
| 303 |
+
scan_started, scan_angle, scan_previous = None, 0., None
|
| 304 |
+
scan_origin = None
|
| 305 |
+
control_epoch = 0
|
| 306 |
+
veto_since, progress_origin, progress_at = None, None, None
|
| 307 |
+
|
| 308 |
+
def send(command):
|
| 309 |
+
try:
|
| 310 |
+
commands.send_json(command, flags=zmq.NOBLOCK)
|
| 311 |
+
except zmq.Again:
|
| 312 |
+
return False
|
| 313 |
+
return True
|
| 314 |
+
|
| 315 |
+
try:
|
| 316 |
+
with (state.args.output / 'commands.jsonl').open('a', buffering=1) as log, \
|
| 317 |
+
(state.args.output / 'robot_status.jsonl').open('a', buffering=1) as robot_log:
|
| 318 |
+
while not state.done.is_set():
|
| 319 |
+
now = time.monotonic()
|
| 320 |
+
if now >= next_scan:
|
| 321 |
+
with state.lock:
|
| 322 |
+
state.conflicts = competing_controllers()
|
| 323 |
+
next_scan = now + 1.
|
| 324 |
+
if status.poll(0):
|
| 325 |
+
robot = status.recv_pyobj()
|
| 326 |
+
robot_log.write(json.dumps(clean_json({'received_unix': time.time(),
|
| 327 |
+
'received_monotonic': time.monotonic(), **robot})) + '\n')
|
| 328 |
+
with state.lock:
|
| 329 |
+
state.robot, state.robot_received = robot, time.monotonic()
|
| 330 |
+
with state.lock:
|
| 331 |
+
robot, robot_at, plan, phase, heartbeat = (state.robot, state.robot_received,
|
| 332 |
+
state.plan, state.phase, state.heartbeat)
|
| 333 |
+
epoch = state.plan_epoch
|
| 334 |
+
if epoch != control_epoch:
|
| 335 |
+
scan_started, scan_angle, scan_origin, scan_previous = None, 0., None, None
|
| 336 |
+
veto_since, progress_origin, progress_at = None, None, None
|
| 337 |
+
control_epoch = epoch
|
| 338 |
+
# Process scanning, deserialization or waiting for the GIL can
|
| 339 |
+
# take time. Gate this snapshot using the current clock.
|
| 340 |
+
now = time.monotonic()
|
| 341 |
+
v, w = 0., 0.
|
| 342 |
+
head_target = None
|
| 343 |
+
footprint_report = None
|
| 344 |
+
requested_velocity = [0., 0.]
|
| 345 |
+
depth_blocked = learned_blocked = False
|
| 346 |
+
queued = None
|
| 347 |
+
reason = 'Teleop owns control; no arm/mode/velocity requests'
|
| 348 |
+
if phase in ('preparing', 'active'):
|
| 349 |
+
if state.conflicts:
|
| 350 |
+
state.finish('Competing base controller detected; navigation ended')
|
| 351 |
+
break
|
| 352 |
+
gate = execution_gate(plan, robot, now=now, robot_received=robot_at,
|
| 353 |
+
heartbeat=heartbeat, state=phase, max_plan_age=state.args.max_plan_age)
|
| 354 |
+
if gate == 'goal reached':
|
| 355 |
+
state.finish('Goal keyframe reached (camera XY within 0.4 m; heading not enforced)')
|
| 356 |
+
break
|
| 357 |
+
recovering = gate == 'map correction recovery' and now < plan.get('recovery_deadline', 0.)
|
| 358 |
+
holding = phase == 'active' and robot is not None and (recovering or plan_wait.holds(gate, now))
|
| 359 |
+
if gate and not holding:
|
| 360 |
+
state.finish(gate + '; navigation ended')
|
| 361 |
+
break
|
| 362 |
+
if robot.get('armed') and robot.get('session') != state.session:
|
| 363 |
+
raise RuntimeError('Relay is owned by another session')
|
| 364 |
+
if phase == 'active' and not robot.get('armed'):
|
| 365 |
+
raise RuntimeError('Navigation lease lost; no automatic re-arm')
|
| 366 |
+
if holding:
|
| 367 |
+
# Renew only zero velocity using fresh camera evidence. An old
|
| 368 |
+
# path never receives extra execution time during this hold.
|
| 369 |
+
sequence += 1
|
| 370 |
+
queued = send({'type': 'velocity', 'session': state.session, 'seq': sequence,
|
| 371 |
+
'frame_id': robot['frame_id'], 'ttl': .3, 'v': 0., 'w': 0.})
|
| 372 |
+
reason = 'Holding at zero: ' + gate
|
| 373 |
+
previous = np.asarray(robot['base_pose'], float).copy()
|
| 374 |
+
elif phase == 'preparing':
|
| 375 |
+
prepare_started = prepare_started or now
|
| 376 |
+
if now - prepare_started > 15.:
|
| 377 |
+
raise RuntimeError('Navigation mode/lease preparation timed out')
|
| 378 |
+
if robot.get('control_mode') != 'navigation':
|
| 379 |
+
if now >= next_mode:
|
| 380 |
+
mode.send_pyobj({'control_mode': 'navigation', 'step': int(robot['bridge_step']) + 1})
|
| 381 |
+
next_mode = now + 1.
|
| 382 |
+
reason = 'Switching base to navigation mode; joints unchanged'
|
| 383 |
+
elif not robot.get('healthy'):
|
| 384 |
+
reason = 'Waiting for healthy robot TF and camera'
|
| 385 |
+
elif not robot.get('armed'):
|
| 386 |
+
state.relay_ever_requested = True
|
| 387 |
+
send({'type': 'arm', 'session': state.session})
|
| 388 |
+
reason = 'Arming expiring robot-local velocity lease'
|
| 389 |
+
else:
|
| 390 |
+
with state.lock:
|
| 391 |
+
state.phase = 'active'
|
| 392 |
+
reason = 'Navigation active'
|
| 393 |
+
else:
|
| 394 |
+
pose = np.asarray(robot['base_pose'], float)
|
| 395 |
+
if previous is not None:
|
| 396 |
+
dt = now - last_tick
|
| 397 |
+
if np.linalg.norm(pose[:2] - previous[:2]) > .2 + .2 * dt or abs(wrap(pose[2] - previous[2])) > .3 + .4 * dt:
|
| 398 |
+
raise RuntimeError('Odom discontinuity')
|
| 399 |
+
if not robot.get('armed'):
|
| 400 |
+
raise RuntimeError('Navigation lease lost; no automatic re-arm')
|
| 401 |
+
path = remaining_path(plan['path_odom'], pose)
|
| 402 |
+
head_target = plan.get('head_target')
|
| 403 |
+
if plan.get('observation_hold'):
|
| 404 |
+
v, w = 0., float(np.clip(plan.get('scan_w', 0.),
|
| 405 |
+
-min(.15, state.args.max_w), min(.15, state.args.max_w)))
|
| 406 |
+
reason = ('Head survey: ' + (plan.get('survey_label') or 'observing')
|
| 407 |
+
if plan.get('stationary_survey') else 'Corner observation: ' + plan.get('corner_phase', 'look'))
|
| 408 |
+
elif plan.get('planner_status') == 2:
|
| 409 |
+
_, w = pure_pursuit(path, v_max=state.args.max_v, w_max=min(.15, state.args.max_w))
|
| 410 |
+
v, reason = 0., 'Guarded native no-route scan'
|
| 411 |
+
else:
|
| 412 |
+
v, w = pure_pursuit(path, v_max=state.args.max_v * plan.get('speed_scale', 1.),
|
| 413 |
+
w_max=state.args.max_w, lookahead=plan.get('lookahead', .4))
|
| 414 |
+
reason = 'Following CROSS local plan'
|
| 415 |
+
v *= min(1., max(0., plan['goal_distance'] - .4) / .6)
|
| 416 |
+
if progress_origin is None or np.linalg.norm(pose[:2] - progress_origin) > .05:
|
| 417 |
+
progress_origin, progress_at = pose[:2].copy(), now
|
| 418 |
+
if plan.get('observation_hold'):
|
| 419 |
+
progress_at = now
|
| 420 |
+
# Scan budgets follow physical odometry and do not reset
|
| 421 |
+
# merely because the planner briefly changes status.
|
| 422 |
+
scanning = plan.get('observation_hold') or plan.get('planner_status') == 2
|
| 423 |
+
if scan_origin is not None and np.linalg.norm(pose[:2] - scan_origin) > .2:
|
| 424 |
+
scan_started, scan_angle, scan_origin = None, 0., None
|
| 425 |
+
if scanning:
|
| 426 |
+
if scan_started is None:
|
| 427 |
+
scan_started, scan_origin = now, pose[:2].copy()
|
| 428 |
+
if scan_previous is not None:
|
| 429 |
+
scan_angle += abs(wrap(pose[2] - scan_previous))
|
| 430 |
+
if now - scan_started > 90. or scan_angle > np.deg2rad(100):
|
| 431 |
+
raise RuntimeError('Observation recovery exhausted without forward progress')
|
| 432 |
+
scan_previous = pose[2]
|
| 433 |
+
requested_velocity = [float(v), float(w)]
|
| 434 |
+
depth_blocked = depth_veto(plan['depth_obstacles'], pose, v, w)
|
| 435 |
+
if plan.get('footprint_grid') is not None:
|
| 436 |
+
footprint_report = command_footprint_report(
|
| 437 |
+
plan['footprint_grid'], plan['planning_base'], pose, v, w)
|
| 438 |
+
learned_blocked = not footprint_report['clear']
|
| 439 |
+
if (depth_blocked or learned_blocked) and abs(v) + abs(w) > 1e-8:
|
| 440 |
+
v, w = 0., 0.
|
| 441 |
+
reason = ('Measured-depth veto' if depth_blocked else 'Learned-footprint veto') + ': obstacle in command footprint'
|
| 442 |
+
veto_since = now if veto_since is None else veto_since
|
| 443 |
+
else:
|
| 444 |
+
veto_since = None
|
| 445 |
+
if not plan.get('observation_hold') and (
|
| 446 |
+
(veto_since is not None and now - veto_since > 1.) or now - progress_at > 10.
|
| 447 |
+
):
|
| 448 |
+
with state.lock:
|
| 449 |
+
state.observation_requested = True
|
| 450 |
+
state.observation_reason = ('measured depth' if depth_blocked else
|
| 451 |
+
'learned footprint' if learned_blocked else 'no odometry progress')
|
| 452 |
+
sequence += 1
|
| 453 |
+
with state.lock:
|
| 454 |
+
# A correction can arrive after this thread took its
|
| 455 |
+
# snapshot. Never send its now-invalid path command.
|
| 456 |
+
if epoch != state.plan_epoch or state.done.is_set():
|
| 457 |
+
v, w, head_target = 0., 0., None
|
| 458 |
+
reason = 'Holding at zero: route generation changed'
|
| 459 |
+
command = {'type': 'velocity', 'session': state.session, 'seq': sequence,
|
| 460 |
+
'frame_id': plan['frame_id'], 'ttl': .3, 'v': float(v), 'w': float(w)}
|
| 461 |
+
if head_target is not None:
|
| 462 |
+
command['head_target'] = head_target
|
| 463 |
+
queued = send(command)
|
| 464 |
+
if queued:
|
| 465 |
+
with state.lock:
|
| 466 |
+
state.motion_commands += int(abs(v) + abs(w) > 1e-8)
|
| 467 |
+
# Relay-published velocity, rather than a queued
|
| 468 |
+
# PC request, drives the native bump expectation.
|
| 469 |
+
state.commanded += max(0., robot.get('v', 0.)) * min(.1, now - last_tick)
|
| 470 |
+
previous = pose.copy()
|
| 471 |
+
last_tick = now
|
| 472 |
+
with state.lock:
|
| 473 |
+
if not state.done.is_set():
|
| 474 |
+
state.reason = reason
|
| 475 |
+
control = {'phase': phase, 'reason': reason, 'v': float(v), 'w': float(w),
|
| 476 |
+
'time_unix': time.time(), 'sequence': sequence,
|
| 477 |
+
'plan_frame_id': plan.get('frame_id') if plan else None,
|
| 478 |
+
'plan_capture_frame': plan.get('capture_frame') if plan else None, 'command_queued': queued,
|
| 479 |
+
'plan_input_age_s': now - plan['input_received'] if plan else None,
|
| 480 |
+
'plan_build_age_s': now - plan.get('published', now) if plan else None,
|
| 481 |
+
'robot_state_age_s': now - robot_at, 'max_plan_age_s': state.args.max_plan_age,
|
| 482 |
+
'holding_for_plan': phase == 'active' and reason.startswith('Holding'),
|
| 483 |
+
'plan_epoch': epoch, 'relay_sequence': robot.get('accepted_sequence') if robot else None,
|
| 484 |
+
'head_target': head_target,
|
| 485 |
+
'requested_velocity': requested_velocity, 'requested_pose': robot.get('base_pose') if robot else None,
|
| 486 |
+
'depth_blocked': depth_blocked, 'learned_blocked': learned_blocked,
|
| 487 |
+
'footprint': footprint_report,
|
| 488 |
+
'relay_reason': robot.get('reason') if robot else None,
|
| 489 |
+
'relay_velocity': [robot.get('v'), robot.get('w')] if robot else None,
|
| 490 |
+
'nonzero_motion_commands': state.motion_commands}
|
| 491 |
+
log.write(json.dumps(clean_json(control), allow_nan=False) + '\n')
|
| 492 |
+
with state.lock:
|
| 493 |
+
state.last_control = clean_json(control)
|
| 494 |
+
save_json(state.args.output / 'control.json', control)
|
| 495 |
+
state.done.wait(.05)
|
| 496 |
+
except BaseException as exc:
|
| 497 |
+
state.finish('Control error: ' + str(exc))
|
| 498 |
+
state.event('control_error', error=str(exc))
|
| 499 |
+
finally:
|
| 500 |
+
if state.relay_ever_requested:
|
| 501 |
+
for _ in range(3):
|
| 502 |
+
send({'type': 'stop', 'session': state.session})
|
| 503 |
+
time.sleep(.03)
|
| 504 |
+
final_control = {'phase': state.phase, 'reason': state.reason, 'v': 0., 'w': 0.,
|
| 505 |
+
'time_unix': time.time(), 'sequence': sequence, 'stop_requested': state.relay_ever_requested,
|
| 506 |
+
'nonzero_motion_commands': state.motion_commands}
|
| 507 |
+
save_json(state.args.output / 'control.json', final_control)
|
| 508 |
+
with (state.args.output / 'commands.jsonl').open('a') as log:
|
| 509 |
+
log.write(json.dumps(final_control) + '\n')
|
| 510 |
+
for socket in (status, commands, mode):
|
| 511 |
+
socket.close()
|
| 512 |
+
context.term()
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def run_mapping(state):
|
| 516 |
+
from cross.core.config import load_config
|
| 517 |
+
from cross.core.types import Camera
|
| 518 |
+
from cross.pipeline import add_session_args, finish_session_args, mode_config_files, session_factory
|
| 519 |
+
from cross_nav.policy.bev_policy import BEVPlannerPolicy, Episode
|
| 520 |
+
|
| 521 |
+
args = state.args
|
| 522 |
+
while state.packet is None and not state.done.wait(.1):
|
| 523 |
+
pass
|
| 524 |
+
if state.done.is_set():
|
| 525 |
+
return
|
| 526 |
+
with state.lock:
|
| 527 |
+
initial = state.packet
|
| 528 |
+
rgb = cv2.imdecode(np.asarray(initial['rgb_jpg'], np.uint8), cv2.IMREAD_COLOR)
|
| 529 |
+
camera_config = Camera(K=np.asarray(initial['camera_K']), frame_width=rgb.shape[1], frame_height=rgb.shape[0])
|
| 530 |
+
parser = argparse.ArgumentParser()
|
| 531 |
+
add_session_args(parser)
|
| 532 |
+
options = parser.parse_args(['--mode', 'mono', '--odometry', 'external', '--mono-estimator', 'ff'])
|
| 533 |
+
finish_session_args(options)
|
| 534 |
+
heads = args.cross_root / 'models/VGGT-Omega-CROSS/nav'
|
| 535 |
+
occupancy, visibility = heads / 'cross_nav_occupancy.pt', heads / 'cross_nav_observability.pt'
|
| 536 |
+
overrides = ['pose_est.ff.checkpoint=finetuned', 'pose_est.obs_max_interval_steps=1',
|
| 537 |
+
f'pose_est.ff.nav_bev_head={occupancy}', f'pose_est.ff.nav_bev_visibility={visibility}',
|
| 538 |
+
f'pose_est.ff.nav_bev_visibility_gravity={occupancy}', 'mapping.loop_closure.async_pgo=False']
|
| 539 |
+
config = load_config(*mode_config_files('mono', 'external', 'ff'), sets=overrides)
|
| 540 |
+
artifacts = RunArtifacts(args.output / 'mapping', {'mode': 'mono', 'odometry': 'external',
|
| 541 |
+
'dataset': str(args.output / 'capture'), 'loaded_map': str(args.map_run / 'map.pkl'),
|
| 542 |
+
'goal_keyframe': args.goal, 'config_overrides': overrides, 'max_v': args.max_v, 'max_w': args.max_w,
|
| 543 |
+
'max_plan_age_s': args.max_plan_age, 'plan_hold_seconds': args.plan_hold_seconds,
|
| 544 |
+
'checkpoint_provenance': json.loads((heads / 'provenance.json').read_text())})
|
| 545 |
+
session = debug_archive = None
|
| 546 |
+
mapping_error = None
|
| 547 |
+
try:
|
| 548 |
+
session = artifacts.wrap_factory(session_factory(options, camera_config, config))()
|
| 549 |
+
session.load_map(args.map_run / 'map.pkl')
|
| 550 |
+
pe = session.mapper.pose_est
|
| 551 |
+
if args.vggt_debug:
|
| 552 |
+
debug_archive = VggtDebugRecorder(args.vggt_debug_dir or args.output / 'vggt_debug', {
|
| 553 |
+
'origin': 'live_recorded', 'cross_root': str(args.cross_root),
|
| 554 |
+
'map_run': str(args.map_run), 'config_overrides': overrides,
|
| 555 |
+
'resolved_config': json.loads((args.output / 'mapping/resolved_config.json').read_text()),
|
| 556 |
+
'camera_catalog': clean_json(session.mapper.cameras), 'session_camera_id': session.mapper.cam_id,
|
| 557 |
+
'checkpoint_provenance': artifacts.metadata['checkpoint_provenance'],
|
| 558 |
+
**model_provenance(args.cross_root),
|
| 559 |
+
}, on_error=lambda exc: state.finish('VGGT debug archive error: ' + str(exc)))
|
| 560 |
+
debug_archive.attach(pe)
|
| 561 |
+
route_planner = SavedRoute(args.map_run / 'map.pkl')
|
| 562 |
+
bev_config = json.loads((args.cross_root / 'cross_nav/configs/policy/bev_planner_vfin2.json').read_text())
|
| 563 |
+
bev_config.update(backbone=str(args.cross_root / 'models/VGGT-Omega-CROSS/vggt_omega_cross_1b_512.pt'),
|
| 564 |
+
occupancy=str(occupancy), visibility=str(visibility), visibility_gravity=str(occupancy))
|
| 565 |
+
# Match the 46 cm execution footprint. Never shrink inflation to invent
|
| 566 |
+
# clearance in a narrow passage; also check the oriented rectangle.
|
| 567 |
+
bev_config['planner']['radius'] = .23
|
| 568 |
+
bev_config['map'].update(radius=.23, retry_radii=[])
|
| 569 |
+
save_json(args.output / 'resolved_bev_config.json', bev_config)
|
| 570 |
+
if debug_archive:
|
| 571 |
+
save_json(debug_archive.root / 'planner_config.json', bev_config)
|
| 572 |
+
policy = BEVPlannerPolicy(bev_config, predictor=pe.backend.nav)
|
| 573 |
+
episode = Episode()
|
| 574 |
+
recovery, corners = CorrectionRecovery(), CornerObserver()
|
| 575 |
+
survey = HeadSurvey()
|
| 576 |
+
obstacle_memory = MeasuredObstacleMemory()
|
| 577 |
+
evidence_directory = args.output / 'footprint_evidence'
|
| 578 |
+
evidence_directory.mkdir()
|
| 579 |
+
last_evidence = -math.inf
|
| 580 |
+
neutral_mount, previous_goal = None, None
|
| 581 |
+
prior, last, streak, previous_alignment = None, -1, 0, None
|
| 582 |
+
trajectory, previous_expected = [], 0.
|
| 583 |
+
with (args.output / 'observations.jsonl').open('a', buffering=1) as log:
|
| 584 |
+
while not state.done.is_set():
|
| 585 |
+
with state.lock:
|
| 586 |
+
raw = state.packet
|
| 587 |
+
phase, cumulative = state.phase, state.commanded
|
| 588 |
+
if raw is None or raw['frame_idx'] <= last:
|
| 589 |
+
state.done.wait(.03)
|
| 590 |
+
continue
|
| 591 |
+
index, camera, base = raw['frame_idx'], np.asarray(raw['camera_pose']), np.asarray(raw['base_pose_matrix'])
|
| 592 |
+
mount = camera_in_base(camera, base)
|
| 593 |
+
if neutral_mount is None:
|
| 594 |
+
neutral_mount = mount.copy()
|
| 595 |
+
rgb = cv2.cvtColor(cv2.imdecode(np.asarray(raw['rgb_jpg'], np.uint8), cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB)
|
| 596 |
+
pe.set_gravity(camera[:3, :3].T @ [0., 0., 1.])
|
| 597 |
+
passes = pe._n_passes
|
| 598 |
+
started = time.monotonic()
|
| 599 |
+
if debug_archive:
|
| 600 |
+
debug_archive.begin_frame(raw)
|
| 601 |
+
session.process({'rgb': rgb, 'frame_idx': index, 'timestamp': raw['sensor_stamp'],
|
| 602 |
+
'delta_pose': None if prior is None else np.linalg.inv(prior) @ camera})
|
| 603 |
+
prior, last = camera, index
|
| 604 |
+
c0, best, weights = session.belief(matrix)
|
| 605 |
+
localized = bool(session.localized())
|
| 606 |
+
streak = streak + 1 if localized else 0
|
| 607 |
+
diagnostics = session.mapper.last_step_diagnostics
|
| 608 |
+
audit = [{'id': int(a['keyframe_id']), 'score': float(a['retrieval_score']),
|
| 609 |
+
'verified': bool(a['verified']), 'loaded': bool(a['loaded'])}
|
| 610 |
+
for a in diagnostics.get('retrieval_audit', [])]
|
| 611 |
+
fresh = pe._n_passes != passes and pe.last_bev is not None
|
| 612 |
+
bev = pe.last_bev if fresh else None
|
| 613 |
+
grid = planner_debug = None
|
| 614 |
+
record = {'frame_idx': index, 'time_s': raw['relative_time_s'], 'localized': localized,
|
| 615 |
+
'localized_streak': streak, 'weights': weights, 'retrieval': audit,
|
| 616 |
+
'camera_display': None, 'global_route': [], 'local_path_display': [],
|
| 617 |
+
'goal_keyframe': args.goal, 'route_ids': [], 'goal_distance': None,
|
| 618 |
+
'planner_name': 'Waiting for committed map pose', 'n_views': 0, 'trajectory': trajectory[-1500:]}
|
| 619 |
+
plan = None if localized else {'input_received': raw['received_monotonic'],
|
| 620 |
+
'localized': False, 'localized_streak': 0, 'goal_distance': 0.}
|
| 621 |
+
if bev is not None:
|
| 622 |
+
grid = reproject_bev(bev['prob'], bev['observability'], bev['uncertainty'],
|
| 623 |
+
bev['R_bev_from_cam'], camera, base, bev['res'])
|
| 624 |
+
images = {f'{layer}.png': learned_png(grid['prob'], grid['obs'], grid['err'], layer)
|
| 625 |
+
for layer in ('occupancy', 'visibility', 'uncertainty')}
|
| 626 |
+
save_bev_frame(args.output, int(index), images)
|
| 627 |
+
with state.lock:
|
| 628 |
+
state.images = images
|
| 629 |
+
record.update(n_views=bev['n_views'], scale_source=bev['scale_source'],
|
| 630 |
+
bev_size=bev['size'], bev_res=bev['res'], gravity_head_deg=bev['gravity_head_deg'])
|
| 631 |
+
if localized and bev is not None:
|
| 632 |
+
alignment = c0 @ np.linalg.inv(camera)
|
| 633 |
+
with state.lock:
|
| 634 |
+
active = state.phase == 'active'
|
| 635 |
+
was_pending = recovery.pending
|
| 636 |
+
correction = recovery.update(previous_alignment if active else None, alignment, base, time.monotonic())
|
| 637 |
+
if correction['started']:
|
| 638 |
+
survey.cancel()
|
| 639 |
+
route_planner.reset_attachment()
|
| 640 |
+
clear_goal_cache(episode)
|
| 641 |
+
corners.reset()
|
| 642 |
+
previous_goal = None
|
| 643 |
+
with state.lock:
|
| 644 |
+
state.plan_epoch += 1
|
| 645 |
+
state.plan = {'input_received': raw['received_monotonic'], 'localized': True,
|
| 646 |
+
'localized_streak': streak, 'goal_distance': 0., 'recovery_pending': True,
|
| 647 |
+
'recovery_deadline': correction['deadline']}
|
| 648 |
+
state.event('map_correction_recovery_started', frame_idx=index,
|
| 649 |
+
previous_alignment=previous_alignment, alignment=alignment,
|
| 650 |
+
base_pose_matrix=base, weights=weights, **correction)
|
| 651 |
+
if was_pending and not recovery.pending:
|
| 652 |
+
corners.restore_neutral(base, time.monotonic())
|
| 653 |
+
state.event('map_correction_recovery_complete', frame_idx=index, **correction)
|
| 654 |
+
record.update(map_correction_at_base_m=correction['distance_m'],
|
| 655 |
+
map_correction_angle_deg=correction['rotation_deg'], correction_recovery=correction,
|
| 656 |
+
camera_in_base=mount, neutral_camera_in_base=neutral_mount)
|
| 657 |
+
previous_alignment = alignment
|
| 658 |
+
inverse_alignment = np.linalg.inv(alignment)
|
| 659 |
+
depth = cv2.imdecode(np.asarray(raw['depth_png'], np.uint8), cv2.IMREAD_UNCHANGED).astype(float) / 1000
|
| 660 |
+
obstacles = depth_obstacles(depth, raw['camera_K'], camera)
|
| 661 |
+
obstacle_memory.observing(survey.active, raw['received_monotonic'])
|
| 662 |
+
obstacles = obstacle_memory.update(obstacles, raw['received_monotonic'], base[:2, 3])
|
| 663 |
+
reference_camera = base @ neutral_mount
|
| 664 |
+
def can_attach(_keyframe_id, point_map):
|
| 665 |
+
point_odom = positions(inverse_alignment, [point_map])[0]
|
| 666 |
+
target_base_xy = base[:2, 3] + point_odom[:2] - reference_camera[:2, 3]
|
| 667 |
+
return attachment_clear(obstacles, raw['base_pose'], target_base_xy)
|
| 668 |
+
# Head panning must not move the virtual camera used for
|
| 669 |
+
# graph attachment or change camera->base goal conversion.
|
| 670 |
+
route = route_planner.route(alignment @ reference_camera, args.goal, can_attach=can_attach)
|
| 671 |
+
ids = route['ids']
|
| 672 |
+
route_map = np.asarray(route['positions']).reshape(-1, 3)
|
| 673 |
+
goal_map = route_planner.matrices[args.goal][:3, 3]
|
| 674 |
+
goal_odom = positions(inverse_alignment, [goal_map])[0]
|
| 675 |
+
goal_distance = float(np.linalg.norm(goal_odom[:2] - reference_camera[:2, 3]))
|
| 676 |
+
route_odom = positions(inverse_alignment, route_map)
|
| 677 |
+
offset = reference_camera[:2, 3] - base[:2, 3]
|
| 678 |
+
hint = route_subgoal(route_odom[:, :2] - offset, base, goal_odom[:2] - offset)
|
| 679 |
+
with state.lock:
|
| 680 |
+
joint = state.robot.get('joint_positions', []) if state.robot else []
|
| 681 |
+
image_head = raw.get('head_joints')
|
| 682 |
+
if image_head is not None and len(joint) >= 11:
|
| 683 |
+
joint = np.asarray(joint, float).copy()
|
| 684 |
+
joint[9:11] = image_head
|
| 685 |
+
elif active and (hint['corner'] is not None or corners.phase != 'cruise' or survey.active):
|
| 686 |
+
raise ValueError('Timestamped head joint feedback missing; refusing camera scan')
|
| 687 |
+
|
| 688 |
+
def start_survey(reason):
|
| 689 |
+
if image_head is None:
|
| 690 |
+
raise ValueError('Timestamped head joint feedback missing; refusing camera survey')
|
| 691 |
+
if not survey.start(base, mount, neutral_mount, joint, time.monotonic(), reason):
|
| 692 |
+
return False
|
| 693 |
+
clear_goal_cache(episode)
|
| 694 |
+
corners.reset()
|
| 695 |
+
with state.lock:
|
| 696 |
+
state.plan_epoch += 1
|
| 697 |
+
if state.plan is not None:
|
| 698 |
+
state.plan = {**state.plan, 'observation_hold': True, 'stationary_survey': True,
|
| 699 |
+
'scan_w': 0., 'head_target': None, 'survey_label': survey.snapshot()['label']}
|
| 700 |
+
state.event('head_survey_started', frame_idx=index, reason=reason,
|
| 701 |
+
pass_number=survey.passes, targets=survey.targets)
|
| 702 |
+
return True
|
| 703 |
+
|
| 704 |
+
observation = {'phase': 'cruise', 'target': hint['target'], 'hold': False,
|
| 705 |
+
'head_target': None, 'scan_w': 0., 'speed_scale': 1., 'lookahead': .4}
|
| 706 |
+
if active and not recovery.pending:
|
| 707 |
+
with state.lock:
|
| 708 |
+
request_observation = state.observation_requested
|
| 709 |
+
request_reason = state.observation_reason
|
| 710 |
+
state.observation_requested = False
|
| 711 |
+
if request_observation:
|
| 712 |
+
start_survey(request_reason or 'stuck')
|
| 713 |
+
if survey.active:
|
| 714 |
+
count = len(survey.views)
|
| 715 |
+
observation = survey.update(base, mount, joint, index, time.monotonic())
|
| 716 |
+
if len(survey.views) > count:
|
| 717 |
+
state.event('head_survey_view', pass_number=survey.passes, **survey.views[-1])
|
| 718 |
+
if observation.get('survey_complete'):
|
| 719 |
+
clear_goal_cache(episode)
|
| 720 |
+
corners.reset()
|
| 721 |
+
state.event('head_survey_complete', frame_idx=index, pass_number=survey.passes)
|
| 722 |
+
else:
|
| 723 |
+
observation = corners.update(hint, base, mount, neutral_mount, joint,
|
| 724 |
+
{**grid, 'res': bev['res']}, time.monotonic())
|
| 725 |
+
target_base = observation['target']
|
| 726 |
+
if previous_goal is not None and np.linalg.norm(target_base - previous_goal) > .6:
|
| 727 |
+
clear_goal_cache(episode)
|
| 728 |
+
previous_goal = np.asarray(target_base).copy()
|
| 729 |
+
goal_body = world_to_body(target_base, base)
|
| 730 |
+
cat = {'prob': grid['prob'][None], 'obs': grid['obs'][None], 'err': grid['err'][None],
|
| 731 |
+
'log_scale': np.array([bev['log_scale']]), 'odometry': np.array([bev['scale_source'] == 'anchors']),
|
| 732 |
+
'up_head_deg': np.array([bev['gravity_head_deg']]), 'n_views': np.array([bev['n_views']])}
|
| 733 |
+
paths, debug = policy.plan_maps(cat, goal_body[None], [episode],
|
| 734 |
+
[{'ep': state.session, 'odom': raw['base_pose'], 'expect': max(0., cumulative - previous_expected)}], [True])
|
| 735 |
+
planner_debug = debug[0]
|
| 736 |
+
previous_expected = cumulative
|
| 737 |
+
path = paths[0]
|
| 738 |
+
code = int(debug[0]['status'])
|
| 739 |
+
native_path, native_code = path.copy(), code
|
| 740 |
+
rectangle_clear = rectangle_path_clear(path, {**grid, 'res': bev['res']})
|
| 741 |
+
if not rectangle_clear and not observation['hold']:
|
| 742 |
+
# Request observation rather than executing a route that
|
| 743 |
+
# clears a centre point but clips a rectangular corner.
|
| 744 |
+
code = 2
|
| 745 |
+
side = 1. if goal_body[1] >= 0 else -1.
|
| 746 |
+
path = np.tile([0., side * .3], (len(path), 1))
|
| 747 |
+
if active and not recovery.pending and code == 2 and not observation['hold']:
|
| 748 |
+
if start_survey('native no route' if rectangle_clear else 'learned path footprint'):
|
| 749 |
+
observation = survey.update(base, mount, joint, index, time.monotonic())
|
| 750 |
+
if observation['hold']:
|
| 751 |
+
path = np.zeros_like(path)
|
| 752 |
+
with state.lock:
|
| 753 |
+
control = state.last_control
|
| 754 |
+
control_report = control.get('footprint')
|
| 755 |
+
footprint_diagnostics = depth_support(control_report, obstacles) if control_report else None
|
| 756 |
+
if footprint_diagnostics is not None:
|
| 757 |
+
footprint_diagnostics['command_capture_frame'] = control.get('plan_capture_frame')
|
| 758 |
+
for cell in footprint_diagnostics['cells'] + footprint_diagnostics.get('self_cells', []):
|
| 759 |
+
cell['display_body_xy'] = world_to_body(cell['world_xy'], base).tolist()
|
| 760 |
+
evidence = None
|
| 761 |
+
if active and (survey.active or control.get('learned_blocked') or control.get('depth_blocked')) and (
|
| 762 |
+
time.monotonic() - last_evidence >= 1.
|
| 763 |
+
):
|
| 764 |
+
last_evidence = time.monotonic()
|
| 765 |
+
evidence = f'footprint_evidence/{index:08d}.npz'
|
| 766 |
+
np.savez_compressed(args.output / evidence, **grid, res=bev['res'],
|
| 767 |
+
base=base, camera=camera, measured_obstacles_odom=obstacles,
|
| 768 |
+
native_path_body=native_path, native_planner_status=native_code)
|
| 769 |
+
path_odom = body_to_world(path, base)
|
| 770 |
+
path_odom_with_origin = np.vstack([base[:2, 3], path_odom])
|
| 771 |
+
plan = {'input_received': raw['received_monotonic'], 'localized': True,
|
| 772 |
+
'localized_streak': streak, 'frame_id': raw['frame_id'],
|
| 773 |
+
'capture_frame': index,
|
| 774 |
+
'route_ids': ids, 'path_odom': path_odom_with_origin, 'planner_status': code,
|
| 775 |
+
'published': time.monotonic(),
|
| 776 |
+
'goal_distance': goal_distance, 'arrived': goal_distance <= .4,
|
| 777 |
+
'depth_obstacles': obstacles, 'recovery_pending': recovery.pending,
|
| 778 |
+
'footprint_grid': {**grid, 'res': bev['res']}, 'planning_base': base,
|
| 779 |
+
'recovery_deadline': correction['deadline'], 'epoch': state.plan_epoch,
|
| 780 |
+
'observation_hold': observation['hold'], 'head_target': observation['head_target'],
|
| 781 |
+
'stationary_survey': observation['phase'].startswith('survey'),
|
| 782 |
+
'survey_label': observation.get('survey_label'),
|
| 783 |
+
'corner_phase': observation['phase'], 'scan_w': observation['scan_w'],
|
| 784 |
+
'scan_authorized': code == 2, 'speed_scale': observation['speed_scale'],
|
| 785 |
+
'lookahead': observation['lookahead']}
|
| 786 |
+
camera_display = positions(state.display, [c0[:3, 3]])[0]
|
| 787 |
+
trajectory.append(camera_display.tolist())
|
| 788 |
+
names = ['goal route', 'local waypoint', 'no route / scan', 'near goal',
|
| 789 |
+
'remembered route', 'relaxed route', 'episode-map route']
|
| 790 |
+
record.update(camera_display=camera_display, global_route=positions(state.display, route_map),
|
| 791 |
+
local_path_display=positions(state.display @ alignment, np.column_stack([path_odom, np.zeros(len(path_odom))])),
|
| 792 |
+
local_path_body=path, goal_body=goal_body, goal_distance=goal_distance,
|
| 793 |
+
route_ids=ids, route_cost_m=route.get('cost_m'), route_attachment=route.get('attachment'),
|
| 794 |
+
corner_observation=observation, rectangle_clear=rectangle_clear,
|
| 795 |
+
head_survey=survey.snapshot(), footprint_diagnostics=footprint_diagnostics,
|
| 796 |
+
footprint_evidence=evidence, native_local_path_body=native_path,
|
| 797 |
+
native_planner_status=native_code,
|
| 798 |
+
planner_name=names[code], blind_zone=bool(debug[0]['blind_zone']),
|
| 799 |
+
trajectory=trajectory[-1500:], native_map_camera=c0)
|
| 800 |
+
record['compute_s'] = time.monotonic() - started
|
| 801 |
+
record['input_age_at_publish_s'] = time.monotonic() - raw['received_monotonic']
|
| 802 |
+
if debug_archive:
|
| 803 |
+
debug_archive.finish_frame(
|
| 804 |
+
observation={key: value for key, value in record.items() if key != 'trajectory'},
|
| 805 |
+
consumed_bev=bev, body_grid=grid, planner_debug=planner_debug,
|
| 806 |
+
planner_state=planner_snapshot(episode) if planner_debug is not None else None)
|
| 807 |
+
record['vggt_debug_frame'] = f'frames/{index:08d}/frame.json'
|
| 808 |
+
with state.lock:
|
| 809 |
+
state.plan, state.last_json = plan, clean_json(record)
|
| 810 |
+
state.processed += 1
|
| 811 |
+
save_json(args.output / 'latest_plan.json', record)
|
| 812 |
+
log.write(json.dumps(clean_json(record), allow_nan=False) + '\n')
|
| 813 |
+
if state.processed % 20 == 1:
|
| 814 |
+
print(json.dumps({'processed': state.processed, 'frame': index, 'localized': localized,
|
| 815 |
+
'streak': streak, 'views': record['n_views'], 'phase': phase}), flush=True)
|
| 816 |
+
artifacts.metadata.update(nonzero_motion_commands=state.motion_commands, stop_reason=state.reason)
|
| 817 |
+
session.release()
|
| 818 |
+
artifacts.finish()
|
| 819 |
+
except BaseException as exc:
|
| 820 |
+
mapping_error = exc
|
| 821 |
+
state.finish('Mapping/planning error: ' + str(exc))
|
| 822 |
+
artifacts.finish(exc)
|
| 823 |
+
raise
|
| 824 |
+
finally:
|
| 825 |
+
if debug_archive:
|
| 826 |
+
debug_archive.close(mapping_error)
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
def main():
|
| 830 |
+
p = argparse.ArgumentParser(description=__doc__)
|
| 831 |
+
p.add_argument('--robot-ip', default='192.0.2.2')
|
| 832 |
+
p.add_argument('--cross-root', type=Path, default=Path('/workspace/CROSS'))
|
| 833 |
+
p.add_argument('--stretch-root', type=Path, default=Path('/workspace/stretch_ai'))
|
| 834 |
+
p.add_argument('--map-run', type=Path, required=True)
|
| 835 |
+
p.add_argument('--output', type=Path, required=True)
|
| 836 |
+
p.add_argument('--goal', type=int, default=1012)
|
| 837 |
+
p.add_argument('--port', type=int, default=8088)
|
| 838 |
+
p.add_argument('--max-v', type=float, default=.10)
|
| 839 |
+
p.add_argument('--max-w', type=float, default=.25)
|
| 840 |
+
p.add_argument('--max-plan-age', type=float, default=1.2)
|
| 841 |
+
p.add_argument('--plan-hold-seconds', type=float, default=3.)
|
| 842 |
+
p.add_argument('--vggt-debug', action=argparse.BooleanOptionalAction, default=True,
|
| 843 |
+
help='Save every VGGT input group and numeric output in a separate debug archive (default: enabled)')
|
| 844 |
+
p.add_argument('--vggt-debug-dir', type=Path, help='Debug archive directory; default: OUTPUT/vggt_debug')
|
| 845 |
+
args = p.parse_args()
|
| 846 |
+
if not 0 < args.max_v <= .10 or not 0 < args.max_w <= .25:
|
| 847 |
+
raise ValueError('Initial live test is limited to 0.10 m/s and 0.25 rad/s')
|
| 848 |
+
if not .4 <= args.max_plan_age <= 1.5 or not 0. <= args.plan_hold_seconds <= 5.:
|
| 849 |
+
raise ValueError('Plan evidence must expire within 0.4–1.5 s; zero-velocity hold at most 5 s')
|
| 850 |
+
args.output, args.map_run = args.output.resolve(), args.map_run.resolve()
|
| 851 |
+
if args.vggt_debug_dir is not None:
|
| 852 |
+
args.vggt_debug_dir = args.vggt_debug_dir.resolve()
|
| 853 |
+
args.cross_root, args.stretch_root = args.cross_root.resolve(), args.stretch_root.resolve()
|
| 854 |
+
required = [args.cross_root / 'cross_nav/configs/policy/bev_planner_vfin2.json',
|
| 855 |
+
args.cross_root / 'models/VGGT-Omega-CROSS/vggt_omega_cross_1b_512.pt',
|
| 856 |
+
args.cross_root / 'models/VGGT-Omega-CROSS/nav/cross_nav_occupancy.pt',
|
| 857 |
+
args.cross_root / 'models/VGGT-Omega-CROSS/nav/cross_nav_observability.pt']
|
| 858 |
+
for file in required:
|
| 859 |
+
if not file.is_file():
|
| 860 |
+
raise FileNotFoundError(f'Required navigation file is missing: {file}')
|
| 861 |
+
graph = json.loads((args.map_run / 'graph.json').read_text())
|
| 862 |
+
nodes = [n for n in graph['nodes'] if not n['temporary']]
|
| 863 |
+
if args.goal not in {n['id'] for n in nodes}:
|
| 864 |
+
raise ValueError('Goal must be a permanent reference map keyframe')
|
| 865 |
+
sys.path[:0] = [str(args.cross_root), str(args.stretch_root / 'scripts')]
|
| 866 |
+
planner_runtime = warmup_native_navigation()
|
| 867 |
+
# Detect an occupied viewer port before creating a run or touching the robot.
|
| 868 |
+
server = ThreadingHTTPServer(('127.0.0.1', args.port), Handler)
|
| 869 |
+
try:
|
| 870 |
+
args.output.mkdir(parents=True, exist_ok=False)
|
| 871 |
+
state = LiveState(args)
|
| 872 |
+
except BaseException:
|
| 873 |
+
server.server_close()
|
| 874 |
+
raise
|
| 875 |
+
source = json.loads((args.map_run / 'run.json').read_text())
|
| 876 |
+
state.display = np.asarray(source['T_display_from_map'])
|
| 877 |
+
state.map_data = {'nodes': [{'id': n['id'], 'position': positions(state.display, [np.asarray(n['pose'])[:3, 3]])[0].tolist()}
|
| 878 |
+
for n in nodes], 'goal': args.goal}
|
| 879 |
+
save_json(args.output / 'map.json', state.map_data)
|
| 880 |
+
save_json(args.output / 'planner_runtime.json', planner_runtime)
|
| 881 |
+
server.daemon_threads = True
|
| 882 |
+
server.state = state
|
| 883 |
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
| 884 |
+
print(f'Live CROSS handoff: http://127.0.0.1:{args.port} — passive until Start navigation', flush=True)
|
| 885 |
+
shutdown = threading.Event()
|
| 886 |
+
def interrupt(*_):
|
| 887 |
+
shutdown.set()
|
| 888 |
+
state.finish('Process interrupted by operator')
|
| 889 |
+
signal.signal(signal.SIGINT, interrupt)
|
| 890 |
+
signal.signal(signal.SIGTERM, interrupt)
|
| 891 |
+
from depth_nav_live import RobotRelayProcess
|
| 892 |
+
relay = RobotRelayProcess(SimpleNamespace(robot_ip=args.robot_ip, ssh_user='hello-robot', container=None,
|
| 893 |
+
world_frame='odom', plan_hz=4., relay_max_frame_age=args.max_plan_age, command_ttl=.3,
|
| 894 |
+
enable_head=True), args.output)
|
| 895 |
+
threads = []
|
| 896 |
+
try:
|
| 897 |
+
relay.start()
|
| 898 |
+
for target in (capture_loop, control_loop):
|
| 899 |
+
t = threading.Thread(target=target, args=(state, relay) if target is capture_loop else (state,), daemon=True)
|
| 900 |
+
t.start()
|
| 901 |
+
threads.append(t)
|
| 902 |
+
os.chdir(args.cross_root)
|
| 903 |
+
run_mapping(state)
|
| 904 |
+
except BaseException as exc:
|
| 905 |
+
state.finish('Live pipeline error: ' + str(exc))
|
| 906 |
+
state.event('pipeline_error', error=str(exc))
|
| 907 |
+
import traceback
|
| 908 |
+
traceback.print_exc()
|
| 909 |
+
finally:
|
| 910 |
+
state.done.set()
|
| 911 |
+
for t in threads:
|
| 912 |
+
t.join(timeout=2.)
|
| 913 |
+
relay_closed = relay.close()
|
| 914 |
+
if relay_closed is False:
|
| 915 |
+
state.reason += '; robot relay shutdown could not be verified'
|
| 916 |
+
# This runner retains only the review UI after stopping. Do not retain
|
| 917 |
+
# the pipeline's model-reuse cache and several GB of GPU memory.
|
| 918 |
+
if 'cross.pipeline' in sys.modules:
|
| 919 |
+
cache = getattr(sys.modules['cross.pipeline'], '_MODEL_CACHE', None)
|
| 920 |
+
if cache is not None:
|
| 921 |
+
cache.clear()
|
| 922 |
+
import gc
|
| 923 |
+
gc.collect()
|
| 924 |
+
import torch
|
| 925 |
+
torch.cuda.empty_cache()
|
| 926 |
+
save_json(args.output / 'final_status.json', state.snapshot())
|
| 927 |
+
print(f'Live session ended; relay shutdown verified={relay_closed is not False}. Viewer remains available.', flush=True)
|
| 928 |
+
# Retain the local review page after the run ends. A new run uses a new directory.
|
| 929 |
+
while not shutdown.wait(1.):
|
| 930 |
+
pass
|
| 931 |
+
server.shutdown()
|
| 932 |
+
server.server_close()
|
| 933 |
+
|
| 934 |
+
|
| 935 |
+
if __name__ == '__main__':
|
| 936 |
+
main()
|
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()
|
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()
|
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()
|
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()
|
code/lite3_ROS/tests/test_stretch_nav_control.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from web_console.stretch_nav_control import (
|
| 5 |
+
PlanWait, alignment_correction, attachment_clear, competing_controllers, depth_veto, execution_gate, remaining_path,
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def planar_transform(angle=0., x=0., y=0.):
|
| 10 |
+
c, s = np.cos(angle), np.sin(angle)
|
| 11 |
+
return np.array([[c, -s, 0., x], [s, c, 0., y], [0., 0., 1., 0.], [0., 0., 0., 1.]])
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_small_map_rotation_about_distant_robot_does_not_look_like_position_jump():
|
| 15 |
+
base = planar_transform(x=20., y=10.)
|
| 16 |
+
angle = np.deg2rad(2.3)
|
| 17 |
+
corrected = base @ planar_transform(angle) @ np.linalg.inv(base)
|
| 18 |
+
assert np.linalg.norm(corrected[:3, 3]) > .5 # The former origin-based check stopped here.
|
| 19 |
+
distance, rotation = alignment_correction(np.eye(4), corrected, base)
|
| 20 |
+
assert distance == pytest.approx(0., abs=1e-12)
|
| 21 |
+
assert rotation == pytest.approx(angle)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_map_correction_is_independent_of_odom_origin():
|
| 25 |
+
previous = planar_transform(.3, 1., 2.)
|
| 26 |
+
current = planar_transform(.32, 1.1, 2.2)
|
| 27 |
+
base = planar_transform(.7, 12., 8.)
|
| 28 |
+
expected = alignment_correction(previous, current, base)
|
| 29 |
+
rebase = planar_transform(-.8, 100., -200.)
|
| 30 |
+
actual = alignment_correction(previous @ np.linalg.inv(rebase), current @ np.linalg.inv(rebase), rebase @ base)
|
| 31 |
+
np.testing.assert_allclose(actual, expected, atol=1e-12)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@pytest.mark.parametrize('translation,angle', [(.51, 0.), (0., np.deg2rad(26))])
|
| 35 |
+
def test_real_map_pose_jump_still_exceeds_stop_limits(translation, angle):
|
| 36 |
+
base = planar_transform(x=20., y=10.)
|
| 37 |
+
corrected = planar_transform(x=translation) @ base @ planar_transform(angle) @ np.linalg.inv(base)
|
| 38 |
+
distance, rotation = alignment_correction(np.eye(4), corrected, base)
|
| 39 |
+
assert distance > .5 or rotation > np.deg2rad(25)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@pytest.mark.parametrize('bad', [np.full((4, 4), np.nan), np.eye(3)])
|
| 43 |
+
def test_invalid_alignment_is_rejected(bad):
|
| 44 |
+
with pytest.raises(ValueError, match='Invalid map alignment'):
|
| 45 |
+
alignment_correction(np.eye(4), bad, np.eye(4))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def valid_inputs():
|
| 49 |
+
plan = {'input_received': 9.8, 'localized': True, 'localized_streak': 3,
|
| 50 |
+
'route_ids': [1, 2], 'planner_status': 0,
|
| 51 |
+
'goal_distance': 2., 'path_odom': [[0., 0.], [1., 0.]]}
|
| 52 |
+
robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True,
|
| 53 |
+
'healthy': True, 'latched': False}
|
| 54 |
+
return plan, robot
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_teleop_never_passes_execution_gate():
|
| 58 |
+
p, r = valid_inputs()
|
| 59 |
+
assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9, state='teleop')
|
| 60 |
+
assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9) == ''
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@pytest.mark.parametrize('field,value', [('localized', False), ('localized_streak', 2),
|
| 64 |
+
('input_received', 8.6), ('input_received', np.nan),
|
| 65 |
+
('route_ids', []), ('planner_status', 2), ('path_odom', []), ('goal_distance', np.nan)])
|
| 66 |
+
def test_bad_plan_blocks_commands(field, value):
|
| 67 |
+
p, r = valid_inputs()
|
| 68 |
+
p[field] = value
|
| 69 |
+
assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@pytest.mark.parametrize('verified_at', [None, 7., -np.inf])
|
| 73 |
+
def test_committed_localization_can_bridge_map_match_gaps(verified_at):
|
| 74 |
+
p, r = valid_inputs()
|
| 75 |
+
# Accept both new plans with no verification clock and older recorded plans.
|
| 76 |
+
if verified_at is not None:
|
| 77 |
+
p['verified_at'] = verified_at
|
| 78 |
+
assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9) == ''
|
| 79 |
+
# Only new sensor/plan evidence keeps execution alive during a longer gap.
|
| 80 |
+
p['input_received'] = 39.8
|
| 81 |
+
assert execution_gate(p, r, now=40., robot_received=39.9, heartbeat=39.9) == ''
|
| 82 |
+
p['localized'] = False
|
| 83 |
+
assert execution_gate(p, r, now=40., robot_received=39.9, heartbeat=39.9) == (
|
| 84 |
+
'waiting for stable committed localization')
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@pytest.mark.parametrize('field,value', [('is_runstopped', True), ('is_homed', False),
|
| 88 |
+
('posture_ok', False), ('latched', True), ('healthy', False)])
|
| 89 |
+
def test_unavailable_robot_blocks_commands(field, value):
|
| 90 |
+
p, r = valid_inputs()
|
| 91 |
+
r[field] = value
|
| 92 |
+
assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def test_stale_browser_and_status_block_commands():
|
| 96 |
+
p, r = valid_inputs()
|
| 97 |
+
assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=7.)
|
| 98 |
+
assert execution_gate(p, r, now=10., robot_received=9., heartbeat=9.9)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_follow_path_drops_passed_prefix_and_rotates_into_current_base():
|
| 102 |
+
result = remaining_path([[0., 0.], [0., 1.], [0., 2.]], [0., .6, np.pi / 2])
|
| 103 |
+
np.testing.assert_allclose(result[:, 0], [0., .4, 1.4], atol=1e-8)
|
| 104 |
+
np.testing.assert_allclose(result[:, 1], 0., atol=1e-8)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def test_depth_guard_vetoes_swept_body_but_ignores_off_path_returns():
|
| 108 |
+
obstacle = np.array([[.30, -.01], [.30, 0.], [.30, .01]])
|
| 109 |
+
assert depth_veto(obstacle, [0., 0., 0.], .1, 0.)
|
| 110 |
+
assert not depth_veto(obstacle + [0., 1.], [0., 0., 0.], .1, 0.)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def test_attachment_rejects_measured_wall_between_base_and_nearby_keyframe():
|
| 114 |
+
obstacle = np.array([[.35, -.01], [.35, 0.], [.35, .01]])
|
| 115 |
+
assert not attachment_clear(obstacle, [0., 0., 0.], [.5, 0.])
|
| 116 |
+
assert attachment_clear(obstacle, [0., 0., 0.], [-.5, 0.])
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def test_attachment_handles_sideways_connection_and_robot_self_mask():
|
| 120 |
+
obstacle = np.array([[0., .35], [.01, .35], [-.01, .35], [0., 0.]])
|
| 121 |
+
assert not attachment_clear(obstacle, [0., 0., np.pi / 2], [0., .5])
|
| 122 |
+
assert attachment_clear(obstacle, [0., 0., np.pi / 2], [0., -.5])
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def test_relaxed_plan_limit_still_expires():
|
| 126 |
+
p, r = valid_inputs()
|
| 127 |
+
p['input_received'] = 8.9
|
| 128 |
+
assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9) == ''
|
| 129 |
+
p['input_received'] = 8.7
|
| 130 |
+
assert execution_gate(p, r, now=10., robot_received=9.9, heartbeat=9.9)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_plan_wait_recovers_transient_gaps_but_ends_sustained_gap():
|
| 134 |
+
wait = PlanWait(timeout=3.)
|
| 135 |
+
assert wait.holds('sensor/plan evidence stale', 10.)
|
| 136 |
+
assert wait.holds('sensor/plan evidence stale', 12.9)
|
| 137 |
+
assert not wait.holds('sensor/plan evidence stale', 13.1)
|
| 138 |
+
assert not wait.holds('', 14.)
|
| 139 |
+
assert wait.since is None
|
| 140 |
+
assert wait.holds('sensor/plan evidence stale', 20.)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@pytest.mark.parametrize('reason', ['viewer heartbeat expired',
|
| 144 |
+
'waiting for stable committed localization', 'robot state/camera/TF unavailable', 'robot stop latched'])
|
| 145 |
+
def test_plan_wait_never_treats_other_faults_as_transient(reason):
|
| 146 |
+
assert not PlanWait().holds(reason, 10.)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_known_teleop_process_detected_without_matching_our_live_adapter(tmp_path):
|
| 150 |
+
for pid, args in [(100, ['python', '/app/teleop.py', '--robot-ip', '192.0.2.1']),
|
| 151 |
+
(101, ['python', '/app/live_stretch_cross_nav.py']),
|
| 152 |
+
(102, ['bash', '-c', 'python teleop.py'])]:
|
| 153 |
+
directory = tmp_path / str(pid)
|
| 154 |
+
directory.mkdir()
|
| 155 |
+
(directory / 'cmdline').write_bytes(b'\0'.join(a.encode() for a in args))
|
| 156 |
+
assert competing_controllers(tmp_path) == [{'pid': 100, 'client': 'teleop.py'}]
|
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))
|
code/lite3_ROS/tests/test_stretch_nav_handoff.py
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exercise command transport with fake sockets; these tests cannot reach hardware."""
|
| 2 |
+
import importlib.util
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
import threading
|
| 6 |
+
import time
|
| 7 |
+
from types import SimpleNamespace
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
def load_adapter():
|
| 13 |
+
path = Path(__file__).resolve().parents[1] / 'scripts/live_stretch_cross_nav.py'
|
| 14 |
+
spec = importlib.util.spec_from_file_location('stretch_live_adapter', path)
|
| 15 |
+
module = importlib.util.module_from_spec(spec)
|
| 16 |
+
spec.loader.exec_module(module)
|
| 17 |
+
return module
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Socket:
|
| 21 |
+
def __init__(self):
|
| 22 |
+
self.sent = []
|
| 23 |
+
|
| 24 |
+
def setsockopt(self, *_):
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
def connect(self, *_):
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
def poll(self, *_):
|
| 31 |
+
return False
|
| 32 |
+
|
| 33 |
+
def close(self):
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
def send_json(self, command, **_):
|
| 37 |
+
self.sent.append(command)
|
| 38 |
+
|
| 39 |
+
def send_pyobj(self, command):
|
| 40 |
+
self.sent.append(command)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class Context:
|
| 44 |
+
def __init__(self):
|
| 45 |
+
self.sockets = []
|
| 46 |
+
|
| 47 |
+
def socket(self, *_):
|
| 48 |
+
result = Socket()
|
| 49 |
+
self.sockets.append(result)
|
| 50 |
+
return result
|
| 51 |
+
|
| 52 |
+
def term(self):
|
| 53 |
+
pass
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def setup(monkeypatch, tmp_path):
|
| 57 |
+
module = load_adapter()
|
| 58 |
+
context = Context()
|
| 59 |
+
monkeypatch.setattr(module.zmq, 'Context', lambda: context)
|
| 60 |
+
monkeypatch.setattr(module, 'competing_controllers', lambda: [])
|
| 61 |
+
monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(
|
| 62 |
+
pure_pursuit=lambda *_a, **_k: (_ for _ in ()).throw(AssertionError('Must not follow a path'))))
|
| 63 |
+
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.)
|
| 64 |
+
state = module.LiveState(args)
|
| 65 |
+
return module, state, context
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_passive_loop_never_sends_arm_mode_stop_or_velocity(monkeypatch, tmp_path):
|
| 69 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 70 |
+
# Complete several real control ticks before ending the fake session.
|
| 71 |
+
timer = threading.Timer(.18, state.done.set)
|
| 72 |
+
timer.start()
|
| 73 |
+
module.control_loop(state)
|
| 74 |
+
timer.join()
|
| 75 |
+
assert len(context.sockets) == 3
|
| 76 |
+
assert all(not socket.sent for socket in context.sockets)
|
| 77 |
+
assert state.motion_commands == 0
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_loss_of_localization_sends_stop_only(monkeypatch, tmp_path):
|
| 81 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 82 |
+
state.phase = 'active'
|
| 83 |
+
state.relay_ever_requested = True
|
| 84 |
+
state.heartbeat = state.robot_received = time.monotonic()
|
| 85 |
+
state.robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True,
|
| 86 |
+
'healthy': True, 'latched': False}
|
| 87 |
+
state.plan = {'input_received': time.monotonic(), 'goal_distance': 2., 'localized': False}
|
| 88 |
+
module.control_loop(state)
|
| 89 |
+
assert state.phase == 'stopped'
|
| 90 |
+
commands = [command for socket in context.sockets for command in socket.sent]
|
| 91 |
+
assert len(commands) == 3
|
| 92 |
+
assert all(command['type'] == 'stop' for command in commands)
|
| 93 |
+
assert state.motion_commands == 0
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_browser_disconnect_stops_without_motion(monkeypatch, tmp_path):
|
| 97 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 98 |
+
state.phase = 'active'
|
| 99 |
+
state.relay_ever_requested = True
|
| 100 |
+
state.heartbeat = time.monotonic() - 3.
|
| 101 |
+
module.control_loop(state)
|
| 102 |
+
assert state.phase == 'stopped'
|
| 103 |
+
assert all(c['type'] == 'stop' for socket in context.sockets for c in socket.sent)
|
| 104 |
+
assert 'heartbeat' in state.reason
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def test_brief_plan_gap_sends_zero_then_resumes_only_with_fresh_plan(monkeypatch, tmp_path):
|
| 108 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 109 |
+
monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=lambda *_a, **_k: (.08, 0.)))
|
| 110 |
+
state.phase = 'active'
|
| 111 |
+
state.relay_ever_requested = True
|
| 112 |
+
now = time.monotonic()
|
| 113 |
+
state.heartbeat = state.robot_received = now
|
| 114 |
+
state.robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True, 'healthy': True,
|
| 115 |
+
'latched': False, 'armed': True, 'session': state.session, 'frame_id': 1, 'base_pose': [0., 0., 0.]}
|
| 116 |
+
state.plan = {'input_received': now - 1.3, 'goal_distance': 2., 'localized': True,
|
| 117 |
+
'localized_streak': 3, 'route_ids': [1, 2],
|
| 118 |
+
'planner_status': 0, 'path_odom': [[0., 0.], [1., 0.]], 'frame_id': 1,
|
| 119 |
+
'depth_obstacles': np.empty((0, 2))}
|
| 120 |
+
fresh = threading.Timer(.075, lambda: state.plan.update(input_received=time.monotonic()))
|
| 121 |
+
end = threading.Timer(.23, lambda: state.finish('End simulated run'))
|
| 122 |
+
fresh.start()
|
| 123 |
+
end.start()
|
| 124 |
+
module.control_loop(state)
|
| 125 |
+
fresh.join()
|
| 126 |
+
end.join()
|
| 127 |
+
commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
|
| 128 |
+
assert commands[0]['v'] == commands[0]['w'] == 0.
|
| 129 |
+
assert any(c['v'] > 0 for c in commands)
|
| 130 |
+
assert all(c['ttl'] == .3 for c in commands)
|
| 131 |
+
import json
|
| 132 |
+
assert json.loads((tmp_path / 'control.json').read_text())['v'] == 0.
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@pytest.mark.parametrize('has_old_verification_clock', [False, True])
|
| 136 |
+
def test_map_match_gap_continues_fresh_local_plan(monkeypatch, tmp_path, has_old_verification_clock):
|
| 137 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 138 |
+
monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=lambda *_a, **_k: (.08, 0.)))
|
| 139 |
+
state.phase = 'active'
|
| 140 |
+
state.relay_ever_requested = True
|
| 141 |
+
now = time.monotonic()
|
| 142 |
+
state.heartbeat = state.robot_received = now
|
| 143 |
+
state.robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True, 'healthy': True,
|
| 144 |
+
'latched': False, 'armed': True, 'session': state.session, 'frame_id': 1, 'base_pose': [0., 0., 0.]}
|
| 145 |
+
state.plan = {'input_received': now, 'goal_distance': 2., 'localized': True,
|
| 146 |
+
'localized_streak': 3, 'route_ids': [1, 2],
|
| 147 |
+
'planner_status': 0, 'path_odom': [[0., 0.], [1., 0.]], 'frame_id': 1,
|
| 148 |
+
'depth_obstacles': np.empty((0, 2))}
|
| 149 |
+
if has_old_verification_clock:
|
| 150 |
+
state.plan['verified_at'] = now - 30.
|
| 151 |
+
end = threading.Timer(.18, lambda: state.finish('End simulated visual gap'))
|
| 152 |
+
end.start()
|
| 153 |
+
module.control_loop(state)
|
| 154 |
+
end.join()
|
| 155 |
+
commands = [c for socket in context.sockets for c in socket.sent]
|
| 156 |
+
velocity = [c for c in commands if c['type'] == 'velocity']
|
| 157 |
+
assert velocity and all(c['v'] == .08 and c['w'] == 0. for c in velocity)
|
| 158 |
+
assert all(c['ttl'] == .3 for c in velocity)
|
| 159 |
+
assert [c['type'] for c in commands[-3:]] == ['stop', 'stop', 'stop']
|
| 160 |
+
assert state.reason == 'End simulated visual gap'
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def test_sustained_plan_gap_never_executes_stale_path(monkeypatch, tmp_path):
|
| 164 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 165 |
+
state.args.plan_hold_seconds = .08
|
| 166 |
+
state.phase = 'active'
|
| 167 |
+
state.relay_ever_requested = True
|
| 168 |
+
now = time.monotonic()
|
| 169 |
+
state.heartbeat = state.robot_received = now
|
| 170 |
+
state.robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True, 'healthy': True,
|
| 171 |
+
'latched': False, 'armed': True, 'session': state.session, 'frame_id': 1, 'base_pose': [0., 0., 0.]}
|
| 172 |
+
state.plan = {'input_received': now - 1.3, 'goal_distance': 2.}
|
| 173 |
+
module.control_loop(state)
|
| 174 |
+
assert state.phase == 'stopped'
|
| 175 |
+
commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
|
| 176 |
+
assert commands and all(c['v'] == c['w'] == 0. for c in commands)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def test_competing_teleop_blocks_mode_switch_and_arm(monkeypatch, tmp_path):
|
| 180 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 181 |
+
monkeypatch.setattr(module, 'competing_controllers', lambda: [{'pid': 123, 'client': 'teleop.py'}])
|
| 182 |
+
state.phase = 'preparing'
|
| 183 |
+
module.control_loop(state)
|
| 184 |
+
assert state.phase == 'stopped'
|
| 185 |
+
assert 'Competing' in state.reason
|
| 186 |
+
assert all(not socket.sent for socket in context.sockets)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def test_time_spent_scanning_controllers_counts_toward_plan_expiry(monkeypatch, tmp_path):
|
| 190 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 191 |
+
clock = [10.]
|
| 192 |
+
monkeypatch.setattr(module.time, 'monotonic', lambda: clock[0])
|
| 193 |
+
def slow_scan():
|
| 194 |
+
clock[0] = 13.
|
| 195 |
+
return []
|
| 196 |
+
monkeypatch.setattr(module, 'competing_controllers', slow_scan)
|
| 197 |
+
state.phase = 'active'
|
| 198 |
+
state.relay_ever_requested = True
|
| 199 |
+
state.args.plan_hold_seconds = 0.
|
| 200 |
+
state.heartbeat = state.robot_received = 13.
|
| 201 |
+
state.robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True,
|
| 202 |
+
'healthy': True, 'latched': False}
|
| 203 |
+
state.plan = {'input_received': 10., 'goal_distance': 2., 'localized': True,
|
| 204 |
+
'localized_streak': 3, 'route_ids': [1, 2], 'planner_status': 0,
|
| 205 |
+
'path_odom': [[0., 0.], [1., 0.]]}
|
| 206 |
+
module.control_loop(state)
|
| 207 |
+
assert state.reason == 'sensor/plan evidence stale; navigation ended'
|
| 208 |
+
assert state.motion_commands == 0
|
| 209 |
+
assert all(c['type'] == 'stop' for socket in context.sockets for c in socket.sent)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def test_planner_warmup_compiles_both_searches_without_robot_transport(monkeypatch):
|
| 213 |
+
module = load_adapter()
|
| 214 |
+
calls = []
|
| 215 |
+
def dijkstra(*args):
|
| 216 |
+
calls.append('dijkstra')
|
| 217 |
+
dijkstra.signatures.append('compiled')
|
| 218 |
+
dijkstra.signatures = []
|
| 219 |
+
search = SimpleNamespace(signatures=[])
|
| 220 |
+
def astar(*args):
|
| 221 |
+
calls.append('astar')
|
| 222 |
+
search.signatures.append('compiled')
|
| 223 |
+
monkeypatch.setitem(sys.modules, 'numba', SimpleNamespace(__version__='test'))
|
| 224 |
+
monkeypatch.setitem(sys.modules, 'cross_nav.plan', SimpleNamespace(_dijkstra=dijkstra))
|
| 225 |
+
monkeypatch.setitem(sys.modules, 'cross_nav.policy.bev_policy', SimpleNamespace(_astar=lambda: search, astar=astar))
|
| 226 |
+
monkeypatch.setattr(module.zmq, 'Context', lambda: (_ for _ in ()).throw(AssertionError('No transport during warmup')))
|
| 227 |
+
result = module.warmup_native_navigation()
|
| 228 |
+
assert calls == ['astar', 'dijkstra']
|
| 229 |
+
assert result['astar_signatures'] == result['dijkstra_signatures'] == ['compiled']
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def test_unaccelerated_planner_is_rejected_before_handoff(monkeypatch):
|
| 233 |
+
module = load_adapter()
|
| 234 |
+
monkeypatch.setitem(sys.modules, 'numba', SimpleNamespace(__version__='test'))
|
| 235 |
+
monkeypatch.setitem(sys.modules, 'cross_nav.plan', SimpleNamespace(_dijkstra=lambda *_: None))
|
| 236 |
+
monkeypatch.setitem(sys.modules, 'cross_nav.policy.bev_policy',
|
| 237 |
+
SimpleNamespace(_astar=lambda: (lambda *_: None), astar=lambda *_: None))
|
| 238 |
+
with pytest.raises(RuntimeError, match='requires CROSS nav dependencies'):
|
| 239 |
+
module.warmup_native_navigation()
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def active_plan(state):
|
| 243 |
+
now = time.monotonic()
|
| 244 |
+
state.phase, state.relay_ever_requested = 'active', True
|
| 245 |
+
state.heartbeat = state.robot_received = now
|
| 246 |
+
state.robot = {'is_runstopped': False, 'is_homed': True, 'posture_ok': True, 'healthy': True,
|
| 247 |
+
'latched': False, 'armed': True, 'session': state.session, 'frame_id': 1,
|
| 248 |
+
'base_pose': [0., 0., 0.], 'head_enabled': True}
|
| 249 |
+
state.plan = {'input_received': now, 'goal_distance': 2., 'localized': True,
|
| 250 |
+
'localized_streak': 3, 'route_ids': [1, 2], 'planner_status': 0,
|
| 251 |
+
'path_odom': [[0., 0.], [1., 0.]], 'frame_id': 1,
|
| 252 |
+
'depth_obstacles': np.empty((0, 2))}
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def test_correction_recovery_keeps_lease_at_zero_then_resumes(monkeypatch, tmp_path):
|
| 256 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 257 |
+
active_plan(state)
|
| 258 |
+
monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=lambda *_a, **_k: (.08, 0.)))
|
| 259 |
+
state.plan.update(recovery_pending=True, recovery_deadline=time.monotonic() + 12.)
|
| 260 |
+
fresh = threading.Timer(.075, lambda: state.plan.update(recovery_pending=False))
|
| 261 |
+
end = threading.Timer(.20, lambda: state.finish('End recovery simulation'))
|
| 262 |
+
fresh.start()
|
| 263 |
+
end.start()
|
| 264 |
+
module.control_loop(state)
|
| 265 |
+
fresh.join()
|
| 266 |
+
end.join()
|
| 267 |
+
commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
|
| 268 |
+
assert commands[0]['v'] == commands[0]['w'] == 0.
|
| 269 |
+
assert any(c['v'] > 0 for c in commands)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def test_brief_robot_status_gap_holds_zero_until_fresh_status_returns(monkeypatch, tmp_path):
|
| 273 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 274 |
+
active_plan(state)
|
| 275 |
+
state.robot_received = time.monotonic() - .4
|
| 276 |
+
monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=lambda *_a, **_k: (.08, 0.)))
|
| 277 |
+
def refresh():
|
| 278 |
+
state.robot_received = time.monotonic()
|
| 279 |
+
state.plan['input_received'] = time.monotonic()
|
| 280 |
+
fresh = threading.Timer(.075, refresh)
|
| 281 |
+
end = threading.Timer(.20, lambda: state.finish('End status gap simulation'))
|
| 282 |
+
fresh.start()
|
| 283 |
+
end.start()
|
| 284 |
+
module.control_loop(state)
|
| 285 |
+
fresh.join()
|
| 286 |
+
end.join()
|
| 287 |
+
commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
|
| 288 |
+
assert commands[0]['v'] == commands[0]['w'] == 0.
|
| 289 |
+
assert any(c['v'] > 0 for c in commands)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def test_sustained_robot_status_gap_stops_without_executing_a_path(monkeypatch, tmp_path):
|
| 293 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 294 |
+
active_plan(state)
|
| 295 |
+
state.args.plan_hold_seconds = .08
|
| 296 |
+
state.robot_received = time.monotonic() - .4
|
| 297 |
+
module.control_loop(state)
|
| 298 |
+
assert state.phase == 'stopped' and 'robot status stale' in state.reason
|
| 299 |
+
commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
|
| 300 |
+
assert commands and all(c['v'] == c['w'] == 0. for c in commands)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def test_pose_correction_racing_control_snapshot_cannot_execute_old_route(monkeypatch, tmp_path):
|
| 304 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 305 |
+
active_plan(state)
|
| 306 |
+
def corrected(*_a, **_k):
|
| 307 |
+
state.plan_epoch += 1
|
| 308 |
+
return .1, 0.
|
| 309 |
+
monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=corrected))
|
| 310 |
+
end = threading.Timer(.12, lambda: state.finish('End correction race'))
|
| 311 |
+
end.start()
|
| 312 |
+
module.control_loop(state)
|
| 313 |
+
end.join()
|
| 314 |
+
commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
|
| 315 |
+
assert commands and all(c['v'] == c['w'] == 0. for c in commands)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def test_corner_observation_sends_head_target_with_zero_base_translation(monkeypatch, tmp_path):
|
| 319 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 320 |
+
active_plan(state)
|
| 321 |
+
state.plan.update(observation_hold=True, head_target=[-1.2, -.4], scan_w=0., corner_phase='look')
|
| 322 |
+
end = threading.Timer(.12, lambda: state.finish('End head scan simulation'))
|
| 323 |
+
end.start()
|
| 324 |
+
module.control_loop(state)
|
| 325 |
+
end.join()
|
| 326 |
+
commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
|
| 327 |
+
assert commands and all(c['v'] == c['w'] == 0. and c['head_target'] == [-1.2, -.4] for c in commands)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def test_native_scan_is_rotation_only_even_if_pursuit_requests_translation(monkeypatch, tmp_path):
|
| 331 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 332 |
+
active_plan(state)
|
| 333 |
+
state.plan.update(planner_status=2, scan_authorized=True)
|
| 334 |
+
monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=lambda *_a, **_k: (.08, .1)))
|
| 335 |
+
end = threading.Timer(.12, lambda: state.finish('End native scan simulation'))
|
| 336 |
+
end.start()
|
| 337 |
+
module.control_loop(state)
|
| 338 |
+
end.join()
|
| 339 |
+
commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
|
| 340 |
+
assert commands and all(c['v'] == 0. and c['w'] == .1 for c in commands)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def test_learned_veto_does_not_block_stationary_yaw_pitch_survey(monkeypatch, tmp_path):
|
| 344 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 345 |
+
active_plan(state)
|
| 346 |
+
monkeypatch.setattr(module, 'command_footprint_report', lambda *_a, **_k: {
|
| 347 |
+
'clear': False, 'reason': 'learned occupancy', 'cells': [], 'blocking_cell_count': 1})
|
| 348 |
+
state.plan.update(observation_hold=True, stationary_survey=True, head_target=[-.7, -1.05],
|
| 349 |
+
scan_w=0., corner_phase='survey', survey_label='right floor',
|
| 350 |
+
footprint_grid={'prob': np.ones((20, 20)), 'obs': np.ones((20, 20)), 'res': .05},
|
| 351 |
+
planning_base=np.eye(4))
|
| 352 |
+
end = threading.Timer(.12, lambda: state.finish('End yaw/pitch simulation'))
|
| 353 |
+
end.start()
|
| 354 |
+
module.control_loop(state)
|
| 355 |
+
end.join()
|
| 356 |
+
commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
|
| 357 |
+
assert commands and all(c['v'] == c['w'] == 0. and c['head_target'] == [-.7, -1.05] for c in commands)
|
| 358 |
+
assert state.last_control['learned_blocked']
|
| 359 |
+
assert state.last_control['reason'] == 'Head survey: right floor'
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def test_survey_transition_with_null_label_holds_then_accepts_fresh_head_target(monkeypatch, tmp_path):
|
| 363 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 364 |
+
active_plan(state)
|
| 365 |
+
# Mapping invalidates the driving plan before publishing its first survey
|
| 366 |
+
# view. The old plan contains an explicit null label and no head target.
|
| 367 |
+
state.plan.update(observation_hold=True, stationary_survey=True, head_target=None,
|
| 368 |
+
scan_w=0., survey_label=None)
|
| 369 |
+
ticks = [0]
|
| 370 |
+
|
| 371 |
+
def tick(_seconds):
|
| 372 |
+
ticks[0] += 1
|
| 373 |
+
if ticks[0] == 1:
|
| 374 |
+
state.plan = {**state.plan, 'survey_label': 'front floor', 'head_target': [-.05, -1.05]}
|
| 375 |
+
if ticks[0] >= 3:
|
| 376 |
+
state.done.set()
|
| 377 |
+
return state.done.is_set()
|
| 378 |
+
|
| 379 |
+
monkeypatch.setattr(state.done, 'wait', tick)
|
| 380 |
+
module.control_loop(state)
|
| 381 |
+
commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
|
| 382 |
+
assert ticks[0] == 3 and state.phase == 'active'
|
| 383 |
+
assert commands and all(c['v'] == c['w'] == 0. for c in commands)
|
| 384 |
+
assert 'head_target' not in commands[0]
|
| 385 |
+
assert commands[-1]['head_target'] == [-.05, -1.05]
|
| 386 |
+
assert state.last_control['reason'] == 'Head survey: front floor'
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def test_persistent_learned_veto_requests_observation_without_executing_path(monkeypatch, tmp_path):
|
| 390 |
+
module, state, context = setup(monkeypatch, tmp_path)
|
| 391 |
+
active_plan(state)
|
| 392 |
+
monkeypatch.setitem(sys.modules, 'cross_nav.policy.robot', SimpleNamespace(pure_pursuit=lambda *_a, **_k: (.08, 0.)))
|
| 393 |
+
clock = [time.monotonic()]
|
| 394 |
+
monkeypatch.setattr(module.time, 'monotonic', lambda: clock[0])
|
| 395 |
+
state.plan.update(footprint_grid={'prob': np.ones((20, 20)), 'obs': np.ones((20, 20)), 'res': .05},
|
| 396 |
+
planning_base=np.eye(4))
|
| 397 |
+
ticks = [0]
|
| 398 |
+
def tick(_seconds):
|
| 399 |
+
ticks[0] += 1
|
| 400 |
+
clock[0] += .1
|
| 401 |
+
state.heartbeat = state.robot_received = state.plan['input_received'] = clock[0]
|
| 402 |
+
if ticks[0] >= 15:
|
| 403 |
+
state.done.set()
|
| 404 |
+
return state.done.is_set()
|
| 405 |
+
monkeypatch.setattr(state.done, 'wait', tick)
|
| 406 |
+
module.control_loop(state)
|
| 407 |
+
commands = [c for socket in context.sockets for c in socket.sent if c['type'] == 'velocity']
|
| 408 |
+
assert commands and all(c['v'] == c['w'] == 0. for c in commands)
|
| 409 |
+
assert state.observation_requested and state.observation_reason == 'learned footprint'
|
| 410 |
+
assert state.last_control['footprint']['blocking_cell_count'] > 0
|
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)
|
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))
|
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)
|
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)
|
code/lite3_ROS/tests/test_stretch_nav_survey.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 = 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 test_stuck_forward_goal_gets_distinct_yaw_and_pitch_views_before_neutral_return():
|
| 48 |
+
survey = HeadSurvey()
|
| 49 |
+
assert survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "learned footprint")
|
| 50 |
+
targets = np.array([target for _, target in survey.targets])
|
| 51 |
+
assert targets[:, 0].min() < -0.6 and targets[:, 0].max() > 0.5
|
| 52 |
+
assert targets[:, 1].min() < -1.0
|
| 53 |
+
np.testing.assert_allclose(targets[-1], [0.0, -0.4])
|
| 54 |
+
_, result = complete_survey(survey)
|
| 55 |
+
assert result["survey_complete"] and result["hold"]
|
| 56 |
+
assert len(survey.views) == 6 and survey.snapshot()["settled_views"] == 6
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_duplicate_frames_or_moving_head_do_not_complete_a_view():
|
| 60 |
+
survey = HeadSurvey()
|
| 61 |
+
survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "blocked")
|
| 62 |
+
target = survey.targets[0][1]
|
| 63 |
+
for now in [0.0, 0.5, 1.0, 1.5]:
|
| 64 |
+
survey.update(np.eye(4), camera(*target), joints(*target), 1, now)
|
| 65 |
+
assert survey.index == 0
|
| 66 |
+
for frame, tilt in enumerate([-0.6, -0.8, -1.0], 2):
|
| 67 |
+
survey.update(np.eye(4), camera(tilt=tilt), joints(tilt=tilt), frame, 2.0 + frame / 10)
|
| 68 |
+
assert survey.index == 0
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_joint_reaching_without_settled_camera_tf_does_not_count():
|
| 72 |
+
survey = HeadSurvey()
|
| 73 |
+
survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "blocked")
|
| 74 |
+
target = survey.targets[0][1]
|
| 75 |
+
for frame in range(6):
|
| 76 |
+
survey.update(np.eye(4), camera(0.1 * frame, target[1]), joints(*target), frame, frame * 0.5)
|
| 77 |
+
assert not survey.views
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_settled_head_with_action_offset_counts_the_actual_image_time_extrinsic():
|
| 81 |
+
survey = HeadSurvey()
|
| 82 |
+
survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "blocked")
|
| 83 |
+
target = np.array(survey.targets[0][1])
|
| 84 |
+
# A successful hardware action can settle about three degrees short. The
|
| 85 |
+
# resulting view is useful, and its measured extrinsic must be retained.
|
| 86 |
+
actual = target + [0.04, 0.054]
|
| 87 |
+
actual_mount = camera(*actual)
|
| 88 |
+
for frame, now in enumerate([0.0, 0.25, 0.75]):
|
| 89 |
+
result = survey.update(np.eye(4), actual_mount, joints(*actual), frame, now)
|
| 90 |
+
assert result["hold"] and result["scan_w"] == 0.0
|
| 91 |
+
assert survey.index == 1 and len(survey.views) == 1
|
| 92 |
+
np.testing.assert_allclose(survey.views[0]["head_joints"], actual)
|
| 93 |
+
np.testing.assert_allclose(survey.views[0]["camera_in_base"], actual_mount)
|
| 94 |
+
assert not np.allclose(actual_mount, camera(*target))
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_stationary_camera_far_from_head_target_does_not_complete_a_view():
|
| 98 |
+
survey = HeadSurvey()
|
| 99 |
+
survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "blocked")
|
| 100 |
+
actual = np.array(survey.targets[0][1]) + [0.0, 0.08]
|
| 101 |
+
for frame in range(6):
|
| 102 |
+
survey.update(np.eye(4), camera(*actual), joints(*actual), frame, frame * 0.5)
|
| 103 |
+
assert survey.index == 0 and not survey.views
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def test_survey_is_bounded_and_only_progress_allows_more_passes():
|
| 107 |
+
survey = HeadSurvey()
|
| 108 |
+
for start in [0.0, 15.0]:
|
| 109 |
+
survey.start(np.eye(4), camera(), camera(), joints(), start, "blocked")
|
| 110 |
+
now, _ = complete_survey(survey, start)
|
| 111 |
+
assert not survey.start(np.eye(4), camera(), camera(), joints(), now, "blocked") # Cooldown.
|
| 112 |
+
with pytest.raises(RuntimeError, match="two passes"):
|
| 113 |
+
survey.start(np.eye(4), camera(), camera(), joints(), now + 4.0, "blocked")
|
| 114 |
+
base = np.eye(4)
|
| 115 |
+
base[0, 3] = 0.21
|
| 116 |
+
assert survey.start(base, camera(), camera(), joints(), now + 4.0, "blocked")
|
| 117 |
+
assert survey.passes == 1
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def test_survey_times_out_without_fresh_settled_frames():
|
| 121 |
+
survey = HeadSurvey()
|
| 122 |
+
survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "blocked")
|
| 123 |
+
with pytest.raises(RuntimeError, match="timed out"):
|
| 124 |
+
survey.update(np.eye(4), camera(), joints(), 1, 12.1)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def test_external_base_motion_aborts_stationary_survey():
|
| 128 |
+
survey = HeadSurvey()
|
| 129 |
+
survey.start(np.eye(4), camera(), camera(), joints(), 0.0, "blocked")
|
| 130 |
+
base = np.eye(4)
|
| 131 |
+
base[0, 3] = 0.1
|
| 132 |
+
with pytest.raises(RuntimeError, match="Base moved"):
|
| 133 |
+
survey.update(base, camera(), joints(), 1, 1.0)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def test_cancelled_downward_scan_restores_pitch_and_yaw_after_correction():
|
| 137 |
+
observer = CornerObserver()
|
| 138 |
+
observer.restore_neutral(np.eye(4), 1.0)
|
| 139 |
+
result = observer.update({"target": np.array([1.0, 0.0]), "corner": None}, np.eye(4),
|
| 140 |
+
camera(-0.7, -1.05), camera(), joints(-0.7, -1.05), empty_grid(), 1.1)
|
| 141 |
+
np.testing.assert_allclose(result["head_target"], [0.0, -0.4], atol=1e-10)
|
| 142 |
+
for i in range(3):
|
| 143 |
+
observer.update({"target": np.array([1.0, 0.0]), "corner": None}, np.eye(4),
|
| 144 |
+
camera(0.0, -1.05), camera(), joints(0.0, -1.05), empty_grid(), 1.2 + i)
|
| 145 |
+
assert observer.phase == "return" # Yaw is restored but pitch is still wrong.
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def test_camera_tf_compensation_holds_for_combined_pitch_and_yaw():
|
| 149 |
+
base = np.eye(4)
|
| 150 |
+
base[:2, 3] = [4.0, 2.0]
|
| 151 |
+
alignment = np.eye(4)
|
| 152 |
+
alignment[:2, 3] = [-2.0, 7.0]
|
| 153 |
+
for pan, tilt in [(0.0, -0.4), (0.55, -1.05), (-0.7, -1.05), (-0.7, -0.4)]:
|
| 154 |
+
actual = base @ camera(pan, tilt)
|
| 155 |
+
recovered = (alignment @ actual) @ np.linalg.inv(actual)
|
| 156 |
+
np.testing.assert_allclose(camera_in_base(actual, base), camera(pan, tilt), atol=1e-12)
|
| 157 |
+
np.testing.assert_allclose(recovered @ base @ camera(), alignment @ base @ camera(), atol=1e-12)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def test_depth_obstacles_survive_a_long_survey_and_its_return():
|
| 161 |
+
memory = MeasuredObstacleMemory()
|
| 162 |
+
obstacle = np.array([[0.3, 0.0], [0.3, 0.01], [0.3, -0.01]])
|
| 163 |
+
memory.update(obstacle, 0.0, [0.0, 0.0])
|
| 164 |
+
memory.observing(True, 1.0)
|
| 165 |
+
assert len(memory.update(np.empty((0, 2)), 35.0, [0.0, 0.0])) >= 3
|
| 166 |
+
memory.observing(False, 36.0)
|
| 167 |
+
assert len(memory.update(np.empty((0, 2)), 40.0, [0.0, 0.0])) >= 3
|
| 168 |
+
assert not len(memory.update(np.empty((0, 2)), 48.1, [0.0, 0.0]))
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def test_own_body_prediction_is_logged_without_locking_the_robot_in_place():
|
| 172 |
+
grid = empty_grid()
|
| 173 |
+
grid["prob"][100, 100] = 0.9
|
| 174 |
+
report = command_footprint_report(grid, np.eye(4), np.zeros(3), 0.1, 0.0)
|
| 175 |
+
assert report["clear"] and report["ignored_current_body_cell_count"] == 1
|
| 176 |
+
assert report["self_cells"][0]["probability"] == 0.9
|
| 177 |
+
unsupported = depth_support(report, np.empty((0, 2)))
|
| 178 |
+
assert unsupported["depth_supported_cells"] == 0
|
| 179 |
+
assert unsupported["self_cells"][0]["nearest_depth_return_m"] is None
|
| 180 |
+
assert rectangle_path_clear([[0.5, 0.0], [1.0, 0.0]], grid)
|
| 181 |
+
assert grid["prob"][100, 100] == 0.9 # Original prediction is not overwritten.
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def test_missing_depth_never_clears_a_prediction_in_newly_swept_space():
|
| 185 |
+
grid = empty_grid()
|
| 186 |
+
grid["prob"][94, 100] = 0.9 # 27.5 cm ahead, beyond the current body.
|
| 187 |
+
report = command_footprint_report(grid, np.eye(4), np.zeros(3), 0.1, 0.0)
|
| 188 |
+
unsupported = depth_support(report, np.empty((0, 2)))
|
| 189 |
+
assert not unsupported["clear"] and unsupported["depth_supported_cells"] == 0
|
| 190 |
+
assert not rectangle_path_clear([[0.5, 0.0]], grid)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_measured_depth_veto_is_preserved_at_the_existing_body_edge():
|
| 194 |
+
points = np.array([[0.215, 0.0], [0.215, 0.01], [0.215, -0.01]])
|
| 195 |
+
assert depth_veto(points, np.zeros(3), 0.1, 0.0)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def test_report_depth_support_uses_world_frame_and_preserves_guard_decision():
|
| 199 |
+
grid = empty_grid()
|
| 200 |
+
grid["prob"][93, 100] = 0.95
|
| 201 |
+
base = np.eye(4)
|
| 202 |
+
base[:2, 3] = [4.0, 7.0]
|
| 203 |
+
report = command_footprint_report(grid, base, [4.0, 7.0, 0.0], 0.15, 0.0)
|
| 204 |
+
assert not report["clear"] and report["sweep_time_s"] > 0.0
|
| 205 |
+
point = report["cells"][0]["world_xy"]
|
| 206 |
+
result = depth_support(report, np.tile(point, (3, 1)))
|
| 207 |
+
assert result["depth_supported_cells"] == 1
|
| 208 |
+
assert result["cells"][0]["nearby_depth_returns"] == 3
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def test_unknown_predictions_do_not_become_learned_obstacles():
|
| 212 |
+
grid = empty_grid()
|
| 213 |
+
grid["prob"][:] = 1.0
|
| 214 |
+
grid["obs"][:] = 0.0
|
| 215 |
+
assert command_footprint_report(grid, np.eye(4), np.zeros(3), 0.1, 0.0)["clear"]
|
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'
|
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()
|
code/lite3_ROS/web_console/__init__.py
ADDED
|
File without changes
|
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()
|
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}}
|
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>
|
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);
|
code/lite3_ROS/web_console/static/vendor/plotly.min.js
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
code/lite3_ROS/web_console/stretch_nav_control.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 9 |
+
def wrap(angle):
|
| 10 |
+
return math.atan2(math.sin(angle), math.cos(angle))
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def alignment_correction(previous, current, base):
|
| 14 |
+
"""Map-pose correction at the current base, independent of the odom origin.
|
| 15 |
+
|
| 16 |
+
Alignment translations describe the coordinate origin. A small rotation
|
| 17 |
+
about a distant robot can move that origin substantially without moving
|
| 18 |
+
the estimated robot position. Compare both alignments at the same base.
|
| 19 |
+
"""
|
| 20 |
+
previous, current, base = [np.asarray(value, dtype=float) for value in (previous, current, base)]
|
| 21 |
+
if any(value.shape != (4, 4) or not np.isfinite(value).all() for value in (previous, current, base)):
|
| 22 |
+
raise ValueError('Invalid map alignment or base transform')
|
| 23 |
+
before, after = previous @ base, current @ base
|
| 24 |
+
distance = float(np.linalg.norm(after[:3, 3] - before[:3, 3]))
|
| 25 |
+
rotation = previous[:3, :3].T @ current[:3, :3]
|
| 26 |
+
angle = float(np.arccos(np.clip((np.trace(rotation) - 1.) / 2., -1., 1.)))
|
| 27 |
+
return distance, angle
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def execution_gate(plan, robot, *, now, robot_received, heartbeat, state='active', max_plan_age=1.2):
|
| 31 |
+
"""Require fresh planning evidence and CROSS's stable map commitment.
|
| 32 |
+
|
| 33 |
+
CROSS carries its committed pose through map-match gaps using odometry.
|
| 34 |
+
Retrieval verification is diagnostic, not a separate execution deadline.
|
| 35 |
+
The PC plan-age gate starts at receipt. Independently, the robot lease
|
| 36 |
+
validates full source-image age, including transport and compute time.
|
| 37 |
+
"""
|
| 38 |
+
if state not in ('preparing', 'active'):
|
| 39 |
+
return 'teleop owns control'
|
| 40 |
+
if now - heartbeat > 2.:
|
| 41 |
+
return 'viewer heartbeat expired'
|
| 42 |
+
if robot is None or now - robot_received > .3:
|
| 43 |
+
return 'robot status stale'
|
| 44 |
+
if robot.get('is_runstopped') is not False or robot.get('is_homed') is not True:
|
| 45 |
+
return 'robot run-stopped or unhomed'
|
| 46 |
+
if not robot.get('posture_ok'):
|
| 47 |
+
return 'arm must already be retracted'
|
| 48 |
+
if robot.get('latched'):
|
| 49 |
+
return 'robot stop latched'
|
| 50 |
+
if robot.get('head_error'):
|
| 51 |
+
return 'head observation fault: ' + str(robot['head_error'])
|
| 52 |
+
if state == 'active' and not robot.get('healthy'):
|
| 53 |
+
return 'robot state/camera/TF unavailable'
|
| 54 |
+
if plan is None or now - plan['input_received'] > max_plan_age:
|
| 55 |
+
return 'sensor/plan evidence stale'
|
| 56 |
+
if not np.isfinite([plan['input_received'], plan.get('goal_distance', math.nan)]).all():
|
| 57 |
+
return 'invalid plan timing or goal'
|
| 58 |
+
if not plan.get('localized') or plan.get('localized_streak', 0) < 3:
|
| 59 |
+
return 'waiting for stable committed localization'
|
| 60 |
+
if plan.get('recovery_pending'):
|
| 61 |
+
return 'map correction recovery'
|
| 62 |
+
if not plan.get('route_ids'):
|
| 63 |
+
return 'no global route'
|
| 64 |
+
if plan.get('arrived'):
|
| 65 |
+
return 'goal reached'
|
| 66 |
+
if plan.get('observation_hold'):
|
| 67 |
+
if plan.get('head_target') is not None and robot.get('head_enabled') is not True:
|
| 68 |
+
return 'leased head control unavailable'
|
| 69 |
+
return ''
|
| 70 |
+
if plan.get('planner_status') == 2 and plan.get('scan_authorized'):
|
| 71 |
+
return ''
|
| 72 |
+
if plan.get('planner_status') == 2 or len(plan.get('path_odom', [])) < 2:
|
| 73 |
+
return 'no executable local path'
|
| 74 |
+
return ''
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@dataclass
|
| 78 |
+
class PlanWait:
|
| 79 |
+
"""Hold at zero through a short perception gap, without re-arming the lease.
|
| 80 |
+
|
| 81 |
+
Physical faults and lost localization never qualify for a transient hold.
|
| 82 |
+
A brief missing status stream also permits only zero velocity. An active
|
| 83 |
+
run can continue only after fresh robot status and its current plan pass
|
| 84 |
+
the full gate again. Sustained gaps end the run.
|
| 85 |
+
"""
|
| 86 |
+
timeout: float = 3.
|
| 87 |
+
since: float | None = None
|
| 88 |
+
|
| 89 |
+
def holds(self, reason, now):
|
| 90 |
+
if reason not in ('sensor/plan evidence stale', 'no executable local path', 'robot status stale'):
|
| 91 |
+
self.since = None
|
| 92 |
+
return False
|
| 93 |
+
if self.since is None:
|
| 94 |
+
self.since = now
|
| 95 |
+
return now - self.since < self.timeout
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def competing_controllers(proc_root='/proc'):
|
| 99 |
+
"""Identify known local base clients that publish even while their keys are up."""
|
| 100 |
+
found = []
|
| 101 |
+
for entry in Path(proc_root).iterdir():
|
| 102 |
+
if not entry.name.isdecimal():
|
| 103 |
+
continue
|
| 104 |
+
try:
|
| 105 |
+
args = (entry / 'cmdline').read_bytes().split(b'\0')
|
| 106 |
+
words = [a.decode(errors='replace') for a in args if a]
|
| 107 |
+
except (OSError, PermissionError):
|
| 108 |
+
continue
|
| 109 |
+
if not words or not Path(words[0]).name.startswith('python'):
|
| 110 |
+
continue
|
| 111 |
+
for word in words[1:]:
|
| 112 |
+
if Path(word).name in ('teleop.py', 'manual_teleop.py', 'depth_nav_live.py') or word == 'stretch.app.manual_teleop':
|
| 113 |
+
found.append({'pid': int(entry.name), 'client': Path(word).name})
|
| 114 |
+
break
|
| 115 |
+
return found
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def remaining_path(path_world, pose):
|
| 119 |
+
"""Trim a saved odom path at the nearest segment and return forward/left."""
|
| 120 |
+
points = np.asarray(path_world, dtype=float).reshape(-1, 2)
|
| 121 |
+
pose = np.asarray(pose, dtype=float)
|
| 122 |
+
if len(points) < 2 or not np.isfinite(points).all() or not np.isfinite(pose).all():
|
| 123 |
+
return np.empty((0, 2))
|
| 124 |
+
delta = np.diff(points, axis=0)
|
| 125 |
+
t = np.clip(np.sum((pose[:2] - points[:-1]) * delta, axis=1)
|
| 126 |
+
/ np.maximum(np.sum(delta ** 2, axis=1), 1e-9), 0., 1.)
|
| 127 |
+
projected = points[:-1] + t[:, None] * delta
|
| 128 |
+
k = int(np.argmin(np.linalg.norm(projected - pose[:2], axis=1)))
|
| 129 |
+
ahead = np.vstack([projected[k], points[k + 1:]]) - pose[:2]
|
| 130 |
+
c, s = np.cos(pose[2]), np.sin(pose[2])
|
| 131 |
+
return ahead @ np.array([[c, -s], [s, c]])
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def depth_obstacles(depth, K, camera, base_z=0.):
|
| 135 |
+
"""Current measured returns for a short-horizon veto, separate from CROSS planning."""
|
| 136 |
+
depth, K, camera = map(np.asarray, (depth, K, camera))
|
| 137 |
+
vv, uu = np.mgrid[0:depth.shape[0]:3, 0:depth.shape[1]:3]
|
| 138 |
+
z = depth[::3, ::3]
|
| 139 |
+
valid = np.isfinite(z) & (z > .12) & (z < 3.)
|
| 140 |
+
if valid.sum() < 100:
|
| 141 |
+
raise ValueError('insufficient measured depth for execution guard')
|
| 142 |
+
z, uu, vv = z[valid], uu[valid], vv[valid]
|
| 143 |
+
pc = np.column_stack([(uu - K[0, 2]) * z / K[0, 0],
|
| 144 |
+
(vv - K[1, 2]) * z / K[1, 1], z])
|
| 145 |
+
world = pc @ camera[:3, :3].T + camera[:3, 3]
|
| 146 |
+
return world[(world[:, 2] > base_z + .12) & (world[:, 2] < base_z + 1.8), :2]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def depth_veto(points_world, pose, v, w, *, horizon=1., half_width=.23, half_length=.23):
|
| 150 |
+
"""Veto a 1 s swept rectangle when measured points intersect it.
|
| 151 |
+
|
| 152 |
+
The starting footprint is excluded as a robot self mask. This is a veto of
|
| 153 |
+
known returns, not evidence that unobserved near-field space is free.
|
| 154 |
+
"""
|
| 155 |
+
points, pose = np.asarray(points_world), np.asarray(pose)
|
| 156 |
+
c, s = np.cos(pose[2]), np.sin(pose[2])
|
| 157 |
+
local = (points - pose[:2]) @ np.array([[c, -s], [s, c]])
|
| 158 |
+
local = local[(np.abs(local[:, 0]) > .20) | (np.abs(local[:, 1]) > .20)]
|
| 159 |
+
for t in np.linspace(0., horizon, 16):
|
| 160 |
+
theta = w * t
|
| 161 |
+
center = np.array([v * t, 0.]) if abs(w) < 1e-6 else np.array([
|
| 162 |
+
v / w * np.sin(theta), v / w * (1. - np.cos(theta))])
|
| 163 |
+
c, s = np.cos(theta), np.sin(theta)
|
| 164 |
+
relative = (local - center) @ np.array([[c, -s], [s, c]])
|
| 165 |
+
inside = (np.abs(relative[:, 0]) <= half_length) & (np.abs(relative[:, 1]) <= half_width)
|
| 166 |
+
if inside.sum() >= 3:
|
| 167 |
+
return True
|
| 168 |
+
return False
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def attachment_clear(points_world, pose, target_xy):
|
| 172 |
+
"""Reject a straight local attachment intersecting measured obstacle returns.
|
| 173 |
+
|
| 174 |
+
Use the execution guard's footprint and robot self mask. Unknown space is
|
| 175 |
+
left to the native local planner; this check only vetoes measured returns.
|
| 176 |
+
"""
|
| 177 |
+
points, pose, target = map(np.asarray, (points_world, pose, target_xy))
|
| 178 |
+
if not all(np.isfinite(value).all() for value in (points, pose, target)):
|
| 179 |
+
raise ValueError('Invalid attachment geometry')
|
| 180 |
+
c, s = np.cos(pose[2]), np.sin(pose[2])
|
| 181 |
+
rotation = np.array([[c, -s], [s, c]])
|
| 182 |
+
local = (points - pose[:2]) @ rotation
|
| 183 |
+
local = local[(np.abs(local[:, 0]) > .20) | (np.abs(local[:, 1]) > .20)]
|
| 184 |
+
end = (target - pose[:2]) @ rotation
|
| 185 |
+
steps = max(2, int(np.ceil(np.linalg.norm(end) / .025)) + 1)
|
| 186 |
+
for fraction in np.linspace(0., 1., steps):
|
| 187 |
+
relative = local - fraction * end
|
| 188 |
+
inside = (np.abs(relative[:, 0]) <= .23) & (np.abs(relative[:, 1]) <= .23)
|
| 189 |
+
if inside.sum() >= 3:
|
| 190 |
+
return False
|
| 191 |
+
return True
|
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"}
|
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()
|
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()
|
code/lite3_ROS/web_console/stretch_nav_recovery.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 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 > 18.0:
|
| 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 |
+
speed_scale=0.5,
|
| 294 |
+
lookahead=0.22,
|
| 295 |
+
target=self.approach,
|
| 296 |
+
)
|
| 297 |
+
# Head first. Base rotation is allowed only after the limited head
|
| 298 |
+
# position is reached; the independent footprint veto still applies.
|
| 299 |
+
if abs(pan - clamped) > 0.10 and abs(joint[9] - clamped) < 0.08:
|
| 300 |
+
result["scan_w"] = math.copysign(0.15, error)
|
| 301 |
+
settled = (
|
| 302 |
+
self.previous_mount is not None and np.linalg.norm(mount[:3, 3] - self.previous_mount[:3, 3]) < 0.005
|
| 303 |
+
)
|
| 304 |
+
if settled:
|
| 305 |
+
_, moved = alignment_correction(self.previous_mount, mount, np.eye(4))
|
| 306 |
+
settled = moved < math.radians(1)
|
| 307 |
+
self.previous_mount = mount.copy()
|
| 308 |
+
pitch_ready = self.phase != "return" or abs(camera_pitch(neutral) - camera_pitch(mount)) < math.radians(4)
|
| 309 |
+
self.count = self.count + 1 if settled and abs(error) < math.radians(6) and pitch_ready else 0
|
| 310 |
+
if self.phase == "look" and self.count:
|
| 311 |
+
self.view_coverages.append(observed_branch(grid, base, self.corner, self.outgoing))
|
| 312 |
+
self.view_coverages = self.view_coverages[-2:]
|
| 313 |
+
self.coverage = min(self.view_coverages)
|
| 314 |
+
if self.count >= 2:
|
| 315 |
+
if self.phase == "look":
|
| 316 |
+
self.phase, self.count, self.since = "return", 0, now
|
| 317 |
+
elif self.scan_only:
|
| 318 |
+
self.phase, self.scan_cooldown = "cruise", now + 12.0
|
| 319 |
+
elif self.coverage >= 0.5:
|
| 320 |
+
self.phase, self.done_at = "advance", origin.copy()
|
| 321 |
+
elif self.peeks < 2 and np.linalg.norm(self.corner - origin) > 0.14:
|
| 322 |
+
# A closer, short approach followed by another stationary
|
| 323 |
+
# look. Native planning + rectangle checks must clear it.
|
| 324 |
+
self.approach = origin + 0.12 * (self.corner - origin) / np.linalg.norm(self.corner - origin)
|
| 325 |
+
self.peeks += 1
|
| 326 |
+
self.phase = "approach"
|
| 327 |
+
else:
|
| 328 |
+
raise RuntimeError("Corner remains occluded after bounded peeks; reposition required")
|
| 329 |
+
self.previous_mount = None
|
| 330 |
+
result["coverage"] = self.coverage
|
| 331 |
+
return result
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def rectangle_command_clear(grid, planning_base, pose, v, w, horizon=1.0):
|
| 335 |
+
"""Actual 1 s swept square, including pure rotation, in the learned grid."""
|
| 336 |
+
from .stretch_nav_footprint import command_footprint_report
|
| 337 |
+
|
| 338 |
+
return command_footprint_report(grid, planning_base, pose, v, w, horizon, max_cells=0)["clear"]
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def rectangle_path_clear(path, grid, half_width=0.23, half_length=0.23, horizon=1.2):
|
| 342 |
+
"""Check an oriented swept body against observed learned occupancy.
|
| 343 |
+
|
| 344 |
+
Unknown is not relabelled free here. The native visibility planner handles
|
| 345 |
+
observation requests, while measured depth remains a separate hard veto.
|
| 346 |
+
"""
|
| 347 |
+
path = np.vstack([[0.0, 0.0], np.asarray(path, float).reshape(-1, 2)])
|
| 348 |
+
if not np.isfinite(path).all():
|
| 349 |
+
return False
|
| 350 |
+
offsets = (
|
| 351 |
+
np.array(np.meshgrid(np.linspace(-half_length, half_length, 11), np.linspace(-half_width, half_width, 11)))
|
| 352 |
+
.reshape(2, -1)
|
| 353 |
+
.T
|
| 354 |
+
)
|
| 355 |
+
travelled, heading = 0.0, 0.0
|
| 356 |
+
n, res = len(grid["prob"]), grid["res"]
|
| 357 |
+
# Match native cross_nav: the robot already occupies this area. Keep the
|
| 358 |
+
# original prediction intact for diagnostics and for all newly swept cells.
|
| 359 |
+
probability = np.asarray(grid["prob"]).copy()
|
| 360 |
+
axis = (n / 2 - np.arange(n) - 0.5) * res
|
| 361 |
+
probability[(np.abs(axis[:, None]) <= half_length) & (np.abs(axis[None, :]) <= half_width)] = 0.0
|
| 362 |
+
for a, b in zip(path[:-1], path[1:]):
|
| 363 |
+
d = float(np.linalg.norm(b - a))
|
| 364 |
+
if d < 1e-5:
|
| 365 |
+
continue
|
| 366 |
+
yaw = math.atan2(*(b - a)[::-1])
|
| 367 |
+
for angle in np.linspace(heading, heading + wrap(yaw - heading), 8):
|
| 368 |
+
c, s = math.cos(angle), math.sin(angle)
|
| 369 |
+
points = offsets @ np.array([[c, s], [-s, c]]) + a
|
| 370 |
+
rc = np.floor(n / 2 - points / res).astype(int)
|
| 371 |
+
inside = ((rc >= 0) & (rc < n)).all(1)
|
| 372 |
+
if (
|
| 373 |
+
not inside.all()
|
| 374 |
+
or ((probability[rc[:, 0], rc[:, 1]] > 0.6) & (grid["obs"][rc[:, 0], rc[:, 1]] > 0.5)).any()
|
| 375 |
+
):
|
| 376 |
+
return False
|
| 377 |
+
count = max(2, int(d / 0.04) + 1)
|
| 378 |
+
for t in np.linspace(0.0, min(1.0, max(0.0, horizon - travelled) / d), count):
|
| 379 |
+
c, s = math.cos(yaw), math.sin(yaw)
|
| 380 |
+
points = offsets @ np.array([[c, s], [-s, c]]) + a + t * (b - a)
|
| 381 |
+
rc = np.floor(n / 2 - points / res).astype(int)
|
| 382 |
+
inside = ((rc >= 0) & (rc < n)).all(1)
|
| 383 |
+
if (
|
| 384 |
+
not inside.all()
|
| 385 |
+
or ((probability[rc[:, 0], rc[:, 1]] > 0.6) & (grid["obs"][rc[:, 0], rc[:, 1]] > 0.5)).any()
|
| 386 |
+
):
|
| 387 |
+
return False
|
| 388 |
+
travelled, heading = travelled + d, yaw
|
| 389 |
+
if travelled >= horizon:
|
| 390 |
+
break
|
| 391 |
+
return True
|
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]
|
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
|
code/lite3_ROS/web_console/stretch_nav_survey.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 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. No survey result requests base motion.
|
| 18 |
+
At most two passes are allowed until the base moves 20 cm; the enclosing
|
| 19 |
+
controller has an independent 90 s/100 degree recovery budget.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self):
|
| 23 |
+
self.active = False
|
| 24 |
+
self.origin = self.base = None
|
| 25 |
+
self.passes = self.index = 0
|
| 26 |
+
self.targets = []
|
| 27 |
+
self.views = []
|
| 28 |
+
self.started = self.since = self.next_allowed = 0.0
|
| 29 |
+
self.previous_mount = self.stable_since = None
|
| 30 |
+
self.last_frame = -1
|
| 31 |
+
self.count = 0
|
| 32 |
+
self.reason = ""
|
| 33 |
+
|
| 34 |
+
def cancel(self):
|
| 35 |
+
self.active = False
|
| 36 |
+
self.next_allowed = 0.0
|
| 37 |
+
|
| 38 |
+
def start(self, base, mount, neutral, joint, now, reason):
|
| 39 |
+
if self.active:
|
| 40 |
+
return False
|
| 41 |
+
joint = np.asarray(joint, float)
|
| 42 |
+
if joint.ndim != 1 or len(joint) < 11 or not np.isfinite(joint).all():
|
| 43 |
+
raise ValueError("Timestamped head joint feedback unavailable for survey")
|
| 44 |
+
base = np.asarray(base, float)
|
| 45 |
+
if self.origin is None or np.linalg.norm(base[:2, 3] - self.origin) > 0.2:
|
| 46 |
+
self.origin, self.passes = base[:2, 3].copy(), 0
|
| 47 |
+
if now < self.next_allowed:
|
| 48 |
+
return False
|
| 49 |
+
if self.passes >= 2:
|
| 50 |
+
raise RuntimeError("Head survey exhausted two passes without forward progress; footprint remains blocked")
|
| 51 |
+
pan = float(np.clip(joint[9] + wrap(camera_yaw(neutral) - camera_yaw(mount)), -2.8, 0.65))
|
| 52 |
+
tilt = float(np.clip(joint[10] + camera_pitch(neutral) - camera_pitch(mount), -1.4, 0.0))
|
| 53 |
+
# Look far enough down to inspect the otherwise hidden near floor.
|
| 54 |
+
down_pitch = max(-1.25, min(-1.05, camera_pitch(neutral) - 0.45))
|
| 55 |
+
down = float(np.clip(joint[10] + down_pitch - camera_pitch(mount), -1.4, 0.0))
|
| 56 |
+
left, right = min(0.65, pan + 0.55), max(-2.8, pan - 0.70)
|
| 57 |
+
self.targets = [
|
| 58 |
+
("front floor", [pan, down]),
|
| 59 |
+
("left floor", [left, down]),
|
| 60 |
+
("right floor", [right, down]),
|
| 61 |
+
("right surroundings", [right, tilt]),
|
| 62 |
+
("left surroundings", [left, tilt]),
|
| 63 |
+
("return to driving view", [pan, tilt]),
|
| 64 |
+
]
|
| 65 |
+
self.base = base.copy()
|
| 66 |
+
self.passes += 1
|
| 67 |
+
self.index, self.count, self.last_frame = 0, 0, -1
|
| 68 |
+
self.started = self.since = now
|
| 69 |
+
self.previous_mount = self.stable_since = None
|
| 70 |
+
self.views, self.reason, self.active = [], reason, True
|
| 71 |
+
return True
|
| 72 |
+
|
| 73 |
+
def snapshot(self):
|
| 74 |
+
return {
|
| 75 |
+
"active": self.active,
|
| 76 |
+
"pass": self.passes,
|
| 77 |
+
"view": min(self.index + 1, len(self.targets)),
|
| 78 |
+
"total": len(self.targets),
|
| 79 |
+
"label": self.targets[min(self.index, len(self.targets) - 1)][0] if self.targets else "idle",
|
| 80 |
+
"settled_views": len(self.views),
|
| 81 |
+
"reason": self.reason,
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
def update(self, base, mount, joint, frame, now):
|
| 85 |
+
if not self.active:
|
| 86 |
+
raise RuntimeError("No active head survey")
|
| 87 |
+
distance, angle = alignment_correction(self.base, base, np.eye(4))
|
| 88 |
+
if distance > 0.05 or angle > math.radians(5):
|
| 89 |
+
raise RuntimeError("Base moved during stationary head survey")
|
| 90 |
+
if now - self.started > 40.0 or now - self.since > 12.0:
|
| 91 |
+
raise RuntimeError("Head survey timed out waiting for settled camera observations")
|
| 92 |
+
joint = np.asarray(joint, float)
|
| 93 |
+
if len(joint) < 11 or not np.isfinite(joint).all():
|
| 94 |
+
raise ValueError("Timestamped head joint feedback unavailable for survey")
|
| 95 |
+
label, target = self.targets[self.index]
|
| 96 |
+
complete = False
|
| 97 |
+
if frame > self.last_frame:
|
| 98 |
+
# Successful hardware actions can settle a few degrees short of
|
| 99 |
+
# their targets. Use the same four-degree allowance as the corner
|
| 100 |
+
# pitch return; geometry uses the measured image-time camera TF.
|
| 101 |
+
reached = np.max(np.abs(joint[9:11] - target)) < HEAD_TARGET_TOLERANCE_RAD
|
| 102 |
+
settled = False
|
| 103 |
+
if self.previous_mount is not None:
|
| 104 |
+
moved, turned = alignment_correction(self.previous_mount, mount, np.eye(4))
|
| 105 |
+
settled = moved < 0.005 and turned < math.radians(1)
|
| 106 |
+
self.previous_mount, self.last_frame = np.asarray(mount).copy(), frame
|
| 107 |
+
if reached and settled:
|
| 108 |
+
self.count += 1
|
| 109 |
+
self.stable_since = now if self.stable_since is None else self.stable_since
|
| 110 |
+
else:
|
| 111 |
+
self.count, self.stable_since = 0, None
|
| 112 |
+
if self.count >= 2 and now - self.stable_since >= 0.4:
|
| 113 |
+
self.views.append({"label": label, "frame_idx": int(frame), "head_joints": joint[9:11].tolist(),
|
| 114 |
+
"camera_in_base": np.asarray(mount).tolist()})
|
| 115 |
+
self.index += 1
|
| 116 |
+
self.since, self.count = now, 0
|
| 117 |
+
self.stable_since = self.previous_mount = None
|
| 118 |
+
if self.index == len(self.targets):
|
| 119 |
+
self.active, complete, self.next_allowed = False, True, now + 3.0
|
| 120 |
+
return {
|
| 121 |
+
"phase": "survey_return" if label == "return to driving view" else "survey",
|
| 122 |
+
"target": self.base[:2, 3].copy(),
|
| 123 |
+
"hold": True,
|
| 124 |
+
"head_target": target,
|
| 125 |
+
"scan_w": 0.0,
|
| 126 |
+
"coverage": 0.0,
|
| 127 |
+
"speed_scale": 0.5,
|
| 128 |
+
"lookahead": 0.22,
|
| 129 |
+
"survey_complete": complete,
|
| 130 |
+
"survey_label": label,
|
| 131 |
+
}
|
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()
|
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
|
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()
|
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.
|
code/stretch_ai/scripts/capture_lingbot_rgbd_ros2.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Capture synchronized head RGB-D and TF without issuing robot commands.
|
| 3 |
+
|
| 4 |
+
Run inside the robot's ROS 2 environment. Images are saved losslessly, with
|
| 5 |
+
depth in metres, and rotated clockwise to match Stretch's upright head view.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import json
|
| 10 |
+
import time
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import cv2
|
| 14 |
+
import message_filters
|
| 15 |
+
import numpy as np
|
| 16 |
+
import rclpy
|
| 17 |
+
from cv_bridge import CvBridge
|
| 18 |
+
from rclpy.qos import qos_profile_sensor_data
|
| 19 |
+
from rclpy.time import Time
|
| 20 |
+
from sensor_msgs.msg import CameraInfo, Image
|
| 21 |
+
from tf2_ros import Buffer, TransformException, TransformListener
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def stamp_seconds(stamp):
|
| 25 |
+
return stamp.sec + stamp.nanosec * 1e-9
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def transform_matrix(transform):
|
| 29 |
+
q = transform.rotation
|
| 30 |
+
x, y, z, w = q.x, q.y, q.z, q.w
|
| 31 |
+
matrix = np.eye(4, dtype=np.float64)
|
| 32 |
+
matrix[:3, :3] = [
|
| 33 |
+
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
| 34 |
+
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
| 35 |
+
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
|
| 36 |
+
]
|
| 37 |
+
t = transform.translation
|
| 38 |
+
matrix[:3, 3] = [t.x, t.y, t.z]
|
| 39 |
+
return matrix
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def rotate_intrinsics_clockwise(k, height):
|
| 43 |
+
"""Rotate both the pixel axes and optical frame, including principal point."""
|
| 44 |
+
return np.array(
|
| 45 |
+
[[k[1, 1], 0, height - 1 - k[1, 2]], [0, k[0, 0], k[0, 2]], [0, 0, 1]],
|
| 46 |
+
dtype=np.float32,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def main():
|
| 51 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 52 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 53 |
+
parser.add_argument("--frames", type=int, default=12)
|
| 54 |
+
parser.add_argument("--interval", type=float, default=0.2)
|
| 55 |
+
parser.add_argument("--timeout", type=float, default=40)
|
| 56 |
+
parser.add_argument("--world-frame", default="map")
|
| 57 |
+
args = parser.parse_args()
|
| 58 |
+
args.output.mkdir(parents=True, exist_ok=False)
|
| 59 |
+
|
| 60 |
+
rclpy.init()
|
| 61 |
+
node = rclpy.create_node("lingbot_depth_readonly_capture")
|
| 62 |
+
bridge = CvBridge()
|
| 63 |
+
tf_buffer = Buffer()
|
| 64 |
+
listener = TransformListener(tf_buffer, node)
|
| 65 |
+
state = {"info": None, "pair": None}
|
| 66 |
+
info_sub = node.create_subscription(
|
| 67 |
+
CameraInfo,
|
| 68 |
+
"/camera/color/camera_info",
|
| 69 |
+
lambda msg: state.update(info=msg),
|
| 70 |
+
qos_profile_sensor_data,
|
| 71 |
+
)
|
| 72 |
+
color_sub = message_filters.Subscriber(
|
| 73 |
+
node, Image, "/camera/color/image_raw", qos_profile=qos_profile_sensor_data
|
| 74 |
+
)
|
| 75 |
+
depth_sub = message_filters.Subscriber(
|
| 76 |
+
node, Image, "/camera/aligned_depth_to_color/image_raw", qos_profile=qos_profile_sensor_data
|
| 77 |
+
)
|
| 78 |
+
sync = message_filters.ApproximateTimeSynchronizer(
|
| 79 |
+
[color_sub, depth_sub], queue_size=10, slop=0.02
|
| 80 |
+
)
|
| 81 |
+
sync.registerCallback(lambda color, depth: state.update(pair=(color, depth)))
|
| 82 |
+
# T_native_optical_from_upright_optical for a clockwise image rotation.
|
| 83 |
+
optical_rotation = np.eye(4)
|
| 84 |
+
optical_rotation[:3, :3] = [[0, 1, 0], [-1, 0, 0], [0, 0, 1]]
|
| 85 |
+
records = []
|
| 86 |
+
start = time.monotonic()
|
| 87 |
+
last_stamp = -float("inf")
|
| 88 |
+
last_error = "No synchronized image pair received"
|
| 89 |
+
try:
|
| 90 |
+
while len(records) < args.frames and time.monotonic() - start < args.timeout:
|
| 91 |
+
rclpy.spin_once(node, timeout_sec=0.1)
|
| 92 |
+
if state["info"] is None or state["pair"] is None:
|
| 93 |
+
continue
|
| 94 |
+
color_msg, depth_msg = state["pair"]
|
| 95 |
+
stamp = stamp_seconds(color_msg.header.stamp)
|
| 96 |
+
if stamp - last_stamp < args.interval:
|
| 97 |
+
continue
|
| 98 |
+
try:
|
| 99 |
+
pose_msg = tf_buffer.lookup_transform(
|
| 100 |
+
args.world_frame,
|
| 101 |
+
color_msg.header.frame_id,
|
| 102 |
+
Time.from_msg(color_msg.header.stamp),
|
| 103 |
+
)
|
| 104 |
+
robot_pose_msg = tf_buffer.lookup_transform(
|
| 105 |
+
args.world_frame, "base_link", Time.from_msg(color_msg.header.stamp)
|
| 106 |
+
)
|
| 107 |
+
except TransformException as exc:
|
| 108 |
+
last_error = str(exc)
|
| 109 |
+
continue
|
| 110 |
+
rgb_native = bridge.imgmsg_to_cv2(color_msg, desired_encoding="rgb8")
|
| 111 |
+
raw = bridge.imgmsg_to_cv2(depth_msg, desired_encoding="passthrough")
|
| 112 |
+
if depth_msg.encoding == "16UC1":
|
| 113 |
+
depth_native = raw.astype(np.float32) / 1000.0
|
| 114 |
+
elif depth_msg.encoding == "32FC1":
|
| 115 |
+
depth_native = raw.astype(np.float32)
|
| 116 |
+
else:
|
| 117 |
+
raise ValueError(f"Unsupported depth encoding: {depth_msg.encoding}")
|
| 118 |
+
if rgb_native.shape[:2] != depth_native.shape:
|
| 119 |
+
raise ValueError("Color and aligned depth dimensions differ")
|
| 120 |
+
info = state["info"]
|
| 121 |
+
k_native = np.array(info.k).reshape(3, 3)
|
| 122 |
+
k = rotate_intrinsics_clockwise(k_native, rgb_native.shape[0])
|
| 123 |
+
rgb = np.rot90(rgb_native, k=3).copy()
|
| 124 |
+
depth = np.rot90(depth_native, k=3).copy()
|
| 125 |
+
pose = transform_matrix(pose_msg.transform) @ optical_rotation
|
| 126 |
+
robot_pose = transform_matrix(robot_pose_msg.transform)
|
| 127 |
+
directory = args.output / f"frame_{len(records):03d}"
|
| 128 |
+
directory.mkdir()
|
| 129 |
+
if not cv2.imwrite(str(directory / "rgb.png"), cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)):
|
| 130 |
+
raise OSError("Could not write RGB image")
|
| 131 |
+
np.save(directory / "depth_input_m.npy", depth)
|
| 132 |
+
cv2.imwrite(
|
| 133 |
+
str(directory / "raw_depth.png"), np.nan_to_num(depth * 1000).astype(np.uint16)
|
| 134 |
+
)
|
| 135 |
+
np.savetxt(directory / "intrinsics.txt", k)
|
| 136 |
+
np.savetxt(directory / "camera_pose.txt", pose)
|
| 137 |
+
np.savetxt(directory / "robot_pose.txt", robot_pose)
|
| 138 |
+
record = {
|
| 139 |
+
"directory": directory.name,
|
| 140 |
+
"rgb_timestamp_s": stamp,
|
| 141 |
+
"depth_timestamp_s": stamp_seconds(depth_msg.header.stamp),
|
| 142 |
+
"sync_difference_s": abs(stamp - stamp_seconds(depth_msg.header.stamp)),
|
| 143 |
+
"tf_timestamp_s": stamp_seconds(pose_msg.header.stamp),
|
| 144 |
+
"source_optical_frame": color_msg.header.frame_id,
|
| 145 |
+
"world_frame": args.world_frame,
|
| 146 |
+
"image_rotation": "90 degrees clockwise",
|
| 147 |
+
"shape_hw": list(depth.shape),
|
| 148 |
+
"intrinsics_pixels": k.tolist(),
|
| 149 |
+
"intrinsics_native_pixels": k_native.tolist(),
|
| 150 |
+
"camera_pose_world_from_upright_optical": pose.tolist(),
|
| 151 |
+
"robot_pose_world_from_base_link": robot_pose.tolist(),
|
| 152 |
+
"distortion_native": list(info.d),
|
| 153 |
+
"distortion_model": info.distortion_model,
|
| 154 |
+
"rgb_encoding_source": color_msg.encoding,
|
| 155 |
+
"depth_encoding_source": depth_msg.encoding,
|
| 156 |
+
"depth_unit": "metres",
|
| 157 |
+
}
|
| 158 |
+
(directory / "metadata.json").write_text(json.dumps(record, indent=2) + "\n")
|
| 159 |
+
records.append(record)
|
| 160 |
+
last_stamp = stamp
|
| 161 |
+
print(
|
| 162 |
+
f"Captured {directory.name}: {depth.shape}, sync={record['sync_difference_s']:.6f}s",
|
| 163 |
+
flush=True,
|
| 164 |
+
)
|
| 165 |
+
(args.output / "capture.json").write_text(
|
| 166 |
+
json.dumps({"frames": records, "elapsed_s": time.monotonic() - start}, indent=2) + "\n"
|
| 167 |
+
)
|
| 168 |
+
if len(records) != args.frames:
|
| 169 |
+
raise TimeoutError(f"Captured {len(records)}/{args.frames}: {last_error}")
|
| 170 |
+
finally:
|
| 171 |
+
node.destroy_node()
|
| 172 |
+
rclpy.shutdown()
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
if __name__ == "__main__":
|
| 176 |
+
main()
|
code/stretch_ai/scripts/depth_nav_control.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CPU navigation controls and robot-local velocity leases; no ROS/model imports."""
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from bisect import bisect_left
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def wrap_angle(angle):
|
| 11 |
+
return math.atan2(math.sin(angle), math.cos(angle))
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def validated_head_target(command, enabled):
|
| 15 |
+
"""Validate optional leased observation; the depth stack leaves it off."""
|
| 16 |
+
target = command.get("head_target")
|
| 17 |
+
if target is None:
|
| 18 |
+
return None
|
| 19 |
+
if not enabled:
|
| 20 |
+
raise ValueError("head control disabled")
|
| 21 |
+
target = np.asarray(target, dtype=float)
|
| 22 |
+
if target.shape != (2,) or not np.isfinite(target).all():
|
| 23 |
+
raise ValueError("invalid head target")
|
| 24 |
+
if not -2.8 <= target[0] <= .65 or not -1.4 <= target[1] <= 0.:
|
| 25 |
+
raise ValueError("head target outside observation limits")
|
| 26 |
+
if float(command.get("v", math.inf)) != 0. or abs(float(command.get("w", math.inf))) > .15:
|
| 27 |
+
raise ValueError("head observation requires a stopped or slowly rotating base")
|
| 28 |
+
return target
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def interpolate_head(samples, stamp, max_gap=.10):
|
| 32 |
+
"""Head joint feedback at the RGB/TF time, never latest-state substitution."""
|
| 33 |
+
if not samples:
|
| 34 |
+
return None
|
| 35 |
+
stamps = [v[0] for v in samples]
|
| 36 |
+
k = bisect_left(stamps, stamp)
|
| 37 |
+
if k < len(samples) and abs(stamps[k] - stamp) < 1e-6:
|
| 38 |
+
return np.asarray(samples[k][1], float).copy()
|
| 39 |
+
if 0 < k < len(samples) and 0 < stamps[k] - stamps[k - 1] <= max_gap:
|
| 40 |
+
t = (stamp - stamps[k - 1]) / (stamps[k] - stamps[k - 1])
|
| 41 |
+
return (1. - t) * np.asarray(samples[k - 1][1]) + t * np.asarray(samples[k][1])
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class LeasedHeadController:
|
| 46 |
+
"""Asynchronous head action with explicit cancellation, including late ACKs.
|
| 47 |
+
|
| 48 |
+
The relay supplies a ROS goal factory; tests supply ordinary fake futures.
|
| 49 |
+
A failure remains visible until the session is restarted.
|
| 50 |
+
"""
|
| 51 |
+
def __init__(self, client, make_goal):
|
| 52 |
+
self.client, self.make_goal = client, make_goal
|
| 53 |
+
self.future = self.goal = self.result = None
|
| 54 |
+
self.sent = None
|
| 55 |
+
self.cancel_requested = False
|
| 56 |
+
self.cancel_sent = False
|
| 57 |
+
self.cancel_future = None
|
| 58 |
+
self.state, self.error = 'idle' if client is not None else 'disabled', ''
|
| 59 |
+
|
| 60 |
+
def _cancel(self):
|
| 61 |
+
self.cancel_requested = True
|
| 62 |
+
if self.goal is not None and not self.cancel_sent:
|
| 63 |
+
self.cancel_future = self.goal.cancel_goal_async()
|
| 64 |
+
self.cancel_sent, self.state = True, 'cancelling'
|
| 65 |
+
|
| 66 |
+
def update(self, target, joint, allowed):
|
| 67 |
+
target = None if target is None else np.asarray(target, float)
|
| 68 |
+
want = allowed and target is not None and not self.error
|
| 69 |
+
changed = want and self.sent is not None and np.max(np.abs(target - self.sent)) > .04
|
| 70 |
+
if not want or changed:
|
| 71 |
+
self._cancel()
|
| 72 |
+
if self.future is not None and self.future.done():
|
| 73 |
+
self.goal = self.future.result()
|
| 74 |
+
self.future = None
|
| 75 |
+
if self.goal is None or not self.goal.accepted:
|
| 76 |
+
self.error, self.state, self.goal = 'head trajectory rejected', 'failed', None
|
| 77 |
+
else:
|
| 78 |
+
self.result, self.state = self.goal.get_result_async(), 'moving'
|
| 79 |
+
if self.cancel_requested:
|
| 80 |
+
self._cancel()
|
| 81 |
+
if self.result is not None and self.result.done():
|
| 82 |
+
response = self.result.result()
|
| 83 |
+
if not self.cancel_requested and (response is None or response.result.error_code != 0):
|
| 84 |
+
detail = '' if response is None else f" ({response.result.error_code}): {getattr(response.result, 'error_string', '')}"
|
| 85 |
+
self.error, self.state = 'head trajectory failed' + detail, 'failed'
|
| 86 |
+
else:
|
| 87 |
+
self.state = 'cancelled' if self.cancel_requested else 'settled'
|
| 88 |
+
self.goal = self.result = None
|
| 89 |
+
if not want:
|
| 90 |
+
self.sent = None
|
| 91 |
+
elif not self.error and self.future is None and self.goal is None and (self.sent is None or changed):
|
| 92 |
+
if self.client is None or not self.client.server_is_ready():
|
| 93 |
+
self.error, self.state = 'head trajectory server unavailable', 'failed'
|
| 94 |
+
else:
|
| 95 |
+
# Tilt has a lower velocity bound than pan. A downward survey
|
| 96 |
+
# must allow that slower joint to reach its observation pose.
|
| 97 |
+
travel = np.abs(target - np.asarray(joint)[9:11]) / np.array([.35, .25])
|
| 98 |
+
duration = max(.5, float(np.max(travel)) + .5)
|
| 99 |
+
self.future = self.client.send_goal_async(self.make_goal(target, duration))
|
| 100 |
+
self.sent, self.cancel_requested, self.cancel_sent = target.copy(), False, False
|
| 101 |
+
self.state = 'requested'
|
| 102 |
+
|
| 103 |
+
def close(self):
|
| 104 |
+
self._cancel()
|
| 105 |
+
if self.future is not None:
|
| 106 |
+
def cancel_late(future):
|
| 107 |
+
handle = future.result()
|
| 108 |
+
if handle is not None and handle.accepted and not self.cancel_sent:
|
| 109 |
+
self.cancel_future = handle.cancel_goal_async()
|
| 110 |
+
self.cancel_sent = True
|
| 111 |
+
if self.future.done():
|
| 112 |
+
cancel_late(self.future)
|
| 113 |
+
else:
|
| 114 |
+
self.future.add_done_callback(cancel_late)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class HeadControlMode:
|
| 118 |
+
"""Yield the bridge's streaming controller for head-only ROS trajectories.
|
| 119 |
+
|
| 120 |
+
Only prepare() makes a request, after explicit navigation handoff. Restore
|
| 121 |
+
the original state on close, including a disable ACK racing shutdown.
|
| 122 |
+
"""
|
| 123 |
+
def __init__(self, disable, enable, request):
|
| 124 |
+
self.disable, self.enable, self.request = disable, enable, request
|
| 125 |
+
self.original = None
|
| 126 |
+
self.future = self.restore_future = None
|
| 127 |
+
self.owned = self.ready = self.closing = False
|
| 128 |
+
self.error = ''
|
| 129 |
+
|
| 130 |
+
def prepare(self, streaming):
|
| 131 |
+
if self.closing or self.error or streaming is None:
|
| 132 |
+
return False
|
| 133 |
+
if self.original is None:
|
| 134 |
+
self.original = bool(streaming)
|
| 135 |
+
if not self.original:
|
| 136 |
+
self.ready = streaming is False
|
| 137 |
+
return self.ready
|
| 138 |
+
if self.future is None and not self.owned:
|
| 139 |
+
if not self.disable.service_is_ready():
|
| 140 |
+
return False
|
| 141 |
+
self.future = self.disable.call_async(self.request())
|
| 142 |
+
if self.future is not None and self.future.done():
|
| 143 |
+
result = self.future.result()
|
| 144 |
+
self.future = None
|
| 145 |
+
if result is None or not result.success:
|
| 146 |
+
self.error = 'could not yield streaming head control'
|
| 147 |
+
return False
|
| 148 |
+
self.owned = True
|
| 149 |
+
self.ready = self.owned and streaming is False
|
| 150 |
+
return self.ready
|
| 151 |
+
|
| 152 |
+
def close(self):
|
| 153 |
+
self.closing = True
|
| 154 |
+
if self.original is not True or self.restore_future is not None:
|
| 155 |
+
return
|
| 156 |
+
def restore(_future=None):
|
| 157 |
+
if self.restore_future is None:
|
| 158 |
+
if not self.enable.service_is_ready():
|
| 159 |
+
self.error = 'could not restore streaming head control'
|
| 160 |
+
else:
|
| 161 |
+
self.restore_future = self.enable.call_async(self.request())
|
| 162 |
+
if self.future is not None and not self.future.done():
|
| 163 |
+
self.future.add_done_callback(restore)
|
| 164 |
+
elif self.owned or self.future is not None:
|
| 165 |
+
restore()
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def relative_goal_to_world(forward_left, pose):
|
| 169 |
+
"""Freeze a ROS body-frame (x forward, y left) goal in world XY."""
|
| 170 |
+
forward, left = np.asarray(forward_left, dtype=float)
|
| 171 |
+
x, y, yaw = np.asarray(pose, dtype=float)
|
| 172 |
+
if not np.isfinite([forward, left, x, y, yaw]).all():
|
| 173 |
+
raise ValueError("Goal and pose must be finite")
|
| 174 |
+
return np.array(
|
| 175 |
+
[
|
| 176 |
+
x + forward * math.cos(yaw) - left * math.sin(yaw),
|
| 177 |
+
y + forward * math.sin(yaw) + left * math.cos(yaw),
|
| 178 |
+
]
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def twist_rollout(pose, v, w, horizon, samples=24):
|
| 183 |
+
t = np.linspace(0, horizon, samples)
|
| 184 |
+
if abs(w) < 1e-6:
|
| 185 |
+
local = np.column_stack([v * t, np.zeros_like(t)])
|
| 186 |
+
else:
|
| 187 |
+
local = np.column_stack([v / w * np.sin(w * t), v / w * (1 - np.cos(w * t))])
|
| 188 |
+
c, s = math.cos(pose[2]), math.sin(pose[2])
|
| 189 |
+
return local @ np.array([[c, s], [-s, c]]) + pose[:2]
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def rollout_allowed(pose, v, w, grid, planning_pose, args):
|
| 193 |
+
from depth_only_path_planner import ego_to_cells, world_to_ego
|
| 194 |
+
from depth_nav_footprint import collisions_at
|
| 195 |
+
from depth_nav_trajectories import body_extent
|
| 196 |
+
|
| 197 |
+
samples = max(
|
| 198 |
+
24,
|
| 199 |
+
int(
|
| 200 |
+
np.ceil(
|
| 201 |
+
(abs(v) + body_extent(args) * abs(w))
|
| 202 |
+
* args.control_horizon
|
| 203 |
+
/ (args.grid_resolution / 4)
|
| 204 |
+
)
|
| 205 |
+
)
|
| 206 |
+
+ 1,
|
| 207 |
+
)
|
| 208 |
+
points = twist_rollout(pose, v, w, args.control_horizon, samples)
|
| 209 |
+
local = world_to_ego(points, planning_pose[:2], planning_pose[2])
|
| 210 |
+
rows, cols, inside = ego_to_cells(local, args, grid["blocked"].shape)
|
| 211 |
+
headings = pose[2] - planning_pose[2] + w * np.linspace(0, args.control_horizon, len(points))
|
| 212 |
+
if collisions_at(local, headings, grid, args).any():
|
| 213 |
+
return False, "command footprint intersects depth obstacles or map boundary"
|
| 214 |
+
if (
|
| 215 |
+
args.unknown_policy != "assume"
|
| 216 |
+
and (grid["unknown_footprint"][rows, cols] > args.max_control_unknown_ratio + 1e-6).any()
|
| 217 |
+
):
|
| 218 |
+
return False, "command footprint lacks observed floor support"
|
| 219 |
+
return True, "clear"
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def pursuit_velocity(path_world, pose, goal_world, args):
|
| 223 |
+
from depth_only_path_planner import world_to_ego
|
| 224 |
+
|
| 225 |
+
distance = float(np.linalg.norm(goal_world - pose[:2]))
|
| 226 |
+
if distance <= args.goal_tolerance:
|
| 227 |
+
return 0.0, 0.0
|
| 228 |
+
if not len(path_world):
|
| 229 |
+
return 0.0, 0.0
|
| 230 |
+
nearest = int(np.argmin(np.linalg.norm(path_world - pose[:2], axis=1)))
|
| 231 |
+
ahead = path_world[nearest:]
|
| 232 |
+
lengths = np.r_[0, np.cumsum(np.linalg.norm(np.diff(ahead, axis=0), axis=1))]
|
| 233 |
+
target = ahead[min(len(ahead) - 1, int(np.searchsorted(lengths, args.pursuit_lookahead)))]
|
| 234 |
+
right, forward = world_to_ego(target[None], pose[:2], pose[2])[0]
|
| 235 |
+
heading = math.atan2(-right, forward)
|
| 236 |
+
if abs(heading) > args.turn_in_place_angle or forward <= 0:
|
| 237 |
+
return 0.0, float(
|
| 238 |
+
np.clip(args.turn_gain * heading, -args.max_angular_speed, args.max_angular_speed)
|
| 239 |
+
)
|
| 240 |
+
curvature = -2 * right / max(right**2 + forward**2, 0.01)
|
| 241 |
+
v = min(args.max_linear_speed, max(0.0, distance - args.goal_tolerance) * 0.5)
|
| 242 |
+
if abs(curvature) > 1e-6:
|
| 243 |
+
v = min(v, args.max_angular_speed / abs(curvature))
|
| 244 |
+
return float(v), float(v * curvature)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def candidate_prefix_allowed(paths, grid, goal_distance, args):
|
| 248 |
+
"""Batch-check each candidate's first pursuit command without Python loops."""
|
| 249 |
+
from depth_only_path_planner import ego_to_cells
|
| 250 |
+
from depth_nav_footprint import collisions_at
|
| 251 |
+
|
| 252 |
+
lengths = np.cumsum(np.linalg.norm(np.diff(paths, axis=1), axis=-1), axis=1)
|
| 253 |
+
reaches = lengths >= args.pursuit_lookahead
|
| 254 |
+
index = np.where(reaches.any(axis=1), reaches.argmax(axis=1) + 1, paths.shape[1] - 1)
|
| 255 |
+
target = paths[np.arange(len(paths)), index]
|
| 256 |
+
right, forward = target[:, 0], target[:, 1]
|
| 257 |
+
heading = np.arctan2(-right, forward)
|
| 258 |
+
curvature = -2 * right / np.maximum(right**2 + forward**2, 0.01)
|
| 259 |
+
v = np.full(
|
| 260 |
+
len(paths), min(args.max_linear_speed, max(0.0, goal_distance - args.goal_tolerance) * 0.5)
|
| 261 |
+
)
|
| 262 |
+
v = np.minimum(v, args.max_angular_speed / np.maximum(np.abs(curvature), 1e-9))
|
| 263 |
+
turn = (np.abs(heading) > args.turn_in_place_angle) | (forward <= 0)
|
| 264 |
+
w = np.where(
|
| 265 |
+
turn,
|
| 266 |
+
np.clip(args.turn_gain * heading, -args.max_angular_speed, args.max_angular_speed),
|
| 267 |
+
v * curvature,
|
| 268 |
+
)
|
| 269 |
+
v[turn] = 0
|
| 270 |
+
t = np.linspace(0, args.control_horizon, 24)[None]
|
| 271 |
+
angle = w[:, None] * t
|
| 272 |
+
radius = v / np.where(np.abs(w) < 1e-6, 1.0, w)
|
| 273 |
+
rollout = np.stack(
|
| 274 |
+
[-radius[:, None] * (1 - np.cos(angle)), radius[:, None] * np.sin(angle)], axis=-1
|
| 275 |
+
)
|
| 276 |
+
straight = np.abs(w) < 1e-6
|
| 277 |
+
rollout[straight, :, 0] = 0
|
| 278 |
+
rollout[straight, :, 1] = v[straight, None] * t
|
| 279 |
+
rows, cols, inside = ego_to_cells(rollout, args, grid["blocked"].shape)
|
| 280 |
+
rr, cc = np.clip(rows, 0, grid["blocked"].shape[0] - 1), np.clip(
|
| 281 |
+
cols, 0, grid["blocked"].shape[1] - 1
|
| 282 |
+
)
|
| 283 |
+
invalid = collisions_at(rollout, angle, grid, args) | (
|
| 284 |
+
(grid["unknown_footprint"][rr, cc] > args.max_control_unknown_ratio + 1e-6)
|
| 285 |
+
& (args.unknown_policy != "assume")
|
| 286 |
+
)
|
| 287 |
+
return ~invalid.any(axis=1)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
@dataclass
|
| 291 |
+
class VelocityLease:
|
| 292 |
+
"""Fail closed on stale evidence/state, bad commands, expiry and latched stop."""
|
| 293 |
+
|
| 294 |
+
max_ttl: float = 0.35
|
| 295 |
+
max_frame_age: float = 0.8
|
| 296 |
+
max_v: float = 0.15
|
| 297 |
+
max_w: float = 0.4
|
| 298 |
+
session: str | None = None
|
| 299 |
+
armed: bool = False
|
| 300 |
+
latched: bool = False
|
| 301 |
+
sequence: int = -1
|
| 302 |
+
expires: float = -math.inf
|
| 303 |
+
evidence_expires: float = -math.inf
|
| 304 |
+
velocity: tuple = (0.0, 0.0)
|
| 305 |
+
reason: str = "unarmed"
|
| 306 |
+
|
| 307 |
+
def arm(self, session, healthy):
|
| 308 |
+
if self.latched or not healthy or not isinstance(session, str) or not session:
|
| 309 |
+
return False
|
| 310 |
+
if self.session is not None and self.session != session:
|
| 311 |
+
return False
|
| 312 |
+
self.session, self.armed = session, True
|
| 313 |
+
return True
|
| 314 |
+
|
| 315 |
+
def stop(self, reason, latch=False):
|
| 316 |
+
self.velocity = (0.0, 0.0)
|
| 317 |
+
self.expires = -math.inf
|
| 318 |
+
self.reason = reason
|
| 319 |
+
if latch:
|
| 320 |
+
self.latched, self.armed = True, False
|
| 321 |
+
|
| 322 |
+
def accept(self, command, now, frame_age, healthy):
|
| 323 |
+
if self.latched:
|
| 324 |
+
return False
|
| 325 |
+
try:
|
| 326 |
+
seq = int(command["seq"])
|
| 327 |
+
ttl, v, w = map(float, (command["ttl"], command["v"], command["w"]))
|
| 328 |
+
except (ValueError, TypeError, KeyError):
|
| 329 |
+
self.stop("malformed command")
|
| 330 |
+
return False
|
| 331 |
+
if (
|
| 332 |
+
self.latched
|
| 333 |
+
or not self.armed
|
| 334 |
+
or not healthy
|
| 335 |
+
or command.get("session") != self.session
|
| 336 |
+
or seq <= self.sequence
|
| 337 |
+
or not np.isfinite([ttl, v, w, frame_age]).all()
|
| 338 |
+
or not 0 < ttl <= self.max_ttl
|
| 339 |
+
or not 0 <= frame_age < self.max_frame_age
|
| 340 |
+
or not 0 <= v <= self.max_v
|
| 341 |
+
or abs(w) > self.max_w
|
| 342 |
+
):
|
| 343 |
+
self.stop("rejected command or stale evidence")
|
| 344 |
+
return False
|
| 345 |
+
self.sequence = seq
|
| 346 |
+
self.velocity = (v, w)
|
| 347 |
+
self.expires = now + ttl
|
| 348 |
+
self.evidence_expires = now + self.max_frame_age - frame_age
|
| 349 |
+
self.reason = "command active"
|
| 350 |
+
return True
|
| 351 |
+
|
| 352 |
+
def output(self, now, healthy, runstopped=False):
|
| 353 |
+
if runstopped and self.armed:
|
| 354 |
+
self.stop("run-stop latched; restart the live session", latch=True)
|
| 355 |
+
if self.latched:
|
| 356 |
+
return (0.0, 0.0)
|
| 357 |
+
if not healthy:
|
| 358 |
+
self.stop("state, camera or posture unavailable")
|
| 359 |
+
if now >= min(self.expires, self.evidence_expires):
|
| 360 |
+
self.stop(
|
| 361 |
+
"command/evidence expired" if self.armed and not self.latched else self.reason
|
| 362 |
+
)
|
| 363 |
+
return self.velocity if self.armed and not self.latched else (0.0, 0.0)
|
code/stretch_ai/scripts/depth_nav_debug.py
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bounded asynchronous debug recording; no robot, model or GPU operations."""
|
| 2 |
+
|
| 3 |
+
from collections import OrderedDict
|
| 4 |
+
from datetime import datetime, timezone
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import queue
|
| 9 |
+
import sys
|
| 10 |
+
import threading
|
| 11 |
+
import time
|
| 12 |
+
from types import SimpleNamespace
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def clean_json(value):
|
| 18 |
+
if isinstance(value, np.ndarray) and value.ndim == 0:
|
| 19 |
+
return clean_json(value.item())
|
| 20 |
+
if isinstance(value, dict):
|
| 21 |
+
return {str(k): clean_json(v) for k, v in value.items()}
|
| 22 |
+
if isinstance(value, (list, tuple, np.ndarray)):
|
| 23 |
+
return [clean_json(v) for v in value]
|
| 24 |
+
if isinstance(value, np.generic):
|
| 25 |
+
return clean_json(value.item())
|
| 26 |
+
if isinstance(value, float) and not np.isfinite(value):
|
| 27 |
+
return None
|
| 28 |
+
if isinstance(value, Path):
|
| 29 |
+
return str(value)
|
| 30 |
+
return value
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def freeze_voxels(snapshot, now):
|
| 34 |
+
names = (
|
| 35 |
+
"points",
|
| 36 |
+
"colors",
|
| 37 |
+
"state",
|
| 38 |
+
"keys",
|
| 39 |
+
"ids",
|
| 40 |
+
"scores",
|
| 41 |
+
"age_s",
|
| 42 |
+
"last_frame",
|
| 43 |
+
"evidence_frame",
|
| 44 |
+
"geometry_frame",
|
| 45 |
+
"geometry_support",
|
| 46 |
+
"last_hit_support",
|
| 47 |
+
"source_raw_depth_m",
|
| 48 |
+
"source_refined_depth_m",
|
| 49 |
+
)
|
| 50 |
+
result = {name: snapshot[name].copy() for name in names if name in snapshot}
|
| 51 |
+
for name in ("last_seen", "last_hit", "last_supported"):
|
| 52 |
+
if name in snapshot:
|
| 53 |
+
result[name + "_age_s"] = (now - snapshot[name]).astype(np.float32)
|
| 54 |
+
return result
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def current_view(point, arrays, args):
|
| 58 |
+
"""Explain why sparse projective clearing can/cannot remove a sample."""
|
| 59 |
+
if not all(
|
| 60 |
+
k in arrays
|
| 61 |
+
for k in ("camera_pose", "camera_K", "raw_depth_m", "refined_depth_m", "retained_mask")
|
| 62 |
+
):
|
| 63 |
+
return {"status": "not_recorded"}
|
| 64 |
+
pose, k = arrays["camera_pose"], arrays["camera_K"]
|
| 65 |
+
camera = (point - pose[:3, 3]) @ pose[:3, :3]
|
| 66 |
+
z = float(camera[2])
|
| 67 |
+
max_depth = getattr(args, "max_depth", 5.0) # Older runs used a 5 m limit.
|
| 68 |
+
if z <= 0.3:
|
| 69 |
+
return {"status": "behind_or_too_close_to_camera_for_clearing", "camera_z_m": z}
|
| 70 |
+
distance = float(np.linalg.norm(camera))
|
| 71 |
+
if z > max_depth:
|
| 72 |
+
return {
|
| 73 |
+
"status": "outside_clearing_depth_limit",
|
| 74 |
+
"camera_z_m": z,
|
| 75 |
+
"camera_distance_m": distance,
|
| 76 |
+
"depth_limit_m": max_depth,
|
| 77 |
+
}
|
| 78 |
+
u = int(np.rint(k[0, 0] * camera[0] / z + k[0, 2]))
|
| 79 |
+
v = int(np.rint(k[1, 1] * camera[1] / z + k[1, 2]))
|
| 80 |
+
h, w = arrays["raw_depth_m"].shape
|
| 81 |
+
if not (1 <= u < w - 1 and 1 <= v < h - 1):
|
| 82 |
+
return {"status": "outside_clearing_image_patch", "pixel_uv": [u, v], "camera_z_m": z}
|
| 83 |
+
raw = arrays["raw_depth_m"][v - 1 : v + 2, u - 1 : u + 2]
|
| 84 |
+
refined = arrays["refined_depth_m"][v - 1 : v + 2, u - 1 : u + 2]
|
| 85 |
+
from lingbot_voxel_map import VoxelMapConfig, clearing_patch_evidence
|
| 86 |
+
|
| 87 |
+
clear, valid, agreement, farther = clearing_patch_evidence(
|
| 88 |
+
raw.reshape(9),
|
| 89 |
+
refined.reshape(9),
|
| 90 |
+
z,
|
| 91 |
+
VoxelMapConfig(voxel_size=args.voxel_size, max_depth_m=max_depth),
|
| 92 |
+
)
|
| 93 |
+
status = (
|
| 94 |
+
"reliable_farther_patch"
|
| 95 |
+
if clear
|
| 96 |
+
else (
|
| 97 |
+
"occluded_or_same_depth"
|
| 98 |
+
if valid.all() and not farther.all()
|
| 99 |
+
else "missing_or_disagreeing_depth"
|
| 100 |
+
)
|
| 101 |
+
)
|
| 102 |
+
return {
|
| 103 |
+
"status": status,
|
| 104 |
+
"pixel_uv": [u, v],
|
| 105 |
+
"camera_z_m": z,
|
| 106 |
+
"camera_distance_m": distance,
|
| 107 |
+
"depth_limit_kind": "optical_axis",
|
| 108 |
+
"raw_depth_m": float(raw[1, 1]),
|
| 109 |
+
"refined_depth_m": float(refined[1, 1]),
|
| 110 |
+
"valid_patch_fraction": float(valid.mean()),
|
| 111 |
+
"farther_patch_fraction": float(farther.mean()),
|
| 112 |
+
"agreement_patch_fraction": float(agreement.mean()),
|
| 113 |
+
"retained_patch_fraction": float(
|
| 114 |
+
arrays["retained_mask"][v - 1 : v + 2, u - 1 : u + 2].mean()
|
| 115 |
+
),
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def collision_report(context, trigger):
|
| 120 |
+
from depth_nav_footprint import collisions_at, footprint_witnesses
|
| 121 |
+
from depth_nav_control import twist_rollout
|
| 122 |
+
from depth_nav_trajectories import body_extent
|
| 123 |
+
from depth_only_path_planner import (
|
| 124 |
+
ego_to_cells,
|
| 125 |
+
ego_to_world,
|
| 126 |
+
world_to_ego,
|
| 127 |
+
obstacle_height_mask,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
arrays, meta = context["arrays"], context["metadata"]
|
| 131 |
+
if "voxel_points" not in arrays or "hard_source" not in arrays:
|
| 132 |
+
return {
|
| 133 |
+
"stage": meta.get("stage", "unknown"),
|
| 134 |
+
"note": "Frame did not reach mapping/planning",
|
| 135 |
+
}
|
| 136 |
+
args = SimpleNamespace(**meta["settings"])
|
| 137 |
+
planning_pose = arrays["planning_pose"]
|
| 138 |
+
control = trigger.get("control", {})
|
| 139 |
+
pose = np.asarray(control.get("robot_pose") or planning_pose.tolist(), dtype=float)
|
| 140 |
+
if pose.shape != (3,) or not np.isfinite(pose).all():
|
| 141 |
+
pose = planning_pose
|
| 142 |
+
v, w = float(control.get("proposed_v", 0)), float(control.get("proposed_w", 0))
|
| 143 |
+
samples = max(
|
| 144 |
+
24,
|
| 145 |
+
int(
|
| 146 |
+
np.ceil(
|
| 147 |
+
(abs(v) + body_extent(args) * abs(w))
|
| 148 |
+
* args.control_horizon
|
| 149 |
+
/ (args.grid_resolution / 4)
|
| 150 |
+
)
|
| 151 |
+
)
|
| 152 |
+
+ 1,
|
| 153 |
+
)
|
| 154 |
+
world = twist_rollout(pose, v, w, args.control_horizon, samples)
|
| 155 |
+
points = world_to_ego(world, planning_pose[:2], planning_pose[2])
|
| 156 |
+
headings = pose[2] - planning_pose[2] + w * np.linspace(0, args.control_horizon, samples)
|
| 157 |
+
grid = {key: arrays[key] for key in ("hard_source", "blocked", "unknown_footprint")}
|
| 158 |
+
grid.update(direct_footprint=True, collision_cache={})
|
| 159 |
+
for key in ("collision_cells", "collision_cell_size", "collision_cell_angle"):
|
| 160 |
+
if key in arrays:
|
| 161 |
+
grid[key] = arrays[key] if key == "collision_cells" else float(arrays[key])
|
| 162 |
+
collides = collisions_at(points, headings, grid, args)
|
| 163 |
+
first = int(np.flatnonzero(collides)[0]) if collides.any() else 0
|
| 164 |
+
contacts, boundary = footprint_witnesses(points[first], headings[first], grid, args)
|
| 165 |
+
report = {
|
| 166 |
+
"command_first_collision_s": (
|
| 167 |
+
None
|
| 168 |
+
if not collides.any()
|
| 169 |
+
else float(np.linspace(0, args.control_horizon, samples)[first])
|
| 170 |
+
),
|
| 171 |
+
"map_boundary_contact": boundary,
|
| 172 |
+
"collision_cell_count": len(contacts),
|
| 173 |
+
"contact_cells_ego": contacts[:16].tolist(),
|
| 174 |
+
"contact_voxels": [],
|
| 175 |
+
"contact_pose_ego": [
|
| 176 |
+
float(points[first, 0]),
|
| 177 |
+
float(points[first, 1]),
|
| 178 |
+
float(headings[first]),
|
| 179 |
+
],
|
| 180 |
+
"collision_cell_size_m": grid.get("collision_cell_size", args.grid_resolution),
|
| 181 |
+
"collision_cell_angle_rad": grid.get("collision_cell_angle", 0.0),
|
| 182 |
+
}
|
| 183 |
+
voxels, state = arrays["voxel_points"], arrays["voxel_state"]
|
| 184 |
+
plane = arrays["floor_plane"]
|
| 185 |
+
height = voxels @ plane[:3] + plane[3] if len(plane) == 4 else np.zeros(len(voxels))
|
| 186 |
+
hazard = obstacle_height_mask(height, args)
|
| 187 |
+
active = hazard & ((state == 1) | ((state == 0) & args.block_uncertain_obstacles))
|
| 188 |
+
local = world_to_ego(voxels, planning_pose[:2], planning_pose[2])
|
| 189 |
+
if "collision_cells" in grid:
|
| 190 |
+
voxel_cells = np.floor(voxels[:, :2] / args.voxel_size).astype(np.int64)
|
| 191 |
+
contact_cells = np.floor(
|
| 192 |
+
ego_to_world(contacts, planning_pose[:2], planning_pose[2]) / args.voxel_size
|
| 193 |
+
).astype(np.int64)
|
| 194 |
+
else:
|
| 195 |
+
r, c, _ = ego_to_cells(local, args, grid["hard_source"].shape)
|
| 196 |
+
voxel_cells = np.column_stack([r, c])
|
| 197 |
+
r, c, _ = ego_to_cells(contacts, args, grid["hard_source"].shape)
|
| 198 |
+
contact_cells = np.column_stack([r, c])
|
| 199 |
+
selected = np.zeros(len(voxels), bool)
|
| 200 |
+
for cell in contact_cells[:16]:
|
| 201 |
+
selected |= (voxel_cells == cell).all(axis=1) & active
|
| 202 |
+
for index in np.flatnonzero(selected)[:16]:
|
| 203 |
+
score = float(arrays.get("voxel_scores", np.full(len(voxels), np.nan))[index])
|
| 204 |
+
origin = (
|
| 205 |
+
"aged_sensor_supported_surface"
|
| 206 |
+
if state[index] == 0 and score >= 0.7
|
| 207 |
+
else (
|
| 208 |
+
"unconfirmed_model_or_sensor_disagreement"
|
| 209 |
+
if state[index] == 0 and np.isfinite(score)
|
| 210 |
+
else (
|
| 211 |
+
"uncertain_origin_not_recorded"
|
| 212 |
+
if state[index] == 0
|
| 213 |
+
else "sensor_supported_surface"
|
| 214 |
+
)
|
| 215 |
+
)
|
| 216 |
+
)
|
| 217 |
+
entry = {
|
| 218 |
+
"index": int(index),
|
| 219 |
+
"world_xyz": voxels[index].tolist(),
|
| 220 |
+
"ego_xy": local[index].tolist(),
|
| 221 |
+
"height_m": float(height[index]),
|
| 222 |
+
"state": int(state[index]),
|
| 223 |
+
"score": score,
|
| 224 |
+
"origin": origin,
|
| 225 |
+
"current_view": current_view(voxels[index], arrays, args),
|
| 226 |
+
}
|
| 227 |
+
point_delta = local[index] - points[first]
|
| 228 |
+
heading = headings[first]
|
| 229 |
+
if args.footprint_shape == "rectangle":
|
| 230 |
+
width = np.cos(heading) * point_delta[0] + np.sin(heading) * point_delta[1]
|
| 231 |
+
length = (
|
| 232 |
+
-np.sin(heading) * point_delta[0]
|
| 233 |
+
+ np.cos(heading) * point_delta[1]
|
| 234 |
+
- args.robot_length_offset
|
| 235 |
+
)
|
| 236 |
+
gap = np.hypot(
|
| 237 |
+
max(0.0, abs(width) - args.robot_width / 2 - args.safety_margin),
|
| 238 |
+
max(0.0, abs(length) - args.robot_length / 2 - args.safety_margin),
|
| 239 |
+
)
|
| 240 |
+
else:
|
| 241 |
+
gap = max(0.0, np.linalg.norm(point_delta) - args.robot_radius - args.safety_margin)
|
| 242 |
+
entry["point_inside_actual_footprint"] = bool(gap <= 1e-9)
|
| 243 |
+
entry["point_clearance_m"] = float(gap)
|
| 244 |
+
for name in (
|
| 245 |
+
"ids",
|
| 246 |
+
"age_s",
|
| 247 |
+
"last_seen_age_s",
|
| 248 |
+
"last_hit_age_s",
|
| 249 |
+
"last_supported_age_s",
|
| 250 |
+
"last_frame",
|
| 251 |
+
"evidence_frame",
|
| 252 |
+
"geometry_frame",
|
| 253 |
+
"geometry_support",
|
| 254 |
+
"last_hit_support",
|
| 255 |
+
"source_raw_depth_m",
|
| 256 |
+
"source_refined_depth_m",
|
| 257 |
+
):
|
| 258 |
+
if "voxel_" + name in arrays:
|
| 259 |
+
entry[name] = arrays["voxel_" + name][index].item()
|
| 260 |
+
distance2 = ((voxels - voxels[index]) ** 2).sum(axis=1)
|
| 261 |
+
entry["neighbors_within_10cm"] = int(((distance2 <= 0.1**2) & (state != 2)).sum()) - 1
|
| 262 |
+
report["contact_voxels"].append(entry)
|
| 263 |
+
report["unknown_space_contacts"] = bool(
|
| 264 |
+
len(contacts) and not report["contact_voxels"] and args.unknown_policy == "block"
|
| 265 |
+
)
|
| 266 |
+
if (
|
| 267 |
+
"proposal_scores" in arrays
|
| 268 |
+
and len(arrays.get("bank_poses", []))
|
| 269 |
+
and not len(arrays["proposal_valid"])
|
| 270 |
+
):
|
| 271 |
+
report["rejected_candidate_examples"] = []
|
| 272 |
+
for index in np.argsort(arrays["proposal_scores"])[:3]:
|
| 273 |
+
path = arrays["bank_poses"][index]
|
| 274 |
+
hit = collisions_at(path[:, :2], path[:, 2], grid, args)
|
| 275 |
+
report["rejected_candidate_examples"].append(
|
| 276 |
+
{
|
| 277 |
+
"index": int(index),
|
| 278 |
+
"first_collision_pose": (
|
| 279 |
+
None if not hit.any() else path[np.flatnonzero(hit)[0]].tolist()
|
| 280 |
+
),
|
| 281 |
+
}
|
| 282 |
+
)
|
| 283 |
+
return clean_json(report)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class DebugRecorder:
|
| 287 |
+
"""No file writes on control/inference threads. Retain bounded snapshots."""
|
| 288 |
+
|
| 289 |
+
def __init__(self, output, args):
|
| 290 |
+
self.output = Path(output)
|
| 291 |
+
self.directory = self.output / "debug"
|
| 292 |
+
self.directory.mkdir(exist_ok=True)
|
| 293 |
+
self.max_snapshots = args.debug_max_snapshots
|
| 294 |
+
self.interval = args.debug_snapshot_interval
|
| 295 |
+
self.stuck_seconds = args.debug_stuck_seconds
|
| 296 |
+
self.started = time.monotonic()
|
| 297 |
+
self.jobs = queue.Queue(maxsize=128)
|
| 298 |
+
self.lock = threading.Lock()
|
| 299 |
+
self.contexts = OrderedDict()
|
| 300 |
+
self.stop = threading.Event()
|
| 301 |
+
self.last_periodic = self.last_incident = -np.inf
|
| 302 |
+
self.last_control = -np.inf
|
| 303 |
+
self.control_key = None
|
| 304 |
+
self.pause_snapshots = {}
|
| 305 |
+
self.progress_pose = None
|
| 306 |
+
self.progress_time = self.started
|
| 307 |
+
self.was_commanding_motion = False
|
| 308 |
+
self.counter = self.written_events = self.written_snapshots = self.dropped = 0
|
| 309 |
+
self.pending_snapshots = 0
|
| 310 |
+
self.last_snapshot = self.last_error = ""
|
| 311 |
+
sources = self.directory / "source"
|
| 312 |
+
sources.mkdir(exist_ok=True)
|
| 313 |
+
hashes = {}
|
| 314 |
+
for name in (
|
| 315 |
+
"depth_nav_live.py",
|
| 316 |
+
"depth_nav_control.py",
|
| 317 |
+
"depth_nav_footprint.py",
|
| 318 |
+
"depth_nav_trajectories.py",
|
| 319 |
+
"depth_nav_memory.py",
|
| 320 |
+
"depth_nav_debug.py",
|
| 321 |
+
"depth_nav_live_viewer.html",
|
| 322 |
+
"lingbot_voxel_map.py",
|
| 323 |
+
"lingbot_depth_geometry.py",
|
| 324 |
+
"lingbot_depth_model.py",
|
| 325 |
+
"lingbot_depth_eval.py",
|
| 326 |
+
"depth_nav_robot_relay.py",
|
| 327 |
+
"capture_lingbot_rgbd_ros2.py",
|
| 328 |
+
):
|
| 329 |
+
path = Path(__file__).with_name(name)
|
| 330 |
+
data = path.read_bytes()
|
| 331 |
+
(sources / name).write_bytes(data)
|
| 332 |
+
hashes[name] = hashlib.sha256(data).hexdigest()
|
| 333 |
+
manifest = {
|
| 334 |
+
"schema_version": 1,
|
| 335 |
+
"started_utc": datetime.now(timezone.utc).isoformat(),
|
| 336 |
+
"python": sys.version,
|
| 337 |
+
"numpy": np.__version__,
|
| 338 |
+
"settings": clean_json(vars(args)),
|
| 339 |
+
"source_sha256": hashes,
|
| 340 |
+
"snapshots_compressed": False,
|
| 341 |
+
}
|
| 342 |
+
(self.output / "run_manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
|
| 343 |
+
self.thread = threading.Thread(target=self._write, name="depth-nav-debug", daemon=True)
|
| 344 |
+
self.thread.start()
|
| 345 |
+
self.event("session_start", {"execute": args.execute})
|
| 346 |
+
|
| 347 |
+
def _enqueue(self, job):
|
| 348 |
+
try:
|
| 349 |
+
self.jobs.put_nowait(job)
|
| 350 |
+
return True
|
| 351 |
+
except queue.Full:
|
| 352 |
+
self.dropped += 1
|
| 353 |
+
return False
|
| 354 |
+
|
| 355 |
+
def event(self, kind, data):
|
| 356 |
+
record = {
|
| 357 |
+
"event": kind,
|
| 358 |
+
"utc": datetime.now(timezone.utc).isoformat(),
|
| 359 |
+
"elapsed_s": time.monotonic() - self.started,
|
| 360 |
+
**clean_json(data),
|
| 361 |
+
}
|
| 362 |
+
self._enqueue(("event", record))
|
| 363 |
+
|
| 364 |
+
def publish(self, context):
|
| 365 |
+
with self.lock:
|
| 366 |
+
self.contexts[context["metadata"]["frame_id"]] = context
|
| 367 |
+
while len(self.contexts) > 3:
|
| 368 |
+
self.contexts.popitem(last=False)
|
| 369 |
+
now = time.monotonic()
|
| 370 |
+
if self.interval > 0 and now - self.last_periodic >= self.interval:
|
| 371 |
+
self.last_periodic = now
|
| 372 |
+
self.incident("periodic", {"frame_id": context["metadata"]["frame_id"]}, periodic=True)
|
| 373 |
+
|
| 374 |
+
def incident(self, reason, data, *, force=False, periodic=False, context=None):
|
| 375 |
+
now = time.monotonic()
|
| 376 |
+
with self.lock:
|
| 377 |
+
if context is None:
|
| 378 |
+
context = self.contexts.get(data.get("frame_id"))
|
| 379 |
+
if context is None and self.contexts:
|
| 380 |
+
context = next(reversed(self.contexts.values()))
|
| 381 |
+
if context is None:
|
| 382 |
+
return False
|
| 383 |
+
if self.pending_snapshots >= 2 or (
|
| 384 |
+
not force and not periodic and now - self.last_incident < 10
|
| 385 |
+
):
|
| 386 |
+
return False
|
| 387 |
+
self.counter += 1
|
| 388 |
+
name = f"snapshot_{self.counter:06d}"
|
| 389 |
+
self.pending_snapshots += 1
|
| 390 |
+
if not periodic:
|
| 391 |
+
self.last_incident = now
|
| 392 |
+
trigger = {
|
| 393 |
+
"reason": reason,
|
| 394 |
+
"utc": datetime.now(timezone.utc).isoformat(),
|
| 395 |
+
"elapsed_s": now - self.started,
|
| 396 |
+
**clean_json(data),
|
| 397 |
+
}
|
| 398 |
+
trigger["source_frame_age_s"] = max(
|
| 399 |
+
0.0, now - context["metadata"].get("received_monotonic", now)
|
| 400 |
+
)
|
| 401 |
+
queued = self._enqueue(("snapshot", (name, context, trigger)))
|
| 402 |
+
if not queued:
|
| 403 |
+
with self.lock:
|
| 404 |
+
self.pending_snapshots -= 1
|
| 405 |
+
return queued
|
| 406 |
+
|
| 407 |
+
def control(self, data, now):
|
| 408 |
+
key = (
|
| 409 |
+
data["reason"],
|
| 410 |
+
bool(data["v"] or data["w"]),
|
| 411 |
+
bool(abs(data["v"]) > 0.001),
|
| 412 |
+
int(np.sign(data["w"])) if abs(data["w"]) > 0.02 else 0,
|
| 413 |
+
data.get("robot_reason"),
|
| 414 |
+
data.get("healthy"),
|
| 415 |
+
data.get("armed"),
|
| 416 |
+
data.get("goal_version"),
|
| 417 |
+
)
|
| 418 |
+
changed = key != self.control_key
|
| 419 |
+
if changed or now - self.last_control >= 1.0:
|
| 420 |
+
self.control_key, self.last_control = key, now
|
| 421 |
+
self.event("control", data)
|
| 422 |
+
if data.get("execute") and data.get("armed"):
|
| 423 |
+
if any(
|
| 424 |
+
word in data["reason"]
|
| 425 |
+
for word in ("overlaps", "intersects", "admissible", "lacks", "stale")
|
| 426 |
+
):
|
| 427 |
+
# A clear/stale oscillation is one recurring cause, not a new
|
| 428 |
+
# incident every frame. Keep every transition in events.jsonl,
|
| 429 |
+
# but bound the expensive image/map captures per pause cause.
|
| 430 |
+
cause = data["reason"]
|
| 431 |
+
if now - self.pause_snapshots.get(cause, -np.inf) >= 10:
|
| 432 |
+
if self.incident(
|
| 433 |
+
"control_pause",
|
| 434 |
+
{"frame_id": data.get("frame_id"), "control": data},
|
| 435 |
+
force=True,
|
| 436 |
+
):
|
| 437 |
+
self.pause_snapshots[cause] = now
|
| 438 |
+
pose = data.get("robot_pose")
|
| 439 |
+
if pose is not None:
|
| 440 |
+
xy = np.asarray(pose)[:2]
|
| 441 |
+
moving = bool(data["v"] or data["w"])
|
| 442 |
+
if (
|
| 443 |
+
self.progress_pose is None
|
| 444 |
+
or (moving and not self.was_commanding_motion)
|
| 445 |
+
or np.linalg.norm(xy - self.progress_pose) >= 0.10
|
| 446 |
+
):
|
| 447 |
+
self.progress_pose, self.progress_time = xy.copy(), now
|
| 448 |
+
if moving and now - self.progress_time >= self.stuck_seconds:
|
| 449 |
+
self.incident(
|
| 450 |
+
"no_translation",
|
| 451 |
+
{
|
| 452 |
+
"frame_id": data.get("frame_id"),
|
| 453 |
+
"control": data,
|
| 454 |
+
"no_translation_s": now - self.progress_time,
|
| 455 |
+
},
|
| 456 |
+
)
|
| 457 |
+
self.was_commanding_motion = moving
|
| 458 |
+
else:
|
| 459 |
+
self.was_commanding_motion = False
|
| 460 |
+
|
| 461 |
+
def status(self):
|
| 462 |
+
return {
|
| 463 |
+
"enabled": True,
|
| 464 |
+
"directory": str(self.directory),
|
| 465 |
+
"snapshots_written": self.written_snapshots,
|
| 466 |
+
"pending_snapshots": self.pending_snapshots,
|
| 467 |
+
"events_written": self.written_events,
|
| 468 |
+
"dropped_jobs": self.dropped,
|
| 469 |
+
"last_snapshot": self.last_snapshot,
|
| 470 |
+
"error": self.last_error,
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
def _write(self):
|
| 474 |
+
try:
|
| 475 |
+
with (self.output / "events.jsonl").open("w", buffering=1) as log:
|
| 476 |
+
while not self.stop.is_set() or not self.jobs.empty():
|
| 477 |
+
try:
|
| 478 |
+
kind, job = self.jobs.get(timeout=0.05)
|
| 479 |
+
except queue.Empty:
|
| 480 |
+
continue
|
| 481 |
+
try:
|
| 482 |
+
if kind == "event":
|
| 483 |
+
log.write(json.dumps(job, allow_nan=False) + "\n")
|
| 484 |
+
self.written_events += 1
|
| 485 |
+
else:
|
| 486 |
+
name, context, trigger = job
|
| 487 |
+
arrays = {k: v for k, v in context["arrays"].items() if v is not None}
|
| 488 |
+
# Stored ZIP avoids compression competing for CPU.
|
| 489 |
+
np.savez(self.directory / (name + ".npz"), **arrays)
|
| 490 |
+
document = {
|
| 491 |
+
"schema_version": 1,
|
| 492 |
+
"snapshot": name,
|
| 493 |
+
"trigger": trigger,
|
| 494 |
+
"frame": clean_json(context["metadata"]),
|
| 495 |
+
"diagnosis": collision_report(context, trigger),
|
| 496 |
+
"viewer_payload": context.get("viewer_payload"),
|
| 497 |
+
}
|
| 498 |
+
(self.directory / (name + ".json")).write_text(
|
| 499 |
+
json.dumps(document, allow_nan=False) + "\n"
|
| 500 |
+
)
|
| 501 |
+
self.written_snapshots += 1
|
| 502 |
+
self.last_snapshot = str(self.directory / (name + ".json"))
|
| 503 |
+
log.write(
|
| 504 |
+
json.dumps(
|
| 505 |
+
{
|
| 506 |
+
"event": "snapshot_saved",
|
| 507 |
+
"snapshot": name,
|
| 508 |
+
"trigger": trigger,
|
| 509 |
+
"source_frame_id": context["metadata"]["frame_id"],
|
| 510 |
+
"diagnosis": document["diagnosis"],
|
| 511 |
+
}
|
| 512 |
+
)
|
| 513 |
+
+ "\n"
|
| 514 |
+
)
|
| 515 |
+
snapshots = sorted(self.directory.glob("snapshot_*.json"))
|
| 516 |
+
for old in snapshots[: -self.max_snapshots]:
|
| 517 |
+
old.with_suffix(".npz").unlink(missing_ok=True)
|
| 518 |
+
old.unlink(missing_ok=True)
|
| 519 |
+
except Exception as exc:
|
| 520 |
+
self.last_error = f"{type(exc).__name__}: {exc}"
|
| 521 |
+
if kind == "snapshot":
|
| 522 |
+
(self.directory / (name + ".npz")).unlink(missing_ok=True)
|
| 523 |
+
(self.directory / (name + ".json")).unlink(missing_ok=True)
|
| 524 |
+
log.write(
|
| 525 |
+
json.dumps({"event": "debug_error", "error": self.last_error}) + "\n"
|
| 526 |
+
)
|
| 527 |
+
finally:
|
| 528 |
+
if kind == "snapshot":
|
| 529 |
+
with self.lock:
|
| 530 |
+
self.pending_snapshots -= 1
|
| 531 |
+
self.jobs.task_done()
|
| 532 |
+
except Exception as exc:
|
| 533 |
+
self.last_error = f"{type(exc).__name__}: {exc}"
|
| 534 |
+
|
| 535 |
+
def close(self):
|
| 536 |
+
self.stop.set()
|
| 537 |
+
self.thread.join(timeout=3)
|
| 538 |
+
if self.thread.is_alive():
|
| 539 |
+
self.last_error = "Debug writer did not finish within shutdown timeout"
|