feat: dai hanh lang theo route graph (Voronoi) cho goal xa, anytime ARA* dung ReplanParams, smoother path

- Anytime dung nghia (pha 0): replan() qua ReplanParams thay vi replan(double) - nghiem dau o
  initial_epsilon, ha dan eps_step toi final_epsilon trong repair_time; return_first_solution
  de bench. eps=1.0 (A* thuan) tren map rong gan chac chan het gio.
- Route graph corridor: nhan robot_sensor_ports::SensorConsumer, doc RouteGraph tu kho (host
  bien dich Voronoi tu map, day qua addRouteGraph), doi chieu map_hash voi static layer song.
  Goal >= min_range_m + co graph -> gan start/goal (BFS), Dijkstra ra tuyen, dong dau mask quanh
  tuyen; o NGOAI mask nhan cost inscribed (hard) hoac bi phat (soft) - search + heuristic 2D chi
  no trong dai (~3% map thay 100% tren sehc). Khong graph/lech/gan that bai = chay full nhu cu,
  log [debug/corridor] noi ly do; "route graph REJECTED" la LOI khong tat duoc. Nguong nghen ->
  noi rong (widen_factor, toi da max_widen) -> bo dai chay full voi thoi gian con lai.
- Path smoother (distance_map.h/.cpp, path_smoother.h/.cpp): keo day doan lattice di thang duoc
  tren costmap SONG (distance-transform giu khoang cach voi LETHAL, khong chi nhin cost), bo goc
  bang cung ban kinh co dinh khop bo mprim - giu nguyen doan lui (cusp). Do tren sehc: path
  lattice dai hon toi uu 2D 12%, 11 lan doi chieu re; smoother giam duoc phan lon.
- Log "metrics: ... detour= turn_deg= arcs= wiggles= plan_ms= corridor= corridor_ms= smooth=
  raw_m= smooth_ms= anchors= fillets=" moi lan plan thanh cong - so dai on/off, hard/soft, eps
  qua script tools/eval_plan_bag.py.
- Test moi: test/path_smoother_test.cpp (path_smoother la hinh hoc thuan, khong SBPL/costmap,
  chay duoc moi noi co gtest). CMakeLists them target catkin_add_gtest + nhanh standalone.
- Phu thuoc build moi: robot_sensor_ports, route_graph (repo rieng, da co remote).
- YAML: schema initial_epsilon/final_epsilon/eps_step/repair_time/return_first_solution,
  khoi voronoi_corridor (12 khoa) va smooth_path (7 khoa) trong cfg/sbpl_global_params.yaml
  (dong bo tu pnkx_nav_core c52cbe5 / move_base2 f4f9965).
This commit is contained in:
2026-09-22 15:51:26 +07:00
parent 34c74cb541
commit 3fff3b15cd
13 changed files with 2510 additions and 100 deletions

View File

@@ -72,6 +72,8 @@ if (NOT BUILDING_WITH_CATKIN)
robot_nav_core robot_nav_core
robot_protocol_msgs robot_protocol_msgs
robot_cpp robot_cpp
robot_sensor_ports
route_graph
) )
else() else()
@@ -91,6 +93,8 @@ else()
robot_nav_core robot_nav_core
robot_protocol_msgs robot_protocol_msgs
robot_cpp robot_cpp
robot_sensor_ports
route_graph
) )
find_library(TF3_LIBRARY NAMES tf3) find_library(TF3_LIBRARY NAMES tf3)
@@ -98,7 +102,7 @@ else()
catkin_package( catkin_package(
INCLUDE_DIRS include INCLUDE_DIRS include
LIBRARIES ${PROJECT_NAME} LIBRARIES ${PROJECT_NAME}
CATKIN_DEPENDS robot_visualization_msgs robot_nav_msgs robot_std_msgs robot_geometry_msgs robot_tf3_geometry_msgs robot_time data_convert robot_costmap_2d robot_nav_core robot_protocol_msgs robot_cpp CATKIN_DEPENDS robot_visualization_msgs robot_nav_msgs robot_std_msgs robot_geometry_msgs robot_tf3_geometry_msgs robot_time data_convert robot_costmap_2d robot_nav_core robot_protocol_msgs robot_cpp robot_sensor_ports route_graph
DEPENDS Eigen3 Boost SBPL DEPENDS Eigen3 Boost SBPL
) )
@@ -115,6 +119,8 @@ endif()
# ======================================================== # ========================================================
add_library(${PROJECT_NAME} SHARED add_library(${PROJECT_NAME} SHARED
src/sbpl_lattice_planner.cpp src/sbpl_lattice_planner.cpp
src/path_smoother.cpp
src/distance_map.cpp
) )
# Header sbpl phải là bản mà SBPL_DIR chọn, ĐỨNG TRƯỚC mọi include của catkin: /opt/ros/noetic/include # Header sbpl phải là bản mà SBPL_DIR chọn, ĐỨNG TRƯỚC mọi include của catkin: /opt/ros/noetic/include
@@ -163,6 +169,35 @@ else()
endif() endif()
# ========================================================
# Tests — path_smoother is pure geometry (no SBPL/costmap), runs anywhere gtest exists.
# catkin_add_gtest KHÔNG link gtest_main nên test tự có main(). Chạy tay:
# ./devel/lib/sbpl_lattice_planner/path_smoother_test (catkin)
# ========================================================
if(BUILDING_WITH_CATKIN)
if(CATKIN_ENABLE_TESTING)
catkin_add_gtest(path_smoother_test test/path_smoother_test.cpp src/path_smoother.cpp src/distance_map.cpp)
if(TARGET path_smoother_test)
# catkin_add_gtest đánh dấu EXCLUDE_FROM_ALL (chỉ ra khi chạy target `tests`); bỏ dấu để
# `catkin_make --pkg sbpl_lattice_planner` ra luôn ./devel/lib/sbpl_lattice_planner/path_smoother_test.
set_target_properties(path_smoother_test PROPERTIES EXCLUDE_FROM_ALL FALSE)
target_compile_options(path_smoother_test PRIVATE -Wall -Wextra)
target_include_directories(path_smoother_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(path_smoother_test pthread)
endif()
endif()
else()
option(BUILD_TESTS "Build sbpl_lattice_planner unit tests" OFF)
if(BUILD_TESTS)
find_package(GTest REQUIRED)
add_executable(path_smoother_test test/path_smoother_test.cpp src/path_smoother.cpp src/distance_map.cpp)
target_include_directories(path_smoother_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(path_smoother_test PRIVATE GTest::GTest pthread)
enable_testing()
add_test(NAME path_smoother_test COMMAND path_smoother_test)
endif()
endif()
# ======================================================== # ========================================================
# Install # Install
# ======================================================== # ========================================================

132
README.md
View File

@@ -77,7 +77,11 @@ sửa nhầm bên đó sẽ không có tác dụng.
| `primitive_filename` | string | `""` (bắt buộc) | đường dẫn file `.mprim`; `resolution_m` trong file PHẢI khớp resolution costmap, lệch là SBPL từ chối nạp | | `primitive_filename` | string | `""` (bắt buộc) | đường dẫn file `.mprim`; `resolution_m` trong file PHẢI khớp resolution costmap, lệch là SBPL từ chối nạp |
| `planner_type` | string | `ARAPlanner` | `ARAPlanner` (ARA\*) hoặc `ADPlanner` (AD\*) | | `planner_type` | string | `ARAPlanner` | `ARAPlanner` (ARA\*) hoặc `ADPlanner` (AD\*) |
| `allocated_time` | double | 10.0 | [s] quỹ thời gian mỗi lần plan; còn dư thì ARA\* tiếp tục hạ epsilon | | `allocated_time` | double | 10.0 | [s] quỹ thời gian mỗi lần plan; còn dư thì ARA\* tiếp tục hạ epsilon |
| `initial_epsilon` | double | 3.0 | hệ số nới heuristic lần search đầu (>= 1); 1.0 = A\* tối ưu ngay, không có nghiệm sớm | | `initial_epsilon` | double | 3.0 | hệ số nới heuristic lần search đầu (>= 1); 1.0 = A\* tối ưu ngay, không có nghiệm sớm — goal xa map rộng gần chắc hết giờ |
| `final_epsilon` | double | 1.0 | (pha 0, 2026-09-21, `ReplanParams`) eps dừng hạ; >1 = chấp nhận sub-optimal chừng đó |
| `eps_step` | double | 0.5 | mỗi vòng ARA\* hạ eps đi ngần này |
| `repair_time` | double | -1 | [s] tổng thời gian tối đa còn được hạ eps sau khi có nghiệm đầu; <= 0 = tới hết `allocated_time` |
| `return_first_solution` | bool | false | trả ngay nghiệm đầu, không hạ eps (bench) |
| `forward_search` | bool | false | search xuôi start→goal hay ngược; AD\* nên dùng backward để replan nhanh | | `forward_search` | bool | false | search xuôi start→goal hay ngược; AD\* nên dùng backward để replan nhanh |
| `force_scratch_limit` | int | 500 | số cell costmap thay đổi vượt ngưỡng này thì bỏ search cũ, plan từ đầu | | `force_scratch_limit` | int | 500 | số cell costmap thay đổi vượt ngưỡng này thì bỏ search cũ, plan từ đầu |
| `nominalvel_mpersecs` | double | 0.4 | [m/s] vận tốc danh định — dùng tính cost thời gian của primitive | | `nominalvel_mpersecs` | double | 0.4 | [m/s] vận tốc danh định — dùng tính cost thời gian của primitive |
@@ -103,6 +107,132 @@ trong file mprim phải được tune **cùng nhau**.
khớp góc rời rạc, spacing pose đều ≤ 1 cell). Các script `genmprim*.m` MATLAB khớp góc rời rạc, spacing pose đều ≤ 1 cell). Các script `genmprim*.m` MATLAB
chỉ giữ làm tham khảo lịch sử. chỉ giữ làm tham khảo lịch sử.
## Dải hành lang theo route graph cho goal xa (2026-09-21)
Goal xa trên map rộng (sehc 153×153 m) làm ARA* + heuristic Dijkstra 2D quét cả 9.4M ô. Planner
giờ nhận **route graph (Voronoi) do host biên dịch sẵn từ map** và khoanh search trong một dải
quanh tuyến graph; bên trong dải vẫn là lattice + mprim + cost như cũ nên path không đổi chất lượng.
- Graph vào bằng `BaseNavigation::addRouteGraph("/route_graph", msg)` → kho `robot_sensor_ports`
(khai `data_type: RouteGraph` trong `sensor_store_params.yaml`) → `PlannerRunner::attachSensors`
trao reader cho planner (kế thừa `robot_sensor_ports::SensorConsumer`) TRƯỚC `initialize()`.
- `tryAdoptRouteGraph()` (cuối `initialize()`, đầu mỗi `makePlan`): bản mới trong kho → kiểm
version, kích thước/resolution/origin và **hash mask vật cản** của static layer sống theo luật ghi
trong `source` (`route_graph::obstacleMaskFromCostmap` + `hashObstacleMask`, giống byte với
`voronoi_route`). Lệch = log LỖI "route graph REJECTED", corridor tắt. Đổi kích thước map → bỏ
graph cũ ngay.
- `makePlan`: goal ≥ `min_range_m` và có graph → `buildCorridor()`: BFS gắn start/goal vào graph
(`route_graph::Graph::attach`, đi qua ô < inscribed hoặc unknown khi `allow_unknown`), Dijkstra
(`route`), đóng dấu mask (`corridorMask`). Vòng cost `applyGridCosts` gán ô NGOÀI dải =
`max(cost costmap, inscribed)` — không lethal, footprint đè lên vẫn hợp lệ, chỉ tâm không đi qua;
heuristic 2D tự dừng ở mép dải. Đổi dải giữa hai lượt tự ra `changedcells` + `force_scratch`.
- Hai chế độ (`outside_mode`): **hard** = ô ngoài dải thành inscribed (chặn, nhanh nhất);
**soft** = chỉ phạt cost (`soft_penalty_cost`, ~3× đắt hơn) — tuyến là "hướng tổng quát", search
vẫn ra ngoài khi cần, dải không bao giờ là lý do fail. Edge hẹp hơn `route_min_clearance_m`
(mặc định = bán kính nội tiếp footprint) không được chọn làm tuyến.
- Nới/fallback (chỉ hard): 2D `h=INF` trong dải hay search **EXHAUSTED** trong dải → nhân bề rộng `widen_factor`
(tối đa `max_widen`), hết nấc → bỏ dải, full với thời gian còn lại. **TIMEOUT** trong dải → trả
lỗi ngay, KHÔNG full (full còn chậm hơn). Pha có dải chỉ được `budget_fraction × allocated_time`.
- Không graph / lệch / gắn thất bại / khác thành phần liên thông / goal gần: chạy full như trước,
`[debug/corridor]` nói lý do. Khối YAML `voronoi_corridor` (12 khoá, comment trong file); robot
thật (`cfg/`) để `enabled: false`.
- `SBPLDetourPlanner` (cùng .so, `sbpl_recovery`) không có reader → corridor không bao giờ bật ở
instance đó; detour ngắn hơn `min_range_m` nên không mất gì.
Thuật toán graph/hash nằm ở `Test/route_graph` (không ROS, không Voronoi); producer ở
`Test/voronoi_route`; thiết kế và bench ở `Test/docs/sbpl_lattice_planner/FAR_GOAL_ANYTIME_CORRIDOR_PLAN.md`.
### Đánh giá đường đi: mượt và chi phí (2026-09-22)
Câu hỏi cần trả lời có số: path có **ngoằn ngoèo ở chỗ đi thẳng được** không, và dải làm nhanh
lên bao nhiêu. Ba nguồn ngoằn ngoèo tách được bằng phép đo, không cần nhìn hình:
| Nguồn | Dấu hiệu | Chỉnh |
|---|---|---|
| Dải kéo path bám trục Voronoi | `detour`/`slack` cao khi corridor=on, thấp khi off cùng goal | hạ `soft_penalty_cost` (200 → 120/80: đi ngoài dải chỉ còn ~1.6×/1.2× thay vì 3×), nới `half_width_m` |
| Nghiệm chưa tối ưu (ARA* dừng ở eps>1) | `eps` > 1 trong dòng `metrics:` | tăng `repair_time`, hạ `initial_epsilon` |
| Lưới 16 hướng (đường xiên không trùng góc lưới thành răng cưa) | `wiggles` cao mà `detour` ≈ 1, có cả khi corridor=off | thuộc mprim, không phải dải; muốn hết phải smoothing sau planner |
Hai chỗ thu số, mỗi lượt plan thành công:
1. **Log** — dòng `[debug/plan] metrics: start= goal= straight_m= path_m= detour= turn_deg= arcs=
wiggles= pts= eps= expands= plan_ms= corridor=off|soft|hard corridor_ms= route_m= widen=`
(khoá `debug_plan`, O(n) trên path). `detour` = path/thẳng; `turn_deg` = Σ|Δθ|; `arcs` = số cung
rẽ; `wiggles` = số lần đổi chiều rẽ. Không cần bag khi chỉ so thời gian/eps.
2. **Bag** — cần khi muốn biết path "đi thẳng được mà không đi": script
`tools/eval_plan_bag.py` kéo dây (string-pull, line-of-sight qua ô < inscribed trên global
costmap trong bag) và báo `slack` = phần chiều dài path bỏ được nếu đi thẳng nơi đi thẳng được.
`--plot` vẽ path (đỏ) + dây kéo (xanh) trên costmap để nhìn đúng chỗ.
```bash
# ghi trong lúc gửi goal (mỗi config một bag + một log; robot ở cùng vị trí xuất phát)
rosbag record -O /tmp/eval_<tag>.bag /global_costmap/costmap /global_costmap/costmap_updates \
/global_costmap/costmap/plan /move_base_simple/goal /tf /tf_static
# so sánh
python3 tools/eval_plan_bag.py --bag off=/tmp/eval_off.bag --log off=/tmp/sim_off.log \
--bag soft=/tmp/eval_soft.bag --log soft=/tmp/sim_soft.log --cache /tmp/eval_cache \
--csv /tmp/eval.csv --plot /tmp/eval
```
Bag 100 m goal ≈ 10 GB (costmap 9 MB/msg) — đọc lần đầu vài phút, `--cache` giữ path + costmap
đã cắt để chạy lại trong vài giây. Cột `over_opt` = path / đường ngắn nhất 2D cho điểm trên chính
costmap đó (skimage `route_through_array`) — số "dài hơn mức cần" thật, không phụ thuộc tường.
Quy trình A/B: cùng điểm xuất phát (khởi động lại sim), cùng bộ goal (gửi qua
`/move_base_simple/goal`, ví dụ 31 m / 51 m / 101 m trên sehc), chỉ chấm **plan đầu tiên** của mỗi
goal (replan xuất phát từ robot đang chạy, không so được giữa hai lần). Config lần lượt:
`enabled: false` (đối chứng) → `soft` 200 → `soft` 120 → `hard`; giữ nguyên `allocated_time`,
`initial_epsilon`, `repair_time` giữa các lần.
Số đo đầu tiên (sehc, 22/9, dải soft 200, eps dừng 1.5, chưa smoother):
| goal | thẳng | path | opt2d | over_opt | slack | turn | wiggles | plan ms |
|---|---|---|---|---|---|---|---|---|
| 61.6 m | 61.6 | 68.2 | 69.6 | 0.98 | 0.02 | 109° | 2 | 3296 |
| 101.2 m | 101.2 | 112.3 | 110.6 | 1.02 | 0.03 | 492° | 8 | 1642 |
| 99.7 m (chiều ngược) | 99.7 | 122.3 | 109.0 | **1.12** | **0.11** | 849° | 11 | 3303 |
Hình vẽ ca cuối: path bám mép dải (y = 18 rồi vọt lên 24 rồi xuống 14) trong khi sàn trống cho
đường chéo thẳng 108.6 m. Với luật cost SBPL `base × (cost/14 + 1)`, free = 60 → 5×, ngoài dải 200
→ 15×: ra ngoài dải đắt 3× nên search không bao giờ cắt tắt khi đường vòng trong dải ngắn hơn 3×
đoạn cắt — tức mọi uốn nhỏ đều giữ nguyên. Hạ `soft_penalty_cost` không đủ (cần penalty < 1.12×
mới cắt được ca này); vì vậy có bước làm mượt dưới đây.
### Làm mượt path sau search (2026-09-22)
`PathSmoother` ([path_smoother.h](include/sbpl_lattice_planner/path_smoother.h), thuần hình học,
test riêng `test/path_smoother_test.cpp`) chạy cuối `makePlan` khi `smooth_path.enabled`:
1. **Kéo dây** (string pulling): từ mỗi mốc lấy điểm xa nhất trên path (≤ `max_shortcut_m` theo
chiều dài path — cửa sổ phải phủ hết đoạn vòng mới cắt được, 30 m để sót chữ V 33 m nên mặc
định 80 m) mà đoạn thẳng tới đó sạch; quét thô bước 0.4 m rồi tinh trong bước cuối. Luật sạch y
hệt lattice: tâm không lên ô ≥ inscribed; footprint không ô nào LETHAL. Khác lattice ở cách biết
"footprint chắc chắn sạch": SBPL dùng `cost_possibly_circumscribed_thresh`, nhưng fork này
FREE_SPACE = 60 nên ngưỡng đó (cost tại r_circ = 16) khớp mọi ô — SBPL quét footprint ở mọi
action, smoother làm theo thì 100 m mất 3.2 s (đo 22/9). Thay bằng **EDT** (`distance_map.h`,
Felzenszwalb, ~2M ô quanh path) tới ô LETHAL: cách vật cản > r_circ + 1.5 ô là sạch, còn lại mới
quét footprint bằng mặt nạ ô theo bin heading 5°, đa giác nới 1.5 ô. Không thấy mốc nào sạch
thì giữ bước gốc — không bao giờ tệ hơn đầu vào.
2. **Bo góc**: cung bán kính `fillet_radius_m` tiếp tuyến hai cạnh, mỗi góc dùng tối đa nửa cạnh;
không đủ chỗ thì thu bán kính, dưới `min_fillet_radius_m` (0.8 m = 1/kappa base giữ được ở
0.4 m/s; cung R=0.4 làm Priest bò 0.20 m/s) hoặc cung đè vật cản thì để gãy (hai heading tại một
điểm — tracker quay tại chỗ, như primitive quay tại chỗ của lattice).
3. Đầu path = đoạn thẳng theo hướng cạnh đầu (giữ hợp đồng `free_start_heading`), cuối = goal với
yaw goal. Path có đoạn **lùi** trả nguyên lattice (cắt tắt qua cusp là đổi lùi thành tiến).
Dòng `metrics:` thêm `smooth=on|off|skipped raw_m= smooth_ms= anchors= fillets=được/tổng`.
Robot thật (`cfg/`) để `enabled: false` tới khi chạy thử; dev bật.
Lượt đầu với smoother (22/9, cửa sổ 30 m, chưa EDT): 6 goal, `slack` median 0.028 → 0.002,
`turn_deg` 301 → 154, `wiggles` 5 → 3, `over_opt` ~1.0; nhưng `smooth_ms` 1.7–3.4 s (footprint
mọi mẫu) và goal 103 m còn chữ V 33 m ở giữa vì cửa sổ 30 m không phủ hết — hai sửa ở trên.
Lượt hai (EDT + cửa sổ 80 m): `smooth_ms` 36 ms, chữ V hết (108.0 m so với string-pull 107.4 m,
`over_opt` 0.985). Nhưng mission 3 ABORTED tại cụm cột (-40,-10): kéo dây không nhìn cost nên cắt
góc sát đúng mép inscribed của costmap toàn cục, local costmap đặt 253 ngay đó → Priest
`blocked_ahead=#0@0.00m(cost=253)` → detour 76 m trong 2 s không ra → hết recovery. Sửa: khoá
`min_clearance_m` — tâm phải cách ô LETHAL ≥ bán kính ngoại tiếp (EDT), chỗ hẹp giữ path lattice.
## Build ## Build
```bash ```bash

View File

@@ -3,7 +3,25 @@ SBPLLatticePlanner:
environment_type: XYThetaLattice environment_type: XYThetaLattice
planner_type: ARAPlanner planner_type: ARAPlanner
allocated_time: 10.0 allocated_time: 10.0
# ===== Anytime (pha 0, 21/9/2026) — ARA* nhận ReplanParams thay vì replan(double) =====
# Chuỗi: tìm nghiệm ĐẦU với heuristic nới eps=initial_epsilon (eps 3 = A* có trọng số, nở ít
# state hơn hàng chục lần so với eps 1 — goal 134 m trên sehc với eps 1.0 nở 925k state/5 s không
# ra), rồi hạ eps từng nấc `eps_step` tới `final_epsilon` chừng nào tổng thời gian còn dưới
# `repair_time`. Path ở eps>1 vẫn mượt (cùng mprim), chỉ có thể dài hơn tối ưu tối đa eps lần.
# ► eps 1.0 = A* thuần: goal xa trên map rộng gần như chắc chắn hết giờ. Chỉ đặt 1.0 khi map nhỏ.
# ⚠ ARA* đo thời gian bằng clock() = CPU time của CẢ tiến trình (mọi thread) nên ngân sách wall
# thực tế ngắn hơn số ghi ở đây khi costmap/control loop bận.
initial_epsilon: 1.0 initial_epsilon: 1.0
# eps dừng hạ. 1.0 = tối ưu; 1.5 = chấp nhận dài hơn tối ưu <= 1.5 lần để dư thời gian.
final_epsilon: 1.0
# Mỗi vòng ARA* hạ eps đi ngần này (SBPL mặc định 0.2; 0.5 = ít vòng hơn, mỗi vòng rẻ hơn).
eps_step: 0.5
# [s] Tổng thời gian tối đa (tính từ lúc bắt đầu search) còn được hạ eps SAU khi đã có nghiệm đầu.
# <= 0 = hạ tới hết allocated_time (hành vi cũ, lượt plan luôn dùng trọn ngân sách khi eps chưa
# về final). 2.0 = có nghiệm là trả về trong ~2 s dù chưa tối ưu — hợp goal xa.
repair_time: -1.0
# [bool] true = trả ngay nghiệm đầu (eps = initial_epsilon), không hạ eps. Chỉ để đo/bench.
return_first_solution: false
force_scratch_limit: 10000 force_scratch_limit: 10000
forward_search: true forward_search: true
# Bỏ ràng buộc heading xuất phát: local planner đã có bước quay tại chỗ đầu path # Bỏ ràng buộc heading xuất phát: local planner đã có bước quay tại chỗ đầu path
@@ -27,7 +45,10 @@ SBPLLatticePlanner:
# hợp lệ nhưng không action nào kết thúc đúng (x,y,theta) đó). # hợp lệ nhưng không action nào kết thúc đúng (x,y,theta) đó).
# TIMEOUT = hết allocated_time -> nới allocated_time hoặc tăng initial_epsilon. # TIMEOUT = hết allocated_time -> nới allocated_time hoặc tăng initial_epsilon.
# [bool] Nhóm log thông tin: "audit: start cell ... goal cell ...", "2D reachability: h=<số>", # [bool] Nhóm log thông tin: "audit: start cell ... goal cell ...", "2D reachability: h=<số>",
# "solved: ... expands= h_2d= phase=". Mặc định BẬT; tắt khi log robot thật quá dày. # "solved: ... expands= h_2d= phase=", và "metrics: ... detour= turn_deg= arcs= wiggles=
# plan_ms= corridor= corridor_ms=" (hình học + chi phí mỗi lượt plan thành công — dùng để so
# dải Voronoi on/off, soft/hard, eps; grep "metrics:" rồi so cùng goal; script offline:
# sbpl_lattice_planner/tools/eval_plan_bag.py). Mặc định BẬT; tắt khi log robot thật quá dày.
debug_plan: true debug_plan: true
# [ô] Bán kính cửa sổ lưới in ASCII quanh goal VÀ start khi goal bị từ chối / không có đường. # [ô] Bán kính cửa sổ lưới in ASCII quanh goal VÀ start khi goal bị từ chối / không có đường.
# 0 = tắt. 15 = 31x31 ô = 1.5 m @ 5 cm mỗi cửa sổ (62 dòng log mỗi lần fail). Trần 60. # 0 = tắt. 15 = 31x31 ô = 1.5 m @ 5 cm mỗi cửa sổ (62 dòng log mỗi lần fail). Trần 60.
@@ -37,3 +58,107 @@ SBPLLatticePlanner:
nominalvel_mpersecs: 0.3 nominalvel_mpersecs: 0.3
timetoturn45degsinplace_secs: 1.31 # = 0.6 rad/s timetoturn45degsinplace_secs: 1.31 # = 0.6 rad/s
primitive_filename: /home/duongtd/T800_ws/src/AMR_T800/Test/mprim_gen/diff_5cm.mprim primitive_filename: /home/duongtd/T800_ws/src/AMR_T800/Test/mprim_gen/diff_5cm.mprim
# ===== Dải hành lang theo route graph (Voronoi) cho goal xa (2026-09-21) =====
# Graph do host biên dịch sẵn từ map (voronoi_route -> voronoi.json trong thư mục map) và đẩy vào kho
# `robot_sensor_ports` cùng lúc với static map (`addRouteGraph`). Planner KHÔNG dựng graph; chỉ nhận
# khi kích thước/resolution/origin VÀ hash mask vật cản khớp static layer sống, rồi với goal xa:
# gắn start/goal vào graph, Dijkstra ra tuyến, đóng dấu dải quanh tuyến; ô NGOÀI dải nhận cost
# inscribed (không lethal) -> ARA* và heuristic 2D chỉ nở trong dải (~3 % map trên sehc thay vì 100 %).
# Search bên trong dải vẫn là lattice + mprim + cost như cũ -> path cùng chất lượng.
# Không graph / lệch map / gắn thất bại / khác thành phần liên thông = chạy full như trước, log
# [debug/corridor] nói lý do. Dòng "route graph REJECTED ..." là LỖI, không tắt được.
voronoi_corridor:
# [bool] Bật cơ chế. false = như chưa có tính năng (không đọc kho).
enabled: false
# Khoá kho nhận graph — phải trùng `topic` trong sensor_store_params.yaml và chuỗi host truyền vào
# addRouteGraph(). Rỗng = không đọc kho.
route_graph_topic: /route_graph
# Tên layer StaticLayer của global costmap để đối chiếu hash (tên trong `plugins:` của
# costmap_global_params*.yaml, ví dụ `navigation_map`). Rỗng = tự lấy StaticLayer ĐẦU TIÊN theo
# kiểu — đủ dùng khi chỉ có một; đặt tên khi có thêm layer tường ảo cũng là StaticLayer.
static_layer_name: ""
# [m] Goal gần hơn ngưỡng này -> không dùng dải (search full đã nhanh, dải chỉ thêm việc).
min_range_m: 15.0
# [m] Nửa bề rộng TỐI THIỂU của dải. Phải >= bán kính ngoại tiếp footprint + 1 ô, nếu không
# footprint tại start/goal đè ô ngoài dải. Hẹp = search nhanh, dễ cạn ở chỗ rẽ gắt.
half_width_m: 1.5
# Nửa bề rộng tại mỗi ô tuyến = max(half_width_m, hệ số × clearance tại ô) — sảnh rộng thì dải
# rộng, lối giữa kệ thì hẹp. 0 = bề rộng cố định.
clearance_scale: 0.8
# [m] Trần nửa bề rộng thích nghi.
max_half_width_m: 6.0
# [m] Bán kính BFS gắn start/goal vào graph. Điểm trong phòng kín xa graph hơn ngần này = không
# gắn được -> full search.
attach_max_radius_m: 10.0
# [m] Edge graph có điểm hẹp nhất dưới ngưỡng này thì tuyến KHÔNG đi qua, start/goal cũng không
# gắn vào (graph do producer lọc chung ở 0.3 m, không biết robot nào dùng). Nếu không, tuyến chui
# khe robot không lọt -> search cạn trong dải -> nới -> bỏ dải -> full: mất hết lợi ích.
# < 0 = tự lấy bán kính NỘI TIẾP footprint (T800: 0.48 m). Đặt lớn hơn khi muốn né lối hẹp.
route_min_clearance_m: -1.0
# hard | soft — ô NGOÀI dải bị xử lý thế nào.
# hard: gán cost inscribed -> tâm robot không đi ra ngoài dải; heuristic 2D dừng ở mép dải.
# Nhanh nhất; cạn trong dải thì nới (`widen_*`), hết nấc thì bỏ dải chạy full.
# soft: chỉ PHẠT cost (`soft_penalty_cost`), search vẫn ra ngoài được khi cần — tuyến chỉ là
# "hướng tổng quát", path không bị ép theo dải, dải không bao giờ là lý do fail; đổi lại
# tăng tốc ít hơn hard. Không có pha nới/bỏ dải, một pha trọn allocated_time.
outside_mode: hard
# [0..252, thang costmap] Cost gán cho ô ngoài dải khi soft (max với cost costmap sẵn có). SBPL
# nhân cost hành động theo (cost_ô/14 + 1): free=60 -> 5x, 200 -> 15x, tức đi ngoài dải đắt ~3 lần.
# Tăng = bám dải chặt hơn, nhanh hơn, đường vòng hơn khi dải chọn sai; giảm = ngược lại.
soft_penalty_cost: 200
# Khi search CẠN trong dải (OPEN rỗng trước giờ) hoặc 2D không nối trong dải: nhân bề rộng lên
# ngần này rồi thử lại, tối đa `max_widen` lần; hết nấc thì bỏ dải, chạy full với thời gian còn lại.
widen_factor: 2.0
max_widen: 1
# Phần `allocated_time` cấp cho pha có dải (0.05..1.0); phần còn lại để nới/fallback. HẾT GIỜ trong
# dải thì KHÔNG fallback (full còn chậm hơn) -> trả lỗi, nới allocated_time hoặc initial_epsilon.
budget_fraction: 0.6
# [bool] false CHỈ để đo (bench): cạn trong dải mà không còn nấc nới thì trả fail thay vì full.
fallback_full_search: true
# [bool] Nhóm log [debug/corridor]: graph nhận/từ chối lý do, gắn, tuyến, mask %, nới, tóm tắt
# mỗi lượt. Mặc định BẬT. Dòng LỖI (graph REJECTED, NO SOLUTION inside the corridor) không qua khoá này.
debug_corridor: true
# ===== Làm mượt path sau search: kéo dây + bo góc (2026-09-22) =====
# Đo trên sehc 22/9 (goal 100 m, dải soft, eps 1.5): path lattice dài hơn đường ngắn nhất 2D 12 %,
# 11 lần đổi chiều rẽ, 11 % chiều dài bỏ được nếu đi thẳng nơi đi thẳng được. Ba nguồn: ARA* dừng ở
# eps>1, dải Voronoi bám trục giữa, lưới 16 hướng làm đường xiên thành răng cưa. Smoother giữ TOPO
# của search (qua khe nào, né đảo bên nào) rồi kéo thẳng mọi đoạn footprint đi thẳng được trên
# costmap SỐNG, bo góc bằng cung bán kính cố định để tracker giữ tốc độ. Luật va chạm y hệt lattice:
# tâm robot không lên ô >= inscribed (253); ô >= cost tại bán kính ngoại tiếp thì xét cả footprint
# (không ô nào LETHAL). Path có đoạn lùi (cusp) KHÔNG làm mượt (giữ nguyên lattice). Chi phí ~10-30
# ms cho 100 m. Kết quả ghi ở dòng "metrics: ... smooth=on raw_m= smooth_ms= anchors= fillets=a/b".
smooth_path:
# [bool] Bật smoother. false = trả path lattice như cũ.
enabled: false
# [m] Cửa sổ kéo dây: từ mỗi mốc chỉ thử tới điểm cách tối đa ngần này THEO CHIỀU DÀI PATH lattice.
# Một đoạn vòng chỉ bị cắt khi cửa sổ phủ hết nó — 30 m đã để sót chữ V dài 33 m trên sehc
# (22/9). Tốn thời gian tuyến tính theo cửa sổ (~200 đoạn thử / mốc ở 80 m), giữ >= goal xa nhất.
max_shortcut_m: 80.0
# [m] Bán kính cung bo góc; nên = bán kính cung trong bộ mprim (diff_r106: 1.06 m) để tracker
# chạy hết tốc. 0 = mọi góc gãy (quay tại chỗ). Cung đè vật cản -> góc đó tự gãy.
fillet_radius_m: 1.06
# [m] Hai cạnh góc ngắn quá thì thu bán kính lại; dưới ngưỡng này thì để gãy (quay tại chỗ) thay
# vì cung tí hon. Đặt = 1/kappa mà base giữ được ở tốc độ danh định: Priest báo "kappa=1.25 1/m at
# 0.40 m/s" -> 0.8 m; cung R=0.4 (22/9) làm nó bò 0.20 m/s suốt cung.
min_fillet_radius_m: 0.8
# [0..252, thang costmap] Ô tâm có cost cao hơn = chặn với smoother (lattice cho tới 252).
# Hạ (vd 200) = đường kéo thẳng giữ khoảng cách với tường lớn hơn, bớt thẳng.
max_cell_cost: 252
# [m] Tâm robot phải cách ô LETHAL (đo bằng distance transform, không phụ thuộc inflation) ít
# nhất ngần này trên mọi đoạn kéo thẳng / cung bo. < 0 = tự lấy bán kính NGOẠI TIẾP footprint
# (T800: 0.755 m). Vì sao cần: kéo dây không nhìn cost nên cắt góc sát đúng mép inscribed
# (0.48 m) của costmap toàn cục; local costmap (laser, inflation 0.55/15) đặt 253 ngay đó ->
# Priest "blocked_ahead cost=253" -> detour -> ABORTED (sehc 22/9, mission 3, cụm cột (-40,-10)).
# Chỗ hẹp không giữ nổi khoảng này thì đoạn đó giữ nguyên path lattice. Tăng = an toàn hơn,
# ít cắt góc hơn; hạ dưới inscribed + 0.1 là mời lại lỗi trên.
min_clearance_m: -1.0
# [m] Khoảng cách pose trên path đầu ra (kiểm va chạm ở nửa bước này).
sample_step_m: 0.05
# [deg] Chỗ đoạn kéo thẳng nối vào đoạn path lattice giữ nguyên (không có chỗ bo cung), hướng
# đoạn thẳng chỉ được lệch heading lattice tối đa ngần này; điểm xa hơn mà lệch nhiều thì bỏ,
# lấy điểm gần hơn thẳng hàng. Không có điểm nào thẳng hàng thì lấy điểm xa nhất như thường.
# Vì sao: mối nối gãy 30-40 độ làm Priest đo kappa 2.3-2.6 và bò 0.2 m/s (sehc 22/9, cụm cột).
# 0 = tắt. Tăng = thẳng hơn nhưng nhiều mối gãy; giảm = ít cắt tắt hơn.
max_junction_deg: 20.0

View File

@@ -0,0 +1,34 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Exact squared Euclidean distance transform on a binary grid (Felzenszwalb & Huttenlocher,
* separable lower-envelope passes, O(w*h)). Used by the path smoother to answer "is the whole
* footprint clear here?" for free with a single lookup wherever the nearest obstacle is farther
* than the circumscribed radius, instead of rasterising the footprint at every sample.
*
* Author: DuongTD
*********************************************************************/
#ifndef SBPL_LATTICE_PLANNER_DISTANCE_MAP_H_
#define SBPL_LATTICE_PLANNER_DISTANCE_MAP_H_
#include <cstdint>
#include <vector>
namespace sbpl_lattice_planner
{
/**
* @brief Squared distance [cells^2] from every cell to the nearest cell with obstacle != 0.
* @param obstacle w*h, row-major (index = y*w + x), non-zero = obstacle.
* @param dist2 resized to w*h; a grid without obstacles gets kFarAway everywhere.
*/
void squaredDistanceTransform(const std::vector<uint8_t>& obstacle, int w, int h,
std::vector<float>& dist2);
/// Value stored where no obstacle exists within range (bigger than any real w*h distance).
constexpr float kFarAway = 1.0e12f;
} // namespace sbpl_lattice_planner
#endif // SBPL_LATTICE_PLANNER_DISTANCE_MAP_H_

View File

@@ -0,0 +1,127 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Shortcut + fillet smoother for lattice paths. Pure geometry: collision queries come in as
* callbacks so the class knows nothing about costmaps and can be unit-tested on a synthetic grid.
*
* Author: DuongTD
*********************************************************************/
#ifndef SBPL_LATTICE_PLANNER_PATH_SMOOTHER_H_
#define SBPL_LATTICE_PLANNER_PATH_SMOOTHER_H_
#include <cstddef>
#include <functional>
#include <vector>
namespace sbpl_lattice_planner
{
/// Pose on the path, world frame, [m] and [rad].
struct SmoothPose
{
double x = 0.0;
double y = 0.0;
double theta = 0.0;
};
/**
* @brief What a costmap cell means for the robot centre. Mirrors the lattice environment's own
* rule (EnvironmentNAVXYTHETALAT::GetActionCost): the centre may never stand on a cell at
* or above the inscribed cost; on cells at or above the "possibly circumscribed" cost the
* whole footprint has to be checked; below that the footprint is known to be clear.
*/
enum class CellClass
{
kBlocked, ///< centre may not be here (>= inscribed, lethal, unknown when not allowed, off-map)
kFree, ///< centre ok and footprint guaranteed clear
kNearObstacle ///< centre ok but footprint must be checked at this pose
};
struct SmootherConfig
{
bool enabled = false;
double max_shortcut_m = 80.0; ///< [m] longest straight segment tried (bounds the work)
double fillet_radius_m = 1.06; ///< [m] arc radius at corners; 0 = every corner sharp
double min_fillet_radius_m = 0.8; ///< [m] corner gets a sharp turn below this radius (1/kappa the base can hold at speed)
double sample_step_m = 0.05; ///< [m] output pose spacing
double check_step_m = 0.025; ///< [m] collision sampling along segments and arcs
double min_corner_deg = 3.0; ///< [deg] corners flatter than this get no fillet
/// [deg] Where a shortcut meets a stretch of untouched lattice path (no room for a fillet), the
/// chord may differ from the lattice heading by at most this much; a farther but misaligned
/// end point is skipped in favour of a nearer aligned one. 0 = off (farthest visible wins).
double max_junction_deg = 20.0;
};
struct SmootherStats
{
std::size_t in_pts = 0;
std::size_t out_pts = 0;
int anchors = 0; ///< polyline vertices after string-pulling (incl. both ends)
int fillets = 0; ///< corners that received an arc
int fillets_rejected = 0; ///< corners kept sharp: arc collided or segments too short
double in_len_m = 0.0;
double out_len_m = 0.0;
};
/**
* @class PathSmoother
* @brief Greedy line-of-sight shortcutting ("string pulling") of a dense path against the live
* costmap, then tangent-continuous fillet arcs at the remaining corners.
*
* Why: the lattice search returns the cheapest chain of motion primitives inside whatever it was
* allowed to explore (an eps>1 anytime bound, a Voronoi corridor, 16 discrete headings). All three
* leave visible detours where the floor is open — a 12 % longer path with 11 wiggles on a 100 m
* goal in the 2026-09-22 measurements. The smoother keeps the search's topology (which gap, which
* side of an island) and straightens everything the footprint can actually cross.
*
* Contract:
* - Output starts at the input's first point with the heading of the first straight run, ends
* at the input's last point with the input's final heading (goal yaw).
* - Every sampled pose is collision-free under the same rule as the lattice (see CellClass).
* - Sharp corners keep a duplicate position with two headings — the local planner turns in
* place there, exactly as it does for lattice turn-in-place primitives.
* - Paths containing reverse motion are returned untouched (false): shortcutting across a cusp
* would silently turn a planned reverse into a forward drive.
*/
class PathSmoother
{
public:
using CellQuery = std::function<CellClass(double x, double y)>;
using PoseQuery = std::function<bool(double x, double y, double theta)>; ///< footprint clear?
PathSmoother(const SmootherConfig& cfg, CellQuery cell, PoseQuery pose);
/**
* @brief Smooth @p in into @p out. Returns false (and leaves @p out empty) when the input is
* too short, contains reverse motion, or the first segment could not even be verified —
* the caller keeps the lattice path in that case.
*/
bool smooth(const std::vector<SmoothPose>& in, std::vector<SmoothPose>& out,
SmootherStats* stats = nullptr) const;
/// Straight segment a->b (world) free for the footprint? Exposed for tests.
bool segmentFree(const SmoothPose& a, const SmoothPose& b) const;
private:
/// Pose free for the footprint under the lattice rule (centre class, then footprint if needed).
bool poseFree(double x, double y, double theta) const;
/// Arc from @p from, centre @p c, radius @p r, sweeping @p sweep [rad] (signed). Samples at
/// check_step_m. When @p out is given the samples (excluding the last) are appended at
/// sample_step_m.
bool arcFree(double cx, double cy, double r, double a0, double sweep) const;
void appendArc(double cx, double cy, double r, double a0, double sweep,
std::vector<SmoothPose>& out) const;
void appendSegment(const SmoothPose& a, const SmoothPose& b, std::vector<SmoothPose>& out) const;
SmootherConfig cfg_;
CellQuery cell_;
PoseQuery pose_;
};
/// Sum of segment lengths [m].
double pathLength(const std::vector<SmoothPose>& p);
} // namespace sbpl_lattice_planner
#endif // SBPL_LATTICE_PLANNER_PATH_SMOOTHER_H_

View File

@@ -2,7 +2,9 @@
#define SBPL_LATTICE_PLANNER_H #define SBPL_LATTICE_PLANNER_H
#include <atomic> #include <atomic>
#include <cstdint>
#include <iostream> #include <iostream>
#include <string>
#include <vector> #include <vector>
using namespace std; using namespace std;
@@ -22,10 +24,19 @@ using namespace std;
#include <robot_nav_core/base_global_planner.h> #include <robot_nav_core/base_global_planner.h>
#include <robot_nav_core/preemptable.h> #include <robot_nav_core/preemptable.h>
// route graph corridor (2026-09-21): graph injected by the host through the shared sensor store
#include <robot_sensor_ports/sensor_consumer.h>
#include <robot_sensor_ports/sensor_reader.h>
#include <route_graph/corridor.h>
#include <route_graph/graph.h>
#include "sbpl_lattice_planner/path_smoother.h"
namespace sbpl_lattice_planner{ namespace sbpl_lattice_planner{
class SBPLLatticePlanner : public robot_nav_core::BaseGlobalPlanner, class SBPLLatticePlanner : public robot_nav_core::BaseGlobalPlanner,
public robot_nav_core::Preemptable { public robot_nav_core::Preemptable,
public robot_sensor_ports::SensorConsumer {
public: public:
/** /**
@@ -89,6 +100,12 @@ public:
*/ */
void setExternalGrid(const robot_costmap_2d::Costmap2D* grid); void setExternalGrid(const robot_costmap_2d::Costmap2D* grid);
/**
* @brief Nhận cổng đọc kho cảm biến dùng chung (robot_sensor_ports::SensorConsumer). PlannerRunner
* gọi TRƯỚC initialize(); null = không có kho -> corridor không bao giờ bật.
*/
void setSensorReader(const robot_sensor_ports::SensorReader* reader) override;
virtual ~SBPLLatticePlanner(){}; virtual ~SBPLLatticePlanner(){};
static robot_nav_core::BaseGlobalPlanner::Ptr create(); static robot_nav_core::BaseGlobalPlanner::Ptr create();
@@ -117,6 +134,17 @@ private:
double allocated_time_; /**< amount of time allowed for search */ double allocated_time_; /**< amount of time allowed for search */
double initial_epsilon_; /**< initial epsilon for beginning the anytime search */ double initial_epsilon_; /**< initial epsilon for beginning the anytime search */
// ---- Anytime đúng nghĩa (pha 0, 2026-09-21): replan() qua ReplanParams thay vì replan(double) --
// replan(double) cũ = eps đặt một lần, chạy tới eps=1.0 hoặc hết giờ: eps 1.0 là A* thuần, goal xa
// nở hàng triệu state. Với ReplanParams: nghiệm đầu ở initial_epsilon (nhanh), rồi hạ dần eps_step
// tới final_epsilon chừng nào tổng thời gian còn < repair_time. Lưu ý ARA* đo bằng clock() = CPU
// time CẢ tiến trình, nên ngân sách tính theo wall ngắn hơn khi thread khác bận.
double final_epsilon_; /**< eps dừng hạ; 1.0 = tối ưu, >1 = chấp nhận sub-optimal chừng đó */
double eps_step_; /**< mỗi vòng ARA* hạ eps đi ngần này */
double repair_time_; /**< [s] sau khi có nghiệm đầu, tổng thời gian tối đa còn được hạ eps; <= 0 = tới hết ngân sách */
bool return_first_solution_; /**< true = trả ngay nghiệm đầu (eps = initial), không hạ eps */
/// @brief Tham số cho một lượt replan với ngân sách @p budget_s, từ 4 khoá trên.
ReplanParams makeReplanParams(double budget_s) const;
std::string environment_type_; /** what type of environment in which to plan. choices are 2D and XYThetaLattice. */ std::string environment_type_; /** what type of environment in which to plan. choices are 2D and XYThetaLattice. */
std::string cost_map_topic_; /** what topic is being used for the costmap topic */ std::string cost_map_topic_; /** what topic is being used for the costmap topic */
@@ -177,6 +205,76 @@ private:
/// @return lưới đang có hiệu lực: lưới ngoài nếu được nạp, không thì lưới sống của costmap. /// @return lưới đang có hiệu lực: lưới ngoài nếu được nạp, không thì lưới sống của costmap.
const robot_costmap_2d::Costmap2D* activeGrid() const; const robot_costmap_2d::Costmap2D* activeGrid() const;
// ---- Route graph corridor (2026-09-21) --------------------------------------------------------
// Graph tuyến (Voronoi) do host biên dịch sẵn từ map và tiêm vào kho `robot_sensor_ports`. Planner
// KHÔNG dựng graph; chỉ nhận, đối chiếu với static layer (kích thước + hash mask vật cản) rồi dùng
// để khoanh vùng tìm kiếm cho goal xa: ô ngoài dải quanh tuyến nhận cost INSCRIBED (không lethal),
// search + heuristic 2D của SBPL tự giới hạn trong dải. Không graph / lệch map = chạy full như cũ.
/// Config khối `voronoi_corridor` trong YAML. Đơn vị mét, quy ra ô lúc initialize().
struct CorridorConfig
{
bool enabled = false; ///< Bật/tắt toàn bộ cơ chế.
std::string route_graph_topic = "/route_graph"; ///< Khoá kho, trùng sensor_store_params.yaml.
std::string static_layer_name; ///< Rỗng = StaticLayer đầu tiên theo kiểu; đặt tên khi có nhiều.
double min_range_m = 15.0; ///< [m] Goal gần hơn -> không dùng dải.
double half_width_m = 1.5; ///< [m] Nửa bề rộng tối thiểu của dải.
double clearance_scale = 0.8; ///< Nửa bề rộng = max(min, scale × clearance tuyến).
double max_half_width_m = 6.0; ///< [m] Trần nửa bề rộng.
double attach_max_radius_m = 10.0; ///< [m] Bán kính BFS gắn start/goal vào graph.
double route_min_clearance_m = -1.0; ///< [m] Edge hẹp hơn không đi; < 0 = bán kính nội tiếp footprint.
std::string outside_mode = "hard"; ///< hard: ngoài dải = inscribed (chặn); soft: chỉ phạt cost.
int soft_penalty_cost = 200; ///< [0..252, thang costmap] cost ô ngoài dải khi soft.
double widen_factor = 2.0; ///< Nhân bề rộng mỗi lần nới khi search cạn.
int max_widen = 1; ///< Số lần nới tối đa trước khi bỏ dải.
double budget_fraction = 0.6; ///< Phần allocated_time cấp cho pha có dải.
bool fallback_full_search = true; ///< false CHỈ để đo: cạn trong dải thì trả fail luôn.
bool debug_corridor = true; ///< Nhóm log [debug/corridor].
};
/// Kết quả một lần dựng dải, để log và để bench đọc.
struct CorridorStats
{
bool active = false;
bool graph_from_store = false;
bool attach_start_ok = false, attach_goal_ok = false;
std::size_t route_cells = 0;
double route_length_m = 0.0;
double route_min_clearance_m = 0.0; ///< Ngưỡng đã dùng để lọc edge hẹp.
std::size_t mask_cells = 0;
int widen_level = 0;
double build_ms = 0.0;
};
/**
* @brief Đọc kho: có bản RouteGraph mới thì đối chiếu với static layer sống (version, kích thước,
* resolution, origin, map_hash theo luật trong `source`) và nhận nếu khớp. Gọi ở cuối
* initialize() và đầu mỗi makePlan; không có bản mới thì rẻ (một lần so cursor).
* Lệch -> log LỖI (không tắt được) một lần cho bản đó, corridor tắt.
*/
void tryAdoptRouteGraph();
/// @return static layer của global costmap (lớp nguồn của graph), null nếu không có.
const robot_costmap_2d::Costmap2D* staticLayerGrid() const;
/**
* @brief Dựng dải cho lượt này: gắn start/goal vào graph, Dijkstra, đóng dấu mask với nửa bề rộng
* `half_width_m × widen_factor^widen_level`. Ghi vào corridor_mask_ (rỗng = không dải).
* @return true khi có dải.
*/
bool buildCorridor(const robot_costmap_2d::Costmap2D* grid, unsigned int sx, unsigned int sy,
unsigned int gx, unsigned int gy, int widen_level, CorridorStats& stats);
CorridorConfig corridor_cfg_;
const robot_sensor_ports::SensorReader* sensors_ = nullptr; ///< Non-owning, có thể null.
uint64_t route_graph_cursor_ = 0; ///< Cursor kho: chỉ xử lý bản mới hơn.
route_graph::Graph route_graph_; ///< Graph đã nhận; rỗng = chưa có / bị từ chối.
bool route_graph_ready_ = false;
std::vector<uint8_t> corridor_mask_; ///< 1 = trong dải; rỗng = không dải cho lượt này.
unsigned char masked_cost_ = 0; ///< Cost SBPL gán cho ô ngoài dải (hard: inscribed; soft: phạt).
bool corridor_hard_ = true; ///< outside_mode == hard.
CorridorStats last_corridor_;
std::string name_; std::string name_;
robot_costmap_2d::Costmap2DROBOT* costmap_robot_; /**< manages the cost map for us */ robot_costmap_2d::Costmap2DROBOT* costmap_robot_; /**< manages the cost map for us */
const robot_costmap_2d::Costmap2D* external_grid_; /**< non-owning; NULL = dùng lưới sống */ const robot_costmap_2d::Costmap2D* external_grid_; /**< non-owning; NULL = dùng lưới sống */
@@ -184,6 +282,19 @@ private:
std::vector<robot_geometry_msgs::Point> footprint_prev_; std::vector<robot_geometry_msgs::Point> footprint_prev_;
unsigned int current_env_width_; unsigned int current_env_width_;
unsigned int current_env_height_; unsigned int current_env_height_;
/**
* @brief Post-search smoothing (khối YAML `smooth_path`): kéo dây (line-of-sight) rồi bo góc bằng
* cung R cố định trên costmap SỐNG, luật va chạm y hệt lattice (tâm < inscribed, footprint
* khi ô >= circumscribed). Sửa "đi thẳng được mà ngoằn ngoèo" do eps>1, dải Voronoi và lưới
* 16 hướng để lại. Path lùi (cusp) không được làm mượt.
*/
SmootherConfig smoother_cfg_;
int smoother_max_cell_cost_ = 252; /**< [thang costmap] ô tâm có cost cao hơn = chặn với smoother */
double smoother_min_clearance_m_ = -1.0; /**< [m] tâm phải cách ô LETHAL ít nhất ngần này (EDT); <0 = bán kính ngoại tiếp */
/// Chạy smoother trên @p sbpl_path (toạ độ tương đối origin lưới); trả false = giữ path lattice.
bool smoothLatticePath(const robot_costmap_2d::Costmap2D* grid,
std::vector<EnvNAVXYTHETALAT3Dpt_t>& sbpl_path, SmootherStats* stats) const;
}; };
}; };

View File

@@ -90,4 +90,11 @@
<build_depend>sbpl</build_depend> <build_depend>sbpl</build_depend>
<run_depend>sbpl</run_depend> <run_depend>sbpl</run_depend>
<!-- Route graph corridor (2026-09-21): graph tiêm qua kho robot_sensor_ports, thuật toán ở route_graph. -->
<build_depend>robot_sensor_ports</build_depend>
<run_depend>robot_sensor_ports</run_depend>
<build_depend>route_graph</build_depend>
<run_depend>route_graph</run_depend>
</package> </package>

78
src/distance_map.cpp Normal file
View File

@@ -0,0 +1,78 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Author: DuongTD
*********************************************************************/
#include "sbpl_lattice_planner/distance_map.h"
#include <algorithm>
#include <limits>
namespace sbpl_lattice_planner
{
namespace
{
/// 1-D squared distance transform of f (sampled on 0..n-1) into d: d[q] = min_p (q-p)^2 + f[p].
/// v/z are scratch of size n and n+1. Felzenszwalb & Huttenlocher 2012, "Distance Transforms of
/// Sampled Functions", lower envelope of parabolas.
void transform1d(const float* f, int n, float* d, int* v, float* z)
{
int k = 0;
v[0] = 0;
z[0] = -std::numeric_limits<float>::infinity();
z[1] = std::numeric_limits<float>::infinity();
for (int q = 1; q < n; ++q) {
float s = ((f[q] + static_cast<float>(q) * q) - (f[v[k]] + static_cast<float>(v[k]) * v[k])) /
(2.0f * q - 2.0f * v[k]);
while (s <= z[k]) {
--k;
s = ((f[q] + static_cast<float>(q) * q) - (f[v[k]] + static_cast<float>(v[k]) * v[k])) /
(2.0f * q - 2.0f * v[k]);
}
++k;
v[k] = q;
z[k] = s;
z[k + 1] = std::numeric_limits<float>::infinity();
}
k = 0;
for (int q = 0; q < n; ++q) {
while (z[k + 1] < static_cast<float>(q)) ++k;
const float dq = static_cast<float>(q - v[k]);
d[q] = dq * dq + f[v[k]];
}
}
} // namespace
void squaredDistanceTransform(const std::vector<uint8_t>& obstacle, int w, int h,
std::vector<float>& dist2)
{
dist2.assign(static_cast<std::size_t>(w) * h, kFarAway);
if (w <= 0 || h <= 0) return;
// kFarAway (not infinity) keeps f[q] + q^2 finite so the parabola intersections stay defined.
for (std::size_t i = 0; i < obstacle.size() && i < dist2.size(); ++i)
if (obstacle[i]) dist2[i] = 0.0f;
const int n = std::max(w, h);
std::vector<float> f(n), d(n), z(n + 1);
std::vector<int> v(n);
// Columns first: distance along y to the nearest obstacle in the same column.
for (int x = 0; x < w; ++x) {
for (int y = 0; y < h; ++y) f[y] = dist2[static_cast<std::size_t>(y) * w + x];
transform1d(f.data(), h, d.data(), v.data(), z.data());
for (int y = 0; y < h; ++y) dist2[static_cast<std::size_t>(y) * w + x] = d[y];
}
// Then rows: combine with the distance along x.
for (int y = 0; y < h; ++y) {
float* row = dist2.data() + static_cast<std::size_t>(y) * w;
for (int x = 0; x < w; ++x) f[x] = row[x];
transform1d(f.data(), w, d.data(), v.data(), z.data());
for (int x = 0; x < w; ++x) row[x] = std::min(d[x], kFarAway);
}
}
} // namespace sbpl_lattice_planner

315
src/path_smoother.cpp Normal file
View File

@@ -0,0 +1,315 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Author: DuongTD
*********************************************************************/
#include "sbpl_lattice_planner/path_smoother.h"
#include <algorithm>
#include <cmath>
#include <utility>
namespace sbpl_lattice_planner
{
namespace
{
constexpr double kEps = 1e-9;
constexpr double kMaxFilletCornerDeg = 170.0; // beyond this tan(theta/2) explodes: turn in place
double dist(const SmoothPose& a, const SmoothPose& b)
{
return std::hypot(b.x - a.x, b.y - a.y);
}
double wrapAngle(double a)
{
return std::remainder(a, 2.0 * M_PI);
}
} // namespace
double pathLength(const std::vector<SmoothPose>& p)
{
double len = 0.0;
for (std::size_t i = 1; i < p.size(); ++i) len += dist(p[i - 1], p[i]);
return len;
}
PathSmoother::PathSmoother(const SmootherConfig& cfg, CellQuery cell, PoseQuery pose)
: cfg_(cfg), cell_(std::move(cell)), pose_(std::move(pose))
{
}
bool PathSmoother::poseFree(double x, double y, double theta) const
{
switch (cell_(x, y)) {
case CellClass::kBlocked: return false;
case CellClass::kFree: return true;
case CellClass::kNearObstacle: return pose_ ? pose_(x, y, theta) : false;
}
return false;
}
bool PathSmoother::segmentFree(const SmoothPose& a, const SmoothPose& b) const
{
// Two passes: the centre test is one cell lookup, the footprint test hundreds. Candidates that
// fail on the centre (most of them during the downward scan) never pay for the footprint.
const double len = dist(a, b);
const double theta = std::atan2(b.y - a.y, b.x - a.x);
const int n = std::max(1, static_cast<int>(std::ceil(len / cfg_.check_step_m)));
bool near = false;
for (int s = 0; s <= n; ++s) {
const double f = static_cast<double>(s) / n;
const CellClass c = cell_(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f);
if (c == CellClass::kBlocked) return false;
near |= c == CellClass::kNearObstacle;
}
if (!near) return true;
if (!pose_) return false;
// Footprint at sample_step_m: two placements 5 cm apart overlap almost entirely, so no cell of
// the swept area is skipped; check_step_m would double the cost for nothing.
const int m = std::max(1, static_cast<int>(std::ceil(len / cfg_.sample_step_m)));
for (int s = 0; s <= m; ++s) {
const double f = static_cast<double>(s) / m;
const double x = a.x + (b.x - a.x) * f;
const double y = a.y + (b.y - a.y) * f;
if (cell_(x, y) == CellClass::kNearObstacle && !pose_(x, y, theta)) return false;
}
return true;
}
bool PathSmoother::arcFree(double cx, double cy, double r, double a0, double sweep) const
{
const double side = sweep >= 0.0 ? 1.0 : -1.0;
const int n = std::max(1, static_cast<int>(std::ceil(std::fabs(sweep) * r / cfg_.check_step_m)));
bool near = false;
for (int s = 0; s <= n; ++s) {
const double a = a0 + sweep * static_cast<double>(s) / n;
const CellClass c = cell_(cx + r * std::cos(a), cy + r * std::sin(a));
if (c == CellClass::kBlocked) return false;
near |= c == CellClass::kNearObstacle;
}
if (!near) return true;
if (!pose_) return false;
const int m = std::max(1, static_cast<int>(std::ceil(std::fabs(sweep) * r / cfg_.sample_step_m)));
for (int s = 0; s <= m; ++s) {
const double a = a0 + sweep * static_cast<double>(s) / m;
const double x = cx + r * std::cos(a);
const double y = cy + r * std::sin(a);
if (cell_(x, y) == CellClass::kNearObstacle && !pose_(x, y, wrapAngle(a + side * M_PI / 2.0)))
return false;
}
return true;
}
void PathSmoother::appendArc(double cx, double cy, double r, double a0, double sweep,
std::vector<SmoothPose>& out) const
{
const double side = sweep >= 0.0 ? 1.0 : -1.0;
const int n = std::max(1, static_cast<int>(std::ceil(std::fabs(sweep) * r / cfg_.sample_step_m)));
for (int s = 0; s < n; ++s) { // end point belongs to the next piece
const double a = a0 + sweep * static_cast<double>(s) / n;
out.push_back({cx + r * std::cos(a), cy + r * std::sin(a), wrapAngle(a + side * M_PI / 2.0)});
}
}
void PathSmoother::appendSegment(const SmoothPose& a, const SmoothPose& b,
std::vector<SmoothPose>& out) const
{
const double len = dist(a, b);
if (len < kEps) return;
const double theta = std::atan2(b.y - a.y, b.x - a.x);
const int n = std::max(1, static_cast<int>(std::ceil(len / cfg_.sample_step_m)));
for (int s = 0; s < n; ++s) { // end point belongs to the next piece
const double f = static_cast<double>(s) / n;
out.push_back({a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f, theta});
}
}
bool PathSmoother::smooth(const std::vector<SmoothPose>& in, std::vector<SmoothPose>& out,
SmootherStats* stats) const
{
out.clear();
SmootherStats st;
st.in_pts = in.size();
st.in_len_m = pathLength(in);
if (stats) *stats = st;
if (in.size() < 3) return false;
// 1. Distinct positions only (turn-in-place primitives repeat a position with new headings),
// and refuse anything driven in reverse: a shortcut across a cusp would flip it to forward.
std::vector<SmoothPose> pts;
pts.reserve(in.size());
pts.push_back(in.front());
for (std::size_t i = 1; i < in.size(); ++i) {
const SmoothPose& prev = pts.back();
const double dx = in[i].x - prev.x;
const double dy = in[i].y - prev.y;
if (std::hypot(dx, dy) < 1e-6) continue;
// Heading at the START of the step decides direction: the last pose may carry the goal yaw,
// which can differ from the arrival direction by more than 90 deg without any reversing.
if (dx * std::cos(prev.theta) + dy * std::sin(prev.theta) < 0.0) return false;
pts.push_back(in[i]);
}
if (pts.size() < 2) return false;
std::vector<double> cum(pts.size(), 0.0);
for (std::size_t i = 1; i < pts.size(); ++i) cum[i] = cum[i - 1] + dist(pts[i - 1], pts[i]);
// 2. String pulling: from each anchor take the farthest point (within max_shortcut_m of path
// length) whose straight segment is free. Visibility is not monotonic in j, so scan downward
// and take the first hit — coarsely (kScanStrideM) first, then refine inside the last stride
// so a 30 m window costs ~80 segment tests instead of 600. If even the next point fails
// (the lattice validated it by its own sampling of primitive cells, ours is finer) keep the
// original step: never worse than the input.
// Junctions (2026-09-22, sehc pillar field): a shortcut that lands on a stretch of untouched
// lattice path has no room for a fillet there, so the chord must already point roughly along
// the lattice heading (max_junction_deg) — otherwise the tracker sees a kink and crawls
// (Priest: kappa 2.3-2.6 -> 0.2 m/s). Aligned end points are preferred; only when none is
// visible does the farthest visible one win.
constexpr double kScanStrideM = 0.4;
const double spacing = pts.size() > 1 ? cum.back() / static_cast<double>(pts.size() - 1) : 1.0;
const std::size_t stride = std::max<std::size_t>(1, static_cast<std::size_t>(kScanStrideM / std::max(spacing, 1e-3)));
const double max_junction = cfg_.max_junction_deg * M_PI / 180.0;
const std::size_t last = pts.size() - 1;
// Chord a->b vs the lattice heading stored at k. The two ends of the path are exempt: the start
// heading is whatever free_start_heading assumed, the goal yaw is reached by turning in place.
const auto aligned = [&](std::size_t a, std::size_t b, std::size_t k) {
if (max_junction <= 0.0 || k == 0 || k == last) return true;
const double chord = std::atan2(pts[b].y - pts[a].y, pts[b].x - pts[a].x);
return std::fabs(wrapAngle(pts[k].theta - chord)) <= max_junction;
};
std::vector<std::size_t> anchors;
anchors.push_back(0);
std::size_t i = 0;
bool prev_was_step = false; // anchor i is the end of an untouched lattice stretch
std::vector<signed char> visible; // per candidate j, cached across the two passes: -1 unknown
while (i < last) {
std::size_t j_max = i + 1;
while (j_max < last && cum[j_max + 1] - cum[i] <= cfg_.max_shortcut_m) ++j_max;
visible.assign(j_max - i + 1, -1);
const auto is_visible = [&](std::size_t j) {
signed char& v = visible[j - i];
if (v < 0) v = segmentFree(pts[i], pts[j]) ? 1 : 0;
return v == 1;
};
const auto ok = [&](std::size_t j, bool need_align) {
if (!is_visible(j)) return false;
if (!need_align) return true;
return aligned(i, j, j) && (!prev_was_step || aligned(i, j, i));
};
// Coarse scan downward for the first acceptable j, then refine upward inside the last stride.
const auto scan = [&](bool need_align) -> std::size_t {
for (std::size_t j = j_max; j > i + 1; j = (j > i + 1 + stride) ? j - stride : i + 1) {
if (!ok(j, need_align)) continue;
std::size_t best = j;
const std::size_t top = std::min(j_max, j + stride - 1);
for (std::size_t jj = top; jj > j; --jj) {
if (ok(jj, need_align)) { best = jj; break; }
}
return best;
}
return 0;
};
std::size_t hit = scan(true);
if (hit == 0) hit = scan(false);
if (hit == 0) hit = i + 1; // fallback: the original step
prev_was_step = (hit == i + 1);
anchors.push_back(hit);
i = hit;
}
st.anchors = static_cast<int>(anchors.size());
// 3. Fillets at interior anchors. Each corner may use at most half of either adjacent segment
// so two fillets never overlap; the radius shrinks to fit, below min_fillet_radius_m the
// corner stays sharp (duplicate position, two headings = turn in place for the tracker).
struct Fillet
{
bool on = false;
SmoothPose a, b; // tangent points on the incoming / outgoing segment
double cx = 0.0, cy = 0.0, r = 0.0, a0 = 0.0, sweep = 0.0;
};
std::vector<Fillet> fillets(anchors.size());
const double min_corner = cfg_.min_corner_deg * M_PI / 180.0;
const double max_corner = kMaxFilletCornerDeg * M_PI / 180.0;
for (std::size_t k = 1; k + 1 < anchors.size(); ++k) {
const SmoothPose& p0 = pts[anchors[k - 1]];
const SmoothPose& p1 = pts[anchors[k]];
const SmoothPose& p2 = pts[anchors[k + 1]];
const double l_in = dist(p0, p1);
const double l_out = dist(p1, p2);
if (l_in < kEps || l_out < kEps || cfg_.fillet_radius_m <= 0.0) continue;
const double d1x = (p1.x - p0.x) / l_in, d1y = (p1.y - p0.y) / l_in;
const double d2x = (p2.x - p1.x) / l_out, d2y = (p2.y - p1.y) / l_out;
const double cross = d1x * d2y - d1y * d2x;
const double theta = std::acos(std::max(-1.0, std::min(1.0, d1x * d2x + d1y * d2y)));
if (theta < min_corner || theta > max_corner) continue; // straight-ish or U-turn
const double tan_half = std::tan(theta / 2.0);
double r = cfg_.fillet_radius_m;
double t = r * tan_half;
const double t_max = 0.5 * std::min(l_in, l_out);
if (t > t_max) {
r = t_max / tan_half;
t = t_max;
}
if (r < cfg_.min_fillet_radius_m) {
++st.fillets_rejected;
continue;
}
const double side = cross >= 0.0 ? 1.0 : -1.0;
Fillet f;
f.a = {p1.x - d1x * t, p1.y - d1y * t, std::atan2(d1y, d1x)};
f.b = {p1.x + d2x * t, p1.y + d2y * t, std::atan2(d2y, d2x)};
f.cx = f.a.x - side * d1y * r; // left normal of d1 is (-d1y, d1x)
f.cy = f.a.y + side * d1x * r;
f.r = r;
f.a0 = std::atan2(f.a.y - f.cy, f.a.x - f.cx);
f.sweep = side * theta;
if (!arcFree(f.cx, f.cy, f.r, f.a0, f.sweep)) {
++st.fillets_rejected;
continue;
}
f.on = true;
fillets[k] = f;
++st.fillets;
}
// 4. Assemble: segment -> (arc | sharp corner) -> segment ... -> goal with the input's final yaw.
SmoothPose cur = pts[anchors[0]];
cur.theta = std::atan2(pts[anchors[1]].y - cur.y, pts[anchors[1]].x - cur.x);
for (std::size_t k = 1; k < anchors.size(); ++k) {
const SmoothPose& v = pts[anchors[k]];
if (k + 1 == anchors.size()) {
appendSegment(cur, v, out);
break;
}
if (fillets[k].on) {
const Fillet& f = fillets[k];
appendSegment(cur, f.a, out);
appendArc(f.cx, f.cy, f.r, f.a0, f.sweep, out);
cur = f.b;
continue;
}
const SmoothPose& next = pts[anchors[k + 1]];
const double h_in = std::atan2(v.y - cur.y, v.x - cur.x);
const double h_out = std::atan2(next.y - v.y, next.x - v.x);
appendSegment(cur, v, out);
if (std::fabs(wrapAngle(h_out - h_in)) >= min_corner) {
out.push_back({v.x, v.y, h_in}); // arrive, then turn in place (next piece starts with h_out)
}
cur = v;
cur.theta = h_out;
}
SmoothPose goal = in.back();
out.push_back(goal);
st.out_pts = out.size();
st.out_len_m = pathLength(out);
if (stats) *stats = st;
return true;
}
} // namespace sbpl_lattice_planner

View File

@@ -36,6 +36,7 @@
*********************************************************************/ *********************************************************************/
#include <sbpl_lattice_planner/sbpl_lattice_planner.h> #include <sbpl_lattice_planner/sbpl_lattice_planner.h>
#include <sbpl_lattice_planner/distance_map.h>
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
@@ -44,9 +45,17 @@
#include <dlfcn.h> #include <dlfcn.h>
#include <unistd.h> #include <unistd.h>
#include <chrono>
#include <typeinfo>
#include <robot_nav_msgs/Path.h> #include <robot_nav_msgs/Path.h>
#include <robot_costmap_2d/costmap_layer.h>
#include <robot_costmap_2d/inflation_layer.h> #include <robot_costmap_2d/inflation_layer.h>
#include <robot_costmap_2d/layered_costmap.h>
#include <robot_sensor_msgs/RouteGraph.h>
#include <robot_sensor_ports/sensor_types.h> // SensorType<RouteGraph> specialisation for latest<>()
#include <route_graph/map_hash.h>
#include <tf3/LinearMath/Quaternion.h> #include <tf3/LinearMath/Quaternion.h>
#include <boost/dll/alias.hpp> #include <boost/dll/alias.hpp>
@@ -100,10 +109,206 @@ void SBPLLatticePlanner::setExternalGrid(const robot_costmap_2d::Costmap2D* grid
external_grid_ = grid; external_grid_ = grid;
} }
ReplanParams SBPLLatticePlanner::makeReplanParams(double budget_s) const{
ReplanParams p(budget_s);
p.initial_eps = initial_epsilon_;
p.final_eps = final_epsilon_;
p.dec_eps = eps_step_;
p.return_first_solution = return_first_solution_;
// ARA* đếm repair_time từ lúc BẮT ĐẦU search (không phải từ nghiệm đầu) và chỉ áp khi > 0.
p.repair_time = repair_time_ > 0.0 ? std::min(repair_time_, budget_s) : -1.0;
return p;
}
const robot_costmap_2d::Costmap2D* SBPLLatticePlanner::activeGrid() const{ const robot_costmap_2d::Costmap2D* SBPLLatticePlanner::activeGrid() const{
return external_grid_ != NULL ? external_grid_ : costmap_robot_->getCostmap(); return external_grid_ != NULL ? external_grid_ : costmap_robot_->getCostmap();
} }
// ================================================================================================
// Route graph corridor (2026-09-21)
// ================================================================================================
void SBPLLatticePlanner::setSensorReader(const robot_sensor_ports::SensorReader* reader){
sensors_ = reader;
}
const robot_costmap_2d::Costmap2D* SBPLLatticePlanner::staticLayerGrid() const{
if (costmap_robot_ == NULL || costmap_robot_->getLayeredCostmap() == NULL) return NULL;
// Nhận diện theo KIỂU, không theo tên: tên plugin là do YAML đặt (`navigation_map`,
// `static_layer`, `virtual_walls_map`...) và mỗi cây config một khác. Không dynamic_cast<StaticLayer*>
// được vì class đó nằm trong libplugins.so mà plugin này không link — nhưng typeid(*plugin).name()
// của object đa hình vẫn trả tên mangled ("...robot_costmap_2d11StaticLayerE") qua ranh giới .so.
// CostmapLayer (lớp cha, trong librobot_costmap_2d) thì cast được để lấy char map.
// Có nhiều StaticLayer (map + tường ảo): lấy layer ĐẦU TIÊN theo thứ tự plugins (map luôn đứng
// trước), trừ khi `static_layer_name` chỉ đích danh.
const std::string& want = corridor_cfg_.static_layer_name;
for (const auto& plugin : *costmap_robot_->getLayeredCostmap()->getPlugins()) {
if (!plugin) continue;
const std::string& n = plugin->getName();
if (!want.empty()) {
const std::string suffix = "/" + want;
const bool named = n == want ||
(n.size() > suffix.size() && n.compare(n.size() - suffix.size(), suffix.size(), suffix) == 0);
if (!named) continue;
}
else if (std::string(typeid(*plugin).name()).find("StaticLayer") == std::string::npos) {
continue;
}
const auto* layer = dynamic_cast<const robot_costmap_2d::CostmapLayer*>(plugin.get());
if (layer != NULL) return layer;
}
return NULL;
}
void SBPLLatticePlanner::tryAdoptRouteGraph(){
if (!corridor_cfg_.enabled || sensors_ == NULL || corridor_cfg_.route_graph_topic.empty()) return;
const boost::shared_ptr<const robot_sensor_msgs::RouteGraph> msg =
robot_sensor_ports::latest<robot_sensor_msgs::RouteGraph>(*sensors_, corridor_cfg_.route_graph_topic,
route_graph_cursor_);
if (!msg) return; // không có bản mới hơn cursor: giữ nguyên trạng thái hiện tại
// Có bản mới: bản cũ (nếu có) hết hiệu lực ngay, dù bản mới có bị từ chối — "map mới thì graph mới".
route_graph_ready_ = false;
route_graph_.clear();
const robot_costmap_2d::Costmap2D* sl = staticLayerGrid();
if (sl == NULL) {
std::string names;
for (const auto& plugin : *costmap_robot_->getLayeredCostmap()->getPlugins())
if (plugin) names += (names.empty() ? "" : ", ") + plugin->getName() + " (" + typeid(*plugin).name() + ")";
robot::log_error("[sbpl_lattice_planner] route graph on '%s' received but no StaticLayer was found in "
"the global costmap to check it against%s%s — graph REJECTED, corridor off. Layers: %s",
corridor_cfg_.route_graph_topic.c_str(),
corridor_cfg_.static_layer_name.empty() ? "" : " under static_layer_name=",
corridor_cfg_.static_layer_name.c_str(), names.c_str());
return;
}
const unsigned int w = sl->getSizeInCellsX(), h = sl->getSizeInCellsY();
if (msg->width != w || msg->height != h ||
std::fabs(msg->resolution - sl->getResolution()) > 1e-6 ||
std::fabs(msg->origin_x - sl->getOriginX()) > 0.5 * sl->getResolution() ||
std::fabs(msg->origin_y - sl->getOriginY()) > 0.5 * sl->getResolution()) {
robot::log_error("[sbpl_lattice_planner] route graph REJECTED: it describes a %ux%u @ %.3f m grid at "
"(%.2f, %.2f) but the static layer is %ux%u @ %.3f m at (%.2f, %.2f). Rebuild the "
"graph for this map (voronoi_route_compile). Corridor off.",
msg->width, msg->height, msg->resolution, msg->origin_x, msg->origin_y, w, h,
sl->getResolution(), sl->getOriginX(), sl->getOriginY());
return;
}
route_graph::ObstacleRule rule;
if (!route_graph::parseSourceRule(msg->source, &rule)) {
robot::log_error("[sbpl_lattice_planner] route graph REJECTED: cannot parse its obstacle rule "
"source='%s' (expected costmap:lethal>=..;..;unknown=..;roi=..). Corridor off.",
msg->source.c_str());
return;
}
// Hash static layer sống theo ĐÚNG luật producer dùng. Giữ mutex master costmap trong lúc đọc:
// thread map-update có thể resize/ghi lại static layer (StaticLayer::incomingMap) — ~20 ms cho 9M ô.
uint64_t live_hash = 0;
{
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*costmap_robot_->getCostmap()->getMutex());
const std::vector<uint8_t> mask = route_graph::obstacleMaskFromCostmap(sl->getCharMap(), w, h, rule);
live_hash = route_graph::hashObstacleMask(mask);
}
if (live_hash != msg->map_hash) {
robot::log_error("[sbpl_lattice_planner] route graph REJECTED: map_hash %016llx (graph) != %016llx "
"(static layer under rule '%s'). The graph was built from a different map (edited, "
"other floor with the same size, or a different unknown/ROI rule). Rebuild it for "
"this map. Corridor off.",
static_cast<unsigned long long>(msg->map_hash),
static_cast<unsigned long long>(live_hash), msg->source.c_str());
return;
}
std::string why;
if (!route_graph_.fromMsg(*msg, &why)) {
robot::log_error("[sbpl_lattice_planner] route graph REJECTED: %s. Corridor off.", why.c_str());
route_graph_.clear();
return;
}
route_graph_ready_ = true;
if (corridor_cfg_.debug_corridor) {
robot::log_info("[sbpl_lattice_planner] [debug/corridor] route graph adopted from '%s': %ux%u, %zu "
"nodes, %zu edges, %zu cells, %d component(s), hash %016llx matches the static layer",
corridor_cfg_.route_graph_topic.c_str(), w, h, route_graph_.nodes().size(),
route_graph_.edges().size(), route_graph_.totalCells(), route_graph_.componentCount(),
static_cast<unsigned long long>(msg->map_hash));
}
}
bool SBPLLatticePlanner::buildCorridor(const robot_costmap_2d::Costmap2D* grid, unsigned int sx,
unsigned int sy, unsigned int gx, unsigned int gy,
int widen_level, CorridorStats& stats){
const auto t0 = std::chrono::steady_clock::now();
corridor_mask_.clear();
stats = CorridorStats();
stats.graph_from_store = route_graph_ready_;
stats.widen_level = widen_level;
if (!route_graph_ready_) return false;
const double res = grid->getResolution();
const int attach_r = std::max(1, static_cast<int>(std::lround(corridor_cfg_.attach_max_radius_m / res)));
// Ô tâm robot đi qua được: dưới inscribed, hoặc unknown khi allow_unknown — đúng tập ô heuristic 2D
// của SBPL dùng, nên điểm gắn luôn nằm trong vùng search có thể tới.
const bool allow_unknown = allow_unknown_;
auto passable = [grid, allow_unknown](int x, int y) {
const unsigned char c = grid->getCost(static_cast<unsigned int>(x), static_cast<unsigned int>(y));
return c < robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE ||
(allow_unknown && c == robot_costmap_2d::NO_INFORMATION);
};
// Edge hẹp hơn bán kính nội tiếp footprint thì robot không lọt: Dijkstra không được chọn, gắn
// cũng không được gắn vào — nếu không dải đi qua khe hẹp, search cạn trong dải rồi rơi về full.
// Graph do producer lọc theo `min_clearance_m` chung chung (0.3 m), không biết robot nào dùng.
const double min_clear_m = corridor_cfg_.route_min_clearance_m >= 0.0
? corridor_cfg_.route_min_clearance_m
: costmap_robot_->getLayeredCostmap()->getInscribedRadius();
const float min_clear_cells = static_cast<float>(min_clear_m / res);
stats.route_min_clearance_m = min_clear_m;
const route_graph::Attachment as =
route_graph_.attach(route_graph::Cell(sx, sy), attach_r, passable, min_clear_cells);
const route_graph::Attachment ag =
route_graph_.attach(route_graph::Cell(gx, gy), attach_r, passable, min_clear_cells);
stats.attach_start_ok = as.ok;
stats.attach_goal_ok = ag.ok;
if (!as.ok || !ag.ok) {
if (corridor_cfg_.debug_corridor)
robot::log_info("[sbpl_lattice_planner] [debug/corridor] no corridor: attach start=%s goal=%s "
"(radius %d cells, edges >= %.2f m clearance) — full search",
as.ok ? "ok" : "FAIL", ag.ok ? "ok" : "FAIL", attach_r, min_clear_m);
return false;
}
const route_graph::Route route = route_graph_.route(as, ag, min_clear_cells);
if (route.empty()) {
if (corridor_cfg_.debug_corridor)
robot::log_info("[sbpl_lattice_planner] [debug/corridor] no corridor: no graph route between "
"start and goal through edges >= %.2f m clearance (different components, or only "
"narrow passages) — full search", min_clear_m);
return false;
}
stats.route_cells = route.cells.size();
stats.route_length_m = route.length_cells * res;
route_graph::CorridorParams cp;
const double widen = std::pow(std::max(1.0, corridor_cfg_.widen_factor), widen_level);
cp.half_width_min_cells = corridor_cfg_.half_width_m * widen / res;
cp.clearance_scale = corridor_cfg_.clearance_scale * widen;
cp.half_width_max_cells = std::max(cp.half_width_min_cells, corridor_cfg_.max_half_width_m * widen / res);
std::size_t n = 0;
corridor_mask_ = route_graph::corridorMask(route, static_cast<int>(grid->getSizeInCellsX()),
static_cast<int>(grid->getSizeInCellsY()), cp, &n);
stats.mask_cells = n;
stats.active = !corridor_mask_.empty();
stats.build_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
if (corridor_cfg_.debug_corridor)
robot::log_info("[sbpl_lattice_planner] [debug/corridor] corridor built: route %zu cells (%.1f m, "
"edges >= %.2f m), half-width %.2f..%.2f m (widen level %d), mask %zu cells = %.2f%% "
"of grid, %.1f ms",
stats.route_cells, stats.route_length_m, min_clear_m, cp.half_width_min_cells * res,
cp.half_width_max_cells * res, widen_level, n,
100.0 * n / (static_cast<double>(grid->getSizeInCellsX()) * grid->getSizeInCellsY()),
stats.build_ms);
return stats.active;
}
const char* SBPLLatticePlanner::costClassName(unsigned char cost){ const char* SBPLLatticePlanner::costClassName(unsigned char cost){
// Semantics của costmap trong port này, không phải của SBPL: 254 lethal, 253 = trong bán kính // Semantics của costmap trong port này, không phải của SBPL: 254 lethal, 253 = trong bán kính
// inscribed của một ô lethal, 255 = chưa biết. FREE_SPACE ở đây là 60 chứ không phải 0 // inscribed của một ô lethal, 255 = chưa biết. FREE_SPACE ở đây là 60 chứ không phải 0
@@ -188,6 +393,24 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
private_nh.param("planner_type", planner_type_, string("ARAPlanner")); private_nh.param("planner_type", planner_type_, string("ARAPlanner"));
private_nh.param("allocated_time", allocated_time_, 10.0); private_nh.param("allocated_time", allocated_time_, 10.0);
private_nh.param("initial_epsilon",initial_epsilon_,3.0); private_nh.param("initial_epsilon",initial_epsilon_,3.0);
private_nh.param("final_epsilon", final_epsilon_, 1.0);
private_nh.param("eps_step", eps_step_, 0.5);
private_nh.param("repair_time", repair_time_, -1.0);
private_nh.param("return_first_solution", return_first_solution_, bool(false));
if (!std::isfinite(initial_epsilon_) || initial_epsilon_ < 1.0) {
robot::log_warning("[sbpl_lattice_planner] initial_epsilon=%g < 1, using 1.0", initial_epsilon_);
initial_epsilon_ = 1.0;
}
if (!std::isfinite(final_epsilon_) || final_epsilon_ < 1.0 || final_epsilon_ > initial_epsilon_) {
robot::log_warning("[sbpl_lattice_planner] final_epsilon=%g outside [1, initial_epsilon=%g], using 1.0",
final_epsilon_, initial_epsilon_);
final_epsilon_ = 1.0;
}
if (!std::isfinite(eps_step_) || eps_step_ <= 0.0) {
robot::log_warning("[sbpl_lattice_planner] eps_step=%g must be > 0, using 0.5", eps_step_);
eps_step_ = 0.5;
}
if (!std::isfinite(repair_time_)) repair_time_ = -1.0;
private_nh.param("environment_type", environment_type_, string("XYThetaLattice")); private_nh.param("environment_type", environment_type_, string("XYThetaLattice"));
private_nh.param("forward_search", forward_search_, bool(false)); private_nh.param("forward_search", forward_search_, bool(false));
private_nh.param("primitive_filename",primitive_filename_,string("")); private_nh.param("primitive_filename",primitive_filename_,string(""));
@@ -265,14 +488,126 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
debug_grid_window_, kMaxGridWindow); debug_grid_window_, kMaxGridWindow);
debug_grid_window_ = kMaxGridWindow; debug_grid_window_ = kMaxGridWindow;
} }
robot::log_info("[sbpl_lattice_planner] '%s' config: allocated_time=%.1fs initial_epsilon=%.2f " robot::log_info("[sbpl_lattice_planner] '%s' config: allocated_time=%.1fs eps %.2f -> %.2f step %.2f "
"allow_unknown=%s free_start_heading=%s forward_search=%s | debug_plan=%s " "repair_time=%.1fs first_solution=%s allow_unknown=%s free_start_heading=%s "
"debug_grid_window=%d", "forward_search=%s | debug_plan=%s debug_grid_window=%d",
name.c_str(), allocated_time_, initial_epsilon_, name.c_str(), allocated_time_, initial_epsilon_, final_epsilon_, eps_step_,
repair_time_, return_first_solution_ ? "true" : "false",
allow_unknown_ ? "true" : "false", free_start_heading_ ? "true" : "false", allow_unknown_ ? "true" : "false", free_start_heading_ ? "true" : "false",
forward_search_ ? "true" : "false", debug_plan_ ? "on" : "off", forward_search_ ? "true" : "false", debug_plan_ ? "on" : "off",
debug_grid_window_); debug_grid_window_);
// ---- voronoi_corridor (2026-09-21) ----------------------------------------------------------
{
robot::NodeHandle cnh(private_nh, "voronoi_corridor");
CorridorConfig& c = corridor_cfg_;
cnh.param("enabled", c.enabled, bool(false));
cnh.param("route_graph_topic", c.route_graph_topic, std::string("/route_graph"));
cnh.param("static_layer_name", c.static_layer_name, std::string(""));
cnh.param("min_range_m", c.min_range_m, 15.0);
cnh.param("half_width_m", c.half_width_m, 1.5);
cnh.param("clearance_scale", c.clearance_scale, 0.8);
cnh.param("max_half_width_m", c.max_half_width_m, 6.0);
cnh.param("attach_max_radius_m", c.attach_max_radius_m, 10.0);
cnh.param("route_min_clearance_m", c.route_min_clearance_m, -1.0);
cnh.param("outside_mode", c.outside_mode, std::string("hard"));
cnh.param("soft_penalty_cost", c.soft_penalty_cost, 200);
if (c.outside_mode != "hard" && c.outside_mode != "soft") {
robot::log_warning("[sbpl_lattice_planner] voronoi_corridor/outside_mode='%s' unknown, using hard",
c.outside_mode.c_str());
c.outside_mode = "hard";
}
corridor_hard_ = c.outside_mode == "hard";
if (c.soft_penalty_cost < 1 || c.soft_penalty_cost > 252) {
robot::log_warning("[sbpl_lattice_planner] voronoi_corridor/soft_penalty_cost=%d out of [1, 252], using 200",
c.soft_penalty_cost);
c.soft_penalty_cost = 200;
}
cnh.param("widen_factor", c.widen_factor, 2.0);
cnh.param("max_widen", c.max_widen, 1);
cnh.param("budget_fraction", c.budget_fraction, 0.6);
cnh.param("fallback_full_search", c.fallback_full_search, bool(true));
cnh.param("debug_corridor", c.debug_corridor, bool(true));
auto clampd = [&](const char* key, double& v, double lo, double hi) {
if (std::isfinite(v) && v >= lo && v <= hi) return;
const double fixed = std::min(hi, std::max(lo, std::isfinite(v) ? v : lo));
robot::log_warning("[sbpl_lattice_planner] voronoi_corridor/%s=%g out of [%g, %g], using %g",
key, v, lo, hi, fixed);
v = fixed;
};
clampd("min_range_m", c.min_range_m, 0.0, 1000.0);
clampd("half_width_m", c.half_width_m, 0.05, 50.0);
clampd("clearance_scale", c.clearance_scale, 0.0, 10.0);
clampd("max_half_width_m", c.max_half_width_m, c.half_width_m, 100.0);
clampd("attach_max_radius_m", c.attach_max_radius_m, 0.1, 100.0);
if (!std::isfinite(c.route_min_clearance_m) || c.route_min_clearance_m > 50.0) {
robot::log_warning("[sbpl_lattice_planner] voronoi_corridor/route_min_clearance_m=%g invalid, using auto",
c.route_min_clearance_m);
c.route_min_clearance_m = -1.0;
}
clampd("widen_factor", c.widen_factor, 1.0, 10.0);
clampd("budget_fraction", c.budget_fraction, 0.05, 1.0);
if (c.max_widen < 0 || c.max_widen > 5) {
robot::log_warning("[sbpl_lattice_planner] voronoi_corridor/max_widen=%d out of [0, 5], using 1", c.max_widen);
c.max_widen = 1;
}
if (c.enabled && sensors_ == NULL)
robot::log_warning("[sbpl_lattice_planner] voronoi_corridor enabled but no sensor store reader was "
"attached (host without robot_sensor_ports?) — corridor can never activate");
robot::log_info("[sbpl_lattice_planner] voronoi_corridor: enabled=%s topic=%s min_range=%.1fm "
"half_width=%.2f..%.2fm (x%.1f clearance) attach_r=%.1fm route_min_clearance=%s "
"outside=%s%s widen x%.1f max %d budget=%.0f%% fallback=%s | debug_corridor=%s",
c.enabled ? "true" : "false", c.route_graph_topic.c_str(), c.min_range_m,
c.half_width_m, c.max_half_width_m, c.clearance_scale, c.attach_max_radius_m,
c.route_min_clearance_m < 0.0 ? "auto(inscribed)" : std::to_string(c.route_min_clearance_m).c_str(),
c.outside_mode.c_str(),
corridor_hard_ ? "" : (" (penalty " + std::to_string(c.soft_penalty_cost) + ")").c_str(),
c.widen_factor, c.max_widen, 100.0 * c.budget_fraction,
c.fallback_full_search ? "true" : "false", c.debug_corridor ? "on" : "off");
}
// ===== smooth_path: kéo dây + bo góc sau search (2026-09-22) =====
{
robot::NodeHandle snh(private_nh, "smooth_path");
SmootherConfig& m = smoother_cfg_;
snh.param("enabled", m.enabled, bool(false));
snh.param("max_shortcut_m", m.max_shortcut_m, 80.0);
snh.param("fillet_radius_m", m.fillet_radius_m, 1.06);
snh.param("min_fillet_radius_m", m.min_fillet_radius_m, 0.8);
snh.param("sample_step_m", m.sample_step_m, 0.05);
snh.param("max_junction_deg", m.max_junction_deg, 20.0);
snh.param("max_cell_cost", smoother_max_cell_cost_, 252);
snh.param("min_clearance_m", smoother_min_clearance_m_, -1.0);
const auto clampd = [&](const char* key, double& v, double lo, double hi, double dflt) {
if (!(v >= lo && v <= hi)) {
robot::log_warning("[sbpl_lattice_planner] smooth_path/%s=%g out of [%g, %g], using %g", key, v, lo, hi, dflt);
v = dflt;
}
};
clampd("max_shortcut_m", m.max_shortcut_m, 1.0, 500.0, 80.0);
clampd("fillet_radius_m", m.fillet_radius_m, 0.0, 20.0, 1.06);
clampd("min_fillet_radius_m", m.min_fillet_radius_m, 0.0, 20.0, 0.8);
clampd("sample_step_m", m.sample_step_m, 0.01, 0.5, 0.05);
clampd("max_junction_deg", m.max_junction_deg, 0.0, 90.0, 20.0);
m.check_step_m = 0.5 * m.sample_step_m; // nửa ô @ 5 cm: không lọt ô nào giữa hai mẫu
if (smoother_max_cell_cost_ < 1 || smoother_max_cell_cost_ > 252) {
robot::log_warning("[sbpl_lattice_planner] smooth_path/max_cell_cost=%d out of [1, 252], using 252",
smoother_max_cell_cost_);
smoother_max_cell_cost_ = 252;
}
if (smoother_min_clearance_m_ > 5.0) {
robot::log_warning("[sbpl_lattice_planner] smooth_path/min_clearance_m=%g > 5 m, using auto (circumscribed)",
smoother_min_clearance_m_);
smoother_min_clearance_m_ = -1.0;
}
robot::log_info("[sbpl_lattice_planner] smooth_path: enabled=%s max_shortcut=%.0fm fillet_r=%.2fm "
"(min %.2fm) max_cell_cost=%d min_clearance=%s junction<=%.0fdeg step=%.3fm",
m.enabled ? "true" : "false", m.max_shortcut_m, m.fillet_radius_m,
m.min_fillet_radius_m, smoother_max_cell_cost_,
smoother_min_clearance_m_ < 0.0 ? "auto(circumscribed)" : std::to_string(smoother_min_clearance_m_).c_str(),
m.max_junction_deg, m.sample_step_m);
}
name_ = name; name_ = name;
costmap_robot_ = costmap_robot; costmap_robot_ = costmap_robot;
@@ -312,6 +647,15 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
robot::log_warning("SBPL performance will suffer."); robot::log_warning("SBPL performance will suffer.");
robot::log_warning("Please decrease the costmap's cost_scaling_factor."); robot::log_warning("Please decrease the costmap's cost_scaling_factor.");
} }
// hard: ô ngoài dải nhận đúng cost inscribed — tâm robot không được đi qua (>= cost_inscribed_thresh)
// nhưng KHÔNG lethal, footprint đè lên vẫn hợp lệ, heuristic 2D tự dừng ở mép dải.
// soft: chỉ phạt (cost < inscribed) — search vẫn ra ngoài được khi cần, heuristic 2D + cost kéo nó
// về hướng tuyến; dải không bao giờ là lý do fail, đổi lại tăng tốc ít hơn.
masked_cost_ = corridor_hard_
? costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)
: costMapCostToSBPLCost(static_cast<unsigned char>(corridor_cfg_.soft_penalty_cost));
if (!corridor_hard_ && masked_cost_ >= costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE))
masked_cost_ = costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE) - 1;
if(!env_->SetEnvParameter("cost_inscribed_thresh",costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE))){ if(!env_->SetEnvParameter("cost_inscribed_thresh",costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE))){
robot::log_error("Failed to set cost_inscribed_thresh parameter"); robot::log_error("Failed to set cost_inscribed_thresh parameter");
exit(1); exit(1);
@@ -415,6 +759,12 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2
"cancel/pause cannot interrupt a running search (runs to allocated_time)"); "cancel/pause cannot interrupt a running search (runs to allocated_time)");
#endif #endif
// Graph tiêm cùng map: đọc ngay lúc này để lượt makePlan đầu đã có dải. (Re-init do đổi kích
// thước map đã xoá graph cũ ở makePlan — static layer khác thì graph cũ vô hiệu, chỉ nhận lại
// khi host đẩy bản mới.)
corridor_mask_.clear();
tryAdoptRouteGraph();
robot::log_info("[sbpl_lattice_planner] Initialized successfully"); robot::log_info("[sbpl_lattice_planner] Initialized successfully");
// plan_pub_ = private_nh.advertise<nav_msgs::Path>("plan", 1); // plan_pub_ = private_nh.advertise<nav_msgs::Path>("plan", 1);
// stats_publisher_ = private_nh.advertise<sbpl_lattice_planner::SBPLLatticePlannerStats>("sbpl_lattice_planner_stats", 1); // stats_publisher_ = private_nh.advertise<sbpl_lattice_planner::SBPLLatticePlannerStats>("sbpl_lattice_planner_stats", 1);
@@ -487,6 +837,13 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
current_env_width_, current_env_height_, current_env_width_, current_env_height_,
grid->getSizeInCellsX(), grid->getSizeInCellsY()); grid->getSizeInCellsX(), grid->getSizeInCellsY());
do_init = true; do_init = true;
// Map khác kích thước = map khác: graph đã nhận là của map cũ. Bỏ ngay, không chờ hash lệch.
if (route_graph_ready_) {
robot::log_info("[sbpl_lattice_planner] map size changed — dropping the adopted route graph until "
"the host pushes one for the new map");
route_graph_ready_ = false;
route_graph_.clear();
}
} }
else if (footprint_ != costmap_robot_->getRobotFootprint()) { else if (footprint_ != costmap_robot_->getRobotFootprint()) {
robot::log_info("Robot footprint has changed, reinitializing sbpl_lattice_planner."); robot::log_info("Robot footprint has changed, reinitializing sbpl_lattice_planner.");
@@ -583,16 +940,75 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
return false; return false;
} }
// ================================================================================================
// Corridor quanh tuyến graph (2026-09-21). Quyết TRƯỚC vòng cost: dải chỉ đổi cost hiệu dụng của
// ô ngoài dải thành inscribed, phần search lattice/mprim/cost bên trong dải y nguyên -> path cùng
// chất lượng, chỉ khác là ARA* và heuristic 2D không nở ra khắp map.
// ================================================================================================
tryAdoptRouteGraph();
const double goal_dist_m = std::hypot(goal.pose.position.x - start.pose.position.x,
goal.pose.position.y - start.pose.position.y);
bool corridor_active = false;
int widen_level = 0;
unsigned int c_sx = 0, c_sy = 0, c_gx = 0, c_gy = 0;
last_corridor_ = CorridorStats();
if (corridor_cfg_.enabled && route_graph_ready_) {
if (goal_dist_m < corridor_cfg_.min_range_m) {
if (corridor_cfg_.debug_corridor)
robot::log_info("[sbpl_lattice_planner] [debug/corridor] goal %.1f m < min_range %.1f m — full "
"search", goal_dist_m, corridor_cfg_.min_range_m);
}
else if (!grid->worldToMap(start.pose.position.x, start.pose.position.y, c_sx, c_sy) ||
!grid->worldToMap(goal.pose.position.x, goal.pose.position.y, c_gx, c_gy)) {
// Ngoài lưới: SetGoal ở trên đã từ chối goal ngoài lưới, đây là start — audit dưới sẽ nói.
}
else {
corridor_active = buildCorridor(grid, c_sx, c_sy, c_gx, c_gy, widen_level, last_corridor_);
}
}
if (!corridor_active) corridor_mask_.clear();
// Nới dải một nấc, hoặc bỏ dải khi đã nới hết. Trả true khi vẫn còn dải.
const auto widenOrDropCorridor = [&](const char* why) -> bool {
if (widen_level < corridor_cfg_.max_widen) {
++widen_level;
corridor_active = buildCorridor(grid, c_sx, c_sy, c_gx, c_gy, widen_level, last_corridor_);
if (corridor_active) {
if (corridor_cfg_.debug_corridor)
robot::log_info("[sbpl_lattice_planner] [debug/corridor] %s — corridor widened to level %d",
why, widen_level);
return true;
}
}
corridor_active = false;
corridor_mask_.clear();
last_corridor_.active = false;
if (corridor_cfg_.debug_corridor)
robot::log_info("[sbpl_lattice_planner] [debug/corridor] %s — corridor dropped, full search", why);
return false;
};
// Đổ cost vào env: cost costmap, cộng inscribed cho ô ngoài dải khi có dải. So với cost env đang
// giữ (có thể mang dải của lượt trước) và chỉ UpdateCost ô khác -> đổi dải giữa hai lượt tự sinh
// changedcells + force_scratch như một lần map đổi lớn.
const unsigned int grid_w = grid->getSizeInCellsX();
const unsigned char masked_cost = masked_cost_;
const auto applyGridCosts = [&]() -> bool {
int offOnCount = 0; int offOnCount = 0;
int onOffCount = 0; int onOffCount = 0;
int allCount = 0; int allCount = 0;
vector<nav2dcell_t> changedcellsV; vector<nav2dcell_t> changedcellsV;
const bool masking = corridor_active && !corridor_mask_.empty();
const unsigned char sbpl_lethal = costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE);
const unsigned char sbpl_inscribed = costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE);
for(unsigned int ix = 0; ix < grid->getSizeInCellsX(); ix++) { for(unsigned int ix = 0; ix < grid->getSizeInCellsX(); ix++) {
for(unsigned int iy = 0; iy < grid->getSizeInCellsY(); iy++) { for(unsigned int iy = 0; iy < grid->getSizeInCellsY(); iy++) {
unsigned char oldCost = env_->GetMapCost(ix,iy); unsigned char oldCost = env_->GetMapCost(ix,iy);
unsigned char newCost = costMapCostToSBPLCost(grid->getCost(ix,iy)); unsigned char newCost = costMapCostToSBPLCost(grid->getCost(ix,iy));
if (masking && !corridor_mask_[static_cast<size_t>(iy) * grid_w + ix] && newCost < masked_cost)
newCost = masked_cost;
if(oldCost == newCost) continue; if(oldCost == newCost) continue;
@@ -600,16 +1016,16 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
//first case - off cell goes on //first case - off cell goes on
if((oldCost != costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) && oldCost != costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)) && if((oldCost != sbpl_lethal && oldCost != sbpl_inscribed) &&
(newCost == costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) || newCost == costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE))) { (newCost == sbpl_lethal || newCost == sbpl_inscribed)) {
offOnCount++; offOnCount++;
} }
if((oldCost == costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) || oldCost == costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)) && if((oldCost == sbpl_lethal || oldCost == sbpl_inscribed) &&
(newCost != costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) && newCost != costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE))) { (newCost != sbpl_lethal && newCost != sbpl_inscribed)) {
onOffCount++; onOffCount++;
} }
env_->UpdateCost(ix, iy, costMapCostToSBPLCost(grid->getCost(ix,iy))); env_->UpdateCost(ix, iy, newCost);
nav2dcell_t nav2dcell; nav2dcell_t nav2dcell;
nav2dcell.x = ix; nav2dcell.x = ix;
@@ -632,6 +1048,13 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
robot::log_error("SBPL failed to update the costmap"); robot::log_error("SBPL failed to update the costmap");
return false; return false;
} }
if (corridor_cfg_.debug_corridor && masking)
robot::log_info("[sbpl_lattice_planner] [debug/corridor] env costs: %d cell(s) changed (%d on, %d off)%s",
allCount, offOnCount, onOffCount,
allCount > force_scratch_limit_ ? ", planning from scratch" : "");
return true;
};
if (!applyGridCosts()) return false;
// ================================================================================================ // ================================================================================================
// Chẩn đoán TRƯỚC khi search (2026-09-18). Env đã nhận cost mới ở vòng trên, nên soi ở đây mới // Chẩn đoán TRƯỚC khi search (2026-09-18). Env đã nhận cost mới ở vòng trên, nên soi ở đây mới
@@ -658,7 +1081,8 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
// (1) Goal. Một action không bao giờ được KẾT THÚC trên ô >= cost_inscribed_thresh (253), và // (1) Goal. Một action không bao giờ được KẾT THÚC trên ô >= cost_inscribed_thresh (253), và
// footprint tại goal phải trong lưới + không đè lethal — hai điều kiện SBPL kiểm khi mở rộng // footprint tại goal phải trong lưới + không đè lethal — hai điều kiện SBPL kiểm khi mở rộng
// nhưng KHÔNG kiểm khi SetGoal. Goal vi phạm = không có successor nào trùng goal = chắc chắn fail // nhưng KHÔNG kiểm khi SetGoal. Goal vi phạm = không có successor nào trùng goal = chắc chắn fail
// sau khi quét hết vùng nối với robot. // sau khi quét hết vùng nối với robot. (Audit đọc cost COSTMAP, không phải cost env, nên dải
// không ảnh hưởng — goal luôn nằm trong dải theo cách dựng.)
const bool goal_cell_blocked = const bool goal_cell_blocked =
goal_audit.cost >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && goal_audit.cost >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE &&
!(allow_unknown_ && goal_audit.cost == robot_costmap_2d::NO_INFORMATION); !(allow_unknown_ && goal_audit.cost == robot_costmap_2d::NO_INFORMATION);
@@ -689,11 +1113,12 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
else if (debug_plan_) { else if (debug_plan_) {
robot::log_info("[sbpl_lattice_planner] audit: start cell (%u,%u) cost=%u %s | goal cell (%u,%u) " robot::log_info("[sbpl_lattice_planner] audit: start cell (%u,%u) cost=%u %s | goal cell (%u,%u) "
"cost=%u %s footprint valid | grid %u x %u @ %.3f m origin (%.2f, %.2f) | " "cost=%u %s footprint valid | grid %u x %u @ %.3f m origin (%.2f, %.2f) | "
"allow_unknown=%s", "allow_unknown=%s | corridor=%s",
start_audit.mx, start_audit.my, start_audit.cost, costClassName(start_audit.cost), start_audit.mx, start_audit.my, start_audit.cost, costClassName(start_audit.cost),
goal_audit.mx, goal_audit.my, goal_audit.cost, costClassName(goal_audit.cost), goal_audit.mx, goal_audit.my, goal_audit.cost, costClassName(goal_audit.cost),
grid->getSizeInCellsX(), grid->getSizeInCellsY(), grid->getResolution(), grid->getSizeInCellsX(), grid->getSizeInCellsY(), grid->getResolution(),
grid->getOriginX(), grid->getOriginY(), allow_unknown_ ? "true" : "false"); grid->getOriginX(), grid->getOriginY(), allow_unknown_ ? "true" : "false",
corridor_active ? "on" : "off");
} }
// (3) Nối 2D. Heuristic của SBPL là Dijkstra 2D từ goal trên ô < cost_inscribed_thresh — đúng tập // (3) Nối 2D. Heuristic của SBPL là Dijkstra 2D từ goal trên ô < cost_inscribed_thresh — đúng tập
@@ -701,7 +1126,11 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
// đường 3D; ARA* sẽ dừng sau 0 expansion, nhưng vẫn tốn khởi tạo + retry heading, và log chỉ // đường 3D; ARA* sẽ dừng sau 0 expansion, nhưng vẫn tốn khởi tạo + retry heading, và log chỉ
// nói "Solution not found". Gọi trước để nói rõ, rồi từ chối. GetGoalHeuristic chia cho // nói "Solution not found". Gọi trước để nói rõ, rồi từ chối. GetGoalHeuristic chia cho
// nominalvel nên INF (1e9) có thể tràn int thành số ÂM — bắt cả hai dạng. // nominalvel nên INF (1e9) có thể tràn int thành số ÂM — bắt cả hai dạng.
// Có dải: INF chỉ nói "không có đường TRONG dải" (dải cắt qua vật cản mới của obstacle layer, hay
// hẹp hơn khe) -> nới dải rồi tính lại, không tốn search; hết nấc thì bỏ dải; chỉ từ chối khi full
// cũng không nối.
int h_2d = 0; int h_2d = 0;
while (true) {
try{ try{
env_->EnsureHeuristicsUpdated(forward_search_); env_->EnsureHeuristicsUpdated(forward_search_);
h_2d = forward_search_ ? env_->GetGoalHeuristic(start_state_id) h_2d = forward_search_ ? env_->GetGoalHeuristic(start_state_id)
@@ -712,7 +1141,12 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
return false; return false;
} }
const bool h_2d_infinite = (h_2d < 0 || h_2d >= INFINITECOST); const bool h_2d_infinite = (h_2d < 0 || h_2d >= INFINITECOST);
if (h_2d_infinite) { if (!h_2d_infinite) break;
if (corridor_active && corridor_hard_) {
widenOrDropCorridor("2D reachability h=INF inside the corridor");
if (!applyGridCosts()) return false;
continue;
}
robot::log_error("[sbpl_lattice_planner] 2D reachability start->goal: h=INF — no point path " robot::log_error("[sbpl_lattice_planner] 2D reachability start->goal: h=INF — no point path "
"through cells < 253 (allow_unknown=%s). Goal region is sealed off from the " "through cells < 253 (allow_unknown=%s). Goal region is sealed off from the "
"robot by lethal/inscribed cells%s. REJECTED without running the lattice search.\n", "robot by lethal/inscribed cells%s. REJECTED without running the lattice search.\n",
@@ -724,13 +1158,11 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
if (debug_plan_) { if (debug_plan_) {
// h tính bằng đơn vị cost SBPL (mm / nominalvel): chỉ dùng để so tương đối giữa các lượt. // h tính bằng đơn vị cost SBPL (mm / nominalvel): chỉ dùng để so tương đối giữa các lượt.
robot::log_info("[sbpl_lattice_planner] 2D reachability start->goal: h=%d (finite) — point path " robot::log_info("[sbpl_lattice_planner] 2D reachability start->goal: h=%d (finite) — point path "
"exists, running lattice search", h_2d); "exists, running lattice search%s", h_2d, corridor_active ? " inside the corridor" : "");
} }
//setting planner parameters //setting planner parameters (eps/mode đi theo từng lượt qua makeReplanParams)
robot::log_debug("allocated:%f, init eps:%f\n",allocated_time_,initial_epsilon_); robot::log_debug("allocated:%f, init eps:%f\n",allocated_time_,initial_epsilon_);
planner_->set_initialsolution_eps(initial_epsilon_);
planner_->set_search_mode(false);
robot::log_debug("[sbpl_lattice_planner] run planner"); robot::log_debug("[sbpl_lattice_planner] run planner");
const robot::Time plan_started = robot::Time::now(); const robot::Time plan_started = robot::Time::now();
@@ -739,6 +1171,7 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
// lượt được cấp lại nguyên allocated_time, trần thật là 3x — 30 s với config 10 s, và khi // lượt được cấp lại nguyên allocated_time, trần thật là 3x — 30 s với config 10 s, và khi
// PlannerRunner còn giữ costmap mutex (global_costmap.snapshot_for_readers = false) thì map-update // PlannerRunner còn giữ costmap mutex (global_costmap.snapshot_for_readers = false) thì map-update
// thread đứng suốt chừng ấy. Lượt sau chỉ chạy khi còn >= kMinReplanBudget. // thread đứng suốt chừng ấy. Lượt sau chỉ chạy khi còn >= kMinReplanBudget.
// Có dải: pha đầu chỉ được `budget_fraction` của allocated_time, phần còn lại để nới/fallback.
constexpr double kMinReplanBudget = 0.5; // [s] dưới mức này một lượt ARA* không kịp ra gì constexpr double kMinReplanBudget = 0.5; // [s] dưới mức này một lượt ARA* không kịp ra gì
const auto budget_left = [&]() { const auto budget_left = [&]() {
return allocated_time_ - (robot::Time::now() - plan_started).toSec(); return allocated_time_ - (robot::Time::now() - plan_started).toSec();
@@ -750,8 +1183,18 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
const char* phase_name = start_heading_overridden ? "free_heading" : "actual_heading"; const char* phase_name = start_heading_overridden ? "free_heading" : "actual_heading";
double phase_budget = allocated_time_; double phase_budget = allocated_time_;
robot::Time phase_started = plan_started; robot::Time phase_started = plan_started;
constexpr double kTimeoutFraction = 0.95; // sát trần ngần này coi là hết giờ
int corridor_phases = 0;
try{ try{
int ret = planner_->replan(allocated_time_, &solution_stateIDs, &solution_cost); // soft: dải không chặn nên không có pha "nới/bỏ" — một pha, trọn ngân sách như không có dải.
double budget = (corridor_active && corridor_hard_) ? allocated_time_ * corridor_cfg_.budget_fraction
: allocated_time_;
int ret = 0;
while (true) {
++corridor_phases;
phase_budget = budget;
phase_started = robot::Time::now();
ret = planner_->replan(&solution_stateIDs, makeReplanParams(budget), &solution_cost);
if(preempt_.load(std::memory_order_relaxed)){ if(preempt_.load(std::memory_order_relaxed)){
robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (first search)", robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (first search)",
(robot::Time::now() - plan_started).toSec() * 1000.0); (robot::Time::now() - plan_started).toSec() * 1000.0);
@@ -769,9 +1212,9 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
theta_start_actual); theta_start_actual);
if(sid >= 0 && planner_->set_start(sid) != 0){ if(sid >= 0 && planner_->set_start(sid) != 0){
phase_name = "actual_heading_retry"; phase_name = "actual_heading_retry";
phase_budget = budget_left(); phase_budget = (corridor_active && corridor_hard_) ? std::min(budget_left(), budget) : budget_left();
phase_started = robot::Time::now(); phase_started = robot::Time::now();
ret = planner_->replan(phase_budget, &solution_stateIDs, &solution_cost); ret = planner_->replan(&solution_stateIDs, makeReplanParams(phase_budget), &solution_cost);
} }
if(preempt_.load(std::memory_order_relaxed)){ if(preempt_.load(std::memory_order_relaxed)){
robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (heading retry)", robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (heading retry)",
@@ -779,6 +1222,37 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
return false; return false;
} }
} }
if (ret || !corridor_active || !corridor_hard_) break;
// Fail TRONG dải. Hết giờ thì full còn chậm hơn -> trả lỗi ngay, không fallback. Cạn (OPEN rỗng
// trước giờ) thì dải chặn mất đường footprint -> nới, hết nấc thì bỏ dải, chạy full với thời
// gian còn lại.
const double phase_elapsed = (robot::Time::now() - phase_started).toSec();
const bool timed_out = phase_budget > 0.0 && phase_elapsed >= kTimeoutFraction * phase_budget;
if (timed_out) {
robot::log_error("[sbpl_lattice_planner] NO SOLUTION inside the corridor (TIMEOUT after %.0f ms "
"of %.0f ms, expands=%d, widen level %d, mask %zu cells) — a full search would "
"be slower still; not retried. Raise allocated_time or initial_epsilon.\n",
phase_elapsed * 1000.0, phase_budget * 1000.0, planner_->get_n_expands(),
widen_level, last_corridor_.mask_cells);
return false;
}
if (!corridor_cfg_.fallback_full_search && widen_level >= corridor_cfg_.max_widen) {
robot::log_error("[sbpl_lattice_planner] NO SOLUTION inside the corridor (EXHAUSTED, widen level "
"%d) and fallback_full_search=false — giving up (bench mode).\n", widen_level);
return false;
}
widenOrDropCorridor("search EXHAUSTED inside the corridor");
if (!applyGridCosts()) return false;
budget = budget_left();
if (budget < kMinReplanBudget) {
robot::log_error("[sbpl_lattice_planner] NO SOLUTION: corridor exhausted and only %.2f s of the "
"budget left for the %s phase — not retried.\n", budget,
corridor_active ? "widened" : "full");
return false;
}
phase_name = corridor_active ? "corridor_widened" : "full_after_corridor";
}
if(ret) if(ret)
{ {
// eps THẬT đạt được, không phải eps đặt trong config. Cần thiết vì toàn bộ log nội bộ của // eps THẬT đạt được, không phải eps đặt trong config. Cần thiết vì toàn bộ log nội bộ của
@@ -790,12 +1264,26 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
// hoặc hạ `initial_epsilon`. eps == 1.0 nghĩa là đã tới nghiệm tối ưu. expands= là số state // hoặc hạ `initial_epsilon`. eps == 1.0 nghĩa là đã tới nghiệm tối ưu. expands= là số state
// ARA* đã mở: so giữa hai lượt cùng goal để thấy map/cost đổi hay không. // ARA* đã mở: so giữa hai lượt cùng goal để thấy map/cost đổi hay không.
if (debug_plan_) { if (debug_plan_) {
// first_cpu_ms = thời gian tới NGHIỆM ĐẦU (eps = initial), đo bằng clock() của SBPL = CPU
// time cả tiến trình (mọi thread), nên nhanh hơn wall ~20 % ở đây. Phần còn lại tới "ms of"
// là hạ eps trong repair_time. Đây là số so sánh có/không dải: tổng thời gian luôn chạm
// repair_time khi eps chưa về 1.0, không nói lên độ khó.
robot::log_info("[sbpl_lattice_planner] solved: eps=%.3f (init %.2f), cost=%d, %zu state(s), " robot::log_info("[sbpl_lattice_planner] solved: eps=%.3f (init %.2f), cost=%d, %zu state(s), "
"%.0f ms of %.2f s allowed, expands=%d, h_2d=%d, phase=%s", "%.0f ms of %.2f s allowed, expands=%d (first solution: %.0f cpu-ms, %d expands), "
"h_2d=%d, phase=%s",
planner_->get_final_epsilon(), initial_epsilon_, solution_cost, planner_->get_final_epsilon(), initial_epsilon_, solution_cost,
solution_stateIDs.size(), solution_stateIDs.size(),
(robot::Time::now() - plan_started).toSec() * 1000.0, allocated_time_, (robot::Time::now() - plan_started).toSec() * 1000.0, allocated_time_,
planner_->get_n_expands(), h_2d, phase_name); planner_->get_n_expands(), planner_->get_initial_eps_planning_time() * 1000.0,
planner_->get_n_expands_init_solution(), h_2d, phase_name);
}
if (corridor_cfg_.enabled && corridor_cfg_.debug_corridor) {
robot::log_info("[sbpl_lattice_planner] [debug/corridor] summary: corridor=%s(%s) src=%s route=%.1f m "
"mask=%zu cells widen=%d phases=%d goal_dist=%.1f m",
corridor_active ? "on" : "off", corridor_hard_ ? "hard" : "soft",
route_graph_ready_ ? "store" : "none",
last_corridor_.route_length_m, last_corridor_.mask_cells, widen_level,
corridor_phases, goal_dist_m);
} }
} }
else{ else{
@@ -808,15 +1296,12 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
// (preempt đã return sớm ở trên, không tới đây.) // (preempt đã return sớm ở trên, không tới đây.)
const double phase_elapsed = (robot::Time::now() - phase_started).toSec(); const double phase_elapsed = (robot::Time::now() - phase_started).toSec();
const double total_elapsed = (robot::Time::now() - plan_started).toSec(); const double total_elapsed = (robot::Time::now() - plan_started).toSec();
constexpr double kTimeoutFraction = 0.95; // sát trần ngần này coi là hết giờ
const bool timed_out = phase_budget > 0.0 && phase_elapsed >= kTimeoutFraction * phase_budget; const bool timed_out = phase_budget > 0.0 && phase_elapsed >= kTimeoutFraction * phase_budget;
robot::log_error("[sbpl_lattice_planner] NO SOLUTION start=(%.3f,%.3f) goal=(%.3f,%.3f) " robot::log_error("[sbpl_lattice_planner] NO SOLUTION start=(%.3f,%.3f) goal=(%.3f,%.3f) "
"dist=%.1f m | phase=%s reason=%s expands=%d phase_elapsed=%.0f ms of %.0f ms " "dist=%.1f m | phase=%s reason=%s expands=%d phase_elapsed=%.0f ms of %.0f ms "
"total=%.0f ms of %.0f ms eps=%.2f h_2d=%d allow_unknown=%s\n", "total=%.0f ms of %.0f ms eps=%.2f h_2d=%d allow_unknown=%s\n",
start.pose.position.x, start.pose.position.y, goal.pose.position.x, start.pose.position.x, start.pose.position.y, goal.pose.position.x,
goal.pose.position.y, goal.pose.position.y, goal_dist_m,
std::hypot(goal.pose.position.x - start.pose.position.x,
goal.pose.position.y - start.pose.position.y),
phase_name, timed_out ? "TIMEOUT" : "EXHAUSTED", planner_->get_n_expands(), phase_name, timed_out ? "TIMEOUT" : "EXHAUSTED", planner_->get_n_expands(),
phase_elapsed * 1000.0, phase_budget * 1000.0, total_elapsed * 1000.0, phase_elapsed * 1000.0, phase_budget * 1000.0, total_elapsed * 1000.0,
allocated_time_ * 1000.0, planner_->get_final_epsilon(), h_2d, allocated_time_ * 1000.0, planner_->get_final_epsilon(), h_2d,
@@ -906,7 +1391,7 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
vector<int> realigned_ids; vector<int> realigned_ids;
int realigned_cost; int realigned_cost;
if(sid >= 0 && planner_->set_start(sid) != 0 && if(sid >= 0 && planner_->set_start(sid) != 0 &&
planner_->replan(budget_left(), &realigned_ids, &realigned_cost)){ planner_->replan(&realigned_ids, makeReplanParams(budget_left()), &realigned_cost)){
vector<EnvNAVXYTHETALAT3Dpt_t> realigned_path; vector<EnvNAVXYTHETALAT3Dpt_t> realigned_path;
env_->ConvertStateIDPathintoXYThetaPath(&realigned_ids, &realigned_path); env_->ConvertStateIDPathintoXYThetaPath(&realigned_ids, &realigned_path);
if(!realigned_path.empty()){ if(!realigned_path.empty()){
@@ -936,9 +1421,80 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
// sbpl_path.push_back(s); // sbpl_path.push_back(s);
} }
// LÀM MƯỢT (2026-09-22): kéo dây + bo góc trên costmap sống, sau realign heading. Path lattice là
// đầu vào; thất bại (lùi, quá ngắn) thì giữ nguyên. Đo trên sbpl_path để dòng metrics thấy cả hai.
const double raw_len_m = [&]() {
double l = 0.0;
for (size_t i = 1; i < sbpl_path.size(); ++i)
l += std::hypot(sbpl_path[i].x - sbpl_path[i - 1].x, sbpl_path[i].y - sbpl_path[i - 1].y);
return l;
}();
SmootherStats smooth_stats;
double smooth_ms = 0.0;
bool smoothed = false;
if (smoother_cfg_.enabled && sbpl_path.size() > 2) {
const auto t0 = std::chrono::steady_clock::now();
smoothed = smoothLatticePath(grid, sbpl_path, &smooth_stats);
smooth_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
}
robot::log_debug("Plan has %d points.\n", (int)sbpl_path.size()); robot::log_debug("Plan has %d points.\n", (int)sbpl_path.size());
robot::Time plan_time = robot::Time::now(); robot::Time plan_time = robot::Time::now();
// ĐO HÌNH HỌC PATH (2026-09-22): một dòng key=value mỗi lượt plan thành công, để đánh giá "đi
// thẳng được mà lại ngoằn ngoèo" và chi phí tính toán mà không cần bag. Đọc thế nào:
// detour = path_len / khoảng cách thẳng start->goal. 1.0 = thẳng tắp. Dải Voronoi bám trục
// giữa nên thường đẩy lên 1.2-1.4 — so với lượt corridor=off CÙNG goal mới có nghĩa.
// turn_deg = tổng |dtheta| dọc path [deg]: path càng lượn càng lớn.
// arcs = số cung rẽ (chuỗi dtheta cùng dấu liên tiếp); wiggles = số lần ĐỔI CHIỀU rẽ
// (trái<->phải). wiggles cao mà detour ~1 = zigzag lưới 16 hướng, không phải do dải.
// eps>1 = nghiệm chưa tối ưu: detour có thể do eps chứ không do dải -> tăng repair_time
// trước khi chỉnh dải. corridor_ms tách riêng để thấy dải tốn bao nhiêu.
// Cùng nhóm debug_plan với dòng "solved:", tắt chung một khoá. Tính O(n) trên path (~400 điểm).
if (debug_plan_ && sbpl_path.size() > 1) {
double path_len_m = 0.0;
double turn_rad = 0.0;
int arcs = 0;
int wiggles = 0;
int run_sign = 0; // dấu của cung đang đi (0 = đang thẳng)
int last_arc_sign = 0; // dấu của cung gần nhất, để đếm đổi chiều qua cả đoạn thẳng xen giữa
for (size_t i = 1; i < sbpl_path.size(); ++i) {
path_len_m += std::hypot(sbpl_path[i].x - sbpl_path[i - 1].x,
sbpl_path[i].y - sbpl_path[i - 1].y);
const double d = std::remainder(sbpl_path[i].theta - sbpl_path[i - 1].theta, 2.0 * M_PI);
turn_rad += std::fabs(d);
const int sign = d > 1e-6 ? 1 : (d < -1e-6 ? -1 : 0);
if (sign == 0) { run_sign = 0; continue; }
if (sign != run_sign) {
++arcs;
if (last_arc_sign != 0 && sign != last_arc_sign) ++wiggles;
run_sign = sign;
last_arc_sign = sign;
}
}
const bool corridor_on = corridor_cfg_.enabled && !corridor_mask_.empty();
robot::log_info("[sbpl_lattice_planner] [debug/plan] metrics: start=(%.2f,%.2f) goal=(%.2f,%.2f) "
"straight_m=%.2f path_m=%.2f detour=%.3f turn_deg=%.0f arcs=%d wiggles=%d "
"pts=%zu eps=%.2f expands=%d plan_ms=%.0f corridor=%s corridor_ms=%.1f "
"route_m=%.1f widen=%d smooth=%s raw_m=%.2f smooth_ms=%.1f anchors=%d fillets=%d/%d "
"first_cpu_ms=%.0f first_expands=%d",
start.pose.position.x, start.pose.position.y,
goal.pose.position.x, goal.pose.position.y,
goal_dist_m, path_len_m, path_len_m / std::max(goal_dist_m, 1e-3),
turn_rad * 180.0 / M_PI, arcs, wiggles, sbpl_path.size(),
planner_->get_final_epsilon(), planner_->get_n_expands(),
(plan_time - plan_started).toSec() * 1000.0,
corridor_on ? (corridor_hard_ ? "hard" : "soft") : "off",
corridor_on ? last_corridor_.build_ms : 0.0,
corridor_on ? last_corridor_.route_length_m : 0.0,
corridor_on ? last_corridor_.widen_level : 0,
!smoother_cfg_.enabled ? "off" : (smoothed ? "on" : "skipped"), raw_len_m, smooth_ms,
smooth_stats.anchors, smooth_stats.fillets,
smooth_stats.fillets + smooth_stats.fillets_rejected,
planner_->get_initial_eps_planning_time() * 1000.0,
planner_->get_n_expands_init_solution());
}
// if (publish_footprint_path_) // if (publish_footprint_path_)
// { // {
// robot_visualization_msgs::Marker sbpl_plan_footprint; // robot_visualization_msgs::Marker sbpl_plan_footprint;
@@ -978,6 +1534,195 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start,
return true; return true;
} }
bool SBPLLatticePlanner::smoothLatticePath(const robot_costmap_2d::Costmap2D* grid,
std::vector<EnvNAVXYTHETALAT3Dpt_t>& sbpl_path,
SmootherStats* stats) const
{
if (!grid || footprint_.size() < 3 || sbpl_path.size() < 3) return false;
const double res = grid->getResolution();
const double ox = grid->getOriginX();
const double oy = grid->getOriginY();
const int W = static_cast<int>(grid->getSizeInCellsX());
const int H = static_cast<int>(grid->getSizeInCellsY());
const bool allow_unknown = allow_unknown_;
const int max_cost = smoother_max_cell_cost_;
// Bán kính ngoại tiếp lấy thẳng từ footprint. Ô có vật cản gần nhất xa hơn r_circ + pad thì
// footprint chắc chắn sạch ở MỌI heading -> không phải quét footprint. pad che hai sai số: tâm
// robot lệch tâm ô (<= 0.71 res) và heading làm tròn vào bin 5 độ (<= 0.755 m x sin 2.5 = 3.3 cm).
double r_circ = 0.0;
for (const auto& p : footprint_) r_circ = std::max(r_circ, std::hypot(p.x, p.y));
const double pad_m = 1.5 * res;
const double safe_m = r_circ + pad_m;
const int safe_cells = static_cast<int>(std::ceil(safe_m / res));
const float safe_cells2 = static_cast<float>((safe_m / res) * (safe_m / res));
// KHOẢNG CÁCH TỐI THIỂU tới ô LETHAL cho tâm robot khi kéo dây (22/9, mission 3 sehc): kéo dây
// không nhìn cost, cắt góc sát đúng mép inscribed của costmap TOÀN CỤC; local costmap (laser,
// inflation khác) đặt 253 ngay đó -> Priest "blocked_ahead=#0@0.00m(cost=253)", detour 76 m
// trong 2 s không ra -> ABORTED. Path lattice tự né vì tối ưu cost (gradient 60->252 đẩy ra
// giữa); kéo dây phải né bằng luật riêng. Mặc định = bán kính ngoại tiếp: footprint không chạm gì
// ở mọi heading và còn ~0.27 m dư so với inscribed (T800). Chỗ hẹp không giữ nổi -> giữ bước
// lattice ở đó (không bao giờ tệ hơn đầu vào). Chỉ áp trong vùng EDT tin cậy.
const double clear_m = smoother_min_clearance_m_ < 0.0 ? r_circ : smoother_min_clearance_m_;
const float clear_cells2 = static_cast<float>((clear_m / res) * (clear_m / res));
// 1. Crop quanh bbox path (+2 m cho cung bo góc, + safe để vật cản ngoài crop không lọt) và EDT
// tới ô LETHAL (unknown tính là vật cản khi !allow_unknown). O(cells), ~2M ô cho goal 100 m.
constexpr double kQueryMarginM = 2.0;
double xmin = 1e300, xmax = -1e300, ymin = 1e300, ymax = -1e300;
for (const auto& p : sbpl_path) {
xmin = std::min(xmin, p.x + ox); xmax = std::max(xmax, p.x + ox);
ymin = std::min(ymin, p.y + oy); ymax = std::max(ymax, p.y + oy);
}
const double crop_margin = kQueryMarginM + safe_m + res;
const int cx0 = std::max(0, static_cast<int>(std::floor((xmin - crop_margin - ox) / res)));
const int cy0 = std::max(0, static_cast<int>(std::floor((ymin - crop_margin - oy) / res)));
const int cx1 = std::min(W - 1, static_cast<int>(std::ceil((xmax + crop_margin - ox) / res)));
const int cy1 = std::min(H - 1, static_cast<int>(std::ceil((ymax + crop_margin - oy) / res)));
if (cx1 <= cx0 || cy1 <= cy0) return false;
const int cw = cx1 - cx0 + 1;
const int ch = cy1 - cy0 + 1;
std::vector<uint8_t> obstacle(static_cast<size_t>(cw) * ch, 0);
for (int y = 0; y < ch; ++y) {
for (int x = 0; x < cw; ++x) {
const unsigned char c = grid->getCost(static_cast<unsigned int>(cx0 + x), static_cast<unsigned int>(cy0 + y));
if (c == robot_costmap_2d::LETHAL_OBSTACLE || (c == robot_costmap_2d::NO_INFORMATION && !allow_unknown))
obstacle[static_cast<size_t>(y) * cw + x] = 1;
}
}
std::vector<float> dist2;
squaredDistanceTransform(obstacle, cw, ch, dist2);
// Luật ô cho TÂM robot, y hệt EnvironmentNAVXYTHETALAT::GetActionCost: >= inscribed là cấm.
// "Chắc chắn sạch" lấy từ EDT thay vì cost_possibly_circumscribed_thresh của SBPL: ở fork này
// FREE_SPACE = 60 nên ngưỡng đó (cost tại r_circ = 16 -> 1 thang SBPL) khớp MỌI ô, tức SBPL
// quét footprint ở mọi action; smoother làm vậy thì 100 m mất 3 s (đo 22/9), EDT đưa về ~50 ms.
const auto cell = [&](double x, double y) {
unsigned int mx, my;
if (!grid->worldToMap(x, y, mx, my)) return CellClass::kBlocked;
const unsigned char c = grid->getCost(mx, my);
if (c == robot_costmap_2d::NO_INFORMATION) {
if (!allow_unknown) return CellClass::kBlocked;
} else if (c >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE || static_cast<int>(c) > max_cost) {
return CellClass::kBlocked;
}
const int lx = static_cast<int>(mx) - cx0;
const int ly = static_cast<int>(my) - cy0;
// Sát mép crop có thể có vật cản chưa thấy -> không tin EDT ở đó, quét footprint.
if (lx >= safe_cells && ly >= safe_cells && lx < cw - safe_cells && ly < ch - safe_cells) {
const float d2 = dist2[static_cast<size_t>(ly) * cw + lx];
if (d2 <= clear_cells2) return CellClass::kBlocked;
if (d2 > safe_cells2) return CellClass::kFree;
}
return CellClass::kNearObstacle;
};
// 2. Footprint quét bằng mặt nạ ô theo bin heading (5 độ), đa giác đã nới ra pad_m (offset từng
// cạnh ra ngoài, giao hai cạnh kề — footprint là đa giác lồi). Tính lười, mỗi bin một lần.
constexpr int kBins = 72;
constexpr double kBinRad = 2.0 * M_PI / kBins;
std::vector<std::pair<double, double>> padded;
{
const size_t n = footprint_.size();
double area2 = 0.0;
for (size_t i = 0; i < n; ++i) {
const auto& a = footprint_[i];
const auto& b = footprint_[(i + 1) % n];
area2 += a.x * b.y - b.x * a.y;
}
const double wind = area2 >= 0.0 ? 1.0 : -1.0; // +1 = ngược chiều kim đồng hồ
// Cạnh i: a->b, pháp tuyến ngoài = quay d 90 độ về phía phải (CCW) hoặc trái (CW).
std::vector<std::pair<double, double>> pt(n), dir(n);
for (size_t i = 0; i < n; ++i) {
const auto& a = footprint_[i];
const auto& b = footprint_[(i + 1) % n];
const double dx = b.x - a.x, dy = b.y - a.y;
const double l = std::max(std::hypot(dx, dy), 1e-9);
dir[i] = {dx / l, dy / l};
const double nx = wind * dy / l, ny = -wind * dx / l;
pt[i] = {a.x + nx * pad_m, a.y + ny * pad_m}; // một điểm trên cạnh đã dời
}
padded.resize(n);
for (size_t i = 0; i < n; ++i) {
// Giao đường (pt[i-1], dir[i-1]) với (pt[i], dir[i]) = đỉnh i đã nới.
const size_t h = (i + n - 1) % n;
const double cr = dir[h].first * dir[i].second - dir[h].second * dir[i].first;
if (std::fabs(cr) < 1e-9) { padded[i] = pt[i]; continue; }
const double t = ((pt[i].first - pt[h].first) * dir[i].second - (pt[i].second - pt[h].second) * dir[i].first) / cr;
padded[i] = {pt[h].first + dir[h].first * t, pt[h].second + dir[h].second * t};
}
}
std::vector<std::vector<std::pair<int, int>>> masks(kBins);
std::vector<bool> mask_ready(kBins, false);
const auto mask_for = [&](int bin) -> const std::vector<std::pair<int, int>>& {
if (!mask_ready[bin]) {
const double th = -M_PI + (bin + 0.5) * kBinRad;
const double c = std::cos(th), s = std::sin(th);
std::vector<std::pair<double, double>> poly;
poly.reserve(padded.size());
double bx0 = 1e300, bx1 = -1e300, by0 = 1e300, by1 = -1e300;
for (const auto& v : padded) {
const double px = v.first * c - v.second * s;
const double py = v.first * s + v.second * c;
poly.emplace_back(px, py);
bx0 = std::min(bx0, px); bx1 = std::max(bx1, px);
by0 = std::min(by0, py); by1 = std::max(by1, py);
}
double area2 = 0.0;
for (size_t i = 0; i < poly.size(); ++i) {
const auto& a = poly[i];
const auto& b = poly[(i + 1) % poly.size()];
area2 += a.first * b.second - b.first * a.second;
}
const double sign = area2 >= 0.0 ? 1.0 : -1.0;
std::vector<std::pair<int, int>>& m = masks[bin];
for (int dy = static_cast<int>(std::floor(by0 / res)); dy <= static_cast<int>(std::ceil(by1 / res)); ++dy) {
for (int dx = static_cast<int>(std::floor(bx0 / res)); dx <= static_cast<int>(std::ceil(bx1 / res)); ++dx) {
const double wx = dx * res, wy = dy * res;
bool inside = true;
for (size_t i = 0; i < poly.size() && inside; ++i) {
const auto& a = poly[i];
const auto& b = poly[(i + 1) % poly.size()];
const double cr = (b.first - a.first) * (wy - a.second) - (b.second - a.second) * (wx - a.first);
if (cr * sign < 0.0) inside = false;
}
if (inside) m.emplace_back(dx, dy);
}
}
mask_ready[bin] = true;
}
return masks[bin];
};
const auto pose_free = [&](double x, double y, double theta) {
unsigned int mx, my;
if (!grid->worldToMap(x, y, mx, my)) return false;
const double a = std::remainder(theta, 2.0 * M_PI); // [-pi, pi)
int bin = static_cast<int>(std::floor((a + M_PI) / kBinRad));
bin = std::min(std::max(bin, 0), kBins - 1);
for (const auto& off : mask_for(bin)) {
const int qx = static_cast<int>(mx) + off.first;
const int qy = static_cast<int>(my) + off.second;
if (qx < 0 || qy < 0 || qx >= W || qy >= H) return false; // footprint đè mép lưới
const unsigned char c = grid->getCost(static_cast<unsigned int>(qx), static_cast<unsigned int>(qy));
if (c == robot_costmap_2d::LETHAL_OBSTACLE) return false;
if (c == robot_costmap_2d::NO_INFORMATION && !allow_unknown) return false;
}
return true;
};
std::vector<SmoothPose> in;
in.reserve(sbpl_path.size());
for (const auto& p : sbpl_path) in.push_back({p.x + ox, p.y + oy, p.theta});
std::vector<SmoothPose> out;
PathSmoother smoother(smoother_cfg_, cell, pose_free);
if (!smoother.smooth(in, out, stats) || out.size() < 2) return false;
sbpl_path.clear();
sbpl_path.reserve(out.size());
for (const auto& p : out) sbpl_path.push_back(EnvNAVXYTHETALAT3Dpt_t(p.x - ox, p.y - oy, p.theta));
return true;
}
void SBPLLatticePlanner::getFootprintList(const std::vector<EnvNAVXYTHETALAT3Dpt_t>& sbpl_path, void SBPLLatticePlanner::getFootprintList(const std::vector<EnvNAVXYTHETALAT3Dpt_t>& sbpl_path,
const std::string& path_frame_id, robot_visualization_msgs::Marker& ma) const std::string& path_frame_id, robot_visualization_msgs::Marker& ma)
{ {

276
test/path_smoother_test.cpp Normal file
View File

@@ -0,0 +1,276 @@
// Unit tests for PathSmoother on synthetic worlds (no costmap, no SBPL).
#include <cmath>
#include <vector>
#include <gtest/gtest.h>
#include "sbpl_lattice_planner/distance_map.h"
#include "sbpl_lattice_planner/path_smoother.h"
using sbpl_lattice_planner::CellClass;
using sbpl_lattice_planner::PathSmoother;
using sbpl_lattice_planner::SmoothPose;
using sbpl_lattice_planner::SmootherConfig;
using sbpl_lattice_planner::SmootherStats;
namespace
{
struct Rect
{
double x0, y0, x1, y1;
bool contains(double x, double y, double margin) const
{
return x >= x0 - margin && x <= x1 + margin && y >= y0 - margin && y <= y1 + margin;
}
};
/// World of axis-aligned obstacles. Centre blocked within `inscribed` of a rectangle, footprint
/// check required within `circumscribed`; footprint = 1.17 x 0.96 m box (T800) tested by corners.
struct World
{
std::vector<Rect> obstacles;
double inscribed = 0.48;
double circumscribed = 0.76;
CellClass cell(double x, double y) const
{
CellClass c = CellClass::kFree;
for (const Rect& r : obstacles) {
if (r.contains(x, y, inscribed)) return CellClass::kBlocked;
if (r.contains(x, y, circumscribed)) c = CellClass::kNearObstacle;
}
return c;
}
bool pose(double x, double y, double th) const
{
const double hl = 0.583, hw = 0.48;
const double c = std::cos(th), s = std::sin(th);
const double cx[4] = {hl, hl, -hl, -hl};
const double cy[4] = {-hw, hw, hw, -hw};
for (int i = 0; i < 4; ++i) {
const double px = x + cx[i] * c - cy[i] * s;
const double py = y + cx[i] * s + cy[i] * c;
for (const Rect& r : obstacles)
if (r.contains(px, py, 0.0)) return false;
}
return true;
}
PathSmoother smoother(SmootherConfig cfg = SmootherConfig()) const
{
cfg.enabled = true;
return PathSmoother(cfg, [this](double x, double y) { return cell(x, y); },
[this](double x, double y, double th) { return pose(x, y, th); });
}
/// Every output pose must pass the same rule the smoother promised to honour.
void expectFree(const std::vector<SmoothPose>& p) const
{
for (const SmoothPose& q : p) {
const CellClass c = cell(q.x, q.y);
EXPECT_NE(c, CellClass::kBlocked) << "blocked at (" << q.x << "," << q.y << ")";
if (c == CellClass::kNearObstacle) {
EXPECT_TRUE(pose(q.x, q.y, q.theta)) << "footprint at (" << q.x << "," << q.y << ")";
}
}
}
};
/// Dense polyline through `v` at 5 cm, heading = segment direction (what the lattice gives).
std::vector<SmoothPose> dense(const std::vector<std::pair<double, double>>& v, double step = 0.05)
{
std::vector<SmoothPose> out;
for (std::size_t i = 1; i < v.size(); ++i) {
const double dx = v[i].first - v[i - 1].first, dy = v[i].second - v[i - 1].second;
const double len = std::hypot(dx, dy), th = std::atan2(dy, dx);
const int n = std::max(1, static_cast<int>(std::ceil(len / step)));
for (int s = 0; s < n; ++s)
out.push_back({v[i - 1].first + dx * s / n, v[i - 1].second + dy * s / n, th});
}
const auto& e = v.back();
out.push_back({e.first, e.second, out.empty() ? 0.0 : out.back().theta});
return out;
}
double maxStep(const std::vector<SmoothPose>& p)
{
double m = 0.0;
for (std::size_t i = 1; i < p.size(); ++i) m = std::max(m, std::hypot(p[i].x - p[i - 1].x, p[i].y - p[i - 1].y));
return m;
}
double maxHeadingJump(const std::vector<SmoothPose>& p)
{
double m = 0.0;
for (std::size_t i = 1; i < p.size(); ++i) m = std::max(m, std::fabs(std::remainder(p[i].theta - p[i - 1].theta, 2 * M_PI)));
return m;
}
} // namespace
TEST(PathSmoother, ZigzagInOpenSpaceBecomesOneSegment)
{
World w; // nothing in it
std::vector<std::pair<double, double>> v;
double x = 0, y = 0;
v.push_back({x, y});
for (int k = 0; k < 20; ++k) { // 0 / 22.5 deg alternating, 0.5 m legs — the lattice staircase
const double th = k % 2 ? 22.5 * M_PI / 180.0 : 0.0;
x += 0.5 * std::cos(th);
y += 0.5 * std::sin(th);
v.push_back({x, y});
}
auto in = dense(v);
in.back().theta = std::atan2(y, x); // goal yaw along the chord, so one heading end to end
std::vector<SmoothPose> out;
SmootherStats st;
ASSERT_TRUE(w.smoother().smooth(in, out, &st));
EXPECT_EQ(st.anchors, 2);
EXPECT_EQ(st.fillets, 0);
EXPECT_NEAR(st.out_len_m, std::hypot(x, y), 1e-6);
EXPECT_LT(st.out_len_m, st.in_len_m);
EXPECT_LE(maxStep(out), 0.05 + 1e-9);
EXPECT_LT(maxHeadingJump(out), 1e-9); // one heading all the way
EXPECT_NEAR(out.front().x, 0.0, 1e-9);
EXPECT_NEAR(out.back().x, x, 1e-9);
EXPECT_NEAR(out.back().y, y, 1e-9);
w.expectFree(out);
}
TEST(PathSmoother, WallForcesCornerWithTangentFillet)
{
World w;
w.obstacles.push_back({2.0, 1.0, 8.0, 9.0});
const auto in = dense({{0, 0}, {10, 0}, {10, 10}});
std::vector<SmoothPose> out;
SmootherStats st;
ASSERT_TRUE(w.smoother().smooth(in, out, &st));
EXPECT_EQ(st.anchors, 3);
EXPECT_EQ(st.fillets, 1);
EXPECT_EQ(st.fillets_rejected, 0);
EXPECT_LT(st.out_len_m, st.in_len_m);
// Tangent-continuous: no heading jump larger than one arc sample (step / R).
EXPECT_LT(maxHeadingJump(out), 0.05 / 1.06 + 1e-6);
EXPECT_LE(maxStep(out), 0.05 + 1e-6);
EXPECT_NEAR(out.back().x, 10.0, 1e-9);
EXPECT_NEAR(out.back().y, 10.0, 1e-9);
w.expectFree(out);
}
TEST(PathSmoother, FilletThatCollidesFallsBackToSharpCorner)
{
World w;
w.obstacles.push_back({2.0, 1.0, 8.0, 9.0});
w.obstacles.push_back({9.0, 0.7, 9.4, 1.2}); // post inside the corner the arc would cut
const auto in = dense({{0, 0}, {10, 0}, {10, 10}});
std::vector<SmoothPose> out;
SmootherStats st;
ASSERT_TRUE(w.smoother().smooth(in, out, &st));
EXPECT_EQ(st.fillets, 0);
EXPECT_GE(st.fillets_rejected, 1);
// Sharp corner = duplicate position carrying two headings (turn in place for the tracker).
bool dup = false;
for (std::size_t i = 1; i < out.size(); ++i)
if (std::hypot(out[i].x - out[i - 1].x, out[i].y - out[i - 1].y) < 1e-9 &&
std::fabs(std::remainder(out[i].theta - out[i - 1].theta, 2 * M_PI)) > 0.5)
dup = true;
EXPECT_TRUE(dup);
w.expectFree(out);
}
TEST(PathSmoother, ReverseMotionLeavesPathUntouched)
{
World w;
auto in = dense({{0, 0}, {5, 0}});
for (SmoothPose& p : in) p.theta = M_PI; // heading opposite to travel: driving backwards
std::vector<SmoothPose> out;
EXPECT_FALSE(w.smoother().smooth(in, out));
EXPECT_TRUE(out.empty());
}
TEST(PathSmoother, EndpointsAndGoalYawPreserved)
{
World w;
auto in = dense({{0, 0}, {3, 4}, {6, 0}});
in.back().theta = 1.234; // goal yaw
std::vector<SmoothPose> out;
ASSERT_TRUE(w.smoother().smooth(in, out));
EXPECT_NEAR(out.front().x, 0.0, 1e-9);
EXPECT_NEAR(out.front().y, 0.0, 1e-9);
EXPECT_NEAR(out.front().theta, 0.0, 1e-9); // straight to (6,0): open space, one segment
EXPECT_NEAR(out.back().x, 6.0, 1e-9);
EXPECT_NEAR(out.back().y, 0.0, 1e-9);
EXPECT_NEAR(out.back().theta, 1.234, 1e-9);
}
TEST(PathSmoother, FootprintCheckBlocksShortcutTheCentreWouldAllow)
{
// Narrow slot: centre fits (kNearObstacle) but the 0.96 m wide footprint does not when driving
// along y = 0 between two posts 0.7 m apart. The detour above them must survive.
World w;
w.inscribed = 0.3; // posts 0.7 m apart leave the centre line unblocked
w.circumscribed = 0.8;
w.obstacles.push_back({4.0, -2.0, 6.0, -0.35});
w.obstacles.push_back({4.0, 0.35, 6.0, 2.0});
const auto in = dense({{0, 0}, {3, 0}, {3, 3.5}, {7, 3.5}, {7, 0}, {10, 0}});
std::vector<SmoothPose> out;
SmootherStats st;
ASSERT_TRUE(w.smoother().smooth(in, out, &st));
EXPECT_GT(st.out_len_m, 10.0 + 1.0); // did not cut straight through the slot
EXPECT_LT(st.out_len_m, st.in_len_m); // but did shortcut the rectangular detour
w.expectFree(out);
}
TEST(PathSmoother, JunctionPrefersLatticeAlignedEndPoint)
{
// East leg (0,0)->(10,0), north leg (10,0)->(10,5) between a wall at x >= 11.2 and a block at
// x <= 9.3 above y = 2.5. From (0,0) the farthest visible point is (10, ~2.4) on the north leg,
// but that chord meets the north heading at ~77 deg. With the junction rule the smoother stops
// at (10,0) (chord along the east heading, then a fillet); with the rule off it takes the
// farthest visible point and the first output heading is the 13 deg chord.
World w;
w.obstacles.push_back({11.2, -1.0, 12.5, 3.0});
w.obstacles.push_back({8.0, 2.5, 9.3, 6.0});
const auto in = dense({{0, 0}, {10, 0}, {10, 5}});
SmootherConfig cfg;
cfg.max_junction_deg = 20.0;
std::vector<SmoothPose> out;
SmootherStats st;
ASSERT_TRUE(w.smoother(cfg).smooth(in, out, &st));
EXPECT_EQ(st.anchors, 3);
EXPECT_EQ(st.fillets, 1);
EXPECT_NEAR(out.front().theta, 0.0, 1e-6);
w.expectFree(out);
cfg.max_junction_deg = 0.0;
ASSERT_TRUE(w.smoother(cfg).smooth(in, out, &st));
EXPECT_GT(out.front().theta, 0.15); // chord straight to the north leg
w.expectFree(out);
}
TEST(DistanceMap, SquaredEuclideanToNearestObstacle)
{
// 7x5 grid, obstacles at (1,1) and (5,3): every cell must report the true squared distance.
const int w = 7, h = 5;
std::vector<uint8_t> obs(w * h, 0);
obs[1 * w + 1] = 1;
obs[3 * w + 5] = 1;
std::vector<float> d2;
sbpl_lattice_planner::squaredDistanceTransform(obs, w, h, d2);
ASSERT_EQ(d2.size(), static_cast<std::size_t>(w * h));
for (int y = 0; y < h; ++y)
for (int x = 0; x < w; ++x) {
const float a = static_cast<float>((x - 1) * (x - 1) + (y - 1) * (y - 1));
const float b = static_cast<float>((x - 5) * (x - 5) + (y - 3) * (y - 3));
EXPECT_FLOAT_EQ(d2[y * w + x], std::min(a, b)) << "at (" << x << "," << y << ")";
}
// No obstacle at all: everything far away.
std::fill(obs.begin(), obs.end(), 0);
sbpl_lattice_planner::squaredDistanceTransform(obs, w, h, d2);
for (float v : d2) EXPECT_GE(v, 1.0e6f);
}
int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

Binary file not shown.

427
tools/eval_plan_bag.py Executable file
View File

@@ -0,0 +1,427 @@
#!/usr/bin/env python3
"""Offline evaluation of global plans recorded in a rosbag (and/or the planner's tee log).
Answers two questions about SBPLLatticePlanner output, with or without the Voronoi corridor:
1. Smoothness — does the path wind where it could go straight? For every plan the script
string-pulls it against the recorded global costmap (greedy line-of-sight shortcutting,
robot centre must stay on cells below INSCRIBED) and reports how much of the path length
that removes (`slack`). A high `slack` with corridor=on and low with corridor=off means
the corridor is bending the path; high in both means the lattice/mprim set is.
2. Cost — plan time / eps / expands, taken from the `[debug/plan] metrics:` lines of the tee
log written by the planner (needs `debug_plan: true`).
Usage:
# record while driving goals (see README "Đánh giá đường đi"):
# /global_costmap/costmap /global_costmap/costmap_updates /global_costmap/costmap/plan
# /move_base_simple/goal /tf /tf_static
python3 eval_plan_bag.py --bag soft=/tmp/eval_soft.bag --bag off=/tmp/eval_off.bag \
--log soft=/tmp/sim_soft.log --log off=/tmp/sim_off.log --cache /tmp/eval_cache \
--csv /tmp/eval.csv --plot /tmp/eval
Columns: `detour` = path / straight line; `opt2d_m` = shortest 8-connected point-robot route on the
recorded costmap (skimage), `over_opt` = path / opt2d — the honest "how much longer than it had to
be"; `slack` = share of the path removed by greedy line-of-sight shortcutting.
Each --bag/--log takes `label=path`; labels join bag rows with log rows (matched by goal
position, in order). Only the FIRST plan of each goal is scored unless --all-plans is given,
because replans start from a moving robot and are not comparable across runs.
Requires ROS Noetic python3 (`rosbag`, `numpy`); matplotlib only for --plot.
"""
import argparse
import csv
import math
import os
import pickle
import re
import sys
import numpy as np
# OccupancyGrid values written by move_base2's CostmapExporter (costmap_exporter.cpp):
# -1 unknown, 0 free, 1..98 inflated, 99 inscribed, 100 lethal, 120 preferred,
# 150 critical (overflows int8 to -106). "Passable for the robot centre" = below inscribed.
OCC_INSCRIBED = 99
OCC_PREFERRED = 120
def yaw_from_quat(q):
return math.atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z))
def wrap(a):
return (a + math.pi) % (2.0 * math.pi) - math.pi
class Grid:
def __init__(self, msg, allow_unknown):
self.res = msg.info.resolution
self.ox = msg.info.origin.position.x
self.oy = msg.info.origin.position.y
self.w = msg.info.width
self.h = msg.info.height
self.data = np.array(msg.data, dtype=np.int16).reshape(self.h, self.w)
self.allow_unknown = allow_unknown
def apply_update(self, upd):
patch = np.array(upd.data, dtype=np.int16).reshape(upd.height, upd.width)
self.data[upd.y:upd.y + upd.height, upd.x:upd.x + upd.width] = patch
def passable_mask(self):
d = self.data
m = (d >= 0) & (d < OCC_INSCRIBED)
m |= d == OCC_PREFERRED
if self.allow_unknown:
m |= d == -1
return m
def to_cell(self, x, y):
return (x - self.ox) / self.res, (y - self.oy) / self.res
def crop(self, xmin, ymin, xmax, ymax):
"""Sub-grid covering the world box (clamped to the map). Keeps the cache small."""
cx0 = max(0, int(math.floor((xmin - self.ox) / self.res)))
cy0 = max(0, int(math.floor((ymin - self.oy) / self.res)))
cx1 = min(self.w, int(math.ceil((xmax - self.ox) / self.res)) + 1)
cy1 = min(self.h, int(math.ceil((ymax - self.oy) / self.res)) + 1)
g = Grid.__new__(Grid)
g.res = self.res
g.ox = self.ox + cx0 * self.res
g.oy = self.oy + cy0 * self.res
g.w = cx1 - cx0
g.h = cy1 - cy0
g.data = self.data[cy0:cy1, cx0:cx1].copy()
g.allow_unknown = self.allow_unknown
return g
def optimal_2d_length(grid, mask, p, q):
"""Length [m] of the shortest 8-connected point-robot path p->q over passable cells (skimage
MCP_Geometric). Lower bound for any footprint path; `path_m / opt2d_m` is how much the lattice,
eps and corridor together stretched the path. NaN when skimage is missing or no route."""
try:
from skimage.graph import route_through_array
except ImportError:
return float('nan')
cost = np.where(mask, 1.0, 1e6) # blocked cells still traversable at 1e6 so MCP never throws
cx0, cy0 = grid.to_cell(p[0], p[1])
cx1, cy1 = grid.to_cell(q[0], q[1])
s = (int(round(cy0)), int(round(cx0)))
t = (int(round(cy1)), int(round(cx1)))
if not (0 <= s[0] < grid.h and 0 <= s[1] < grid.w and 0 <= t[0] < grid.h and 0 <= t[1] < grid.w):
return float('nan')
idx, total = route_through_array(cost, s, t, fully_connected=True, geometric=True)
if total >= 1e6:
return float('nan') # went through a blocked cell: no real route inside the crop
idx = np.array(idx)
d = np.diff(idx, axis=0)
return float(np.sum(np.hypot(d[:, 0], d[:, 1])) * grid.res)
def line_of_sight(mask, grid, p, q):
"""True if every cell under segment p->q (world coords) is passable. Samples at half a cell."""
cx0, cy0 = grid.to_cell(p[0], p[1])
cx1, cy1 = grid.to_cell(q[0], q[1])
n = int(max(2, math.ceil(math.hypot(cx1 - cx0, cy1 - cy0) * 2.0)))
xs = np.rint(np.linspace(cx0, cx1, n)).astype(int)
ys = np.rint(np.linspace(cy0, cy1, n)).astype(int)
if (xs < 0).any() or (ys < 0).any() or (xs >= grid.w).any() or (ys >= grid.h).any():
return False
return bool(mask[ys, xs].all())
def string_pull(pts, mask, grid):
"""Greedy shortcut: from anchor i take the farthest j with clear line of sight. Exact
(scans j downward), O(anchors * n) LOS checks — fine for a few hundred points."""
out = [0]
i = 0
n = len(pts)
while i < n - 1:
j = n - 1
while j > i + 1 and not line_of_sight(mask, grid, pts[i], pts[j]):
j -= 1
out.append(j)
i = j
return out
def path_metrics(xy, th):
"""Same definitions as the planner's `[debug/plan] metrics:` line (sbpl_lattice_planner.cpp)."""
path_m = 0.0
turn = 0.0
arcs = wiggles = 0
run_sign = last_sign = 0
for i in range(1, len(xy)):
path_m += math.hypot(xy[i][0] - xy[i - 1][0], xy[i][1] - xy[i - 1][1])
d = wrap(th[i] - th[i - 1])
turn += abs(d)
s = 1 if d > 1e-6 else (-1 if d < -1e-6 else 0)
if s == 0:
run_sign = 0
continue
if s != run_sign:
arcs += 1
if last_sign != 0 and s != last_sign:
wiggles += 1
run_sign = last_sign = s
straight = math.hypot(xy[-1][0] - xy[0][0], xy[-1][1] - xy[0][1])
return xy, dict(pts=len(xy), straight_m=straight, path_m=path_m,
detour=path_m / max(straight, 1e-3), turn_deg=math.degrees(turn),
arcs=arcs, wiggles=wiggles)
def read_bag(path, allow_unknown, all_plans, topics):
import rosbag
grid = None
plans = []
last_goal = None
seen_goal_ids = set()
with rosbag.Bag(path) as bag:
for topic, msg, t in bag.read_messages(topics=[topics['costmap'], topics['costmap'] + '_updates',
topics['plan'], topics['goal']]):
if topic == topics['costmap']:
grid = Grid(msg, allow_unknown)
elif topic == topics['costmap'] + '_updates':
if grid is not None:
grid.apply_update(msg)
elif topic == topics['goal']:
last_goal = (msg.pose.position.x, msg.pose.position.y)
elif topic == topics['plan']:
if len(msg.poses) < 2:
continue
stamp = msg.header.stamp.to_sec()
if plans and abs(plans[-1]['stamp'] - stamp) < 1e-6:
continue # same plan republished at 10 Hz
goal = (round(msg.poses[-1].pose.position.x, 2), round(msg.poses[-1].pose.position.y, 2))
first = goal not in seen_goal_ids
seen_goal_ids.add(goal)
if not first and not all_plans:
continue
xy = [(p.pose.position.x, p.pose.position.y) for p in msg.poses]
yaw = [yaw_from_quat(p.pose.orientation) for p in msg.poses]
crop = None
if grid is not None:
xs = [c[0] for c in xy]
ys = [c[1] for c in xy]
crop = grid.crop(min(xs) - CROP_MARGIN_M, min(ys) - CROP_MARGIN_M,
max(xs) + CROP_MARGIN_M, max(ys) + CROP_MARGIN_M)
plans.append(dict(stamp=stamp, t=t.to_sec(), goal=goal, first=first,
xy=xy, yaw=yaw, grid=crop, sent_goal=last_goal))
return plans
CROP_MARGIN_M = 20.0 # [m] around the path bbox: room for the optimal 2D route to detour
def load_plans(label, path, allow_unknown, all_plans, topics, cache_dir):
"""Bag read is the slow part (a full costmap is 9 MB per message); cache the extracted plans
+ cropped grids per label so re-analysis after a script change is seconds, not minutes."""
cache = os.path.join(cache_dir, f'{label}.pkl') if cache_dir else None
if cache and os.path.exists(cache) and os.path.getmtime(cache) >= os.path.getmtime(path):
with open(cache, 'rb') as f:
return pickle.load(f)
plans = read_bag(path, allow_unknown, all_plans, topics)
if cache:
os.makedirs(cache_dir, exist_ok=True)
with open(cache, 'wb') as f:
pickle.dump(plans, f, protocol=pickle.HIGHEST_PROTOCOL)
return plans
LOG_RE = re.compile(r'\[debug/plan\] metrics: (.*)$')
KV_RE = re.compile(r'(\w+)=(\([^)]*\)|[^\s]+)')
def read_log(path):
rows = []
with open(path, errors='replace') as f:
for line in f:
m = LOG_RE.search(line)
if not m:
continue
kv = dict(KV_RE.findall(m.group(1)))
gx, gy = kv['goal'].strip('()').split(',')
row = dict(goal=(round(float(gx), 2), round(float(gy), 2)))
for k in ('straight_m', 'path_m', 'detour', 'turn_deg', 'plan_ms', 'corridor_ms', 'route_m', 'eps',
'raw_m', 'smooth_ms', 'first_cpu_ms'):
row[k] = float(kv.get(k, 'nan'))
for k in ('arcs', 'wiggles', 'pts', 'expands', 'widen', 'anchors', 'first_expands'):
row[k] = int(kv.get(k, '0'))
row['corridor'] = kv.get('corridor', '?')
row['smooth'] = kv.get('smooth', '?')
row['fillets'] = kv.get('fillets', '')
rows.append(row)
return rows
LOG_JOIN_COLS = ('plan_ms', 'corridor_ms', 'route_m', 'eps', 'expands', 'corridor', 'widen',
'raw_m', 'smooth', 'smooth_ms', 'anchors', 'fillets', 'first_cpu_ms', 'first_expands')
def match_log(plan_rows, log_rows):
"""Attach the k-th log row whose goal lies within 0.1 m to the k-th bag plan with that goal
(the bag's goal is the plan's last pose, the log's is the requested goal — they differ by the
lattice cell rounding, so no exact match)."""
used = [False] * len(log_rows)
for r in plan_rows:
for i, lr in enumerate(log_rows):
if not used[i] and math.hypot(lr['goal'][0] - r['goal'][0], lr['goal'][1] - r['goal'][1]) <= 0.1:
used[i] = True
for k in LOG_JOIN_COLS:
r[k] = lr[k]
break
def evaluate(label, plans):
rows = []
for p in plans:
xy = p['xy']
_, m = path_metrics(xy, p['yaw'])
m.update(label=label, stamp=p['stamp'], goal=p['goal'], first=p['first'])
if p['grid'] is not None:
mask = p['grid'].passable_mask()
idx = string_pull(xy, mask, p['grid'])
sc = sum(math.hypot(xy[idx[k]][0] - xy[idx[k - 1]][0], xy[idx[k]][1] - xy[idx[k - 1]][1])
for k in range(1, len(idx)))
m['shortcut_m'] = sc
m['sc_pts'] = len(idx)
m['slack'] = (m['path_m'] - sc) / max(m['path_m'], 1e-3)
m['opt2d_m'] = optimal_2d_length(p['grid'], mask, xy[0], xy[-1])
m['over_opt'] = m['path_m'] / m['opt2d_m'] if m['opt2d_m'] > 0 else float('nan')
m['_xy'] = xy
m['_sc'] = [xy[i] for i in idx]
m['_grid'] = p['grid']
else:
m['shortcut_m'] = float('nan')
m['sc_pts'] = 0
m['slack'] = float('nan')
m['opt2d_m'] = float('nan')
m['over_opt'] = float('nan')
rows.append(m)
return rows
COLS = ['label', 'goal', 'first', 'straight_m', 'path_m', 'detour', 'opt2d_m', 'over_opt', 'shortcut_m',
'slack', 'turn_deg', 'arcs', 'wiggles', 'pts', 'plan_ms', 'corridor_ms', 'eps', 'expands',
'corridor', 'route_m', 'widen', 'smooth', 'raw_m', 'smooth_ms', 'fillets', 'first_cpu_ms', 'first_expands']
def fmt(v):
if isinstance(v, float):
return f'{v:.3f}' if abs(v) < 10 else f'{v:.1f}'
if isinstance(v, tuple):
return f'({v[0]:.1f},{v[1]:.1f})'
return str(v)
def print_table(rows):
widths = {c: max(len(c), *(len(fmt(r.get(c, ''))) for r in rows)) for c in COLS}
print(' '.join(c.rjust(widths[c]) for c in COLS))
for r in rows:
print(' '.join(fmt(r.get(c, '')).rjust(widths[c]) for c in COLS))
def print_summary(rows):
by = {}
for r in rows:
by.setdefault(r['label'], []).append(r)
print('\nsummary (median over plans, first plan per goal):')
for label, rs in by.items():
rs = [r for r in rs if r['first']] or rs
def med(k):
vals = [r[k] for r in rs if k in r]
return float(np.nanmedian(vals)) if vals else float('nan')
print(f" {label:>10}: n={len(rs)} detour={med('detour'):.3f} over_opt={med('over_opt'):.3f} "
f"slack={med('slack'):.3f} turn_deg={med('turn_deg'):.0f} wiggles={med('wiggles'):.0f} "
f"plan_ms={med('plan_ms'):.0f} eps={med('eps'):.2f}")
def plot(rows, prefix):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
for k, r in enumerate(rows):
if '_grid' not in r:
continue
g = r['_grid']
fig, ax = plt.subplots(figsize=(10, 10))
ax.imshow(g.data, cmap='gray_r', origin='lower', vmin=-1, vmax=100,
extent=[g.ox, g.ox + g.w * g.res, g.oy, g.oy + g.h * g.res])
xy = np.array(r['_xy'])
sc = np.array(r['_sc'])
ax.plot(xy[:, 0], xy[:, 1], 'r-', lw=1.2, label=f"plan {r['path_m']:.1f} m")
ax.plot(sc[:, 0], sc[:, 1], 'g--', lw=1.0, label=f"string-pull {r['shortcut_m']:.1f} m")
pad = 3.0
ax.set_xlim(xy[:, 0].min() - pad, xy[:, 0].max() + pad)
ax.set_ylim(xy[:, 1].min() - pad, xy[:, 1].max() + pad)
ax.set_title(f"{r['label']} goal={fmt(r['goal'])} detour={r['detour']:.2f} over_opt={r['over_opt']:.2f} "
f"slack={r['slack']:.2f} turn={r['turn_deg']:.0f}deg wiggles={r['wiggles']}")
ax.legend(loc='upper right')
out = f"{prefix}_{r['label']}_{k:02d}.png"
fig.savefig(out, dpi=110, bbox_inches='tight')
plt.close(fig)
print(f'plot: {out}')
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('--bag', action='append', default=[], metavar='LABEL=PATH')
ap.add_argument('--log', action='append', default=[], metavar='LABEL=PATH',
help='planner tee log; adds plan_ms/eps/expands/corridor columns')
ap.add_argument('--csv', help='write all rows here')
ap.add_argument('--plot', metavar='PREFIX', help='write <PREFIX>_<label>_<k>.png per plan')
ap.add_argument('--all-plans', action='store_true', help='score replans too, not only the first plan per goal')
ap.add_argument('--no-unknown', action='store_true', help='treat unknown (-1) as blocked for line of sight')
ap.add_argument('--cache', metavar='DIR', help='cache extracted plans per label here; reused while the bag is unchanged')
ap.add_argument('--plan-topic', default='/global_costmap/costmap/plan')
ap.add_argument('--costmap-topic', default='/global_costmap/costmap')
ap.add_argument('--goal-topic', default='/move_base_simple/goal')
args = ap.parse_args()
if not args.bag and not args.log:
ap.error('give at least one --bag or --log')
topics = dict(plan=args.plan_topic, costmap=args.costmap_topic, goal=args.goal_topic)
logs = {}
for spec in args.log:
label, path = spec.split('=', 1)
logs[label] = read_log(path)
rows = []
for spec in args.bag:
label, path = spec.split('=', 1)
plans = load_plans(label, path, not args.no_unknown, args.all_plans, topics, args.cache)
if not plans:
print(f'{label}: no plans on {topics["plan"]} in {path}', file=sys.stderr)
rs = evaluate(label, plans)
if label in logs:
match_log(rs, logs[label])
rows.extend(rs)
for label, lrs in logs.items(): # log-only labels: still print their cost columns
if not any(r['label'] == label for r in rows):
for lr in lrs:
lr.update(label=label, first=True, shortcut_m=float('nan'), slack=float('nan'),
opt2d_m=float('nan'), over_opt=float('nan'))
rows.extend(lrs)
if not rows:
print('no plans found (bag: no messages on the plan topic; log: no "[debug/plan] metrics:" '
'lines — needs debug_plan: true and a planner built after 2026-09-22)', file=sys.stderr)
sys.exit(1)
print_table(rows)
print_summary(rows)
if args.csv:
with open(args.csv, 'w', newline='') as f:
w = csv.DictWriter(f, fieldnames=COLS, extrasaction='ignore')
w.writeheader()
for r in rows:
w.writerow({c: fmt(r.get(c, '')) for c in COLS})
print(f'csv: {args.csv}')
if args.plot:
plot(rows, args.plot)
if __name__ == '__main__':
main()