From 6367f13d7d351865dede67ef72f1c322ee7beb6d Mon Sep 17 00:00:00 2001 From: duongtd Date: Mon, 16 Nov 2026 14:01:11 +0700 Subject: [PATCH] feat(lane_route_core): try the lattice when a verified graph route is a suspicious detour When the graph tier returns a verified path longer than suspicious_ratio * chord + suspicious_margin_m, and the lattice tier is enabled, run one lattice attempt within its own time budget and the request deadline. The lattice path replaces the graph path only if it is verified, not cancelled, and its cost (length plus zone_deviation_weight * deviation / 45) is at least detour_upgrade_min_saving lower, without adding more than detour_upgrade_max_extra_zone_deviation_m of zone-deviated length. - PlannerConfig: detour_upgrade_enabled (true), detour_upgrade_time_limit_s [s] (2.0), detour_upgrade_min_saving (0.15, in [0, 1)), detour_upgrade_max_extra_zone_deviation_m [m] (0.5); validated in PlannerConfig::validate(). - PlanInfo: detour_upgrade_outcome (off, not_triggered, taken, kept_graph, kept_graph_zone_deviation, lattice_failed, cancelled), graph/lattice length, cost, zone deviation, time and lattice reason. - lane_route_eval: overrides for the new keys, outcome fields in the JSON. - Tests: lane_route_core_test 135/135. --- include/lane_route_core/route_planner.h | 9 ++ include/lane_route_core/types.h | 4 + src/grid_checks.cpp | 5 + src/route_planner.cpp | 60 +++++++++ test/lane_route_core_test.cpp | 163 ++++++++++++++++++++++++ tools/lane_route_eval.cpp | 15 ++- 6 files changed, 255 insertions(+), 1 deletion(-) diff --git a/include/lane_route_core/route_planner.h b/include/lane_route_core/route_planner.h index 9f43823..900cd1d 100644 --- a/include/lane_route_core/route_planner.h +++ b/include/lane_route_core/route_planner.h @@ -90,6 +90,15 @@ struct PlanInfo int swing_builds = 0; ///< Extra path builds for those searches. int swing_selected = 0; ///< Paths taken from those searches. std::string tier_used; ///< "graph", "lattice" or empty on failure. + std::string detour_upgrade_outcome = "off"; ///< off, not_triggered, taken, kept_graph, kept_graph_zone_deviation, lattice_failed or cancelled. + double detour_upgrade_graph_length_m = 0.0; ///< [m] Graph polyline length when evaluated. + double detour_upgrade_lattice_length_m = 0.0; ///< [m] Verified candidate polyline length, 0 if unavailable. + double detour_upgrade_graph_cost = 0.0; ///< [m] Length plus weighted zone deviation. + double detour_upgrade_lattice_cost = 0.0; ///< [m] Verified candidate cost; 0 if unavailable. + double detour_upgrade_graph_zone_deviation_m = 0.0; ///< [m] Graph length deviating more than 3 degrees in zones. + double detour_upgrade_lattice_zone_deviation_m = 0.0; ///< [m] Candidate deviated length; 0 if unavailable. + double detour_upgrade_time_ms = 0.0; ///< [ms] Time spent in the detour attempt. + std::string detour_upgrade_lattice_reason; ///< Lattice attempt reason, separate from the graph diagnostics. std::string graph_reason; ///< Most recent graph tier reason. std::string lattice_reason; ///< Most recent lattice tier reason. std::vector graph_rung_reasons; ///< Graph reasons, in attempted-rung order. diff --git a/include/lane_route_core/types.h b/include/lane_route_core/types.h index 961601c..6203fb1 100644 --- a/include/lane_route_core/types.h +++ b/include/lane_route_core/types.h @@ -134,6 +134,10 @@ struct PlannerConfig double live_ridge_pad_m = 6.0; ///< Margin of the live retry window around start and goal. int64_t live_ridge_max_cells = 1500000; ///< Larger windows skip the live retry. + bool detour_upgrade_enabled = true; ///< Try the lattice for a suspicious verified graph detour. + double detour_upgrade_time_limit_s = 2.0; ///< [s] Maximum additional lattice time, bounded by the request deadline. + double detour_upgrade_min_saving = 0.15; ///< Minimum fractional improvement in length plus zone deviation cost, in [0, 1). + double detour_upgrade_max_extra_zone_deviation_m = 0.5; ///< [m] Largest allowed increase in deviated path length. bool lattice_enabled = false; ///< Enable fallback after the graph tier. double lattice_preferred_gap_m = 0.15; ///< [m] Preferred footprint gap away from endpoints; values <= footprint_min_gap_m (e.g. 0) disable the preferred pass. double lattice_preferred_time_fraction = 0.25; ///< Maximum fraction of the rung slice for the optional preferred search, after recheck. diff --git a/src/grid_checks.cpp b/src/grid_checks.cpp index 9efb327..6bedde9 100644 --- a/src/grid_checks.cpp +++ b/src/grid_checks.cpp @@ -106,6 +106,11 @@ std::string PlannerConfig::validate() const else if (!positive(route_too_long_ratio) || !not_negative(route_too_long_margin_m) || !positive(suspicious_ratio) || !not_negative(suspicious_margin_m)) error << "route length limits must be finite, ratios > 0, margins >= 0"; + else if (!positive(detour_upgrade_time_limit_s) || detour_upgrade_time_limit_s > 86400.0 || + !not_negative(detour_upgrade_min_saving) || detour_upgrade_min_saving >= 1.0) + error << "detour upgrade time must be in (0, 86400] and minimum saving in [0, 1)"; + else if (!not_negative(detour_upgrade_max_extra_zone_deviation_m)) + error << "detour_upgrade_max_extra_zone_deviation_m must be finite and >= 0"; else if (max_route_attempts < 1) error << "max_route_attempts must be >= 1"; else if (!positive(time_limit_s) || !positive(output_step_m)) diff --git a/src/route_planner.cpp b/src/route_planner.cpp index 6c6c29c..1a655d1 100644 --- a/src/route_planner.cpp +++ b/src/route_planner.cpp @@ -40,6 +40,17 @@ double polylineLength(const Path& path) length += std::hypot(path[i].x - path[i - 1].x, path[i].y - path[i - 1].y); return length; } +ZoneDeviation pathZoneDeviation(const Path& path, const GridRef& grid) +{ + ZoneDeviation total; + for (std::size_t i = 1; i < path.size(); ++i) + { + const auto part = lineZoneDeviation({path[i-1].x, path[i-1].y}, {path[i].x, path[i].y}, grid); + total.integral_deg_m += part.integral_deg_m; + total.deviated_length_m += part.deviated_length_m; + } + return total; +} } // namespace PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, const GridRef& live, const PlannerConfig& config, @@ -53,6 +64,7 @@ PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, c { PlanResult result; const TimePoint began = Clock::now(); + result.info.detour_upgrade_outcome = config.detour_upgrade_enabled ? "not_triggered" : "off"; const auto finish = [&]() { result.info.query_ms = msSince(began); if (request.cancel && request.cancel->load(std::memory_order_relaxed)) @@ -211,6 +223,54 @@ PlanResult planRoute(const GraphProvider& graphs, const RouteRequest& request, c result.info.tier_used = "graph"; result.info.rung_used_deg = deviation; result.info.rung_reasons.push_back(result.info.reason); + if (config.detour_upgrade_enabled && config.lattice_enabled && !request.lattice_only) + { + const double graph_length = polylineLength(result.path); + result.info.detour_upgrade_graph_length_m = graph_length; + if (graph_length > config.suspicious_ratio * chord + config.suspicious_margin_m) + { + const TimePoint upgrade_began = Clock::now(); + const TimePoint upgrade_deadline = std::min(deadline, upgrade_began + std::chrono::duration_cast( + std::chrono::duration(config.detour_upgrade_time_limit_s))); + Path candidate; + PathCheck candidate_check; + PlanInfo candidate_info = result.info; + const bool candidate_ok = upgrade_began < upgrade_deadline && + detail::planLatticeTier({ request, live, lattice_config, deviation, upgrade_deadline, upgrade_deadline }, + { candidate, candidate_check, candidate_info }); + const double candidate_length = candidate_ok ? polylineLength(candidate) : 0.0; + const std::string lattice_reason = candidate_info.lattice_reason; + // Match the graph's zone term on the live direction field, not the lattice's forced zero weight. + const ZoneDeviation graph_zone = has_zones ? pathZoneDeviation(result.path, live) : ZoneDeviation{}; + const ZoneDeviation candidate_zone = candidate_ok && has_zones ? pathZoneDeviation(candidate, live) : ZoneDeviation{}; + const double graph_cost = graph_length + config.zone_deviation_weight * graph_zone.integral_deg_m / 45.0; + const double candidate_cost = candidate_length + config.zone_deviation_weight * candidate_zone.integral_deg_m / 45.0; + const bool excess_deviation = candidate_zone.deviated_length_m > + graph_zone.deviated_length_m + config.detour_upgrade_max_extra_zone_deviation_m; + const bool length_saves = candidate_length < (1.0 - config.detour_upgrade_min_saving) * graph_length; + const bool cost_saves = candidate_cost < (1.0 - config.detour_upgrade_min_saving) * graph_cost; + const bool zone_rejected = excess_deviation || (length_saves && !cost_saves); + const bool cancelled = request.cancel && request.cancel->load(std::memory_order_relaxed); + const bool taken = !cancelled && candidate_ok && candidate_check.valid && !excess_deviation && cost_saves; + if (taken) + { + result.path = std::move(candidate); + result.check = candidate_check; + result.info = std::move(candidate_info); + result.info.tier_used = "lattice"; + } + result.info.detour_upgrade_outcome = cancelled ? "cancelled" : taken ? "taken" : !candidate_ok ? "lattice_failed" : + zone_rejected ? "kept_graph_zone_deviation" : "kept_graph"; + result.info.detour_upgrade_graph_length_m = graph_length; + result.info.detour_upgrade_lattice_length_m = candidate_length; + result.info.detour_upgrade_graph_cost = graph_cost; + result.info.detour_upgrade_lattice_cost = candidate_cost; + result.info.detour_upgrade_graph_zone_deviation_m = graph_zone.deviated_length_m; + result.info.detour_upgrade_lattice_zone_deviation_m = candidate_zone.deviated_length_m; + result.info.detour_upgrade_time_ms = msSince(upgrade_began); + result.info.detour_upgrade_lattice_reason = lattice_reason; + } + } return finish(); } // Preserve R0 early exits exactly while the new tier is disabled. diff --git a/test/lane_route_core_test.cpp b/test/lane_route_core_test.cpp index 26d3f5c..7c1b338 100644 --- a/test/lane_route_core_test.cpp +++ b/test/lane_route_core_test.cpp @@ -1099,6 +1099,169 @@ void expectLatticeMotion(const PlanResult& result, const PlannerConfig& config) } // namespace +namespace +{ +class DetourUpgradeTest : public ::testing::Test +{ +protected: + LatticeTestGrid map{300, 240}; + PlannerConfig config = latticeConfig(); + RouteRequest request{pose(1.5, 5.0, 0.0), pose(13.5, 5.0, 0.0), {}}; + CoarseGraph coarse; + void SetUp() override + { + for (int y = 50; y < 170; ++y) + for (int x = 70; x < 230; ++x) + map.direction[static_cast(y * map.width + x)] = 3; + coarse.nodes = {{2.0, 8.8}, {13.0, 8.8}}; + coarse.edges.push_back({0, 1, {coarse.nodes[0], coarse.nodes[1]}}); + config.deviation_ladder_deg.clear(); + config.max_deviation_deg = 90.0; + config.zone_deviation_weight = 20.0; + config.suspicious_ratio = 1.0; + config.suspicious_margin_m = 0.0; + } + void usePreferredDetour() + { + std::fill(map.direction.begin(), map.direction.end(), 0); + std::fill(map.cost.begin(), map.cost.end(), kUnpreferredSpace); + // A low-cost U-shaped corridor biases the graph, while the lattice ignores soft cost values. + for (int y = 75; y <= 185; ++y) + for (int x = 20; x < 280; ++x) + if (y >= 165 || x < 50 || x >= 250) + map.cost[static_cast(y * map.width + x)] = kPreferredSpace; + coarse.nodes = {{1.5, 8.6}, {13.5, 8.6}}; + coarse.edges = {{0, 1, {coarse.nodes[0], coarse.nodes[1]}}}; + config.zone_deviation_weight = 0.0; + } + PlanResult run() + { + const auto grid = map.view(); + const GraphProvider provider = [&](double deviation) { + return std::make_shared(compileGraph(coarse, grid, grid.cost, deviation, config, RidgeBackend{})); + }; + return planRoute(provider, request, grid, config, RidgeBackend{}); + } +}; + +void expectSamePath(const Path& a, const Path& b) +{ + ASSERT_EQ(a.size(), b.size()); + for (std::size_t i = 0; i < a.size(); ++i) + { + EXPECT_DOUBLE_EQ(a[i].x, b[i].x); + EXPECT_DOUBLE_EQ(a[i].y, b[i].y); + EXPECT_DOUBLE_EQ(a[i].yaw, b[i].yaw); + EXPECT_DOUBLE_EQ(a[i].curvature, b[i].curvature); + } +} +} // namespace + +TEST(DetourUpgradeConfig, ValidatesBounds) +{ + PlannerConfig config; + EXPECT_TRUE(config.validate().empty()); + config.detour_upgrade_time_limit_s = 0.0; + EXPECT_FALSE(config.validate().empty()); + config.detour_upgrade_time_limit_s = 2.0; + config.detour_upgrade_min_saving = 1.0; + EXPECT_FALSE(config.validate().empty()); + config.detour_upgrade_min_saving = std::numeric_limits::quiet_NaN(); + EXPECT_FALSE(config.validate().empty()); + config.detour_upgrade_min_saving = 0.15; + config.detour_upgrade_max_extra_zone_deviation_m = -0.1; + EXPECT_FALSE(config.validate().empty()); + config.detour_upgrade_max_extra_zone_deviation_m = std::numeric_limits::infinity(); + EXPECT_FALSE(config.validate().empty()); +} + +TEST_F(DetourUpgradeTest, TakesVerifiedShorterLattice) +{ + usePreferredDetour(); + const auto result = run(); + ASSERT_TRUE(result.ok) << result.info.reason; + EXPECT_TRUE(result.check.valid); + EXPECT_EQ(result.info.detour_upgrade_outcome, "taken"); + EXPECT_EQ(result.info.tier_used, "lattice"); + EXPECT_LT(result.info.detour_upgrade_lattice_length_m, 0.85 * result.info.detour_upgrade_graph_length_m); +} + +TEST_F(DetourUpgradeTest, InsufficientSavingKeepsGraph) +{ + usePreferredDetour(); + config.detour_upgrade_enabled = false; + const auto baseline = run(); + config.detour_upgrade_enabled = true; + config.detour_upgrade_min_saving = 0.99; + const auto result = run(); + ASSERT_TRUE(result.ok); + EXPECT_EQ(result.info.detour_upgrade_outcome, "kept_graph"); + EXPECT_EQ(result.info.tier_used, "graph"); + EXPECT_EQ(result.info.reason, baseline.info.reason); + EXPECT_EQ(result.info.retries, baseline.info.retries); + expectSamePath(result.path, baseline.path); +} + +TEST_F(DetourUpgradeTest, ZoneDeviationGuardKeepsGraphDespiteLengthSaving) +{ + usePreferredDetour(); + for (int y = 90; y < 110; ++y) + for (int x = 70; x < 230; ++x) + map.direction[static_cast(y * map.width + x)] = 2; + // The upper, preferred graph leg follows an eastbound zone; the short direct path cuts across the diagonal zone. + for (int y = 165; y < 185; ++y) + for (int x = 70; x < 230; ++x) + map.direction[static_cast(y * map.width + x)] = 1; + config.detour_upgrade_enabled = false; + const auto graph = run(); + config.detour_upgrade_enabled = true; + const auto result = run(); + ASSERT_TRUE(graph.ok); + ASSERT_TRUE(result.ok); + EXPECT_EQ(result.info.detour_upgrade_outcome, "kept_graph_zone_deviation"); + EXPECT_LT(result.info.detour_upgrade_lattice_cost, 0.85 * result.info.detour_upgrade_graph_cost); + EXPECT_LT(result.info.detour_upgrade_graph_zone_deviation_m, 0.5); + EXPECT_GT(result.info.detour_upgrade_lattice_zone_deviation_m, + result.info.detour_upgrade_graph_zone_deviation_m + config.detour_upgrade_max_extra_zone_deviation_m); + expectSamePath(result.path, graph.path); +} + +TEST_F(DetourUpgradeTest, WeightedCostRejectsExtraDeviation) +{ + config.detour_upgrade_max_extra_zone_deviation_m = 100.0; + const auto result = run(); + ASSERT_TRUE(result.ok); + EXPECT_EQ(result.info.detour_upgrade_outcome, "kept_graph_zone_deviation"); + EXPECT_LT(result.info.detour_upgrade_lattice_length_m, 0.85 * result.info.detour_upgrade_graph_length_m); + EXPECT_GE(result.info.detour_upgrade_lattice_cost, 0.85 * result.info.detour_upgrade_graph_cost); +} + +TEST_F(DetourUpgradeTest, DisabledLeavesGraphUnchanged) +{ + config.lattice_enabled = false; + const auto baseline = run(); + config.lattice_enabled = true; + config.detour_upgrade_enabled = false; + const auto result = run(); + ASSERT_TRUE(result.ok); + EXPECT_EQ(result.info.detour_upgrade_outcome, "off"); + EXPECT_EQ(result.info.tier_used, "graph"); + expectSamePath(result.path, baseline.path); +} + +TEST_F(DetourUpgradeTest, ExpiredBudgetKeepsGraph) +{ + config.detour_upgrade_enabled = false; + const auto baseline = run(); + config.detour_upgrade_enabled = true; + config.detour_upgrade_time_limit_s = 1e-9; + const auto result = run(); + ASSERT_TRUE(result.ok); + EXPECT_EQ(result.info.detour_upgrade_outcome, "lattice_failed"); + EXPECT_LT(result.info.detour_upgrade_time_ms, 200.0); + expectSamePath(result.path, baseline.path); +} + TEST(Lattice, StraightAndExactGoalYaw) { LatticeTestGrid map(120, 120); diff --git a/tools/lane_route_eval.cpp b/tools/lane_route_eval.cpp index 2cc0308..99bd0ed 100644 --- a/tools/lane_route_eval.cpp +++ b/tools/lane_route_eval.cpp @@ -263,6 +263,9 @@ void applyOverrides(PlannerConfig* config) { "lattice_analytic_radius_m", &config->lattice_analytic_radius_m }, { "lattice_analytic_near_goal_m", &config->lattice_analytic_near_goal_m }, { "lattice_field_time_fraction", &config->lattice_field_time_fraction }, + { "detour_upgrade_time_limit_s", &config->detour_upgrade_time_limit_s }, + { "detour_upgrade_max_extra_zone_deviation_m", &config->detour_upgrade_max_extra_zone_deviation_m }, + { "detour_upgrade_min_saving", &config->detour_upgrade_min_saving }, { "fallback_time_limit_s", &config->fallback_time_limit_s }, { "time_limit_s", &config->time_limit_s }, { "lattice_end_relax_radius_m", &config->lattice_end_relax_radius_m }, @@ -290,6 +293,7 @@ void applyOverrides(PlannerConfig* config) { "lattice_smooth_max_checks", &config->lattice_smooth_max_checks }, }; const std::map bools{ + { "detour_upgrade_enabled", &config->detour_upgrade_enabled }, { "lattice_smooth_enabled", &config->lattice_smooth_enabled }, { "lattice_tight_arcs", &config->lattice_tight_arcs }, { "lattice_alt_field_enabled", &config->lattice_alt_field_enabled }, @@ -514,7 +518,16 @@ int main(int argc, char** argv) } out << "]"; } - out << ",\"tier\":\"" << info.tier_used << "\",\"graph_reason\":\"" << info.graph_reason + out << ",\"detour_upgrade_outcome\":\"" << info.detour_upgrade_outcome + << "\",\"detour_upgrade_graph_length_m\":" << info.detour_upgrade_graph_length_m + << ",\"detour_upgrade_lattice_length_m\":" << info.detour_upgrade_lattice_length_m + << ",\"detour_upgrade_graph_cost\":" << info.detour_upgrade_graph_cost + << ",\"detour_upgrade_lattice_cost\":" << info.detour_upgrade_lattice_cost + << ",\"detour_upgrade_graph_zone_deviation_m\":" << info.detour_upgrade_graph_zone_deviation_m + << ",\"detour_upgrade_lattice_zone_deviation_m\":" << info.detour_upgrade_lattice_zone_deviation_m + << ",\"detour_upgrade_time_ms\":" << info.detour_upgrade_time_ms + << ",\"detour_upgrade_lattice_reason\":\"" << info.detour_upgrade_lattice_reason << "\"" + << ",\"tier\":\"" << info.tier_used << "\",\"graph_reason\":\"" << info.graph_reason << "\",\"lattice_reason\":\"" << info.lattice_reason << "\",\"lattice_states_expanded\":" << info.lattice_states_expanded << ",\"lattice_closed_pruned\":" << info.lattice_closed_pruned << ",\"lattice_refinement_attempts\":" << info.lattice_refinement_attempts << ",\"lattice_pose_checks\":" << info.lattice_pose_checks << ",\"lattice_field_cells\":" << info.lattice_field_cells