diff --git a/CMakeLists.txt b/CMakeLists.txt index add932a..f39db49 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 # ======================================================== diff --git a/README.md b/README.md index ea9c9aa..f03c7dc 100644 --- a/README.md +++ b/README.md @@ -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_.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 diff --git a/cfg/sbpl_global_params.yaml b/cfg/sbpl_global_params.yaml index 012429d..6bacd0e 100644 --- a/cfg/sbpl_global_params.yaml +++ b/cfg/sbpl_global_params.yaml @@ -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=", - # "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 diff --git a/include/sbpl_lattice_planner/distance_map.h b/include/sbpl_lattice_planner/distance_map.h deleted file mode 100644 index 32e874e..0000000 --- a/include/sbpl_lattice_planner/distance_map.h +++ /dev/null @@ -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 -#include - -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& obstacle, int w, int h, - std::vector& 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_ diff --git a/include/sbpl_lattice_planner/path_smoother.h b/include/sbpl_lattice_planner/path_smoother.h deleted file mode 100644 index 4957d4e..0000000 --- a/include/sbpl_lattice_planner/path_smoother.h +++ /dev/null @@ -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 -#include -#include - -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; - using PoseQuery = std::function; ///< 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& in, std::vector& 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& out) const; - void appendSegment(const SmoothPose& a, const SmoothPose& b, std::vector& out) const; - - SmootherConfig cfg_; - CellQuery cell_; - PoseQuery pose_; -}; - -/// Sum of segment lengths [m]. -double pathLength(const std::vector& p); - -} // namespace sbpl_lattice_planner - -#endif // SBPL_LATTICE_PLANNER_PATH_SMOOTHER_H_ diff --git a/include/sbpl_lattice_planner/sbpl_lattice_planner.h b/include/sbpl_lattice_planner/sbpl_lattice_planner.h index be27e24..18a9d46 100644 --- a/include/sbpl_lattice_planner/sbpl_lattice_planner.h +++ b/include/sbpl_lattice_planner/sbpl_lattice_planner.h @@ -2,9 +2,7 @@ #define SBPL_LATTICE_PLANNER_H #include -#include #include -#include #include using namespace std; @@ -24,19 +22,10 @@ using namespace std; #include #include -// route graph corridor (2026-09-21): graph injected by the host through the shared sensor store -#include -#include -#include -#include - -#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 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 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& sbpl_path, SmootherStats* stats) const; }; }; diff --git a/package.xml b/package.xml index b1a1efb..4f75ed2 100644 --- a/package.xml +++ b/package.xml @@ -90,11 +90,4 @@ sbpl sbpl - - robot_sensor_ports - robot_sensor_ports - - route_graph - route_graph - \ No newline at end of file diff --git a/src/distance_map.cpp b/src/distance_map.cpp deleted file mode 100644 index 0863df1..0000000 --- a/src/distance_map.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/********************************************************************* - * - * Software License Agreement (BSD License) - * - * Author: DuongTD - *********************************************************************/ -#include "sbpl_lattice_planner/distance_map.h" - -#include -#include - -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::infinity(); - z[1] = std::numeric_limits::infinity(); - for (int q = 1; q < n; ++q) { - float s = ((f[q] + static_cast(q) * q) - (f[v[k]] + static_cast(v[k]) * v[k])) / - (2.0f * q - 2.0f * v[k]); - while (s <= z[k]) { - --k; - s = ((f[q] + static_cast(q) * q) - (f[v[k]] + static_cast(v[k]) * v[k])) / - (2.0f * q - 2.0f * v[k]); - } - ++k; - v[k] = q; - z[k] = s; - z[k + 1] = std::numeric_limits::infinity(); - } - k = 0; - for (int q = 0; q < n; ++q) { - while (z[k + 1] < static_cast(q)) ++k; - const float dq = static_cast(q - v[k]); - d[q] = dq * dq + f[v[k]]; - } -} - -} // namespace - -void squaredDistanceTransform(const std::vector& obstacle, int w, int h, - std::vector& dist2) -{ - dist2.assign(static_cast(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 f(n), d(n), z(n + 1); - std::vector 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(y) * w + x]; - transform1d(f.data(), h, d.data(), v.data(), z.data()); - for (int y = 0; y < h; ++y) dist2[static_cast(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(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 diff --git a/src/path_smoother.cpp b/src/path_smoother.cpp deleted file mode 100644 index aebed82..0000000 --- a/src/path_smoother.cpp +++ /dev/null @@ -1,315 +0,0 @@ -/********************************************************************* - * - * Software License Agreement (BSD License) - * - * Author: DuongTD - *********************************************************************/ -#include "sbpl_lattice_planner/path_smoother.h" - -#include -#include -#include - -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& 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(std::ceil(len / cfg_.check_step_m))); - bool near = false; - for (int s = 0; s <= n; ++s) { - const double f = static_cast(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(std::ceil(len / cfg_.sample_step_m))); - for (int s = 0; s <= m; ++s) { - const double f = static_cast(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(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(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(std::ceil(std::fabs(sweep) * r / cfg_.sample_step_m))); - for (int s = 0; s <= m; ++s) { - const double a = a0 + sweep * static_cast(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& out) const -{ - const double side = sweep >= 0.0 ? 1.0 : -1.0; - const int n = std::max(1, static_cast(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(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& 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(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(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& in, std::vector& 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 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 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(pts.size() - 1) : 1.0; - const std::size_t stride = std::max(1, static_cast(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 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 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(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 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 diff --git a/src/sbpl_lattice_planner.cpp b/src/sbpl_lattice_planner.cpp index 1d364c5..7e48206 100644 --- a/src/sbpl_lattice_planner.cpp +++ b/src/sbpl_lattice_planner.cpp @@ -36,7 +36,6 @@ *********************************************************************/ #include -#include #include #include @@ -45,17 +44,9 @@ #include #include -#include -#include - #include -#include #include -#include -#include -#include // SensorType specialisation for latest<>() -#include #include #include @@ -109,206 +100,10 @@ void SBPLLatticePlanner::setExternalGrid(const robot_costmap_2d::Costmap2D* 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{ 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 - // đượ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(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 msg = - robot_sensor_ports::latest(*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 lock(*costmap_robot_->getCostmap()->getMutex()); - const std::vector 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(msg->map_hash), - static_cast(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(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(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(x), static_cast(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(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(grid->getSizeInCellsX()), - static_cast(grid->getSizeInCellsY()), cp, &n); - stats.mask_cells = n; - stats.active = !corridor_mask_.empty(); - stats.build_ms = std::chrono::duration(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(grid->getSizeInCellsX()) * grid->getSizeInCellsY()), - stats.build_ms); - return stats.active; -} - 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 // inscribed của một ô lethal, 255 = chưa biết. FREE_SPACE ở đây là 60 chứ không phải 0 @@ -393,24 +188,6 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2 private_nh.param("planner_type", planner_type_, string("ARAPlanner")); private_nh.param("allocated_time", allocated_time_, 10.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("forward_search", forward_search_, bool(false)); private_nh.param("primitive_filename",primitive_filename_,string("")); @@ -488,126 +265,14 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2 debug_grid_window_, kMaxGridWindow); debug_grid_window_ = kMaxGridWindow; } - robot::log_info("[sbpl_lattice_planner] '%s' config: allocated_time=%.1fs eps %.2f -> %.2f step %.2f " - "repair_time=%.1fs first_solution=%s allow_unknown=%s free_start_heading=%s " - "forward_search=%s | debug_plan=%s debug_grid_window=%d", - name.c_str(), allocated_time_, initial_epsilon_, final_epsilon_, eps_step_, - repair_time_, return_first_solution_ ? "true" : "false", + robot::log_info("[sbpl_lattice_planner] '%s' config: allocated_time=%.1fs initial_epsilon=%.2f " + "allow_unknown=%s free_start_heading=%s forward_search=%s | debug_plan=%s " + "debug_grid_window=%d", + name.c_str(), allocated_time_, initial_epsilon_, allow_unknown_ ? "true" : "false", free_start_heading_ ? "true" : "false", forward_search_ ? "true" : "false", debug_plan_ ? "on" : "off", 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; costmap_robot_ = costmap_robot; @@ -647,15 +312,6 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2 robot::log_warning("SBPL performance will suffer."); 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(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))){ robot::log_error("Failed to set cost_inscribed_thresh parameter"); exit(1); @@ -759,12 +415,6 @@ bool SBPLLatticePlanner::initialize(std::string name, robot_costmap_2d::Costmap2 "cancel/pause cannot interrupt a running search (runs to allocated_time)"); #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"); // plan_pub_ = private_nh.advertise("plan", 1); // stats_publisher_ = private_nh.advertise("sbpl_lattice_planner_stats", 1); @@ -837,13 +487,6 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, current_env_width_, current_env_height_, grid->getSizeInCellsX(), grid->getSizeInCellsY()); 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()) { robot::log_info("Robot footprint has changed, reinitializing sbpl_lattice_planner."); @@ -940,121 +583,55 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, 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_); + int offOnCount = 0; + int onOffCount = 0; + int allCount = 0; + vector changedcellsV; + + for(unsigned int ix = 0; ix < grid->getSizeInCellsX(); ix++) { + for(unsigned int iy = 0; iy < grid->getSizeInCellsY(); iy++) { + + unsigned char oldCost = env_->GetMapCost(ix,iy); + unsigned char newCost = costMapCostToSBPLCost(grid->getCost(ix,iy)); + + if(oldCost == newCost) continue; + + allCount++; + + //first case - off cell goes on + + if((oldCost != costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) && oldCost != costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)) && + (newCost == costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) || newCost == costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE))) { + offOnCount++; + } + + if((oldCost == costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) || oldCost == costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE)) && + (newCost != costMapCostToSBPLCost(robot_costmap_2d::LETHAL_OBSTACLE) && newCost != costMapCostToSBPLCost(robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE))) { + onOffCount++; + } + env_->UpdateCost(ix, iy, costMapCostToSBPLCost(grid->getCost(ix,iy))); + + nav2dcell_t nav2dcell; + nav2dcell.x = ix; + nav2dcell.y = iy; + changedcellsV.push_back(nav2dcell); } } - 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; - } + try{ + if(!changedcellsV.empty()){ + StateChangeQuery* scq = new LatticeSCQ(env_, changedcellsV); + planner_->costs_changed(*scq); + delete scq; } - 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); + + if(allCount > force_scratch_limit_) + planner_->force_planning_from_scratch(); + } + catch(SBPL_Exception *e){ + robot::log_error("SBPL failed to update the costmap"); 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 onOffCount = 0; - int allCount = 0; - vector 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 iy = 0; iy < grid->getSizeInCellsY(); iy++) { - - unsigned char oldCost = env_->GetMapCost(ix,iy); - unsigned char newCost = costMapCostToSBPLCost(grid->getCost(ix,iy)); - if (masking && !corridor_mask_[static_cast(iy) * grid_w + ix] && newCost < masked_cost) - newCost = masked_cost; - - if(oldCost == newCost) continue; - - allCount++; - - //first case - off cell goes on - - if((oldCost != sbpl_lethal && oldCost != sbpl_inscribed) && - (newCost == sbpl_lethal || newCost == sbpl_inscribed)) { - offOnCount++; - } - - if((oldCost == sbpl_lethal || oldCost == sbpl_inscribed) && - (newCost != sbpl_lethal && newCost != sbpl_inscribed)) { - onOffCount++; - } - env_->UpdateCost(ix, iy, newCost); - - nav2dcell_t nav2dcell; - nav2dcell.x = ix; - nav2dcell.y = iy; - changedcellsV.push_back(nav2dcell); - } - } - - try{ - if(!changedcellsV.empty()){ - StateChangeQuery* scq = new LatticeSCQ(env_, changedcellsV); - planner_->costs_changed(*scq); - delete scq; - } - - if(allCount > force_scratch_limit_) - planner_->force_planning_from_scratch(); - } - catch(SBPL_Exception *e){ - robot::log_error("SBPL failed to update the costmap"); - 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 @@ -1081,8 +658,7 @@ 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à // 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 - // 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.) + // sau khi quét hết vùng nối với robot. const bool goal_cell_blocked = goal_audit.cost >= robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE && !(allow_unknown_ && goal_audit.cost == robot_costmap_2d::NO_INFORMATION); @@ -1113,12 +689,11 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, else if (debug_plan_) { 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) | " - "allow_unknown=%s | corridor=%s", + "allow_unknown=%s", 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), grid->getSizeInCellsX(), grid->getSizeInCellsY(), grid->getResolution(), - grid->getOriginX(), grid->getOriginY(), allow_unknown_ ? "true" : "false", - corridor_active ? "on" : "off"); + grid->getOriginX(), grid->getOriginY(), allow_unknown_ ? "true" : "false"); } // (3) Nối 2D. Heuristic của SBPL là Dijkstra 2D từ goal trên ô < cost_inscribed_thresh — đúng tập @@ -1126,27 +701,18 @@ 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ỉ // 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. - // 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; - while (true) { - try{ - env_->EnsureHeuristicsUpdated(forward_search_); - h_2d = forward_search_ ? env_->GetGoalHeuristic(start_state_id) - : env_->GetStartHeuristic(goal_state_id); - } - catch(SBPL_Exception *e){ - robot::log_error("SBPL encountered a fatal exception while computing the 2D heuristic"); - return false; - } - const bool h_2d_infinite = (h_2d < 0 || h_2d >= INFINITECOST); - if (!h_2d_infinite) break; - if (corridor_active && corridor_hard_) { - widenOrDropCorridor("2D reachability h=INF inside the corridor"); - if (!applyGridCosts()) return false; - continue; - } + try{ + env_->EnsureHeuristicsUpdated(forward_search_); + h_2d = forward_search_ ? env_->GetGoalHeuristic(start_state_id) + : env_->GetStartHeuristic(goal_state_id); + } + catch(SBPL_Exception *e){ + robot::log_error("SBPL encountered a fatal exception while computing the 2D heuristic"); + return false; + } + const bool h_2d_infinite = (h_2d < 0 || h_2d >= INFINITECOST); + if (h_2d_infinite) { 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 " "robot by lethal/inscribed cells%s. REJECTED without running the lattice search.\n", @@ -1158,11 +724,13 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, 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. robot::log_info("[sbpl_lattice_planner] 2D reachability start->goal: h=%d (finite) — point path " - "exists, running lattice search%s", h_2d, corridor_active ? " inside the corridor" : ""); + "exists, running lattice search", h_2d); } - //setting planner parameters (eps/mode đi theo từng lượt qua makeReplanParams) + //setting planner parameters 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"); const robot::Time plan_started = robot::Time::now(); @@ -1171,7 +739,6 @@ 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 // 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. - // 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ì const auto budget_left = [&]() { return allocated_time_ - (robot::Time::now() - plan_started).toSec(); @@ -1183,75 +750,34 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, const char* phase_name = start_heading_overridden ? "free_heading" : "actual_heading"; double phase_budget = allocated_time_; 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{ - // 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); + int ret = planner_->replan(allocated_time_, &solution_stateIDs, &solution_cost); + if(preempt_.load(std::memory_order_relaxed)){ + robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (first search)", + (robot::Time::now() - plan_started).toSec() * 1000.0); + return false; + } + if(!ret && start_heading_overridden && budget_left() >= kMinReplanBudget){ + // Heading giả định có thể không khả thi (vd hướng tới goal đâm thẳng vào tường + // ngay tại cell xuất phát) — thử lại MỘT lần với heading thật trước khi bỏ cuộc. + robot::log_warning("[sbpl_lattice_planner] no solution with free start heading after %d " + "expansions in %.0f ms, retrying with actual robot heading (%.2f s left)", + planner_->get_n_expands(), + (robot::Time::now() - plan_started).toSec() * 1000.0, budget_left()); + int sid = env_->SetStart(start.pose.position.x - grid->getOriginX(), + start.pose.position.y - grid->getOriginY(), + theta_start_actual); + if(sid >= 0 && planner_->set_start(sid) != 0){ + phase_name = "actual_heading_retry"; + phase_budget = budget_left(); + phase_started = robot::Time::now(); + ret = planner_->replan(phase_budget, &solution_stateIDs, &solution_cost); + } 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 (heading retry)", (robot::Time::now() - plan_started).toSec() * 1000.0); return false; } - if(!ret && start_heading_overridden && budget_left() >= kMinReplanBudget){ - // Heading giả định có thể không khả thi (vd hướng tới goal đâm thẳng vào tường - // ngay tại cell xuất phát) — thử lại MỘT lần với heading thật trước khi bỏ cuộc. - robot::log_warning("[sbpl_lattice_planner] no solution with free start heading after %d " - "expansions in %.0f ms, retrying with actual robot heading (%.2f s left)", - planner_->get_n_expands(), - (robot::Time::now() - plan_started).toSec() * 1000.0, budget_left()); - int sid = env_->SetStart(start.pose.position.x - grid->getOriginX(), - start.pose.position.y - grid->getOriginY(), - theta_start_actual); - if(sid >= 0 && planner_->set_start(sid) != 0){ - phase_name = "actual_heading_retry"; - phase_budget = (corridor_active && corridor_hard_) ? std::min(budget_left(), budget) : budget_left(); - phase_started = robot::Time::now(); - ret = planner_->replan(&solution_stateIDs, makeReplanParams(phase_budget), &solution_cost); - } - if(preempt_.load(std::memory_order_relaxed)){ - robot::log_info("[sbpl_lattice_planner] preempted after %.0f ms (heading retry)", - (robot::Time::now() - plan_started).toSec() * 1000.0); - 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) { @@ -1264,26 +790,12 @@ 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 // ARA* đã mở: so giữa hai lượt cùng goal để thấy map/cost đổi hay không. 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), " - "%.0f ms of %.2f s allowed, expands=%d (first solution: %.0f cpu-ms, %d expands), " - "h_2d=%d, phase=%s", + "%.0f ms of %.2f s allowed, expands=%d, h_2d=%d, phase=%s", planner_->get_final_epsilon(), initial_epsilon_, solution_cost, solution_stateIDs.size(), (robot::Time::now() - plan_started).toSec() * 1000.0, allocated_time_, - 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); + planner_->get_n_expands(), h_2d, phase_name); } } else{ @@ -1296,12 +808,15 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, // (preempt đã return sớm ở trên, không tới đây.) const double phase_elapsed = (robot::Time::now() - phase_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; 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 " "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, - goal.pose.position.y, goal_dist_m, + goal.pose.position.y, + 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_elapsed * 1000.0, phase_budget * 1000.0, total_elapsed * 1000.0, allocated_time_ * 1000.0, planner_->get_final_epsilon(), h_2d, @@ -1391,7 +906,7 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, vector realigned_ids; int realigned_cost; if(sid >= 0 && planner_->set_start(sid) != 0 && - planner_->replan(&realigned_ids, makeReplanParams(budget_left()), &realigned_cost)){ + planner_->replan(budget_left(), &realigned_ids, &realigned_cost)){ vector realigned_path; env_->ConvertStateIDPathintoXYThetaPath(&realigned_ids, &realigned_path); if(!realigned_path.empty()){ @@ -1421,80 +936,9 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, // 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(std::chrono::steady_clock::now() - t0).count(); - } - robot::log_debug("Plan has %d points.\n", (int)sbpl_path.size()); 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_) // { // robot_visualization_msgs::Marker sbpl_plan_footprint; @@ -1534,195 +978,6 @@ bool SBPLLatticePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, return true; } -bool SBPLLatticePlanner::smoothLatticePath(const robot_costmap_2d::Costmap2D* grid, - std::vector& 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(grid->getSizeInCellsX()); - const int H = static_cast(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(std::ceil(safe_m / res)); - const float safe_cells2 = static_cast((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((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(std::floor((xmin - crop_margin - ox) / res))); - const int cy0 = std::max(0, static_cast(std::floor((ymin - crop_margin - oy) / res))); - const int cx1 = std::min(W - 1, static_cast(std::ceil((xmax + crop_margin - ox) / res))); - const int cy1 = std::min(H - 1, static_cast(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 obstacle(static_cast(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(cx0 + x), static_cast(cy0 + y)); - if (c == robot_costmap_2d::LETHAL_OBSTACLE || (c == robot_costmap_2d::NO_INFORMATION && !allow_unknown)) - obstacle[static_cast(y) * cw + x] = 1; - } - } - std::vector 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(c) > max_cost) { - return CellClass::kBlocked; - } - const int lx = static_cast(mx) - cx0; - const int ly = static_cast(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(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> 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> 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>> masks(kBins); - std::vector mask_ready(kBins, false); - const auto mask_for = [&](int bin) -> const std::vector>& { - 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> 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>& m = masks[bin]; - for (int dy = static_cast(std::floor(by0 / res)); dy <= static_cast(std::ceil(by1 / res)); ++dy) { - for (int dx = static_cast(std::floor(bx0 / res)); dx <= static_cast(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(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(mx) + off.first; - const int qy = static_cast(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(qx), static_cast(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 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 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& sbpl_path, const std::string& path_frame_id, robot_visualization_msgs::Marker& ma) { diff --git a/test/path_smoother_test.cpp b/test/path_smoother_test.cpp deleted file mode 100644 index db3f382..0000000 --- a/test/path_smoother_test.cpp +++ /dev/null @@ -1,276 +0,0 @@ -// Unit tests for PathSmoother on synthetic worlds (no costmap, no SBPL). -#include -#include - -#include - -#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 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& 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 dense(const std::vector>& v, double step = 0.05) -{ - std::vector 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(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& 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& 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> 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 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 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 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 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 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 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 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 obs(w * h, 0); - obs[1 * w + 1] = 1; - obs[3 * w + 5] = 1; - std::vector d2; - sbpl_lattice_planner::squaredDistanceTransform(obs, w, h, d2); - ASSERT_EQ(d2.size(), static_cast(w * h)); - for (int y = 0; y < h; ++y) - for (int x = 0; x < w; ++x) { - const float a = static_cast((x - 1) * (x - 1) + (y - 1) * (y - 1)); - const float b = static_cast((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(); -} diff --git a/tools/__pycache__/eval_plan_bag.cpython-38.pyc b/tools/__pycache__/eval_plan_bag.cpython-38.pyc deleted file mode 100644 index 9d22005..0000000 Binary files a/tools/__pycache__/eval_plan_bag.cpython-38.pyc and /dev/null differ diff --git a/tools/eval_plan_bag.py b/tools/eval_plan_bag.py deleted file mode 100755 index 53a2e26..0000000 --- a/tools/eval_plan_bag.py +++ /dev/null @@ -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 _