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

This reverts commit 3fff3b15cd.
This commit is contained in:
2026-10-03 15:30:14 +07:00
parent 3fff3b15cd
commit d3a9b3f271
13 changed files with 100 additions and 2510 deletions

View File

@@ -72,8 +72,6 @@ if (NOT BUILDING_WITH_CATKIN)
robot_nav_core
robot_protocol_msgs
robot_cpp
robot_sensor_ports
route_graph
)
else()
@@ -93,8 +91,6 @@ else()
robot_nav_core
robot_protocol_msgs
robot_cpp
robot_sensor_ports
route_graph
)
find_library(TF3_LIBRARY NAMES tf3)
@@ -102,7 +98,7 @@ else()
catkin_package(
INCLUDE_DIRS include
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 robot_sensor_ports route_graph
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
DEPENDS Eigen3 Boost SBPL
)
@@ -119,8 +115,6 @@ endif()
# ========================================================
add_library(${PROJECT_NAME} SHARED
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
@@ -169,35 +163,6 @@ else()
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
# ========================================================

132
README.md
View File

@@ -77,11 +77,7 @@ 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 |
| `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 |
| `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) |
| `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 |
| `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 |
| `nominalvel_mpersecs` | double | 0.4 | [m/s] vận tốc danh định — dùng tính cost thời gian của primitive |
@@ -107,132 +103,6 @@ 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
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
```bash

View File

@@ -3,25 +3,7 @@ SBPLLatticePlanner:
environment_type: XYThetaLattice
planner_type: ARAPlanner
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
# 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
forward_search: true
# Bỏ ràng buộc heading xuất phát: local planner đã có bước quay tại chỗ đầu path
@@ -45,10 +27,7 @@ SBPLLatticePlanner:
# 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.
# [bool] Nhóm log thông tin: "audit: start cell ... goal cell ...", "2D reachability: h=<số>",
# "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.
# "solved: ... expands= h_2d= phase=". Mặc định BẬT; tắt khi log robot thật quá dày.
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.
# 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.
@@ -58,107 +37,3 @@ SBPLLatticePlanner:
nominalvel_mpersecs: 0.3
timetoturn45degsinplace_secs: 1.31 # = 0.6 rad/s
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

@@ -1,34 +0,0 @@
/*********************************************************************
*
* 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

@@ -1,127 +0,0 @@
/*********************************************************************
*
* 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,9 +2,7 @@
#define SBPL_LATTICE_PLANNER_H
#include <atomic>
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
@@ -24,19 +22,10 @@ using namespace std;
#include <robot_nav_core/base_global_planner.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{
class SBPLLatticePlanner : public robot_nav_core::BaseGlobalPlanner,
public robot_nav_core::Preemptable,
public robot_sensor_ports::SensorConsumer {
public robot_nav_core::Preemptable {
public:
/**
@@ -100,12 +89,6 @@ public:
*/
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(){};
static robot_nav_core::BaseGlobalPlanner::Ptr create();
@@ -134,17 +117,6 @@ private:
double allocated_time_; /**< amount of time allowed for 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 cost_map_topic_; /** what topic is being used for the costmap topic */
@@ -205,76 +177,6 @@ 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.
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_;
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 */
@@ -282,19 +184,6 @@ private:
std::vector<robot_geometry_msgs::Point> footprint_prev_;
unsigned int current_env_width_;
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,11 +90,4 @@
<build_depend>sbpl</build_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>

View File

@@ -1,78 +0,0 @@
/*********************************************************************
*
* 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

View File

@@ -1,315 +0,0 @@
/*********************************************************************
*
* 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

File diff suppressed because it is too large Load Diff

View File

@@ -1,276 +0,0 @@
// 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();
}

View File

@@ -1,427 +0,0 @@
#!/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()