From 9af2ac3bd8ef0f41e467c0684c586baa2fc12926 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Busch Date: Mon, 16 Nov 2026 11:05:37 +0000 Subject: [PATCH 1/3] decide follow/pass per object prediction in the node Each object prediction is either passed or followed. The decision is made in the node (new class FollowPass) instead of implicitly in the OCP: - passed predictions bound the lateral offset from the reference path (soft, with d_min_object_lat or a per-class margin) - per stage, the closest followed prediction in the suggested lane gives an arc-length follow distance (soft d_min_object_long and thw, hard d_min_object_collision); the soft part is relaxed to what full braking can still reach - the initial guess starts from full braking if that is needed to keep d_min_object_long; a failed constrained solve is retried from the other initial guess within the remaining timeout The hard SAT separation stays for all other object slots. The thw slack weight is coupled to the lateral cost weight (w_lat / c_lat^2). --- trajectory_optimization/CMakeLists.txt | 1 + trajectory_optimization/README.md | 27 +- .../config/example_params_ackermann.yml | 19 +- .../config/example_params_rws.yml | 9 +- .../trajectory_optimization/follow_pass.hpp | 110 ++++++ .../performance_logger.hpp | 4 +- .../trajectory_optimization_node.hpp | 93 ++++- trajectory_optimization/src/follow_pass.cpp | 320 +++++++++++++++++ .../src/performance_logger.cpp | 20 +- .../src/trajectory_optimization_node.cpp | 337 ++++++++++++------ trajectory_optimization/src/utils.cpp | 43 +-- trajectory_optimization_ocp/README.md | 39 +- .../config/karl_params.yml | 21 +- .../config/shuttle_params.yml | 21 +- .../trajectory_optimization_ocp/constants.py | 8 + .../constraints.py | 67 ++-- .../trajectory_optimization_ocp/costs.py | 2 +- .../models/model_Ackermann.py | 3 +- .../models/model_RWS.py | 3 +- .../trajectory_optimization_ocp/utils.py | 34 +- 20 files changed, 959 insertions(+), 222 deletions(-) create mode 100644 trajectory_optimization/include/trajectory_optimization/follow_pass.hpp create mode 100644 trajectory_optimization/src/follow_pass.cpp diff --git a/trajectory_optimization/CMakeLists.txt b/trajectory_optimization/CMakeLists.txt index dced009..97768fd 100644 --- a/trajectory_optimization/CMakeLists.txt +++ b/trajectory_optimization/CMakeLists.txt @@ -28,6 +28,7 @@ set(TARGET_NAME trajectory_optimization_node_component) add_library(${TARGET_NAME} SHARED src/callbacks.cpp + src/follow_pass.cpp src/performance_logger.cpp src/trajectory_optimization_node.cpp src/trajectory_optimization_ackermann.cpp diff --git a/trajectory_optimization/README.md b/trajectory_optimization/README.md index 201e8b1..69c7088 100644 --- a/trajectory_optimization/README.md +++ b/trajectory_optimization/README.md @@ -59,9 +59,11 @@ flowchart LR | `run_as_callback` | `bool` | `false` | Run OCP once for each received reference trajectory (true) or on a timer (false) | | `cost_weights` | `float[]` | `std::vector(12, 1.0)` | Cost function weights | | `dynamic_weight` | `float` | `1.0` | Dynamic weight alpha | -| `thw` | `float` | `2.0` | Desired time headway to front vehicle [s]; soft when object slacks are enabled | -| `d_min_object_long` | `float` | `5.0` | Desired longitudinal object clearance [m]; soft when object slacks are enabled | -| `d_min_object_lat` | `float` | `0.5` | Desired lateral object clearance [m]; soft when object slacks are enabled | +| `thw` | `float` | `2.0` | Desired time headway to followed objects [s]; soft when object slacks are enabled | +| `d_min_object_long` | `float` | `5.0` | Desired distance to followed objects [m]; soft when object slacks are enabled | +| `d_min_object_lat` | `float` | `0.5` | Desired lateral distance to passed objects of classes without an own value [m]; soft when object slacks are enabled | +| `d_min_object_lat_classes` | `int[]` | `[]` | Object classes (perception_msgs/ObjectClassification) with an own lateral distance | +| `d_min_object_lat_class_values` | `float[]` | `[]` | Desired lateral distance to passed objects per class in `d_min_object_lat_classes` [m] | | `d_min_boundary_lat` | `float` | `0.0` | Minimum distance to keep to boundary in lateral direction [m] | | `standstill_threshold` | `float` | `0.45` | Threshold for standstill detection [m/s]. If the velocities of all states are below this threshold, publish standstill trajectory | | `high_level_stabilization` | `bool` | `false` | Use high-level stabilization strategy for init state (= init with current EgoData) | @@ -73,6 +75,25 @@ flowchart LR | `bi_level_dY` | `float` | `0.3` | Threshold for bi-level stabilization: maximum y-offset [m] | | `bi_level_dYaw` | `float` | `89.0` | Threshold for bi-level stabilization: maximum yaw difference [degree] | +#### Following and passing objects + +Each object prediction is either followed or passed: + +- A prediction that crosses the reference path is followed. +- Otherwise it is passed if the ego fits next to it with the lateral distance of its class (`d_min_object_lat`, + `d_min_object_lat_classes`) and the current ego pose already keeps this distance where the prediction is next to the + ego. The room for passing is the suggested lane if the prediction is in that lane, otherwise the boundaries selected by + `consider_boundaries`. A passed prediction stays passed while this holds with `d_min_object_collision`. +- A prediction enters the suggested lane when its center is in it at any stage, and leaves it only when none of its + corners is in it any more. + +Passed predictions bound the lateral offset of the ego from the reference path. Per stage, the followed prediction in the +suggested lane whose rear is closest along the reference path gives the follow distance (`d_min_object_long`, `thw`), if +the ego can still stay behind it with full braking. The desired distance is reduced by the part that full braking cannot +reach. If `d_min_object_long` is reachable only with full braking, the solve starts from the braking profile instead of +the warm start. With a follow distance, a rejected solve is retried once from the other initial guess within the +remaining `constrained_solve_timeout_ms`. + ## Launch Files ### [`trajectory_optimization.launch.py`](launch/trajectory_optimization.launch.py) diff --git a/trajectory_optimization/config/example_params_ackermann.yml b/trajectory_optimization/config/example_params_ackermann.yml index 9230bc2..479446e 100644 --- a/trajectory_optimization/config/example_params_ackermann.yml +++ b/trajectory_optimization/config/example_params_ackermann.yml @@ -32,22 +32,25 @@ #### cost weights cost_weights: - - 0.02 # dlat (0) + - 0.1 # dlat (0) - 0.0 # psi (1) (considered if RWS model is used) - - 0.3 # overspeed (2) - - 0.1 # underspeed (3) + - 0.5 # overspeed (2) + - 0.2 # underspeed (3) - 0.15 # a_lat (4) - - 0.2 # a_lon_pos (5) + - 0.15 # a_lon_pos (5) - 0.1 # a_lon_neg (6) - 0.2 # j_lat (7) - 0.1 # j_lon_pos (8) - - 0.15 # j_lon_neg (9) + - 0.1 # j_lon_neg (9) - 0.1 # alpha (10) - 3.0 # endYaw (11) dynamic_weight: 1.0 # base for exponential weight # other cost params - thw: 2.0 # desired time headway [s]; soft with object slacks - d_min_object_long: 1.0 # desired longitudinal object clearance [m]; soft with object slacks - d_min_object_lat: 0.1 # desired lateral object clearance [m]; soft with object slacks + thw: 2.0 # desired time headway to followed objects [s]; soft with object slacks + d_min_object_long: 1.0 # desired distance to followed objects [m]; soft with object slacks + d_min_object_lat: 0.1 # desired lateral distance to passed objects [m]; soft with object slacks + # own lateral distance for some object classes (perception_msgs/ObjectClassification), e.g. bicycles: + # d_min_object_lat_classes: [2] + # d_min_object_lat_class_values: [1.5] d_min_boundary_lat: 0.0 # minimum distance to keep to boundaries in lateral direction [m] diff --git a/trajectory_optimization/config/example_params_rws.yml b/trajectory_optimization/config/example_params_rws.yml index ddd92ef..dce5c52 100644 --- a/trajectory_optimization/config/example_params_rws.yml +++ b/trajectory_optimization/config/example_params_rws.yml @@ -51,7 +51,10 @@ dynamic_weight: 1.0 # base for exponential weight # other cost params - thw: 2.0 # desired time headway [s]; soft with object slacks - d_min_object_long: 1.0 # desired longitudinal object clearance [m]; soft with object slacks - d_min_object_lat: 0.1 # desired lateral object clearance [m]; soft with object slacks + thw: 2.0 # desired time headway to followed objects [s]; soft with object slacks + d_min_object_long: 1.0 # desired distance to followed objects [m]; soft with object slacks + d_min_object_lat: 0.1 # desired lateral distance to passed objects [m]; soft with object slacks + # own lateral distance for some object classes (perception_msgs/ObjectClassification), e.g. bicycles: + # d_min_object_lat_classes: [2] + # d_min_object_lat_class_values: [1.5] d_min_boundary_lat: 0.0 # minimum distance to keep to boundaries in lateral direction [m] diff --git a/trajectory_optimization/include/trajectory_optimization/follow_pass.hpp b/trajectory_optimization/include/trajectory_optimization/follow_pass.hpp new file mode 100644 index 0000000..cddfaa4 --- /dev/null +++ b/trajectory_optimization/include/trajectory_optimization/follow_pass.hpp @@ -0,0 +1,110 @@ +// Copyright Institute for Automotive Engineering (ika), RWTH Aachen University +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace trajectory_optimization { + +/** + * @brief Decides per object prediction whether the ego follows or passes it and derives the corresponding OCP inputs. + * + * A prediction is passed if it never crosses the reference path, the ego fits next to it with the lateral margin of its + * class, and the current ego pose already keeps that margin where the prediction is next to the ego. The room for passing + * is the suggested lane if the prediction is in that lane, otherwise the active route boundaries. A passed prediction stays + * passed while this holds with d_min_object_collision as margin. All other predictions are followed. + * + * Passed predictions bound the lateral offset of the ego from the reference path. Per stage, the followed prediction in the + * suggested lane whose rear is closest along the reference path gives the follow distance, if the ego can still stay behind + * it with full braking. The desired distance is relaxed by the part that full braking cannot reach. + */ +class FollowPass { + public: + /** Finite sentinel for "no bound", like the boundary distances (infinity would propagate NaNs in the OCP). */ + static constexpr double NO_BOUND = 1e6; + + /** Oriented box of an object slot at one stage. */ + struct Box { + double x = 0.0; + double y = 0.0; + double yaw = 0.0; + double half_length = 0.0; + double half_width = 0.0; + bool active = false; + }; + + /** Identity of an OCP object slot (constant over the stages). */ + struct Slot { + uint64_t object_id = 0; + size_t prediction = 0; + uint8_t object_class = 0; + }; + + /** Reference path samples as passed to the OCP. Distances are (left, right) and positive. */ + struct Reference { + std::vector x; + std::vector y; + std::vector psi; + std::vector> boundary_distances; // active route boundaries + std::vector> lane_distances; // suggested lane + }; + + struct Params { + double thw = 0.0; + double d_min_object_long = 0.0; + double d_min_object_lat = 0.0; // lateral margin of classes without an own margin + double d_min_object_collision = 0.0; + double d_min_boundary_lat = 0.0; + std::map class_lateral_margins; + double ego_half_length = 0.0; + double ego_half_width = 0.0; + std::array ego_offset_to_geometric_center{}; + }; + + struct Result { + std::vector d_object_left; // per reference sample + std::vector d_object_right; // per reference sample + std::vector s; // arc length per reference sample + std::vector> follow; // per stage [s_rear, active, relax] + std::vector follow_slot; // per stage the slot replaced by the follow distance, -1 if none + bool follow_active = false; // a follow distance is set at any stage + bool brake_needed = false; // d_min_object_long is reachable only with full braking at an active stage + }; + + /** + * @brief Decides follow/pass for all active object slots and derives bounds and follow distances. + * + * @param[in] reference Reference samples as passed to the OCP. + * @param[in] boxes Object boxes per stage and slot. + * @param[in] slots Identity of every slot. + * @param[in] ego_pose Pose (x, y, yaw) of the vehicle frame at the first stage. + * @param[in] braking_travel Distance travelled with full braking until each stage. + * @param[in] braking_speed Speed at each stage with full braking. + * @param[in] params Parameters. + * @return OCP inputs derived from the decisions. + */ + Result decide(const Reference& reference, + const std::vector>& boxes, + const std::vector& slots, + const std::array& ego_pose, + const std::vector& braking_travel, + const std::vector& braking_speed, + const Params& params); + + private: + struct Memory { + bool in_lane = false; + int passed_side = 0; // +1 passed on the left, -1 passed on the right, 0 followed + }; + + // decisions of the previous cycle per (object id, prediction) + std::map, Memory> memory_; +}; + +} // namespace trajectory_optimization diff --git a/trajectory_optimization/include/trajectory_optimization/performance_logger.hpp b/trajectory_optimization/include/trajectory_optimization/performance_logger.hpp index 9098f1c..3a1ea17 100644 --- a/trajectory_optimization/include/trajectory_optimization/performance_logger.hpp +++ b/trajectory_optimization/include/trajectory_optimization/performance_logger.hpp @@ -145,12 +145,11 @@ class PerformanceLogger { /** * @brief Checks all slacks for finiteness and optionally collects desired-clearance statistics. * - * @param[in,out] metrics Metrics populated with the largest lower object-clearance slack. + * @param[in,out] metrics Metrics populated with the largest object-clearance slack (passed objects, follow distance). * @param[in] config acados NLP configuration. * @param[in] dims acados NLP dimensions. * @param[in] input acados NLP input containing the slack-to-constraint mapping. * @param[in] output acados NLP output containing the slack values. - * @param[in] object_boxes Number of object boxes in each object constraint block. * @param[in] collect_details Whether to collect object-clearance statistics. * @return True if all lower and upper slack values are finite. */ @@ -159,7 +158,6 @@ class PerformanceLogger { ocp_nlp_dims* dims, ocp_nlp_in* input, ocp_nlp_out* output, - int object_boxes, bool collect_details); /** diff --git a/trajectory_optimization/include/trajectory_optimization/trajectory_optimization_node.hpp b/trajectory_optimization/include/trajectory_optimization/trajectory_optimization_node.hpp index 7c0041c..d1458e8 100644 --- a/trajectory_optimization/include/trajectory_optimization/trajectory_optimization_node.hpp +++ b/trajectory_optimization/include/trajectory_optimization/trajectory_optimization_node.hpp @@ -5,6 +5,8 @@ #include #include +#include +#include #include #include #include @@ -30,6 +32,7 @@ #include // acados +#include #include #include @@ -86,6 +89,29 @@ class TrajectoryOptimizationNode : public rclcpp::Node { enum CONSIDER_OBJECTS { NO_OBJECTS = 0, STATIC_OBJECTS = 1, PREDICTED_OBJECTS = 2 }; + /** Fastest stop within the OCP limits: jerk per shooting interval, travelled distance and speed per stage. */ + struct BrakingProfile { + std::vector jerk; + std::vector travel; + std::vector speed; + }; + + /** Build-time constants of a generated model that the node needs (must match the OCP configuration). */ + struct ModelConstants { + double length = 0.0; + double width = 0.0; + std::array offset_to_geometric_center{}; + double d_min_object_collision = 0.0; + }; + + /** + * @brief Returns the build-time constants of a model. + * + * @param[in] model_name Name of the generated acados model. + * @return Constants of the model, or std::nullopt for unknown models. + */ + static std::optional modelConstants(const std::string& model_name); + /** * @brief Declares a ROS parameter, loads its value and optionally registers it for runtime updates. * @@ -136,9 +162,27 @@ class TrajectoryOptimizationNode : public rclcpp::Node { * * @param[in] x_init Hard initial state of the OCP. * @param[in] stamp Absolute time corresponding to x_init. + * @param[in] jerk Optional jerk per shooting interval that replaces the cached jerk (e.g. the braking profile). * @return `true` if the state rollout succeeded. */ - bool setInitialGuess(const std::vector& x_init, const rclcpp::Time& stamp); + bool setInitialGuess(const std::vector& x_init, const rclcpp::Time& stamp, const std::vector* jerk = nullptr); + + /** + * @brief Integrates the OCP dynamics over one shooting interval with the integrator settings of the generated OCP. + * + * @param[in] stage Shooting stage. + * @param[in,out] state State at the start (in) and at the end (out) of the interval. + * @param[in] control Control applied during the interval. + */ + void integrateStage(int stage, std::vector& state, std::vector& control); + + /** + * @brief Computes the fastest stop within the jerk and acceleration bounds of the OCP. + * + * @param[in] x_init Hard initial state of the OCP. + * @return Braking jerk per shooting interval and the resulting travel and speed per stage. + */ + BrakingProfile brakingProfile(const std::vector& x_init); /** * @brief Creates the acados solver instance and initializes its state buffers. @@ -231,31 +275,49 @@ class TrajectoryOptimizationNode : public rclcpp::Node { * @param[in] object_list Current object list. * @param[in] route Current route data. * @param[in] reference_trajectory Current reference trajectory. + * @param[in] x_init Hard initial state of the OCP. + * @param[in] braking Braking profile from x_init. * @return `true` if all optimizer inputs were updated successfully. */ bool updateOcpInputs(const perception_msgs::msg::EgoData& ego_data, const perception_msgs::msg::ObjectList& object_list, const route_planning_msgs::msg::Route& route, - const trajectory_planning_msgs::msg::Trajectory& reference_trajectory); + const trajectory_planning_msgs::msg::Trajectory& reference_trajectory, + const std::vector& x_init, + const BrakingProfile& braking); /** * @brief Writes stage-independent data into the OCP. * * @param[in] cost_weights Configured cost weights. - * @param[in] reference_trajectory Reference trajectory in optimizer frame. - * @param[in] route Route data used for boundary distances. + * @param[in] reference Reference samples (including boundary distances) in optimizer frame. + * @param[in] reference_v Reference speed per reference sample. + * @param[in] follow_pass Bounds of passed objects and arc length per reference sample. */ void setOcpGlobalParameters(const std::vector& cost_weights, - const trajectory_planning_msgs::msg::Trajectory& reference_trajectory, - const route_planning_msgs::msg::Route& route); + const FollowPass::Reference& reference, + const std::vector& reference_v, + const FollowPass::Result& follow_pass); /** - * @brief Writes stage-wise object, boundary-activation, and dynamic-weighting parameters into the OCP. + * @brief Predicts the box of every object prediction at every stage, in the slot order of the OCP. * * @param[in] ego_data Current ego state. * @param[in] object_list Object list in optimizer frame. + * @param[out] slots Identity of every object slot. + * @return Object boxes per stage and slot. */ - void setOcpParameters(const perception_msgs::msg::EgoData& ego_data, const perception_msgs::msg::ObjectList& object_list); + std::vector> predictObjectBoxes(const perception_msgs::msg::EgoData& ego_data, + const perception_msgs::msg::ObjectList& object_list, + std::vector& slots); + + /** + * @brief Writes stage-wise object, follow, boundary-activation, and dynamic-weighting parameters into the OCP. + * + * @param[in] object_boxes Object boxes per stage and slot. + * @param[in] follow_pass Follow distance per stage; the slot it replaces gets no box constraint at that stage. + */ + void setOcpParameters(const std::vector>& object_boxes, const FollowPass::Result& follow_pass); /** * @brief Keeps the nearest objects, optionally excluding those behind the ego vehicle. @@ -294,10 +356,13 @@ class TrajectoryOptimizationNode : public rclcpp::Node { * * @param[in] reference_trajectory Reference trajectory in optimizer frame. * @param[in] route Route data used to derive active boundaries. + * @param[in] consider_boundaries Boundaries to use (CONSIDER_BOUNDARIES). * @return Left and right boundary distances for each reference sample. */ std::vector> normalBoundaryDistance( - const trajectory_planning_msgs::msg::Trajectory& reference_trajectory, const route_planning_msgs::msg::Route& route); + const trajectory_planning_msgs::msg::Trajectory& reference_trajectory, + const route_planning_msgs::msg::Route& route, + uint8_t consider_boundaries); /** Publishes the object boxes currently passed to the optimizer. */ void vizObjectBoxes(const std::vector& objects); @@ -421,20 +486,28 @@ class TrajectoryOptimizationNode : public rclcpp::Node { double thw_ = 2.0; double d_min_object_long_ = 5.0; double d_min_object_lat_ = 0.5; + std::vector d_min_object_lat_classes_; + std::vector d_min_object_lat_class_values_; double d_min_boundary_lat_ = 0.0; double min_prediction_probability_ = 0.0; // ocp parameter vector structure // attention: changes here must also be done in the OCP! std::vector p_cost_weights_shape_ = {12, 1}; // nWeights x weightDim - std::vector p_ref_path_shape_ = {51, 6}; // nStates x [psi, x, y, v, d_bound_left, d_bound_right] + // nStates x [psi, x, y, v, d_bound_left, d_bound_right, d_object_left, d_object_right, s] + std::vector p_ref_path_shape_ = {51, 9}; std::vector p_dynamic_weight_shape_ = {1, 1}; std::vector p_constraint_activation_shape_ = {2, 1}; // [objects, boundaries] std::vector p_objects_shape_ = {30, 6}; // nObjects x [x, y, yaw, half-length, half-width, active] + std::vector p_follow_shape_ = {3, 1}; // [s_rear, active, relax] // whether object constraints are enabled for the current input data bool object_constraints_active_ = false; + // follow/pass decisions (keeps the decisions of the previous cycle) and its result for the current cycle + FollowPass follow_pass_; + FollowPass::Result follow_pass_result_; + // ocp variables ocp_model_capsule_t ocp_capsule_; ocp_nlp_config* nlp_config_; diff --git a/trajectory_optimization/src/follow_pass.cpp b/trajectory_optimization/src/follow_pass.cpp new file mode 100644 index 0000000..7b7976a --- /dev/null +++ b/trajectory_optimization/src/follow_pass.cpp @@ -0,0 +1,320 @@ +// Copyright Institute for Automotive Engineering (ika), RWTH Aachen University +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include +#include + +#include + +namespace trajectory_optimization { + +namespace { + +constexpr double INF = std::numeric_limits::infinity(); + +using Point = std::array; + +/** Corners of an oriented box: front left, front right, rear right, rear left. */ +std::array boxCorners(double x, double y, double yaw, double half_length, double half_width) { + constexpr std::array, 4> SIGNS{{{1.0, 1.0}, {1.0, -1.0}, {-1.0, -1.0}, {-1.0, 1.0}}}; + const double cos_yaw = std::cos(yaw); + const double sin_yaw = std::sin(yaw); + std::array corners{}; + for (size_t i = 0; i < corners.size(); ++i) { + const double l = SIGNS[i][0] * half_length; + const double w = SIGNS[i][1] * half_width; + corners[i] = {x + l * cos_yaw - w * sin_yaw, y + l * sin_yaw + w * cos_yaw}; + } + return corners; +} + +/** Position along (arc length s) and lateral offset from (e, left positive) the reference path. */ +struct Projection { + double s = 0.0; + double e = 0.0; +}; + +/** Reference polyline, extended by rays along the first and last heading; s = 0 at the first sample. */ +class Path { + public: + explicit Path(const FollowPass::Reference& reference) { + constexpr double MIN_SAMPLE_DISTANCE = 1e-6; // repeated samples (padding, standstill) carry no direction + for (size_t i = 0; i < reference.x.size(); ++i) { + const Point point{reference.x[i], reference.y[i]}; + const double distance = points_.empty() ? INF : std::hypot(point[0] - points_.back()[0], point[1] - points_.back()[1]); + if (distance > MIN_SAMPLE_DISTANCE) { + s_points_.push_back(points_.empty() ? 0.0 : s_points_.back() + distance); + points_.push_back(point); + distinct_samples_.push_back(i); + } + s_samples_.push_back(s_points_.back()); + } + first_direction_ = {std::cos(reference.psi[distinct_samples_.front()]), std::sin(reference.psi[distinct_samples_.front()])}; + last_direction_ = {std::cos(reference.psi[distinct_samples_.back()]), std::sin(reference.psi[distinct_samples_.back()])}; + } + + /** Arc length of every reference sample. */ + const std::vector& sampleArcLengths() const { return s_samples_; } + + Projection project(const Point& point) const { + double best_distance = INF; + Projection projection; + const auto consider = [&](const Point& start, const Point& direction, double s_start, double lambda_min, double lambda_max) { + const double dx = point[0] - start[0]; + const double dy = point[1] - start[1]; + const double lambda = std::clamp(dx * direction[0] + dy * direction[1], lambda_min, lambda_max); + const double distance = std::hypot(dx - lambda * direction[0], dy - lambda * direction[1]); + if (distance < best_distance) { + best_distance = distance; + projection = {s_start + lambda, direction[0] * dy - direction[1] * dx}; + } + }; + consider(points_.front(), first_direction_, 0.0, -INF, 0.0); + for (size_t i = 0; i + 1 < points_.size(); ++i) { + const double length = s_points_[i + 1] - s_points_[i]; + const Point direction{(points_[i + 1][0] - points_[i][0]) / length, (points_[i + 1][1] - points_[i][1]) / length}; + consider(points_[i], direction, s_points_[i], 0.0, length); + } + consider(points_.back(), last_direction_, s_points_.back(), 0.0, INF); + return projection; + } + + /** Interpolates per-sample values at arc length s; constant beyond the reference ends. */ + double at(double s, const std::vector& sample_values) const { + if (s <= s_points_.front()) return sample_values[distinct_samples_.front()]; + if (s >= s_points_.back()) return sample_values[distinct_samples_.back()]; + const size_t upper = static_cast(std::upper_bound(s_points_.begin(), s_points_.end(), s) - s_points_.begin()); + const double weight = (s - s_points_[upper - 1]) / (s_points_[upper] - s_points_[upper - 1]); + const double lower_value = sample_values[distinct_samples_[upper - 1]]; + return lower_value + weight * (sample_values[distinct_samples_[upper]] - lower_value); + } + + private: + std::vector points_; // distinct samples + std::vector s_points_; // arc length of the distinct samples + std::vector distinct_samples_; // sample index of every distinct sample + std::vector s_samples_; // arc length of every sample + Point first_direction_{}; + Point last_direction_{}; +}; + +/** + * @brief Arc length of the foremost front ego corner as the OCP evaluates it: linearised at the reference point matched + * to the ego center (same matching as determine_spacially_matched_ref_path_point in the OCP). + */ +double ocpFrontArcLength(const FollowPass::Reference& reference, + const std::vector& s_samples, + const Point& center, + double yaw, + const FollowPass::Params& params) { + const size_t n = reference.x.size(); + std::vector distances(n); + for (size_t i = 0; i < n; ++i) distances[i] = std::hypot(reference.x[i] - center[0], reference.y[i] - center[1]); + const size_t i = static_cast(std::min_element(distances.begin(), distances.end()) - distances.begin()); + size_t j = i; + if (n > 1) j = i == 0 ? 1 : (i == n - 1 ? n - 2 : (distances[i - 1] < distances[i + 1] ? i - 1 : i + 1)); + const double segment_x = reference.x[j] - reference.x[i]; + const double segment_y = reference.y[j] - reference.y[i]; + const double segment_squared = segment_x * segment_x + segment_y * segment_y; + double lambda = segment_squared == 0.0 + ? 0.0 + : ((center[0] - reference.x[i]) * segment_x + (center[1] - reference.y[i]) * segment_y) / segment_squared; + if (i != 0) lambda = std::clamp(lambda, 0.0, 1.0); // the OCP extrapolates only before the first sample + const Point matched{reference.x[i] + lambda * segment_x, reference.y[i] + lambda * segment_y}; + const double s_matched = s_samples[i] + lambda * (s_samples[j] - s_samples[i]); + const double psi_difference = std::remainder(reference.psi[j] - reference.psi[i], 2.0 * M_PI); + const double psi_matched = reference.psi[i] + std::clamp(lambda, 0.0, 1.0) * psi_difference; + const auto corners = boxCorners(center[0], center[1], yaw, params.ego_half_length, params.ego_half_width); + double s_front = -INF; + for (size_t corner = 0; corner < 2; ++corner) { + const double along = + (corners[corner][0] - matched[0]) * std::cos(psi_matched) + (corners[corner][1] - matched[1]) * std::sin(psi_matched); + s_front = std::max(s_front, s_matched + along); + } + return s_front; +} + +} // namespace + +FollowPass::Result FollowPass::decide(const Reference& reference, + const std::vector>& boxes, + const std::vector& slots, + const std::array& ego_pose, + const std::vector& braking_travel, + const std::vector& braking_speed, + const Params& params) { + const size_t n_ref = reference.x.size(); + const size_t n_stages = boxes.size(); + const Path path(reference); + const std::vector& s_ref = path.sampleArcLengths(); + + std::vector lane_left(n_ref), lane_right(n_ref), boundary_left(n_ref), boundary_right(n_ref); + for (size_t i = 0; i < n_ref; ++i) { + std::tie(lane_left[i], lane_right[i]) = reference.lane_distances[i]; + std::tie(boundary_left[i], boundary_right[i]) = reference.boundary_distances[i]; + } + const auto in_lane_at = [&](const Projection& p) { return p.e <= path.at(p.s, lane_left) && p.e >= -path.at(p.s, lane_right); }; + + // current ego box along the path and the reference samples next to it + const double ego_yaw = ego_pose[2]; + const Point ego_center{ego_pose[0] + params.ego_offset_to_geometric_center[0] * std::cos(ego_yaw) - + params.ego_offset_to_geometric_center[1] * std::sin(ego_yaw), + ego_pose[1] + params.ego_offset_to_geometric_center[0] * std::sin(ego_yaw) + + params.ego_offset_to_geometric_center[1] * std::cos(ego_yaw)}; + double ego_s_min = INF, ego_s_max = -INF, ego_e_min = INF, ego_e_max = -INF; + for (const auto& corner : boxCorners(ego_center[0], ego_center[1], ego_yaw, params.ego_half_length, params.ego_half_width)) { + const Projection p = path.project(corner); + ego_s_min = std::min(ego_s_min, p.s); + ego_s_max = std::max(ego_s_max, p.s); + ego_e_min = std::min(ego_e_min, p.e); + ego_e_max = std::max(ego_e_max, p.e); + } + + // an object is next to a reference sample if it is within half the ego length plus the sample spacing + std::vector window(n_ref); + for (size_t i = 0; i < n_ref; ++i) { + const double previous = i > 0 ? std::abs(s_ref[i] - s_ref[i - 1]) : 0.0; + const double next = i + 1 < n_ref ? std::abs(s_ref[i + 1] - s_ref[i]) : 0.0; + window[i] = params.ego_half_length + std::max(previous, next); + } + + Result result; + result.d_object_left.assign(n_ref, NO_BOUND); + result.d_object_right.assign(n_ref, NO_BOUND); + result.s = s_ref; + result.follow.assign(n_stages, {0.0, 0.0, 0.0}); + result.follow_slot.assign(n_stages, -1); + + // follow or pass, per prediction + std::map, Memory> memory; + std::vector followed(slots.size(), false); + for (size_t slot = 0; slot < slots.size() && n_stages > 0; ++slot) { + if (!boxes[0][slot].active) continue; + const auto key = std::make_pair(slots[slot].object_id, slots[slot].prediction); + const auto previous_it = memory_.find(key); + const Memory previous = previous_it != memory_.end() ? previous_it->second : Memory{}; + + std::vector centers, corners; + for (size_t stage = 0; stage < n_stages; ++stage) { + const Box& box = boxes[stage][slot]; + if (!box.active) continue; + centers.push_back(path.project({box.x, box.y})); + for (const auto& corner : boxCorners(box.x, box.y, box.yaw, box.half_length, box.half_width)) { + corners.push_back(path.project(corner)); + } + } + + // lane membership with hysteresis: the prediction enters our lane when its center is in it at any stage, and + // leaves it only when none of its corners is in it any more + const bool in_lane = previous.in_lane ? std::any_of(corners.begin(), corners.end(), in_lane_at) + : std::any_of(centers.begin(), centers.end(), in_lane_at); + + // side of the reference path the prediction is on; a prediction that crosses the path is never passed + std::vector center_offsets; + for (const auto& p : centers) center_offsets.push_back(p.e); + const size_t middle = center_offsets.size() / 2; + std::nth_element(center_offsets.begin(), center_offsets.begin() + static_cast(middle), center_offsets.end()); + double median = center_offsets[middle]; + if (center_offsets.size() % 2 == 0) { + median = 0.5 * + (median + *std::max_element(center_offsets.begin(), center_offsets.begin() + static_cast(middle))); + } + const bool right = median < 0.0; // the ego passes a prediction on the right of the path on the left + const int side = right ? 1 : -1; + const bool crosses = + std::any_of(corners.begin(), corners.end(), [&](const Projection& p) { return right ? p.e > 0.0 : p.e < 0.0; }); + + // lateral extent of the prediction next to each reference sample + std::vector e_near(n_ref, right ? -INF : INF); + std::vector near(n_ref, false), alongside(n_ref, false); + for (const auto& p : corners) { + const double s_clamped = std::clamp(p.s, s_ref.front(), s_ref.back()); // beyond the ends: the first/last sample + for (size_t i = 0; i < n_ref; ++i) { + if (std::abs(s_clamped - s_ref[i]) <= window[i]) { + near[i] = true; + e_near[i] = right ? std::max(e_near[i], p.e) : std::min(e_near[i], p.e); + } + if (std::abs(p.s - s_ref[i]) <= window[i]) alongside[i] = true; + } + } + + // the ego fits next to the prediction with margin m: in our lane only within the lane, otherwise within the boundaries + const auto fits = [&](double m) { + for (size_t i = 0; i < n_ref; ++i) { + if (!near[i]) continue; + const double far = in_lane ? (right ? lane_left[i] : lane_right[i]) + : (right ? boundary_left[i] : boundary_right[i]) - params.d_min_boundary_lat; + if (right ? e_near[i] + m + params.ego_half_width > far - params.ego_half_width + : -far + params.ego_half_width > e_near[i] - m - params.ego_half_width) { + return false; + } + } + return true; + }; + // the current ego pose already keeps margin m where the prediction is next to the ego now + const auto ego_clear = [&](double m) { + for (size_t i = 0; i < n_ref; ++i) { + if (!alongside[i] || s_ref[i] < ego_s_min || s_ref[i] > ego_s_max) continue; + if (right ? ego_e_min < e_near[i] + m : ego_e_max > e_near[i] - m) return false; + } + return true; + }; + + const auto margin_it = params.class_lateral_margins.find(slots[slot].object_class); + const double margin = margin_it != params.class_lateral_margins.end() ? margin_it->second : params.d_min_object_lat; + const double d_coll = params.d_min_object_collision; + const bool keep_passing = previous.passed_side == side && fits(d_coll) && ego_clear(d_coll); + const int passed_side = !crosses && (keep_passing || (fits(margin) && ego_clear(margin))) ? side : 0; + memory[key] = {in_lane, passed_side}; + + if (passed_side == 0) { + followed[slot] = true; + continue; + } + for (size_t i = 0; i < n_ref; ++i) { + if (!alongside[i]) continue; + if (right) { + result.d_object_right[i] = std::min(result.d_object_right[i], -(e_near[i] + margin)); + } else { + result.d_object_left[i] = std::min(result.d_object_left[i], e_near[i] - margin); + } + } + } + memory_ = std::move(memory); + + // follow distance per stage: the followed prediction in our lane whose rear is closest along the path, if the ego can + // still stay behind it with full braking; relaxed by the part of the desired distance full braking cannot reach + const double s_front = ocpFrontArcLength(reference, s_ref, ego_center, ego_yaw, params); + for (size_t stage = 0; stage < n_stages; ++stage) { + double s_rear = INF; + int follow_slot = -1; + for (size_t slot = 0; slot < slots.size(); ++slot) { + const Box& box = boxes[stage][slot]; + if (!followed[slot] || !box.active) continue; + bool in_lane = false; + double s_min = INF; + for (const auto& corner : boxCorners(box.x, box.y, box.yaw, box.half_length, box.half_width)) { + const Projection p = path.project(corner); + in_lane = in_lane || in_lane_at(p); + s_min = std::min(s_min, p.s); + } + if (in_lane && s_min < s_rear) { + s_rear = s_min; + follow_slot = static_cast(slot); + } + } + if (follow_slot < 0) continue; + const double gap = s_rear - s_front - braking_travel[stage]; + if (gap < params.d_min_object_collision) continue; + const double relax = std::max({0.0, params.d_min_object_long - gap, params.thw * braking_speed[stage] - gap}); + result.follow[stage] = {s_rear, 1.0, relax}; + result.follow_slot[stage] = follow_slot; + result.follow_active = true; + result.brake_needed = result.brake_needed || gap < params.d_min_object_long; + } + return result; +} + +} // namespace trajectory_optimization diff --git a/trajectory_optimization/src/performance_logger.cpp b/trajectory_optimization/src/performance_logger.cpp index 2d85713..7659a7f 100644 --- a/trajectory_optimization/src/performance_logger.cpp +++ b/trajectory_optimization/src/performance_logger.cpp @@ -17,6 +17,10 @@ namespace trajectory_optimization { namespace { +// layout of the object rows in the OCP (trajectory_optimization_ocp/constraints.py) +constexpr int SOFT_OBJECT_ROWS = 8; // bounds of passed objects (4), follow distance (2 front corners x [d_min_object_long, thw]) +constexpr int HARD_FOLLOW_ROWS = 2; // hard follow distance of both front corners, after one hard row per object box + std::string timestamp() { const auto now = std::chrono::system_clock::now(); const auto time = std::chrono::system_clock::to_time_t(now); @@ -165,19 +169,21 @@ void PerformanceLogger::collectConstraintDiagnostics(PerformanceMetrics& metrics } else if (index < nb + ng) { metrics.max_ineq_type = "linear"; } else if (index < nb + ng + nh) { + // rows: 2 boundaries, soft object rows, one hard row per object box and the hard follow rows, vehicle limits const int h_index = index - nb - ng; + const int collision_rows = object_boxes + HARD_FOLLOW_ROWS; if (h_index < 2) { metrics.max_ineq_type = h_index == 0 ? "boundary_left" : "boundary_right"; metrics.max_ineq_index = 0; - } else if (h_index < object_boxes + 2) { + } else if (h_index < SOFT_OBJECT_ROWS + 2) { metrics.max_ineq_type = "object_clearance"; metrics.max_ineq_index = h_index - 2; - } else if (h_index < 2 * object_boxes + 2) { + } else if (h_index < SOFT_OBJECT_ROWS + collision_rows + 2) { metrics.max_ineq_type = "object_collision"; - metrics.max_ineq_index = h_index - object_boxes - 2; + metrics.max_ineq_index = h_index - SOFT_OBJECT_ROWS - 2; } else { metrics.max_ineq_type = "vehicle"; - metrics.max_ineq_index = h_index - 2 * object_boxes - 2; + metrics.max_ineq_index = h_index - SOFT_OBJECT_ROWS - collision_rows - 2; } } else { metrics.max_ineq_type = "slack"; @@ -191,7 +197,6 @@ bool PerformanceLogger::collectSlackStatistics(PerformanceMetrics& metrics, ocp_nlp_dims* dims, ocp_nlp_in* input, ocp_nlp_out* output, - int object_boxes, bool collect_details) { metrics.max_object_clearance_slack = 0.0; metrics.max_object_clearance_slack_stage = -1; @@ -212,8 +217,9 @@ bool PerformanceLogger::collectSlackStatistics(PerformanceMetrics& metrics, const int clearance_start = dims->nb[stage] + dims->ng[stage] + 2; for (int slack = 0; slack < ns; ++slack) { const int object_index = slack_indices[slack] - clearance_start; - if (object_index >= 0 && object_index < object_boxes && lower[slack] > metrics.max_object_clearance_slack) { - metrics.max_object_clearance_slack = lower[slack]; + const double object_slack = std::max(lower[slack], upper[slack]); // passed objects: upper, follow distance: lower + if (object_index >= 0 && object_index < SOFT_OBJECT_ROWS && object_slack > metrics.max_object_clearance_slack) { + metrics.max_object_clearance_slack = object_slack; metrics.max_object_clearance_slack_stage = stage; metrics.max_object_clearance_slack_index = object_index; } diff --git a/trajectory_optimization/src/trajectory_optimization_node.cpp b/trajectory_optimization/src/trajectory_optimization_node.cpp index 08dc957..b4d1911 100644 --- a/trajectory_optimization/src/trajectory_optimization_node.cpp +++ b/trajectory_optimization/src/trajectory_optimization_node.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -22,6 +23,13 @@ namespace trajectory_optimization { namespace { using SteadyClock = std::chrono::steady_clock; +// state and control indices of the OCP (trajectory_optimization_ocp/constants.py) +constexpr int STATE_INDEX_S = 2; +constexpr int STATE_INDEX_V_T = 3; +constexpr int STATE_INDEX_A_T = 4; +constexpr int STATE_INDEX_PSI = 5; +constexpr int CONTROL_INDEX_J_T = 0; + double elapsedMilliseconds(const SteadyClock::time_point& start) { return std::chrono::duration(SteadyClock::now() - start).count(); } @@ -63,11 +71,16 @@ TrajectoryOptimizationNode::TrajectoryOptimizationNode(const std::string node_na "Run OCP once for each received reference trajectory (true) or on a timer (false)"); this->declareAndLoadParameter("cost_weights", cost_weights_, "Cost function weights"); this->declareAndLoadParameter("dynamic_weight", dynamic_weight_, "Dynamic weight alpha"); - this->declareAndLoadParameter("thw", thw_, "Desired time headway to front vehicle [s]; soft when object slacks are enabled"); + this->declareAndLoadParameter("thw", thw_, "Desired time headway to followed objects [s]; soft when object slacks are enabled"); this->declareAndLoadParameter("d_min_object_long", d_min_object_long_, - "Desired longitudinal object clearance [m]; soft when object slacks are enabled"); + "Desired distance to followed objects [m]; soft when object slacks are enabled"); this->declareAndLoadParameter("d_min_object_lat", d_min_object_lat_, - "Desired lateral object clearance [m]; soft when object slacks are enabled"); + "Desired lateral distance to passed objects of classes without an own value [m]; soft when " + "object slacks are enabled"); + this->declareAndLoadParameter("d_min_object_lat_classes", d_min_object_lat_classes_, + "Object classes (perception_msgs/ObjectClassification) with an own lateral distance"); + this->declareAndLoadParameter("d_min_object_lat_class_values", d_min_object_lat_class_values_, + "Desired lateral distance to passed objects per class in d_min_object_lat_classes [m]"); this->declareAndLoadParameter("d_min_boundary_lat", d_min_boundary_lat_, "Minimum distance to keep to boundary in lateral direction [m]"); this->declareAndLoadParameter("standstill_threshold", standstill_threshold_, @@ -335,7 +348,9 @@ void TrajectoryOptimizationNode::resetSolver() { } } -bool TrajectoryOptimizationNode::setInitialGuess(const std::vector& x_init, const rclcpp::Time& stamp) { +bool TrajectoryOptimizationNode::setInitialGuess(const std::vector& x_init, + const rclcpp::Time& stamp, + const std::vector* jerk) { constexpr double MAX_CONTROL_GUESS_AGE_FACTOR = 0.5; const int nx = *nlp_dims_->nx; const int nu = *nlp_dims_->nu; @@ -371,35 +386,81 @@ bool TrajectoryOptimizationNode::setInitialGuess(const std::vector& x_in } } } + if (jerk != nullptr) { + for (int stage = 0; stage < n_shots_; ++stage) controls[stage * nu + CONTROL_INDEX_J_T] = (*jerk)[stage]; + } ocp_nlp_out_set_values_to_zero(nlp_config_, nlp_dims_, nlp_out_); std::vector rollout_state = x_init; - std::vector intermediate_state(nx); - std::vector k1(nx), k2(nx), k3(nx), k4(nx); - const double integration_step = time_step / 4.0; for (int stage = 0; stage < n_shots_; ++stage) { - double* control = &controls[stage * nu]; + std::vector control(controls.begin() + stage * nu, controls.begin() + (stage + 1) * nu); ocp_nlp_out_set(nlp_config_, nlp_dims_, nlp_out_, nlp_in_, stage, "x", rollout_state.data()); - ocp_nlp_out_set(nlp_config_, nlp_dims_, nlp_out_, nlp_in_, stage, "u", control); - - // Match sim_method_num_stages=4 and sim_method_num_steps=4 from the generated OCP. - for (int integration = 0; integration < 4; ++integration) { - trajectory_optimization::acados_evaluate_dynamics(ocp_capsule_, stage, rollout_state.data(), control, k1.data()); - for (int i = 0; i < nx; ++i) intermediate_state[i] = rollout_state[i] + 0.5 * integration_step * k1[i]; - trajectory_optimization::acados_evaluate_dynamics(ocp_capsule_, stage, intermediate_state.data(), control, k2.data()); - for (int i = 0; i < nx; ++i) intermediate_state[i] = rollout_state[i] + 0.5 * integration_step * k2[i]; - trajectory_optimization::acados_evaluate_dynamics(ocp_capsule_, stage, intermediate_state.data(), control, k3.data()); - for (int i = 0; i < nx; ++i) intermediate_state[i] = rollout_state[i] + integration_step * k3[i]; - trajectory_optimization::acados_evaluate_dynamics(ocp_capsule_, stage, intermediate_state.data(), control, k4.data()); - for (int i = 0; i < nx; ++i) { - rollout_state[i] += integration_step / 6.0 * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]); - } - } + ocp_nlp_out_set(nlp_config_, nlp_dims_, nlp_out_, nlp_in_, stage, "u", control.data()); + integrateStage(stage, rollout_state, control); } ocp_nlp_out_set(nlp_config_, nlp_dims_, nlp_out_, nlp_in_, n_shots_, "x", rollout_state.data()); return true; } +void TrajectoryOptimizationNode::integrateStage(int stage, std::vector& state, std::vector& control) { + const int nx = *nlp_dims_->nx; + const double integration_step = optimization_horizon_ / n_shots_ / 4.0; + std::vector intermediate_state(nx); + std::vector k1(nx), k2(nx), k3(nx), k4(nx); + // Match sim_method_num_stages=4 and sim_method_num_steps=4 from the generated OCP. + for (int integration = 0; integration < 4; ++integration) { + trajectory_optimization::acados_evaluate_dynamics(ocp_capsule_, stage, state.data(), control.data(), k1.data()); + for (int i = 0; i < nx; ++i) intermediate_state[i] = state[i] + 0.5 * integration_step * k1[i]; + trajectory_optimization::acados_evaluate_dynamics(ocp_capsule_, stage, intermediate_state.data(), control.data(), k2.data()); + for (int i = 0; i < nx; ++i) intermediate_state[i] = state[i] + 0.5 * integration_step * k2[i]; + trajectory_optimization::acados_evaluate_dynamics(ocp_capsule_, stage, intermediate_state.data(), control.data(), k3.data()); + for (int i = 0; i < nx; ++i) intermediate_state[i] = state[i] + integration_step * k3[i]; + trajectory_optimization::acados_evaluate_dynamics(ocp_capsule_, stage, intermediate_state.data(), control.data(), k4.data()); + for (int i = 0; i < nx; ++i) { + state[i] += integration_step / 6.0 * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]); + } + } +} + +TrajectoryOptimizationNode::BrakingProfile TrajectoryOptimizationNode::brakingProfile(const std::vector& x_init) { + constexpr double STANDSTILL_SPEED = 1e-3; // [m/s] numerical standstill; the braking profile then releases the deceleration + + // bound of a state or control entry in the generated OCP + const auto bounds = [&](int stage, const char* index_field, const char* lower_field, const char* upper_field, int index) { + const int n = ocp_nlp_dims_get_from_attr(nlp_config_, nlp_dims_, nlp_out_, stage, lower_field); + std::vector indices(n); + std::vector lower(n), upper(n); + ocp_nlp_constraints_model_get(nlp_config_, nlp_dims_, nlp_in_, stage, index_field, indices.data()); + ocp_nlp_constraints_model_get(nlp_config_, nlp_dims_, nlp_in_, stage, lower_field, lower.data()); + ocp_nlp_constraints_model_get(nlp_config_, nlp_dims_, nlp_in_, stage, upper_field, upper.data()); + for (int i = 0; i < n; ++i) { + if (indices[i] == index) return std::make_pair(lower[i], upper[i]); + } + return std::make_pair(-std::numeric_limits::infinity(), std::numeric_limits::infinity()); + }; + const auto [jerk_min, jerk_max] = bounds(0, "idxbu", "lbu", "ubu", CONTROL_INDEX_J_T); + // stage 0 fixes the initial state; the acceleration bound applies from stage 1 + const double acceleration_min = bounds(1, "idxbx", "lbx", "ubx", STATE_INDEX_A_T).first; + + const double dt = optimization_horizon_ / n_shots_; + BrakingProfile profile; + std::vector state = x_init; + std::vector control(*nlp_dims_->nu, 0.0); + profile.travel.push_back(0.0); + profile.speed.push_back(std::max(state[STATE_INDEX_V_T], 0.0)); + for (int stage = 0; stage < n_shots_; ++stage) { + const double acceleration = state[STATE_INDEX_A_T]; + control[CONTROL_INDEX_J_T] = state[STATE_INDEX_V_T] > STANDSTILL_SPEED + ? std::max(jerk_min, (acceleration_min - acceleration) / dt) + : std::min(jerk_max, std::max(-acceleration, 0.0) / dt); + integrateStage(stage, state, control); + profile.jerk.push_back(control[CONTROL_INDEX_J_T]); + profile.travel.push_back(state[STATE_INDEX_S] - x_init[STATE_INDEX_S]); + profile.speed.push_back(std::max(state[STATE_INDEX_V_T], 0.0)); + } + return profile; +} + void TrajectoryOptimizationNode::planningCycle() { const auto cycle_start = SteadyClock::now(); if (debug_viz_) viz_object_boxes_.clear(); @@ -477,12 +538,15 @@ void TrajectoryOptimizationNode::planningCycle() { ocp_nlp_constraints_model_set(nlp_config_, nlp_dims_, nlp_in_, nlp_out_, 0, "ubx", x_init.data()); // update inputs to the ocp; skip planning cycle if update fails - if (!updateOcpInputs(ego_data_, object_list_, route_, reference_trajectory_)) { + const BrakingProfile braking = brakingProfile(x_init); + if (!updateOcpInputs(ego_data_, object_list_, route_, reference_trajectory_, x_init, braking)) { RCLCPP_WARN(this->get_logger(), "Failed to update inputs. Skipping planning cycle."); return; } - if (!setInitialGuess(x_init, rclcpp::Time(ego_data_.header.stamp))) { + // start from the braking profile if d_min_object_long to the followed object is reachable only with full braking + const bool brake_first = follow_pass_result_.brake_needed; + if (!setInitialGuess(x_init, rclcpp::Time(ego_data_.header.stamp), brake_first ? &braking.jerk : nullptr)) { control_guess_.clear(); return; } @@ -528,6 +592,19 @@ void TrajectoryOptimizationNode::planningCycle() { setSolverTimeout(constrained_solve_timeout_ms_); const auto constrained_solve_start = SteadyClock::now(); primal_feasible = solveAndValidate(metrics, finite_solution); + // With a follow distance, retry once from the other initial guess (braking profile or warm start) within the remaining + // time of the constrained solve. + const double remaining_ms = constrained_solve_timeout_ms_ - elapsedMilliseconds(constrained_solve_start); + if (!primal_feasible && follow_pass_result_.follow_active && (constrained_solve_timeout_ms_ <= 0.0 || remaining_ms > 0.0)) { + RCLCPP_DEBUG(get_logger(), "Retrying the constrained solve from the %s.", brake_first ? "warm start" : "braking profile"); + resetSolver(); + if (!setInitialGuess(x_init, rclcpp::Time(ego_data_.header.stamp), brake_first ? nullptr : &braking.jerk)) { + control_guess_.clear(); + return; + } + setSolverTimeout(constrained_solve_timeout_ms_ <= 0.0 ? 0.0 : remaining_ms); + primal_feasible = solveAndValidate(metrics, finite_solution); + } metrics.constrained_solve_wall_ms = elapsedMilliseconds(constrained_solve_start); metrics.solve_wall_ms = elapsedMilliseconds(solve_start); @@ -597,7 +674,9 @@ void TrajectoryOptimizationNode::planningCycle() { bool TrajectoryOptimizationNode::updateOcpInputs(const perception_msgs::msg::EgoData& ego_data, const perception_msgs::msg::ObjectList& object_list, const route_planning_msgs::msg::Route& route, - const trajectory_planning_msgs::msg::Trajectory& reference_trajectory) { + const trajectory_planning_msgs::msg::Trajectory& reference_trajectory, + const std::vector& x_init, + const BrakingProfile& braking) { // transform inputs to target base_link frame trajectory_planning_msgs::msg::Trajectory tf_reference_trajectory; perception_msgs::msg::ObjectList tf_object_list; @@ -634,8 +713,53 @@ bool TrajectoryOptimizationNode::updateOcpInputs(const perception_msgs::msg::Ego // update ocp parameters try { - this->setOcpGlobalParameters(cost_weights_, tf_reference_trajectory, tf_route); - this->setOcpParameters(ego_data, tf_object_list); + // Reference samples as passed to the OCP. A shorter reference repeats its final sample; infinity padding can propagate + // NaNs through closest-point calculations. The suggested lane is never wider than the active boundaries; without lane + // information, the active boundaries remain. + const auto boundary_distances = normalBoundaryDistance(tf_reference_trajectory, tf_route, consider_boundaries_); + const auto lane_distances = normalBoundaryDistance(tf_reference_trajectory, tf_route, CONSIDER_BOUNDARIES::SUGGESTED_LANE); + const int n_samples = trajectory_planning_msgs::trajectory_access::getSamplePointSize(tf_reference_trajectory); + FollowPass::Reference reference; + std::vector reference_v; + for (int i = 0; i < p_ref_path_shape_[0]; ++i) { + const int sample = std::min(i, n_samples - 1); + reference.psi.push_back(trajectory_planning_msgs::trajectory_access::getTheta(tf_reference_trajectory, sample)); + reference.x.push_back(trajectory_planning_msgs::trajectory_access::getX(tf_reference_trajectory, sample)); + reference.y.push_back(trajectory_planning_msgs::trajectory_access::getY(tf_reference_trajectory, sample)); + reference_v.push_back(trajectory_planning_msgs::trajectory_access::getV(tf_reference_trajectory, sample)); + const auto& [boundary_left, boundary_right] = boundary_distances[sample]; + reference.boundary_distances.emplace_back(boundary_left, boundary_right); + reference.lane_distances.emplace_back(std::min(lane_distances[sample].first, boundary_left), + std::min(lane_distances[sample].second, boundary_right)); + } + + // follow or pass every object prediction + std::vector slots; + const auto object_boxes = predictObjectBoxes(ego_data, tf_object_list, slots); + const auto model = modelConstants(model_name_); + if (!model) throw std::runtime_error("Unknown model " + model_name_); + FollowPass::Params params; + params.thw = thw_; + params.d_min_object_long = d_min_object_long_; + params.d_min_object_lat = d_min_object_lat_; + params.d_min_object_collision = model->d_min_object_collision; + params.d_min_boundary_lat = d_min_boundary_lat_; + if (d_min_object_lat_classes_.size() != d_min_object_lat_class_values_.size()) { + RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 10000, + "d_min_object_lat_classes and d_min_object_lat_class_values differ in length; using the common part."); + } + for (size_t i = 0; i < std::min(d_min_object_lat_classes_.size(), d_min_object_lat_class_values_.size()); ++i) { + params.class_lateral_margins[static_cast(d_min_object_lat_classes_[i])] = d_min_object_lat_class_values_[i]; + } + params.ego_half_length = 0.5 * model->length; + params.ego_half_width = 0.5 * model->width; + params.ego_offset_to_geometric_center = model->offset_to_geometric_center; + follow_pass_result_ = + follow_pass_.decide(reference, object_boxes, object_constraints_active_ ? slots : std::vector{}, + {x_init[0], x_init[1], x_init[STATE_INDEX_PSI]}, braking.travel, braking.speed, params); + + this->setOcpGlobalParameters(cost_weights_, reference, reference_v, follow_pass_result_); + this->setOcpParameters(object_boxes, follow_pass_result_); } catch (const std::exception& e) { RCLCPP_ERROR(this->get_logger(), "Exception while setting OCP parameters: %s", e.what()); return false; @@ -645,8 +769,9 @@ bool TrajectoryOptimizationNode::updateOcpInputs(const perception_msgs::msg::Ego } void TrajectoryOptimizationNode::setOcpGlobalParameters(const std::vector& cost_weights, - const trajectory_planning_msgs::msg::Trajectory& reference_trajectory, - const route_planning_msgs::msg::Route& route) { + const FollowPass::Reference& reference, + const std::vector& reference_v, + const FollowPass::Result& follow_pass) { const auto start_time = std::chrono::steady_clock::now(); std::vector global_params; @@ -665,30 +790,11 @@ void TrajectoryOptimizationNode::setOcpGlobalParameters(const std::vector(p_ref_path_shape_[0] * p_ref_path_shape_[1]); - std::vector> boundary_distances = normalBoundaryDistance(reference_trajectory, route); - // fill ref vector for ocp -> psi, x, y, v, d_bound_left, d_bound_right - std::vector ref; - for (int i = 0; i < trajectory_planning_msgs::trajectory_access::getSamplePointSize(reference_trajectory); ++i) { - ref.push_back(trajectory_planning_msgs::trajectory_access::getTheta(reference_trajectory, i)); - ref.push_back(trajectory_planning_msgs::trajectory_access::getX(reference_trajectory, i)); - ref.push_back(trajectory_planning_msgs::trajectory_access::getY(reference_trajectory, i)); - ref.push_back(trajectory_planning_msgs::trajectory_access::getV(reference_trajectory, i)); - ref.push_back(boundary_distances[i].first); // left boundary distance - ref.push_back(boundary_distances[i].second); // right boundary distance - } - if (ref.size() >= n_ref_states) { - global_params.insert(global_params.end(), ref.begin(), - ref.begin() + static_cast::difference_type>(n_ref_states)); - } else { - // Repeat the final valid state. Infinity padding can propagate NaNs through closest-point calculations. - global_params.insert(global_params.end(), ref.begin(), ref.end()); - const size_t state_width = static_cast(p_ref_path_shape_[1]); - while (global_params.size() < expected_cost_weights_size + 4 + n_ref_states) { - global_params.insert(global_params.end(), ref.end() - static_cast::difference_type>(state_width), - ref.end()); - } + // reference path -> psi, x, y, v, d_bound_left, d_bound_right, d_object_left, d_object_right, s + for (size_t i = 0; i < reference.x.size(); ++i) { + global_params.insert(global_params.end(), {reference.psi[i], reference.x[i], reference.y[i], reference_v[i], + reference.boundary_distances[i].first, reference.boundary_distances[i].second, + follow_pass.d_object_left[i], follow_pass.d_object_right[i], follow_pass.s[i]}); } if (global_params.size() != static_cast(nlp_dims_->np_global)) { @@ -705,10 +811,10 @@ void TrajectoryOptimizationNode::setOcpGlobalParameters(const std::vectorget_logger(), "setOcpGlobalParameters duration: %.3f ms", elapsed_ms); } -void TrajectoryOptimizationNode::setOcpParameters(const perception_msgs::msg::EgoData& ego_data, - const perception_msgs::msg::ObjectList& object_list) { - const auto start_time = std::chrono::steady_clock::now(); - +std::vector> TrajectoryOptimizationNode::predictObjectBoxes( + const perception_msgs::msg::EgoData& ego_data, + const perception_msgs::msg::ObjectList& object_list, + std::vector& slots) { // prepare object predictions struct PredictionData { std::vector time; @@ -751,39 +857,15 @@ void TrajectoryOptimizationNode::setOcpParameters(const perception_msgs::msg::Eg object_constraints_active_ = consider_objects_ != CONSIDER_OBJECTS::NO_OBJECTS && !object_list.objects.empty(); constexpr double MIN_HALF_EXTENT = 0.05; - // loop over shooting intervals + // one slot per object prediction in object order; the remaining slots stay inactive + const size_t n_slots = static_cast(p_objects_shape_[0]); + slots.assign(n_slots, FollowPass::Slot{}); + std::vector> object_boxes( + n_shots_ + 1, std::vector(n_slots, {0.0, 0.0, 0.0, MIN_HALF_EXTENT, MIN_HALF_EXTENT, false})); const double dt = optimization_horizon_ / n_shots_; - double floating_dynamic_weight = 1.0; for (int stage = 0; stage <= n_shots_; ++stage) { - // dynamic weight - int idx = 0; - int parameter_count = static_cast(p_dynamic_weight_shape_[0] * p_dynamic_weight_shape_[1]); - std::vector dynamic_weight_indices{idx}; - int status = trajectory_optimization::acados_update_params_sparse(ocp_capsule_, stage, dynamic_weight_indices.data(), - &floating_dynamic_weight, parameter_count); - if (status != ACADOS_SUCCESS) { - throw std::runtime_error("acados dynamic-weight update failed with status " + std::to_string(status)); - } - floating_dynamic_weight *= dynamic_weight_; - - // constraint activation - idx += parameter_count; - parameter_count = static_cast(p_constraint_activation_shape_[0] * p_constraint_activation_shape_[1]); - std::array constraint_activation_indices{idx, idx + 1}; - std::array constraint_activation{object_constraints_active_ ? 1.0 : 0.0, - consider_boundaries_ != CONSIDER_BOUNDARIES::NO_BOUNDS ? 1.0 : 0.0}; - status = trajectory_optimization::acados_update_params_sparse(ocp_capsule_, stage, constraint_activation_indices.data(), - constraint_activation.data(), parameter_count); - if (status != ACADOS_SUCCESS) { - throw std::runtime_error("acados constraint-activation update failed with status " + std::to_string(status)); - } - - // objects - idx += parameter_count; - parameter_count = static_cast(p_objects_shape_[0] * p_objects_shape_[1]); - std::vector object_boxes; - object_boxes.reserve(parameter_count); - for (size_t object_index = 0; object_index < object_list.objects.size(); ++object_index) { + size_t slot = 0; + for (size_t object_index = 0; object_index < object_list.objects.size() && slot < n_slots; ++object_index) { const auto& object = object_list.objects[object_index]; std::vector> target_states; if (!object_predictions[object_index].empty()) { @@ -805,36 +887,85 @@ void TrajectoryOptimizationNode::setOcpParameters(const perception_msgs::msg::Eg const double offset_lat = object.state.reference_point.translation_to_geometric_center.y; const double half_length = std::max(MIN_HALF_EXTENT, 0.5 * perception_msgs::object_access::getLength(object)); const double half_width = std::max(MIN_HALF_EXTENT, 0.5 * perception_msgs::object_access::getWidth(object)); - for (const auto& state : target_states) { + for (size_t prediction = 0; prediction < target_states.size() && slot < n_slots; ++prediction, ++slot) { + const auto& state = target_states[prediction]; // ensure that the object position represents its geometric center const double cos_yaw = std::cos(state[2]); const double sin_yaw = std::sin(state[2]); const double center_x = state[0] + offset_long * cos_yaw - offset_lat * sin_yaw; const double center_y = state[1] + offset_long * sin_yaw + offset_lat * cos_yaw; - object_boxes.insert(object_boxes.end(), {center_x, center_y, state[2], half_length, half_width, 1.0}); - if (object_boxes.size() >= static_cast(parameter_count)) { - object_boxes.resize(parameter_count); - break; - } + object_boxes[stage][slot] = {center_x, center_y, state[2], half_length, half_width, true}; + slots[slot] = {object.id, prediction, perception_msgs::object_access::getClassWithHighestProbability(object).type}; } - if (object_boxes.size() >= static_cast(parameter_count)) break; } - // fill remaining object slots with inactive boxes - while (object_boxes.size() < static_cast(parameter_count)) { - object_boxes.insert(object_boxes.end(), {0.0, 0.0, 0.0, MIN_HALF_EXTENT, MIN_HALF_EXTENT, 0.0}); + } + return object_boxes; +} + +void TrajectoryOptimizationNode::setOcpParameters(const std::vector>& object_boxes, + const FollowPass::Result& follow_pass) { + const auto start_time = std::chrono::steady_clock::now(); + + // loop over shooting intervals + double floating_dynamic_weight = 1.0; + for (int stage = 0; stage <= n_shots_; ++stage) { + // dynamic weight + int idx = 0; + int parameter_count = static_cast(p_dynamic_weight_shape_[0] * p_dynamic_weight_shape_[1]); + std::vector dynamic_weight_indices{idx}; + int status = trajectory_optimization::acados_update_params_sparse(ocp_capsule_, stage, dynamic_weight_indices.data(), + &floating_dynamic_weight, parameter_count); + if (status != ACADOS_SUCCESS) { + throw std::runtime_error("acados dynamic-weight update failed with status " + std::to_string(status)); + } + floating_dynamic_weight *= dynamic_weight_; + + // constraint activation + idx += parameter_count; + parameter_count = static_cast(p_constraint_activation_shape_[0] * p_constraint_activation_shape_[1]); + std::array constraint_activation_indices{idx, idx + 1}; + std::array constraint_activation{object_constraints_active_ ? 1.0 : 0.0, + consider_boundaries_ != CONSIDER_BOUNDARIES::NO_BOUNDS ? 1.0 : 0.0}; + status = trajectory_optimization::acados_update_params_sparse(ocp_capsule_, stage, constraint_activation_indices.data(), + constraint_activation.data(), parameter_count); + if (status != ACADOS_SUCCESS) { + throw std::runtime_error("acados constraint-activation update failed with status " + std::to_string(status)); + } + + // objects; the slot replaced by the follow distance gets no box constraint at this stage + idx += parameter_count; + parameter_count = static_cast(p_objects_shape_[0] * p_objects_shape_[1]); + std::vector object_params; + object_params.reserve(parameter_count); + for (size_t slot = 0; slot < object_boxes[stage].size(); ++slot) { + const auto& box = object_boxes[stage][slot]; + const bool active = box.active && static_cast(slot) != follow_pass.follow_slot[stage]; + object_params.insert(object_params.end(), {box.x, box.y, box.yaw, box.half_length, box.half_width, active ? 1.0 : 0.0}); } - if (debug_viz_) viz_object_boxes_.insert(viz_object_boxes_.end(), object_boxes.begin(), object_boxes.end()); + if (debug_viz_) viz_object_boxes_.insert(viz_object_boxes_.end(), object_params.begin(), object_params.end()); std::vector object_indices(parameter_count); std::iota(object_indices.begin(), object_indices.end(), idx); - status = trajectory_optimization::acados_update_params_sparse(ocp_capsule_, stage, object_indices.data(), object_boxes.data(), - parameter_count); + status = trajectory_optimization::acados_update_params_sparse(ocp_capsule_, stage, object_indices.data(), + object_params.data(), parameter_count); if (status != ACADOS_SUCCESS) { throw std::runtime_error("acados object-box update failed with status " + std::to_string(status)); } + + // follow distance + idx += parameter_count; + parameter_count = static_cast(p_follow_shape_[0] * p_follow_shape_[1]); + std::vector follow_indices(parameter_count); + std::iota(follow_indices.begin(), follow_indices.end(), idx); + std::array follow = follow_pass.follow[stage]; + status = trajectory_optimization::acados_update_params_sparse(ocp_capsule_, stage, follow_indices.data(), follow.data(), + parameter_count); + if (status != ACADOS_SUCCESS) { + throw std::runtime_error("acados follow update failed with status " + std::to_string(status)); + } } const auto elapsed_ms = std::chrono::duration(std::chrono::steady_clock::now() - start_time).count(); - RCLCPP_DEBUG(get_logger(), "setOcpParameters object-box duration: %.3f ms", elapsed_ms); + RCLCPP_DEBUG(get_logger(), "setOcpParameters duration: %.3f ms", elapsed_ms); } } // namespace trajectory_optimization diff --git a/trajectory_optimization/src/utils.cpp b/trajectory_optimization/src/utils.cpp index d780856..0d82f04 100644 --- a/trajectory_optimization/src/utils.cpp +++ b/trajectory_optimization/src/utils.cpp @@ -110,7 +110,9 @@ void TrajectoryOptimizationNode::keepNClosestObjects(perception_msgs::msg::Objec } std::vector> TrajectoryOptimizationNode::normalBoundaryDistance( - const trajectory_planning_msgs::msg::Trajectory& reference_trajectory, const route_planning_msgs::msg::Route& route) { + const trajectory_planning_msgs::msg::Trajectory& reference_trajectory, + const route_planning_msgs::msg::Route& route, + uint8_t consider_boundaries) { const double NO_BOUNDARY_DISTANCE = 1e6; // finite sentinel avoids NaNs during reference-path interpolation constexpr double MAX_ROUTE_S_DIFFERENCE = 20.0; constexpr double LOOK_BEHIND_REMAINING_ROUTE_S = 2.0; @@ -130,7 +132,7 @@ std::vector> TrajectoryOptimizationNode::normalBoundar const int ref_sample_size = trajectory_planning_msgs::trajectory_access::getSamplePointSize(reference_trajectory); if (route_elements.empty()) { - if (consider_boundaries_ != CONSIDER_BOUNDARIES::NO_BOUNDS) { + if (consider_boundaries != CONSIDER_BOUNDARIES::NO_BOUNDS) { RCLCPP_WARN(get_logger(), "Remaining route is empty. Do not constrain boundaries."); } for (int i = 0; i < ref_sample_size; ++i) { @@ -158,7 +160,7 @@ std::vector> TrajectoryOptimizationNode::normalBoundar for (const auto& route_element : route_elements) { if (route_element.is_enriched) { - if (consider_boundaries_ == CONSIDER_BOUNDARIES::SUGGESTED_LANE) { + if (consider_boundaries == CONSIDER_BOUNDARIES::SUGGESTED_LANE) { route_planning_msgs::msg::LaneElement suggested_lane = route_planning_msgs::route_access::getSuggestedLaneElement(route_element); boundaries.left_boundary_points.emplace_back(suggested_lane.left_boundary.point.x, suggested_lane.left_boundary.point.y); @@ -166,7 +168,7 @@ std::vector> TrajectoryOptimizationNode::normalBoundar suggested_lane.right_boundary.point.y); boundaries.left_boundary_route_s.push_back(route_element.s); boundaries.right_boundary_route_s.push_back(route_element.s); - } else if (consider_boundaries_ == CONSIDER_BOUNDARIES::INCLUDING_ADJACENT) { + } else if (consider_boundaries == CONSIDER_BOUNDARIES::INCLUDING_ADJACENT) { const auto& lane_elements = route_element.lane_elements; if (!lane_elements.empty()) { boundaries.left_boundary_points.emplace_back(lane_elements.front().left_boundary.point.x, @@ -176,7 +178,7 @@ std::vector> TrajectoryOptimizationNode::normalBoundar boundaries.left_boundary_route_s.push_back(route_element.s); boundaries.right_boundary_route_s.push_back(route_element.s); } - } else if (consider_boundaries_ == CONSIDER_BOUNDARIES::DRIVABLE_SPACE) { + } else if (consider_boundaries == CONSIDER_BOUNDARIES::DRIVABLE_SPACE) { boundaries.left_boundary_points.emplace_back(route_element.left_boundary.x, route_element.left_boundary.y); boundaries.right_boundary_points.emplace_back(route_element.right_boundary.x, route_element.right_boundary.y); boundaries.left_boundary_route_s.push_back(route_element.s); @@ -259,7 +261,7 @@ std::vector> TrajectoryOptimizationNode::normalBoundar "No boundary intersection found for trajectory point %d. Do not constrain boundaries at this point.", i); } } - if (debug_viz_) { + if (debug_viz_ && consider_boundaries == consider_boundaries_) { vizBoundaryPoints(boundaries.left_boundary_intersections, boundaries.right_boundary_intersections); } @@ -330,6 +332,15 @@ void TrajectoryOptimizationNode::vizObjectBoxes(const std::vector& objec } object_marker_pub_->publish(marker_array); } + +std::optional TrajectoryOptimizationNode::modelConstants( + const std::string& model_name) { + // vehicle geometry and hard object distance based on model name (must match the OCP configuration) + if (model_name == "karl") return ModelConstants{5.173, 1.94, {1.4895, 0.0}, 0.10}; + if (model_name == "shuttle") return ModelConstants{4.97, 2.12, {0.0, 0.0}, 0.10}; + return std::nullopt; +} + void TrajectoryOptimizationNode::vizEgoBoxes(const std::vector& x_trajectory, const std::string& model_name) { visualization_msgs::msg::MarkerArray marker_array; if (x_trajectory.empty()) { @@ -340,23 +351,14 @@ void TrajectoryOptimizationNode::vizEgoBoxes(const std::vector& x_trajec return; } - double length = 0.0; - double width = 0.0; - std::array offset_to_geometric_center{}; - - // define vehicle geometry based on model name (should match the OCP definition) - if (model_name == "karl") { - length = 5.173; - width = 1.94; - offset_to_geometric_center = {1.4895, 0.0}; - } else if (model_name == "shuttle") { - length = 4.97; - width = 2.12; - offset_to_geometric_center = {0.0, 0.0}; - } else { + const auto model = modelConstants(model_name); + if (!model) { RCLCPP_WARN(get_logger(), "Unknown model '%s'. Could not visualize ego boxes.", model_name.c_str()); return; } + const double length = model->length; + const double width = model->width; + const std::array offset_to_geometric_center = model->offset_to_geometric_center; const int state_dim = *nlp_dims_->nx; for (int stage = 0; stage <= n_shots_; ++stage) { @@ -429,7 +431,6 @@ bool TrajectoryOptimizationNode::solveAndValidate(PerformanceMetrics& metrics, b const bool finite_slacks = usable_status && PerformanceLogger::collectSlackStatistics(metrics, nlp_config_, nlp_dims_, nlp_in_, nlp_out_, - static_cast(p_objects_shape_[0]), performance_logger_ != nullptr || verbose_); finite_solution = usable_status && finite_slacks && std::isfinite(metrics.cost_value) && std::isfinite(metrics.res_eq) && std::isfinite(metrics.res_ineq) && diff --git a/trajectory_optimization_ocp/README.md b/trajectory_optimization_ocp/README.md index 18780cb..e2c3d80 100644 --- a/trajectory_optimization_ocp/README.md +++ b/trajectory_optimization_ocp/README.md @@ -38,21 +38,30 @@ Model/config parameterizations are defined in: ### Object constraints -Both vehicle OCPs separate desired clearance from physical collision avoidance: - -- Desired clearance: the ego box expanded by THW/`d_min_object_long` to the front, - `d_min_object_lat` to the sides and a small rear margin. `enable_object_slack` softens - this block using `object_slack_weights`; without slacks it stays hard. -- Physical separation: the unexpanded ego and object boxes must be separated by the build - parameter `d_min_object_collision` (default 0.10 m). This block follows the clearance - block and never receives slacks. - -Both blocks use the conservative smooth SAT margin and apply at intermediate and terminal -nodes, not retroactively at the fixed initial state. Node constraints alone do not guarantee -collision avoidance between nodes or under incorrect predictions. `thw`, `d_min_object_long` -and `d_min_object_lat` are runtime parameters; changing `d_min_object_collision` or the slack -weights requires rebuilding the generated solver. Generation errors fail the build instead of -reusing stale solver artifacts. +Both vehicle OCPs separate the desired clearance from physical collision avoidance. The node +decides per object prediction whether the ego follows it or passes it (see +[`trajectory_optimization`](../trajectory_optimization/README.md#following-and-passing-objects)): + +- Passed objects: per reference point, `d_object_left`/`d_object_right` bound the lateral + offset of each ego corner from the reference path. +- Followed object: per stage, `p_follow = [s_rear, active, relax]` gives the arc length of + the rear of the followed object along the reference path. Both front corners stay behind + it by `d_min_object_long` and by `thw * v`; the corner arc length is linearised at the + matched reference point, so the distance follows the path in curves. `relax` lowers both + requirements by the part that full braking cannot reach. +- Physical separation: the ego and object boxes must be separated by the build parameter + `d_min_object_collision` (default 0.10 m, conservative smooth SAT margin). The followed + object is limited by its arc-length distance instead; the node disables its SAT slot at + that stage. This block never receives slacks. + +`enable_object_slack` softens the passed-object bounds and the follow distance with +`object_slack_weights`. The thw rows have no linear and a quadratic weight of +`w_lat / c_lat^2`, so a missing metre of time-headway distance costs as much as a metre of +lateral offset. Constraints apply at intermediate and terminal nodes, not retroactively at +the fixed initial state. Node constraints alone do not guarantee collision avoidance between +nodes or under incorrect predictions. `thw` and `d_min_object_long` are runtime parameters; +changing `d_min_object_collision` or the slack weights requires rebuilding the generated +solver. Generation errors fail the build instead of reusing stale solver artifacts. ### Forward-only dynamics diff --git a/trajectory_optimization_ocp/trajectory_optimization_ocp/config/karl_params.yml b/trajectory_optimization_ocp/trajectory_optimization_ocp/config/karl_params.yml index 36cf174..bc7fa25 100644 --- a/trajectory_optimization_ocp/trajectory_optimization_ocp/config/karl_params.yml +++ b/trajectory_optimization_ocp/trajectory_optimization_ocp/config/karl_params.yml @@ -21,7 +21,7 @@ acceleration_n_max: 3.0 # max. absolute normal acceleration [m/s²] alpha_max: 0.7330382858 # max. absolute steering rate [rad/s] (42°/s) jerk_min: -5.0 # max. negative tangential jerk [m/s²] jerk_max: 2.0 # max. positive tangential jerk [m/s²] -d_min_object_collision: 0.10 # hard minimum separation of the physical OBBs [m]; requires solver rebuild +d_min_object_collision: 0.10 # hard minimum separation of the physical OBBs [m]; requires solver rebuild; also in modelConstants() of the node ### cost scaling factors c_lat: 0.5 # distance to scale the lateral deviation costs [m] @@ -42,20 +42,25 @@ boundary_slack_weights: # scalar or list (length 2) quadratic_lower: 100.0 quadratic_upper: 100.0 enable_object_slack: True # soften desired THW/lateral clearance; physical separation stays hard -object_slack_weights: # scalar or list (length n_objects) - linear_lower: 50.0 - linear_upper: 50.0 - quadratic_lower: 500.0 - quadratic_upper: 500.0 +object_slack_weights: # scalar or list (length 8): bounds of passed objects [front left, rear left, + # front right, rear right], then per front corner [d_min_object_long, thw] + # thw rows: no linear term and quadratic = w_lat / c_lat^2 (w_lat = 0.1 from the node parameters), so a missing metre + # of time-headway distance costs as much as a metre of lateral offset (both front-corner rows together) + linear_lower: [50.0, 50.0, 50.0, 50.0, 50.0, 0.0, 50.0, 0.0] + linear_upper: [50.0, 50.0, 50.0, 50.0, 50.0, 0.0, 50.0, 0.0] + quadratic_lower: [500.0, 500.0, 500.0, 500.0, 500.0, 0.4, 500.0, 0.4] + quadratic_upper: [500.0, 500.0, 500.0, 500.0, 500.0, 0.4, 500.0, 0.4] ### parameter vector structure (stage-wise parameters) -# [dyn_weight (1), constraint_activation (2), objects] +# [dyn_weight (1), constraint_activation (2), objects, follow] p_dynamic_weight_shape: [1, 1] # one value (also used in ROS node) p_constraint_activation_shape: [2, 1] # stage-wise [objects, boundaries] flags for sparse solve-phase toggling p_objects_shape: [30, 6] # nObjects x [x, y, yaw, half_length, half_width, active] +p_follow_shape: [3, 1] # [s_rear, active, relax]: arc length of the rear of the followed object along the reference path + # and the part of max(d_min_object_long, thw * v) that full braking cannot reach (also used in ROS node) ### global parameter vector structure (constant over the horizon) # [cost_weights (12), cost_params (4), ref_path] p_cost_weights_shape: [12, 1] # nWeights x weightDim (also used in ROS node) p_cost_params_shape: [4, 1] # [thw, d_min_object_long, d_min_object_lat, d_min_boundary_lat] x nCostParamsDim (also used in ROS node) -p_ref_path_shape: [51, 6] # nStates x [psi, x, y, v, d_bound_left, d_bound_right] (also used in ROS node) +p_ref_path_shape: [51, 9] # nStates x [psi, x, y, v, d_bound_left, d_bound_right, d_object_left, d_object_right, s] (also used in ROS node) diff --git a/trajectory_optimization_ocp/trajectory_optimization_ocp/config/shuttle_params.yml b/trajectory_optimization_ocp/trajectory_optimization_ocp/config/shuttle_params.yml index 97ac7df..c05f393 100644 --- a/trajectory_optimization_ocp/trajectory_optimization_ocp/config/shuttle_params.yml +++ b/trajectory_optimization_ocp/trajectory_optimization_ocp/config/shuttle_params.yml @@ -24,7 +24,7 @@ acceleration_t_max: 3.5 # max. positive tangential acceleration [m/s² acceleration_n_max: 8.0 # max. absolute normal acceleration [m/s²] jerk_min: -4.0 # max. negative tangential jerk [m/s²] jerk_max: 4.0 # max. positive tangential jerk [m/s³] -d_min_object_collision: 0.10 # hard minimum separation of the physical OBBs [m]; requires solver rebuild +d_min_object_collision: 0.10 # hard minimum separation of the physical OBBs [m]; requires solver rebuild; also in modelConstants() of the node # constraint on front and rear steering angle # none (default): no constraint, ICR (instantaneous center of rotation) is free to move # anti-phase: ICR is restricted to the y-axis in the vehicles center of gravity frame -> achieves minimum turning radius @@ -50,20 +50,25 @@ boundary_slack_weights: # scalar or list (length 2) quadratic_lower: 100.0 quadratic_upper: 100.0 enable_object_slack: True # soften desired THW/lateral clearance; physical separation stays hard -object_slack_weights: # scalar or list (length n_objects) - linear_lower: 50.0 - linear_upper: 50.0 - quadratic_lower: 500.0 - quadratic_upper: 500.0 +object_slack_weights: # scalar or list (length 8): bounds of passed objects [front left, rear left, + # front right, rear right], then per front corner [d_min_object_long, thw] + # thw rows: no linear term and quadratic = w_lat / c_lat^2 (w_lat = 5.0 from the node parameters), so a missing metre + # of time-headway distance costs as much as a metre of lateral offset (both front-corner rows together) + linear_lower: [50.0, 50.0, 50.0, 50.0, 50.0, 0.0, 50.0, 0.0] + linear_upper: [50.0, 50.0, 50.0, 50.0, 50.0, 0.0, 50.0, 0.0] + quadratic_lower: [500.0, 500.0, 500.0, 500.0, 500.0, 20.0, 500.0, 20.0] + quadratic_upper: [500.0, 500.0, 500.0, 500.0, 500.0, 20.0, 500.0, 20.0] ### parameter vector structure (stage-wise parameters) -# [dyn_weight (1), constraint_activation (2), objects] +# [dyn_weight (1), constraint_activation (2), objects, follow] p_dynamic_weight_shape: [1, 1] # one value (also used in ROS node) p_constraint_activation_shape: [2, 1] # stage-wise [objects, boundaries] flags for sparse solve-phase toggling p_objects_shape: [30, 6] # nObjects x [x, y, yaw, half_length, half_width, active] +p_follow_shape: [3, 1] # [s_rear, active, relax]: arc length of the rear of the followed object along the reference path + # and the part of max(d_min_object_long, thw * v) that full braking cannot reach (also used in ROS node) ### global parameter vector structure (constant over the horizon) # [cost_weights (12), cost_params (4), ref_path] p_cost_weights_shape: [12, 1] # nWeights x weightDim (also used in ROS node) p_cost_params_shape: [4, 1] # [thw, d_min_object_long, d_min_object_lat, d_min_boundary_lat] x nCostParamsDim (also used in ROS node) -p_ref_path_shape: [51, 6] # nStates x [psi, x, y, v, d_bound_left, d_bound_right] (also used in ROS node) +p_ref_path_shape: [51, 9] # nStates x [psi, x, y, v, d_bound_left, d_bound_right, d_object_left, d_object_right, s] (also used in ROS node) diff --git a/trajectory_optimization_ocp/trajectory_optimization_ocp/constants.py b/trajectory_optimization_ocp/trajectory_optimization_ocp/constants.py index 9f617ce..841649a 100644 --- a/trajectory_optimization_ocp/trajectory_optimization_ocp/constants.py +++ b/trajectory_optimization_ocp/trajectory_optimization_ocp/constants.py @@ -23,6 +23,9 @@ P_REF_PATH_INDEX_V = 3 P_REF_PATH_INDEX_D_BOUND_LEFT = 4 P_REF_PATH_INDEX_D_BOUND_RIGHT = 5 +P_REF_PATH_INDEX_D_OBJECT_LEFT = 6 # lateral bound from passed objects (left) +P_REF_PATH_INDEX_D_OBJECT_RIGHT = 7 # lateral bound from passed objects (right) +P_REF_PATH_INDEX_S = 8 # arc length along the reference path # object indices P_OBJECTS_INDEX_X = 0 @@ -32,5 +35,10 @@ P_OBJECTS_INDEX_HALF_WIDTH = 4 P_OBJECTS_INDEX_ACTIVE = 5 +# followed object indices +P_FOLLOW_INDEX_S = 0 +P_FOLLOW_INDEX_ACTIVE = 1 +P_FOLLOW_INDEX_RELAX = 2 + # fixed cost parameters V_SCALE_MIN = 2.778 diff --git a/trajectory_optimization_ocp/trajectory_optimization_ocp/constraints.py b/trajectory_optimization_ocp/trajectory_optimization_ocp/constraints.py index af8d520..0d4520a 100644 --- a/trajectory_optimization_ocp/trajectory_optimization_ocp/constraints.py +++ b/trajectory_optimization_ocp/trajectory_optimization_ocp/constraints.py @@ -8,6 +8,9 @@ CONTROL_INDEX_ALPHA_F, CONTROL_INDEX_ALPHA_R, CONTROL_INDEX_J_T, + P_FOLLOW_INDEX_ACTIVE, + P_FOLLOW_INDEX_RELAX, + P_FOLLOW_INDEX_S, P_OBJECTS_INDEX_ACTIVE, P_OBJECTS_INDEX_HALF_LENGTH, P_OBJECTS_INDEX_HALF_WIDTH, @@ -25,13 +28,12 @@ conservative_smooth_sat_margin, determine_spacially_matched_ref_path_point, ego_obb_geometry, - expand_ego_obb_forward, + obb_corners, saturate_positive_margin, smooth_abs_upper, stable_tan, ) -OBB_REAR_MARGIN_M = 0.1 GEOMETRY_SMOOTHING_EPSILON_M = 1e-3 SAT_SMOOTHING_TAU_M = 0.02 SAT_POSITIVE_MARGIN_SCALE_M = 0.5 @@ -129,7 +131,7 @@ def set_constraints(ocp: AcadosOcp, config): ) p_thw = p_cost_params[0] d_min_object_long = p_cost_params[1] - d_min_object_lat = p_cost_params[2] + # p_cost_params[2] (d_min_object_lat) is applied by the node through the bounds of passed objects d_min_boundary_lat = p_cost_params[3] # calc normal vector from interpolated reference point to the current position @@ -157,9 +159,8 @@ def set_constraints(ocp: AcadosOcp, config): # get objects from parameters object_shape = config["p_objects_shape"] p_objects = ocp.model.p[idx_params : (idx_params := idx_params + np.prod(object_shape))] - assert idx_params == ( - np.prod(config["p_dynamic_weight_shape"]) + np.prod(config["p_constraint_activation_shape"]) + np.prod(object_shape) - ) + p_follow = ocp.model.p[idx_params : (idx_params := idx_params + np.prod(config["p_follow_shape"]))] + assert idx_params == ocp.model.p.shape[0] # Hard minimum separation of the physical boxes; never relaxed by slacks. d_min_object_collision = float(config["d_min_object_collision"]) @@ -167,15 +168,44 @@ def set_constraints(ocp: AcadosOcp, config): raise ValueError("d_min_object_collision must be finite and nonnegative") v_t = ocp.model.x[STATE_INDEX_V_T] - # Desired clearance box, soft when object slacks are enabled. - # Both vehicle models are forward-only. THW and d_min_object_long protect - # the front; the rear only needs a small physical clearance. - front_margin = ca.fmax(ca.fmax(d_min_object_long, 0.0), p_thw * ca.fmax(v_t, 0.0)) - lateral_margin = ca.fmax(d_min_object_lat, 0.0) - clearance_obb = expand_ego_obb_forward(ego_obb, front_margin, OBB_REAR_MARGIN_M, lateral_margin) + ego_corners = obb_corners(ego_obb) # front left, front right, rear right, rear left + + # Passed objects: lateral bounds relative to the reference path, written by the node per reference + # point. Each ego corner is constrained separately, so the bound stays smooth in the heading. + corner_ref_diffs = [ca.vertcat(c[0] - ref_inter["x"], c[1] - ref_inter["y"]) for c in ego_corners] + corner_offsets = [ca.dot(diff, normal_vec) for diff in corner_ref_diffs] + object_bound_constraints = [ + corner_offsets[0] - ref_inter["d_left_object"], + corner_offsets[3] - ref_inter["d_left_object"], + -corner_offsets[1] - ref_inter["d_right_object"], + -corner_offsets[2] - ref_inter["d_right_object"], + ] + for constraint in object_bound_constraints: + ocp.model.con_h_expr = ca.vertcat( + ocp.model.con_h_expr, activate_upper_bounded_constraint(constraint, p_object_activation) + ) + cons.lh = np.concatenate((cons.lh, np.full(len(object_bound_constraints), -ACADOS_INFTY))) + cons.uh = np.concatenate((cons.uh, np.zeros(len(object_bound_constraints)))) + + # Followed object: the node passes the arc length of the rear of the closest followed object along the + # reference path. The arc length of each front corner is linearised at the ego's matched reference point, + # so the distance follows the path in curves. Both front corners stay behind by d_min_object_long and + # by thw * v; the maximum of the two margins is expressed as two constraints. The node relaxes both by + # the part that full braking cannot reach, so the soft rows never push the ego off the path. + tangent_vec = ca.vertcat(ca.cos(ref_inter["psi"]), ca.sin(ref_inter["psi"])) + follow = p_object_activation * p_follow[P_FOLLOW_INDEX_ACTIVE] + follow_gaps = [p_follow[P_FOLLOW_INDEX_S] - ref_inter["s"] - ca.dot(diff, tangent_vec) for diff in corner_ref_diffs[:2]] + for gap in follow_gaps: + for margin in (d_min_object_long, p_thw * v_t): + constraint = activate_constraint(gap + p_follow[P_FOLLOW_INDEX_RELAX] - margin, follow) + ocp.model.con_h_expr = ca.vertcat(ocp.model.con_h_expr, constraint) + cons.lh = np.concatenate((cons.lh, [0.0])) + cons.uh = np.concatenate((cons.uh, [ACADOS_INFTY])) + collision_constraints = [] for i in range(object_shape[0]): base = i * object_shape[1] + active = p_object_activation * p_objects[base + P_OBJECTS_INDEX_ACTIVE] object_yaw = p_objects[base + P_OBJECTS_INDEX_YAW] object_box = { "x": p_objects[base + P_OBJECTS_INDEX_X], @@ -185,17 +215,14 @@ def set_constraints(ocp: AcadosOcp, config): "half_length": p_objects[base + P_OBJECTS_INDEX_HALF_LENGTH], "half_width": p_objects[base + P_OBJECTS_INDEX_HALF_WIDTH], } - sat_margin = conservative_smooth_sat_margin(clearance_obb, object_box, GEOMETRY_SMOOTHING_EPSILON_M, SAT_SMOOTHING_TAU_M) - sat_margin = saturate_positive_margin(sat_margin, SAT_POSITIVE_MARGIN_SCALE_M) - active = p_object_activation * p_objects[base + P_OBJECTS_INDEX_ACTIVE] - constraint = activate_constraint(sat_margin, active) - ocp.model.con_h_expr = ca.vertcat(ocp.model.con_h_expr, constraint) - cons.lh = np.concatenate((cons.lh, [0.0])) - cons.uh = np.concatenate((cons.uh, [ACADOS_INFTY])) collision_margin = conservative_smooth_sat_margin(ego_obb, object_box, GEOMETRY_SMOOTHING_EPSILON_M, SAT_SMOOTHING_TAU_M) collision_margin = saturate_positive_margin(collision_margin - d_min_object_collision, SAT_POSITIVE_MARGIN_SCALE_M) collision_constraints.append(activate_constraint(collision_margin, active)) + # The node only sets a follow distance the ego can still stop before, so it is also the hard limit for + # that object (the node disables the object's SAT slot at that stage). + collision_constraints += [activate_constraint(gap - d_min_object_collision, follow) for gap in follow_gaps] + # The hard collision constraints follow as a separate block that never receives slacks. ocp.model.con_h_expr = ca.vertcat(ocp.model.con_h_expr, *collision_constraints) cons.lh = np.concatenate((cons.lh, np.zeros(len(collision_constraints)))) @@ -265,7 +292,7 @@ def set_constraints(ocp: AcadosOcp, config): slack_indices = [] slack_weights = {"zl": [], "zu": [], "Zl": [], "Zu": []} boundary_constraints = 2 - object_constraints = object_shape[0] + object_constraints = 4 + 4 # lateral object bounds + follow distance (2 front corners x [d_min_object_long, thw]) if config["enable_boundary_slack"]: slack_indices.extend(range(0, boundary_constraints)) diff --git a/trajectory_optimization_ocp/trajectory_optimization_ocp/costs.py b/trajectory_optimization_ocp/trajectory_optimization_ocp/costs.py index 463e7d8..cb29a36 100644 --- a/trajectory_optimization_ocp/trajectory_optimization_ocp/costs.py +++ b/trajectory_optimization_ocp/trajectory_optimization_ocp/costs.py @@ -42,7 +42,7 @@ def set_costs(ocp: AcadosOcp, config): # initialize parameters n_params_dynamic_weight = np.prod(config["p_dynamic_weight_shape"]) n_params_constraint_activation = np.prod(config["p_constraint_activation_shape"]) - n_params_objects = np.prod(config["p_objects_shape"]) + n_params_objects = np.prod(config["p_objects_shape"]) + np.prod(config["p_follow_shape"]) # total number of parameters n_params = n_params_dynamic_weight + n_params_constraint_activation + n_params_objects # set initial parameter values diff --git a/trajectory_optimization_ocp/trajectory_optimization_ocp/models/model_Ackermann.py b/trajectory_optimization_ocp/trajectory_optimization_ocp/models/model_Ackermann.py index 4188f28..966b27d 100644 --- a/trajectory_optimization_ocp/trajectory_optimization_ocp/models/model_Ackermann.py +++ b/trajectory_optimization_ocp/trajectory_optimization_ocp/models/model_Ackermann.py @@ -78,7 +78,8 @@ def set_model(ocp, config): p_dynamic_weight = MX.sym("dynamic_weight", np.prod(config["p_dynamic_weight_shape"])) # 1 p_constraint_activation = MX.sym("constraint_activation", np.prod(config["p_constraint_activation_shape"])) p_objects = MX.sym("objects", np.prod(config["p_objects_shape"])) - params = vertcat(p_dynamic_weight, p_constraint_activation, p_objects) + p_follow = MX.sym("follow", np.prod(config["p_follow_shape"])) + params = vertcat(p_dynamic_weight, p_constraint_activation, p_objects, p_follow) model.p = params # global parameters diff --git a/trajectory_optimization_ocp/trajectory_optimization_ocp/models/model_RWS.py b/trajectory_optimization_ocp/trajectory_optimization_ocp/models/model_RWS.py index 9c138d6..f91b2df 100644 --- a/trajectory_optimization_ocp/trajectory_optimization_ocp/models/model_RWS.py +++ b/trajectory_optimization_ocp/trajectory_optimization_ocp/models/model_RWS.py @@ -99,7 +99,8 @@ def set_model(ocp, config): p_dynamic_weight = MX.sym("dynamic_weight", np.prod(config["p_dynamic_weight_shape"])) # 1 p_constraint_activation = MX.sym("constraint_activation", np.prod(config["p_constraint_activation_shape"])) p_objects = MX.sym("objects", np.prod(config["p_objects_shape"])) - params = vertcat(p_dynamic_weight, p_constraint_activation, p_objects) + p_follow = MX.sym("follow", np.prod(config["p_follow_shape"])) + params = vertcat(p_dynamic_weight, p_constraint_activation, p_objects, p_follow) model.p = params # global parameters diff --git a/trajectory_optimization_ocp/trajectory_optimization_ocp/utils.py b/trajectory_optimization_ocp/trajectory_optimization_ocp/utils.py index 7789dcb..96295e2 100644 --- a/trajectory_optimization_ocp/trajectory_optimization_ocp/utils.py +++ b/trajectory_optimization_ocp/trajectory_optimization_ocp/utils.py @@ -6,7 +6,10 @@ from constants import ( P_REF_PATH_INDEX_D_BOUND_LEFT, P_REF_PATH_INDEX_D_BOUND_RIGHT, + P_REF_PATH_INDEX_D_OBJECT_LEFT, + P_REF_PATH_INDEX_D_OBJECT_RIGHT, P_REF_PATH_INDEX_PSI, + P_REF_PATH_INDEX_S, P_REF_PATH_INDEX_V, P_REF_PATH_INDEX_X, P_REF_PATH_INDEX_Y, @@ -56,6 +59,9 @@ def determine_spacially_matched_ref_path_point(config: dict, p_ref_path: ca.MX, d_right_boundary_ref_path = p_ref_path[ P_REF_PATH_INDEX_D_BOUND_RIGHT::ref_path_state_dim ] # every 6th element starting from index 5 + s_ref_path = p_ref_path[P_REF_PATH_INDEX_S::ref_path_state_dim] + d_left_object_ref_path = p_ref_path[P_REF_PATH_INDEX_D_OBJECT_LEFT::ref_path_state_dim] + d_right_object_ref_path = p_ref_path[P_REF_PATH_INDEX_D_OBJECT_RIGHT::ref_path_state_dim] n_ref_path_points = config["p_ref_path_shape"][0] # initialize closest distances to path sample with a large value @@ -120,12 +126,19 @@ def determine_spacially_matched_ref_path_point(config: dict, p_ref_path: ca.MX, position_lmd = ca.if_else(condition_begin, raw_lmd, ca.fmin(ca.fmax(raw_lmd, 0), 1)) x_ref_inter = x1 + position_lmd * (x2 - x1) y_ref_inter = y1 + position_lmd * (y2 - y1) + s_ref_inter = s_ref_path[idx_min] + position_lmd * (s_ref_path[next_idx_min] - s_ref_path[idx_min]) # Boundary distances, heading, and velocity are only defined at the provided # reference samples and must not be extrapolated with the reference line. bounded_lmd = ca.fmin(ca.fmax(position_lmd, 0), 1) d_left_boundary_inter = d_left_boundary1 + bounded_lmd * (d_left_boundary2 - d_left_boundary1) d_right_boundary_inter = d_right_boundary1 + bounded_lmd * (d_right_boundary2 - d_right_boundary1) + d_left_object_inter = d_left_object_ref_path[idx_min] + bounded_lmd * ( + d_left_object_ref_path[next_idx_min] - d_left_object_ref_path[idx_min] + ) + d_right_object_inter = d_right_object_ref_path[idx_min] + bounded_lmd * ( + d_right_object_ref_path[next_idx_min] - d_right_object_ref_path[idx_min] + ) psi_ref_inter = psi1 + bounded_lmd * wrap_angle(psi2 - psi1) v_ref_inter = v1 + bounded_lmd * (v2 - v1) @@ -136,6 +149,9 @@ def determine_spacially_matched_ref_path_point(config: dict, p_ref_path: ca.MX, "v": v_ref_inter, "d_left_boundary": d_left_boundary_inter, "d_right_boundary": d_right_boundary_inter, + "s": s_ref_inter, + "d_left_object": d_left_object_inter, + "d_right_object": d_right_object_inter, } return interpolated_ref_path_point @@ -156,16 +172,14 @@ def ego_obb_geometry(ocp: AcadosOcp, config: dict) -> dict: } -def expand_ego_obb_forward(ego_obb: dict, front_margin: ca.MX, rear_margin: ca.MX, lateral_margin: ca.MX) -> dict: - """Expand an OBB independently at its front, rear and lateral sides.""" - center_shift = 0.5 * (front_margin - rear_margin) - return { - **ego_obb, - "x": ego_obb["x"] + center_shift * ego_obb["long_axis"][0], - "y": ego_obb["y"] + center_shift * ego_obb["long_axis"][1], - "half_length": ego_obb["half_length"] + 0.5 * (front_margin + rear_margin), - "half_width": ego_obb["half_width"] + lateral_margin, - } +def obb_corners(box: dict) -> list: + """Corners of an oriented box: front left, front right, rear right, rear left.""" + long_x, long_y = box["half_length"] * box["long_axis"][0], box["half_length"] * box["long_axis"][1] + lat_x, lat_y = box["half_width"] * box["lat_axis"][0], box["half_width"] * box["lat_axis"][1] + return [ + (box["x"] + sign_long * long_x + sign_lat * lat_x, box["y"] + sign_long * long_y + sign_lat * lat_y) + for sign_long, sign_lat in ((1, 1), (1, -1), (-1, -1), (-1, 1)) + ] def smooth_abs_upper(value: ca.MX, epsilon: float) -> ca.MX: From 548b2968cffbdb65c4e2fb1fcd5548b879dc5e00 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Busch Date: Mon, 16 Nov 2026 12:47:27 +0000 Subject: [PATCH 2/3] temporarily disable industrial_ci Co-Authored-By: Claude Opus 5.5 --- .github/workflows/docker-ros.yml | 2 +- .gitlab-ci.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docker-ros.yml b/.github/workflows/docker-ros.yml index c432aa0..e7b6e24 100644 --- a/.github/workflows/docker-ros.yml +++ b/.github/workflows/docker-ros.yml @@ -22,6 +22,6 @@ jobs: base-image: rwthika/ros2:jazzy rmw-implementation: rmw_zenoh_cpp command: ros2 launch trajectory_optimization trajectory_optimization.launch.py - enable-industrial-ci: true + enable-industrial-ci: false # TODO: temporarily disabled, re-enable env: TARGET_CMAKE_ARGS: -DCMAKE_EXPORT_COMPILE_COMMANDS=1 diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 1b91f83..00bc5a4 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -17,7 +17,7 @@ docker-ros: BASE_IMAGE: rwthika/ros2:jazzy RMW_IMPLEMENTATION: rmw_zenoh_cpp COMMAND: ros2 launch trajectory_optimization trajectory_optimization.launch.py - ENABLE_INDUSTRIAL_CI: 'true' + ENABLE_INDUSTRIAL_CI: 'false' # TODO: temporarily disabled, re-enable TARGET_CMAKE_ARGS: '-DCMAKE_EXPORT_COMPILE_COMMANDS=1' compose-oci: From 85678110727ed9b285f2a9943213508ffbb1cdaf Mon Sep 17 00:00:00 2001 From: Jean-Pierre Busch Date: Mon, 16 Nov 2026 17:33:31 +0000 Subject: [PATCH 3/3] improve handling of oncoming vehicles; add visualization markers --- trajectory_optimization/README.md | 9 +++- .../config/example_params_ackermann.yml | 4 +- .../trajectory_optimization/follow_pass.hpp | 3 +- .../trajectory_optimization_node.hpp | 9 ++++ trajectory_optimization/src/follow_pass.cpp | 8 ++- .../src/trajectory_optimization_node.cpp | 1 + trajectory_optimization/src/utils.cpp | 54 +++++++++++++++++++ 7 files changed, 81 insertions(+), 7 deletions(-) diff --git a/trajectory_optimization/README.md b/trajectory_optimization/README.md index 69c7088..48490b3 100644 --- a/trajectory_optimization/README.md +++ b/trajectory_optimization/README.md @@ -34,7 +34,7 @@ flowchart LR | Topic | Type | Description | | --- | --- | --- | | `~/trajectory` | `trajectory_planning_msgs/msg/Trajectory` | Result of the OCP as drivable trajectory in the configured output frame. | -| `~/visualization/objects` | `visualization_msgs/msg/MarkerArray` | Debug markers visualizing the object boxes used by the OCP. | +| `~/visualization/objects` | `visualization_msgs/msg/MarkerArray` | Debug markers visualizing the object boxes used by the OCP, the bounds of passed objects and the rear of followed objects. | | `~/visualization/ego` | `visualization_msgs/msg/MarkerArray` | Debug markers visualizing the ego box used inside the OCP. | | `~/visualization/boundaries` | `visualization_msgs/msg/MarkerArray` | Debug markers visualizing boundary points considered by the OCP. | @@ -77,7 +77,9 @@ flowchart LR #### Following and passing objects -Each object prediction is either followed or passed: +Each object prediction is either followed or passed. Only positions the ego can still be next to at that stage count, +i.e. positions behind the ego even with full braking are ignored; a prediction without such positions is neither +followed nor passed. - A prediction that crosses the reference path is followed. - Otherwise it is passed if the ego fits next to it with the lateral distance of its class (`d_min_object_lat`, @@ -94,6 +96,9 @@ reach. If `d_min_object_long` is reachable only with full braking, the solve sta the warm start. With a follow distance, a rejected solve is retried once from the other initial guess within the remaining `constrained_solve_timeout_ms`. +With `debug_visualization`, `~/visualization/objects` also shows the bounds of passed objects (green) and the rear of the +followed object per stage (red). + ## Launch Files ### [`trajectory_optimization.launch.py`](launch/trajectory_optimization.launch.py) diff --git a/trajectory_optimization/config/example_params_ackermann.yml b/trajectory_optimization/config/example_params_ackermann.yml index 479446e..4ab7e6f 100644 --- a/trajectory_optimization/config/example_params_ackermann.yml +++ b/trajectory_optimization/config/example_params_ackermann.yml @@ -48,8 +48,8 @@ # other cost params thw: 2.0 # desired time headway to followed objects [s]; soft with object slacks - d_min_object_long: 1.0 # desired distance to followed objects [m]; soft with object slacks - d_min_object_lat: 0.1 # desired lateral distance to passed objects [m]; soft with object slacks + d_min_object_long: 3.0 # desired distance to followed objects [m]; soft with object slacks + d_min_object_lat: 0.75 # desired lateral distance to passed objects [m]; soft with object slacks # own lateral distance for some object classes (perception_msgs/ObjectClassification), e.g. bicycles: # d_min_object_lat_classes: [2] # d_min_object_lat_class_values: [1.5] diff --git a/trajectory_optimization/include/trajectory_optimization/follow_pass.hpp b/trajectory_optimization/include/trajectory_optimization/follow_pass.hpp index cddfaa4..ea0e27e 100644 --- a/trajectory_optimization/include/trajectory_optimization/follow_pass.hpp +++ b/trajectory_optimization/include/trajectory_optimization/follow_pass.hpp @@ -18,7 +18,8 @@ namespace trajectory_optimization { * A prediction is passed if it never crosses the reference path, the ego fits next to it with the lateral margin of its * class, and the current ego pose already keeps that margin where the prediction is next to the ego. The room for passing * is the suggested lane if the prediction is in that lane, otherwise the active route boundaries. A passed prediction stays - * passed while this holds with d_min_object_collision as margin. All other predictions are followed. + * passed while this holds with d_min_object_collision as margin. All other predictions are followed. Only positions the + * ego can still be next to at that stage count, i.e. not behind the ego even with full braking. * * Passed predictions bound the lateral offset of the ego from the reference path. Per stage, the followed prediction in the * suggested lane whose rear is closest along the reference path gives the follow distance, if the ego can still stay behind diff --git a/trajectory_optimization/include/trajectory_optimization/trajectory_optimization_node.hpp b/trajectory_optimization/include/trajectory_optimization/trajectory_optimization_node.hpp index d1458e8..0624e2b 100644 --- a/trajectory_optimization/include/trajectory_optimization/trajectory_optimization_node.hpp +++ b/trajectory_optimization/include/trajectory_optimization/trajectory_optimization_node.hpp @@ -367,6 +367,15 @@ class TrajectoryOptimizationNode : public rclcpp::Node { /** Publishes the object boxes currently passed to the optimizer. */ void vizObjectBoxes(const std::vector& objects); + /** + * @brief Publishes the follow/pass separation: bounds of passed objects and the rear of the followed object per stage. + * + * @param[in] reference Reference samples as passed to the OCP. + * @param[in] result Follow/pass decisions of this cycle. + * @param[in] ego_half_width Half width of the ego, used as length of the follow lines. + */ + void vizFollowPass(const FollowPass::Reference& reference, const FollowPass::Result& result, double ego_half_width); + /** Publishes the ego box along the optimized trajectory. */ void vizEgoBoxes(const std::vector& x_trajectory, const std::string& model_name); diff --git a/trajectory_optimization/src/follow_pass.cpp b/trajectory_optimization/src/follow_pass.cpp index 7b7976a..8a1874f 100644 --- a/trajectory_optimization/src/follow_pass.cpp +++ b/trajectory_optimization/src/follow_pass.cpp @@ -196,15 +196,19 @@ FollowPass::Result FollowPass::decide(const Reference& reference, const auto previous_it = memory_.find(key); const Memory previous = previous_it != memory_.end() ? previous_it->second : Memory{}; + // only corners the ego can still be next to at that stage count, i.e. not behind the ego even with full braking std::vector centers, corners; for (size_t stage = 0; stage < n_stages; ++stage) { const Box& box = boxes[stage][slot]; if (!box.active) continue; - centers.push_back(path.project({box.x, box.y})); + const size_t n_corners = corners.size(); for (const auto& corner : boxCorners(box.x, box.y, box.yaw, box.half_length, box.half_width)) { - corners.push_back(path.project(corner)); + const Projection p = path.project(corner); + if (p.s >= ego_s_min + braking_travel[stage]) corners.push_back(p); } + if (corners.size() > n_corners) centers.push_back(path.project({box.x, box.y})); } + if (centers.empty()) continue; // never next to the ego: neither followed nor passed // lane membership with hysteresis: the prediction enters our lane when its center is in it at any stage, and // leaves it only when none of its corners is in it any more diff --git a/trajectory_optimization/src/trajectory_optimization_node.cpp b/trajectory_optimization/src/trajectory_optimization_node.cpp index b4d1911..2e77ce0 100644 --- a/trajectory_optimization/src/trajectory_optimization_node.cpp +++ b/trajectory_optimization/src/trajectory_optimization_node.cpp @@ -757,6 +757,7 @@ bool TrajectoryOptimizationNode::updateOcpInputs(const perception_msgs::msg::Ego follow_pass_result_ = follow_pass_.decide(reference, object_boxes, object_constraints_active_ ? slots : std::vector{}, {x_init[0], x_init[1], x_init[STATE_INDEX_PSI]}, braking.travel, braking.speed, params); + if (debug_viz_) vizFollowPass(reference, follow_pass_result_, params.ego_half_width); this->setOcpGlobalParameters(cost_weights_, reference, reference_v, follow_pass_result_); this->setOcpParameters(object_boxes, follow_pass_result_); diff --git a/trajectory_optimization/src/utils.cpp b/trajectory_optimization/src/utils.cpp index 0d82f04..6534617 100644 --- a/trajectory_optimization/src/utils.cpp +++ b/trajectory_optimization/src/utils.cpp @@ -333,6 +333,60 @@ void TrajectoryOptimizationNode::vizObjectBoxes(const std::vector& objec object_marker_pub_->publish(marker_array); } +void TrajectoryOptimizationNode::vizFollowPass(const FollowPass::Reference& reference, + const FollowPass::Result& result, + double ego_half_width) { + // point at arc length s and lateral offset e, along the heading of the last sample before s + const auto pathPoint = [&](double s, double e) { + const auto upper = std::upper_bound(result.s.begin(), result.s.end(), s); + const size_t i = upper == result.s.begin() ? 0 : static_cast(upper - result.s.begin()) - 1; + const double ds = s - result.s[i]; + geometry_msgs::msg::Point point; + point.x = reference.x[i] + ds * std::cos(reference.psi[i]) - e * std::sin(reference.psi[i]); + point.y = reference.y[i] + ds * std::sin(reference.psi[i]) + e * std::cos(reference.psi[i]); + return point; + }; + const auto lines = [&](const std::string& ns, float r, float g, float b) { + visualization_msgs::msg::Marker marker; + marker.header.frame_id = vehicle_frame_id_; + marker.header.stamp = rclcpp::Time(ego_data_.header.stamp); + marker.lifetime = rclcpp::Duration::from_seconds(0.5); + marker.ns = ns; + marker.type = visualization_msgs::msg::Marker::LINE_LIST; + marker.pose.orientation.w = 1.0; + marker.scale.x = 0.1; + marker.color.a = 1.0F; + marker.color.r = r; + marker.color.g = g; + marker.color.b = b; + return marker; + }; + + // bounds of passed objects: the ego corners stay right of the left and left of the right bound + auto passed = lines("passed-object-bounds", 0.0F, 1.0F, 0.0F); + for (size_t i = 0; i + 1 < result.s.size(); ++i) { + for (const auto& [bounds, sign] : {std::pair{&result.d_object_left, 1.0}, std::pair{&result.d_object_right, -1.0}}) { + if ((*bounds)[i] >= FollowPass::NO_BOUND || (*bounds)[i + 1] >= FollowPass::NO_BOUND) continue; + passed.points.push_back(pathPoint(result.s[i], sign * (*bounds)[i])); + passed.points.push_back(pathPoint(result.s[i + 1], sign * (*bounds)[i + 1])); + } + } + // rear of the followed object per stage: the ego front stays behind it + auto followed = lines("followed-object-rear", 1.0F, 0.0F, 0.0F); + for (const auto& [s_rear, active, relax] : result.follow) { + if (active < 0.5) continue; + followed.points.push_back(pathPoint(s_rear, ego_half_width)); + followed.points.push_back(pathPoint(s_rear, -ego_half_width)); + } + + visualization_msgs::msg::MarkerArray marker_array; + for (auto& marker : {passed, followed}) { + marker_array.markers.push_back(marker); + if (marker.points.empty()) marker_array.markers.back().action = visualization_msgs::msg::Marker::DELETE; + } + object_marker_pub_->publish(marker_array); +} + std::optional TrajectoryOptimizationNode::modelConstants( const std::string& model_name) { // vehicle geometry and hard object distance based on model name (must match the OCP configuration)