diff --git a/README.md b/README.md index a007bbf..5daa6bf 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,16 @@ Keys (defaults from `PlannerConfig`): uses at most the configured share of the rung budget. An unsuccessful upgrade retains the verified minimum path. A preferred gap at or below `footprint_min_gap_m` disables the upgrade. - `lattice_smooth_enabled: true`, `lattice_smooth_max_checks: 450000`. +- `regular_turn_radius_m: 1.06`: radius ladder. The first graph pass, the lattice and the smoother + use only radii at or above it, as before. When `min_turn_radius_m` is lower, the graph adds a second + pass with all `corner_radii_m` (largest first) if the first pass fails or returns a long detour, and + keeps it only when it is at least 20% shorter. +- `lattice_tight_arcs: false`, `lattice_tight_turn_cost_m: 0.15`: optional lattice arcs at + `min_turn_radius_m`; off because they cost many regress7 queries to timeouts. +- `debug/dump_dir: ""`, `debug/dump_max_files: 20`: when the directory is set, each failed query + writes its static cost, master cost, direction codes and poses as `lane_route_eval` input + (`.grid`, `.live`, `.scene`, `.txt`), at most that many per session. Off by default because + each dump writes a few MB. - `debug/fallback: true` enables one diagnostic line per request when lattice ran; failure logs remain enabled. See the runtime YAML for units, tuning effects and valid ranges. diff --git a/include/lane_route_planner/lane_route_session.h b/include/lane_route_planner/lane_route_session.h index f4ad4d6..e81782f 100644 --- a/include/lane_route_planner/lane_route_session.h +++ b/include/lane_route_planner/lane_route_session.h @@ -28,6 +28,10 @@ struct SessionConfig bool debug_fallback = true; ///< Enable per-request fallback diagnostics. bool debug_plan = true; ///< Enable plan diagnostics. bool debug_state = true; ///< Enable state-change diagnostics. + /// Directory for failed-query dumps that lane_route_eval can replay; empty disables them. Off by default, unlike the + /// log groups, because each dump writes a few MB to disk. + std::string debug_dump_dir; + int debug_dump_max_files = 20; ///< Dumps per session at most, so a repeating failure cannot fill the disk. /** @return Empty when valid; otherwise the invalid key and its value, or the core validation error. */ std::string validate() const; @@ -39,6 +43,19 @@ SessionConfig loadSessionConfig(const robot::NodeHandle& nh); /** @brief Log fallback diagnostics when enabled and always report a failed result. */ void logPlanResult(const lane_route_core::PlanResult& result, bool debug_fallback); +/** @brief Write a failed query in lane_route_eval's input format: .grid (static cost and direction codes), + * .live (master cost), .scene (one scene line) and .txt (reasons, effective settings, replay command). + * @param dir Output directory, created when missing. + * @param name File stem inside dir. + * @param live Master grid that the core planned on; its geometry is written. + * @param static_cost Static layer cost the graph was compiled from, width*height. + * @param directions Direction codes, width*height, or empty when the map has no zones. + * @return The stem path, or empty when a file could not be written. */ +std::string writeFailureDump(const std::string& dir, const std::string& name, const lane_route_core::GridRef& live, + const std::vector& static_cost, const std::vector& directions, + const lane_route_core::RouteRequest& route, const lane_route_core::PlannerConfig& config, + const lane_route_core::PlanResult& result); + /** @brief Inputs for one planner-thread query. Shared snapshots and live bytes must outlive plan(). */ struct SessionRequest { @@ -126,6 +143,12 @@ public: /** @brief Discard cached graphs and snapshot-derived data on the planner thread. */ void clearCache(); + /** @brief Stem of the dump written by the last plan(), "!" + directory when writing failed, or empty. */ + const std::string& lastDump() const + { + return last_dump_; + } + private: SessionConfig config_; std::vector live_cost_; @@ -145,6 +168,8 @@ private: double half_x_ = -1; ///< [m] Cached footprint half length. double half_y_ = -1; ///< [m] Cached footprint half width. double inscribed_ = -1; ///< [m] Cached inscribed radius. + int dumps_attempted_ = 0; ///< Failed-query dumps tried by this session, including failed writes. + std::string last_dump_; }; } // namespace lane_route_planner diff --git a/src/lane_route_planner.cpp b/src/lane_route_planner.cpp index beb0f0c..8095525 100644 --- a/src/lane_route_planner.cpp +++ b/src/lane_route_planner.cpp @@ -69,6 +69,9 @@ SessionConfig loadSessionConfig(const robot::NodeHandle& nh) load("live_ridge_max_cells", max_cells, max_cells); p.live_ridge_max_cells = max_cells; load("lattice_enabled", p.lattice_enabled, d.lattice_enabled); + load("regular_turn_radius_m", p.regular_turn_radius_m, d.regular_turn_radius_m); + load("lattice_tight_turn_cost_m", p.lattice_tight_turn_cost_m, d.lattice_tight_turn_cost_m); + load("lattice_tight_arcs", p.lattice_tight_arcs, d.lattice_tight_arcs); load("lattice_preferred_gap_m", p.lattice_preferred_gap_m, d.lattice_preferred_gap_m); load("lattice_preferred_time_fraction", p.lattice_preferred_time_fraction, d.lattice_preferred_time_fraction); load("lattice_smooth_enabled", p.lattice_smooth_enabled, d.lattice_smooth_enabled); @@ -101,6 +104,8 @@ SessionConfig loadSessionConfig(const robot::NodeHandle& nh) load("lattice_max_memory_mb", max_memory_mb, max_memory_mb); p.lattice_max_memory_mb = max_memory_mb; load("debug/fallback", config.debug_fallback, defaults.debug_fallback); + load("debug/dump_dir", config.debug_dump_dir, defaults.debug_dump_dir); + load("debug/dump_max_files", config.debug_dump_max_files, defaults.debug_dump_max_files); load("debug_plan", config.debug_plan, defaults.debug_plan); load("debug_state", config.debug_state, defaults.debug_state); return config; @@ -163,6 +168,11 @@ bool LaneRoutePlanner::initialize(std::string name, robot_costmap_2d::Costmap2DR p.lattice_enabled, p.fallback_time_limit_s, p.lattice_preferred_gap_m, p.lattice_preferred_time_fraction, p.lattice_smooth_enabled, static_cast(p.lattice_smooth_max_checks), p.lattice_heuristic_weight, p.lattice_heading_bins, static_cast(p.lattice_max_memory_mb), config_.debug_fallback); + robot::log_info("[lane_route_planner] radii: min_turn_radius_m=%.3f corner_radii_m=%zu values %.3f..%.3f regular_turn_radius_m=%.3f lattice_tight_arcs=%d lattice_tight_turn_cost_m=%.3f", + p.min_turn_radius_m, p.corner_radii_m.size(), p.corner_radii_m.front(), p.corner_radii_m.back(), + p.regular_turn_radius_m, p.lattice_tight_arcs, p.lattice_tight_turn_cost_m); + robot::log_info("[lane_route_planner] debug/dump_dir='%s' debug/dump_max_files=%d (empty dir: no failure dumps)", + config_.debug_dump_dir.c_str(), config_.debug_dump_max_files); if (costmap_->getLayeredCostmap()->getReferenceGraphSnapshot().state == robot_costmap_2d::ReferenceGraphState::kDisabled) robot::log_error("[lane_route_planner] reference graph is disabled; plans will fail until enabled"); return true; @@ -287,13 +297,19 @@ bool LaneRoutePlanner::makePlan(const robot_geometry_msgs::PoseStamped& start, c } auto result = session_.plan(request); if (config_.debug_plan) - robot::log_info("[lane_route_planner] [debug] ok=%d reason=%s rung=%.3f retries=%d gap_failures=%d soft_ignored=%d live=%s query=%.1fms compile=%.1fms search=%.1fms build=%.1fms verify=%.1fms live_ridge=%.1fms gap=%.3fm raise=%.3fm exempt=%d swing_windows=%d swing_checks=%ld swing_builds=%d swing_selected=%d", - result.ok, result.info.reason.c_str(), result.info.rung_used_deg, result.info.retries, + robot::log_info("[lane_route_planner] [debug] ok=%d reason=%s radius_pass=%s rung=%.3f retries=%d gap_failures=%d soft_ignored=%d live=%s query=%.1fms compile=%.1fms search=%.1fms build=%.1fms verify=%.1fms live_ridge=%.1fms gap=%.3fm raise=%.3fm exempt=%d swing_windows=%d swing_checks=%ld swing_builds=%d swing_selected=%d", + result.ok, result.info.reason.c_str(), + result.info.graph_radius_pass.empty() ? "none" : result.info.graph_radius_pass.c_str(), result.info.rung_used_deg, result.info.retries, result.info.gap_failures, result.info.soft_cost_ignored, result.info.live_ridge.c_str(), result.info.query_ms, result.info.compile_ms, result.info.search_ms, result.info.build_ms, result.info.verify_ms, result.info.live_ridge_ms, result.info.min_gap_m, result.info.gap_shortcut_raise_m, result.info.gap_exemption_used, result.info.swing_windows, result.info.swing_line_checks, result.info.swing_builds, result.info.swing_selected); logPlanResult(result, config_.debug_fallback); + const std::string& dump = session_.lastDump(); + if (!dump.empty() && dump[0] == '!') + robot::log_error("[lane_route_planner] could not write the failure dump into '%s'", dump.c_str() + 1); + else if (!dump.empty()) + robot::log_info("[lane_route_planner] failure dump written: %s.{grid,live,scene,txt}", dump.c_str()); if (!result.ok || result.path.empty() || !result.check.valid) return false; const auto final_graph = layered->getReferenceGraphSnapshot(); diff --git a/src/lane_route_session.cpp b/src/lane_route_session.cpp index b07efda..2f19bd8 100644 --- a/src/lane_route_session.cpp +++ b/src/lane_route_session.cpp @@ -4,8 +4,13 @@ #include #include #include +#include +#include +#include +#include #include #include +#include #include #include @@ -55,11 +60,91 @@ std::string SessionConfig::validate() const << " must be >= clearance_min_margin_m=" << clearance_min_margin_m; else if (!nonnegative(collision_check_margin_m)) error << "collision_check_margin_m must be finite and >= 0, got " << collision_check_margin_m; + else if (debug_dump_max_files < 0) + error << "debug/dump_max_files must be >= 0, got " << debug_dump_max_files; if (!error.str().empty()) return error.str(); return planner.validate(); } +namespace +{ +// Run-length text in the format lane_route_eval reads: " " then " " pairs. +void writeRuns(std::ostream& out, const char* key, const uint8_t* data, std::size_t count) +{ + std::vector> runs; + for (std::size_t i = 0; i < count;) + { + std::size_t j = i; + while (j < count && data[j] == data[i]) + ++j; + runs.emplace_back(data[i], j - i); + i = j; + } + out << key << ' ' << runs.size() << '\n'; + for (const auto& run : runs) + out << run.first << ' ' << run.second << ' '; + out << '\n'; +} + +void writePose(std::ostream& out, const lane_route_core::Pose2& pose) +{ + out << (pose.has_yaw ? 1 : 0) << ' ' << pose.x << ' ' << pose.y << ' ' << pose.yaw; +} +} // namespace + +std::string writeFailureDump(const std::string& dir, const std::string& name, const lane_route_core::GridRef& live, + const std::vector& static_cost, const std::vector& directions, + const lane_route_core::RouteRequest& route, const lane_route_core::PlannerConfig& config, + const lane_route_core::PlanResult& result) +{ + const std::size_t cells = static_cast(live.width) * static_cast(live.height); + if (!live.cost || static_cost.size() != cells || (!directions.empty() && directions.size() != cells)) + return {}; + std::error_code error; + std::filesystem::create_directories(dir, error); + if (error) + return {}; + const std::string stem = (std::filesystem::path(dir) / name).string(); + { + std::ofstream grid(stem + ".grid"); + grid << std::setprecision(10) << "reference_grid 1\nsize " << live.width << ' ' << live.height << "\nresolution " + << live.resolution << "\norigin " << live.origin_x << ' ' << live.origin_y << '\n'; + writeRuns(grid, "cost", static_cost.data(), cells); + grid << "variants 1\n"; + if (directions.empty()) + { + const std::vector none(cells, 0); + writeRuns(grid, "direction", none.data(), cells); + } + else + { + writeRuns(grid, "direction", directions.data(), cells); + } + std::ofstream master(stem + ".live"); + writeRuns(master, "cost", live.cost, cells); + std::ofstream scene(stem + ".scene"); + scene << std::setprecision(10) << name << ' ' << stem << ".grid 0 " << stem << ".live "; + writePose(scene, route.start); + scene << ' '; + writePose(scene, route.goal); + scene << " 0\n"; + std::ofstream meta(stem + ".txt"); + const auto& info = result.info; + meta << std::setprecision(10) << "reason " << info.reason << "\ngraph_reason " << info.graph_reason << "\nlattice_reason " + << info.lattice_reason << "\nquery_ms " << info.query_ms << "\nlattice_states_expanded " << info.lattice_states_expanded + << "\nmax_deviation_deg " << config.max_deviation_deg << "\nhalf_x_m " << config.half_x_m << "\nhalf_y_m " + << config.half_y_m << "\nclearance_min_m " << config.clearance_min_m << "\nfootprint_min_gap_m " + << config.footprint_min_gap_m << "\nmin_turn_radius_m " << config.min_turn_radius_m << "\nlattice_enabled " + << config.lattice_enabled << "\nfallback_time_limit_s " << config.fallback_time_limit_s << "\ntime_limit_s " + << config.time_limit_s << "\n# Replay: lane_route_eval " << stem << ".scene " << stem + << ".jsonl " << config.max_deviation_deg << " none fallback\n"; + if (!grid || !master || !scene || !meta) + return {}; + } + return stem; +} + bool footprintRectangle(const std::vector& footprint, double* half_x, double* half_y, bool* centered_rectangle) { @@ -165,6 +250,7 @@ void LaneRouteSession::clearCache() lane_route_core::PlanResult LaneRouteSession::plan(const SessionRequest& request) { using namespace lane_route_core; + last_dump_.clear(); PlanResult failed; failed.info.reason = validateRequest(request); if (!failed.info.reason.empty()) @@ -318,6 +404,20 @@ lane_route_core::PlanResult LaneRouteSession::plan(const SessionRequest& request result.info.reason = request.cancel && request.cancel->load(std::memory_order_relaxed) ? "cancelled" : "exact_goal_invalid"; } } + // A failed query is dumped only after the core ran on it, so the replay sees the same grid, zones and poses. + if (!result.ok && result.info.reason != "cancelled" && !config_.debug_dump_dir.empty() && + dumps_attempted_ < config_.debug_dump_max_files) + { + ++dumps_attempted_; + const std::time_t now = std::time(nullptr); + std::tm local{}; + localtime_r(&now, &local); + std::ostringstream name; + name << "lane_route_" << std::put_time(&local, "%Y%m%d_%H%M%S") << '_' << dumps_attempted_; + const std::string stem = writeFailureDump(config_.debug_dump_dir, name.str(), live, reference.static_cost, directions_, + route, config, result); + last_dump_ = stem.empty() ? "!" + config_.debug_dump_dir : stem; + } return result; } } // namespace lane_route_planner diff --git a/test/lane_route_planner_test.cpp b/test/lane_route_planner_test.cpp index 616b7a6..9c5c766 100644 --- a/test/lane_route_planner_test.cpp +++ b/test/lane_route_planner_test.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -740,4 +741,80 @@ TEST(AdapterParity, Inflation) { runParity(true); } +TEST(AdapterDump, FailureDumpIsReadableRunLengthText) +{ + // 4 x 3 grid: one lethal cell, one zone cell. The replay tool reads " " and then value/count pairs. + std::vector master{ 60, 60, 254, 60, 60, 60, 60, 60, 253, 60, 60, 60 }; + const std::vector static_cost{ 0, 0, 254, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + std::vector directions(12, 0); + directions[5] = 3; + GridRef live; + live.width = 4; + live.height = 3; + live.resolution = 0.05; + live.origin_x = -1.5; + live.origin_y = 2.25; + live.cost = master.data(); + RouteRequest route; + route.start = { 0.1, 0.2, 0.3, true }; + route.goal = { 0.4, 0.5, 0.0, false }; + PlannerConfig config; + config.max_deviation_deg = 22.5; + PlanResult result; + result.info.reason = "lattice_timeout"; + const std::string dir = (std::filesystem::temp_directory_path() / "lane_route_dump_test").string(); + const std::string stem = writeFailureDump(dir, "case", live, static_cost, directions, route, config, result); + ASSERT_EQ(stem, dir + "/case"); + + std::ifstream grid(stem + ".grid"); + std::string key; + int version = 0, width = 0, height = 0, runs = 0, variants = 0; + double resolution = 0.0, ox = 0.0, oy = 0.0; + grid >> key >> version >> key >> width >> height >> key >> resolution >> key >> ox >> oy >> key >> runs; + EXPECT_EQ(width, 4); + EXPECT_EQ(height, 3); + EXPECT_DOUBLE_EQ(resolution, 0.05); + EXPECT_DOUBLE_EQ(ox, -1.5); + EXPECT_DOUBLE_EQ(oy, 2.25); + EXPECT_EQ(key, "cost"); + EXPECT_EQ(runs, 3); // 0 x2, 254 x1, 0 x9 + int value = 0, count = 0, total = 0; + for (int i = 0; i < runs; ++i) + { + grid >> value >> count; + total += count; + } + EXPECT_EQ(total, 12); + grid >> key >> variants >> key >> runs; + EXPECT_EQ(variants, 1); + EXPECT_EQ(key, "direction"); + EXPECT_EQ(runs, 3); + + std::ifstream scene(stem + ".scene"); + std::string id, grid_file, live_file; + int variant = -1, has_start = -1, has_goal = -1, boxes = -1; + double sx, sy, syaw, gx, gy, gyaw; + scene >> id >> grid_file >> variant >> live_file >> has_start >> sx >> sy >> syaw >> has_goal >> gx >> gy >> gyaw >> boxes; + EXPECT_EQ(id, "case"); + EXPECT_EQ(grid_file, stem + ".grid"); + EXPECT_EQ(live_file, stem + ".live"); + EXPECT_EQ(has_start, 1); + EXPECT_DOUBLE_EQ(syaw, 0.3); + EXPECT_EQ(has_goal, 0); + EXPECT_EQ(boxes, 0); + + std::ifstream master_file(stem + ".live"); + master_file >> key >> runs; + EXPECT_EQ(key, "cost"); + EXPECT_EQ(runs, 5); // 60 x2, 254, 60 x5, 253, 60 x3 + std::ifstream meta(stem + ".txt"); + std::stringstream text; + text << meta.rdbuf(); + EXPECT_NE(text.str().find("reason lattice_timeout"), std::string::npos); + EXPECT_NE(text.str().find("max_deviation_deg 22.5"), std::string::npos); + + // A grid whose static layer does not match the master size is refused instead of writing a misleading replay. + EXPECT_TRUE(writeFailureDump(dir, "bad", live, std::vector(5, 0), directions, route, config, result).empty()); +} + } // namespace