repo_id
stringlengths
19
138
file_path
stringlengths
32
200
content
stringlengths
1
12.9M
__index_level_0__
int64
0
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/open_space_decider/open_space_roi_decider.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <algorithm> #include <memory> #include <string> #include <vector> #include "Eigen/Dense" #include "modules/common/vehicle_state/proto/vehicle_state.pb.h" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common_msgs/map_msgs/map_id.pb.h" #include "cyber/common/log.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/vec2d.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/map/pnc_map/path.h" #include "modules/map/pnc_map/pnc_map.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/indexed_queue.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/tasks/deciders/decider.h" namespace apollo { namespace planning { class OpenSpaceRoiDecider : public Decider { public: OpenSpaceRoiDecider(const TaskConfig &config, const std::shared_ptr<DependencyInjector> &injector); private: apollo::common::Status Process(Frame *frame) override; private: // @brief generate the path by vehicle location and return the target parking // spot on that path bool GetParkingSpot(Frame *const frame, std::array<common::math::Vec2d, 4> *vertices, hdmap::Path *nearby_path); // @brief get path from reference line and return vertices of pullover spot bool GetPullOverSpot(Frame *const frame, std::array<common::math::Vec2d, 4> *vertices, hdmap::Path *nearby_path); // @brief Set an origin to normalize the problem for later computation void SetOrigin(Frame *const frame, const std::array<common::math::Vec2d, 4> &vertices); void SetOriginFromADC(Frame *const frame, const hdmap::Path &nearby_path); void SetParkingSpotEndPose( Frame *const frame, const std::array<common::math::Vec2d, 4> &vertices); void SetPullOverSpotEndPose(Frame *const frame); void SetParkAndGoEndPose(Frame *const frame); // @brief Get road boundaries of both sides void GetRoadBoundary( const hdmap::Path &nearby_path, const double center_line_s, const common::math::Vec2d &origin_point, const double origin_heading, std::vector<common::math::Vec2d> *left_lane_boundary, std::vector<common::math::Vec2d> *right_lane_boundary, std::vector<common::math::Vec2d> *center_lane_boundary_left, std::vector<common::math::Vec2d> *center_lane_boundary_right, std::vector<double> *center_lane_s_left, std::vector<double> *center_lane_s_right, std::vector<double> *left_lane_road_width, std::vector<double> *right_lane_road_width); // @brief Get the Road Boundary From Map object void GetRoadBoundaryFromMap( const hdmap::Path &nearby_path, const double center_line_s, const common::math::Vec2d &origin_point, const double origin_heading, std::vector<common::math::Vec2d> *left_lane_boundary, std::vector<common::math::Vec2d> *right_lane_boundary, std::vector<common::math::Vec2d> *center_lane_boundary_left, std::vector<common::math::Vec2d> *center_lane_boundary_right, std::vector<double> *center_lane_s_left, std::vector<double> *center_lane_s_right, std::vector<double> *left_lane_road_width, std::vector<double> *right_lane_road_width); // @brief Check single-side curb and add key points to the boundary void AddBoundaryKeyPoint( const hdmap::Path &nearby_path, const double check_point_s, const double start_s, const double end_s, const bool is_anchor_point, const bool is_left_curb, std::vector<common::math::Vec2d> *center_lane_boundary, std::vector<common::math::Vec2d> *curb_lane_boundary, std::vector<double> *center_lane_s, std::vector<double> *road_width); // @brief "Region of Interest", load map boundary for open space scenario // @param vertices is an array consisting four points describing the // boundary of spot in box. Four points are in sequence of left_top, // left_down, right_down, right_top // ------------------------------------------------------------------ // // --> lane_direction // // ----------------left_top right_top-------------------------- // - - // - - // - - // - - // left_down-------right_down bool GetParkingBoundary(Frame *const frame, const std::array<common::math::Vec2d, 4> &vertices, const hdmap::Path &nearby_path, std::vector<std::vector<common::math::Vec2d>> *const roi_parking_boundary); bool GetPullOverBoundary(Frame *const frame, const std::array<common::math::Vec2d, 4> &vertices, const hdmap::Path &nearby_path, std::vector<std::vector<common::math::Vec2d>> *const roi_parking_boundary); bool GetParkAndGoBoundary(Frame *const frame, const hdmap::Path &nearby_path, std::vector<std::vector<common::math::Vec2d>> *const roi_parking_boundary); // @brief search target parking spot on the path by vehicle location, if // no return a nullptr in target_parking_spot void SearchTargetParkingSpotOnPath( const hdmap::Path &nearby_path, hdmap::ParkingSpaceInfoConstPtr *target_parking_spot); // @brief if not close enough to parking spot, return false bool CheckDistanceToParkingSpot( Frame *const frame, const hdmap::Path &nearby_path, const hdmap::ParkingSpaceInfoConstPtr &target_parking_spot); // @brief Helper function for fuse line segments into convex vertices set bool FuseLineSegments( std::vector<std::vector<common::math::Vec2d>> *line_segments_vec); // @brief main process to compute and load info needed by open space planner bool FormulateBoundaryConstraints( const std::vector<std::vector<common::math::Vec2d>> &roi_parking_boundary, Frame *const frame); // @brief Represent the obstacles in vertices and load it into // obstacles_vertices_vec_ in clock wise order. Take different approach // towards warm start and distance approach bool LoadObstacleInVertices( const std::vector<std::vector<common::math::Vec2d>> &roi_parking_boundary, Frame *const frame); bool FilterOutObstacle(const Frame &frame, const Obstacle &obstacle); // @brief Transform the vertice presentation of the obstacles into linear // inequality as Ax>b bool LoadObstacleInHyperPlanes(Frame *const frame); // @brief Helper function for LoadObstacleInHyperPlanes() bool GetHyperPlanes(const size_t &obstacles_num, const Eigen::MatrixXi &obstacles_edges_num, const std::vector<std::vector<common::math::Vec2d>> &obstacles_vertices_vec, Eigen::MatrixXd *A_all, Eigen::MatrixXd *b_all); /** * @brief check if vehicle is parked in a parking lot * * @return true adc parked in a parking lot * @return false adc parked at a pull-over spot */ bool IsInParkingLot(const double adc_init_x, const double adc_init_y, const double adc_init_heading, std::array<common::math::Vec2d, 4> *parking_lot_vertices); /** * @brief Get the Park Spot From Map object * * @param parking_lot * @param vertices */ void GetParkSpotFromMap(hdmap::ParkingSpaceInfoConstPtr parking_lot, std::array<common::math::Vec2d, 4> *vertices); /** * @brief Collect all the lane segments in the routing reponse. * * @param routing_response The routing response containing the lane segments. * @param routing_segments The output vector of lane segments. */ void GetAllLaneSegments(const routing::RoutingResponse &routing_response, std::vector<routing::LaneSegment> *routing_segments); private: // @brief parking_spot_id from routing std::string target_parking_spot_id_; const hdmap::HDMap *hdmap_ = nullptr; apollo::common::VehicleParam vehicle_params_; ThreadSafeIndexedObstacles *obstacles_by_frame_; common::VehicleState vehicle_state_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/open_space_decider/open_space_roi_decider_test.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/open_space_decider/open_space_roi_decider.h" #include "gtest/gtest.h" #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { class OpenSpaceRoiDeciderTest : public ::testing::Test { public: virtual void SetUp() { config_.set_task_type(TaskConfig::OPEN_SPACE_ROI_DECIDER); injector_ = std::make_shared<DependencyInjector>(); } protected: TaskConfig config_; std::shared_ptr<DependencyInjector> injector_; }; TEST_F(OpenSpaceRoiDeciderTest, Init) { OpenSpaceRoiDecider open_space_roi_decider(config_, injector_); EXPECT_EQ(open_space_roi_decider.Name(), TaskConfig::TaskType_Name(config_.task_type())); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/open_space_decider/open_space_pre_stop_decider.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <memory> #include "cyber/common/macros.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/reference_line_info.h" #include "modules/planning/tasks/deciders/decider.h" namespace apollo { namespace planning { class OpenSpacePreStopDecider : public Decider { public: OpenSpacePreStopDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); private: apollo::common::Status Process( Frame* frame, ReferenceLineInfo* reference_line_info) override; bool CheckParkingSpotPreStop(Frame* const frame, ReferenceLineInfo* const reference_line_info, double* target_s); bool CheckPullOverPreStop(Frame* const frame, ReferenceLineInfo* const reference_line_info, double* target_s); void SetParkingSpotStopFence(const double target_s, Frame* const frame, ReferenceLineInfo* const reference_line_info); void SetPullOverStopFence(const double target_s, Frame* const frame, ReferenceLineInfo* const reference_line_info); private: static constexpr const char* OPEN_SPACE_STOP_ID = "OPEN_SPACE_PRE_STOP"; OpenSpacePreStopDeciderConfig open_space_pre_stop_decider_config_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/open_space_decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) PLANNING_COPTS = ["-DMODULE_NAME=\\\"planning\\\""] cc_library( name = "open_space_roi_decider", srcs = ["open_space_roi_decider.cc"], hdrs = ["open_space_roi_decider.h"], copts = PLANNING_COPTS, deps = [ "//modules/planning/common:planning_context", "//modules/planning/common:planning_gflags", "//modules/planning/tasks/deciders:decider_base", ], ) cc_library( name = "open_space_pre_stop_decider", srcs = ["open_space_pre_stop_decider.cc"], hdrs = ["open_space_pre_stop_decider.h"], copts = PLANNING_COPTS, deps = [ "//modules/planning/common:reference_line_info", "//modules/planning/common/util:common_lib", "//modules/planning/tasks/deciders:decider_base", ], ) cc_library( name = "open_space_fallback_decider", srcs = ["open_space_fallback_decider.cc"], hdrs = ["open_space_fallback_decider.h"], copts = PLANNING_COPTS, deps = [ "//modules/planning/common:dependency_injector", "//modules/planning/common:planning_context", "//modules/planning/common:planning_gflags", "//modules/planning/tasks/deciders:decider_base", ], ) cc_test( name = "open_space_roi_decider_test", size = "small", srcs = ["open_space_roi_decider_test.cc"], deps = [ ":open_space_roi_decider", "@com_google_googletest//:gtest_main", ], tags = ["exclude"] ) cc_test( name = "open_space_fallback_decider_test", size = "small", srcs = ["open_space_fallback_decider_test.cc"], deps = [ ":open_space_fallback_decider", "//modules/planning/common:dependency_injector", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/open_space_decider/open_space_fallback_decider.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/open_space_decider/open_space_fallback_decider.h" namespace apollo { namespace planning { using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::math::Box2d; using apollo::common::math::Vec2d; OpenSpaceFallbackDecider::OpenSpaceFallbackDecider( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Decider(config, injector) {} bool OpenSpaceFallbackDecider::QuardraticFormulaLowerSolution(const double a, const double b, const double c, double* sol) { // quardratic formula: ax^2 + bx + c = 0, return lower solution // TODO(QiL): use const from common::math const double kEpsilon = 1e-6; *sol = 0.0; if (std::abs(a) < kEpsilon) { return false; } double tmp = b * b - 4 * a * c; if (tmp < kEpsilon) { return false; } double sol1 = (-b + std::sqrt(tmp)) / (2.0 * a); double sol2 = (-b - std::sqrt(tmp)) / (2.0 * a); *sol = std::abs(std::min(sol1, sol2)); ADEBUG << "QuardraticFormulaLowerSolution finished with sol: " << *sol << "sol1: " << sol1 << ", sol2: " << sol2 << "a: " << a << "b: " << b << "c: " << c; return true; } Status OpenSpaceFallbackDecider::Process(Frame* frame) { std::vector<std::vector<common::math::Box2d>> predicted_bounding_rectangles; size_t first_collision_index = 0; size_t fallback_start_index = 0; BuildPredictedEnvironment(frame->obstacles(), predicted_bounding_rectangles); ADEBUG << "Numbers of obstsacles are: " << frame->obstacles().size(); ADEBUG << "Numbers of predicted bounding rectangles are: " << predicted_bounding_rectangles[0].size() << " and : " << predicted_bounding_rectangles.size(); if (!IsCollisionFreeTrajectory( frame->open_space_info().chosen_partitioned_trajectory(), predicted_bounding_rectangles, &fallback_start_index, &first_collision_index)) { // change flag frame_->mutable_open_space_info()->set_fallback_flag(true); // generate fallback trajectory base on current partition trajectory // vehicle speed is decreased to zero inside safety distance TrajGearPair fallback_trajectory_pair_candidate = frame->open_space_info().chosen_partitioned_trajectory(); // auto* ptr_fallback_trajectory_pair = // frame_->mutable_open_space_info()->mutable_fallback_trajectory(); const auto future_collision_point = fallback_trajectory_pair_candidate.first[first_collision_index]; // Fallback starts from current location but with vehicle velocity auto fallback_start_point = fallback_trajectory_pair_candidate.first[fallback_start_index]; const auto& vehicle_state = injector_->vehicle_state()->vehicle_state(); fallback_start_point.set_v(vehicle_state.linear_velocity()); *(frame_->mutable_open_space_info()->mutable_future_collision_point()) = future_collision_point; // min stop distance: (max_acc) double min_stop_distance = 0.5 * fallback_start_point.v() * fallback_start_point.v() / 4.0; // TODO(QiL): move 1.0 to configs double stop_distance = fallback_trajectory_pair_candidate.second == canbus::Chassis::GEAR_DRIVE ? std::max(future_collision_point.path_point().s() - fallback_start_point.path_point().s() - 1.0, 0.0) : std::min(future_collision_point.path_point().s() - fallback_start_point.path_point().s() + 1.0, 0.0); ADEBUG << "stop distance : " << stop_distance; // const auto& vehicle_config = // common::VehicleConfigHelper::Instance()->GetConfig(); const double vehicle_max_acc = 4.0; // vehicle_config.max_acceleration(); const double vehicle_max_dec = -4.0; // vehicle_config.max_deceleration(); double stop_deceleration = 0.0; if (fallback_trajectory_pair_candidate.second == canbus::Chassis::GEAR_REVERSE) { stop_deceleration = std::min(fallback_start_point.v() * fallback_start_point.v() / (2.0 * (stop_distance + 1e-6)), vehicle_max_acc); stop_distance = std::min(-1 * min_stop_distance, stop_distance); } else { stop_deceleration = std::max(-fallback_start_point.v() * fallback_start_point.v() / (2.0 * (stop_distance + 1e-6)), vehicle_max_dec); stop_distance = std::max(min_stop_distance, stop_distance); } ADEBUG << "stop_deceleration: " << stop_deceleration; // Search stop index in chosen trajectory by distance size_t stop_index = fallback_start_index; for (size_t i = fallback_start_index; i < fallback_trajectory_pair_candidate.first.NumOfPoints(); ++i) { if (std::abs( fallback_trajectory_pair_candidate.first[i].path_point().s()) >= std::abs(fallback_start_point.path_point().s() + stop_distance)) { stop_index = i; break; } } ADEBUG << "stop index before is: " << stop_index << "; fallback_start index before is: " << fallback_start_index; for (size_t i = 0; i < fallback_start_index; ++i) { fallback_trajectory_pair_candidate.first[i].set_v( fallback_start_point.v()); fallback_trajectory_pair_candidate.first[i].set_a(stop_deceleration); } // TODO(QiL): refine the logic and remove redundant code, change 0.5 to from // loading optimizer configs // If stop_index == fallback_start_index; if (fallback_start_index >= stop_index) { // 1. Set fallback start speed to 0, acceleration to max acceleration. AINFO << "Stop distance within safety buffer, stop now!"; fallback_start_point.set_v(0.0); fallback_start_point.set_a(0.0); fallback_trajectory_pair_candidate.first[stop_index].set_v(0.0); fallback_trajectory_pair_candidate.first[stop_index].set_a(0.0); // 2. Trim all trajectory points after stop index fallback_trajectory_pair_candidate.first.erase( fallback_trajectory_pair_candidate.first.begin() + stop_index + 1, fallback_trajectory_pair_candidate.first.end()); // 3. AppendTrajectoryPoint with same location but zero velocity for (int i = 0; i < 20; ++i) { common::TrajectoryPoint trajectory_point( fallback_trajectory_pair_candidate.first[stop_index]); trajectory_point.set_relative_time( i * 0.5 + 0.5 + fallback_trajectory_pair_candidate.first[stop_index] .relative_time()); fallback_trajectory_pair_candidate.first.AppendTrajectoryPoint( trajectory_point); } *(frame_->mutable_open_space_info()->mutable_fallback_trajectory()) = fallback_trajectory_pair_candidate; return Status::OK(); } ADEBUG << "before change, size : " << fallback_trajectory_pair_candidate.first.size() << ", first index information : " << fallback_trajectory_pair_candidate.first[0].DebugString() << ", second index information : " << fallback_trajectory_pair_candidate.first[1].DebugString(); // If stop_index > fallback_start_index for (size_t i = fallback_start_index; i <= stop_index; ++i) { double new_relative_time = 0.0; double temp_v = 0.0; double c = -2.0 * fallback_trajectory_pair_candidate.first[i].path_point().s(); if (QuardraticFormulaLowerSolution(stop_deceleration, 2.0 * fallback_start_point.v(), c, &new_relative_time) && std::abs( fallback_trajectory_pair_candidate.first[i].path_point().s()) <= std::abs(stop_distance)) { ADEBUG << "new_relative_time" << new_relative_time; temp_v = fallback_start_point.v() + stop_deceleration * new_relative_time; // speed limit if (std::abs(temp_v) < 1.0) { fallback_trajectory_pair_candidate.first[i].set_v(temp_v); } else { fallback_trajectory_pair_candidate.first[i].set_v( temp_v / std::abs(temp_v) * 1.0); } fallback_trajectory_pair_candidate.first[i].set_a(stop_deceleration); fallback_trajectory_pair_candidate.first[i].set_relative_time( new_relative_time); } else { if (i != 0) { fallback_trajectory_pair_candidate.first[i] .mutable_path_point() ->CopyFrom( fallback_trajectory_pair_candidate.first[i - 1].path_point()); fallback_trajectory_pair_candidate.first[i].set_v(0.0); fallback_trajectory_pair_candidate.first[i].set_a(0.0); fallback_trajectory_pair_candidate.first[i].set_relative_time( fallback_trajectory_pair_candidate.first[i - 1].relative_time() + 0.5); } else { fallback_trajectory_pair_candidate.first[i].set_v(0.0); fallback_trajectory_pair_candidate.first[i].set_a(0.0); } } } ADEBUG << "fallback start point after changes: " << fallback_start_point.DebugString(); ADEBUG << "stop index: " << stop_index; ADEBUG << "fallback start index: " << fallback_start_index; // 2. Erase afterwards fallback_trajectory_pair_candidate.first.erase( fallback_trajectory_pair_candidate.first.begin() + stop_index + 1, fallback_trajectory_pair_candidate.first.end()); // 3. AppendTrajectoryPoint with same location but zero velocity for (int i = 0; i < 20; ++i) { common::TrajectoryPoint trajectory_point( fallback_trajectory_pair_candidate.first[stop_index]); trajectory_point.set_relative_time( i * 0.5 + 0.5 + fallback_trajectory_pair_candidate.first[stop_index].relative_time()); fallback_trajectory_pair_candidate.first.AppendTrajectoryPoint( trajectory_point); } *(frame_->mutable_open_space_info()->mutable_fallback_trajectory()) = fallback_trajectory_pair_candidate; } else { frame_->mutable_open_space_info()->set_fallback_flag(false); } return Status::OK(); } void OpenSpaceFallbackDecider::BuildPredictedEnvironment( const std::vector<const Obstacle*>& obstacles, std::vector<std::vector<common::math::Box2d>>& predicted_bounding_rectangles) { predicted_bounding_rectangles.clear(); double relative_time = 0.0; while (relative_time < config_.open_space_fallback_decider_config() .open_space_prediction_time_period()) { std::vector<Box2d> predicted_env; for (const Obstacle* obstacle : obstacles) { if (!obstacle->IsVirtual()) { TrajectoryPoint point = obstacle->GetPointAtTime(relative_time); Box2d box = obstacle->GetBoundingBox(point); predicted_env.push_back(std::move(box)); } } predicted_bounding_rectangles.emplace_back(std::move(predicted_env)); relative_time += FLAGS_trajectory_time_resolution; } } bool OpenSpaceFallbackDecider::IsCollisionFreeTrajectory( const TrajGearPair& trajectory_gear_pair, const std::vector<std::vector<common::math::Box2d>>& predicted_bounding_rectangles, size_t* current_index, size_t* first_collision_index) { // prediction time resolution: FLAGS_trajectory_time_resolution const auto& vehicle_config = common::VehicleConfigHelper::Instance()->GetConfig(); double ego_length = vehicle_config.vehicle_param().length(); double ego_width = vehicle_config.vehicle_param().width(); auto trajectory_pb = trajectory_gear_pair.first; const size_t point_size = trajectory_pb.NumOfPoints(); *current_index = trajectory_pb.QueryLowerBoundPoint(0.0); for (size_t i = *current_index; i < point_size; ++i) { const auto& trajectory_point = trajectory_pb.TrajectoryPointAt(i); double ego_theta = trajectory_point.path_point().theta(); Box2d ego_box( {trajectory_point.path_point().x(), trajectory_point.path_point().y()}, ego_theta, ego_length, ego_width); double shift_distance = ego_length / 2.0 - vehicle_config.vehicle_param().back_edge_to_center(); Vec2d shift_vec{shift_distance * std::cos(ego_theta), shift_distance * std::sin(ego_theta)}; ego_box.Shift(shift_vec); size_t predicted_time_horizon = predicted_bounding_rectangles.size(); for (size_t j = 0; j < predicted_time_horizon; j++) { for (const auto& obstacle_box : predicted_bounding_rectangles[j]) { if (ego_box.HasOverlap(obstacle_box)) { ADEBUG << "HasOverlap(obstacle_box) [" << i << "]"; const auto& vehicle_state = frame_->vehicle_state(); Vec2d vehicle_vec({vehicle_state.x(), vehicle_state.y()}); // remove points in previous trajectory if (std::abs(trajectory_point.relative_time() - static_cast<double>(j) * FLAGS_trajectory_time_resolution) < config_.open_space_fallback_decider_config() .open_space_fallback_collision_time_buffer() && trajectory_point.relative_time() > 0.0) { ADEBUG << "first_collision_index: [" << i << "]"; *first_collision_index = i; return false; } } } } } return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/open_space_decider/open_space_fallback_decider.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <algorithm> #include <memory> #include <utility> #include <vector> #include "Eigen/Dense" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/vec2d.h" #include "modules/planning/common/dependency_injector.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/trajectory/discretized_trajectory.h" #include "modules/planning/common/trajectory/publishable_trajectory.h" #include "modules/planning/tasks/deciders/decider.h" namespace apollo { namespace planning { class OpenSpaceFallbackDecider : public Decider { public: OpenSpaceFallbackDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); private: apollo::common::Status Process(Frame* frame) override; // bool IsCollisionFreeTrajectory(const ADCTrajectory& trajectory_pb); void BuildPredictedEnvironment(const std::vector<const Obstacle*>& obstacles, std::vector<std::vector<common::math::Box2d>>& predicted_bounding_rectangles); bool IsCollisionFreeTrajectory( const TrajGearPair& trajectory_pb, const std::vector<std::vector<common::math::Box2d>>& predicted_bounding_rectangles, size_t* current_idx, size_t* first_collision_idx); bool QuardraticFormulaLowerSolution(const double a, const double b, const double c, double* sol); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/open_space_decider/open_space_roi_decider.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/open_space_decider/open_space_roi_decider.h" #include <memory> #include <utility> #include "modules/common/util/point_factory.h" #include "modules/planning/common/planning_context.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::math::Box2d; using apollo::common::math::Vec2d; using apollo::hdmap::HDMapUtil; using apollo::hdmap::LaneInfoConstPtr; using apollo::hdmap::LaneSegment; using apollo::hdmap::ParkingSpaceInfoConstPtr; using apollo::hdmap::Path; using apollo::routing::ParkingSpaceType; OpenSpaceRoiDecider::OpenSpaceRoiDecider( const TaskConfig &config, const std::shared_ptr<DependencyInjector> &injector) : Decider(config, injector) { hdmap_ = hdmap::HDMapUtil::BaseMapPtr(); CHECK_NOTNULL(hdmap_); vehicle_params_ = apollo::common::VehicleConfigHelper::GetConfig().vehicle_param(); AINFO << config_.DebugString(); } Status OpenSpaceRoiDecider::Process(Frame *frame) { if (frame == nullptr) { const std::string msg = "Invalid frame, fail to process the OpenSpaceRoiDecider."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } vehicle_state_ = frame->vehicle_state(); obstacles_by_frame_ = frame->GetObstacleList(); std::array<Vec2d, 4> spot_vertices; Path nearby_path; // @brief vector of different obstacle consisting of vertice points.The // obstacle and the vertices order are in counter-clockwise order std::vector<std::vector<common::math::Vec2d>> roi_boundary; const auto &roi_type = config_.open_space_roi_decider_config().roi_type(); if (roi_type == OpenSpaceRoiDeciderConfig::PARKING) { const auto &routing_request = frame->local_view().routing->routing_request(); if (routing_request.has_parking_info() && routing_request.parking_info().has_parking_space_id()) { target_parking_spot_id_ = routing_request.parking_info().parking_space_id(); } else { const std::string msg = "Failed to get parking space id from routing"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (!GetParkingSpot(frame, &spot_vertices, &nearby_path)) { const std::string msg = "Fail to get parking boundary from map"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } SetOrigin(frame, spot_vertices); SetParkingSpotEndPose(frame, spot_vertices); if (!GetParkingBoundary(frame, spot_vertices, nearby_path, &roi_boundary)) { const std::string msg = "Fail to get parking boundary from map"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } } else if (roi_type == OpenSpaceRoiDeciderConfig::PULL_OVER) { if (!GetPullOverSpot(frame, &spot_vertices, &nearby_path)) { const std::string msg = "Fail to get parking boundary from map"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } SetOrigin(frame, spot_vertices); SetPullOverSpotEndPose(frame); if (!GetPullOverBoundary(frame, spot_vertices, nearby_path, &roi_boundary)) { const std::string msg = "Fail to get parking boundary from map"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } } else if (roi_type == OpenSpaceRoiDeciderConfig::PARK_AND_GO) { ADEBUG << "in Park_and_Go"; nearby_path = frame->reference_line_info().front().reference_line().GetMapPath(); ADEBUG << "nearby_path: " << nearby_path.DebugString(); ADEBUG << "found nearby_path"; if (!injector_->planning_context() ->planning_status() .park_and_go() .has_adc_init_position()) { const std::string msg = "ADC initial position is unavailable"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } SetOriginFromADC(frame, nearby_path); ADEBUG << "SetOrigin"; SetParkAndGoEndPose(frame); ADEBUG << "SetEndPose"; if (!GetParkAndGoBoundary(frame, nearby_path, &roi_boundary)) { const std::string msg = "Fail to get park and go boundary from map"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } } else { const std::string msg = "chosen open space roi secenario type not implemented"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (!FormulateBoundaryConstraints(roi_boundary, frame)) { const std::string msg = "Fail to formulate boundary constraints"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } return Status::OK(); } // get origin from ADC void OpenSpaceRoiDecider::SetOriginFromADC(Frame *const frame, const hdmap::Path &nearby_path) { // get ADC box const auto &park_and_go_status = injector_->planning_context()->planning_status().park_and_go(); const double adc_init_x = park_and_go_status.adc_init_position().x(); const double adc_init_y = park_and_go_status.adc_init_position().y(); const double adc_init_heading = park_and_go_status.adc_init_heading(); common::math::Vec2d adc_init_position = {adc_init_x, adc_init_y}; const double adc_length = vehicle_params_.length(); const double adc_width = vehicle_params_.width(); // ADC box Box2d adc_box(adc_init_position, adc_init_heading, adc_length, adc_width); // get vertices from ADC box std::vector<common::math::Vec2d> adc_corners; adc_box.GetAllCorners(&adc_corners); for (size_t i = 0; i < adc_corners.size(); ++i) { ADEBUG << "ADC [" << i << "]x: " << std::setprecision(9) << adc_corners[i].x(); ADEBUG << "ADC [" << i << "]y: " << std::setprecision(9) << adc_corners[i].y(); } auto left_top = adc_corners[3]; ADEBUG << "left_top x: " << std::setprecision(9) << left_top.x(); ADEBUG << "left_top y: " << std::setprecision(9) << left_top.y(); // rotate the points to have the lane to be horizontal to x axis positive // direction and scale them base on the origin point // heading angle double heading; if (!nearby_path.GetHeadingAlongPath(left_top, &heading)) { AERROR << "fail to get heading on reference line"; return; } frame->mutable_open_space_info()->set_origin_heading( common::math::NormalizeAngle(heading)); ADEBUG << "heading: " << heading; frame->mutable_open_space_info()->mutable_origin_point()->set_x(left_top.x()); frame->mutable_open_space_info()->mutable_origin_point()->set_y(left_top.y()); } void OpenSpaceRoiDecider::SetOrigin( Frame *const frame, const std::array<common::math::Vec2d, 4> &vertices) { auto left_top = vertices[0]; auto right_top = vertices[3]; // rotate the points to have the lane to be horizontal to x axis positive // direction and scale them base on the origin point Vec2d heading_vec = right_top - left_top; frame->mutable_open_space_info()->set_origin_heading(heading_vec.Angle()); frame->mutable_open_space_info()->mutable_origin_point()->set_x(left_top.x()); frame->mutable_open_space_info()->mutable_origin_point()->set_y(left_top.y()); } void OpenSpaceRoiDecider::SetParkingSpotEndPose( Frame *const frame, const std::array<common::math::Vec2d, 4> &vertices) { const auto &routing_request = frame->local_view().routing->routing_request(); auto plot_type = routing_request.parking_info().parking_space_type(); auto left_top = vertices[0]; auto left_down = vertices[1]; auto right_down = vertices[2]; auto right_top = vertices[3]; const auto &origin_point = frame->open_space_info().origin_point(); const auto &origin_heading = frame->open_space_info().origin_heading(); // End pose is set in normalized boundary left_top -= origin_point; left_top.SelfRotate(-origin_heading); left_down -= origin_point; left_down.SelfRotate(-origin_heading); right_top -= origin_point; right_top.SelfRotate(-origin_heading); right_down -= origin_point; right_down.SelfRotate(-origin_heading); // TODO(Jinyun): adjust end pose setting for more parking spot configurations double parking_spot_heading = (left_down - left_top).Angle(); double end_x = (left_top.x() + right_top.x()) / 2.0; double end_y = 0.0; const double parking_depth_buffer = config_.open_space_roi_decider_config().parking_depth_buffer(); CHECK_GE(parking_depth_buffer, 0.0); const bool parking_inwards = config_.open_space_roi_decider_config().parking_inwards(); const double top_to_down_distance = left_top.y() - left_down.y(); if (parking_spot_heading > common::math::kMathEpsilon) { if (parking_inwards) { end_y = left_down.y() - (std::max(3.0 * -top_to_down_distance / 4.0, vehicle_params_.front_edge_to_center()) + parking_depth_buffer); } else { end_y = left_down.y() - (std::max(-top_to_down_distance / 4.0, vehicle_params_.back_edge_to_center()) + parking_depth_buffer); } } else { if (parking_inwards) { end_y = left_down.y() + (std::max(3.0 * top_to_down_distance / 4.0, vehicle_params_.front_edge_to_center()) + parking_depth_buffer); } else { end_y = left_down.y() + (std::max(top_to_down_distance / 4.0, vehicle_params_.back_edge_to_center()) + parking_depth_buffer); } } if (plot_type == ParkingSpaceType::PARALLEL_PARKING) { double parllel_park_end_x_buffer = config_.open_space_roi_decider_config().parallel_park_end_x_buffer(); // Check the validity of parllel_park_end_x_buffer double max_parllel_park_end_x_buffer = (std::abs(left_top.x() - right_top.x()) - vehicle_params_.length()) / 2.0; if (parllel_park_end_x_buffer > max_parllel_park_end_x_buffer) { parllel_park_end_x_buffer = max_parllel_park_end_x_buffer; } parking_spot_heading = (left_down - right_down).Angle(); end_y = (left_top.y() + left_down.y()) / 2.0; end_x = left_top.x() + vehicle_params_.back_edge_to_center() + parllel_park_end_x_buffer; } auto *end_pose = frame->mutable_open_space_info()->mutable_open_space_end_pose(); end_pose->push_back(end_x); end_pose->push_back(end_y); if (config_.open_space_roi_decider_config().parking_inwards()) { end_pose->push_back(parking_spot_heading); } else { end_pose->push_back( common::math::NormalizeAngle(parking_spot_heading + M_PI)); } end_pose->push_back(0.0); } void OpenSpaceRoiDecider::SetPullOverSpotEndPose(Frame *const frame) { const auto &pull_over_status = injector_->planning_context()->planning_status().pull_over(); const double pull_over_x = pull_over_status.position().x(); const double pull_over_y = pull_over_status.position().y(); double pull_over_theta = pull_over_status.theta(); // Normalize according to origin_point and origin_heading const auto &origin_point = frame->open_space_info().origin_point(); const auto &origin_heading = frame->open_space_info().origin_heading(); Vec2d center(pull_over_x, pull_over_y); center -= origin_point; center.SelfRotate(-origin_heading); pull_over_theta = common::math::NormalizeAngle(pull_over_theta - origin_heading); auto *end_pose = frame->mutable_open_space_info()->mutable_open_space_end_pose(); end_pose->push_back(center.x()); end_pose->push_back(center.y()); end_pose->push_back(pull_over_theta); // end pose velocity set to be zero end_pose->push_back(0.0); } void OpenSpaceRoiDecider::SetParkAndGoEndPose(Frame *const frame) { const double kSTargetBuffer = config_.open_space_roi_decider_config().end_pose_s_distance(); const double kSpeedRatio = 0.1; // after adjust speed is 10% of speed limit // get vehicle current location // get vehicle s,l info auto park_and_go_status = injector_->planning_context() ->mutable_planning_status() ->mutable_park_and_go(); const double adc_init_x = park_and_go_status->adc_init_position().x(); const double adc_init_y = park_and_go_status->adc_init_position().y(); ADEBUG << "ADC position (x): " << std::setprecision(9) << adc_init_x; ADEBUG << "ADC position (y): " << std::setprecision(9) << adc_init_y; const common::math::Vec2d adc_position = {adc_init_x, adc_init_y}; common::SLPoint adc_position_sl; // get nearest reference line const auto &reference_line_list = frame->reference_line_info(); ADEBUG << reference_line_list.size(); const auto reference_line_info = std::min_element( reference_line_list.begin(), reference_line_list.end(), [&](const ReferenceLineInfo &ref_a, const ReferenceLineInfo &ref_b) { common::SLPoint adc_position_sl_a; common::SLPoint adc_position_sl_b; ref_a.reference_line().XYToSL(adc_position, &adc_position_sl_a); ref_b.reference_line().XYToSL(adc_position, &adc_position_sl_b); return std::fabs(adc_position_sl_a.l()) < std::fabs(adc_position_sl_b.l()); }); const auto &reference_line = reference_line_info->reference_line(); reference_line.XYToSL(adc_position, &adc_position_sl); // target is at reference line const double target_s = adc_position_sl.s() + kSTargetBuffer; const auto reference_point = reference_line.GetReferencePoint(target_s); const double target_x = reference_point.x(); const double target_y = reference_point.y(); double target_theta = reference_point.heading(); park_and_go_status->mutable_adc_adjust_end_pose()->set_x(target_x); park_and_go_status->mutable_adc_adjust_end_pose()->set_y(target_y); ADEBUG << "center.x(): " << std::setprecision(9) << target_x; ADEBUG << "center.y(): " << std::setprecision(9) << target_y; ADEBUG << "target_theta: " << std::setprecision(9) << target_theta; // Normalize according to origin_point and origin_heading const auto &origin_point = frame->open_space_info().origin_point(); const auto &origin_heading = frame->open_space_info().origin_heading(); Vec2d center(target_x, target_y); center -= origin_point; center.SelfRotate(-origin_heading); target_theta = common::math::NormalizeAngle(target_theta - origin_heading); auto *end_pose = frame->mutable_open_space_info()->mutable_open_space_end_pose(); end_pose->push_back(center.x()); end_pose->push_back(center.y()); end_pose->push_back(target_theta); ADEBUG << "ADC position (x): " << std::setprecision(9) << (*end_pose)[0]; ADEBUG << "ADC position (y): " << std::setprecision(9) << (*end_pose)[1]; ADEBUG << "reference_line ID: " << reference_line_info->Lanes().Id(); // end pose velocity set to be speed limit double target_speed = reference_line.GetSpeedLimitFromS(target_s); end_pose->push_back(kSpeedRatio * target_speed); } void OpenSpaceRoiDecider::GetRoadBoundary( const hdmap::Path &nearby_path, const double center_line_s, const common::math::Vec2d &origin_point, const double origin_heading, std::vector<Vec2d> *left_lane_boundary, std::vector<Vec2d> *right_lane_boundary, std::vector<Vec2d> *center_lane_boundary_left, std::vector<Vec2d> *center_lane_boundary_right, std::vector<double> *center_lane_s_left, std::vector<double> *center_lane_s_right, std::vector<double> *left_lane_road_width, std::vector<double> *right_lane_road_width) { double start_s = center_line_s - config_.open_space_roi_decider_config().roi_longitudinal_range_start(); double end_s = center_line_s + config_.open_space_roi_decider_config().roi_longitudinal_range_end(); hdmap::MapPathPoint start_point = nearby_path.GetSmoothPoint(start_s); double last_check_point_heading = start_point.heading(); double index = 0.0; double check_point_s = start_s; // For the road boundary, add key points to left/right side boundary // separately. Iterate s_value to check key points at a step of // roi_line_segment_length. Key points include: start_point, end_point, points // where path curvature is large, points near left/right road-curb corners while (check_point_s <= end_s) { hdmap::MapPathPoint check_point = nearby_path.GetSmoothPoint(check_point_s); double check_point_heading = check_point.heading(); bool is_center_lane_heading_change = std::abs(common::math::NormalizeAngle(check_point_heading - last_check_point_heading)) > config_.open_space_roi_decider_config().roi_line_segment_min_angle(); last_check_point_heading = check_point_heading; ADEBUG << "is is_center_lane_heading_change: " << is_center_lane_heading_change; // Check if the current center-lane checking-point is start point || end // point || or point with larger curvature. If yes, mark it as an anchor // point. bool is_anchor_point = check_point_s == start_s || check_point_s == end_s || is_center_lane_heading_change; // Add key points to the left-half boundary AddBoundaryKeyPoint(nearby_path, check_point_s, start_s, end_s, is_anchor_point, true, center_lane_boundary_left, left_lane_boundary, center_lane_s_left, left_lane_road_width); // Add key points to the right-half boundary AddBoundaryKeyPoint(nearby_path, check_point_s, start_s, end_s, is_anchor_point, false, center_lane_boundary_right, right_lane_boundary, center_lane_s_right, right_lane_road_width); if (check_point_s == end_s) { break; } index += 1.0; check_point_s = start_s + index * config_.open_space_roi_decider_config().roi_line_segment_length(); check_point_s = check_point_s >= end_s ? end_s : check_point_s; } size_t left_point_size = left_lane_boundary->size(); size_t right_point_size = right_lane_boundary->size(); for (size_t i = 0; i < left_point_size; i++) { left_lane_boundary->at(i) -= origin_point; left_lane_boundary->at(i).SelfRotate(-origin_heading); } for (size_t i = 0; i < right_point_size; i++) { right_lane_boundary->at(i) -= origin_point; right_lane_boundary->at(i).SelfRotate(-origin_heading); } } void OpenSpaceRoiDecider::GetRoadBoundaryFromMap( const hdmap::Path &nearby_path, const double center_line_s, const Vec2d &origin_point, const double origin_heading, std::vector<Vec2d> *left_lane_boundary, std::vector<Vec2d> *right_lane_boundary, std::vector<Vec2d> *center_lane_boundary_left, std::vector<Vec2d> *center_lane_boundary_right, std::vector<double> *center_lane_s_left, std::vector<double> *center_lane_s_right, std::vector<double> *left_lane_road_width, std::vector<double> *right_lane_road_width) { // Longitudinal range can be asymmetric. double start_s = center_line_s - config_.open_space_roi_decider_config().roi_longitudinal_range_start(); double end_s = center_line_s + config_.open_space_roi_decider_config().roi_longitudinal_range_end(); hdmap::MapPathPoint start_point = nearby_path.GetSmoothPoint(start_s); double check_point_s = start_s; while (check_point_s <= end_s) { hdmap::MapPathPoint check_point = nearby_path.GetSmoothPoint(check_point_s); // get road boundaries double left_road_width = nearby_path.GetRoadLeftWidth(check_point_s); double right_road_width = nearby_path.GetRoadRightWidth(check_point_s); double current_road_width = std::max(left_road_width, right_road_width); // get road boundaries at current location common::PointENU check_point_xy; std::vector<hdmap::RoadRoiPtr> road_boundaries; std::vector<hdmap::JunctionInfoConstPtr> junctions; check_point_xy.set_x(check_point.x()); check_point_xy.set_y(check_point.y()); hdmap_->GetRoadBoundaries(check_point_xy, current_road_width, &road_boundaries, &junctions); if (check_point_s < center_line_s) { for (size_t i = 0; i < (*road_boundaries.at(0)).left_boundary.line_points.size(); i++) { right_lane_boundary->emplace_back( Vec2d((*road_boundaries.at(0)).left_boundary.line_points[i].x(), (*road_boundaries.at(0)).left_boundary.line_points[i].y())); } for (size_t i = 0; i < (*road_boundaries.at(0)).right_boundary.line_points.size(); i++) { left_lane_boundary->emplace_back( Vec2d((*road_boundaries.at(0)).right_boundary.line_points[i].x(), (*road_boundaries.at(0)).right_boundary.line_points[i].y())); } } else { for (size_t i = 0; i < (*road_boundaries.at(0)).left_boundary.line_points.size(); i++) { left_lane_boundary->emplace_back( Vec2d((*road_boundaries.at(0)).left_boundary.line_points[i].x(), (*road_boundaries.at(0)).left_boundary.line_points[i].y())); } for (size_t i = 0; i < (*road_boundaries.at(0)).right_boundary.line_points.size(); i++) { right_lane_boundary->emplace_back( Vec2d((*road_boundaries.at(0)).right_boundary.line_points[i].x(), (*road_boundaries.at(0)).right_boundary.line_points[i].y())); } } center_lane_boundary_right->emplace_back(check_point); center_lane_boundary_left->emplace_back(check_point); center_lane_s_left->emplace_back(check_point_s); center_lane_s_right->emplace_back(check_point_s); left_lane_road_width->emplace_back(left_road_width); right_lane_road_width->emplace_back(right_road_width); check_point_s = check_point_s + config_.open_space_roi_decider_config() .roi_line_segment_length_from_map(); } size_t left_point_size = left_lane_boundary->size(); size_t right_point_size = right_lane_boundary->size(); ADEBUG << "right_road_boundary size: " << right_lane_boundary->size(); ADEBUG << "left_road_boundary size: " << left_lane_boundary->size(); for (size_t i = 0; i < left_point_size; i++) { left_lane_boundary->at(i) -= origin_point; left_lane_boundary->at(i).SelfRotate(-origin_heading); ADEBUG << "left_road_boundary: [" << std::setprecision(9) << left_lane_boundary->at(i).x() << ", " << left_lane_boundary->at(i).y() << "]"; } for (size_t i = 0; i < right_point_size; i++) { right_lane_boundary->at(i) -= origin_point; right_lane_boundary->at(i).SelfRotate(-origin_heading); ADEBUG << "right_road_boundary: [" << std::setprecision(9) << right_lane_boundary->at(i).x() << ", " << right_lane_boundary->at(i).y() << "]"; } if (!left_lane_boundary->empty()) { sort(left_lane_boundary->begin(), left_lane_boundary->end(), [](const Vec2d &first_pt, const Vec2d &second_pt) { return first_pt.x() < second_pt.x() || (first_pt.x() == second_pt.x() && first_pt.y() < second_pt.y()); }); auto unique_end = std::unique(left_lane_boundary->begin(), left_lane_boundary->end()); left_lane_boundary->erase(unique_end, left_lane_boundary->end()); } if (!right_lane_boundary->empty()) { sort(right_lane_boundary->begin(), right_lane_boundary->end(), [](const Vec2d &first_pt, const Vec2d &second_pt) { return first_pt.x() < second_pt.x() || (first_pt.x() == second_pt.x() && first_pt.y() < second_pt.y()); }); auto unique_end = std::unique(right_lane_boundary->begin(), right_lane_boundary->end()); right_lane_boundary->erase(unique_end, right_lane_boundary->end()); } } void OpenSpaceRoiDecider::AddBoundaryKeyPoint( const hdmap::Path &nearby_path, const double check_point_s, const double start_s, const double end_s, const bool is_anchor_point, const bool is_left_curb, std::vector<Vec2d> *center_lane_boundary, std::vector<Vec2d> *curb_lane_boundary, std::vector<double> *center_lane_s, std::vector<double> *road_width) { // Check if current central-lane checking point's mapping on the left/right // road boundary is a key point. The road boundary point is a key point if // one of the following two confitions is satisfied: // 1. the current central-lane point is an anchor point: (a start/end point // or the point on path with large curvatures) // 2. the point on the left/right lane boundary is close to a curb corner // As indicated below: // (#) Key Point Type 1: Lane anchor points // (*) Key Point Type 2: Curb-corner points // # // Path Direction --> / / # // Left Lane Boundary #--------------------------------# / / // / / // Center Lane - - - - - - - - - - - - - - - - - - / / // / // Right Lane Boundary #--------* *----------# // \ / // *-------------* // road width changes slightly at the turning point of a path // TODO(SHU): 1. consider distortion introduced by curvy road; 2. use both // round boundaries for single-track road; 3. longitudinal range may not be // symmetric const double previous_distance_s = std::min( config_.open_space_roi_decider_config().roi_line_segment_length(), check_point_s - start_s); const double next_distance_s = std::min( config_.open_space_roi_decider_config().roi_line_segment_length(), end_s - check_point_s); hdmap::MapPathPoint current_check_point = nearby_path.GetSmoothPoint(check_point_s); hdmap::MapPathPoint previous_check_point = nearby_path.GetSmoothPoint(check_point_s - previous_distance_s); hdmap::MapPathPoint next_check_point = nearby_path.GetSmoothPoint(check_point_s + next_distance_s); double current_check_point_heading = current_check_point.heading(); double current_road_width = is_left_curb ? nearby_path.GetRoadLeftWidth(check_point_s) : nearby_path.GetRoadRightWidth(check_point_s); // If the current center-lane checking point is an anchor point, then add // current left/right curb boundary point as a key point if (is_anchor_point) { double point_vec_cos = is_left_curb ? std::cos(current_check_point_heading + M_PI / 2.0) : std::cos(current_check_point_heading - M_PI / 2.0); double point_vec_sin = is_left_curb ? std::sin(current_check_point_heading + M_PI / 2.0) : std::sin(current_check_point_heading - M_PI / 2.0); Vec2d curb_lane_point = Vec2d(current_road_width * point_vec_cos, current_road_width * point_vec_sin); curb_lane_point = curb_lane_point + current_check_point; center_lane_boundary->push_back(current_check_point); curb_lane_boundary->push_back(curb_lane_point); center_lane_s->push_back(check_point_s); road_width->push_back(current_road_width); return; } double previous_road_width = is_left_curb ? nearby_path.GetRoadLeftWidth(check_point_s - previous_distance_s) : nearby_path.GetRoadRightWidth(check_point_s - previous_distance_s); double next_road_width = is_left_curb ? nearby_path.GetRoadLeftWidth(check_point_s + next_distance_s) : nearby_path.GetRoadRightWidth(check_point_s + next_distance_s); double previous_curb_segment_angle = (current_road_width - previous_road_width) / previous_distance_s; double next_segment_angle = (next_road_width - current_road_width) / next_distance_s; double current_curb_point_delta_theta = next_segment_angle - previous_curb_segment_angle; // If the delta angle between the previous curb segment and the next curb // segment is large (near a curb corner), then add current curb_lane_point // as a key point. if (std::abs(current_curb_point_delta_theta) > config_.open_space_roi_decider_config() .curb_heading_tangent_change_upper_limit()) { double point_vec_cos = is_left_curb ? std::cos(current_check_point_heading + M_PI / 2.0) : std::cos(current_check_point_heading - M_PI / 2.0); double point_vec_sin = is_left_curb ? std::sin(current_check_point_heading + M_PI / 2.0) : std::sin(current_check_point_heading - M_PI / 2.0); Vec2d curb_lane_point = Vec2d(current_road_width * point_vec_cos, current_road_width * point_vec_sin); curb_lane_point = curb_lane_point + current_check_point; center_lane_boundary->push_back(current_check_point); curb_lane_boundary->push_back(curb_lane_point); center_lane_s->push_back(check_point_s); road_width->push_back(current_road_width); } } bool OpenSpaceRoiDecider::GetParkingBoundary( Frame *const frame, const std::array<Vec2d, 4> &vertices, const hdmap::Path &nearby_path, std::vector<std::vector<common::math::Vec2d>> *const roi_parking_boundary) { auto left_top = vertices[0]; ADEBUG << "left_top: " << left_top.x() << ", " << left_top.y(); auto left_down = vertices[1]; ADEBUG << "left_down: " << left_down.x() << ", " << left_down.y(); auto right_down = vertices[2]; ADEBUG << "right_down: " << right_down.x() << ", " << left_down.y(); auto right_top = vertices[3]; ADEBUG << "right_top: " << right_top.x() << ", " << right_top.y(); const auto &origin_point = frame->open_space_info().origin_point(); ADEBUG << "origin_point: " << origin_point.x() << ", " << origin_point.y(); const auto &origin_heading = frame->open_space_info().origin_heading(); double left_top_s = 0.0; double left_top_l = 0.0; double right_top_s = 0.0; double right_top_l = 0.0; if (!(nearby_path.GetProjection(left_top, &left_top_s, &left_top_l) && nearby_path.GetProjection(right_top, &right_top_s, &right_top_l))) { AERROR << "fail to get parking spot points' projections on reference line"; return false; } left_top -= origin_point; left_top.SelfRotate(-origin_heading); left_down -= origin_point; left_down.SelfRotate(-origin_heading); right_top -= origin_point; right_top.SelfRotate(-origin_heading); right_down -= origin_point; right_down.SelfRotate(-origin_heading); const double center_line_s = (left_top_s + right_top_s) / 2.0; std::vector<Vec2d> left_lane_boundary; std::vector<Vec2d> right_lane_boundary; // The pivot points on the central lane, mapping with the key points on // the left lane boundary. std::vector<Vec2d> center_lane_boundary_left; // The pivot points on the central lane, mapping with the key points on // the right lane boundary. std::vector<Vec2d> center_lane_boundary_right; // The s-value for the anchor points on the center_lane_boundary_left. std::vector<double> center_lane_s_left; // The s-value for the anchor points on the center_lane_boundary_right. std::vector<double> center_lane_s_right; // The left-half road width between the pivot points on the // center_lane_boundary_left and key points on the // left_lane_boundary. std::vector<double> left_lane_road_width; // The right-half road width between the pivot points on the // center_lane_boundary_right and key points on the // right_lane_boundary. std::vector<double> right_lane_road_width; GetRoadBoundary(nearby_path, center_line_s, origin_point, origin_heading, &left_lane_boundary, &right_lane_boundary, &center_lane_boundary_left, &center_lane_boundary_right, &center_lane_s_left, &center_lane_s_right, &left_lane_road_width, &right_lane_road_width); // If smaller than zero, the parking spot is on the right of the lane // Left, right, down or opposite of the boundary is decided when viewing the // parking spot upward const double average_l = (left_top_l + right_top_l) / 2.0; std::vector<Vec2d> boundary_points; // TODO(jiaxuan): Write a half-boundary formation function and call it twice // to avoid duplicated manipulations on the left and right sides if (average_l < 0) { // if average_l is lower than zero, the parking spot is on the right // lane boundary and assume that the lane half width is average_l ADEBUG << "average_l is less than 0 in OpenSpaceROI"; size_t point_size = right_lane_boundary.size(); for (size_t i = 0; i < point_size; i++) { right_lane_boundary[i].SelfRotate(origin_heading); right_lane_boundary[i] += origin_point; right_lane_boundary[i] -= center_lane_boundary_right[i]; right_lane_boundary[i] /= right_lane_road_width[i]; right_lane_boundary[i] *= (-average_l); right_lane_boundary[i] += center_lane_boundary_right[i]; right_lane_boundary[i] -= origin_point; right_lane_boundary[i].SelfRotate(-origin_heading); } auto point_left_to_left_top_connor_s = std::lower_bound( center_lane_s_right.begin(), center_lane_s_right.end(), left_top_s); size_t point_left_to_left_top_connor_index = std::distance( center_lane_s_right.begin(), point_left_to_left_top_connor_s); point_left_to_left_top_connor_index = point_left_to_left_top_connor_index == 0 ? point_left_to_left_top_connor_index : point_left_to_left_top_connor_index - 1; auto point_left_to_left_top_connor_itr = right_lane_boundary.begin() + point_left_to_left_top_connor_index; auto point_right_to_right_top_connor_s = std::upper_bound( center_lane_s_right.begin(), center_lane_s_right.end(), right_top_s); size_t point_right_to_right_top_connor_index = std::distance( center_lane_s_right.begin(), point_right_to_right_top_connor_s); auto point_right_to_right_top_connor_itr = right_lane_boundary.begin() + point_right_to_right_top_connor_index; std::copy(right_lane_boundary.begin(), point_left_to_left_top_connor_itr, std::back_inserter(boundary_points)); std::vector<Vec2d> parking_spot_boundary{left_top, left_down, right_down, right_top}; std::copy(parking_spot_boundary.begin(), parking_spot_boundary.end(), std::back_inserter(boundary_points)); std::copy(point_right_to_right_top_connor_itr, right_lane_boundary.end(), std::back_inserter(boundary_points)); std::reverse_copy(left_lane_boundary.begin(), left_lane_boundary.end(), std::back_inserter(boundary_points)); // reinsert the initial point to the back to from closed loop boundary_points.push_back(right_lane_boundary.front()); // disassemble line into line2d segments for (size_t i = 0; i < point_left_to_left_top_connor_index; i++) { std::vector<Vec2d> segment{right_lane_boundary[i], right_lane_boundary[i + 1]}; roi_parking_boundary->push_back(segment); } std::vector<Vec2d> left_stitching_segment{ right_lane_boundary[point_left_to_left_top_connor_index], left_top}; roi_parking_boundary->push_back(left_stitching_segment); std::vector<Vec2d> left_parking_spot_segment{left_top, left_down}; std::vector<Vec2d> down_parking_spot_segment{left_down, right_down}; std::vector<Vec2d> right_parking_spot_segment{right_down, right_top}; roi_parking_boundary->push_back(left_parking_spot_segment); roi_parking_boundary->push_back(down_parking_spot_segment); roi_parking_boundary->push_back(right_parking_spot_segment); std::vector<Vec2d> right_stitching_segment{ right_top, right_lane_boundary[point_right_to_right_top_connor_index]}; roi_parking_boundary->push_back(right_stitching_segment); size_t right_lane_boundary_last_index = right_lane_boundary.size() - 1; for (size_t i = point_right_to_right_top_connor_index; i < right_lane_boundary_last_index; i++) { std::vector<Vec2d> segment{right_lane_boundary[i], right_lane_boundary[i + 1]}; roi_parking_boundary->push_back(segment); } size_t left_lane_boundary_last_index = left_lane_boundary.size() - 1; for (size_t i = left_lane_boundary_last_index; i > 0; i--) { std::vector<Vec2d> segment{left_lane_boundary[i], left_lane_boundary[i - 1]}; roi_parking_boundary->push_back(segment); } } else { // if average_l is higher than zero, the parking spot is on the left // lane boundary and assume that the lane half width is average_l ADEBUG << "average_l is greater than 0 in OpenSpaceROI"; size_t point_size = left_lane_boundary.size(); for (size_t i = 0; i < point_size; i++) { left_lane_boundary[i].SelfRotate(origin_heading); left_lane_boundary[i] += origin_point; left_lane_boundary[i] -= center_lane_boundary_left[i]; left_lane_boundary[i] /= left_lane_road_width[i]; left_lane_boundary[i] *= average_l; left_lane_boundary[i] += center_lane_boundary_left[i]; left_lane_boundary[i] -= origin_point; left_lane_boundary[i].SelfRotate(-origin_heading); ADEBUG << "left_lane_boundary[" << i << "]: " << left_lane_boundary[i].x() << ", " << left_lane_boundary[i].y(); } auto point_right_to_right_top_connor_s = std::lower_bound( center_lane_s_left.begin(), center_lane_s_left.end(), right_top_s); size_t point_right_to_right_top_connor_index = std::distance( center_lane_s_left.begin(), point_right_to_right_top_connor_s); if (point_right_to_right_top_connor_index > 0) { --point_right_to_right_top_connor_index; } auto point_right_to_right_top_connor_itr = left_lane_boundary.begin() + point_right_to_right_top_connor_index; auto point_left_to_left_top_connor_s = std::upper_bound( center_lane_s_left.begin(), center_lane_s_left.end(), left_top_s); size_t point_left_to_left_top_connor_index = std::distance( center_lane_s_left.begin(), point_left_to_left_top_connor_s); auto point_left_to_left_top_connor_itr = left_lane_boundary.begin() + point_left_to_left_top_connor_index; std::copy(right_lane_boundary.begin(), right_lane_boundary.end(), std::back_inserter(boundary_points)); std::reverse_copy(point_left_to_left_top_connor_itr, left_lane_boundary.end(), std::back_inserter(boundary_points)); std::vector<Vec2d> parking_spot_boundary{left_top, left_down, right_down, right_top}; std::copy(parking_spot_boundary.begin(), parking_spot_boundary.end(), std::back_inserter(boundary_points)); std::reverse_copy(left_lane_boundary.begin(), point_right_to_right_top_connor_itr, std::back_inserter(boundary_points)); // reinsert the initial point to the back to from closed loop boundary_points.push_back(right_lane_boundary.front()); // disassemble line into line2d segments size_t right_lane_boundary_last_index = right_lane_boundary.size() - 1; for (size_t i = 0; i < right_lane_boundary_last_index; i++) { std::vector<Vec2d> segment{right_lane_boundary[i], right_lane_boundary[i + 1]}; roi_parking_boundary->push_back(segment); } size_t left_lane_boundary_last_index = left_lane_boundary.size() - 1; for (size_t i = left_lane_boundary_last_index; i > point_left_to_left_top_connor_index; i--) { std::vector<Vec2d> segment{left_lane_boundary[i], left_lane_boundary[i - 1]}; roi_parking_boundary->push_back(segment); } std::vector<Vec2d> left_stitching_segment{ left_lane_boundary[point_left_to_left_top_connor_index], left_top}; roi_parking_boundary->push_back(left_stitching_segment); std::vector<Vec2d> left_parking_spot_segment{left_top, left_down}; std::vector<Vec2d> down_parking_spot_segment{left_down, right_down}; std::vector<Vec2d> right_parking_spot_segment{right_down, right_top}; roi_parking_boundary->push_back(left_parking_spot_segment); roi_parking_boundary->push_back(down_parking_spot_segment); roi_parking_boundary->push_back(right_parking_spot_segment); std::vector<Vec2d> right_stitching_segment{ right_top, left_lane_boundary[point_right_to_right_top_connor_index]}; roi_parking_boundary->push_back(right_stitching_segment); for (size_t i = point_right_to_right_top_connor_index; i > 0; --i) { std::vector<Vec2d> segment{left_lane_boundary[i], left_lane_boundary[i - 1]}; roi_parking_boundary->push_back(segment); } } // Fuse line segments into convex contraints if (!FuseLineSegments(roi_parking_boundary)) { AERROR << "FuseLineSegments failed in parking ROI"; return false; } // Get xy boundary auto xminmax = std::minmax_element( boundary_points.begin(), boundary_points.end(), [](const Vec2d &a, const Vec2d &b) { return a.x() < b.x(); }); auto yminmax = std::minmax_element( boundary_points.begin(), boundary_points.end(), [](const Vec2d &a, const Vec2d &b) { return a.y() < b.y(); }); std::vector<double> ROI_xy_boundary{xminmax.first->x(), xminmax.second->x(), yminmax.first->y(), yminmax.second->y()}; auto *xy_boundary = frame->mutable_open_space_info()->mutable_ROI_xy_boundary(); xy_boundary->assign(ROI_xy_boundary.begin(), ROI_xy_boundary.end()); Vec2d vehicle_xy = Vec2d(vehicle_state_.x(), vehicle_state_.y()); vehicle_xy -= origin_point; vehicle_xy.SelfRotate(-origin_heading); if (vehicle_xy.x() < ROI_xy_boundary[0] || vehicle_xy.x() > ROI_xy_boundary[1] || vehicle_xy.y() < ROI_xy_boundary[2] || vehicle_xy.y() > ROI_xy_boundary[3]) { AERROR << "vehicle outside of xy boundary of parking ROI"; return false; } return true; } bool OpenSpaceRoiDecider::GetPullOverBoundary( Frame *const frame, const std::array<common::math::Vec2d, 4> &vertices, const hdmap::Path &nearby_path, std::vector<std::vector<common::math::Vec2d>> *const roi_parking_boundary) { auto left_top = vertices[0]; auto left_down = vertices[1]; auto right_down = vertices[2]; auto right_top = vertices[3]; const auto &origin_point = frame->open_space_info().origin_point(); const auto &origin_heading = frame->open_space_info().origin_heading(); double left_top_s = 0.0; double left_top_l = 0.0; double right_top_s = 0.0; double right_top_l = 0.0; if (!(nearby_path.GetProjection(left_top, &left_top_s, &left_top_l) && nearby_path.GetProjection(right_top, &right_top_s, &right_top_l))) { AERROR << "fail to get parking spot points' projections on reference line"; return false; } left_top -= origin_point; left_top.SelfRotate(-origin_heading); left_down -= origin_point; left_down.SelfRotate(-origin_heading); right_top -= origin_point; right_top.SelfRotate(-origin_heading); right_down -= origin_point; right_down.SelfRotate(-origin_heading); const double center_line_s = (left_top_s + right_top_s) / 2.0; std::vector<Vec2d> left_lane_boundary; std::vector<Vec2d> right_lane_boundary; std::vector<Vec2d> center_lane_boundary_left; std::vector<Vec2d> center_lane_boundary_right; std::vector<double> center_lane_s_left; std::vector<double> center_lane_s_right; std::vector<double> left_lane_road_width; std::vector<double> right_lane_road_width; GetRoadBoundary(nearby_path, center_line_s, origin_point, origin_heading, &left_lane_boundary, &right_lane_boundary, &center_lane_boundary_left, &center_lane_boundary_right, &center_lane_s_left, &center_lane_s_right, &left_lane_road_width, &right_lane_road_width); // Load boundary as line segments in counter-clockwise order std::reverse(left_lane_boundary.begin(), left_lane_boundary.end()); std::vector<Vec2d> boundary_points; std::copy(right_lane_boundary.begin(), right_lane_boundary.end(), std::back_inserter(boundary_points)); std::copy(left_lane_boundary.begin(), left_lane_boundary.end(), std::back_inserter(boundary_points)); size_t right_lane_boundary_last_index = right_lane_boundary.size() - 1; for (size_t i = 0; i < right_lane_boundary_last_index; i++) { std::vector<Vec2d> segment{right_lane_boundary[i], right_lane_boundary[i + 1]}; roi_parking_boundary->push_back(segment); } size_t left_lane_boundary_last_index = left_lane_boundary.size() - 1; for (size_t i = left_lane_boundary_last_index; i > 0; i--) { std::vector<Vec2d> segment{left_lane_boundary[i], left_lane_boundary[i - 1]}; roi_parking_boundary->push_back(segment); } // Fuse line segments into convex contraints if (!FuseLineSegments(roi_parking_boundary)) { return false; } // Get xy boundary auto xminmax = std::minmax_element( boundary_points.begin(), boundary_points.end(), [](const Vec2d &a, const Vec2d &b) { return a.x() < b.x(); }); auto yminmax = std::minmax_element( boundary_points.begin(), boundary_points.end(), [](const Vec2d &a, const Vec2d &b) { return a.y() < b.y(); }); std::vector<double> ROI_xy_boundary{xminmax.first->x(), xminmax.second->x(), yminmax.first->y(), yminmax.second->y()}; auto *xy_boundary = frame->mutable_open_space_info()->mutable_ROI_xy_boundary(); xy_boundary->assign(ROI_xy_boundary.begin(), ROI_xy_boundary.end()); Vec2d vehicle_xy = Vec2d(vehicle_state_.x(), vehicle_state_.y()); vehicle_xy -= origin_point; vehicle_xy.SelfRotate(-origin_heading); if (vehicle_xy.x() < ROI_xy_boundary[0] || vehicle_xy.x() > ROI_xy_boundary[1] || vehicle_xy.y() < ROI_xy_boundary[2] || vehicle_xy.y() > ROI_xy_boundary[3]) { AERROR << "vehicle outside of xy boundary of parking ROI"; return false; } return true; } bool OpenSpaceRoiDecider::GetParkAndGoBoundary( Frame *const frame, const hdmap::Path &nearby_path, std::vector<std::vector<common::math::Vec2d>> *const roi_parking_boundary) { const auto &park_and_go_status = injector_->planning_context()->planning_status().park_and_go(); const double adc_init_x = park_and_go_status.adc_init_position().x(); const double adc_init_y = park_and_go_status.adc_init_position().y(); const double adc_init_heading = park_and_go_status.adc_init_heading(); common::math::Vec2d adc_init_position = {adc_init_x, adc_init_y}; const double adc_length = vehicle_params_.length(); const double adc_width = vehicle_params_.width(); // ADC box Box2d adc_box(adc_init_position, adc_init_heading, adc_length, adc_width); // get vertices from ADC box std::vector<common::math::Vec2d> adc_corners; adc_box.GetAllCorners(&adc_corners); auto left_top = adc_corners[1]; auto right_top = adc_corners[0]; const auto &origin_point = frame->open_space_info().origin_point(); const auto &origin_heading = frame->open_space_info().origin_heading(); double left_top_s = 0.0; double left_top_l = 0.0; double right_top_s = 0.0; double right_top_l = 0.0; if (!(nearby_path.GetProjection(left_top, &left_top_s, &left_top_l) && nearby_path.GetProjection(right_top, &right_top_s, &right_top_l))) { AERROR << "fail to get parking spot points' projections on reference line"; return false; } left_top -= origin_point; left_top.SelfRotate(-origin_heading); right_top -= origin_point; right_top.SelfRotate(-origin_heading); const double center_line_s = (left_top_s + right_top_s) / 2.0; std::vector<Vec2d> left_lane_boundary; std::vector<Vec2d> right_lane_boundary; std::vector<Vec2d> center_lane_boundary_left; std::vector<Vec2d> center_lane_boundary_right; std::vector<double> center_lane_s_left; std::vector<double> center_lane_s_right; std::vector<double> left_lane_road_width; std::vector<double> right_lane_road_width; if (FLAGS_use_road_boundary_from_map) { GetRoadBoundaryFromMap( nearby_path, center_line_s, origin_point, origin_heading, &left_lane_boundary, &right_lane_boundary, &center_lane_boundary_left, &center_lane_boundary_right, &center_lane_s_left, &center_lane_s_right, &left_lane_road_width, &right_lane_road_width); } else { GetRoadBoundary(nearby_path, center_line_s, origin_point, origin_heading, &left_lane_boundary, &right_lane_boundary, &center_lane_boundary_left, &center_lane_boundary_right, &center_lane_s_left, &center_lane_s_right, &left_lane_road_width, &right_lane_road_width); } // Load boundary as line segments in counter-clockwise order std::reverse(left_lane_boundary.begin(), left_lane_boundary.end()); std::vector<Vec2d> boundary_points; std::copy(right_lane_boundary.begin(), right_lane_boundary.end(), std::back_inserter(boundary_points)); std::copy(left_lane_boundary.begin(), left_lane_boundary.end(), std::back_inserter(boundary_points)); size_t right_lane_boundary_last_index = right_lane_boundary.size() - 1; for (size_t i = 0; i < right_lane_boundary_last_index; i++) { std::vector<Vec2d> segment{right_lane_boundary[i], right_lane_boundary[i + 1]}; ADEBUG << "right segment"; ADEBUG << "right_road_boundary: [" << std::setprecision(9) << right_lane_boundary[i].x() << ", " << right_lane_boundary[i].y() << "]"; ADEBUG << "right_road_boundary: [" << std::setprecision(9) << right_lane_boundary[i + 1].x() << ", " << right_lane_boundary[i + 1].y() << "]"; roi_parking_boundary->push_back(segment); } size_t left_lane_boundary_last_index = left_lane_boundary.size() - 1; for (size_t i = left_lane_boundary_last_index; i > 0; i--) { std::vector<Vec2d> segment{left_lane_boundary[i], left_lane_boundary[i - 1]}; roi_parking_boundary->push_back(segment); } ADEBUG << "roi_parking_boundary size: [" << roi_parking_boundary->size() << "]"; // Fuse line segments into convex contraints if (!FuseLineSegments(roi_parking_boundary)) { return false; } ADEBUG << "roi_parking_boundary size: [" << roi_parking_boundary->size() << "]"; // Get xy boundary auto xminmax = std::minmax_element( boundary_points.begin(), boundary_points.end(), [](const Vec2d &a, const Vec2d &b) { return a.x() < b.x(); }); auto yminmax = std::minmax_element( boundary_points.begin(), boundary_points.end(), [](const Vec2d &a, const Vec2d &b) { return a.y() < b.y(); }); std::vector<double> ROI_xy_boundary{xminmax.first->x(), xminmax.second->x(), yminmax.first->y(), yminmax.second->y()}; auto *xy_boundary = frame->mutable_open_space_info()->mutable_ROI_xy_boundary(); xy_boundary->assign(ROI_xy_boundary.begin(), ROI_xy_boundary.end()); Vec2d vehicle_xy = Vec2d(vehicle_state_.x(), vehicle_state_.y()); vehicle_xy -= origin_point; vehicle_xy.SelfRotate(-origin_heading); if (vehicle_xy.x() < ROI_xy_boundary[0] || vehicle_xy.x() > ROI_xy_boundary[1] || vehicle_xy.y() < ROI_xy_boundary[2] || vehicle_xy.y() > ROI_xy_boundary[3]) { AERROR << "vehicle outside of xy boundary of parking ROI"; return false; } return true; } bool OpenSpaceRoiDecider::GetParkingSpot(Frame *const frame, std::array<Vec2d, 4> *vertices, Path *nearby_path) { const auto &routing_request = frame->local_view().routing->routing_request(); auto plot_type = routing_request.parking_info().parking_space_type(); if (frame == nullptr) { AERROR << "Invalid frame, fail to GetParkingSpotFromMap from frame. "; return false; } LaneInfoConstPtr nearest_lane; // Check if last frame lane is available const auto &ptr_last_frame = injector_->frame_history()->Latest(); if (ptr_last_frame == nullptr) { AERROR << "Last frame failed, fail to GetParkingSpotfrom frame " "history."; return false; } const auto &previous_open_space_info = ptr_last_frame->open_space_info(); const auto &parking_spot_id_string = frame->open_space_info().target_parking_spot_id(); if (previous_open_space_info.target_parking_lane() != nullptr && previous_open_space_info.target_parking_spot_id() == parking_spot_id_string) { nearest_lane = previous_open_space_info.target_parking_lane(); } else { hdmap::Id parking_spot_id = hdmap::MakeMapId(parking_spot_id_string); auto parking_spot = hdmap_->GetParkingSpaceById(parking_spot_id); if (nullptr == parking_spot) { AERROR << "The parking spot id is invalid!"; return false; } auto parking_space = parking_spot->parking_space(); auto overlap_ids = parking_space.overlap_id(); if (overlap_ids.empty()) { AERROR << "There is no lane overlaps with the parking spot: " << parking_spot_id_string; return false; } std::vector<routing::LaneSegment> lane_segments; GetAllLaneSegments(*(frame->local_view().routing), &lane_segments); bool has_found_nearest_lane = false; size_t nearest_lane_index = 0; for (auto id : overlap_ids) { auto overlaps = hdmap_->GetOverlapById(id)->overlap(); for (auto object : overlaps.object()) { if (!object.has_lane_overlap_info()) { continue; } nearest_lane = hdmap_->GetLaneById(object.id()); if (nearest_lane == nullptr) { continue; } // Check if the lane is contained in the routing response. for (auto &segment : lane_segments) { if (segment.id() == nearest_lane->id().id()) { has_found_nearest_lane = true; break; } ++nearest_lane_index; } if (has_found_nearest_lane) { break; } } } if (!has_found_nearest_lane) { AERROR << "Cannot find the lane nearest to the parking spot when " "GetParkingSpot!"; } // Get the lane nearest to the current position of the vehicle. If the // vehicle has not reached the nearest lane to the parking spot, set the // lane nearest to the vehicle as "nearest_lane". LaneInfoConstPtr nearest_lane_to_vehicle; auto point = common::util::PointFactory::ToPointENU(vehicle_state_); double vehicle_lane_s = 0.0; double vehicle_lane_l = 0.0; int status = hdmap_->GetNearestLaneWithHeading( point, 10.0, vehicle_state_.heading(), M_PI / 2.0, &nearest_lane_to_vehicle, &vehicle_lane_s, &vehicle_lane_l); if (status == 0) { size_t nearest_lane_to_vehicle_index = 0; bool has_found_nearest_lane_to_vehicle = false; for (auto &segment : lane_segments) { if (segment.id() == nearest_lane_to_vehicle->id().id()) { has_found_nearest_lane_to_vehicle = true; break; } ++nearest_lane_to_vehicle_index; } // The vehicle has not reached the nearest lane to the parking spot。 if (has_found_nearest_lane_to_vehicle && nearest_lane_to_vehicle_index < nearest_lane_index) { nearest_lane = nearest_lane_to_vehicle; } } } frame->mutable_open_space_info()->set_target_parking_lane(nearest_lane); // Find parking spot by getting nearestlane ParkingSpaceInfoConstPtr target_parking_spot = nullptr; LaneSegment nearest_lanesegment = LaneSegment(nearest_lane, nearest_lane->accumulate_s().front(), nearest_lane->accumulate_s().back()); std::vector<LaneSegment> segments_vector; int next_lanes_num = nearest_lane->lane().successor_id_size(); if (next_lanes_num != 0) { for (int i = 0; i < next_lanes_num; ++i) { auto next_lane_id = nearest_lane->lane().successor_id(i); segments_vector.push_back(nearest_lanesegment); auto next_lane = hdmap_->GetLaneById(next_lane_id); LaneSegment next_lanesegment = LaneSegment(next_lane, next_lane->accumulate_s().front(), next_lane->accumulate_s().back()); segments_vector.push_back(next_lanesegment); size_t succeed_lanes_num = next_lane->lane().successor_id_size(); if (succeed_lanes_num != 0) { for (size_t j = 0; j < succeed_lanes_num; j++) { auto succeed_lane_id = next_lane->lane().successor_id(j); auto succeed_lane = hdmap_->GetLaneById(succeed_lane_id); LaneSegment succeed_lanesegment = LaneSegment(succeed_lane, succeed_lane->accumulate_s().front(), succeed_lane->accumulate_s().back()); segments_vector.push_back(succeed_lanesegment); } } *nearby_path = Path(segments_vector); SearchTargetParkingSpotOnPath(*nearby_path, &target_parking_spot); if (target_parking_spot != nullptr) { break; } } } else { segments_vector.push_back(nearest_lanesegment); *nearby_path = Path(segments_vector); SearchTargetParkingSpotOnPath(*nearby_path, &target_parking_spot); } if (target_parking_spot == nullptr) { AERROR << "No such parking spot found after searching all path forward " "possible"; return false; } if (!CheckDistanceToParkingSpot(frame, *nearby_path, target_parking_spot)) { AERROR << "target parking spot found, but too far, distance larger than " "pre-defined distance"; return false; } // left or right of the parking lot is decided when viewing the parking spot // open upward ADEBUG << target_parking_spot->parking_space().DebugString(); auto parking_polygon = target_parking_spot->parking_space().polygon(); Vec2d left_top(parking_polygon.point(0).x(), parking_polygon.point(0).y()); Vec2d left_down(parking_polygon.point(3).x(), parking_polygon.point(3).y()); Vec2d right_down(parking_polygon.point(2).x(), parking_polygon.point(2).y()); Vec2d right_top(parking_polygon.point(1).x(), parking_polygon.point(1).y()); if (plot_type == ParkingSpaceType::PARALLEL_PARKING) { left_top.set_x(parking_polygon.point(3).x()); left_top.set_y(parking_polygon.point(3).y()); left_down.set_x(parking_polygon.point(2).x()); left_down.set_y(parking_polygon.point(2).y()); right_down.set_x(parking_polygon.point(1).x()); right_down.set_y(parking_polygon.point(1).y()); right_top.set_x(parking_polygon.point(0).x()); right_top.set_y(parking_polygon.point(0).y()); } std::array<Vec2d, 4> parking_vertices{left_top, left_down, right_down, right_top}; *vertices = std::move(parking_vertices); return true; } bool OpenSpaceRoiDecider::GetPullOverSpot( Frame *const frame, std::array<common::math::Vec2d, 4> *vertices, hdmap::Path *nearby_path) { const auto &pull_over_status = injector_->planning_context()->planning_status().pull_over(); if (!pull_over_status.has_position() || !pull_over_status.position().has_x() || !pull_over_status.position().has_y() || !pull_over_status.has_theta()) { AERROR << "Pull over position not set in planning context"; return false; } if (frame->reference_line_info().size() > 1) { AERROR << "Should not be in pull over when changing lane in open space " "planning"; return false; } *nearby_path = frame->reference_line_info().front().reference_line().GetMapPath(); // Construct left_top, left_down, right_down, right_top points double pull_over_x = pull_over_status.position().x(); double pull_over_y = pull_over_status.position().y(); const double pull_over_theta = pull_over_status.theta(); const double pull_over_length_front = pull_over_status.length_front(); const double pull_over_length_back = pull_over_status.length_back(); const double pull_over_width_left = pull_over_status.width_left(); const double pull_over_width_right = pull_over_status.width_right(); Vec2d center_shift_vec((pull_over_length_front - pull_over_length_back) * 0.5, (pull_over_width_left - pull_over_width_right) * 0.5); center_shift_vec.SelfRotate(pull_over_theta); pull_over_x += center_shift_vec.x(); pull_over_y += center_shift_vec.y(); const double half_length = (pull_over_length_front + pull_over_length_back) / 2.0; const double half_width = (pull_over_width_left + pull_over_width_right) / 2.0; const double cos_heading = std::cos(pull_over_theta); const double sin_heading = std::sin(pull_over_theta); const double dx1 = cos_heading * half_length; const double dy1 = sin_heading * half_length; const double dx2 = sin_heading * half_width; const double dy2 = -cos_heading * half_width; Vec2d left_top(pull_over_x - dx1 + dx2, pull_over_y - dy1 + dy2); Vec2d left_down(pull_over_x - dx1 - dx2, pull_over_y - dy1 - dy2); Vec2d right_down(pull_over_x + dx1 - dx2, pull_over_y + dy1 - dy2); Vec2d right_top(pull_over_x + dx1 + dx2, pull_over_y + dy1 + dy2); std::array<Vec2d, 4> pull_over_vertices{left_top, left_down, right_down, right_top}; *vertices = std::move(pull_over_vertices); return true; } void OpenSpaceRoiDecider::SearchTargetParkingSpotOnPath( const hdmap::Path &nearby_path, ParkingSpaceInfoConstPtr *target_parking_spot) { const auto &parking_space_overlaps = nearby_path.parking_space_overlaps(); for (const auto &parking_overlap : parking_space_overlaps) { if (parking_overlap.object_id == target_parking_spot_id_) { hdmap::Id id; id.set_id(parking_overlap.object_id); *target_parking_spot = hdmap_->GetParkingSpaceById(id); } } } bool OpenSpaceRoiDecider::CheckDistanceToParkingSpot( Frame *const frame, const hdmap::Path &nearby_path, const hdmap::ParkingSpaceInfoConstPtr &target_parking_spot) { const auto &routing_request = frame->local_view().routing->routing_request(); auto corner_point = routing_request.parking_info().corner_point(); Vec2d left_bottom_point = target_parking_spot->polygon().points().at(0); Vec2d right_bottom_point = target_parking_spot->polygon().points().at(1); left_bottom_point.set_x(corner_point.point().at(0).x()); left_bottom_point.set_y(corner_point.point().at(0).y()); right_bottom_point.set_x(corner_point.point().at(1).x()); right_bottom_point.set_y(corner_point.point().at(1).y()); double left_bottom_point_s = 0.0; double left_bottom_point_l = 0.0; double right_bottom_point_s = 0.0; double right_bottom_point_l = 0.0; double vehicle_point_s = 0.0; double vehicle_point_l = 0.0; nearby_path.GetNearestPoint(left_bottom_point, &left_bottom_point_s, &left_bottom_point_l); nearby_path.GetNearestPoint(right_bottom_point, &right_bottom_point_s, &right_bottom_point_l); Vec2d vehicle_vec(vehicle_state_.x(), vehicle_state_.y()); nearby_path.GetNearestPoint(vehicle_vec, &vehicle_point_s, &vehicle_point_l); if (std::abs((left_bottom_point_s + right_bottom_point_s) / 2 - vehicle_point_s) < config_.open_space_roi_decider_config().parking_start_range()) { return true; } else { return false; } } bool OpenSpaceRoiDecider::FuseLineSegments( std::vector<std::vector<common::math::Vec2d>> *line_segments_vec) { static constexpr double kEpsilon = 1.0e-8; auto cur_segment = line_segments_vec->begin(); while (cur_segment != line_segments_vec->end() - 1) { auto next_segment = cur_segment + 1; auto cur_last_point = cur_segment->back(); auto next_first_point = next_segment->front(); // Check if they are the same points if (cur_last_point.DistanceTo(next_first_point) > kEpsilon) { ++cur_segment; continue; } if (cur_segment->size() < 2 || next_segment->size() < 2) { AERROR << "Single point line_segments vec not expected"; return false; } size_t cur_segments_size = cur_segment->size(); auto cur_second_to_last_point = cur_segment->at(cur_segments_size - 2); auto next_second_point = next_segment->at(1); if (CrossProd(cur_second_to_last_point, cur_last_point, next_second_point) < 0.0) { cur_segment->push_back(next_second_point); next_segment->erase(next_segment->begin(), next_segment->begin() + 2); if (next_segment->empty()) { line_segments_vec->erase(next_segment); } } else { ++cur_segment; } } return true; } bool OpenSpaceRoiDecider::FormulateBoundaryConstraints( const std::vector<std::vector<common::math::Vec2d>> &roi_parking_boundary, Frame *const frame) { // Gather vertice needed by warm start and distance approach if (!LoadObstacleInVertices(roi_parking_boundary, frame)) { AERROR << "fail at LoadObstacleInVertices()"; return false; } // Transform vertices into the form of Ax>b if (!LoadObstacleInHyperPlanes(frame)) { AERROR << "fail at LoadObstacleInHyperPlanes()"; return false; } return true; } bool OpenSpaceRoiDecider::LoadObstacleInVertices( const std::vector<std::vector<common::math::Vec2d>> &roi_parking_boundary, Frame *const frame) { auto *mutable_open_space_info = frame->mutable_open_space_info(); const auto &open_space_info = frame->open_space_info(); auto *obstacles_vertices_vec = mutable_open_space_info->mutable_obstacles_vertices_vec(); auto *obstacles_edges_num_vec = mutable_open_space_info->mutable_obstacles_edges_num(); // load vertices for parking boundary (not need to repeat the first // vertice to get close hull) size_t parking_boundaries_num = roi_parking_boundary.size(); size_t perception_obstacles_num = 0; for (size_t i = 0; i < parking_boundaries_num; ++i) { obstacles_vertices_vec->push_back(roi_parking_boundary[i]); } Eigen::MatrixXi parking_boundaries_obstacles_edges_num(parking_boundaries_num, 1); for (size_t i = 0; i < parking_boundaries_num; i++) { CHECK_GT(roi_parking_boundary[i].size(), 1U); parking_boundaries_obstacles_edges_num(i, 0) = static_cast<int>(roi_parking_boundary[i].size()) - 1; } if (config_.open_space_roi_decider_config().enable_perception_obstacles()) { if (perception_obstacles_num == 0) { ADEBUG << "no obstacle given by perception"; } // load vertices for perception obstacles(repeat the first vertice at the // last to form closed convex hull) const auto &origin_point = open_space_info.origin_point(); const auto &origin_heading = open_space_info.origin_heading(); for (const auto &obstacle : obstacles_by_frame_->Items()) { if (FilterOutObstacle(*frame, *obstacle)) { continue; } ++perception_obstacles_num; Box2d original_box = obstacle->PerceptionBoundingBox(); original_box.Shift(-1.0 * origin_point); original_box.LongitudinalExtend( config_.open_space_roi_decider_config().perception_obstacle_buffer()); original_box.LateralExtend( config_.open_space_roi_decider_config().perception_obstacle_buffer()); // TODO(Jinyun): Check correctness of ExpandByDistance() in polygon // Polygon2d buffered_box(original_box); // buffered_box = buffered_box.ExpandByDistance( // config_.open_space_roi_decider_config().perception_obstacle_buffer()); // TODO(Runxin): Rotate from origin instead // original_box.RotateFromCenter(-1.0 * origin_heading); std::vector<Vec2d> vertices_ccw = original_box.GetAllCorners(); std::vector<Vec2d> vertices_cw; while (!vertices_ccw.empty()) { auto current_corner_pt = vertices_ccw.back(); current_corner_pt.SelfRotate(-1.0 * origin_heading); vertices_cw.push_back(current_corner_pt); vertices_ccw.pop_back(); } // As the perception obstacle is a closed convex set, the first vertice // is repeated at the end of the vector to help transform all four edges // to inequality constraint vertices_cw.push_back(vertices_cw.front()); obstacles_vertices_vec->push_back(vertices_cw); } // obstacle boundary box is used, thus the edges are set to be 4 Eigen::MatrixXi perception_obstacles_edges_num = 4 * Eigen::MatrixXi::Ones(perception_obstacles_num, 1); obstacles_edges_num_vec->resize( parking_boundaries_obstacles_edges_num.rows() + perception_obstacles_edges_num.rows(), 1); *(obstacles_edges_num_vec) << parking_boundaries_obstacles_edges_num, perception_obstacles_edges_num; } else { obstacles_edges_num_vec->resize( parking_boundaries_obstacles_edges_num.rows(), 1); *(obstacles_edges_num_vec) << parking_boundaries_obstacles_edges_num; } mutable_open_space_info->set_obstacles_num(parking_boundaries_num + perception_obstacles_num); return true; } bool OpenSpaceRoiDecider::FilterOutObstacle(const Frame &frame, const Obstacle &obstacle) { if (obstacle.IsVirtual()) { return true; } const auto &open_space_info = frame.open_space_info(); const auto &origin_point = open_space_info.origin_point(); const auto &origin_heading = open_space_info.origin_heading(); const auto &obstacle_box = obstacle.PerceptionBoundingBox(); auto obstacle_center_xy = obstacle_box.center(); // xy_boundary in xmin, xmax, ymin, ymax. const auto &roi_xy_boundary = open_space_info.ROI_xy_boundary(); obstacle_center_xy -= origin_point; obstacle_center_xy.SelfRotate(-origin_heading); if (obstacle_center_xy.x() < roi_xy_boundary[0] || obstacle_center_xy.x() > roi_xy_boundary[1] || obstacle_center_xy.y() < roi_xy_boundary[2] || obstacle_center_xy.y() > roi_xy_boundary[3]) { return true; } // Translate the end pose back to world frame with endpose in x, y, phi, v const auto &end_pose = open_space_info.open_space_end_pose(); Vec2d end_pose_x_y(end_pose[0], end_pose[1]); end_pose_x_y.SelfRotate(origin_heading); end_pose_x_y += origin_point; // Get vehicle state Vec2d vehicle_x_y(vehicle_state_.x(), vehicle_state_.y()); // Use vehicle position and end position to filter out obstacle const double vehicle_center_to_obstacle = obstacle_box.DistanceTo(vehicle_x_y); const double end_pose_center_to_obstacle = obstacle_box.DistanceTo(end_pose_x_y); const double filtering_distance = config_.open_space_roi_decider_config() .perception_obstacle_filtering_distance(); if (vehicle_center_to_obstacle > filtering_distance && end_pose_center_to_obstacle > filtering_distance) { return true; } return false; } bool OpenSpaceRoiDecider::LoadObstacleInHyperPlanes(Frame *const frame) { *(frame->mutable_open_space_info()->mutable_obstacles_A()) = Eigen::MatrixXd::Zero( frame->open_space_info().obstacles_edges_num().sum(), 2); *(frame->mutable_open_space_info()->mutable_obstacles_b()) = Eigen::MatrixXd::Zero( frame->open_space_info().obstacles_edges_num().sum(), 1); // vertices using H-representation if (!GetHyperPlanes( frame->open_space_info().obstacles_num(), frame->open_space_info().obstacles_edges_num(), frame->open_space_info().obstacles_vertices_vec(), frame->mutable_open_space_info()->mutable_obstacles_A(), frame->mutable_open_space_info()->mutable_obstacles_b())) { AERROR << "Fail to present obstacle in hyperplane"; return false; } return true; } bool OpenSpaceRoiDecider::GetHyperPlanes( const size_t &obstacles_num, const Eigen::MatrixXi &obstacles_edges_num, const std::vector<std::vector<Vec2d>> &obstacles_vertices_vec, Eigen::MatrixXd *A_all, Eigen::MatrixXd *b_all) { if (obstacles_num != obstacles_vertices_vec.size()) { AERROR << "obstacles_num != obstacles_vertices_vec.size()"; return false; } A_all->resize(obstacles_edges_num.sum(), 2); b_all->resize(obstacles_edges_num.sum(), 1); int counter = 0; double kEpsilon = 1.0e-5; // start building H representation for (size_t i = 0; i < obstacles_num; ++i) { size_t current_vertice_num = obstacles_edges_num(i, 0); Eigen::MatrixXd A_i(current_vertice_num, 2); Eigen::MatrixXd b_i(current_vertice_num, 1); // take two subsequent vertices, and computer hyperplane for (size_t j = 0; j < current_vertice_num; ++j) { Vec2d v1 = obstacles_vertices_vec[i][j]; Vec2d v2 = obstacles_vertices_vec[i][j + 1]; Eigen::MatrixXd A_tmp(2, 1), b_tmp(1, 1), ab(2, 1); // find hyperplane passing through v1 and v2 if (std::abs(v1.x() - v2.x()) < kEpsilon) { if (v2.y() < v1.y()) { A_tmp << 1, 0; b_tmp << v1.x(); } else { A_tmp << -1, 0; b_tmp << -v1.x(); } } else if (std::abs(v1.y() - v2.y()) < kEpsilon) { if (v1.x() < v2.x()) { A_tmp << 0, 1; b_tmp << v1.y(); } else { A_tmp << 0, -1; b_tmp << -v1.y(); } } else { Eigen::MatrixXd tmp1(2, 2); tmp1 << v1.x(), 1, v2.x(), 1; Eigen::MatrixXd tmp2(2, 1); tmp2 << v1.y(), v2.y(); ab = tmp1.inverse() * tmp2; double a = ab(0, 0); double b = ab(1, 0); if (v1.x() < v2.x()) { A_tmp << -a, 1; b_tmp << b; } else { A_tmp << a, -1; b_tmp << -b; } } // store vertices A_i.block(j, 0, 1, 2) = A_tmp.transpose(); b_i.block(j, 0, 1, 1) = b_tmp; } A_all->block(counter, 0, A_i.rows(), 2) = A_i; b_all->block(counter, 0, b_i.rows(), 1) = b_i; counter += static_cast<int>(current_vertice_num); } return true; } bool OpenSpaceRoiDecider::IsInParkingLot( const double adc_init_x, const double adc_init_y, const double adc_init_heading, std::array<Vec2d, 4> *parking_lot_vertices) { std::vector<ParkingSpaceInfoConstPtr> parking_lots; // make sure there is only one parking lot in search range const double kDistance = 1.0; auto adc_parking_spot = common::util::PointFactory::ToPointENU(adc_init_x, adc_init_y, 0); ADEBUG << "IsInParkingLot"; ADEBUG << hdmap_; ADEBUG << hdmap_->GetParkingSpaces(adc_parking_spot, kDistance, &parking_lots); if (hdmap_->GetParkingSpaces(adc_parking_spot, kDistance, &parking_lots) == 0) { GetParkSpotFromMap(parking_lots.front(), parking_lot_vertices); return true; } return false; } void OpenSpaceRoiDecider::GetParkSpotFromMap( ParkingSpaceInfoConstPtr parking_lot, std::array<Vec2d, 4> *vertices) { // left or right of the parking lot is decided when viewing the parking spot // open upward Vec2d left_top = parking_lot->polygon().points().at(3); Vec2d left_down = parking_lot->polygon().points().at(0); Vec2d right_down = parking_lot->polygon().points().at(1); Vec2d right_top = parking_lot->polygon().points().at(2); std::array<Vec2d, 4> parking_vertices{left_top, left_down, right_down, right_top}; *vertices = std::move(parking_vertices); Vec2d tmp = (*vertices)[0]; ADEBUG << "Parking Lot"; ADEBUG << "parking_lot_vertices: (" << tmp.x() << ", " << tmp.y() << ")"; } void OpenSpaceRoiDecider::GetAllLaneSegments( const routing::RoutingResponse &routing_response, std::vector<routing::LaneSegment> *routing_segments) { routing_segments->clear(); for (const auto &road : routing_response.road()) { for (const auto &passage : road.passage()) { for (const auto &segment : passage.segment()) { routing_segments->emplace_back(segment); } } } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_reuse_decider/path_reuse_decider_test.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/tasks/deciders/path_reuse_decider/path_reuse_decider.h" #include "gtest/gtest.h" #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { class PathReuseDeciderTest : public ::testing::Test { public: virtual void SetUp() { config_.set_task_type(TaskConfig::PATH_REUSE_DECIDER); config_.mutable_path_reuse_decider_config(); injector_ = std::make_shared<DependencyInjector>(); } virtual void TearDown() {} protected: TaskConfig config_; std::shared_ptr<DependencyInjector> injector_; }; TEST_F(PathReuseDeciderTest, Init) { PathReuseDecider path_reuse_decider(config_, injector_); EXPECT_EQ(path_reuse_decider.Name(), TaskConfig::TaskType_Name(config_.task_type())); } // TEST_F(PathReuseDeciderTest, GetHistoryStopPositions) { // PathReuseDecider path_reuse_decider(config_); // History* history = History::Instance(); // ADCTrajectory adc_trajectory; // EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile( // "/apollo/modules/planning/testdata/common/history_01.pb.txt", // &adc_trajectory)); // history->Add(adc_trajectory); // const std::vector<const HistoryObjectDecision*> // history_stop_objects_decisions = // history->GetLastFrame()->GetStopObjectDecisions(); // std::vector<const common::PointENU*> history_stop_positions; // path_reuse_decider.GetHistoryStopPositions(history_stop_objects_decisions, // &history_stop_positions); // common::PointENU stop_position; // double stop_x = 586261.33054620528; // double stop_y = 4141304.5678338786; // stop_position.set_x(stop_x); // stop_position.set_y(stop_y); // const common::PointENU* point = history_stop_positions[1]; // EXPECT_DOUBLE_EQ(point->x(), stop_position.x()); // EXPECT_DOUBLE_EQ(point->y(), stop_position.y()); // } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_reuse_decider/path_reuse_decider.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <memory> #include <utility> #include <vector> #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/history.h" #include "modules/planning/common/indexed_list.h" #include "modules/planning/common/obstacle_blocking_analyzer.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/tasks/deciders/decider.h" namespace apollo { namespace planning { class PathReuseDecider : public Decider { public: PathReuseDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); private: common::Status Process(Frame* frame, ReferenceLineInfo* reference_line_info) override; void GetCurrentStopPositions( Frame* frame, std::vector<const common::PointENU*>* current_stop_positions); // get current s_projection of history objects which has stop decisions void GetHistoryStopPositions( ReferenceLineInfo* const reference_line_info, const std::vector<const HistoryObjectDecision*>& history_objects_decisions, std::vector<std::pair<const double, const common::PointENU>>* history_stop_positions); void GetADCSLPoint(const ReferenceLine& reference_line, common::SLPoint* adc_position_sl); bool GetBlockingObstacleS(ReferenceLineInfo* const reference_line_info, double* blocking_obstacle_s); // ignore blocking obstacle when it is far away bool IsIgnoredBlockingObstacle(ReferenceLineInfo* const reference_line_info); // check if path is collision free bool IsCollisionFree(ReferenceLineInfo* const reference_line_info); // check path length bool NotShortPath(const DiscretizedPath& current_path); // trim history path bool TrimHistoryPath(Frame* frame, ReferenceLineInfo* const reference_line_info); private: static int reusable_path_counter_; // count reused path static int total_path_counter_; // count total path static bool path_reusable_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_reuse_decider/path_reuse_decider.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/path_reuse_decider/path_reuse_decider.h" #include <algorithm> #include <memory> #include <string> #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/planning/common/planning_context.h" namespace apollo { namespace planning { using apollo::common::Status; using apollo::common::math::Polygon2d; using apollo::common::math::Vec2d; int PathReuseDecider::reusable_path_counter_ = 0; int PathReuseDecider::total_path_counter_ = 0; bool PathReuseDecider::path_reusable_ = false; PathReuseDecider::PathReuseDecider( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Decider(config, injector) {} Status PathReuseDecider::Process(Frame* const frame, ReferenceLineInfo* const reference_line_info) { // Sanity checks. CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); if (!Decider::config_.path_reuse_decider_config().reuse_path()) { ADEBUG << "skipping reusing path: conf"; reference_line_info->set_path_reusable(false); return Status::OK(); } // skip path reuse if not in LANE_FOLLOW_SCENARIO const auto scenario_type = injector_->planning_context() ->planning_status() .scenario() .scenario_type(); if (scenario_type != ScenarioType::LANE_FOLLOW) { ADEBUG << "skipping reusing path: not in LANE_FOLLOW scenario"; reference_line_info->set_path_reusable(false); return Status::OK(); } // active path reuse during change_lane only auto* lane_change_status = injector_->planning_context() ->mutable_planning_status() ->mutable_change_lane(); ADEBUG << "lane change status: " << lane_change_status->ShortDebugString(); // skip path reuse if not in_change_lane if (lane_change_status->status() != ChangeLaneStatus::IN_CHANGE_LANE && !FLAGS_enable_reuse_path_in_lane_follow) { ADEBUG << "skipping reusing path: not in lane_change"; reference_line_info->set_path_reusable(false); return Status::OK(); } // for hybrid model: skip reuse path for valid path reference const bool valid_model_output = reference_line_info->path_data().is_valid_path_reference(); if (valid_model_output) { ADEBUG << "skipping reusing path: path reference is valid"; reference_line_info->set_path_reusable(false); return Status::OK(); } /*count total_path_ when in_change_lane && reuse_path*/ ++total_path_counter_; /*reuse path when in non_change_lane reference line or optimization succeeded in change_lane reference line */ bool is_change_lane_path = reference_line_info->IsChangeLanePath(); if (is_change_lane_path && !lane_change_status->is_current_opt_succeed()) { reference_line_info->set_path_reusable(false); ADEBUG << "reusable_path_counter[" << reusable_path_counter_ << "] total_path_counter[" << total_path_counter_ << "]"; ADEBUG << "Stop reusing path when optimization failed on change lane path"; return Status::OK(); } // stop reusing current path: // 1. replan path // 2. collision // 3. failed to trim previous path // 4. speed optimization failed on previous path bool speed_optimization_successful = false; const auto& history_frame = injector_->frame_history()->Latest(); if (history_frame) { const auto history_trajectory_type = history_frame->reference_line_info().front().trajectory_type(); speed_optimization_successful = (history_trajectory_type != ADCTrajectory::SPEED_FALLBACK); } // const auto history_trajectory_type = injector_->FrameHistory()s // ->Latest() // ->reference_line_info() // .front() // .trajectory_type(); if (path_reusable_) { if (!frame->current_frame_planned_trajectory().is_replan() && speed_optimization_successful && IsCollisionFree(reference_line_info) && TrimHistoryPath(frame, reference_line_info)) { ADEBUG << "reuse path"; ++reusable_path_counter_; // count reusable path } else { // stop reuse path ADEBUG << "stop reuse path"; path_reusable_ = false; } } else { // F -> T auto* mutable_path_decider_status = injector_->planning_context() ->mutable_planning_status() ->mutable_path_decider(); static constexpr int kWaitCycle = -2; // wait 2 cycle const int front_static_obstacle_cycle_counter = mutable_path_decider_status->front_static_obstacle_cycle_counter(); const bool ignore_blocking_obstacle = IsIgnoredBlockingObstacle(reference_line_info); ADEBUG << "counter[" << front_static_obstacle_cycle_counter << "] IsIgnoredBlockingObstacle[" << ignore_blocking_obstacle << "]"; // stop reusing current path: // 1. blocking obstacle disappeared or moving far away // 2. trimming successful // 3. no statical obstacle collision. if ((front_static_obstacle_cycle_counter <= kWaitCycle || ignore_blocking_obstacle) && speed_optimization_successful && IsCollisionFree(reference_line_info) && TrimHistoryPath(frame, reference_line_info)) { // enable reuse path ADEBUG << "reuse path: front_blocking_obstacle ignorable"; path_reusable_ = true; ++reusable_path_counter_; } } reference_line_info->set_path_reusable(path_reusable_); ADEBUG << "reusable_path_counter[" << reusable_path_counter_ << "] total_path_counter[" << total_path_counter_ << "]"; return Status::OK(); } bool PathReuseDecider::IsIgnoredBlockingObstacle( ReferenceLineInfo* const reference_line_info) { const ReferenceLine& reference_line = reference_line_info->reference_line(); static constexpr double kSDistBuffer = 30.0; // meter static constexpr int kTimeBuffer = 3; // second // vehicle speed double adc_speed = injector_->vehicle_state()->linear_velocity(); double final_s_buffer = std::max(kSDistBuffer, kTimeBuffer * adc_speed); // current vehicle s position common::SLPoint adc_position_sl; GetADCSLPoint(reference_line, &adc_position_sl); // blocking obstacle start s double blocking_obstacle_start_s; if (GetBlockingObstacleS(reference_line_info, &blocking_obstacle_start_s) && // distance to blocking obstacle (blocking_obstacle_start_s - adc_position_sl.s() > final_s_buffer)) { ADEBUG << "blocking obstacle distance: " << blocking_obstacle_start_s - adc_position_sl.s(); return true; } else { return false; } } bool PathReuseDecider::GetBlockingObstacleS( ReferenceLineInfo* const reference_line_info, double* blocking_obstacle_s) { auto* mutable_path_decider_status = injector_->planning_context() ->mutable_planning_status() ->mutable_path_decider(); // get blocking obstacle ID (front_static_obstacle_id) const std::string& blocking_obstacle_ID = mutable_path_decider_status->front_static_obstacle_id(); const IndexedList<std::string, Obstacle>& indexed_obstacles = reference_line_info->path_decision()->obstacles(); const auto* blocking_obstacle = indexed_obstacles.Find(blocking_obstacle_ID); if (blocking_obstacle == nullptr) { return false; } const auto& obstacle_sl = blocking_obstacle->PerceptionSLBoundary(); *blocking_obstacle_s = obstacle_sl.start_s(); ADEBUG << "blocking obstacle distance: " << obstacle_sl.start_s(); return true; } void PathReuseDecider::GetADCSLPoint(const ReferenceLine& reference_line, common::SLPoint* adc_position_sl) { common::math::Vec2d adc_position = {injector_->vehicle_state()->x(), injector_->vehicle_state()->y()}; reference_line.XYToSL(adc_position, adc_position_sl); } bool PathReuseDecider::IsCollisionFree( ReferenceLineInfo* const reference_line_info) { const ReferenceLine& reference_line = reference_line_info->reference_line(); static constexpr double kMinObstacleArea = 1e-4; const double kSBuffer = 0.5; static constexpr int kNumExtraTailBoundPoint = 21; static constexpr double kPathBoundsDeciderResolution = 0.5; // current vehicle sl position common::SLPoint adc_position_sl; GetADCSLPoint(reference_line, &adc_position_sl); // current obstacles std::vector<Polygon2d> obstacle_polygons; for (auto obstacle : reference_line_info->path_decision()->obstacles().Items()) { // filtered all non-static objects and virtual obstacle if (!obstacle->IsStatic() || obstacle->IsVirtual()) { if (!obstacle->IsStatic()) { ADEBUG << "SPOT a dynamic obstacle"; } if (obstacle->IsVirtual()) { ADEBUG << "SPOT a virtual obstacle"; } continue; } const auto& obstacle_sl = obstacle->PerceptionSLBoundary(); // Ignore obstacles behind ADC if ((obstacle_sl.end_s() < adc_position_sl.s() - kSBuffer) || // Ignore too small obstacles. (obstacle_sl.end_s() - obstacle_sl.start_s()) * (obstacle_sl.end_l() - obstacle_sl.start_l()) < kMinObstacleArea) { continue; } obstacle_polygons.push_back( Polygon2d({Vec2d(obstacle_sl.start_s(), obstacle_sl.start_l()), Vec2d(obstacle_sl.start_s(), obstacle_sl.end_l()), Vec2d(obstacle_sl.end_s(), obstacle_sl.end_l()), Vec2d(obstacle_sl.end_s(), obstacle_sl.start_l())})); } if (obstacle_polygons.empty()) { return true; } const auto& history_frame = injector_->frame_history()->Latest(); if (!history_frame) { return false; } const DiscretizedPath& history_path = history_frame->current_frame_planned_path(); // path end point common::SLPoint path_end_position_sl; common::math::Vec2d path_end_position = {history_path.back().x(), history_path.back().y()}; reference_line.XYToSL(path_end_position, &path_end_position_sl); for (size_t i = 0; i < history_path.size(); ++i) { common::SLPoint path_position_sl; common::math::Vec2d path_position = {history_path[i].x(), history_path[i].y()}; reference_line.XYToSL(path_position, &path_position_sl); if (path_end_position_sl.s() - path_position_sl.s() <= kNumExtraTailBoundPoint * kPathBoundsDeciderResolution) { break; } if (path_position_sl.s() < adc_position_sl.s() - kSBuffer) { continue; } const auto& vehicle_box = common::VehicleConfigHelper::Instance()->GetBoundingBox( history_path[i]); std::vector<Vec2d> ABCDpoints = vehicle_box.GetAllCorners(); for (const auto& corner_point : ABCDpoints) { // For each corner point, project it onto reference_line common::SLPoint curr_point_sl; if (!reference_line.XYToSL(corner_point, &curr_point_sl)) { AERROR << "Failed to get the projection from point onto " "reference_line"; return false; } auto curr_point = Vec2d(curr_point_sl.s(), curr_point_sl.l()); // Check if it's in any polygon of other static obstacles. for (const auto& obstacle_polygon : obstacle_polygons) { if (obstacle_polygon.IsPointIn(curr_point)) { // for debug ADEBUG << "s distance to end point:" << path_end_position_sl.s(); ADEBUG << "s distance to end point:" << path_position_sl.s(); ADEBUG << "[" << i << "]" << ", history_path[i].x(): " << std::setprecision(9) << history_path[i].x() << ", history_path[i].y()" << std::setprecision(9) << history_path[i].y(); ADEBUG << "collision:" << curr_point.x() << ", " << curr_point.y(); Vec2d xy_point; reference_line.SLToXY(curr_point_sl, &xy_point); ADEBUG << "collision:" << xy_point.x() << ", " << xy_point.y(); return false; } } } } return true; } // check the length of the path bool PathReuseDecider::NotShortPath(const DiscretizedPath& current_path) { // TODO(shu): use gflag static constexpr double kShortPathThreshold = 60; return current_path.size() >= kShortPathThreshold; } bool PathReuseDecider::TrimHistoryPath( Frame* frame, ReferenceLineInfo* const reference_line_info) { const ReferenceLine& reference_line = reference_line_info->reference_line(); const auto& history_frame = injector_->frame_history()->Latest(); if (!history_frame) { ADEBUG << "no history frame"; return false; } const common::TrajectoryPoint history_planning_start_point = history_frame->PlanningStartPoint(); common::PathPoint history_init_path_point = history_planning_start_point.path_point(); ADEBUG << "history_init_path_point x:[" << std::setprecision(9) << history_init_path_point.x() << "], y[" << history_init_path_point.y() << "], s: [" << history_init_path_point.s() << "]"; const common::TrajectoryPoint planning_start_point = frame->PlanningStartPoint(); common::PathPoint init_path_point = planning_start_point.path_point(); ADEBUG << "init_path_point x:[" << std::setprecision(9) << init_path_point.x() << "], y[" << init_path_point.y() << "], s: [" << init_path_point.s() << "]"; const DiscretizedPath& history_path = history_frame->current_frame_planned_path(); DiscretizedPath trimmed_path; common::SLPoint adc_position_sl; // current vehicle sl position GetADCSLPoint(reference_line, &adc_position_sl); ADEBUG << "adc_position_sl.s(): " << adc_position_sl.s(); size_t path_start_index = 0; for (size_t i = 0; i < history_path.size(); ++i) { // find previous init point if (history_path[i].s() > 0) { path_start_index = i; break; } } ADEBUG << "!!!path_start_index[" << path_start_index << "]"; // get current s=0 common::SLPoint init_path_position_sl; reference_line.XYToSL(init_path_point, &init_path_position_sl); bool inserted_init_point = false; for (size_t i = path_start_index; i < history_path.size(); ++i) { common::SLPoint path_position_sl; common::math::Vec2d path_position = {history_path[i].x(), history_path[i].y()}; reference_line.XYToSL(path_position, &path_position_sl); double updated_s = path_position_sl.s() - init_path_position_sl.s(); // insert init point if (updated_s > 0 && !inserted_init_point) { trimmed_path.emplace_back(init_path_point); trimmed_path.back().set_s(0); inserted_init_point = true; } trimmed_path.emplace_back(history_path[i]); // if (i < 50) { // ADEBUG << "path_point:[" << i << "]" << updated_s; // path_position_sl.s(); // ADEBUG << std::setprecision(9) << "path_point:[" << i << "]" // << "x: [" << history_path[i].x() << "], y:[" << // history_path[i].y() // << "]. s[" << history_path[i].s() << "]"; // } trimmed_path.back().set_s(updated_s); } ADEBUG << "trimmed_path[0]: " << trimmed_path.front().s(); ADEBUG << "[END] trimmed_path.size(): " << trimmed_path.size(); if (!NotShortPath(trimmed_path)) { ADEBUG << "short path: " << trimmed_path.size(); return false; } // set path auto path_data = reference_line_info->mutable_path_data(); ADEBUG << "previous path_data size: " << history_path.size(); path_data->SetReferenceLine(&reference_line); ADEBUG << "previous path_data size: " << path_data->discretized_path().size(); path_data->SetDiscretizedPath(DiscretizedPath(std::move(trimmed_path))); ADEBUG << "not short path: " << trimmed_path.size(); ADEBUG << "current path size: " << reference_line_info->path_data().discretized_path().size(); return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_reuse_decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "path_reuse_decider", srcs = ["path_reuse_decider.cc"], hdrs = ["path_reuse_decider.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/planning/common:history", "//modules/planning/common:obstacle_blocking_analyzer", "//modules/planning/common:planning_context", "//modules/planning/common:planning_gflags", "//modules/planning/common:reference_line_info", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/tasks/deciders:decider_base", ], ) cc_test( name = "path_reuse_decider_test", size = "small", srcs = ["path_reuse_decider_test.cc"], deps = [ "path_reuse_decider", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/speed_bounds_decider/st_boundary_mapper_test.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/tasks/deciders/speed_bounds_decider/st_boundary_mapper.h" #include "cyber/common/log.h" #include "gmock/gmock.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/reference_line/qp_spline_reference_line_smoother.h" #include "modules/planning/tasks/deciders/speed_bounds_decider/speed_limit_decider.h" namespace apollo { namespace planning { class StBoundaryMapperTest : public ::testing::Test { public: virtual void SetUp() { hdmap_.LoadMapFromFile(map_file); const std::string lane_id = "1_-1"; lane_info_ptr = hdmap_.GetLaneById(hdmap::MakeMapId(lane_id)); if (!lane_info_ptr) { AERROR << "failed to find lane " << lane_id << " from map " << map_file; return; } ReferenceLineSmootherConfig config; injector_ = std::make_shared<DependencyInjector>(); std::vector<ReferencePoint> ref_points; const auto& points = lane_info_ptr->points(); const auto& headings = lane_info_ptr->headings(); const auto& accumulate_s = lane_info_ptr->accumulate_s(); for (size_t i = 0; i < points.size(); ++i) { std::vector<hdmap::LaneWaypoint> waypoint; waypoint.emplace_back(lane_info_ptr, accumulate_s[i]); hdmap::MapPathPoint map_path_point(points[i], headings[i], waypoint); ref_points.emplace_back(map_path_point, 0.0, 0.0); } reference_line_.reset(new ReferenceLine(ref_points)); vehicle_position_ = points[0]; path_data_.SetReferenceLine(reference_line_.get()); std::vector<common::FrenetFramePoint> ff_points; for (int i = 0; i < 100; ++i) { common::FrenetFramePoint ff_point; ff_point.set_s(i * 1.0); ff_point.set_l(0.1); ff_points.push_back(std::move(ff_point)); } frenet_frame_path_ = FrenetFramePath(std::move(ff_points)); path_data_.SetFrenetPath(std::move(frenet_frame_path_)); } protected: const std::string map_file = "modules/planning/testdata/garage_map/base_map.txt"; hdmap::HDMap hdmap_; common::math::Vec2d vehicle_position_; std::unique_ptr<ReferenceLine> reference_line_; hdmap::LaneInfoConstPtr lane_info_ptr = nullptr; PathData path_data_; FrenetFramePath frenet_frame_path_; std::shared_ptr<DependencyInjector> injector_; }; TEST_F(StBoundaryMapperTest, check_overlap_test) { SpeedBoundsDeciderConfig config; double planning_distance = 70.0; double planning_time = 10.0; STBoundaryMapper mapper(config, *reference_line_, path_data_, planning_distance, planning_time, injector_); common::PathPoint path_point; path_point.set_x(1.0); path_point.set_y(1.0); common::math::Box2d box(common::math::Vec2d(1.0, 1.0), 0.0, 5.0, 3.0); EXPECT_TRUE(mapper.CheckOverlap(path_point, box, 0.0)); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/speed_bounds_decider/st_boundary_mapper.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <memory> #include <string> #include <vector> #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/status/status.h" #include "modules/planning/common/dependency_injector.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/path/path_data.h" #include "modules/planning/common/path_decision.h" #include "modules/planning/common/speed/st_boundary.h" #include "modules/planning/common/speed_limit.h" #include "modules/planning/proto/task_config.pb.h" #include "modules/planning/reference_line/reference_line.h" namespace apollo { namespace planning { class STBoundaryMapper { public: STBoundaryMapper(const SpeedBoundsDeciderConfig& config, const ReferenceLine& reference_line, const PathData& path_data, const double planning_distance, const double planning_time, const std::shared_ptr<DependencyInjector>& injector); virtual ~STBoundaryMapper() = default; common::Status ComputeSTBoundary(PathDecision* path_decision) const; private: FRIEND_TEST(StBoundaryMapperTest, check_overlap_test); /** @brief Calls GetOverlapBoundaryPoints to get upper and lower points * for a given obstacle, and then formulate STBoundary based on that. * It also labels boundary type based on previously documented decisions. */ void ComputeSTBoundary(Obstacle* obstacle) const; /** @brief Map the given obstacle onto the ST-Graph. The boundary is * represented as upper and lower points for every s of interests. * Note that upper_points.size() = lower_points.size() */ bool GetOverlapBoundaryPoints( const std::vector<common::PathPoint>& path_points, const Obstacle& obstacle, std::vector<STPoint>* upper_points, std::vector<STPoint>* lower_points) const; /** @brief Given a path-point and an obstacle bounding box, check if the * ADC, when at that path-point, will collide with the obstacle. * @param The path-point of the center of rear-axis for ADC. * @param The bounding box of the obstacle. * @param The extra lateral buffer for our ADC. */ bool CheckOverlap(const common::PathPoint& path_point, const common::math::Box2d& obs_box, const double l_buffer) const; /** @brief Maps the closest STOP decision onto the ST-graph. This STOP * decision can be stopping for blocking obstacles, or can be due to * traffic rules, etc. */ bool MapStopDecision(Obstacle* stop_obstacle, const ObjectDecisionType& decision) const; /** @brief Fine-tune the boundary for yielding or overtaking obstacles. * Increase boundary on the s-dimension or set the boundary type, etc., * when necessary. */ void ComputeSTBoundaryWithDecision(Obstacle* obstacle, const ObjectDecisionType& decision) const; private: const SpeedBoundsDeciderConfig& speed_bounds_config_; const ReferenceLine& reference_line_; const PathData& path_data_; const common::VehicleParam& vehicle_param_; const double planning_max_distance_; const double planning_max_time_; std::shared_ptr<DependencyInjector> injector_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/speed_bounds_decider/st_boundary_mapper.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/speed_bounds_decider/st_boundary_mapper.h" #include <algorithm> #include <limits> #include <memory> #include <utility> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common_msgs/planning_msgs/decision.pb.h" #include "cyber/common/log.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/line_segment2d.h" #include "modules/common/math/vec2d.h" #include "modules/common/util/string_util.h" #include "modules/common/util/util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::PathPoint; using apollo::common::Status; using apollo::common::math::Box2d; using apollo::common::math::Vec2d; STBoundaryMapper::STBoundaryMapper( const SpeedBoundsDeciderConfig& config, const ReferenceLine& reference_line, const PathData& path_data, const double planning_distance, const double planning_time, const std::shared_ptr<DependencyInjector>& injector) : speed_bounds_config_(config), reference_line_(reference_line), path_data_(path_data), vehicle_param_(common::VehicleConfigHelper::GetConfig().vehicle_param()), planning_max_distance_(planning_distance), planning_max_time_(planning_time), injector_(injector) {} Status STBoundaryMapper::ComputeSTBoundary(PathDecision* path_decision) const { // Sanity checks. CHECK_GT(planning_max_time_, 0.0); if (path_data_.discretized_path().size() < 2) { AERROR << "Fail to get params because of too few path points. path points " "size: " << path_data_.discretized_path().size() << "."; return Status(ErrorCode::PLANNING_ERROR, "Fail to get params because of too few path points"); } // Go through every obstacle. Obstacle* stop_obstacle = nullptr; ObjectDecisionType stop_decision; double min_stop_s = std::numeric_limits<double>::max(); for (const auto* ptr_obstacle_item : path_decision->obstacles().Items()) { Obstacle* ptr_obstacle = path_decision->Find(ptr_obstacle_item->Id()); ACHECK(ptr_obstacle != nullptr); // If no longitudinal decision has been made, then plot it onto ST-graph. if (!ptr_obstacle->HasLongitudinalDecision()) { ComputeSTBoundary(ptr_obstacle); continue; } // If there is a longitudinal decision, then fine-tune boundary. const auto& decision = ptr_obstacle->LongitudinalDecision(); if (decision.has_stop()) { // 1. Store the closest stop fence info. // TODO(all): store ref. s value in stop decision; refine the code then. common::SLPoint stop_sl_point; reference_line_.XYToSL(decision.stop().stop_point(), &stop_sl_point); const double stop_s = stop_sl_point.s(); if (stop_s < min_stop_s) { stop_obstacle = ptr_obstacle; min_stop_s = stop_s; stop_decision = decision; } } else if (decision.has_follow() || decision.has_overtake() || decision.has_yield()) { // 2. Depending on the longitudinal overtake/yield decision, // fine-tune the upper/lower st-boundary of related obstacles. ComputeSTBoundaryWithDecision(ptr_obstacle, decision); } else if (!decision.has_ignore()) { // 3. Ignore those unrelated obstacles. AWARN << "No mapping for decision: " << decision.DebugString(); } } if (stop_obstacle) { bool success = MapStopDecision(stop_obstacle, stop_decision); if (!success) { const std::string msg = "Fail to MapStopDecision."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } } return Status::OK(); } bool STBoundaryMapper::MapStopDecision( Obstacle* stop_obstacle, const ObjectDecisionType& stop_decision) const { DCHECK(stop_decision.has_stop()) << "Must have stop decision"; common::SLPoint stop_sl_point; reference_line_.XYToSL(stop_decision.stop().stop_point(), &stop_sl_point); double st_stop_s = 0.0; const double stop_ref_s = stop_sl_point.s() - vehicle_param_.front_edge_to_center(); if (stop_ref_s > path_data_.frenet_frame_path().back().s()) { st_stop_s = path_data_.discretized_path().back().s() + (stop_ref_s - path_data_.frenet_frame_path().back().s()); } else { PathPoint stop_point; if (!path_data_.GetPathPointWithRefS(stop_ref_s, &stop_point)) { return false; } st_stop_s = stop_point.s(); } const double s_min = std::fmax(0.0, st_stop_s); const double s_max = std::fmax( s_min, std::fmax(planning_max_distance_, reference_line_.Length())); std::vector<std::pair<STPoint, STPoint>> point_pairs; point_pairs.emplace_back(STPoint(s_min, 0.0), STPoint(s_max, 0.0)); point_pairs.emplace_back( STPoint(s_min, planning_max_time_), STPoint(s_max + speed_bounds_config_.boundary_buffer(), planning_max_time_)); auto boundary = STBoundary(point_pairs); boundary.SetBoundaryType(STBoundary::BoundaryType::STOP); boundary.SetCharacteristicLength(speed_bounds_config_.boundary_buffer()); boundary.set_id(stop_obstacle->Id()); stop_obstacle->set_path_st_boundary(boundary); return true; } void STBoundaryMapper::ComputeSTBoundary(Obstacle* obstacle) const { if (FLAGS_use_st_drivable_boundary) { return; } std::vector<STPoint> lower_points; std::vector<STPoint> upper_points; if (!GetOverlapBoundaryPoints(path_data_.discretized_path(), *obstacle, &upper_points, &lower_points)) { return; } auto boundary = STBoundary::CreateInstance(lower_points, upper_points); boundary.set_id(obstacle->Id()); // TODO(all): potential bug here. const auto& prev_st_boundary = obstacle->path_st_boundary(); const auto& ref_line_st_boundary = obstacle->reference_line_st_boundary(); if (!prev_st_boundary.IsEmpty()) { boundary.SetBoundaryType(prev_st_boundary.boundary_type()); } else if (!ref_line_st_boundary.IsEmpty()) { boundary.SetBoundaryType(ref_line_st_boundary.boundary_type()); } obstacle->set_path_st_boundary(boundary); } bool STBoundaryMapper::GetOverlapBoundaryPoints( const std::vector<PathPoint>& path_points, const Obstacle& obstacle, std::vector<STPoint>* upper_points, std::vector<STPoint>* lower_points) const { // Sanity checks. DCHECK(upper_points->empty()); DCHECK(lower_points->empty()); if (path_points.empty()) { AERROR << "No points in path_data_.discretized_path()."; return false; } const auto* planning_status = injector_->planning_context() ->mutable_planning_status() ->mutable_change_lane(); double l_buffer = planning_status->status() == ChangeLaneStatus::IN_CHANGE_LANE ? FLAGS_lane_change_obstacle_nudge_l_buffer : FLAGS_nonstatic_obstacle_nudge_l_buffer; // Draw the given obstacle on the ST-graph. const auto& trajectory = obstacle.Trajectory(); if (trajectory.trajectory_point().empty()) { // For those with no predicted trajectories, just map the obstacle's // current position to ST-graph and always assume it's static. if (!obstacle.IsStatic()) { AWARN << "Non-static obstacle[" << obstacle.Id() << "] has NO prediction trajectory." << obstacle.Perception().ShortDebugString(); } for (const auto& curr_point_on_path : path_points) { if (curr_point_on_path.s() > planning_max_distance_) { break; } const Box2d& obs_box = obstacle.PerceptionBoundingBox(); if (CheckOverlap(curr_point_on_path, obs_box, l_buffer)) { // If there is overlapping, then plot it on ST-graph. const double backward_distance = -vehicle_param_.front_edge_to_center(); const double forward_distance = obs_box.length(); double low_s = std::fmax(0.0, curr_point_on_path.s() + backward_distance); double high_s = std::fmin(planning_max_distance_, curr_point_on_path.s() + forward_distance); // It is an unrotated rectangle appearing on the ST-graph. // TODO(jiacheng): reconsider the backward_distance, it might be // unnecessary, but forward_distance is indeed meaningful though. lower_points->emplace_back(low_s, 0.0); lower_points->emplace_back(low_s, planning_max_time_); upper_points->emplace_back(high_s, 0.0); upper_points->emplace_back(high_s, planning_max_time_); break; } } } else { // For those with predicted trajectories (moving obstacles): // 1. Subsample to reduce computation time. const int default_num_point = 50; DiscretizedPath discretized_path; if (path_points.size() > 2 * default_num_point) { const auto ratio = path_points.size() / default_num_point; std::vector<PathPoint> sampled_path_points; for (size_t i = 0; i < path_points.size(); ++i) { if (i % ratio == 0) { sampled_path_points.push_back(path_points[i]); } } discretized_path = DiscretizedPath(std::move(sampled_path_points)); } else { discretized_path = DiscretizedPath(path_points); } // 2. Go through every point of the predicted obstacle trajectory. for (int i = 0; i < trajectory.trajectory_point_size(); ++i) { const auto& trajectory_point = trajectory.trajectory_point(i); const Box2d obs_box = obstacle.GetBoundingBox(trajectory_point); double trajectory_point_time = trajectory_point.relative_time(); static constexpr double kNegtiveTimeThreshold = -1.0; if (trajectory_point_time < kNegtiveTimeThreshold) { continue; } const double step_length = vehicle_param_.front_edge_to_center(); auto path_len = std::min(FLAGS_max_trajectory_len, discretized_path.Length()); // Go through every point of the ADC's path. for (double path_s = 0.0; path_s < path_len; path_s += step_length) { const auto curr_adc_path_point = discretized_path.Evaluate(path_s + discretized_path.front().s()); if (CheckOverlap(curr_adc_path_point, obs_box, l_buffer)) { // Found overlap, start searching with higher resolution const double backward_distance = -step_length; const double forward_distance = vehicle_param_.length() + vehicle_param_.width() + obs_box.length() + obs_box.width(); const double default_min_step = 0.1; // in meters const double fine_tuning_step_length = std::fmin( default_min_step, discretized_path.Length() / default_num_point); bool find_low = false; bool find_high = false; double low_s = std::fmax(0.0, path_s + backward_distance); double high_s = std::fmin(discretized_path.Length(), path_s + forward_distance); // Keep shrinking by the resolution bidirectionally until finally // locating the tight upper and lower bounds. while (low_s < high_s) { if (find_low && find_high) { break; } if (!find_low) { const auto& point_low = discretized_path.Evaluate( low_s + discretized_path.front().s()); if (!CheckOverlap(point_low, obs_box, l_buffer)) { low_s += fine_tuning_step_length; } else { find_low = true; } } if (!find_high) { const auto& point_high = discretized_path.Evaluate( high_s + discretized_path.front().s()); if (!CheckOverlap(point_high, obs_box, l_buffer)) { high_s -= fine_tuning_step_length; } else { find_high = true; } } } if (find_high && find_low) { lower_points->emplace_back( low_s - speed_bounds_config_.point_extension(), trajectory_point_time); upper_points->emplace_back( high_s + speed_bounds_config_.point_extension(), trajectory_point_time); } break; } } } } // Sanity checks and return. DCHECK_EQ(lower_points->size(), upper_points->size()); return (lower_points->size() > 1 && upper_points->size() > 1); } void STBoundaryMapper::ComputeSTBoundaryWithDecision( Obstacle* obstacle, const ObjectDecisionType& decision) const { DCHECK(decision.has_follow() || decision.has_yield() || decision.has_overtake()) << "decision is " << decision.DebugString() << ", but it must be follow or yield or overtake."; std::vector<STPoint> lower_points; std::vector<STPoint> upper_points; if (FLAGS_use_st_drivable_boundary && obstacle->is_path_st_boundary_initialized()) { const auto& path_st_boundary = obstacle->path_st_boundary(); lower_points = path_st_boundary.lower_points(); upper_points = path_st_boundary.upper_points(); } else { if (!GetOverlapBoundaryPoints(path_data_.discretized_path(), *obstacle, &upper_points, &lower_points)) { return; } } auto boundary = STBoundary::CreateInstance(lower_points, upper_points); // get characteristic_length and boundary_type. STBoundary::BoundaryType b_type = STBoundary::BoundaryType::UNKNOWN; double characteristic_length = 0.0; if (decision.has_follow()) { characteristic_length = std::fabs(decision.follow().distance_s()); b_type = STBoundary::BoundaryType::FOLLOW; } else if (decision.has_yield()) { characteristic_length = std::fabs(decision.yield().distance_s()); boundary = STBoundary::CreateInstance(lower_points, upper_points) .ExpandByS(characteristic_length); b_type = STBoundary::BoundaryType::YIELD; } else if (decision.has_overtake()) { characteristic_length = std::fabs(decision.overtake().distance_s()); b_type = STBoundary::BoundaryType::OVERTAKE; } else { DCHECK(false) << "Obj decision should be either yield or overtake: " << decision.DebugString(); } boundary.SetBoundaryType(b_type); boundary.set_id(obstacle->Id()); boundary.SetCharacteristicLength(characteristic_length); obstacle->set_path_st_boundary(boundary); } bool STBoundaryMapper::CheckOverlap(const PathPoint& path_point, const Box2d& obs_box, const double l_buffer) const { // Convert reference point from center of rear axis to center of ADC. Vec2d ego_center_map_frame((vehicle_param_.front_edge_to_center() - vehicle_param_.back_edge_to_center()) * 0.5, (vehicle_param_.left_edge_to_center() - vehicle_param_.right_edge_to_center()) * 0.5); ego_center_map_frame.SelfRotate(path_point.theta()); ego_center_map_frame.set_x(ego_center_map_frame.x() + path_point.x()); ego_center_map_frame.set_y(ego_center_map_frame.y() + path_point.y()); // Compute the ADC bounding box. Box2d adc_box(ego_center_map_frame, path_point.theta(), vehicle_param_.length(), vehicle_param_.width() + l_buffer * 2); // Check whether ADC bounding box overlaps with obstacle bounding box. return obs_box.HasOverlap(adc_box); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/speed_bounds_decider/speed_limit_decider.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <string> #include <vector> #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/status/status.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/path/path_data.h" #include "modules/planning/common/speed_limit.h" #include "modules/planning/proto/task_config.pb.h" #include "modules/planning/reference_line/reference_line.h" namespace apollo { namespace planning { class SpeedLimitDecider { public: SpeedLimitDecider(const SpeedBoundsDeciderConfig& config, const ReferenceLine& reference_line, const PathData& path_data); virtual ~SpeedLimitDecider() = default; virtual common::Status GetSpeedLimits( const IndexedList<std::string, Obstacle>& obstacles, SpeedLimit* const speed_limit_data) const; private: FRIEND_TEST(SpeedLimitDeciderTest, get_centric_acc_limit); double GetCentricAccLimit(const double kappa) const; void GetAvgKappa(const std::vector<common::PathPoint>& path_points, std::vector<double>* kappa) const; private: const SpeedBoundsDeciderConfig& speed_bounds_config_; const ReferenceLine& reference_line_; const PathData& path_data_; const apollo::common::VehicleParam& vehicle_param_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/speed_bounds_decider/speed_bounds_decider.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <memory> #include "modules/planning/common/frame.h" #include "modules/planning/common/st_graph_data.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/tasks/deciders/decider.h" namespace apollo { namespace planning { class SpeedBoundsDecider : public Decider { public: SpeedBoundsDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); private: common::Status Process(Frame* const frame, ReferenceLineInfo* const reference_line_info) override; double SetSpeedFallbackDistance(PathDecision* const path_decision); void RecordSTGraphDebug( const StGraphData& st_graph_data, planning_internal::STGraphDebug* st_graph_debug) const; private: SpeedBoundsDeciderConfig speed_bounds_config_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/speed_bounds_decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "speed_bounds_decider", srcs = ["speed_bounds_decider.cc"], hdrs = ["speed_bounds_decider.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ ":st_boundary_mapper", "//modules/common/status", "//modules/planning/common:frame", "//modules/planning/common:planning_gflags", "//modules/planning/common:st_graph_data", "//modules/planning/common/util:common_lib", "//modules/planning/tasks:task", "//modules/planning/tasks/deciders:decider_base", "//modules/planning/tasks/deciders/lane_change_decider", ], ) cc_library( name = "st_boundary_mapper", srcs = [ "speed_limit_decider.cc", "st_boundary_mapper.cc", ], hdrs = [ "speed_limit_decider.h", "st_boundary_mapper.h", ], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/common_msgs/config_msgs:vehicle_config_cc_proto", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/status", "//modules/map/pnc_map", "//modules/planning/common:dependency_injector", "//modules/planning/common:frame", "//modules/planning/common:obstacle", "//modules/planning/common:path_decision", "//modules/planning/common:planning_gflags", "//modules/planning/common:speed_limit", "//modules/planning/common/path:discretized_path", "//modules/planning/common/path:frenet_frame_path", "//modules/planning/common/path:path_data", "//modules/planning/common/speed:st_boundary", "//modules/planning/common/trajectory:discretized_trajectory", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/proto:planning_config_cc_proto", "//modules/planning/reference_line", ], ) cc_test( name = "st_boundary_mapper_test", size = "small", srcs = ["st_boundary_mapper_test.cc"], data = [ "//modules/planning:planning_testdata", ], deps = [ ":st_boundary_mapper", "//cyber", "//modules/common/util", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/speed_bounds_decider/speed_limit_decider.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/speed_bounds_decider/speed_limit_decider.h" #include <algorithm> #include <limits> #include "cyber/common/log.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/planning/common/planning_gflags.h" #include "modules/common_msgs/planning_msgs/decision.pb.h" namespace apollo { namespace planning { using apollo::common::Status; SpeedLimitDecider::SpeedLimitDecider(const SpeedBoundsDeciderConfig& config, const ReferenceLine& reference_line, const PathData& path_data) : speed_bounds_config_(config), reference_line_(reference_line), path_data_(path_data), vehicle_param_(common::VehicleConfigHelper::GetConfig().vehicle_param()) { } Status SpeedLimitDecider::GetSpeedLimits( const IndexedList<std::string, Obstacle>& obstacles, SpeedLimit* const speed_limit_data) const { CHECK_NOTNULL(speed_limit_data); const auto& discretized_path = path_data_.discretized_path(); const auto& frenet_path = path_data_.frenet_frame_path(); for (uint32_t i = 0; i < discretized_path.size(); ++i) { const double path_s = discretized_path.at(i).s(); const double reference_line_s = frenet_path.at(i).s(); if (reference_line_s > reference_line_.Length()) { AWARN << "path w.r.t. reference line at [" << reference_line_s << "] is LARGER than reference_line_ length [" << reference_line_.Length() << "]. Please debug before proceeding."; break; } // (1) speed limit from map double speed_limit_from_reference_line = reference_line_.GetSpeedLimitFromS(reference_line_s); // (2) speed limit from path curvature // -- 2.1: limit by centripetal force (acceleration) const double speed_limit_from_centripetal_acc = std::sqrt(speed_bounds_config_.max_centric_acceleration_limit() / std::fmax(std::fabs(discretized_path.at(i).kappa()), speed_bounds_config_.minimal_kappa())); // (3) speed limit from nudge obstacles // TODO(all): in future, expand the speed limit not only to obstacles with // nudge decisions. double speed_limit_from_nearby_obstacles = std::numeric_limits<double>::max(); const double collision_safety_range = speed_bounds_config_.collision_safety_range(); for (const auto* ptr_obstacle : obstacles.Items()) { if (ptr_obstacle->IsVirtual()) { continue; } if (!ptr_obstacle->LateralDecision().has_nudge()) { continue; } /* ref line: * ------------------------------- * start_s end_s * ------| adc |--------------- * ------------| obstacle |------ */ // TODO(all): potential problem here; // frenet and cartesian coordinates are mixed. const double vehicle_front_s = reference_line_s + vehicle_param_.front_edge_to_center(); const double vehicle_back_s = reference_line_s - vehicle_param_.back_edge_to_center(); const double obstacle_front_s = ptr_obstacle->PerceptionSLBoundary().end_s(); const double obstacle_back_s = ptr_obstacle->PerceptionSLBoundary().start_s(); if (vehicle_front_s < obstacle_back_s || vehicle_back_s > obstacle_front_s) { continue; } const auto& nudge_decision = ptr_obstacle->LateralDecision().nudge(); // Please notice the differences between adc_l and frenet_point_l const double frenet_point_l = frenet_path.at(i).l(); // obstacle is on the right of ego vehicle (at path point i) bool is_close_on_left = (nudge_decision.type() == ObjectNudge::LEFT_NUDGE) && (frenet_point_l - vehicle_param_.right_edge_to_center() - collision_safety_range < ptr_obstacle->PerceptionSLBoundary().end_l()); // obstacle is on the left of ego vehicle (at path point i) bool is_close_on_right = (nudge_decision.type() == ObjectNudge::RIGHT_NUDGE) && (ptr_obstacle->PerceptionSLBoundary().start_l() - collision_safety_range < frenet_point_l + vehicle_param_.left_edge_to_center()); // TODO(all): dynamic obstacles do not have nudge decision if (is_close_on_left || is_close_on_right) { double nudge_speed_ratio = 1.0; if (ptr_obstacle->IsStatic()) { nudge_speed_ratio = speed_bounds_config_.static_obs_nudge_speed_ratio(); } else { nudge_speed_ratio = speed_bounds_config_.dynamic_obs_nudge_speed_ratio(); } speed_limit_from_nearby_obstacles = nudge_speed_ratio * speed_limit_from_reference_line; break; } } double curr_speed_limit = 0.0; if (FLAGS_enable_nudge_slowdown) { curr_speed_limit = std::fmax(speed_bounds_config_.lowest_speed(), std::min({speed_limit_from_reference_line, speed_limit_from_centripetal_acc, speed_limit_from_nearby_obstacles})); } else { curr_speed_limit = std::fmax(speed_bounds_config_.lowest_speed(), std::min({speed_limit_from_reference_line, speed_limit_from_centripetal_acc})); } speed_limit_data->AppendSpeedLimit(path_s, curr_speed_limit); } return Status::OK(); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/speed_bounds_decider/speed_bounds_decider.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/tasks/deciders/speed_bounds_decider/speed_bounds_decider.h" #include <algorithm> #include <limits> #include <memory> #include <string> #include <vector> #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/path/path_data.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/st_graph_data.h" #include "modules/planning/common/util/common.h" #include "modules/planning/tasks/deciders/speed_bounds_decider/speed_limit_decider.h" #include "modules/planning/tasks/deciders/speed_bounds_decider/st_boundary_mapper.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::planning_internal::StGraphBoundaryDebug; using apollo::planning_internal::STGraphDebug; SpeedBoundsDecider::SpeedBoundsDecider( const TaskConfig &config, const std::shared_ptr<DependencyInjector> &injector) : Decider(config, injector) { ACHECK(config.has_speed_bounds_decider_config()); speed_bounds_config_ = config.speed_bounds_decider_config(); } Status SpeedBoundsDecider::Process( Frame *const frame, ReferenceLineInfo *const reference_line_info) { // retrieve data from frame and reference_line_info const PathData &path_data = reference_line_info->path_data(); const TrajectoryPoint &init_point = frame->PlanningStartPoint(); const ReferenceLine &reference_line = reference_line_info->reference_line(); PathDecision *const path_decision = reference_line_info->path_decision(); // 1. Map obstacles into st graph auto time1 = std::chrono::system_clock::now(); STBoundaryMapper boundary_mapper( speed_bounds_config_, reference_line, path_data, path_data.discretized_path().Length(), speed_bounds_config_.total_time(), injector_); if (!FLAGS_use_st_drivable_boundary) { path_decision->EraseStBoundaries(); } if (boundary_mapper.ComputeSTBoundary(path_decision).code() == ErrorCode::PLANNING_ERROR) { const std::string msg = "Mapping obstacle failed."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } auto time2 = std::chrono::system_clock::now(); std::chrono::duration<double> diff = time2 - time1; ADEBUG << "Time for ST Boundary Mapping = " << diff.count() * 1000 << " msec."; std::vector<const STBoundary *> boundaries; for (auto *obstacle : path_decision->obstacles().Items()) { const auto &id = obstacle->Id(); const auto &st_boundary = obstacle->path_st_boundary(); if (!st_boundary.IsEmpty()) { if (st_boundary.boundary_type() == STBoundary::BoundaryType::KEEP_CLEAR) { path_decision->Find(id)->SetBlockingObstacle(false); } else { path_decision->Find(id)->SetBlockingObstacle(true); } boundaries.push_back(&st_boundary); } } const double min_s_on_st_boundaries = SetSpeedFallbackDistance(path_decision); // 2. Create speed limit along path SpeedLimitDecider speed_limit_decider(speed_bounds_config_, reference_line, path_data); SpeedLimit speed_limit; if (!speed_limit_decider .GetSpeedLimits(path_decision->obstacles(), &speed_limit) .ok()) { const std::string msg = "Getting speed limits failed!"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // 3. Get path_length as s axis search bound in st graph const double path_data_length = path_data.discretized_path().Length(); // 4. Get time duration as t axis search bound in st graph const double total_time_by_conf = speed_bounds_config_.total_time(); // Load generated st graph data back to frame StGraphData *st_graph_data = reference_line_info_->mutable_st_graph_data(); // Add a st_graph debug info and save the pointer to st_graph_data for // optimizer logging auto *debug = reference_line_info_->mutable_debug(); STGraphDebug *st_graph_debug = debug->mutable_planning_data()->add_st_graph(); st_graph_data->LoadData(boundaries, min_s_on_st_boundaries, init_point, speed_limit, reference_line_info->GetCruiseSpeed(), path_data_length, total_time_by_conf, st_graph_debug); // Create and record st_graph debug info RecordSTGraphDebug(*st_graph_data, st_graph_debug); return Status::OK(); } double SpeedBoundsDecider::SetSpeedFallbackDistance( PathDecision *const path_decision) { // Set min_s_on_st_boundaries to guide speed fallback. static constexpr double kEpsilon = 1.0e-6; double min_s_non_reverse = std::numeric_limits<double>::infinity(); double min_s_reverse = std::numeric_limits<double>::infinity(); for (auto *obstacle : path_decision->obstacles().Items()) { const auto &st_boundary = obstacle->path_st_boundary(); if (st_boundary.IsEmpty()) { continue; } const auto left_bottom_point_s = st_boundary.bottom_left_point().s(); const auto right_bottom_point_s = st_boundary.bottom_right_point().s(); const auto lowest_s = std::min(left_bottom_point_s, right_bottom_point_s); if (left_bottom_point_s - right_bottom_point_s > kEpsilon) { if (min_s_reverse > lowest_s) { min_s_reverse = lowest_s; } } else if (min_s_non_reverse > lowest_s) { min_s_non_reverse = lowest_s; } } min_s_reverse = std::max(min_s_reverse, 0.0); min_s_non_reverse = std::max(min_s_non_reverse, 0.0); return min_s_non_reverse > min_s_reverse ? 0.0 : min_s_non_reverse; } void SpeedBoundsDecider::RecordSTGraphDebug( const StGraphData &st_graph_data, STGraphDebug *st_graph_debug) const { if (!FLAGS_enable_record_debug || !st_graph_debug) { ADEBUG << "Skip record debug info"; return; } for (const auto &boundary : st_graph_data.st_boundaries()) { auto boundary_debug = st_graph_debug->add_boundary(); boundary_debug->set_name(boundary->id()); switch (boundary->boundary_type()) { case STBoundary::BoundaryType::FOLLOW: boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_FOLLOW); break; case STBoundary::BoundaryType::OVERTAKE: boundary_debug->set_type( StGraphBoundaryDebug::ST_BOUNDARY_TYPE_OVERTAKE); break; case STBoundary::BoundaryType::STOP: boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_STOP); break; case STBoundary::BoundaryType::UNKNOWN: boundary_debug->set_type( StGraphBoundaryDebug::ST_BOUNDARY_TYPE_UNKNOWN); break; case STBoundary::BoundaryType::YIELD: boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_YIELD); break; case STBoundary::BoundaryType::KEEP_CLEAR: boundary_debug->set_type( StGraphBoundaryDebug::ST_BOUNDARY_TYPE_KEEP_CLEAR); break; } for (const auto &point : boundary->points()) { auto point_debug = boundary_debug->add_point(); point_debug->set_t(point.x()); point_debug->set_s(point.y()); } } for (const auto &point : st_graph_data.speed_limit().speed_limit_points()) { common::SpeedPoint *speed_point = st_graph_debug->add_speed_limit(); speed_point->set_s(point.first); speed_point->set_v(point.second); } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_decider/path_decider.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <memory> #include <string> #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { class PathDecider : public Task { public: PathDecider(const TaskConfig &config, const std::shared_ptr<DependencyInjector> &injector); apollo::common::Status Execute( Frame *frame, ReferenceLineInfo *reference_line_info) override; private: apollo::common::Status Process(const ReferenceLineInfo *reference_line_info, const PathData &path_data, PathDecision *const path_decision); bool MakeObjectDecision(const PathData &path_data, const std::string &blocking_obstacle_id, PathDecision *const path_decision); bool MakeStaticObstacleDecision(const PathData &path_data, const std::string &blocking_obstacle_id, PathDecision *const path_decision); ObjectStop GenerateObjectStopDecision(const Obstacle &obstacle) const; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_decider/path_decider.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/path_decider/path_decider.h" #include <memory> #include "modules/common_msgs/planning_msgs/decision.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::VehicleConfigHelper; PathDecider::PathDecider(const TaskConfig &config, const std::shared_ptr<DependencyInjector> &injector) : Task(config, injector) {} Status PathDecider::Execute(Frame *frame, ReferenceLineInfo *reference_line_info) { Task::Execute(frame, reference_line_info); return Process(reference_line_info, reference_line_info->path_data(), reference_line_info->path_decision()); } Status PathDecider::Process(const ReferenceLineInfo *reference_line_info, const PathData &path_data, PathDecision *const path_decision) { // skip path_decider if reused path if (FLAGS_enable_skip_path_tasks && reference_line_info->path_reusable()) { return Status::OK(); } std::string blocking_obstacle_id; if (reference_line_info->GetBlockingObstacle() != nullptr) { blocking_obstacle_id = reference_line_info->GetBlockingObstacle()->Id(); } if (!MakeObjectDecision(path_data, blocking_obstacle_id, path_decision)) { const std::string msg = "Failed to make decision based on tunnel"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } return Status::OK(); } bool PathDecider::MakeObjectDecision(const PathData &path_data, const std::string &blocking_obstacle_id, PathDecision *const path_decision) { if (!MakeStaticObstacleDecision(path_data, blocking_obstacle_id, path_decision)) { AERROR << "Failed to make decisions for static obstacles"; return false; } return true; } // TODO(jiacheng): eventually this entire "path_decider" should be retired. // Before it gets retired, its logics are slightly modified so that everything // still works well for now. bool PathDecider::MakeStaticObstacleDecision( const PathData &path_data, const std::string &blocking_obstacle_id, PathDecision *const path_decision) { // Sanity checks and get important values. ACHECK(path_decision); const auto &frenet_path = path_data.frenet_frame_path(); if (frenet_path.empty()) { AERROR << "Path is empty."; return false; } const double half_width = common::VehicleConfigHelper::GetConfig().vehicle_param().width() / 2.0; const double lateral_radius = half_width + FLAGS_lateral_ignore_buffer; // Go through every obstacle and make decisions. for (const auto *obstacle : path_decision->obstacles().Items()) { const std::string &obstacle_id = obstacle->Id(); const std::string obstacle_type_name = PerceptionObstacle_Type_Name(obstacle->Perception().type()); ADEBUG << "obstacle_id[<< " << obstacle_id << "] type[" << obstacle_type_name << "]"; if (!obstacle->IsStatic() || obstacle->IsVirtual()) { continue; } // - skip decision making for obstacles with IGNORE/STOP decisions already. if (obstacle->HasLongitudinalDecision() && obstacle->LongitudinalDecision().has_ignore() && obstacle->HasLateralDecision() && obstacle->LateralDecision().has_ignore()) { continue; } if (obstacle->HasLongitudinalDecision() && obstacle->LongitudinalDecision().has_stop()) { // STOP decision continue; } // - add STOP decision for blocking obstacles. if (obstacle->Id() == blocking_obstacle_id && !injector_->planning_context() ->planning_status() .path_decider() .is_in_path_lane_borrow_scenario()) { // Add stop decision ADEBUG << "Blocking obstacle = " << blocking_obstacle_id; ObjectDecisionType object_decision; *object_decision.mutable_stop() = GenerateObjectStopDecision(*obstacle); path_decision->AddLongitudinalDecision("PathDecider/blocking_obstacle", obstacle->Id(), object_decision); continue; } // - skip decision making for clear-zone obstacles. if (obstacle->reference_line_st_boundary().boundary_type() == STBoundary::BoundaryType::KEEP_CLEAR) { continue; } // 0. IGNORE by default and if obstacle is not in path s at all. ObjectDecisionType object_decision; object_decision.mutable_ignore(); const auto &sl_boundary = obstacle->PerceptionSLBoundary(); if (sl_boundary.end_s() < frenet_path.front().s() || sl_boundary.start_s() > frenet_path.back().s()) { path_decision->AddLongitudinalDecision("PathDecider/not-in-s", obstacle->Id(), object_decision); path_decision->AddLateralDecision("PathDecider/not-in-s", obstacle->Id(), object_decision); continue; } const auto frenet_point = frenet_path.GetNearestPoint(sl_boundary); const double curr_l = frenet_point.l(); double min_nudge_l = half_width + config_.path_decider_config().static_obstacle_buffer() / 2.0; if (curr_l - lateral_radius > sl_boundary.end_l() || curr_l + lateral_radius < sl_boundary.start_l()) { // 1. IGNORE if laterally too far away. path_decision->AddLateralDecision("PathDecider/not-in-l", obstacle->Id(), object_decision); } else if (sl_boundary.end_l() >= curr_l - min_nudge_l && sl_boundary.start_l() <= curr_l + min_nudge_l) { // 2. STOP if laterally too overlapping. *object_decision.mutable_stop() = GenerateObjectStopDecision(*obstacle); if (path_decision->MergeWithMainStop( object_decision.stop(), obstacle->Id(), reference_line_info_->reference_line(), reference_line_info_->AdcSlBoundary())) { path_decision->AddLongitudinalDecision("PathDecider/nearest-stop", obstacle->Id(), object_decision); } else { ObjectDecisionType object_decision; object_decision.mutable_ignore(); path_decision->AddLongitudinalDecision("PathDecider/not-nearest-stop", obstacle->Id(), object_decision); } } else { // 3. NUDGE if laterally very close. if (sl_boundary.end_l() < curr_l - min_nudge_l) { // && // sl_boundary.end_l() > curr_l - min_nudge_l - 0.3) { // LEFT_NUDGE ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); object_nudge_ptr->set_type(ObjectNudge::LEFT_NUDGE); object_nudge_ptr->set_distance_l( config_.path_decider_config().static_obstacle_buffer()); path_decision->AddLateralDecision("PathDecider/left-nudge", obstacle->Id(), object_decision); } else if (sl_boundary.start_l() > curr_l + min_nudge_l) { // && // sl_boundary.start_l() < curr_l + min_nudge_l + 0.3) { // RIGHT_NUDGE ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); object_nudge_ptr->set_type(ObjectNudge::RIGHT_NUDGE); object_nudge_ptr->set_distance_l( -config_.path_decider_config().static_obstacle_buffer()); path_decision->AddLateralDecision("PathDecider/right-nudge", obstacle->Id(), object_decision); } } } return true; } ObjectStop PathDecider::GenerateObjectStopDecision( const Obstacle &obstacle) const { ObjectStop object_stop; double stop_distance = obstacle.MinRadiusStopDistance( VehicleConfigHelper::GetConfig().vehicle_param()); object_stop.set_reason_code(StopReasonCode::STOP_REASON_OBSTACLE); object_stop.set_distance_s(-stop_distance); const double stop_ref_s = obstacle.PerceptionSLBoundary().start_s() - stop_distance; const auto stop_ref_point = reference_line_info_->reference_line().GetReferencePoint(stop_ref_s); object_stop.mutable_stop_point()->set_x(stop_ref_point.x()); object_stop.mutable_stop_point()->set_y(stop_ref_point.y()); object_stop.set_stop_heading(stop_ref_point.heading()); return object_stop; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "path_decider", srcs = ["path_decider.cc"], hdrs = ["path_decider.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/common_msgs/planning_msgs:decision_cc_proto", "//modules/common/configs:vehicle_config_helper", "//modules/common/util", "//modules/planning/common:planning_context", "//modules/planning/common:planning_gflags", "//modules/planning/proto:planning_config_cc_proto", "//modules/planning/tasks:task", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_reference_decider/path_reference_decider.cc
/****************************************************************************** * Copyright 2020 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file path_reference_decider.cc */ #include "modules/planning/tasks/deciders/path_reference_decider/path_reference_decider.h" #include <string> #include <utility> #include <vector> #include "modules/planning/proto/planning_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/box2d.h" #include "modules/common/math/line_segment2d.h" #include "modules/planning/common/path/discretized_path.h" #include "modules/planning/common/path_boundary.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { using common::ErrorCode; using common::PathPoint; using common::SLPoint; using common::Status; using common::TrajectoryPoint; using common::math::Box2d; using common::math::LineSegment2d; using common::math::Vec2d; int PathReferenceDecider::valid_path_reference_counter_ = 0; int PathReferenceDecider::total_path_counter_ = 0; PathReferenceDecider::PathReferenceDecider( const TaskConfig &config, const std::shared_ptr<DependencyInjector> &injector) : Task(config, injector) {} Status PathReferenceDecider::Execute(Frame *frame, ReferenceLineInfo *reference_line_info) { Task::Execute(frame, reference_line_info); return Process(frame, reference_line_info); } Status PathReferenceDecider::Process(Frame *frame, ReferenceLineInfo *reference_line_info) { constexpr double kMathEpsilon = 1e-10; // skip using path reference during lane changing // There are two reference line during change lane if (FLAGS_skip_path_reference_in_change_lane && frame->reference_line_info().size() > 1) { reference_line_info->mutable_path_data()->set_is_valid_path_reference( false); ADEBUG << "Skip path reference when changing lane."; ADEBUG << "valid_path_reference_counter[" << valid_path_reference_counter_ << "] total_path_counter[" << total_path_counter_ << "]"; std::string err_msg = "Skip path reference when changing lane."; reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_learning_model_output_fail_reason(err_msg); reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_learning_model_output_usage_ratio( static_cast<double>(valid_path_reference_counter_) / (total_path_counter_ + kMathEpsilon)); return Status::OK(); } // skip using path reference during side pass if (FLAGS_skip_path_reference_in_side_pass && reference_line_info->is_path_lane_borrow()) { reference_line_info->mutable_path_data()->set_is_valid_path_reference( false); ADEBUG << "Skip path reference when sidepass."; ADEBUG << "valid_path_reference_counter[" << valid_path_reference_counter_ << "] total_path_counter[" << total_path_counter_ << "]"; std::string err_msg = "Skip path reference when sidepass."; reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_learning_model_output_fail_reason(err_msg); reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_learning_model_output_usage_ratio( static_cast<double>(valid_path_reference_counter_) / (total_path_counter_ + kMathEpsilon)); return Status::OK(); } // get path bounds info from reference line info const std::vector<PathBoundary> &path_boundaries = reference_line_info_->GetCandidatePathBoundaries(); ADEBUG << "There are " << path_boundaries.size() << " path boundaries."; // get learning model output (trajectory) from frame const std::vector<common::TrajectoryPoint> &learning_model_trajectory = injector_->learning_based_data() ->learning_data_adc_future_trajectory_points(); ADEBUG << "There are " << learning_model_trajectory.size() << " path points."; // get regular path bound size_t regular_path_bound_idx = GetRegularPathBound(path_boundaries); if (regular_path_bound_idx == path_boundaries.size()) { reference_line_info->mutable_path_data()->set_is_valid_path_reference( false); const std::string msg = "No regular path boundary"; AERROR << msg; ADEBUG << "valid_path_reference_counter[" << valid_path_reference_counter_ << "] total_path_counter[" << total_path_counter_ << "]"; std::string err_msg = "No regular path boundary"; reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_learning_model_output_fail_reason(err_msg); reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_learning_model_output_usage_ratio( static_cast<double>(valid_path_reference_counter_) / (total_path_counter_ + kMathEpsilon)); return Status(ErrorCode::PLANNING_ERROR, msg); } ++total_path_counter_; // when learning model has no output, use rule-based model instead. if (learning_model_trajectory.size() == 0) { reference_line_info->mutable_path_data()->set_is_valid_path_reference( false); ADEBUG << "valid_path_reference_counter[" << valid_path_reference_counter_ << "] total_path_counter[" << total_path_counter_ << "]"; std::string err_msg = "No learning model output"; reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_learning_model_output_fail_reason(err_msg); reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_learning_model_output_usage_ratio( static_cast<double>(valid_path_reference_counter_) / (total_path_counter_ + kMathEpsilon)); return Status::OK(); } std::vector<PathPoint> path_reference; // adjusting trajectory init point DiscretizedTrajectory stitched_learning_model_trajectory; reference_line_info->AdjustTrajectoryWhichStartsFromCurrentPos( frame->PlanningStartPoint(), learning_model_trajectory, &stitched_learning_model_trajectory); // when path_reference is too short not valid path reference if (stitched_learning_model_trajectory.size() <= 1) { reference_line_info->mutable_path_data()->set_is_valid_path_reference( false); ADEBUG << "valid_path_reference_counter[" << valid_path_reference_counter_ << "] total_path_counter[" << total_path_counter_ << "]"; std::string err_msg = "Stitched path reference is too short"; reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_learning_model_output_fail_reason(err_msg); reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_learning_model_output_usage_ratio( static_cast<double>(valid_path_reference_counter_) / (total_path_counter_ + kMathEpsilon)); return Status::OK(); } ConvertTrajectoryToPath(stitched_learning_model_trajectory, &path_reference); const std::string path_reference_name = "path_reference"; RecordDebugInfo(path_reference, path_reference_name, reference_line_info); // check if path reference is valid // current, only check if path reference point is within path bounds if (!IsValidPathReference(*reference_line_info, path_boundaries[regular_path_bound_idx], path_reference)) { reference_line_info->mutable_path_data()->set_is_valid_path_reference( false); ADEBUG << "valid_path_reference_counter[" << valid_path_reference_counter_ << "] total_path_counter[" << total_path_counter_ << "]"; std::string err_msg = "Learning model output violates path bounds"; reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_learning_model_output_fail_reason(err_msg); // export reuse ratio to debug info reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_learning_model_output_usage_ratio( static_cast<double>(valid_path_reference_counter_) / (total_path_counter_ + kMathEpsilon)); return Status::OK(); } // evaluate path reference std::vector<PathPoint> evaluated_path_reference; EvaluatePathReference(path_boundaries[regular_path_bound_idx], path_reference, &evaluated_path_reference); ADEBUG << "evaluated_path_reference: " << evaluated_path_reference.size(); // mark learning trajectory as path reference reference_line_info->mutable_path_data()->set_is_valid_path_reference(true); // export decider result to debug info reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_using_learning_model_output(true); // export evaluated path reference reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->mutable_evaluated_path_reference() ->mutable_path_point() ->CopyFrom( {evaluated_path_reference.begin(), evaluated_path_reference.end()}); // set evaluated path data reference_line_info->mutable_path_data()->set_path_reference( std::move(evaluated_path_reference)); // uncomment this for debug // const std::string evaluation_path_name = "evaluated_path_reference"; // RecordDebugInfo(evaluated_path_reference, evaluation_path_name, // reference_line_info); ++valid_path_reference_counter_; ADEBUG << "valid_path_reference_counter[" << valid_path_reference_counter_ << "] total_path_counter[" << total_path_counter_ << "]"; // export reuse ratio to debug info reference_line_info->mutable_debug() ->mutable_planning_data() ->mutable_hybrid_model() ->set_learning_model_output_usage_ratio( static_cast<double>(valid_path_reference_counter_) / (total_path_counter_ + kMathEpsilon)); ADEBUG << "path reference size:" << path_reference.size(); return Status::OK(); } void PathReferenceDecider::ConvertTrajectoryToPath( const std::vector<TrajectoryPoint> &trajectory_points, std::vector<PathPoint> *path_points) { for (auto trajectory_point : trajectory_points) { if (trajectory_point.has_path_point()) { path_points->push_back(trajectory_point.path_point()); } } } size_t PathReferenceDecider::GetRegularPathBound( const std::vector<PathBoundary> &path_bounds) const { for (auto iter = begin(path_bounds); iter != end(path_bounds); ++iter) { if (iter->label().find("regular") != std::string::npos) { return distance(begin(path_bounds), iter); } } return path_bounds.size(); } bool PathReferenceDecider::IsValidPathReference( const ReferenceLineInfo &reference_line_info, const PathBoundary &regular_path_bound, const std::vector<PathPoint> &path_reference) { for (auto path_referece_point : path_reference) { const double cur_x = path_referece_point.x(); const double cur_y = path_referece_point.y(); if (-1 == IsPointWithinPathBounds(reference_line_info, regular_path_bound, cur_x, cur_y)) { ADEBUG << ", x: " << std::setprecision(9) << cur_x << ", y: " << std::setprecision(9) << cur_y; return false; } } return true; } bool PathReferenceDecider::IsADCBoxAlongPathReferenceWithinPathBounds( const std::vector<TrajectoryPoint> &path_reference, const PathBoundary &regular_path_bound) { /* check adc box has overlap with each path line segment*/ // loop over output trajectory points // check if path reference point is valid or not // 1. line segment formed by two adjacent boundary point std::vector<std::vector<LineSegment2d>> segmented_path_bounds; PathBoundToLineSegments(regular_path_bound, &segmented_path_bounds); // has intersection with std::vector<Box2d> vehicle_boxes; for (const auto path_reference_point : path_reference) { // add ADC box to current path_reference_point const auto &path_point = path_reference_point.path_point(); Box2d vehicle_box = common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point); vehicle_boxes.emplace_back(vehicle_box); } // check intersection of linesegments and adc boxes // left & right path bounds for (auto segmented_path_bound : segmented_path_bounds) { // line segment for each bound for (auto line_segment : segmented_path_bound) { // check if all vehicle boxes along learning model outputhas // overlap with ADC box // TODO(Shu): early stop when vehicle box is far away. for (auto vehicle_box : vehicle_boxes) { if (vehicle_box.HasOverlap(line_segment)) { ADEBUG << std::setprecision(9) << "Vehicle box:[" << vehicle_box.center_x() << "," << vehicle_box.center_y() << "]" << "Violate path bound at [" << line_segment.start().x() << "," << line_segment.start().y() << "];" << "[" << line_segment.end().x() << "," << line_segment.end().y() << "]"; return false; } } } } return true; } void PathReferenceDecider::PathBoundToLineSegments( const PathBoundary &path_bound, std::vector<std::vector<LineSegment2d>> *path_bound_segments) { const double start_s = path_bound.start_s(); const double delta_s = path_bound.delta_s(); const size_t path_bound_size = path_bound.boundary().size(); std::vector<LineSegment2d> cur_left_bound_segments; std::vector<LineSegment2d> cur_right_bound_segments; const std::vector<std::pair<double, double>> &path_bound_points = path_bound.boundary(); // setup the init path bound point SLPoint prev_left_sl_point; SLPoint prev_right_sl_point; prev_left_sl_point.set_l(std::get<0>(path_bound_points[0])); prev_left_sl_point.set_s(start_s); prev_right_sl_point.set_l(std::get<1>(path_bound_points[0])); prev_right_sl_point.set_s(start_s); // slpoint to cartesion point Vec2d prev_left_cartesian_point; Vec2d prev_right_cartesian_point; reference_line_info_->reference_line().SLToXY(prev_left_sl_point, &prev_left_cartesian_point); reference_line_info_->reference_line().SLToXY(prev_right_sl_point, &prev_right_cartesian_point); for (size_t i = 1; i < path_bound_size; ++i) { // s = start_s + i * delta_s double current_s = start_s + i * delta_s; SLPoint left_sl_point; Vec2d left_cartesian_point; SLPoint right_sl_point; Vec2d right_cartesian_point; left_sl_point.set_l(std::get<0>(path_bound_points[i])); left_sl_point.set_s(current_s); right_sl_point.set_l(std::get<1>(path_bound_points[i])); right_sl_point.set_s(current_s); reference_line_info_->reference_line().SLToXY(left_sl_point, &left_cartesian_point); reference_line_info_->reference_line().SLToXY(right_sl_point, &right_cartesian_point); // together with previous point form line segment LineSegment2d cur_left_segment(prev_left_cartesian_point, left_cartesian_point); LineSegment2d cur_right_segment(prev_right_cartesian_point, right_cartesian_point); prev_left_cartesian_point = left_cartesian_point; prev_right_cartesian_point = right_cartesian_point; cur_left_bound_segments.emplace_back(cur_left_segment); cur_right_bound_segments.emplace_back(cur_right_segment); } path_bound_segments->emplace_back(cur_left_bound_segments); path_bound_segments->emplace_back(cur_right_bound_segments); } int PathReferenceDecider::IsPointWithinPathBounds( const ReferenceLineInfo &reference_line_info, const PathBoundary &path_bound, const double x, const double y) { const double kPathBoundsDeciderResolution = 0.5; common::SLPoint point_sl; reference_line_info.reference_line().XYToSL({x, y}, &point_sl); const double start_s = path_bound.start_s(); const double delta_s = path_bound.delta_s(); const int path_bound_size = path_bound.boundary().size(); const double end_s = start_s + delta_s * (path_bound_size - 1); if (point_sl.s() > end_s || point_sl.s() < start_s - kPathBoundsDeciderResolution * 2) { AERROR << "Longitudinally outside the boundary."; return -1; } int idx_after = 0; while (idx_after < path_bound_size && start_s + idx_after * delta_s < point_sl.s()) { ++idx_after; } if (idx_after == 0) { // consider as a valid point if the starting point is before path bound // begining point return idx_after; } else { ADEBUG << "idx_after[" << idx_after << "] point_l[" << point_sl.l() << "]"; int idx_before = idx_after - 1; if (std::get<0>(path_bound.boundary().at(idx_before)) <= point_sl.l() && std::get<1>(path_bound.boundary().at(idx_before)) >= point_sl.l() && std::get<0>(path_bound.boundary().at(idx_after)) <= point_sl.l() && std::get<1>(path_bound.boundary().at(idx_after)) >= point_sl.l()) { return idx_after; } } ADEBUG << "Laterally outside the boundary."; return -1; } void PathReferenceDecider::EvaluatePathReference( const PathBoundary &path_bound, const std::vector<PathPoint> &path_reference, std::vector<PathPoint> *evaluated_path_reference) { const double delta_s = path_bound.delta_s(); const double path_reference_end_s = path_reference.back().s(); DiscretizedPath discrete_path_reference; for (auto path_point : path_reference) { discrete_path_reference.emplace_back(path_point); } size_t idx; for (idx = 0; idx < path_bound.boundary().size(); ++idx) { // relative s double cur_s = static_cast<double>(idx) * delta_s; if (cur_s > path_reference_end_s) { break; } evaluated_path_reference->emplace_back( discrete_path_reference.Evaluate(cur_s)); } } void PathReferenceDecider::RecordDebugInfo( const std::vector<PathPoint> &path_points, const std::string &path_name, ReferenceLineInfo *const reference_line_info) { // Sanity checks. ACHECK(!path_points.empty()); CHECK_NOTNULL(reference_line_info); // Insert the transformed PathData into the simulator display. auto *ptr_display_path = reference_line_info->mutable_debug()->mutable_planning_data()->add_path(); ptr_display_path->set_name(path_name); ptr_display_path->mutable_path_point()->CopyFrom( {path_points.begin(), path_points.end()}); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_reference_decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "path_reference_decider", srcs = ["path_reference_decider.cc"], hdrs = ["path_reference_decider.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/status", "//modules/planning/common:frame", "//modules/planning/common:path_decision", "//modules/planning/common:planning_gflags", "//modules/planning/common:reference_line_info", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/proto:planning_config_cc_proto", "//modules/planning/tasks:task", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_reference_decider/path_reference_decider.h
/****************************************************************************** * Copyright 2020 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file path_reference_decider.h **/ #pragma once #include <memory> #include <string> #include <vector> #include "modules/planning/common/path_boundary.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { class PathReferenceDecider : public Task { public: PathReferenceDecider(const TaskConfig &config, const std::shared_ptr<DependencyInjector> &injector); apollo::common::Status Execute( Frame *frame, ReferenceLineInfo *reference_line_info) override; private: apollo::common::Status Process(Frame *frame, ReferenceLineInfo *reference_line_info); /** * @brief check is learning model output is within path bounds * * @param path_reference learning model output * @param path_bound path boundaries for rule-based model * @return true using learning model output as path reference * @return false */ bool IsValidPathReference( const ReferenceLineInfo &reference_line_info, const PathBoundary &path_bound, const std::vector<common::PathPoint> &path_reference); /** * @brief convert discrete path bounds to line segments * */ void PathBoundToLineSegments( const PathBoundary &path_bound, std::vector<std::vector<common::math::LineSegment2d>> *path_bound_segments); /** * @brief convert path points from evenly dt to evenly ds distribution * * @param path_bound * @param path_reference * @param evaluated_path_reference */ void EvaluatePathReference( const PathBoundary &path_bound, const std::vector<common::PathPoint> &path_reference, std::vector<common::PathPoint> *evaluated_path_reference); /** * @brief check if a point (x,y) is within path bounds * * @param reference_line_info * @param path_bound * @param x * @param y * @return int */ int IsPointWithinPathBounds(const ReferenceLineInfo &reference_line_info, const PathBoundary &path_bound, const double x, const double y); /** * @brief Get the Regular Path Bound object * * @param path_bounds * @return size_t */ size_t GetRegularPathBound( const std::vector<PathBoundary> &path_bounds) const; /** * @brief check is ADC box along path reference is within path bounds * more accurate method. * * @param path_reference * @param regular_path_bound * @return true * @return false */ bool IsADCBoxAlongPathReferenceWithinPathBounds( const std::vector<common::TrajectoryPoint> &path_reference, const PathBoundary &regular_path_bound); void ConvertTrajectoryToPath( const std::vector<common::TrajectoryPoint> &trajectory, std::vector<common::PathPoint> *path); void RecordDebugInfo(const std::vector<common::PathPoint> &path_points, const std::string &path_name, ReferenceLineInfo *const reference_line_info); private: static int valid_path_reference_counter_; // count valid path reference static int total_path_counter_; // count total path }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/tools/pad_terminal.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "cyber/cyber.h" #include "cyber/init.h" #include "cyber/time/time.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/message_util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/common_msgs/planning_msgs/pad_msg.pb.h" #include "modules/planning/proto/planning_config.pb.h" namespace { using apollo::cyber::CreateNode; using apollo::cyber::Node; using apollo::cyber::Writer; using apollo::cyber::common::GetProtoFromFile; using apollo::planning::PadMessage; using apollo::planning::PlanningConfig; class PadTerminal { public: PadTerminal() : node_(CreateNode("planning_pad_terminal")) {} void init() { const std::string planning_config_file = "/apollo/modules/planning/conf/planning_config.pb.txt"; PlanningConfig planning_config; ACHECK(GetProtoFromFile(planning_config_file, &planning_config)) << "failed to load planning config file " << planning_config_file; pad_writer_ = node_->CreateWriter<PadMessage>( planning_config.topic_config().planning_pad_topic()); terminal_thread_.reset(new std::thread([this] { terminal_thread_func(); })); } void help() { AINFO << "COMMAND:0~10\n"; AINFO << "\t0: follow"; AINFO << "\t1: change left"; AINFO << "\t2: change right"; AINFO << "\t3: pull over"; AINFO << "\t4: stop"; AINFO << "\t5: resume cruise"; AINFO << "\t10: exit"; AINFO << "\tother number: print help"; } void send(int action) { PadMessage pad; pad.set_action(PadMessage::DrivingAction(action)); if (action == PadMessage::FOLLOW) { AINFO << "sending FOLLOW action command."; } else if (action == PadMessage::CHANGE_LEFT) { AINFO << "sending CHANGE LEFT action command."; } else if (action == PadMessage::CHANGE_RIGHT) { AINFO << "sending CHANGE RIGHT action command."; } else if (action == PadMessage::PULL_OVER) { AINFO << "sending PULL OVER action command."; } else if (action == PadMessage::STOP) { AINFO << "sending STOP action command."; } else if (action == PadMessage::RESUME_CRUISE) { AINFO << "sending RESUME CRUISE action command."; } apollo::common::util::FillHeader("terminal", &pad); pad_writer_->Write(pad); AINFO << "send pad_message OK"; } void terminal_thread_func() { int mode = 0; bool should_exit = false; while (std::cin >> mode) { switch (mode) { case 0: send(PadMessage::FOLLOW); break; case 1: send(PadMessage::CHANGE_LEFT); break; case 2: send(PadMessage::CHANGE_RIGHT); break; case 3: send(PadMessage::PULL_OVER); break; case 4: send(PadMessage::STOP); break; case 5: send(PadMessage::RESUME_CRUISE); break; case 10: should_exit = true; break; default: help(); break; } if (should_exit) { break; } } } void stop() { terminal_thread_->join(); } private: std::unique_ptr<std::thread> terminal_thread_; std::shared_ptr<Writer<PadMessage>> pad_writer_; std::shared_ptr<Node> node_; }; } // namespace int main(int argc, char **argv) { apollo::cyber::Init("planning_pad_terminal"); FLAGS_alsologtostderr = true; FLAGS_v = 3; google::ParseCommandLineFlags(&argc, &argv, true); PadTerminal pad_terminal; pad_terminal.init(); pad_terminal.help(); apollo::cyber::WaitForShutdown(); pad_terminal.stop(); return 0; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/tools/inference_demo.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <gflags/gflags.h> #include "torch/script.h" #include "torch/torch.h" DEFINE_string(model_file, "/apollo/modules/planning/tools/planning_demo_model.pt", "pytorch model file."); int main(int argc, char** argv) { google::ParseCommandLineFlags(&argc, &argv, true); torch::jit::script::Module model; std::cout << "is_optimized:" << model.is_optimized() << std::endl; std::cout << "parameter size:" << model.parameters().size() << std::endl; torch::Device device(torch::kCPU); torch::set_num_threads(1); try { // Deserialize the ScriptModule from a file using torch::jit::load(). model = torch::jit::load(FLAGS_model_file, device); } catch (const c10::Error& e) { std::cerr << "error loading the model\n"; return -1; } std::cout << "is_optimized:" << model.is_optimized() << std::endl; std::cout << "after loading parameter size:" << model.parameters().size() << std::endl; std::vector<torch::jit::IValue> torch_inputs; int input_dim = 2 * 3 * 224 * 224 + 2 * 14; std::vector<double> feature_values(input_dim, 0.5); std::vector<torch::jit::IValue> inputs; std::vector<torch::jit::IValue> tuple; tuple.push_back(torch::zeros({2, 3, 224, 224})); tuple.push_back(torch::zeros({2, 14})); inputs.push_back(torch::ivalue::Tuple::create(tuple)); auto torch_output = model.forward(inputs); std::cout << torch_output << std::endl; std::cout << "isDoubleList:" << torch_output.isDoubleList() << std::endl; std::cout << "isTensorList:" << torch_output.isTensorList() << std::endl; std::cout << "isTensor:" << torch_output.isTensor() << std::endl; auto torch_output_tensor = torch_output.toTensor(); std::cout << "tensor dim:" << torch_output_tensor.dim() << std::endl; std::cout << "tensor sizes:" << torch_output_tensor.sizes() << std::endl; std::cout << "tensor toString:" << torch_output_tensor.toString() << std::endl; std::cout << "tensor [0,0,0] element:" << torch_output_tensor[0][0][0] << std::endl; std::cout << "tensor [0,0,1] element:" << torch_output_tensor[0][0][1] << std::endl; std::cout << "tensor [0,0,0] element:" << double(torch_output_tensor.accessor<float, 3>()[0][0][0]) << std::endl; std::cout << "tensor [0,0,1] element:" << double(torch_output_tensor.accessor<float, 3>()[0][0][1]) << std::endl; return 0; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/tools/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_binary( name = "pad_terminal", srcs = ["pad_terminal.cc"], deps = [ "//cyber", "//modules/common/adapters:adapter_gflags", "//modules/common/util:util_tool", "//modules/planning/common:planning_gflags", "//modules/common_msgs/planning_msgs:pad_msg_cc_proto", "//modules/planning/proto:planning_config_cc_proto", "@com_github_gflags_gflags//:gflags", ], ) cc_binary( name = "inference_demo", srcs = ["inference_demo.cc"], deps = [ "//third_party:libtorch", "@com_github_gflags_gflags//:gflags", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/task_config.proto
syntax = "proto2"; package apollo.planning; ////////////////////////////////// // CreesDeciderConfig message CreepDeciderConfig { // stop distance(m) to the creeping stop fence while creeping optional double stop_distance = 1 [default = 0.5]; // meter optional double speed_limit = 2 [default = 1.0]; // m/s // max distance(m) to the to the creeping stop fence // to be considered as a valid stop for creep optional double max_valid_stop_distance = 3 [default = 0.3]; // meter // min boundary t to ignore obstacles while creeping optional double min_boundary_t = 4 [default = 6.0]; // second // tolerance min_t & min_s to ignore obstacles which are moving // on same direction of ADC while creeping optional double ignore_max_st_min_t = 5 [default = 0.1]; // second optional double ignore_min_st_min_s = 6 [default = 15.0]; // meter } ////////////////////////////////// // LaneChangeDeciderConfig message LaneChangeDeciderConfig { optional bool enable_lane_change_urgency_check = 1; // True to enable prioritize change_lane reference line optional bool enable_prioritize_change_lane = 2 [default = false]; // True to enable remove change_lane reference line"); optional bool enable_remove_change_lane = 3 [default = false]; // always allow the vehicle change lane. The vehicle may continue changing // lane optional bool reckless_change_lane = 4 [default = false]; // not allowed to change lane this amount of time if just finished optional double change_lane_success_freeze_time = 5 [default = 1.5]; // second // not allowed to change lane this amount of time if just failed optional double change_lane_fail_freeze_time = 6 [default = 1.0]; // second } ////////////////////////////////// // LearningModelInferenceTaskConfig message LearningModelInferenceTaskConfig { enum ModelType { CNN = 1; CNN_LSTM = 2; } optional ModelType model_type = 1; optional string cpu_model_file = 2; optional string gpu_model_file = 3; optional bool use_cuda = 4 [default = true]; // delta_t depends on the model output, not a configurable value here optional double trajectory_delta_t = 5 [default = 0.2]; // second optional bool allow_empty_learning_based_data = 6 [default = false]; optional bool allow_empty_output_trajectory = 7 [default = false]; } ////////////////////////////////// // LearningModelInferenceTrajectoryTaskConfig message LearningModelInferenceTrajectoryTaskConfig { optional double min_adc_future_trajectory_time_length = 1 [default = 2.0]; // second } ////////////////////////////////// // Navi message NaviObstacleDeciderConfig { optional double min_nudge_distance = 1 [default = 0.2]; optional double max_nudge_distance = 2 [default = 1.2]; optional double max_allow_nudge_speed = 3 [default = 16.667]; optional double safe_distance = 4 [default = 0.2]; optional double nudge_allow_tolerance = 5 [default = 0.05]; optional uint32 cycles_number = 6 [default = 3]; optional double judge_dis_coeff = 7 [default = 2.0]; optional double basis_dis_value = 8 [default = 30.0]; optional double lateral_velocity_value = 9 [default = 0.5]; optional double speed_decider_detect_range = 10 [default = 1.0]; optional uint32 max_keep_nudge_cycles = 11 [default = 100]; } message NaviPathDeciderConfig { optional double min_path_length = 1 [default = 5]; optional uint32 min_look_forward_time = 2 [default = 2]; optional double max_keep_lane_distance = 3 [default = 0.8]; optional double max_keep_lane_shift_y = 4 [default = 20.0]; optional double min_keep_lane_offset = 5 [default = 15.0]; optional double keep_lane_shift_compensation = 6 [default = 0.01]; optional MoveDestLaneConfigTable move_dest_lane_config_talbe = 7; optional double move_dest_lane_compensation = 8 [default = 0.35]; optional double max_kappa_threshold = 9 [default = 0.0]; optional double kappa_move_dest_lane_compensation = 10 [default = 0.0]; optional uint32 start_plan_point_from = 11 [default = 0]; } message MoveDestLaneConfigTable { repeated ShiftConfig lateral_shift = 1; } message ShiftConfig { optional double max_speed = 1 [default = 4.16]; optional double max_move_dest_lane_shift_y = 3 [default = 0.4]; } message NaviSpeedDeciderConfig { optional double preferred_accel = 1 [default = 2.0]; optional double preferred_decel = 2 [default = 2.0]; optional double preferred_jerk = 3 [default = 2.0]; optional double max_accel = 4 [default = 4.0]; optional double max_decel = 5 [default = 5.0]; optional double obstacle_buffer = 6 [default = 0.5]; optional double safe_distance_base = 7 [default = 2.0]; optional double safe_distance_ratio = 8 [default = 1.0]; optional double following_accel_ratio = 9 [default = 0.5]; optional double soft_centric_accel_limit = 10 [default = 1.2]; optional double hard_centric_accel_limit = 11 [default = 1.5]; optional double hard_speed_limit = 12 [default = 100.0]; optional double hard_accel_limit = 13 [default = 10.0]; optional bool enable_safe_path = 14 [default = true]; optional bool enable_planning_start_point = 15 [default = true]; optional bool enable_accel_auto_compensation = 16 [default = true]; optional double kappa_preview = 17 [default = 0.0]; optional double kappa_threshold = 18 [default = 0.0]; } ////////////////////////////////// // PathAssessmentDeciderConfig message PathAssessmentDeciderConfig {} ////////////////////////////////// // PathBoundsDeciderConfig message PathBoundsDeciderConfig { optional bool is_lane_borrowing = 1; optional bool is_pull_over = 2; // not search pull-over position if the destination is within this distance // from ADC optional double pull_over_destination_to_adc_buffer = 3 [default = 25.0]; // not search pull-over position if the destination is within this distance to // path-end optional double pull_over_destination_to_pathend_buffer = 4 [default = 10.0]; // disquality a pull-over position if the available path boundary's edge is // not within this distance from the road edge optional double pull_over_road_edge_buffer = 5 [default = 0.15]; optional double pull_over_approach_lon_distance_adjust_factor = 6 [default = 1.5]; optional double adc_buffer_coeff = 7 [default = 1.0]; optional bool is_extend_lane_bounds_to_include_adc = 8 [default = true]; } ////////////////////////////////// // PathDeciderConfig message PathDeciderConfig { // buffer for static obstacles (meter) optional double static_obstacle_buffer = 1 [default = 0.3]; } ////////////////////////////////// // PathLaneBorrowDeciderConfig message PathLaneBorrowDeciderConfig { optional bool allow_lane_borrowing = 1; } ////////////////////////////////// // PathReferenceDeciderConfig message PathReferenceDeciderConfig { optional uint32 min_path_reference_length = 1 [default = 20]; // learning model s weight optional double weight_x_ref_path_reference = 2; } ////////////////////////////////// // PathReuseDeciderConfig message PathReuseDeciderConfig { optional bool reuse_path = 1; } ////////////////////////////////// // PiecewiseJerkNonlinearSpeedOptimizerConfig message PiecewiseJerkNonlinearSpeedOptimizerConfig { // Driving comfort weights optional double acc_weight = 1 [default = 500.0]; optional double jerk_weight = 2 [default = 100.0]; optional double lat_acc_weight = 3 [default = 500.0]; // Minimal traversal time weight optional double s_potential_weight = 4 [default = 10.0]; // Preferred cruising speed weight optional double ref_v_weight = 5 [default = 10.0]; // Optional reference speed profile weight optional double ref_s_weight = 6 [default = 10.0]; // Task specific end point weight optional double end_s_weight = 7 [default = 10.0]; optional double end_v_weight = 8 [default = 10.0]; optional double end_a_weight = 9 [default = 10.0]; // soft safety boundary constraint violation weight optional double soft_s_bound_weight = 10 [default = 10.0]; // Solver settings optional bool use_warm_start = 100 [default = true]; } ////////////////////////////////// // PiecewiseJerkPathOptimizerConfig message PiecewiseJerkPathOptimizerConfig { optional PiecewiseJerkPathWeights default_path_config = 1; optional PiecewiseJerkPathWeights lane_change_path_config = 2; optional double path_reference_l_weight = 3 [default = 0.0]; } message PiecewiseJerkPathWeights { optional double l_weight = 1 [default = 1.0]; optional double dl_weight = 2 [default = 100.0]; optional double ddl_weight = 3 [default = 1000.0]; optional double dddl_weight = 4 [default = 10000.0]; } ////////////////////////////////// // PiecewiseJerkSpeedOptimizerConfig message PiecewiseJerkSpeedOptimizerConfig { optional double acc_weight = 1 [default = 1.0]; optional double jerk_weight = 2 [default = 10.0]; optional double kappa_penalty_weight = 3 [default = 1000.0]; optional double ref_s_weight = 4 [default = 10.0]; optional double ref_v_weight = 5 [default = 10.0]; } ////////////////////////////////// // RuleBasedStopDeciderConfig message RuleBasedStopDeciderConfig { optional double max_adc_stop_speed = 1 [default = 0.3]; optional double max_valid_stop_distance = 2 [default = 0.5]; optional double search_beam_length = 3 [default = 5.0]; optional double search_beam_radius_intensity = 4 [default = 0.08]; optional double search_range = 5 [default = 3.14]; optional double is_block_angle_threshold = 6 [default = 1.57]; optional double approach_distance_for_lane_change = 10 [default = 80.0]; optional double urgent_distance_for_lane_change = 11 [default = 50.0]; } ////////////////////////////////// // SpeedBoundsDeciderConfig message SpeedBoundsDeciderConfig { optional double total_time = 1 [default = 7.0]; optional double boundary_buffer = 2 [default = 0.1]; optional double max_centric_acceleration_limit = 3 [default = 2.0]; optional double minimal_kappa = 4 [default = 0.00001]; optional double point_extension = 5 [default = 1.0]; optional double lowest_speed = 6 [default = 2.5]; optional double collision_safety_range = 7 [default = 1.0]; optional double static_obs_nudge_speed_ratio = 8; optional double dynamic_obs_nudge_speed_ratio = 9; } ////////////////////////////////// // SpeedHeuristicOptimizerConfig message SpeedHeuristicOptimizerConfig { optional DpStSpeedOptimizerConfig default_speed_config = 1; optional DpStSpeedOptimizerConfig lane_change_speed_config = 2; } message DpStSpeedOptimizerConfig { optional double unit_t = 1 [default = 1.0]; optional int32 dense_dimension_s = 2 [default = 41]; optional double dense_unit_s = 3 [default = 0.5]; optional double sparse_unit_s = 4 [default = 1.0]; optional double speed_weight = 10 [default = 0.0]; optional double accel_weight = 11 [default = 10.0]; optional double jerk_weight = 12 [default = 10.0]; optional double obstacle_weight = 13 [default = 1.0]; optional double reference_weight = 14 [default = 0.0]; optional double go_down_buffer = 15 [default = 5.0]; optional double go_up_buffer = 16 [default = 5.0]; // obstacle cost config optional double default_obstacle_cost = 20 [default = 1e10]; // speed cost config optional double default_speed_cost = 31 [default = 1.0]; optional double exceed_speed_penalty = 32 [default = 10.0]; optional double low_speed_penalty = 33 [default = 2.5]; optional double reference_speed_penalty = 34 [default = 1.0]; optional double keep_clear_low_speed_penalty = 35 [default = 10.0]; // accel cost config optional double accel_penalty = 40 [default = 2.0]; optional double decel_penalty = 41 [default = 2.0]; // jerk cost config optional double positive_jerk_coeff = 50 [default = 1.0]; optional double negative_jerk_coeff = 51 [default = 300.0]; // other constraint optional double max_acceleration = 60 [default = 4.5]; optional double max_deceleration = 61 [default = -4.5]; // buffer optional double safe_time_buffer = 70 [default = 3.0]; optional double safe_distance = 71 [default = 20.0]; // spatial potential cost config for minimal time traversal optional double spatial_potential_penalty = 80 [default = 1.0]; optional bool is_lane_changing = 81 [default = false]; } ////////////////////////////////// // STBoundsDeciderConfig message STBoundsDeciderConfig { optional double total_time = 1 [default = 7.0]; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/st_drivable_boundary.proto
syntax = "proto2"; package apollo.planning; message STDrivableBoundaryInstance { optional double t = 1; optional double s_lower = 2; optional double s_upper = 3; optional double v_obs_lower = 4; optional double v_obs_upper = 5; } message STDrivableBoundary { repeated STDrivableBoundaryInstance st_boundary = 1; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/planning_config.proto
syntax = "proto2"; package apollo.planning; import "modules/planning/proto/open_space_task_config.proto"; import "modules/planning/proto/task_config.proto"; import "modules/common_msgs/planning_msgs/scenario_type.proto"; // Planning's configuration is based on the following architecture // * Scenario has one more multiple stages // * a stage has one or more // tasks are shared among all scenarios and stages. message TaskConfig { enum TaskType { // deciders CREEP_DECIDER = 1; LANE_CHANGE_DECIDER = 2; NAVI_OBSTACLE_DECIDER = 3; NAVI_PATH_DECIDER = 4; NAVI_SPEED_DECIDER = 5; OPEN_SPACE_FALLBACK_DECIDER = 6; OPEN_SPACE_PRE_STOP_DECIDER = 7; OPEN_SPACE_ROI_DECIDER = 8; PATH_ASSESSMENT_DECIDER = 9; PATH_BOUNDS_DECIDER = 10; PATH_DECIDER = 11; PATH_LANE_BORROW_DECIDER = 12; PATH_REFERENCE_DECIDER = 13; PATH_REUSE_DECIDER = 14; RSS_DECIDER = 15; RULE_BASED_STOP_DECIDER = 16; SPEED_BOUNDS_PRIORI_DECIDER = 17; SPEED_BOUNDS_FINAL_DECIDER = 18; SPEED_DECIDER = 19; ST_BOUNDS_DECIDER = 20; // optimizers OPEN_SPACE_TRAJECTORY_PARTITION = 21; OPEN_SPACE_TRAJECTORY_PROVIDER = 22; PIECEWISE_JERK_NONLINEAR_SPEED_OPTIMIZER = 23; PIECEWISE_JERK_PATH_OPTIMIZER = 24; PIECEWISE_JERK_SPEED_OPTIMIZER = 25; SPEED_HEURISTIC_OPTIMIZER = 26; // other tasks LEARNING_MODEL_INFERENCE_TASK = 27; LEARNING_MODEL_INFERENCE_TRAJECTORY_TASK = 28; }; optional TaskType task_type = 1; oneof task_config { // deciders CreepDeciderConfig creep_decider_config = 2; LaneChangeDeciderConfig lane_change_decider_config = 3; OpenSpaceFallBackDeciderConfig open_space_fallback_decider_config = 4; OpenSpacePreStopDeciderConfig open_space_pre_stop_decider_config = 5; OpenSpaceRoiDeciderConfig open_space_roi_decider_config = 6; PathAssessmentDeciderConfig path_assessment_decider_config = 7; PathBoundsDeciderConfig path_bounds_decider_config = 8; PathDeciderConfig path_decider_config = 9; PathLaneBorrowDeciderConfig path_lane_borrow_decider_config = 10; PathReferenceDeciderConfig path_reference_decider_config = 11; PathReuseDeciderConfig path_reuse_decider_config = 12; RuleBasedStopDeciderConfig rule_based_stop_decider_config = 13; SpeedBoundsDeciderConfig speed_bounds_decider_config = 14; STBoundsDeciderConfig st_bounds_decider_config = 15; // optimizers OpenSpaceTrajectoryPartitionConfig open_space_trajectory_partition_config = 16; OpenSpaceTrajectoryProviderConfig open_space_trajectory_provider_config = 17; PiecewiseJerkNonlinearSpeedOptimizerConfig piecewise_jerk_nonlinear_speed_optimizer_config = 18; PiecewiseJerkPathOptimizerConfig piecewise_jerk_path_optimizer_config = 19; PiecewiseJerkSpeedOptimizerConfig piecewise_jerk_speed_optimizer_config = 20; SpeedHeuristicOptimizerConfig speed_heuristic_optimizer_config = 21; // other tasks LearningModelInferenceTaskConfig learning_model_inference_task_config = 22; LearningModelInferenceTrajectoryTaskConfig learning_model_inference_trajectory_task_config = 23; } } message ScenarioBareIntersectionUnprotectedConfig { optional double start_bare_intersection_scenario_distance = 1 [default = 25.0]; // meter // explicit stop while waiting optional bool enable_explicit_stop = 2 [default = false]; optional double min_pass_s_distance = 3 [default = 3.0]; // meter optional double approach_cruise_speed = 4 [default = 6.7056]; // m/s (15 mph) optional double stop_distance = 5 [default = 0.5]; // meter optional float stop_timeout_sec = 6 [default = 8.0]; // sec optional float creep_timeout_sec = 7 [default = 10.0]; // sec } message ScenarioEmergencyPullOverConfig { optional double max_stop_deceleration = 1 [default = 3.0]; optional double slow_down_deceleration_time = 2 [default = 3.0]; // second optional double target_slow_down_speed = 3 [default = 2.5]; // m/s optional double stop_distance = 4 [default = 1.5]; // meter } message ScenarioEmergencyStopConfig { optional double max_stop_deceleration = 1 [default = 6.0]; optional double stop_distance = 2 [default = 1.0]; // meter } message ScenarioLaneFollowConfig {} message ScenarioLearningModelSampleConfig {} message ScenarioNarrowStreetUTurnConfig {} message ScenarioParkAndGoConfig { optional double front_obstacle_buffer = 1 [default = 4.0]; // meter optional double heading_buffer = 2 [default = 0.5]; // rad optional double min_dist_to_dest = 3 [default = 25.0]; // meter optional double max_steering_percentage_when_cruise = 4 [default = 90.0]; } message ScenarioPullOverConfig { optional double start_pull_over_scenario_distance = 1 [default = 50.0]; // meter optional double pull_over_min_distance_buffer = 2 [default = 10.0]; // meter // keep the same value as pull_over_destination_to_adc_buffer in // PathBoundsDeciderConfig optional double max_distance_stop_search = 3 [default = 25.0]; // meter optional double max_s_error_to_end_point = 4 [default = 0.2]; optional double max_l_error_to_end_point = 5 [default = 0.5]; optional double max_theta_error_to_end_point = 6 [default = 0.2]; optional double max_distance_error_to_end_point = 7 [default = 0.2]; optional double pass_destination_threshold = 8 [default = 10.0]; optional double max_valid_stop_distance = 9 [default = 1.0]; optional double s_distance_to_stop_for_open_space_parking = 10 [default = 7.0]; } message ScenarioStopSignUnprotectedConfig { optional double start_stop_sign_scenario_distance = 1 [default = 5.0]; // meter optional double watch_vehicle_max_valid_stop_distance = 2 [default = 5.0]; // meter optional double max_valid_stop_distance = 3 [default = 3.5]; // meter optional float stop_duration_sec = 4 [default = 1.0]; // sec optional double min_pass_s_distance = 5 [default = 3.0]; // meter optional float stop_timeout_sec = 6 [default = 8.0]; // sec optional float creep_timeout_sec = 7 [default = 10.0]; // sec } message ScenarioTrafficLightProtectedConfig { optional double start_traffic_light_scenario_distance = 1 [default = 5.0]; // meter optional double max_valid_stop_distance = 2 [default = 2.0]; // meter optional double min_pass_s_distance = 3 [default = 3.0]; // meter } message ScenarioTrafficLightUnprotectedLeftTurnConfig { optional double start_traffic_light_scenario_distance = 1 [default = 5.0]; // meter optional double approach_cruise_speed = 2 [default = 2.78]; // m/s (10km/h) optional double max_valid_stop_distance = 3 [default = 3.5]; // meter optional double min_pass_s_distance = 4 [default = 3.0]; // meter optional float creep_timeout_sec = 5 [default = 10.0]; // sec optional double max_adc_speed_before_creep = 6 [default = 5.56]; // m/s (20m/h) } message ScenarioTrafficLightUnprotectedRightTurnConfig { optional double start_traffic_light_scenario_distance = 1 [default = 5.0]; // meter optional bool enable_right_turn_on_red = 2 [default = false]; optional double max_valid_stop_distance = 3 [default = 3.5]; // meter optional double min_pass_s_distance = 4 [default = 3.0]; // meter optional float red_light_right_turn_stop_duration_sec = 5 [default = 3.0]; // sec optional float creep_timeout_sec = 6 [default = 10.0]; // sec optional double max_adc_speed_before_creep = 7 [default = 3.0]; // m/s } message ScenarioValetParkingConfig { optional double parking_spot_range_to_start = 1 [default = 20.0]; optional double max_valid_stop_distance = 2 [default = 1.0]; // meter } message ScenarioDeadEndTurnAroundConfig { optional double dead_end_start_range = 1 [default = 20.0]; optional double max_valid_stop_distance = 2 [default = 1.0]; // meter } message ScenarioYieldSignConfig { optional double start_yield_sign_scenario_distance = 1 [default = 10.0]; // meter optional double max_valid_stop_distance = 2 [default = 4.5]; // meter optional double min_pass_s_distance = 3 [default = 3.0]; // meter optional float creep_timeout_sec = 4 [default = 10.0]; // sec } // scenario configs message ScenarioConfig { message StageConfig { optional StageType stage_type = 1; optional bool enabled = 2 [default = true]; // an ordered list of tasks that are used at runtime. // the order determines the runtime order of the tasks. repeated TaskConfig.TaskType task_type = 3; // an unordered task configurations repeated TaskConfig task_config = 4; } optional ScenarioType scenario_type = 1; oneof scenario_config { ScenarioLaneFollowConfig lane_follow_config = 2; ScenarioBareIntersectionUnprotectedConfig bare_intersection_unprotected_config = 3; ScenarioEmergencyPullOverConfig emergency_pull_over_config = 4; ScenarioEmergencyStopConfig emergency_stop_config = 5; ScenarioLearningModelSampleConfig learning_model_sample_config = 6; ScenarioNarrowStreetUTurnConfig narrow_street_u_turn_config = 7; ScenarioParkAndGoConfig park_and_go_config = 8; ScenarioPullOverConfig pull_over_config = 9; ScenarioStopSignUnprotectedConfig stop_sign_unprotected_config = 10; ScenarioTrafficLightProtectedConfig traffic_light_protected_config = 11; ScenarioTrafficLightUnprotectedLeftTurnConfig traffic_light_unprotected_left_turn_config = 12; ScenarioTrafficLightUnprotectedRightTurnConfig traffic_light_unprotected_right_turn_config = 13; ScenarioValetParkingConfig valet_parking_config = 14; ScenarioYieldSignConfig yield_sign_config = 15; ScenarioDeadEndTurnAroundConfig deadend_turnaround_config = 18; } // a list of stages that are used at runtime. The first one is default stage. repeated StageType stage_type = 16; // an unordered list of stage configs. repeated StageConfig stage_config = 17; } message PlannerPublicRoadConfig {} message PlannerNaviConfig { repeated TaskConfig.TaskType task = 1; optional NaviPathDeciderConfig navi_path_decider_config = 2; optional NaviSpeedDeciderConfig navi_speed_decider_config = 3; optional NaviObstacleDeciderConfig navi_obstacle_decider_config = 4; } enum PlannerType { RTK = 0; PUBLIC_ROAD = 1; // public road planner NAVI = 2; // navigation planner LATTICE = 3; // lattice planner } message RtkPlanningConfig { optional PlannerType planner_type = 1; } message StandardPlanningConfig { repeated PlannerType planner_type = 1; // supported planners optional PlannerPublicRoadConfig planner_public_road_config = 2; } message NavigationPlanningConfig { repeated PlannerType planner_type = 1; // supported planners optional PlannerNaviConfig planner_navi_config = 4; } message TopicConfig { optional string chassis_topic = 1; optional string hmi_status_topic = 2; optional string localization_topic = 3; optional string planning_pad_topic = 4; optional string planning_trajectory_topic = 5; optional string prediction_topic = 6; optional string relative_map_topic = 7; optional string routing_request_topic = 8; optional string routing_response_topic = 9; optional string story_telling_topic = 10; optional string traffic_light_detection_topic = 11; optional string planning_learning_data_topic = 12; } message PlanningConfig { enum PlanningLearningMode { NO_LEARNING = 0; E2E = 1; HYBRID = 2; RL_TEST = 3; E2E_TEST = 4; HYBRID_TEST = 5; } optional TopicConfig topic_config = 1; optional PlanningLearningMode learning_mode = 2; oneof planning_config { RtkPlanningConfig rtk_planning_config = 3; StandardPlanningConfig standard_planning_config = 4; NavigationPlanningConfig navigation_planning_config = 5; } // default task config, it will be used if there is no scenario-specific // task config. repeated TaskConfig default_task_config = 6; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/planner_open_space_config.proto
syntax = "proto2"; import "modules/planning/proto/math/fem_pos_deviation_smoother_config.proto"; import "modules/planning/proto/task_config.proto"; package apollo.planning; enum DualWarmUpMode { IPOPT = 0; IPOPTQP = 1; OSQP = 2; DEBUG = 3; SLACKQP = 4; } enum DistanceApproachMode { DISTANCE_APPROACH_IPOPT = 0; DISTANCE_APPROACH_IPOPT_CUDA = 1; DISTANCE_APPROACH_IPOPT_FIXED_TS = 2; DISTANCE_APPROACH_IPOPT_FIXED_DUAL = 3; DISTANCE_APPROACH_IPOPT_RELAX_END = 4; DISTANCE_APPROACH_IPOPT_RELAX_END_SLACK = 5; } message PlannerOpenSpaceConfig { // Open Space ROIConfig optional ROIConfig roi_config = 1; // Hybrid A Star Warm Start optional WarmStartConfig warm_start_config = 2; // Dual Variable Warm Start optional DualVariableWarmStartConfig dual_variable_warm_start_config = 3; // Distance Approach Configs optional DistanceApproachConfig distance_approach_config = 4; // Iterative Anchoring Configs optional IterativeAnchoringConfig iterative_anchoring_smoother_config = 5; // Trajectory PartitionConfig Configs optional TrajectoryPartitionConfig trajectory_partition_config = 6; optional float delta_t = 7 [default = 1.0]; optional double is_near_destination_threshold = 8 [default = 0.001]; optional bool enable_check_parallel_trajectory = 9 [default = false]; optional bool enable_linear_interpolation = 10 [default = false]; optional double is_near_destination_theta_threshold = 11 [default = 0.05]; } message ROIConfig { // longitudinal range of parking roi backward optional double roi_longitudinal_range_start = 1 [default = 10.0]; // longitudinal range of parking roi forward optional double roi_longitudinal_range_end = 2 [default = 10.0]; // parking spot range detection threshold optional double parking_start_range = 3 [default = 7.0]; // Parking orientation for reverse parking optional bool parking_inwards = 4 [default = false]; } message WarmStartConfig { // Hybrid a star for warm start optional double xy_grid_resolution = 1 [default = 0.2]; optional double phi_grid_resolution = 2 [default = 0.05]; optional uint64 next_node_num = 3 [default = 10]; optional double step_size = 4 [default = 0.5]; optional double traj_forward_penalty = 5 [default = 0.0]; optional double traj_back_penalty = 6 [default = 0.0]; optional double traj_gear_switch_penalty = 7 [default = 10.0]; optional double traj_steer_penalty = 8 [default = 100.0]; optional double traj_steer_change_penalty = 9 [default = 10.0]; // Grid a star for heuristic optional double grid_a_star_xy_resolution = 15 [default = 0.1]; optional double node_radius = 16 [default = 0.5]; optional PiecewiseJerkSpeedOptimizerConfig s_curve_config = 17; optional double traj_kappa_contraint_ratio = 10 [default = 0.7]; } message DualVariableWarmStartConfig { // Dual variable Warm Start optional double weight_d = 1 [default = 1.0]; optional IpoptConfig ipopt_config = 2; optional DualWarmUpMode qp_format = 3; optional double min_safety_distance = 4 [default = 0.0]; optional bool debug_osqp = 5 [default = false]; optional double beta = 6 [default = 1.0]; optional OSQPConfig osqp_config = 7; } message DistanceApproachConfig { // Distance approach weight configs optional double weight_steer = 1; optional double weight_a = 2; optional double weight_steer_rate = 3; optional double weight_a_rate = 4; optional double weight_x = 5; optional double weight_y = 6; optional double weight_phi = 7; optional double weight_v = 8; optional double weight_steer_stitching = 9; optional double weight_a_stitching = 10; optional double weight_first_order_time = 11; optional double weight_second_order_time = 12; optional double min_safety_distance = 13 [default = 0.0]; optional double max_speed_forward = 14 [default = 3.0]; optional double max_speed_reverse = 15 [default = 2.0]; optional double max_acceleration_forward = 16 [default = 2.0]; optional double max_acceleration_reverse = 17 [default = 2.0]; optional double min_time_sample_scaling = 18 [default = 0.1]; optional double max_time_sample_scaling = 19 [default = 10.0]; optional bool use_fix_time = 20 [default = false]; optional IpoptConfig ipopt_config = 21; optional bool enable_constraint_check = 22; optional bool enable_hand_derivative = 23; // True to enable hand derived derivative inside open space planner optional bool enable_derivative_check = 24; // True to enable derivative check inside open space planner optional bool enable_initial_final_check = 25 [default = false]; optional DistanceApproachMode distance_approach_mode = 26; optional bool enable_jacobian_ad = 27 [default = false]; optional bool enable_check_initial_state = 28 [default = false]; optional double weight_end_state = 29 [default = 0.0]; optional double weight_slack = 30 [default = 0.0]; } message IpoptConfig { // Ipopt configs optional int32 ipopt_print_level = 1; optional int32 mumps_mem_percent = 2; optional double mumps_pivtol = 3; optional int32 ipopt_max_iter = 4; optional double ipopt_tol = 5; optional double ipopt_acceptable_constr_viol_tol = 6; optional double ipopt_min_hessian_perturbation = 7; optional double ipopt_jacobian_regularization_value = 8; optional string ipopt_print_timing_statistics = 9; optional string ipopt_alpha_for_y = 10; optional string ipopt_recalc_y = 11; optional double ipopt_mu_init = 12 [default = 0.1]; // ipopt barrier parameter, default 0.1 } // Dual variable configs for OSQP message OSQPConfig { optional double alpha = 1 [default = 1.0]; optional double eps_abs = 2 [default = 1.0e-3]; optional double eps_rel = 3 [default = 1.0e-3]; optional int32 max_iter = 4 [default = 10000]; optional bool polish = 5 [default = true]; optional bool osqp_debug_log = 6 [default = false]; } message IterativeAnchoringConfig { // Ipopt configs optional double interpolated_delta_s = 1 [default = 0.1]; optional int32 reanchoring_trails_num = 2 [default = 50]; optional double reanchoring_pos_stddev = 3 [default = 0.25]; optional double reanchoring_length_stddev = 4 [default = 1.0]; optional bool estimate_bound = 5 [default = false]; optional double default_bound = 6 [default = 2.0]; optional double vehicle_shortest_dimension = 7 [default = 1.04]; optional FemPosDeviationSmootherConfig fem_pos_deviation_smoother_config = 8; optional double collision_decrease_ratio = 9 [default = 0.9]; // TODO(QiL, Jinyun): Merge following with overall config for open space optional double max_forward_v = 10 [default = 2.0]; optional double max_reverse_v = 11 [default = 2.0]; optional double max_forward_acc = 12 [default = 3.0]; optional double max_reverse_acc = 13 [default = 2.0]; optional double max_acc_jerk = 14 [default = 4.0]; optional double delta_t = 15 [default = 0.2]; optional PiecewiseJerkSpeedOptimizerConfig s_curve_config = 16; } message TrajectoryPartitionConfig { optional uint64 interpolated_pieces_num = 1 [default = 50]; optional uint64 initial_gear_check_horizon = 2 [default = 3]; optional double heading_searching_range = 3 [default = 0.3]; optional double gear_shift_period_duration = 4 [default = 2.0]; optional double gear_shift_max_t = 5 [default = 3.0]; optional double gear_shift_unit_t = 6 [default = 0.02]; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/planning_stats.proto
syntax = "proto2"; package apollo.planning; message StatsGroup { optional double max = 1; optional double min = 2 [default = 1e10]; optional double sum = 3; optional double avg = 4; optional int32 num = 5; }; message PlanningStats { optional StatsGroup total_path_length = 1; optional StatsGroup total_path_time = 2; // linear velocity optional StatsGroup v = 3; // acceleration optional StatsGroup a = 4; optional StatsGroup kappa = 5; optional StatsGroup dkappa = 6; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/planning_semantic_map_config.proto
syntax = "proto2"; package apollo.planning; message PlanningSemanticMapConfig { // resolution(m / pixel) of local map img and base map img optional double resolution = 1; // [height, width] of a local map img centering around ego vehicle optional int32 height = 100; optional int32 width = 101; // ego vehicle rear center location in the local map img with origin point at // top left corner optional int32 ego_idx_x = 102; optional int32 ego_idx_y = 103; // ego vehicle is normally heading upward in the local map img, but a // randomized change of heading could be used optional double max_rand_delta_phi = 104; // ego vehicle max future trajectory time horizon optional double max_ego_future_horizon = 105; // ego vehicle max past trajectory time horizon optional double max_ego_past_horizon = 106; // ego obstacle max prediction trajectory time horizon optional double max_obs_future_horizon = 107; // ego obstacle max past trajectory time horizon optional double max_obs_past_horizon = 108; // padding(pixel) around base map of region map optional int32 base_map_padding = 200; // max_speed_limit in base speed limit map optional double city_driving_max_speed = 201; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/traffic_rule_config.proto
syntax = "proto2"; package apollo.planning; message BacksideVehicleConfig { // a vehicle is considered within current lane if it is behind the ADC and its // lateral difference is less than this number. optional double backside_lane_width = 1 [default = 4.0]; } message CrosswalkConfig { // stop distance from stop line of crosswalk optional double stop_distance = 1 [default = 1.0]; // meter // max deceleration optional double max_stop_deceleration = 2 [default = 4.0]; // min s_distance for adc to be considered have passed crosswalk // (stop_line_end_s) optional double min_pass_s_distance = 3 [default = 1.0]; // meter // max distance(m) to the stop line to be considered as a valid stop optional double max_valid_stop_distance = 4 [default = 3.0]; // meter // expand s_distance for pedestrian/bicycle detection optional double expand_s_distance = 5 [default = 2.0]; // meter // strict stop rule within this l_distance optional double stop_strict_l_distance = 6 [default = 4.0]; // meter // loose stop rule beyond this l_distance optional double stop_loose_l_distance = 7 [default = 5.0]; // meter // stop timeout for bicycles/pedestrians which are not moving optional double stop_timeout = 8 [default = 10.0]; // second } message DestinationConfig { // stop distance from destination line optional double stop_distance = 1 [default = 0.5]; // meter } message KeepClearConfig { // min s_distance to be considered have passed keep_clear (stop_line_end_s) optional bool enable_keep_clear_zone = 1 [default = true]; optional bool enable_junction = 2 [default = true]; optional double min_pass_s_distance = 3 [default = 2.0]; // meter // tolerance distance to align pnc_junction boundary with stop_line of traffic // sign(s) optional double align_with_traffic_sign_tolerance = 4 [default = 4.5]; // meter } message ReferenceLineEndConfig { // stop distance from reference line end optional double stop_distance = 1 [default = 0.5]; // meter optional double min_reference_line_remain_length = 2 [default = 50.0]; } message ReroutingConfig { // should not rerouting more frequent than this number optional double cooldown_time = 1 [default = 3.0]; // seconds optional double prepare_rerouting_time = 2 [default = 2.0]; // seconds } message StopSignConfig { optional bool enabled = 1 [default = true]; // stop distance(m) to the stop line of the stop sign optional double stop_distance = 2 [default = 1.0]; // meter } message TrafficLightConfig { optional bool enabled = 1 [default = true]; // stop distance(m) to the stop line of the traffic light optional double stop_distance = 2 [default = 1.0]; // meter // max deceleration optional double max_stop_deceleration = 3 [default = 4.0]; } message YieldSignConfig { optional bool enabled = 1 [default = true]; // stop distance(m) to the stop line of the yield sign optional double stop_distance = 2 [default = 1.0]; // meter optional double start_watch_distance = 3 [default = 2.0]; // meter } message TrafficRuleConfig { enum RuleId { BACKSIDE_VEHICLE = 1; CROSSWALK = 2; DESTINATION = 3; KEEP_CLEAR = 4; REFERENCE_LINE_END = 5; REROUTING = 6; STOP_SIGN = 7; TRAFFIC_LIGHT = 8; YIELD_SIGN = 9; } optional RuleId rule_id = 1; optional bool enabled = 2; oneof config { BacksideVehicleConfig backside_vehicle = 3; CrosswalkConfig crosswalk = 4; DestinationConfig destination = 5; KeepClearConfig keep_clear = 6; ReferenceLineEndConfig reference_line_end = 7; ReroutingConfig rerouting = 8; StopSignConfig stop_sign = 9; TrafficLightConfig traffic_light = 10; YieldSignConfig yield_sign = 11; } } message TrafficRuleConfigs { repeated TrafficRuleConfig config = 1; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/open_space_task_config.proto
syntax = "proto2"; package apollo.planning; import "modules/planning/proto/planner_open_space_config.proto"; ////////////////////////////////// // OpenSpaceFallBackDeciderConfig message OpenSpaceFallBackDeciderConfig { // prediction time horizon for prediction obstacles optional double open_space_prediction_time_period = 1 [default = 5.0]; // fallback collision check distance optional double open_space_fallback_collision_distance = 2 [default = 5.0]; // fallback stop trajectory safety gap to obstacles optional double open_space_fallback_stop_distance = 3 [default = 2.0]; // fallback collision time buffer (s) optional double open_space_fallback_collision_time_buffer = 4 [default = 10.0]; } ////////////////////////////////// // OpenSpacePreStopDeciderConfig message OpenSpacePreStopDeciderConfig { // roi scenario definitions enum StopType { NOT_DEFINED = 0; PARKING = 1; PULL_OVER = 2; NARROW_STREET_U_TURN = 3; DEAD_END_PRE_STOP = 4; } optional StopType stop_type = 1; optional double rightaway_stop_distance = 2 [default = 2.0]; // meter optional double stop_distance_to_target = 3 [default = 5.0]; // second } ////////////////////////////////// // OpenSpaceRoiDeciderConfig message OpenSpaceRoiDeciderConfig { // roi scenario definitions enum RoiType { NOT_DEFINED = 0; PARKING = 1; PULL_OVER = 2; PARK_AND_GO = 3; NARROW_STREET_U_TURN = 4; DEAD_END = 5; } optional RoiType roi_type = 1; // longitudinal range of parking roi start optional double roi_longitudinal_range_start = 2 [default = 10.0]; // longitudinal range of parking roi end optional double roi_longitudinal_range_end = 3 [default = 10.0]; // parking spot range detection threshold optional double parking_start_range = 4 [default = 7.0]; // Parking orientation for reverse parking optional bool parking_inwards = 5 [default = false]; // wrap previous gflags optional bool enable_perception_obstacles = 6; // buffer distance from vehicle's edge to parking spot end line optional double parking_depth_buffer = 7 [default = 0.1]; // min angle difference to stitch a new segment in roi representation optional double roi_line_segment_min_angle = 8 [default = 0.3]; optional double roi_line_segment_length = 9 [default = 1.0]; // roi line segment length when getting road boundary from map optional double roi_line_segment_length_from_map = 10 [default = 10.0]; // relative distance threshold to filter out ignored obstacle optional double perception_obstacle_filtering_distance = 11 [default = 1000.0]; // buffer distance for perception obstacle optional double perception_obstacle_buffer = 12; // tolerance limit for road_bound_width abnormal changes optional double curb_heading_tangent_change_upper_limit = 13 [default = 1.0]; // end pose s distance to current vehicle optional double end_pose_s_distance = 14 [default = 10.0]; // end pose x to parallel parking optional double parallel_park_end_x_buffer = 15 [default = 0.2]; // extend right spot width size optional double extend_right_x_buffer = 16 [default = 0.0]; // extend left spot width size optional double extend_left_x_buffer = 17 [default = 0.0]; } ////////////////////////////////// // OpenSpaceTrajectoryPartitionConfig message OpenSpaceTrajectoryPartitionConfig { // Gear shift trajectory parameter optional double gear_shift_max_t = 1; optional double gear_shift_unit_t = 2; optional double gear_shift_period_duration = 3; optional uint64 interpolated_pieces_num = 4; optional uint64 initial_gear_check_horizon = 5; // @brief heading search range is the range to filter out too large // angle difference between vehicle heading and pathpoint heading optional double heading_search_range = 6; // @brief heading_track_range is the range to filter out too large // angle difference between vehicle heading and vehicle to pathpoint vector optional double heading_track_range = 7; optional double distance_search_range = 8 [default = 1.0e-6]; // @brief IOU, intersection over union optional double heading_offset_to_midpoint = 9; optional double lateral_offset_to_midpoint = 10 [default = 0.1]; optional double longitudinal_offset_to_midpoint = 11 [default = 0.1]; optional double vehicle_box_iou_threshold_to_midpoint = 12 [default = 0.95]; optional double linear_velocity_threshold_on_ego = 13 [default = 0.2]; } ////////////////////////////////// // OpenSpaceTrajectoryProviderConfig message OpenSpaceTrajectoryProviderConfig { // TODO(Jinyun) Move PlannerOpenSpaceConfig to // OpenSpaceTrajectoryOptimizerConfig optional OpenSpaceTrajectoryOptimizerConfig open_space_trajectory_optimizer_config = 1; } message OpenSpaceTrajectoryOptimizerConfig { enum TrajectorySmoother { ITERATIVE_ANCHORING_SMOOTHER = 0; DISTANCE_APPROACH = 1; USE_WARM_START = 2; } // Hybrid a star warm start configs optional HybridAStarConfig hybrid_a_star_config = 1; // Dual variable configs optional DualVariableConfig dual_variable_warm_start_config = 2; optional TrajectorySmoother trajectory_smoother = 7 [default = USE_WARM_START]; // Distance approach trajectory smoothing configs optional DistanceApproachTrajectorySmootherConfig distance_approach_trajectory_smoother_config = 3; optional float delta_t = 4 [default = 0.5]; optional double is_near_destination_threshold = 5 [default = 0.001]; // (TODO:(QiL) tmp message during refactoring, deprecate when all tuning done. optional PlannerOpenSpaceConfig planner_open_space_config = 6; } // Hybrid a star as warm start for later smoothing message HybridAStarConfig { optional double xy_grid_resolution = 1 [default = 0.2]; optional double phi_grid_resolution = 2 [default = 0.05]; optional uint64 next_node_num = 3 [default = 10]; optional double step_size = 4 [default = 0.5]; optional double traj_forward_penalty = 5 [default = 0.0]; optional double traj_back_penalty = 6 [default = 0.0]; optional double traj_gear_switch_penalty = 7 [default = 10.0]; optional double traj_steer_penalty = 8 [default = 100.0]; optional double traj_steer_change_penalty = 9 [default = 10.0]; optional double grid_a_star_xy_resolution = 15 [default = 0.1]; optional double node_radius = 16 [default = 0.5]; } enum DualVariableMode { DUAL_VARIABLE_IPOPT = 0; DUAL_VARIABLE_IPOPTQP = 1; DUAL_VARIABLE_OSQP = 2; DUAL_VARIABLE_DEBUG = 3; } // Dual variable configs for warm starting distance approach trajectory // smoothing message DualVariableConfig { optional double weight_d = 1 [default = 1.0]; optional IpoptSolverConfig ipopt_config = 2; optional DualVariableMode qp_format = 3; optional double min_safety_distance = 4 [default = 0.0]; optional bool debug_osqp = 5 [default = false]; optional double beta = 6 [default = 1.0]; } // Distance approach trajectory smoothing configs message DistanceApproachTrajectorySmootherConfig { optional double weight_steer = 1; optional double weight_a = 2; optional double weight_steer_rate = 3; optional double weight_a_rate = 4; optional double weight_x = 5; optional double weight_y = 6; optional double weight_phi = 7; optional double weight_v = 8; optional double weight_steer_stitching = 9; optional double weight_a_stitching = 10; optional double weight_first_order_time = 11; optional double weight_second_order_time = 12; optional double min_safety_distance = 13 [default = 0.0]; optional double max_speed_forward = 14 [default = 3.0]; optional double max_speed_reverse = 15 [default = 2.0]; optional double max_acceleration_forward = 16 [default = 2.0]; optional double max_acceleration_reverse = 17 [default = 2.0]; optional double min_time_sample_scaling = 18 [default = 0.1]; optional double max_time_sample_scaling = 19 [default = 10.0]; optional bool use_fix_time = 20 [default = false]; optional IpoptSolverConfig ipopt_config = 21; optional bool enable_constraint_check = 22; optional bool enable_hand_derivative = 23; // True to enable hand derived derivative inside open space planner optional bool enable_derivative_check = 24; // True to enable derivative check inside open space planner optional bool enable_initial_final_check = 25 [default = false]; } // Ipopt configs message IpoptSolverConfig { optional int32 ipopt_print_level = 1; optional int32 mumps_mem_percent = 2; optional double mumps_pivtol = 3; optional int32 ipopt_max_iter = 4; optional double ipopt_tol = 5; optional double ipopt_acceptable_constr_viol_tol = 6; optional double ipopt_min_hessian_perturbation = 7; optional double ipopt_jacobian_regularization_value = 8; optional string ipopt_print_timing_statistics = 9; optional string ipopt_alpha_for_y = 10; optional string ipopt_recalc_y = 11; optional double ipopt_mu_init = 12 [default = 0.1]; // ipopt barrier parameter, default 0.1 }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/planning_status.proto
syntax = "proto2"; package apollo.planning; import "modules/common_msgs/basic_msgs/geometry.proto"; import "modules/planning/proto/planning_config.proto"; import "modules/common_msgs/routing_msgs/routing.proto"; import "modules/common_msgs/planning_msgs/scenario_type.proto"; /* This file defines the data types that represents the internal state of the planning module. It will not be refreshed in each planning cycle. */ message BareIntersectionStatus { optional string current_pnc_junction_overlap_id = 1; optional string done_pnc_junction_overlap_id = 2; optional uint32 clear_counter = 3; } message ChangeLaneStatus { enum Status { IN_CHANGE_LANE = 1; // during change lane state CHANGE_LANE_FAILED = 2; // change lane failed CHANGE_LANE_FINISHED = 3; // change lane finished } optional Status status = 1; // the id of the route segment that the vehicle is driving on optional string path_id = 2; // the time stamp when the state started. optional double timestamp = 3; // the starting position only after which lane-change can happen. optional bool exist_lane_change_start_position = 4 [default = false]; optional apollo.common.Point3D lane_change_start_position = 5; // the last time stamp when the lane-change planning succeed. optional double last_succeed_timestamp = 6; // if the current path and speed planning on the lane-change // reference-line succeed. optional bool is_current_opt_succeed = 7 [default = false]; // denotes if the surrounding area is clear for ego vehicle to // change lane at this moment. optional bool is_clear_to_change_lane = 8 [default = false]; } message CreepDeciderStatus { optional uint32 creep_clear_counter = 1; } message StopTime { optional string obstacle_id = 1; // the timestamp when start stopping for the crosswalk optional double stop_timestamp_sec = 2; } message CrosswalkStatus { optional string crosswalk_id = 1; // the timestamp when start stopping for the crosswalk repeated StopTime stop_time = 2; repeated string finished_crosswalk = 3; } message DestinationStatus { optional bool has_passed_destination = 1 [default = false]; } message EmergencyStopStatus { optional apollo.common.PointENU stop_fence_point = 1; } message OpenSpaceStatus { repeated string partitioned_trajectories_index_history = 1; optional bool position_init = 2 [default = false]; } message ParkAndGoStatus { optional apollo.common.PointENU adc_init_position = 1; optional double adc_init_heading = 2; optional bool in_check_stage = 3; optional apollo.common.PointENU adc_adjust_end_pose = 4; } message PathDeciderStatus { enum LaneBorrowDirection { LEFT_BORROW = 1; // borrow left neighbor lane RIGHT_BORROW = 2; // borrow right neighbor lane } optional int32 front_static_obstacle_cycle_counter = 1 [default = 0]; optional int32 able_to_use_self_lane_counter = 2 [default = 0]; optional bool is_in_path_lane_borrow_scenario = 3 [default = false]; optional string front_static_obstacle_id = 4 [default = ""]; repeated LaneBorrowDirection decided_side_pass_direction = 5; } message PullOverStatus { enum PullOverType { PULL_OVER = 1; // pull-over upon destination arrival EMERGENCY_PULL_OVER = 2; // emergency pull-over } optional PullOverType pull_over_type = 1; optional bool plan_pull_over_path = 2 [default = false]; optional apollo.common.PointENU position = 3; optional double theta = 4; optional double length_front = 5; optional double length_back = 6; optional double width_left = 7; optional double width_right = 8; } message ReroutingStatus { optional double last_rerouting_time = 1; optional bool need_rerouting = 2 [default = false]; optional apollo.routing.RoutingRequest routing_request = 3; } message SpeedDeciderStatus { repeated StopTime pedestrian_stop_time = 1; } message ScenarioStatus { optional ScenarioType scenario_type = 1; optional StageType stage_type = 2; } message StopSignStatus { optional string current_stop_sign_overlap_id = 1; optional string done_stop_sign_overlap_id = 2; repeated string wait_for_obstacle_id = 3; } message TrafficLightStatus { repeated string current_traffic_light_overlap_id = 1; repeated string done_traffic_light_overlap_id = 2; } message YieldSignStatus { repeated string current_yield_sign_overlap_id = 1; repeated string done_yield_sign_overlap_id = 2; repeated string wait_for_obstacle_id = 3; } // note: please keep this one as minimal as possible. do NOT pollute it. message PlanningStatus { optional BareIntersectionStatus bare_intersection = 1; optional ChangeLaneStatus change_lane = 2; optional CreepDeciderStatus creep_decider = 3; optional CrosswalkStatus crosswalk = 4; optional DestinationStatus destination = 5; optional EmergencyStopStatus emergency_stop = 6; optional OpenSpaceStatus open_space = 7; optional ParkAndGoStatus park_and_go = 8; optional PathDeciderStatus path_decider = 9; optional PullOverStatus pull_over = 10; optional ReroutingStatus rerouting = 11; optional ScenarioStatus scenario = 12; optional SpeedDeciderStatus speed_decider = 13; optional StopSignStatus stop_sign = 14; optional TrafficLightStatus traffic_light = 15; optional YieldSignStatus yield_sign = 16; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/lattice_structure.proto
syntax = "proto2"; package apollo.planning; message StopPoint { optional double s = 1; enum Type { HARD = 0; SOFT = 1; } optional Type type = 2 [default = HARD]; } message PlanningTarget { optional StopPoint stop_point = 1; optional double cruise_speed = 2; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/learning_data.proto
syntax = "proto2"; package apollo.planning; import "modules/common_msgs/chassis_msgs/chassis.proto"; import "modules/common_msgs/basic_msgs/geometry.proto"; import "modules/common_msgs/basic_msgs/header.proto"; import "modules/common_msgs/basic_msgs/pnc_point.proto"; import "modules/common_msgs/map_msgs/map_lane.proto"; import "modules/common_msgs/perception_msgs/perception_obstacle.proto"; import "modules/common_msgs/prediction_msgs/feature.proto"; import "modules/common_msgs/prediction_msgs/prediction_obstacle.proto"; import "modules/common_msgs/perception_msgs/traffic_light_detection.proto"; import "modules/common_msgs/routing_msgs/routing.proto"; message OverlapFeature { optional string id = 1; optional double distance = 2; } message PlanningTag { optional apollo.hdmap.Lane.LaneTurn lane_turn = 1; optional OverlapFeature clear_area = 2; optional OverlapFeature crosswalk = 3; optional OverlapFeature pnc_junction = 4; optional OverlapFeature signal = 5; optional OverlapFeature stop_sign = 6; optional OverlapFeature yield_sign = 7; } message ChassisFeature { optional double message_timestamp_sec = 1; // Features from chassis // Vehicle Speed in meters per second. optional float speed_mps = 2; // Real throttle location in [%], ranging from 0 to 100. optional float throttle_percentage = 3; // Real brake location in [%], ranging from 0 to 100. optional float brake_percentage = 4; // Real steering location in [%], ranging from -100 to 100. // steering_angle / max_steering_angle // Clockwise: negative // CountClockwise: positive optional float steering_percentage = 5; optional apollo.canbus.Chassis.GearPosition gear_location = 6; } message LocalizationFeature { optional double message_timestamp_sec = 1; // Position of the vehicle reference point (VRP) in the map reference frame. // The VRP is the center of rear axle. optional apollo.common.PointENU position = 2; // Heading // The heading is zero when the car is facing East and positive when facing // North. optional double heading = 3; // Linear velocity of the VRP in the map reference frame. // East/north/up in meters per second. optional apollo.common.Point3D linear_velocity = 4; // Linear acceleration of the VRP in the map reference frame. // East/north/up in meters per second. optional apollo.common.Point3D linear_acceleration = 5; // Angular velocity of the vehicle in the map reference frame. // Around east/north/up axes in radians per second. optional apollo.common.Point3D angular_velocity = 6; } // based on apollo.common.PathPoint message CommonPathPointFeature { // coordinates optional double x = 1; optional double y = 2; optional double z = 3; // direction on the x-y plane optional double theta = 4; // accumulated distance from beginning of the path optional double s = 5; // The lane ID where the path point is on optional string lane_id = 6; } // based on apollo.commom.TrajectoryPoint message CommonTrajectoryPointFeature { // path point optional CommonPathPointFeature path_point = 1; // linear velocity optional double v = 2; // in [m/s] // linear acceleration optional double a = 3; // relative time from beginning of the trajectory optional double relative_time = 4; // Gaussian probability information optional apollo.common.GaussianInfo gaussian_info = 5; } message TrajectoryPointFeature { optional double timestamp_sec = 1; optional CommonTrajectoryPointFeature trajectory_point = 2; } // based on apollo.perception.PerceptionObstacle message PerceptionObstacleFeature { optional double timestamp_sec = 1; // GPS time in seconds // obstacle position in the OBJECT coordinate system optional apollo.common.Point3D position = 2; // heading in RELATIVE coordinate to ADC optional double theta = 3; // obstacle velocity in RELATIVE coordinate to ADC optional apollo.common.Point3D velocity = 4; // obstacle velocity // obstacle acceleration in RELATIVE coordinate to ADC optional apollo.common.Point3D acceleration = 5; // obstacle corner points in RELATIVE coordinate to ADC repeated apollo.common.Point3D polygon_point = 6; } message ObstacleTrajectoryFeature { repeated PerceptionObstacleFeature perception_obstacle_history = 1; repeated TrajectoryPointFeature evaluated_trajectory_point = 2; } // based on apollo.prediction.Trajectory message PredictionTrajectoryFeature { optional double probability = 1; // probability of this trajectory repeated TrajectoryPointFeature trajectory_point = 2; } // based on apollo.prediction.PredictionObstacle message PredictionObstacleFeature { optional double timestamp_sec = 1; // GPS time in seconds optional double predicted_period = 2; optional apollo.prediction.ObstacleIntent intent = 3; optional apollo.prediction.ObstaclePriority priority = 4; optional bool is_static = 5 [default = false]; // can have multiple trajectories per obstacle repeated PredictionTrajectoryFeature trajectory = 6; } message ObstacleFeature { optional int32 id = 1; // obstacle ID. optional double length = 2; // obstacle length. optional double width = 3; // obstacle width. optional double height = 4; // obstacle height. optional apollo.perception.PerceptionObstacle.Type type = 5; // obstacle type optional ObstacleTrajectoryFeature obstacle_trajectory = 6; optional PredictionObstacleFeature obstacle_prediction = 7; } // based on apollo.routing.RoutingResponse message RoutingResponseFeature { repeated apollo.routing.RoadSegment road = 1; optional apollo.routing.Measurement measurement = 2; } message RoutingFeature { optional RoutingResponseFeature routing_response = 1; repeated string local_routing_lane_id = 2; // local routing close to ADC optional RoutingResponseFeature local_routing = 3; } // based on apollo.perception.TrafficLight message TrafficLightFeature { optional apollo.perception.TrafficLight.Color color = 1; optional string id = 2; optional double confidence = 3 [default = 1.0]; optional double tracking_time = 4; optional bool blink = 5; optional double remaining_time = 6; } message TrafficLightDetectionFeature { optional double message_timestamp_sec = 1; repeated TrafficLightFeature traffic_light = 2; } message ADCTrajectoryPoint { optional double timestamp_sec = 1; // localization measurement_time optional PlanningTag planning_tag = 2; optional CommonTrajectoryPointFeature trajectory_point = 3; } message LearningOutput { repeated TrajectoryPointFeature adc_future_trajectory_point = 1; } message LearningDataFrame { // localization message publishing time in seconds. optional double message_timestamp_sec = 1; optional uint32 frame_num = 2; optional string map_name = 3; optional PlanningTag planning_tag = 4; // Features from chassis optional ChassisFeature chassis = 5; // Features from localization optional LocalizationFeature localization = 6; // Features from perception obstacles repeated ObstacleFeature obstacle = 7; // Features from routing optional RoutingFeature routing = 8; // Features from traffic_light_detection optional TrafficLightDetectionFeature traffic_light_detection = 9; // ADC past trajectory repeated ADCTrajectoryPoint adc_trajectory_point = 10; // Learning ouputs optional LearningOutput output = 11; } message LearningData { repeated LearningDataFrame learning_data_frame = 1; } message PlanningLearningData { optional apollo.common.Header header = 1; optional LearningDataFrame learning_data_frame = 2; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/BUILD
## Auto generated by `proto_build_generator.py` load("@rules_proto//proto:defs.bzl", "proto_library") load("@rules_cc//cc:defs.bzl", "cc_proto_library") load("//tools/install:install.bzl", "install", "install_files") load("//third_party/gpus:common.bzl", "if_gpu") load("//tools:python_rules.bzl", "py_proto_library") package(default_visibility = ["//visibility:public"]) install_files( name = "py_pb_planning", dest = if_gpu( "planning-gpu/python/modules/planning/proto", "planning/python/modules/planning/proto", ), files = [ ":st_drivable_boundary_py_pb2", ":planning_stats_py_pb2", ":planning_semantic_map_config_py_pb2", ":traffic_rule_config_py_pb2", ":planning_status_py_pb2", ":lattice_structure_py_pb2", ":learning_data_py_pb2", ":auto_tuning_model_input_py_pb2", ":auto_tuning_raw_feature_py_pb2", ":reference_line_smoother_config_py_pb2", ":ipopt_return_status_py_pb2", "//modules/planning/proto/math:fem_pos_deviation_smoother_config_py_pb2", ":open_space_task_config_py_pb2", ":planner_open_space_config_py_pb2", ":task_config_py_pb2", ":planning_config_py_pb2", ] ) install_files( name = "pb_hdrs_planning", dest = if_gpu( "planning-gpu/include/proto", "planning/include/proto", ), files = [ ":st_drivable_boundary_cc_proto", ":planning_stats_cc_proto", ":planning_semantic_map_config_cc_proto", ":traffic_rule_config_cc_proto", ":planning_status_cc_proto", ":lattice_structure_cc_proto", ":learning_data_cc_proto", ":auto_tuning_model_input_cc_proto", ":auto_tuning_raw_feature_cc_proto", ":reference_line_smoother_config_cc_proto", ":ipopt_return_status_cc_proto", "//modules/planning/proto/math:fem_pos_deviation_smoother_config_cc_proto", "//modules/planning/proto/math:cos_theta_smoother_config_cc_proto", "//modules/planning/proto/math:qp_problem_cc_proto", ":open_space_task_config_cc_proto", ":planner_open_space_config_cc_proto", ":task_config_cc_proto", ":planning_config_cc_proto", ] ) cc_proto_library( name = "st_drivable_boundary_cc_proto", deps = [ ":st_drivable_boundary_proto", ], ) proto_library( name = "st_drivable_boundary_proto", srcs = ["st_drivable_boundary.proto"], ) py_proto_library( name = "st_drivable_boundary_py_pb2", deps = [ ":st_drivable_boundary_proto", ], ) cc_proto_library( name = "planning_stats_cc_proto", deps = [ ":planning_stats_proto", ], ) proto_library( name = "planning_stats_proto", srcs = ["planning_stats.proto"], ) py_proto_library( name = "planning_stats_py_pb2", deps = [ ":planning_stats_proto", ], ) cc_proto_library( name = "planning_semantic_map_config_cc_proto", deps = [ ":planning_semantic_map_config_proto", ], ) proto_library( name = "planning_semantic_map_config_proto", srcs = ["planning_semantic_map_config.proto"], ) py_proto_library( name = "planning_semantic_map_config_py_pb2", deps = [ ":planning_semantic_map_config_proto", ], ) cc_proto_library( name = "traffic_rule_config_cc_proto", deps = [ ":traffic_rule_config_proto", ], ) proto_library( name = "traffic_rule_config_proto", srcs = ["traffic_rule_config.proto"], ) py_proto_library( name = "traffic_rule_config_py_pb2", deps = [ ":traffic_rule_config_proto", ], ) cc_proto_library( name = "planning_status_cc_proto", deps = [ ":planning_status_proto", ], ) proto_library( name = "planning_status_proto", srcs = ["planning_status.proto"], deps = [ "//modules/common_msgs/basic_msgs:geometry_proto", ":planning_config_proto", "//modules/common_msgs/routing_msgs:routing_proto", "//modules/common_msgs/planning_msgs:scenario_type_proto", ], ) py_proto_library( name = "planning_status_py_pb2", deps = [ ":planning_status_proto", "//modules/common_msgs/basic_msgs:geometry_py_pb2", ":planning_config_py_pb2", "//modules/common_msgs/routing_msgs:routing_py_pb2", "//modules/common_msgs/planning_msgs:scenario_type_py_pb2", ], ) cc_proto_library( name = "lattice_structure_cc_proto", deps = [ ":lattice_structure_proto", ], ) proto_library( name = "lattice_structure_proto", srcs = ["lattice_structure.proto"], ) py_proto_library( name = "lattice_structure_py_pb2", deps = [ ":lattice_structure_proto", ], ) cc_proto_library( name = "learning_data_cc_proto", deps = [ ":learning_data_proto", ], ) proto_library( name = "learning_data_proto", srcs = ["learning_data.proto"], deps = [ "//modules/common_msgs/chassis_msgs:chassis_proto", "//modules/common_msgs/basic_msgs:geometry_proto", "//modules/common_msgs/basic_msgs:header_proto", "//modules/common_msgs/basic_msgs:pnc_point_proto", "//modules/common_msgs/map_msgs:map_lane_proto", "//modules/common_msgs/perception_msgs:perception_obstacle_proto", "//modules/common_msgs/prediction_msgs:feature_proto", "//modules/common_msgs/prediction_msgs:prediction_obstacle_proto", "//modules/common_msgs/perception_msgs:traffic_light_detection_proto", "//modules/common_msgs/routing_msgs:routing_proto", ], ) py_proto_library( name = "learning_data_py_pb2", deps = [ ":learning_data_proto", "//modules/common_msgs/chassis_msgs:chassis_py_pb2", "//modules/common_msgs/basic_msgs:geometry_py_pb2", "//modules/common_msgs/basic_msgs:header_py_pb2", "//modules/common_msgs/basic_msgs:pnc_point_py_pb2", "//modules/common_msgs/map_msgs:map_lane_py_pb2", "//modules/common_msgs/perception_msgs:perception_obstacle_py_pb2", "//modules/common_msgs/prediction_msgs:feature_py_pb2", "//modules/common_msgs/prediction_msgs:prediction_obstacle_py_pb2", "//modules/common_msgs/perception_msgs:traffic_light_detection_py_pb2", "//modules/common_msgs/routing_msgs:routing_py_pb2", ], ) cc_proto_library( name = "auto_tuning_model_input_cc_proto", deps = [ ":auto_tuning_model_input_proto", ], ) proto_library( name = "auto_tuning_model_input_proto", srcs = ["auto_tuning_model_input.proto"], ) py_proto_library( name = "auto_tuning_model_input_py_pb2", deps = [ ":auto_tuning_model_input_proto", ], ) cc_proto_library( name = "auto_tuning_raw_feature_cc_proto", deps = [ ":auto_tuning_raw_feature_proto", ], ) proto_library( name = "auto_tuning_raw_feature_proto", srcs = ["auto_tuning_raw_feature.proto"], deps = [ "//modules/common_msgs/basic_msgs:pnc_point_proto", ], ) py_proto_library( name = "auto_tuning_raw_feature_py_pb2", deps = [ ":auto_tuning_raw_feature_proto", "//modules/common_msgs/basic_msgs:pnc_point_py_pb2", ], ) cc_proto_library( name = "reference_line_smoother_config_cc_proto", deps = [ ":reference_line_smoother_config_proto", ], ) proto_library( name = "reference_line_smoother_config_proto", srcs = ["reference_line_smoother_config.proto"], deps = [ "//modules/planning/proto/math:cos_theta_smoother_config_proto", "//modules/planning/proto/math:fem_pos_deviation_smoother_config_proto", ], ) py_proto_library( name = "reference_line_smoother_config_py_pb2", deps = [ ":reference_line_smoother_config_proto", "//modules/planning/proto/math:cos_theta_smoother_config_py_pb2", "//modules/planning/proto/math:fem_pos_deviation_smoother_config_py_pb2", ], ) cc_proto_library( name = "ipopt_return_status_cc_proto", deps = [ ":ipopt_return_status_proto", ], ) proto_library( name = "ipopt_return_status_proto", srcs = ["ipopt_return_status.proto"], ) py_proto_library( name = "ipopt_return_status_py_pb2", deps = [ ":ipopt_return_status_proto", ], ) cc_proto_library( name = "open_space_task_config_cc_proto", deps = [ ":open_space_task_config_proto", ], ) proto_library( name = "open_space_task_config_proto", srcs = ["open_space_task_config.proto"], deps = [ ":planner_open_space_config_proto", ], ) py_proto_library( name = "open_space_task_config_py_pb2", deps = [ ":open_space_task_config_proto", ":planner_open_space_config_py_pb2", ], ) cc_proto_library( name = "planner_open_space_config_cc_proto", deps = [ ":planner_open_space_config_proto", ], ) proto_library( name = "planner_open_space_config_proto", srcs = ["planner_open_space_config.proto"], deps = [ "//modules/planning/proto/math:fem_pos_deviation_smoother_config_proto", ":task_config_proto", ], ) py_proto_library( name = "planner_open_space_config_py_pb2", deps = [ ":planner_open_space_config_proto", "//modules/planning/proto/math:fem_pos_deviation_smoother_config_py_pb2", ":task_config_py_pb2", ], ) cc_proto_library( name = "task_config_cc_proto", deps = [ ":task_config_proto", ], ) proto_library( name = "task_config_proto", srcs = ["task_config.proto"], ) py_proto_library( name = "task_config_py_pb2", deps = [ ":task_config_proto", ], ) cc_proto_library( name = "planning_config_cc_proto", deps = [ ":planning_config_proto", ], ) proto_library( name = "planning_config_proto", srcs = ["planning_config.proto"], deps = [ ":open_space_task_config_proto", ":task_config_proto", "//modules/common_msgs/planning_msgs:scenario_type_proto", ], ) py_proto_library( name = "planning_config_py_pb2", deps = [ ":planning_config_proto", ":open_space_task_config_py_pb2", ":task_config_py_pb2", "//modules/common_msgs/planning_msgs:scenario_type_py_pb2", ], )
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/auto_tuning_model_input.proto
syntax = "proto2"; package apollo.planning.autotuning; // general features before extracting specific model input features for // auto-tuning message PathPointwiseFeature { message ObstacleFeature { optional double lateral_distance = 1; } message BoundRelatedFeature { optional double bound_distance = 1; enum CrossableLevel { CROSS_FREE = 0; CROSS_ABLE = 1; CROSS_FORBIDDEN = 2; } optional CrossableLevel crossable_level = 2; } optional double l = 1; optional double dl = 2; optional double ddl = 3; optional double kappa = 4; repeated ObstacleFeature obstacle_info = 5; optional BoundRelatedFeature left_bound_feature = 6; optional BoundRelatedFeature right_bound_feature = 7; } message SpeedPointwiseFeature { message ObstacleFeature { optional double longitudinal_distance = 1; optional double obstacle_speed = 2; optional double lateral_distance = 3 [default = 10.0]; optional double probability = 4; optional double relative_v = 5; } optional double s = 1 [default = 0.0]; optional double t = 2 [default = 0.0]; optional double v = 3 [default = 0.0]; optional double speed_limit = 4 [default = 0.0]; optional double acc = 5 [default = 0.0]; optional double jerk = 6 [default = 0.0]; repeated ObstacleFeature follow_obs_feature = 7; repeated ObstacleFeature overtake_obs_feature = 8; repeated ObstacleFeature nudge_obs_feature = 9; repeated ObstacleFeature stop_obs_feature = 10; optional int32 collision_times = 11 [default = 0]; repeated ObstacleFeature virtual_obs_feature = 12; optional double lateral_acc = 13 [default = 0.0]; optional double path_curvature_abs = 14 [default = 0.0]; repeated ObstacleFeature sidepass_front_obs_feature = 15; repeated ObstacleFeature sidepass_rear_obs_feature = 16; } message TrajectoryPointwiseFeature { optional PathPointwiseFeature path_input_feature = 1; optional SpeedPointwiseFeature speed_input_feature = 2; } message TrajectoryFeature { repeated TrajectoryPointwiseFeature point_feature = 1; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/auto_tuning_raw_feature.proto
syntax = "proto2"; package apollo.planning.autotuning; import "modules/common_msgs/basic_msgs/pnc_point.proto"; message PathPointRawFeature { optional apollo.common.PathPoint cartesian_coord = 1; optional apollo.common.FrenetFramePoint frenet_coord = 2; } message SpeedPointRawFeature { message ObjectDecisionFeature { // obstacle id optional int32 id = 1; // relative to eog, s_obs - s_host [m] optional double relative_s = 2; // relative to ego, l_obs - l_host [m] optional double relative_l = 3; // relative to ego, v_obs - v_host [m/s] optional double relative_v = 4; // speed [m / s] optional double speed = 5; } optional double s = 1; // [m] optional double t = 2; // [s] optional double v = 3; // [m/s] optional double a = 4; // [m/s^2] optional double j = 5; // [m/s^3] optional double speed_limit = 6; // speed limit with curvature adj [m/s] repeated ObjectDecisionFeature follow = 10; repeated ObjectDecisionFeature overtake = 11; repeated ObjectDecisionFeature virtual_decision = 13; repeated ObjectDecisionFeature stop = 14; repeated ObjectDecisionFeature collision = 15; repeated ObjectDecisionFeature nudge = 12; repeated ObjectDecisionFeature sidepass_front = 16; repeated ObjectDecisionFeature sidepass_rear = 17; repeated ObjectDecisionFeature keep_clear = 18; } // caputuring the obstacle raw distance information from surrounding environment // based on ST graph message ObstacleSTRawData { message STPointPair { optional double s_lower = 1; optional double s_upper = 2; optional double t = 3; optional double l = 4 [default = 10.0]; // filled when nudging } message ObstacleSTData { optional int32 id = 1; optional double speed = 2; optional bool is_virtual = 3; optional double probability = 4; repeated STPointPair polygon = 8; repeated STPointPair distribution = 9; } repeated ObstacleSTData obstacle_st_data = 1; repeated ObstacleSTData obstacle_st_nudge = 2; repeated ObstacleSTData obstacle_st_sidepass = 3; } message TrajectoryPointRawFeature { optional PathPointRawFeature path_feature = 1; optional SpeedPointRawFeature speed_feature = 2; } message TrajectoryRawFeature { repeated TrajectoryPointRawFeature point_feature = 1; optional ObstacleSTRawData st_raw_data = 2; }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/reference_line_smoother_config.proto
syntax = "proto2"; package apollo.planning; import "modules/planning/proto/math/cos_theta_smoother_config.proto"; import "modules/planning/proto/math/fem_pos_deviation_smoother_config.proto"; message QpSplineSmootherConfig { optional uint32 spline_order = 1 [default = 5]; optional double max_spline_length = 2 [default = 25]; optional double regularization_weight = 3 [default = 0.1]; optional double second_derivative_weight = 4 [default = 0.0]; optional double third_derivative_weight = 5 [default = 100]; } message SpiralSmootherConfig { // The max deviation of spiral reference line smoother. optional double max_deviation = 1 [default = 0.1]; // The piecewise length of spiral smoother. optional double piecewise_length = 2 [default = 10.0]; // The iteration num of spiral reference line smoother."); optional uint32 max_iteration = 3 [default = 1000]; // The desired convergence tol for spiral opt; optional double opt_tol = 4 [default = 1.0e-8]; // The acceptable convergence tol for spiral opt optional double opt_acceptable_tol = 5 [default = 1e-6]; // The number of acceptable iters before termination for spiral opt; optional uint32 opt_acceptable_iteration = 6 [default = 15]; // The weight of curve length term in objective function optional double weight_curve_length = 7 [default = 1.0]; // The weight of kappa term in objective function optional double weight_kappa = 8 [default = 1.0]; // The weight of dkappa term in objective function optional double weight_dkappa = 9 [default = 100.0]; } message DiscretePointsSmootherConfig { enum SmoothingMethod { NOT_DEFINED = 0; COS_THETA_SMOOTHING = 1; FEM_POS_DEVIATION_SMOOTHING = 2; } optional SmoothingMethod smoothing_method = 3 [default = FEM_POS_DEVIATION_SMOOTHING]; oneof SmootherConfig { CosThetaSmootherConfig cos_theta_smoothing = 4; FemPosDeviationSmootherConfig fem_pos_deviation_smoothing = 5; } } message ReferenceLineSmootherConfig { // The output resolution for discrete point smoother reference line is // directly decided by max_constraint_interval optional double max_constraint_interval = 1 [default = 5]; optional double longitudinal_boundary_bound = 2 [default = 1.0]; optional double max_lateral_boundary_bound = 3 [default = 0.5]; optional double min_lateral_boundary_bound = 4 [default = 0.2]; // The output resolution for qp smoother reference line. optional uint32 num_of_total_points = 5 [default = 500]; optional double curb_shift = 6 [default = 0.2]; optional double lateral_buffer = 7 [default = 0.2]; // The output resolution for spiral smoother reference line. optional double resolution = 8 [default = 0.02]; oneof SmootherConfig { QpSplineSmootherConfig qp_spline = 20; SpiralSmootherConfig spiral = 21; DiscretePointsSmootherConfig discrete_points = 22; } }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/proto/ipopt_return_status.proto
syntax = "proto2"; package apollo.planning; enum IpoptReturnStatus { SOLVE_SUCCEEDED = 0; SOLVED_TO_ACCEPTABLE_LEVEL = 1; INFEASIBLE_PROBLEM_DETECTED = 2; SEARCH_DIRECTION_BECOMES_TOO_SMALL = 3; DIVERGIN_ITERATES = 4; USER_REQUESTED_STOP = 5; FEASIBLE_POINT_FOUND = 6; MAXIMUM_ITERATIONS_EXCEEDED = -1; RESTORATION_FAILED = -2; ERROR_IN_STEP_COMPUTATION = -3; NOT_ENOUGH_DEGREES_OF_FREEDOM = -10; INVALID_PROGRAM_DEFINITION = -11; INVALID_OPTION = -12; INVALID_NUMBER_DETECTED = -13; UNRECOVERABLE_EXCEPTION = -100; NONIPOPT_EXCEPTION_THROWN = -101; INSUFFICIENT_MEMORY = -102; INTERNAL_ERROR = 199; }
0
apollo_public_repos/apollo/modules/planning/proto
apollo_public_repos/apollo/modules/planning/proto/math/qp_problem.proto
syntax = "proto2"; package apollo.planning; // create the quadratic programming proto // 1/2 x^T Q x + c^T x // w.r.t // A x = b // C x >= d // specified input: input_marker // as well as optimal solution optimal param message QuadraticProgrammingProblem { optional int32 param_size = 1; // specified parameter size optional QPMatrix quadratic_matrix = 2; // Q matrix repeated double bias = 3; // c optional QPMatrix equality_matrix = 4; // A matrix repeated double equality_value = 5; // b vector optional QPMatrix inequality_matrix = 6; // C matrix repeated double inequality_value = 7; // d vector repeated double input_marker = 8; // marker for the specified matrix repeated double optimal_param = 9; // optimal result }; message QPMatrix { optional int32 row_size = 1; optional int32 col_size = 2; // element with element(col_size * r + c) repeated double element = 3; } message QuadraticProgrammingProblemSet { repeated QuadraticProgrammingProblem problem = 1; // QPProblem }
0
apollo_public_repos/apollo/modules/planning/proto
apollo_public_repos/apollo/modules/planning/proto/math/cos_theta_smoother_config.proto
syntax = "proto2"; package apollo.planning; message CosThetaSmootherConfig { optional double weight_cos_included_angle = 1 [default = 10000.0]; optional double weight_anchor_points = 2 [default = 1.0]; optional double weight_length = 3 [default = 1.0]; // ipopt settings optional int32 print_level = 4 [default = 0]; optional int32 max_num_of_iterations = 5 [default = 500]; optional int32 acceptable_num_of_iterations = 6 [default = 15]; optional double tol = 7 [default = 1e-8]; optional double acceptable_tol = 8 [default = 1e-1]; optional bool ipopt_use_automatic_differentiation = 9 [default = false]; }
0
apollo_public_repos/apollo/modules/planning/proto
apollo_public_repos/apollo/modules/planning/proto/math/fem_pos_deviation_smoother_config.proto
syntax = "proto2"; package apollo.planning; message FemPosDeviationSmootherConfig { optional double weight_fem_pos_deviation = 2 [default = 1.0e10]; optional double weight_ref_deviation = 3 [default = 1.0]; optional double weight_path_length = 4 [default = 1.0]; optional bool apply_curvature_constraint = 5 [default = false]; optional double weight_curvature_constraint_slack_var = 6 [default = 1.0e2]; optional double curvature_constraint = 7 [default = 0.2]; optional bool use_sqp = 8 [default = false]; optional double sqp_ftol = 9 [default = 1e-4]; optional double sqp_ctol = 10 [default = 1e-3]; optional int32 sqp_pen_max_iter = 11 [default = 10]; optional int32 sqp_sub_max_iter = 12 [default = 100]; // osqp settings optional int32 max_iter = 100 [default = 500]; // time_limit set to be 0.0 meaning no time limit optional double time_limit = 101 [default = 0.0]; optional bool verbose = 102 [default = false]; optional bool scaled_termination = 103 [default = true]; optional bool warm_start = 104 [default = true]; // ipopt settings optional int32 print_level = 200 [default = 0]; optional int32 max_num_of_iterations = 201 [default = 500]; optional int32 acceptable_num_of_iterations = 202 [default = 15]; optional double tol = 203 [default = 1e-8]; optional double acceptable_tol = 204 [default = 1e-1]; }
0
apollo_public_repos/apollo/modules/planning/proto
apollo_public_repos/apollo/modules/planning/proto/math/BUILD
## Auto generated by `proto_build_generator.py` load("@rules_proto//proto:defs.bzl", "proto_library") load("@rules_cc//cc:defs.bzl", "cc_proto_library") load("//tools:python_rules.bzl", "py_proto_library") package(default_visibility = ["//visibility:public"]) cc_proto_library( name = "cos_theta_smoother_config_cc_proto", deps = [ ":cos_theta_smoother_config_proto", ], ) proto_library( name = "cos_theta_smoother_config_proto", srcs = ["cos_theta_smoother_config.proto"], ) py_proto_library( name = "cos_theta_smoother_config_py_pb2", deps = [ ":cos_theta_smoother_config_proto", ], ) cc_proto_library( name = "qp_problem_cc_proto", deps = [ ":qp_problem_proto", ], ) proto_library( name = "qp_problem_proto", srcs = ["qp_problem.proto"], ) py_proto_library( name = "qp_problem_py_pb2", deps = [ ":qp_problem_proto", ], ) cc_proto_library( name = "fem_pos_deviation_smoother_config_cc_proto", deps = [ ":fem_pos_deviation_smoother_config_proto", ], ) proto_library( name = "fem_pos_deviation_smoother_config_proto", srcs = ["fem_pos_deviation_smoother_config.proto"], ) py_proto_library( name = "fem_pos_deviation_smoother_config_py_pb2", deps = [ ":fem_pos_deviation_smoother_config_proto", ], )
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/integration_tests/sunnyvale_loop_test.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/common/configs/config_gflags.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/integration_tests/planning_test_base.h" DECLARE_bool(reckless_change_lane); namespace apollo { namespace planning { /** * @class SunnyvaleLoopTest * @brief This is an integration test that uses the sunnyvale_loop map. */ class SunnyvaleLoopTest : public PlanningTestBase { public: virtual void SetUp() { FLAGS_use_navigation_mode = false; FLAGS_map_dir = "modules/map/data/sunnyvale_loop"; FLAGS_test_base_map_filename = "base_map_test.bin"; FLAGS_test_data_dir = "modules/planning/testdata/sunnyvale_loop_test"; FLAGS_planning_upper_speed_limit = 12.5; FLAGS_use_multi_thread_to_add_obstacles = false; FLAGS_enable_scenario_stop_sign = false; FLAGS_enable_scenario_traffic_light = false; FLAGS_enable_rss_info = false; ENABLE_RULE(TrafficRuleConfig::CROSSWALK, false); } }; /* * test stop for not-nudgable obstacle * A cruise test case */ TEST_F(SunnyvaleLoopTest, cruise) { std::string seq_num = "1"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * stop case to trigger QP ST failed to solve */ // TODO(all): need fix test data. // the existing obstacle is not along reference line and gets ignored /* TEST_F(SunnyvaleLoopTest, stop) { std::string seq_num = "2"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } */ /* * test follow a vehicle with medium distance * A follow test case */ TEST_F(SunnyvaleLoopTest, follow_01) { std::string seq_num = "3"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test nudge a static vehicle with medium distance * A nudge test case */ TEST_F(SunnyvaleLoopTest, nudge) { std::string seq_num = "4"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test follow a vehicle at right turn * A follow test case */ TEST_F(SunnyvaleLoopTest, follow_02) { std::string seq_num = "5"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test follow a vehicle at right turn with a close leading vehicle * A follow test case */ TEST_F(SunnyvaleLoopTest, follow_03) { std::string seq_num = "6"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test slowdown when dp_st_graph is failed. * A slowdown test case */ TEST_F(SunnyvaleLoopTest, slowdown_01) { std::string seq_num = "7"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test right turn. * A right turn test case */ TEST_F(SunnyvaleLoopTest, rightturn_01) { std::string seq_num = "8"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; ENABLE_RULE(TrafficRuleConfig::TRAFFIC_LIGHT, true); PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test right turn, but stop before traffic light * A right turn test case * A traffic light test case */ TEST_F(SunnyvaleLoopTest, rightturn_with_red_light) { std::string seq_num = "8"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; FLAGS_test_traffic_light_file = seq_num + "_traffic_light.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test change lane * A change lane test case */ TEST_F(SunnyvaleLoopTest, change_lane) { std::string seq_num = "9"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test mission complete */ TEST_F(SunnyvaleLoopTest, mission_complete) { std::string seq_num = "10"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test change lane with obstacle at target lane */ TEST_F(SunnyvaleLoopTest, avoid_change_left) { std::string seq_num = "11"; FLAGS_reckless_change_lane = true; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test qp path failure */ TEST_F(SunnyvaleLoopTest, qp_path_failure) { std::string seq_num = "12"; FLAGS_reckless_change_lane = true; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test change lane faillback * ADC position passed the change lane zone, failed to change to the new lane * and reroute is triggered but new rerouting result is not received yet. * Expect to keep going on the current lane. */ TEST_F(SunnyvaleLoopTest, change_lane_failback) { // temporarily disable this test case, because a lane in routing cannot be // found on test map. auto target_lane = hdmap::HDMapUtil::BaseMapPtr()->GetLaneById( hdmap::MakeMapId("2020_1_-2")); if (target_lane == nullptr) { AERROR << "Could not find lane 2020_1_-2 on map " << hdmap::BaseMapFile(); return; } std::string seq_num = "13"; FLAGS_reckless_change_lane = true; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } } // namespace planning } // namespace apollo TMAIN;
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/integration_tests/sunnyvale_big_loop_test.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/time/clock.h" #include "modules/common/configs/config_gflags.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/integration_tests/planning_test_base.h" #include "modules/planning/scenarios/stop_sign/unprotected/stop_sign_unprotected_scenario.h" namespace apollo { namespace planning { using apollo::cyber::Clock; /** * @class SunnyvaleBigLoopTest * @brief This is an integration test that uses the sunnyvale_big_loop map. * * sequence number allocation: * 0 - 99: stop sign * 100 - 199: keep clear * 200 - 299: crosswalk * 300 - 399: signal light * 400 - 499: change lane * 500 - 599: front vehicle * 600 - 699: destination */ class SunnyvaleBigLoopTest : public PlanningTestBase { public: virtual void SetUp() { FLAGS_use_navigation_mode = false; FLAGS_map_dir = "modules/map/data/sunnyvale_big_loop"; FLAGS_test_base_map_filename = "base_map.bin"; FLAGS_test_data_dir = "modules/planning/testdata/sunnyvale_big_loop_test"; FLAGS_planning_upper_speed_limit = 20.0; FLAGS_enable_scenario_pull_over = false; FLAGS_enable_scenario_stop_sign = false; FLAGS_enable_scenario_traffic_light = false; FLAGS_enable_rss_info = false; ENABLE_RULE(TrafficRuleConfig::CROSSWALK, false); ENABLE_RULE(TrafficRuleConfig::DESTINATION, false); ENABLE_RULE(TrafficRuleConfig::KEEP_CLEAR, false); ENABLE_RULE(TrafficRuleConfig::TRAFFIC_LIGHT, false); } }; /* * stop_sign: * desc: adc proceed, 27m from stop sign, not enter stop-sign scenario yet, * but the stop decision for stop-sign shall be there * decision: STOP */ TEST_F(SunnyvaleBigLoopTest, stop_sign_01) { FLAGS_enable_scenario_stop_sign = true; std::string seq_num = "1"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST_DECISION(0); // check PlanningContext content const auto& stop_sign_status = injector_->planning_context()->planning_status().stop_sign(); EXPECT_EQ(stop_sign_status.current_stop_sign_overlap_id(), ""); EXPECT_EQ(stop_sign_status.done_stop_sign_overlap_id(), ""); EXPECT_EQ(stop_sign_status.wait_for_obstacle_id_size(), 0); } /* * stop_sign: * desc: adc close enough to stop-sign, enter PRE-STOP stage * decision: STOP */ TEST_F(SunnyvaleBigLoopTest, stop_sign_02) { FLAGS_enable_scenario_stop_sign = true; std::string seq_num = "2"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST_DECISION(0); // check PlanningContext content const auto& stop_sign_status = injector_->planning_context()->planning_status().stop_sign(); EXPECT_EQ(stop_sign_status.current_stop_sign_overlap_id(), "1017"); EXPECT_EQ(stop_sign_status.done_stop_sign_overlap_id(), ""); EXPECT_EQ(stop_sign_status.wait_for_obstacle_id_size(), 0); } /* * stop_sign: * desc: adc stopped + wait_time < STOP_DURATION, stage PRE-STOP => STOP * decision: STOP */ TEST_F(SunnyvaleBigLoopTest, stop_sign_03) { FLAGS_enable_scenario_stop_sign = true; std::string seq_num = "2"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); // PRE-STOP stage RUN_GOLDEN_TEST_DECISION(0); // check PlanningContext content const auto& stop_sign_status = injector_->planning_context()->planning_status().stop_sign(); EXPECT_EQ(stop_sign_status.current_stop_sign_overlap_id(), "1017"); EXPECT_EQ(stop_sign_status.done_stop_sign_overlap_id(), ""); EXPECT_EQ(stop_sign_status.wait_for_obstacle_id_size(), 0); std::this_thread::sleep_for(std::chrono::milliseconds(1)); // STOP stage RUN_GOLDEN_TEST_DECISION(1); // check PlanningContext content const auto& stop_sign_status_2 = injector_->planning_context()->planning_status().stop_sign(); EXPECT_EQ(stop_sign_status_2.current_stop_sign_overlap_id(), "1017"); EXPECT_EQ(stop_sign_status_2.done_stop_sign_overlap_id(), ""); EXPECT_EQ(stop_sign_status_2.wait_for_obstacle_id_size(), 0); } /* * keep_clear: keep clear zone clear * bag: 2018-05-22-13-59-27/2018-05-22-14-09-29_10.bag * decision: not stopped by KEEP_CLEAR */ TEST_F(SunnyvaleBigLoopTest, keep_clear_01) { ENABLE_RULE(TrafficRuleConfig::CROSSWALK, false); ENABLE_RULE(TrafficRuleConfig::KEEP_CLEAR, true); ENABLE_RULE(TrafficRuleConfig::TRAFFIC_LIGHT, false); std::string seq_num = "101"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST_DECISION(0); } /* * keep_clear: vehicle inside KEEP Clear zone, with speed and BLOCKING * bag: 2018-05-22-13-59-27/2018-05-22-14-13-29_14.bag * decision: STOP */ TEST_F(SunnyvaleBigLoopTest, keep_clear_02) { ENABLE_RULE(TrafficRuleConfig::CROSSWALK, false); ENABLE_RULE(TrafficRuleConfig::KEEP_CLEAR, true); ENABLE_RULE(TrafficRuleConfig::TRAFFIC_LIGHT, false); std::string seq_num = "102"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST_DECISION(0); } /* * keep_clear: vehicle inside KEEP Clear zone, with speed and NOT BLOCKING * bag: 2018-05-22-13-59-27/2018-05-22-14-13-29_14.bag * decision: CRUISE */ TEST_F(SunnyvaleBigLoopTest, keep_clear_03) { ENABLE_RULE(TrafficRuleConfig::CROSSWALK, false); ENABLE_RULE(TrafficRuleConfig::KEEP_CLEAR, true); ENABLE_RULE(TrafficRuleConfig::TRAFFIC_LIGHT, false); std::string seq_num = "103"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST_DECISION(0); } /* * crosswalk: pedestrian on crosswalk * bag: 2018-01-29-17-22-46/2018-01-29-17-31-47_9.bag * decision: STOP */ TEST_F(SunnyvaleBigLoopTest, crosswalk_01) { ENABLE_RULE(TrafficRuleConfig::CROSSWALK, true); ENABLE_RULE(TrafficRuleConfig::KEEP_CLEAR, false); ENABLE_RULE(TrafficRuleConfig::TRAFFIC_LIGHT, true); std::string seq_num = "200"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST_DECISION(0); } /* * crosswalk: timeout on static pedestrian on crosswalk * bag: 2018-01-29-17-22-46/2018-01-29-17-31-47_9.bag * decision: STOP first, and then CRUISE */ TEST_F(SunnyvaleBigLoopTest, crosswalk_02) { ENABLE_RULE(TrafficRuleConfig::CROSSWALK, true); ENABLE_RULE(TrafficRuleConfig::KEEP_CLEAR, false); ENABLE_RULE(TrafficRuleConfig::TRAFFIC_LIGHT, true); std::string seq_num = "201"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST_DECISION(0); // check PlanningStatus value auto* crosswalk_status = injector_->planning_context() ->mutable_planning_status() ->mutable_crosswalk(); EXPECT_EQ("2832", crosswalk_status->crosswalk_id()); EXPECT_EQ(1, crosswalk_status->stop_time_size()); EXPECT_EQ("11652", crosswalk_status->stop_time(0).obstacle_id()); // step 2: // timeout on static pedestrian // set PlanningStatus auto* crosswalk_config = PlanningTestBase::GetTrafficRuleConfig(TrafficRuleConfig::CROSSWALK); double stop_timeout = crosswalk_config->crosswalk().stop_timeout(); double wait_time = stop_timeout + 0.5; for (auto& stop_time : *crosswalk_status->mutable_stop_time()) { if (stop_time.obstacle_id() == "11652") { stop_time.set_stop_timestamp_sec(Clock::NowInSeconds() - wait_time); } } RUN_GOLDEN_TEST_DECISION(1); } TEST_F(SunnyvaleBigLoopTest, traffic_light_green) { ENABLE_RULE(TrafficRuleConfig::CROSSWALK, false); ENABLE_RULE(TrafficRuleConfig::KEEP_CLEAR, false); ENABLE_RULE(TrafficRuleConfig::TRAFFIC_LIGHT, true); std::string seq_num = "300"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; FLAGS_test_traffic_light_file = seq_num + "_traffic_light.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST_DECISION(0); } TEST_F(SunnyvaleBigLoopTest, change_lane_abort_for_fast_back_vehicle) { ENABLE_RULE(TrafficRuleConfig::CROSSWALK, false); ENABLE_RULE(TrafficRuleConfig::KEEP_CLEAR, false); ENABLE_RULE(TrafficRuleConfig::TRAFFIC_LIGHT, true); std::string seq_num = "400"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST_DECISION(0); } /* * destination: stop on arriving destination when pull-over is disabled * bag: 2018-05-16-10-00-32/2018-05-16-10-00-32_10.bag * decision: STOP */ TEST_F(SunnyvaleBigLoopTest, destination_stop_01) { ENABLE_RULE(TrafficRuleConfig::CROSSWALK, false); ENABLE_RULE(TrafficRuleConfig::DESTINATION, true); ENABLE_RULE(TrafficRuleConfig::KEEP_CLEAR, false); ENABLE_RULE(TrafficRuleConfig::TRAFFIC_LIGHT, false); std::string seq_num = "600"; FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST_DECISION(0); } } // namespace planning } // namespace apollo TMAIN;
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/integration_tests/navigation_mode_test.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "gtest/gtest.h" #include "modules/common/configs/config_gflags.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/integration_tests/planning_test_base.h" namespace apollo { namespace planning { /** * @class SunnyvaleLoopTest * @brief This is an integration test that uses the sunnyvale_loop map. */ class NavigationModeTest : public PlanningTestBase { public: virtual void SetUp() { FLAGS_use_navigation_mode = true; FLAGS_lane_follow_scenario_config_file = "modules/planning/conf/lane_follow_scenario_config.pb.txt"; FLAGS_test_data_dir = "modules/planning/testdata/navigation_mode_test"; FLAGS_traffic_rule_config_filename = "modules/planning/conf/traffic_rule_config.pb.txt"; } }; /* * test stop for not-nudgable obstacle * A cruise test case */ TEST_F(NavigationModeTest, cruise) { std::string seq_num = "1"; FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; FLAGS_test_relative_map_file = seq_num + "_relative_map.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } } // namespace planning } // namespace apollo TMAIN;
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/integration_tests/garage_test.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cyber/time/clock.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/integration_tests/planning_test_base.h" namespace apollo { namespace planning { DECLARE_string(test_routing_response_file); DECLARE_string(test_localization_file); DECLARE_string(test_chassis_file); /** * @class GarageTest * @brief This is an integration test that uses the garage map. */ class GarageTest : public PlanningTestBase { public: virtual void SetUp() { FLAGS_use_multi_thread_to_add_obstacles = false; FLAGS_enable_multi_thread_in_dp_st_graph = false; FLAGS_use_navigation_mode = false; FLAGS_map_dir = "modules/planning/testdata/garage_map"; FLAGS_base_map_filename = "base_map.txt"; FLAGS_test_data_dir = "modules/planning/testdata/garage_test"; FLAGS_planning_upper_speed_limit = 12.5; FLAGS_test_routing_response_file = "garage_routing.pb.txt"; FLAGS_test_previous_planning_file = ""; FLAGS_test_prediction_file = ""; FLAGS_test_localization_file = ""; FLAGS_test_chassis_file = ""; FLAGS_enable_rss_info = false; FLAGS_enable_scenario_stop_sign = false; FLAGS_enable_scenario_traffic_light = false; } }; /* * test stop for not-nudgable obstacle */ TEST_F(GarageTest, stop_obstacle) { FLAGS_test_prediction_file = "stop_obstacle_prediction.pb.txt"; FLAGS_test_localization_file = "stop_obstacle_localization.pb.txt"; FLAGS_test_chassis_file = "stop_obstacle_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test follow head_vehicle */ TEST_F(GarageTest, follow) { FLAGS_test_prediction_file = "follow_prediction.pb.txt"; FLAGS_test_localization_file = "follow_localization.pb.txt"; FLAGS_test_chassis_file = "follow_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test destination stop */ TEST_F(GarageTest, dest_stop_01) { FLAGS_test_prediction_file = "stop_dest_prediction.pb.txt"; FLAGS_test_localization_file = "stop_dest_localization.pb.txt"; FLAGS_test_chassis_file = "stop_dest_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test stop for out of map * planning should fail in this case, but the module should not core. */ TEST_F(GarageTest, out_of_map) { FLAGS_test_prediction_file = "out_of_map_prediction.pb.txt"; FLAGS_test_localization_file = "out_of_map_localization.pb.txt"; FLAGS_test_chassis_file = "out_of_map_chassis.pb.txt"; PlanningTestBase::SetUp(); RUN_GOLDEN_TEST(0); } /* * test stop passed stop line */ // TEST_F(GarageTest, stop_over_line) { // std::string seq_num = "1"; // FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt"; // FLAGS_test_localization_file = seq_num + "_localization.pb.txt"; // FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt"; // PlanningTestBase::SetUp(); // RUN_GOLDEN_TEST(0); // } } // namespace planning } // namespace apollo TMAIN;
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/integration_tests/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "planning_test_base", srcs = ["planning_test_base.cc"], hdrs = ["planning_test_base.h"], copts = ["-fno-access-control"], data = [ "//modules/planning:planning_conf", "//modules/planning:planning_testdata", ], deps = [ "//cyber", "//modules/common/adapters:adapter_gflags", "//modules/common/configs:config_gflags", "//modules/common/util", "//modules/common/vehicle_state:vehicle_state_provider", "//modules/planning:planning_component_lib", "@com_google_googletest//:gtest", ], linkstatic = True, ) # FIXME(all): temporarily disable integration test for planning flaky problems. # cc_test( # name = "garage_test", # size = "small", # srcs = ["garage_test.cc"], # data = [ # "//modules/common/configs:config_gflags", # "//modules/planning:planning_testdata", # ], # deps = [ # ":planning_test_base", # ], # ) # cc_test( # name = "sunnyvale_loop_test", # size = "small", # srcs = ["sunnyvale_loop_test.cc"], # data = [ # "//modules/common/configs:config_gflags", # "//modules/map/data:map_sunnyvale_loop", # "//modules/planning:planning_testdata", # ], # deps = [ # ":planning_test_base", # ], # ) # cc_test( # name = "sunnyvale_big_loop_test", # size = "medium", # srcs = ["sunnyvale_big_loop_test.cc"], # data = [ # "//modules/common/configs:config_gflags", # "//modules/map/data:map_sunnyvale_big_loop", # "//modules/planning:planning_testdata", # ], # linkopts = ["-lgomp"], # deps = [ # ":planning_test_base", # ], # linkstatic = True, # ) # cc_test( # name = "navigation_mode_test", # size = "small", # srcs = [navigation_mode_test.cc"], # data = [ # "//modules/common/configs:config_gflags", # "//modules/planning:planning_testdata", # ], # deps = [ # ":planning_test_base", # ], # ) cpplint()
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/integration_tests/planning_test_base.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <map> #include <memory> #include <string> #include "gtest/gtest.h" #include "modules/planning/proto/traffic_rule_config.pb.h" // TODO(all) #include "modules/planning/navi_planning.h" #include "modules/planning/on_lane_planning.h" #include "modules/planning/planning_base.h" namespace apollo { namespace planning { #define RUN_GOLDEN_TEST(sub_case_num) \ { \ const ::testing::TestInfo* const test_info = \ ::testing::UnitTest::GetInstance()->current_test_info(); \ bool no_trajectory_point = false; \ bool run_planning_success = \ RunPlanning(test_info->name(), sub_case_num, no_trajectory_point); \ EXPECT_TRUE(run_planning_success); \ } #define RUN_GOLDEN_TEST_DECISION(sub_case_num) \ { \ const ::testing::TestInfo* const test_info = \ ::testing::UnitTest::GetInstance()->current_test_info(); \ bool no_trajectory_point = true; \ bool run_planning_success = \ RunPlanning(test_info->name(), sub_case_num, no_trajectory_point); \ EXPECT_TRUE(run_planning_success); \ } #define TMAIN \ int main(int argc, char** argv) { \ ::apollo::cyber::Init("planning_test"); \ ::testing::InitGoogleTest(&argc, argv); \ ::google::ParseCommandLineFlags(&argc, &argv, true); \ return RUN_ALL_TESTS(); \ } #define ENABLE_RULE(RULE_ID, ENABLED) this->rule_enabled_[RULE_ID] = ENABLED DECLARE_string(test_routing_response_file); DECLARE_string(test_localization_file); DECLARE_string(test_chassis_file); DECLARE_string(test_data_dir); DECLARE_string(test_prediction_file); DECLARE_string(test_traffic_light_file); DECLARE_string(test_relative_map_file); DECLARE_string(test_previous_planning_file); class PlanningTestBase : public ::testing::Test { public: virtual ~PlanningTestBase() = default; static void SetUpTestCase(); virtual void SetUp(); void UpdateData(); /** * Execute the planning code. * @return true if planning is success. The ADCTrajectory will be used to * store the planing results. Otherwise false. */ bool RunPlanning(const std::string& test_case_name, int case_num, bool no_trajectory_point); TrafficRuleConfig* GetTrafficRuleConfig( const TrafficRuleConfig::RuleId& rule_id); protected: void TrimPlanning(ADCTrajectory* origin, bool no_trajectory_point); bool FeedTestData(); bool IsValidTrajectory(const ADCTrajectory& trajectory); protected: std::unique_ptr<PlanningBase> planning_ = nullptr; std::map<TrafficRuleConfig::RuleId, bool> rule_enabled_; ADCTrajectory adc_trajectory_; LocalView local_view_; PlanningConfig config_; std::shared_ptr<DependencyInjector> injector_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/integration_tests/planning_test_base.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/integration_tests/planning_test_base.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "modules/common_msgs/chassis_msgs/chassis.pb.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common_msgs/localization_msgs/localization.pb.h" #include "modules/common_msgs/perception_msgs/traffic_light_detection.pb.h" #include "modules/planning/common/planning_gflags.h" #include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h" #include "modules/common_msgs/routing_msgs/routing.pb.h" namespace apollo { namespace planning { using apollo::canbus::Chassis; using apollo::cyber::Clock; using apollo::localization::LocalizationEstimate; using apollo::perception::TrafficLightDetection; using apollo::prediction::PredictionObstacles; using apollo::routing::RoutingResponse; DEFINE_string(test_data_dir, "", "the test data folder"); DEFINE_bool(test_update_golden_log, false, "true to update decision golden log file."); DEFINE_string(test_routing_response_file, "", "The routing file used in test"); DEFINE_string(test_localization_file, "", "The localization test file"); DEFINE_string(test_chassis_file, "", "The chassis test file"); DEFINE_string(test_planning_config_file, "", "planning config file for test"); DEFINE_string(test_prediction_file, "", "The prediction module test file"); DEFINE_string(test_traffic_light_file, "", "The traffic light test file"); DEFINE_string(test_relative_map_file, "", "The relative map test file"); DEFINE_string(test_previous_planning_file, "", "The previous planning test file"); void PlanningTestBase::SetUpTestCase() { FLAGS_use_multi_thread_to_add_obstacles = false; FLAGS_enable_multi_thread_in_dp_st_graph = false; FLAGS_traffic_rule_config_filename = "/apollo/modules/planning/conf/traffic_rule_config.pb.txt"; FLAGS_smoother_config_filename = "/apollo/modules/planning/conf/qp_spline_smoother_config.pb.txt"; FLAGS_map_dir = "/apollo/modules/planning/testdata"; FLAGS_test_localization_file = ""; FLAGS_test_chassis_file = ""; FLAGS_test_routing_response_file = ""; FLAGS_test_planning_config_file = "/apollo/modules/planning/conf/planning_config.pb.txt"; FLAGS_test_previous_planning_file = ""; FLAGS_test_prediction_file = ""; FLAGS_align_prediction_time = false; FLAGS_enable_reference_line_provider_thread = false; // FLAGS_enable_trajectory_check is temporarily disabled, otherwise EMPlanner // and LatticePlanner can't pass the unit test. FLAGS_enable_trajectory_check = false; FLAGS_planning_test_mode = true; } bool PlanningTestBase::FeedTestData() { // chassis Chassis chassis; if (FLAGS_test_chassis_file.empty()) { AERROR << "Requires FLAGS_test_chassis_file to be set"; return false; } if (!apollo::cyber::common::GetProtoFromFile( FLAGS_test_data_dir + "/" + FLAGS_test_chassis_file, &chassis)) { AERROR << "failed to load file: " << FLAGS_test_chassis_file; return false; } // localization if (FLAGS_test_localization_file.empty()) { AERROR << "Requires FLAGS_test_localization_file to be set"; return false; } LocalizationEstimate localization; if (!apollo::cyber::common::GetProtoFromFile( FLAGS_test_data_dir + "/" + FLAGS_test_localization_file, &localization)) { AERROR << "failed to load file: " << FLAGS_test_localization_file; return false; } Clock::SetMode(apollo::cyber::proto::MODE_MOCK); Clock::SetNowInSeconds(localization.header().timestamp_sec()); // prediction if (FLAGS_test_prediction_file.empty()) { AERROR << "Requires FLAGS_test_prediction_file to be set"; return false; } PredictionObstacles prediction; if (!apollo::cyber::common::GetProtoFromFile( FLAGS_test_data_dir + "/" + FLAGS_test_prediction_file, &prediction)) { AERROR << "failed to load file: " << FLAGS_test_prediction_file; return false; } // routing_response if (FLAGS_test_routing_response_file.empty()) { AERROR << "Requires FLAGS_test_routing_response_file"; return false; } RoutingResponse routing_response; if (!apollo::cyber::common::GetProtoFromFile( FLAGS_test_data_dir + "/" + FLAGS_test_routing_response_file, &routing_response)) { AERROR << "failed to load file: " << FLAGS_test_routing_response_file; return false; } // traffic_light_detection // optional TrafficLightDetection traffic_light_detection; if (!apollo::cyber::common::GetProtoFromFile( FLAGS_test_data_dir + "/" + FLAGS_test_traffic_light_file, &traffic_light_detection)) { AERROR << "failed to load file: " << FLAGS_test_traffic_light_file; return false; } local_view_.prediction_obstacles = std::make_shared<PredictionObstacles>(prediction); local_view_.chassis = std::make_shared<Chassis>(chassis); local_view_.localization_estimate = std::make_shared<LocalizationEstimate>(localization); local_view_.routing = std::make_shared<routing::RoutingResponse>(routing_response); local_view_.traffic_light = std::make_shared<TrafficLightDetection>(traffic_light_detection); AINFO << "Successfully feed proto files."; return true; } void PlanningTestBase::SetUp() { injector_ = std::make_shared<DependencyInjector>(); if (FLAGS_use_navigation_mode) { // TODO(all) // planning_ = std::unique_ptr<PlanningBase>(new NaviPlanning()); } else { planning_ = std::unique_ptr<PlanningBase>(new OnLanePlanning(injector_)); } ACHECK(FeedTestData()) << "Failed to feed test data"; ACHECK(cyber::common::GetProtoFromFile(FLAGS_test_planning_config_file, &config_)) << "failed to load planning config file " << FLAGS_test_planning_config_file; ACHECK(planning_->Init(config_).ok()) << "Failed to init planning module"; if (!FLAGS_test_previous_planning_file.empty()) { const auto prev_planning_file = FLAGS_test_data_dir + "/" + FLAGS_test_previous_planning_file; ADCTrajectory prev_planning; ACHECK(cyber::common::GetProtoFromFile(prev_planning_file, &prev_planning)); planning_->last_publishable_trajectory_.reset( new PublishableTrajectory(prev_planning)); } for (auto& config : *(planning_->traffic_rule_configs_.mutable_config())) { auto iter = rule_enabled_.find(config.rule_id()); if (iter != rule_enabled_.end()) { config.set_enabled(iter->second); } } } void PlanningTestBase::UpdateData() { ACHECK(FeedTestData()) << "Failed to feed test data"; if (!FLAGS_test_previous_planning_file.empty()) { const auto prev_planning_file = FLAGS_test_data_dir + "/" + FLAGS_test_previous_planning_file; ADCTrajectory prev_planning; ACHECK(cyber::common::GetProtoFromFile(prev_planning_file, &prev_planning)); planning_->last_publishable_trajectory_.reset( new PublishableTrajectory(prev_planning)); } for (auto& config : *planning_->traffic_rule_configs_.mutable_config()) { auto iter = rule_enabled_.find(config.rule_id()); if (iter != rule_enabled_.end()) { config.set_enabled(iter->second); } } } void PlanningTestBase::TrimPlanning(ADCTrajectory* origin, bool no_trajectory_point) { origin->clear_latency_stats(); origin->clear_debug(); // origin->mutable_header()->clear_radar_timestamp(); // origin->mutable_header()->clear_lidar_timestamp(); // origin->mutable_header()->clear_timestamp_sec(); // origin->mutable_header()->clear_camera_timestamp(); // origin->mutable_header()->clear_sequence_num(); if (no_trajectory_point) { origin->clear_total_path_length(); origin->clear_total_path_time(); origin->clear_trajectory_point(); } } bool PlanningTestBase::RunPlanning(const std::string& test_case_name, int case_num, bool no_trajectory_point) { const std::string golden_result_file = absl::StrCat("result_", test_case_name, "_", case_num, ".pb.txt"); std::string full_golden_path = FLAGS_test_data_dir + "/" + golden_result_file; ADCTrajectory adc_trajectory_pb; planning_->RunOnce(local_view_, &adc_trajectory_pb); if (!IsValidTrajectory(adc_trajectory_pb)) { AERROR << "Fail to pass trajectory check."; return false; } adc_trajectory_ = adc_trajectory_pb; TrimPlanning(&adc_trajectory_, no_trajectory_point); if (FLAGS_test_update_golden_log) { AINFO << "The golden file is regenerated:" << full_golden_path; cyber::common::SetProtoToASCIIFile(adc_trajectory_, full_golden_path); } else { ADCTrajectory golden_result; bool load_success = cyber::common::GetProtoFromASCIIFile(full_golden_path, &golden_result); TrimPlanning(&golden_result, no_trajectory_point); if (!load_success || !common::util::IsProtoEqual(golden_result, adc_trajectory_)) { char tmp_fname[100] = "/tmp/XXXXXX"; int fd = mkstemp(tmp_fname); if (fd < 0) { AERROR << "Failed to create temporary file: " << tmp_fname; return false; } if (!cyber::common::SetProtoToASCIIFile(adc_trajectory_, fd)) { AERROR << "Failed to write to file: " << tmp_fname; } AERROR << "found error\ndiff -y " << tmp_fname << " " << full_golden_path; AERROR << "to override error\nmv " << tmp_fname << " " << full_golden_path; AERROR << "to visualize\n/usr/bin/python " "modules/tools/plot_trace/plot_planning_result.py " << tmp_fname << " " << full_golden_path; return false; } } return true; } bool PlanningTestBase::IsValidTrajectory(const ADCTrajectory& trajectory) { for (int i = 0; i < trajectory.trajectory_point_size(); ++i) { const auto& point = trajectory.trajectory_point(i); const double kMaxAccelThreshold = FLAGS_longitudinal_acceleration_upper_bound; const double kMinAccelThreshold = FLAGS_longitudinal_acceleration_lower_bound; if (point.a() > kMaxAccelThreshold || point.a() < kMinAccelThreshold) { AERROR << "Invalid trajectory point because accel out of range: " << point.DebugString(); return false; } if (!point.has_path_point()) { AERROR << "Invalid trajectory point because NO path_point in " "trajectory_point: " << point.DebugString(); return false; } if (i > 0) { const double kPathSEpsilon = 1e-3; const auto& last_point = trajectory.trajectory_point(i - 1); if (point.path_point().s() + kPathSEpsilon < last_point.path_point().s()) { AERROR << "Invalid trajectory point because s value error. last point: " << last_point.DebugString() << ", curr point: " << point.DebugString(); return false; } } } return true; } TrafficRuleConfig* PlanningTestBase::GetTrafficRuleConfig( const TrafficRuleConfig::RuleId& rule_id) { for (auto& config : *planning_->traffic_rule_configs_.mutable_config()) { if (config.rule_id() == rule_id) { return &config; } } return nullptr; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/launch/planning.launch
<cyber> <module> <name>planning</name> <dag_conf>/apollo/modules/planning/dag/planning.dag</dag_conf> <process_name>planning</process_name> </module> </cyber>
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/planner/on_lane_planner_dispatcher.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planner/on_lane_planner_dispatcher.h" #include <memory> #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { std::unique_ptr<Planner> OnLanePlannerDispatcher::DispatchPlanner( const PlanningConfig& planning_config, const std::shared_ptr<DependencyInjector>& injector) { return planner_factory_.CreateObject( planning_config.standard_planning_config().planner_type(0), injector); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/planner/planner.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include <string> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/status/status.h" #include "modules/planning/common/frame.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/scenarios/scenario.h" #include "modules/planning/scenarios/scenario_manager.h" /** * @namespace apollo::planning * @brief apollo::planning */ namespace apollo { namespace planning { /** * @class Planner * @brief Planner is a base class for specific planners. * It contains a pure virtual function Plan which must be implemented in * derived class. */ class Planner { public: /** * @brief Constructor */ Planner() = delete; explicit Planner(const std::shared_ptr<DependencyInjector>& injector) : scenario_manager_(injector) {} /** * @brief Destructor */ virtual ~Planner() = default; virtual std::string Name() = 0; virtual apollo::common::Status Init(const PlanningConfig& config) = 0; /** * @brief Compute trajectories for execution. * @param planning_init_point The trajectory point where planning starts. * @param frame Current planning frame. * @return OK if planning succeeds; error otherwise. */ virtual apollo::common::Status Plan( const common::TrajectoryPoint& planning_init_point, Frame* frame, ADCTrajectory* ptr_computed_trajectory) = 0; virtual void Stop() = 0; protected: PlanningConfig config_; scenario::ScenarioManager scenario_manager_; scenario::Scenario* scenario_ = nullptr; }; class PlannerWithReferenceLine : public Planner { public: /** * @brief Constructor */ PlannerWithReferenceLine() = delete; explicit PlannerWithReferenceLine( const std::shared_ptr<DependencyInjector>& injector) : Planner(injector) {} /** * @brief Destructor */ virtual ~PlannerWithReferenceLine() = default; /** * @brief Compute a trajectory for execution. * @param planning_init_point The trajectory point where planning starts. * @param frame Current planning frame. * @param reference_line_info The computed reference line. * @return OK if planning succeeds; error otherwise. */ virtual apollo::common::Status PlanOnReferenceLine( const common::TrajectoryPoint& planning_init_point, Frame* frame, ReferenceLineInfo* reference_line_info) { CHECK_NOTNULL(frame); return apollo::common::Status::OK(); } }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/planner/navi_planner_dispatcher.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include "modules/common/util/factory.h" #include "modules/planning/planner/planner_dispatcher.h" /** * @namespace apollo::planning * @brief apollo::planning */ namespace apollo { namespace planning { /** * @class planning * * @brief PlannerDispatcher module main class. */ class NaviPlannerDispatcher final : public PlannerDispatcher { public: NaviPlannerDispatcher() = default; virtual ~NaviPlannerDispatcher() = default; std::unique_ptr<Planner> DispatchPlanner( const PlanningConfig& planning_config, const std::shared_ptr<DependencyInjector>& injector) override; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/planner/navi_planner_dispatcher_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/planner/navi_planner_dispatcher.h" #include "cyber/common/file.h" #include "gtest/gtest.h" #include "modules/planning/planner/planner_dispatcher.h" namespace apollo { namespace planning { class NaviPlannerDispatcherTest : public ::testing::Test { public: virtual void SetUp() {} protected: std::unique_ptr<PlannerDispatcher> pd_; }; TEST_F(NaviPlannerDispatcherTest, Simple) { auto injector = std::make_shared<DependencyInjector>(); pd_.reset(new NaviPlannerDispatcher()); pd_->Init(); const std::string planning_config_file = "/apollo/modules/planning/conf/planning_config.pb.txt"; PlanningConfig planning_config; apollo::cyber::common::GetProtoFromFile(planning_config_file, &planning_config); auto planner = pd_->DispatchPlanner(planning_config, injector); EXPECT_EQ(planner->Name(), "NAVI"); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/planner/on_lane_planner_dispatcher.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include "modules/common/util/factory.h" #include "modules/planning/planner/planner_dispatcher.h" /** * @namespace apollo::planning * @brief apollo::planning */ namespace apollo { namespace planning { /** * @class planning * * @brief PlannerDispatcher module main class. */ class OnLanePlannerDispatcher final : public PlannerDispatcher { public: OnLanePlannerDispatcher() = default; virtual ~OnLanePlannerDispatcher() = default; std::unique_ptr<Planner> DispatchPlanner( const PlanningConfig& planning_config, const std::shared_ptr<DependencyInjector>& injector) override; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/planner/on_lane_planner_dispatcher_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/planner/on_lane_planner_dispatcher.h" #include "cyber/common/file.h" #include "gtest/gtest.h" #include "modules/planning/planner/planner_dispatcher.h" namespace apollo { namespace planning { class OnLanePlannerDispatcherTest : public ::testing::Test { public: virtual void SetUp() {} protected: std::unique_ptr<PlannerDispatcher> pd_; }; TEST_F(OnLanePlannerDispatcherTest, Simple) { auto injector = std::make_shared<DependencyInjector>(); pd_.reset(new OnLanePlannerDispatcher()); pd_->Init(); const std::string planning_config_file = "/apollo/modules/planning/conf/planning_config.pb.txt"; PlanningConfig planning_config; apollo::cyber::common::GetProtoFromFile(planning_config_file, &planning_config); auto planner = pd_->DispatchPlanner(planning_config, injector); EXPECT_EQ(planner->Name(), "PUBLIC_ROAD"); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/planner/navi_planner_dispatcher.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planner/navi_planner_dispatcher.h" #include <memory> #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { std::unique_ptr<Planner> NaviPlannerDispatcher::DispatchPlanner( const PlanningConfig& planning_config, const std::shared_ptr<DependencyInjector>& injector) { auto planner_type = PlannerType::NAVI; if (planning_config.has_navigation_planning_config()) { planner_type = planning_config.navigation_planning_config().planner_type(0); } return planner_factory_.CreateObject(planner_type, injector); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/planner/planner_dispatcher.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planner/planner_dispatcher.h" #include <memory> #include "modules/planning/planner/lattice/lattice_planner.h" #include "modules/planning/planner/navi/navi_planner.h" #include "modules/planning/planner/public_road/public_road_planner.h" #include "modules/planning/planner/rtk/rtk_replay_planner.h" #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { void PlannerDispatcher::RegisterPlanners() { planner_factory_.Register( PlannerType::RTK, [](const std::shared_ptr<DependencyInjector>& injector) -> Planner* { return new RTKReplayPlanner(injector); }); planner_factory_.Register( PlannerType::PUBLIC_ROAD, [](const std::shared_ptr<DependencyInjector>& injector) -> Planner* { return new PublicRoadPlanner(injector); }); planner_factory_.Register( PlannerType::LATTICE, [](const std::shared_ptr<DependencyInjector>& injector) -> Planner* { return new LatticePlanner(injector); }); planner_factory_.Register( PlannerType::NAVI, [](const std::shared_ptr<DependencyInjector>& injector) -> Planner* { return new NaviPlanner(injector); }); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/planner/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "planner", hdrs = ["planner.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/status", "//modules/planning/common:frame", "//modules/planning/common:reference_line_info", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/scenarios:scenario", "//modules/planning/scenarios:scenario_manager", ], ) cc_library( name = "planner_dispatcher", srcs = [ "navi_planner_dispatcher.cc", "on_lane_planner_dispatcher.cc", "planner_dispatcher.cc", ], hdrs = [ "navi_planner_dispatcher.h", "on_lane_planner_dispatcher.h", "planner_dispatcher.h", ], copts = [ "-DMODULE_NAME=\\\"planning\\\"", "-fopenmp", ], deps = [ ":planner", "//modules/common/status", "//modules/common/util", "//modules/planning/planner/lattice:lattice_planner", "//modules/planning/planner/navi:navi_planner", "//modules/planning/planner/public_road:public_road_planner", "//modules/planning/planner/rtk:rtk_planner", "//modules/common_msgs/planning_msgs:planning_cc_proto", ], ) cc_test( name = "on_lane_planner_dispatcher_test", size = "small", srcs = ["on_lane_planner_dispatcher_test.cc"], linkopts = ["-lgomp"], deps = [ ":planner_dispatcher", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_test( name = "navi_planner_dispatcher_test", size = "small", srcs = ["navi_planner_dispatcher_test.cc"], linkopts = ["-lgomp"], deps = [ ":planner_dispatcher", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cpplint()
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/planner/planner_dispatcher.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include "modules/common/status/status.h" #include "modules/common/util/factory.h" #include "modules/planning/planner/planner.h" /** * @namespace apollo::planning * @brief apollo::planning */ namespace apollo { namespace planning { /** * @class planning * * @brief PlannerDispatcher module main class. */ class PlannerDispatcher { public: PlannerDispatcher() = default; virtual ~PlannerDispatcher() = default; virtual common::Status Init() { RegisterPlanners(); return common::Status::OK(); } virtual std::unique_ptr<Planner> DispatchPlanner( const PlanningConfig& planning_config, const std::shared_ptr<DependencyInjector>& injector) = 0; protected: void RegisterPlanners(); common::util::Factory< PlannerType, Planner, Planner* (*)(const std::shared_ptr<DependencyInjector>& injector)> planner_factory_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/public_road/public_road_planner.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planner/public_road/public_road_planner.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::Status; using apollo::common::TrajectoryPoint; Status PublicRoadPlanner::Init(const PlanningConfig& config) { config_ = config; scenario_manager_.Init(config); return Status::OK(); } Status PublicRoadPlanner::Plan(const TrajectoryPoint& planning_start_point, Frame* frame, ADCTrajectory* ptr_computed_trajectory) { scenario_manager_.Update(planning_start_point, *frame); scenario_ = scenario_manager_.mutable_scenario(); auto result = scenario_->Process(planning_start_point, frame); if (FLAGS_enable_record_debug) { auto scenario_debug = ptr_computed_trajectory->mutable_debug() ->mutable_planning_data() ->mutable_scenario(); scenario_debug->set_scenario_type(scenario_->scenario_type()); scenario_debug->set_stage_type(scenario_->GetStage()); scenario_debug->set_msg(scenario_->GetMsg()); } if (result == scenario::Scenario::STATUS_DONE) { // only updates scenario manager when previous scenario's status is // STATUS_DONE scenario_manager_.Update(planning_start_point, *frame); } else if (result == scenario::Scenario::STATUS_UNKNOWN) { return Status(common::PLANNING_ERROR, "scenario returned unknown"); } return Status::OK(); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/public_road/public_road_planner_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planner/public_road/public_road_planner.h" #include "gtest/gtest.h" #include "modules/common_msgs/basic_msgs/drive_state.pb.h" #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { TEST(PublicRoadPlannerTest, Simple) { auto injector = std::make_shared<DependencyInjector>(); PublicRoadPlanner public_road_planner(injector); PlanningConfig config; EXPECT_EQ(public_road_planner.Name(), "PUBLIC_ROAD"); EXPECT_EQ(public_road_planner.Init(config), common::Status::OK()); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/public_road/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "public_road_planner", srcs = ["public_road_planner.cc"], hdrs = ["public_road_planner.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//cyber", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/status", "//modules/common/util", "//modules/common/util:util_tool", "//modules/common/vehicle_state:vehicle_state_provider", "//modules/map/hdmap", "//modules/planning/common:planning_common", "//modules/planning/common:planning_gflags", "//modules/planning/constraint_checker", "//modules/planning/math/curve1d:quartic_polynomial_curve1d", "//modules/planning/planner", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/reference_line", "//modules/planning/reference_line:qp_spline_reference_line_smoother", "//modules/planning/tasks:task", "//modules/planning/tasks/deciders/path_decider", "//modules/planning/tasks/deciders/speed_decider", "//modules/planning/tasks/optimizers:path_optimizer", "//modules/planning/tasks/optimizers:speed_optimizer", "//modules/planning/tasks/optimizers/path_time_heuristic:path_time_heuristic_optimizer", "@com_github_gflags_gflags//:gflags", "@eigen", ], ) cc_test( name = "public_road_planner_test", size = "small", srcs = ["public_road_planner_test.cc"], linkopts = ["-lgomp"], deps = [ ":public_road_planner", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cpplint()
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/public_road/public_road_planner.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include <string> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/status/status.h" #include "modules/common/util/factory.h" #include "modules/planning/common/reference_line_info.h" #include "modules/planning/math/curve1d/quintic_polynomial_curve1d.h" #include "modules/planning/planner/planner.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/reference_line/reference_line.h" #include "modules/planning/reference_line/reference_point.h" #include "modules/planning/tasks/task.h" /** * @namespace apollo::planning * @brief apollo::planning */ namespace apollo { namespace planning { /** * @class PublicRoadPlanner * @brief PublicRoadPlanner is an expectation maximization planner. */ class PublicRoadPlanner : public PlannerWithReferenceLine { public: /** * @brief Constructor */ PublicRoadPlanner() = delete; explicit PublicRoadPlanner( const std::shared_ptr<DependencyInjector>& injector) : PlannerWithReferenceLine(injector) {} /** * @brief Destructor */ virtual ~PublicRoadPlanner() = default; void Stop() override {} std::string Name() override { return "PUBLIC_ROAD"; } common::Status Init(const PlanningConfig& config) override; /** * @brief Override function Plan in parent class Planner. * @param planning_init_point The trajectory point where planning starts. * @param frame Current planning frame. * @return OK if planning succeeds; error otherwise. */ common::Status Plan(const common::TrajectoryPoint& planning_init_point, Frame* frame, ADCTrajectory* ptr_computed_trajectory) override; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/navi/navi_planner_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides several unit tests for the class "NaviPlanner". */ #include "modules/planning/planner/navi/navi_planner.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { // TODO(all): Add your unit test code here according to the Google Unit Testing // Specification. TEST(NaviPlannerTest, ComputeTrajectory) {} TEST(NaviPlannerTest, ErrorTest) {} } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/navi/navi_planner.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides the declaration of the class "NaviPlanner". */ #pragma once #include <memory> #include <string> #include <vector> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/status/status.h" #include "modules/common/util/factory.h" #include "modules/planning/common/reference_line_info.h" #include "modules/planning/math/curve1d/quintic_polynomial_curve1d.h" #include "modules/planning/navi/decider/navi_task.h" #include "modules/planning/planner/planner.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/reference_line/reference_line.h" #include "modules/planning/reference_line/reference_point.h" /** * @namespace apollo::planning * @brief apollo::planning */ namespace apollo { namespace planning { /** * @class NaviPlanner * @brief NaviPlanner is a planner based on real-time relative maps. It uses the * vehicle's FLU (Front-Left-Up) coordinate system to accomplish tasks such as * cruising, following, overtaking, nudging, changing lanes and stopping. * Note that NaviPlanner is only used in navigation mode (turn on navigation * mode by setting "FLAGS_use_navigation_mode" to "true") and do not use it in * standard mode. */ class NaviPlanner : public PlannerWithReferenceLine { public: NaviPlanner() = delete; explicit NaviPlanner(const std::shared_ptr<DependencyInjector>& injector) : PlannerWithReferenceLine(injector) {} virtual ~NaviPlanner() = default; std::string Name() override { return "NAVI"; } common::Status Init(const PlanningConfig& config) override; /** * @brief Override function Plan in parent class Planner. * @param planning_init_point The trajectory point where planning starts. * @param frame Current planning frame. * @return OK if planning succeeds; error otherwise. */ common::Status Plan(const common::TrajectoryPoint& planning_init_point, Frame* frame, ADCTrajectory* ptr_computed_trajectory) override; void Stop() override {} /** * @brief Override function Plan in parent class Planner. * @param planning_init_point The trajectory point where planning starts. * @param frame Current planning frame. * @param reference_line_info The computed reference line. * @return OK if planning succeeds; error otherwise. */ common::Status PlanOnReferenceLine( const common::TrajectoryPoint& planning_init_point, Frame* frame, ReferenceLineInfo* reference_line_info) override; private: void RegisterTasks(); std::vector<common::SpeedPoint> GenerateInitSpeedProfile( const common::TrajectoryPoint& planning_init_point, const ReferenceLineInfo* reference_line_info); std::vector<common::SpeedPoint> DummyHotStart( const common::TrajectoryPoint& planning_init_point); std::vector<common::SpeedPoint> GenerateSpeedHotStart( const common::TrajectoryPoint& planning_init_point); void GenerateFallbackPathProfile(const ReferenceLineInfo* reference_line_info, PathData* path_data); void GenerateFallbackSpeedProfile(SpeedData* speed_data); SpeedData GenerateStopProfile(const double init_speed, const double init_acc) const; SpeedData GenerateStopProfileFromPolynomial(const double init_speed, const double init_acc) const; bool IsValidProfile(const QuinticPolynomialCurve1d& curve) const; void RecordObstacleDebugInfo(ReferenceLineInfo* reference_line_info); void RecordDebugInfo(ReferenceLineInfo* reference_line_info, const std::string& name, const double time_diff_ms); private: apollo::common::util::Factory<TaskConfig::TaskType, NaviTask> task_factory_; std::vector<std::unique_ptr<NaviTask>> tasks_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/navi/navi_planner.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides the implementation of the class "NaviPlanner". */ #include "modules/planning/planner/navi/navi_planner.h" #include <memory> #include <utility> #include "absl/strings/str_cat.h" #include "cyber/common/log.h" #include "cyber/time/clock.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/point_factory.h" #include "modules/common/util/string_util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/hdmap/hdmap.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/planning/common/ego_info.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/constraint_checker/constraint_checker.h" #include "modules/planning/navi/decider/navi_obstacle_decider.h" #include "modules/planning/navi/decider/navi_path_decider.h" #include "modules/planning/navi/decider/navi_speed_decider.h" /** * @namespace apollo::planning * @brief apollo::planning */ namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::SLPoint; using apollo::common::SpeedPoint; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::math::Vec2d; using apollo::common::util::PointFactory; using apollo::cyber::Clock; namespace { constexpr uint32_t KDestLanePriority = 0; constexpr double kPathOptimizationFallbackClost = 2e4; constexpr double kSpeedOptimizationFallbackClost = 2e4; constexpr double kStraightForwardLineCost = 10.0; } // namespace void NaviPlanner::RegisterTasks() { task_factory_.Register(TaskConfig::NAVI_PATH_DECIDER, []() -> NaviTask* { return new NaviPathDecider(); }); task_factory_.Register(TaskConfig::NAVI_SPEED_DECIDER, []() -> NaviTask* { return new NaviSpeedDecider(); }); } Status NaviPlanner::Init(const PlanningConfig& config) { // NaviPlanner is only used in navigation mode based on the real-time relative // map. if (!FLAGS_use_navigation_mode) { const std::string msg = "NaviPlanner is only used in navigation mode."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } AINFO << "In NaviPlanner::Init()"; RegisterTasks(); PlannerNaviConfig planner_conf = config.navigation_planning_config().planner_navi_config(); for (const auto task : planner_conf.task()) { tasks_.emplace_back( task_factory_.CreateObject(static_cast<TaskConfig::TaskType>(task))); AINFO << "Created task:" << tasks_.back()->Name(); } for (auto& task : tasks_) { if (!task->Init(config)) { const std::string msg = absl::StrCat( "Init task[", task->Name(), "] failed."); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } } return Status::OK(); } Status NaviPlanner::Plan(const TrajectoryPoint& planning_init_point, Frame* frame, ADCTrajectory* ptr_computed_trajectory) { // NaviPlanner is only used in navigation mode based on the real-time relative // map. if (!FLAGS_use_navigation_mode) { const std::string msg = "NaviPlanner is only used in navigation mode."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } size_t success_line_count = 0; for (auto& reference_line_info : *frame->mutable_reference_line_info()) { uint32_t priority = reference_line_info.GetPriority(); reference_line_info.SetCost(priority * kStraightForwardLineCost); if (priority != KDestLanePriority) { reference_line_info.SetDrivable(false); continue; } auto status = PlanOnReferenceLine(planning_init_point, frame, &reference_line_info); if (status.ok() && reference_line_info.IsDrivable()) { success_line_count += 1; } else { reference_line_info.SetDrivable(false); AERROR << "Failed to plan on reference line " << reference_line_info.Lanes().Id(); } ADEBUG << "ref line info: " << reference_line_info.Lanes().Id() << " priority : " << reference_line_info.GetPriority() << " cost : " << reference_line_info.Cost() << " driveable : " << reference_line_info.IsDrivable(); } if (success_line_count > 0) { return Status::OK(); } return Status(ErrorCode::PLANNING_ERROR, "Failed to plan on any reference line."); } Status NaviPlanner::PlanOnReferenceLine( const TrajectoryPoint& planning_init_point, Frame* frame, ReferenceLineInfo* reference_line_info) { if (!reference_line_info->IsChangeLanePath() && reference_line_info->IsNeighborLanePath()) { reference_line_info->AddCost(kStraightForwardLineCost); } ADEBUG << "planning start point:" << planning_init_point.DebugString(); auto* heuristic_speed_data = reference_line_info->mutable_speed_data(); auto speed_profile = GenerateInitSpeedProfile(planning_init_point, reference_line_info); if (speed_profile.empty()) { speed_profile = GenerateSpeedHotStart(planning_init_point); ADEBUG << "Using dummy hot start for speed vector"; } *heuristic_speed_data = SpeedData(speed_profile); auto ret = Status::OK(); for (auto& task : tasks_) { const double start_timestamp = Clock::NowInSeconds(); ret = task->Execute(frame, reference_line_info); if (!ret.ok()) { AERROR << "Failed to run tasks[" << task->Name() << "], Error message: " << ret.error_message(); break; } const double end_timestamp = Clock::NowInSeconds(); const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; ADEBUG << "after task " << task->Name() << ":" << reference_line_info->PathSpeedDebugString(); ADEBUG << task->Name() << " time spend: " << time_diff_ms << " ms."; RecordDebugInfo(reference_line_info, task->Name(), time_diff_ms); } RecordObstacleDebugInfo(reference_line_info); if (reference_line_info->path_data().Empty()) { ADEBUG << "Path fallback."; GenerateFallbackPathProfile(reference_line_info, reference_line_info->mutable_path_data()); reference_line_info->AddCost(kPathOptimizationFallbackClost); } if (!ret.ok() || reference_line_info->speed_data().empty()) { ADEBUG << "Speed fallback."; GenerateFallbackSpeedProfile(reference_line_info->mutable_speed_data()); reference_line_info->AddCost(kSpeedOptimizationFallbackClost); } DiscretizedTrajectory trajectory; if (!reference_line_info->CombinePathAndSpeedProfile( planning_init_point.relative_time(), planning_init_point.path_point().s(), &trajectory)) { const std::string msg = "Fail to aggregate planning trajectory."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } for (const auto* obstacle : reference_line_info->path_decision()->obstacles().Items()) { if (obstacle->IsVirtual()) { continue; } if (!obstacle->IsStatic()) { continue; } if (obstacle->LongitudinalDecision().has_stop()) { static constexpr double kRefrenceLineStaticObsCost = 1e3; reference_line_info->AddCost(kRefrenceLineStaticObsCost); } } if (FLAGS_enable_trajectory_check) { if (ConstraintChecker::ValidTrajectory(trajectory) != ConstraintChecker::Result::VALID) { const std::string msg = "Current planning trajectory is not valid."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } } reference_line_info->SetTrajectory(trajectory); reference_line_info->SetDrivable(true); return Status::OK(); } void NaviPlanner::RecordObstacleDebugInfo( ReferenceLineInfo* reference_line_info) { if (!FLAGS_enable_record_debug) { ADEBUG << "Skip record debug info"; return; } auto ptr_debug = reference_line_info->mutable_debug(); const auto path_decision = reference_line_info->path_decision(); for (const auto obstacle : path_decision->obstacles().Items()) { auto obstacle_debug = ptr_debug->mutable_planning_data()->add_obstacle(); obstacle_debug->set_id(obstacle->Id()); obstacle_debug->mutable_sl_boundary()->CopyFrom( obstacle->PerceptionSLBoundary()); const auto& decider_tags = obstacle->decider_tags(); const auto& decisions = obstacle->decisions(); if (decider_tags.size() != decisions.size()) { AERROR << "decider_tags size: " << decider_tags.size() << " different from decisions size:" << decisions.size(); } for (size_t i = 0; i < decider_tags.size(); ++i) { auto decision_tag = obstacle_debug->add_decision_tag(); decision_tag->set_decider_tag(decider_tags[i]); decision_tag->mutable_decision()->CopyFrom(decisions[i]); } } } void NaviPlanner::RecordDebugInfo(ReferenceLineInfo* reference_line_info, const std::string& name, const double time_diff_ms) { if (!FLAGS_enable_record_debug) { ADEBUG << "Skip record debug info"; return; } if (reference_line_info == nullptr) { AERROR << "Reference line info is null."; return; } auto ptr_latency_stats = reference_line_info->mutable_latency_stats(); auto ptr_stats = ptr_latency_stats->add_task_stats(); ptr_stats->set_name(name); ptr_stats->set_time_ms(time_diff_ms); } std::vector<SpeedPoint> NaviPlanner::GenerateInitSpeedProfile( const TrajectoryPoint& planning_init_point, const ReferenceLineInfo* reference_line_info) { std::vector<SpeedPoint> speed_profile; const auto* last_frame = scenario_manager_.injector()->frame_history()->Latest(); if (!last_frame) { AWARN << "last frame is empty"; return speed_profile; } const ReferenceLineInfo* last_reference_line_info = last_frame->DriveReferenceLineInfo(); if (!last_reference_line_info) { ADEBUG << "last reference line info is empty"; return speed_profile; } if (!reference_line_info->IsStartFrom(*last_reference_line_info)) { ADEBUG << "Current reference line is not started previous drived line"; return speed_profile; } const auto& last_speed_data = last_reference_line_info->speed_data(); if (!last_speed_data.empty()) { const auto& last_init_point = last_frame->PlanningStartPoint().path_point(); Vec2d last_xy_point(last_init_point.x(), last_init_point.y()); SLPoint last_sl_point; if (!last_reference_line_info->reference_line().XYToSL(last_xy_point, &last_sl_point)) { AERROR << "Fail to transfer xy to sl when init speed profile"; } Vec2d xy_point(planning_init_point.path_point().x(), planning_init_point.path_point().y()); SLPoint sl_point; if (!last_reference_line_info->reference_line().XYToSL(xy_point, &sl_point)) { AERROR << "Fail to transfer xy to sl when init speed profile"; } double s_diff = sl_point.s() - last_sl_point.s(); double start_time = 0.0; double start_s = 0.0; bool is_updated_start = false; for (const auto& speed_point : last_speed_data) { if (speed_point.s() < s_diff) { continue; } if (!is_updated_start) { start_time = speed_point.t(); start_s = speed_point.s(); is_updated_start = true; } speed_profile.push_back(PointFactory::ToSpeedPoint( speed_point.s() - start_s, speed_point.t() - start_time, speed_point.v(), speed_point.a(), speed_point.da())); } } return speed_profile; } // This is a dummy simple hot start, need refine later std::vector<SpeedPoint> NaviPlanner::GenerateSpeedHotStart( const TrajectoryPoint& planning_init_point) { std::vector<SpeedPoint> hot_start_speed_profile; double s = 0.0; double t = 0.0; double v = common::math::Clamp(planning_init_point.v(), 5.0, FLAGS_planning_upper_speed_limit); while (t < FLAGS_trajectory_time_length) { hot_start_speed_profile.push_back(PointFactory::ToSpeedPoint(s, t, v)); t += FLAGS_trajectory_time_min_interval; s += v * FLAGS_trajectory_time_min_interval; } return hot_start_speed_profile; } void NaviPlanner::GenerateFallbackPathProfile( const ReferenceLineInfo* reference_line_info, PathData* path_data) { auto adc_point = scenario_manager_.injector()->ego_info()->start_point(); double adc_s = reference_line_info->AdcSlBoundary().end_s(); const double max_s = 150.0; const double unit_s = 1.0; // projection of adc point onto reference line const auto& adc_ref_point = reference_line_info->reference_line().GetReferencePoint(0.5 * adc_s); DCHECK(adc_point.has_path_point()); const double dx = adc_point.path_point().x() - adc_ref_point.x(); const double dy = adc_point.path_point().y() - adc_ref_point.y(); std::vector<common::PathPoint> path_points; for (double s = adc_s; s < max_s; s += unit_s) { const auto& ref_point = reference_line_info->reference_line().GetReferencePoint(s); path_points.push_back(PointFactory::ToPathPoint( ref_point.x() + dx, ref_point.y() + dy, 0.0, s, ref_point.heading(), ref_point.kappa(), ref_point.dkappa())); } path_data->SetReferenceLine(&(reference_line_info->reference_line())); path_data->SetDiscretizedPath(DiscretizedPath(std::move(path_points))); } void NaviPlanner::GenerateFallbackSpeedProfile(SpeedData* speed_data) { const auto& start_point = scenario_manager_.injector()->ego_info()->start_point(); *speed_data = GenerateStopProfileFromPolynomial(start_point.v(), start_point.a()); if (speed_data->empty()) { *speed_data = GenerateStopProfile(start_point.v(), start_point.a()); } } SpeedData NaviPlanner::GenerateStopProfile(const double init_speed, const double init_acc) const { AERROR << "Slowing down the car."; SpeedData speed_data; const double kFixedJerk = -1.0; const double first_point_acc = std::fmin(0.0, init_acc); const double max_t = 3.0; const double unit_t = 0.02; double pre_s = 0.0; const double t_mid = (FLAGS_slowdown_profile_deceleration - first_point_acc) / kFixedJerk; const double s_mid = init_speed * t_mid + 0.5 * first_point_acc * t_mid * t_mid + 1.0 / 6.0 * kFixedJerk * t_mid * t_mid * t_mid; const double v_mid = init_speed + first_point_acc * t_mid + 0.5 * kFixedJerk * t_mid * t_mid; for (double t = 0.0; t < max_t; t += unit_t) { double s = 0.0; double v = 0.0; if (t <= t_mid) { s = std::fmax(pre_s, init_speed * t + 0.5 * first_point_acc * t * t + 1.0 / 6.0 * kFixedJerk * t * t * t); v = std::fmax( 0.0, init_speed + first_point_acc * t + 0.5 * kFixedJerk * t * t); const double a = first_point_acc + kFixedJerk * t; speed_data.AppendSpeedPoint(s, t, v, a, 0.0); pre_s = s; } else { s = std::fmax(pre_s, s_mid + v_mid * (t - t_mid) + 0.5 * FLAGS_slowdown_profile_deceleration * (t - t_mid) * (t - t_mid)); v = std::fmax(0.0, v_mid + (t - t_mid) * FLAGS_slowdown_profile_deceleration); speed_data.AppendSpeedPoint(s, t, v, FLAGS_slowdown_profile_deceleration, 0.0); } pre_s = s; } return speed_data; } SpeedData NaviPlanner::GenerateStopProfileFromPolynomial( const double init_speed, const double init_acc) const { AERROR << "Slowing down the car with polynomial."; static constexpr double kMaxT = 4.0; for (double t = 2.0; t <= kMaxT; t += 0.5) { for (double s = 0.0; s < 50.0; s += 1.0) { QuinticPolynomialCurve1d curve(0.0, init_speed, init_acc, s, 0.0, 0.0, t); if (!IsValidProfile(curve)) { continue; } static constexpr double kUnitT = 0.02; SpeedData speed_data; for (double curve_t = 0.0; curve_t <= t; curve_t += kUnitT) { const double curve_s = curve.Evaluate(0, curve_t); const double curve_v = curve.Evaluate(1, curve_t); const double curve_a = curve.Evaluate(2, curve_t); const double curve_da = curve.Evaluate(3, curve_t); speed_data.AppendSpeedPoint(curve_s, curve_t, curve_v, curve_a, curve_da); } return speed_data; } } return SpeedData(); } bool NaviPlanner::IsValidProfile(const QuinticPolynomialCurve1d& curve) const { for (double evaluate_t = 0.1; evaluate_t <= curve.ParamLength(); evaluate_t += 0.2) { const double v = curve.Evaluate(1, evaluate_t); const double a = curve.Evaluate(2, evaluate_t); static constexpr double kEpsilon = 1e-3; if (v < -kEpsilon || a < -5.0) { return false; } } return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/navi/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "navi_planner", srcs = ["navi_planner.cc"], hdrs = ["navi_planner.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//cyber", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/status", "//modules/common/util", "//modules/common/util:util_tool", "//modules/common/vehicle_state:vehicle_state_provider", "//modules/map/hdmap", "//modules/planning/common:planning_common", "//modules/planning/constraint_checker", "//modules/planning/math/curve1d:quartic_polynomial_curve1d", "//modules/planning/navi/decider:navi_obstacle_decider", "//modules/planning/navi/decider:navi_path_decider", "//modules/planning/navi/decider:navi_speed_decider", "//modules/planning/planner", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/reference_line", "//modules/planning/reference_line:qp_spline_reference_line_smoother", "@com_github_gflags_gflags//:gflags", ], ) cc_test( name = "navi_planner_test", size = "small", srcs = ["navi_planner_test.cc"], data = ["//modules/planning:planning_testdata"], linkopts = ["-lgomp"], deps = [ ":navi_planner", "//cyber", "//modules/common/util", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cpplint()
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/lattice/lattice_planner.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/planner/lattice/lattice_planner.h" #include <limits> #include <memory> #include <utility> #include <vector> #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "cyber/time/clock.h" #include "modules/common/math/cartesian_frenet_conversion.h" #include "modules/common/math/path_matcher.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/constraint_checker/collision_checker.h" #include "modules/planning/constraint_checker/constraint_checker.h" #include "modules/planning/lattice/behavior/path_time_graph.h" #include "modules/planning/lattice/behavior/prediction_querier.h" #include "modules/planning/lattice/trajectory_generation/backup_trajectory_generator.h" #include "modules/planning/lattice/trajectory_generation/lattice_trajectory1d.h" #include "modules/planning/lattice/trajectory_generation/trajectory1d_generator.h" #include "modules/planning/lattice/trajectory_generation/trajectory_combiner.h" #include "modules/planning/lattice/trajectory_generation/trajectory_evaluator.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::PathPoint; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::math::CartesianFrenetConverter; using apollo::common::math::PathMatcher; using apollo::cyber::Clock; namespace { std::vector<PathPoint> ToDiscretizedReferenceLine( const std::vector<ReferencePoint>& ref_points) { double s = 0.0; std::vector<PathPoint> path_points; for (const auto& ref_point : ref_points) { PathPoint path_point; path_point.set_x(ref_point.x()); path_point.set_y(ref_point.y()); path_point.set_theta(ref_point.heading()); path_point.set_kappa(ref_point.kappa()); path_point.set_dkappa(ref_point.dkappa()); if (!path_points.empty()) { double dx = path_point.x() - path_points.back().x(); double dy = path_point.y() - path_points.back().y(); s += std::sqrt(dx * dx + dy * dy); } path_point.set_s(s); path_points.push_back(std::move(path_point)); } return path_points; } void ComputeInitFrenetState(const PathPoint& matched_point, const TrajectoryPoint& cartesian_state, std::array<double, 3>* ptr_s, std::array<double, 3>* ptr_d) { CartesianFrenetConverter::cartesian_to_frenet( matched_point.s(), matched_point.x(), matched_point.y(), matched_point.theta(), matched_point.kappa(), matched_point.dkappa(), cartesian_state.path_point().x(), cartesian_state.path_point().y(), cartesian_state.v(), cartesian_state.a(), cartesian_state.path_point().theta(), cartesian_state.path_point().kappa(), ptr_s, ptr_d); } } // namespace Status LatticePlanner::Plan(const TrajectoryPoint& planning_start_point, Frame* frame, ADCTrajectory* ptr_computed_trajectory) { size_t success_line_count = 0; size_t index = 0; for (auto& reference_line_info : *frame->mutable_reference_line_info()) { if (index != 0) { reference_line_info.SetPriorityCost( FLAGS_cost_non_priority_reference_line); } else { reference_line_info.SetPriorityCost(0.0); } auto status = PlanOnReferenceLine(planning_start_point, frame, &reference_line_info); if (status != Status::OK()) { if (reference_line_info.IsChangeLanePath()) { AERROR << "Planner failed to change lane to " << reference_line_info.Lanes().Id(); } else { AERROR << "Planner failed to " << reference_line_info.Lanes().Id(); } } else { success_line_count += 1; } ++index; } if (success_line_count > 0) { return Status::OK(); } return Status(ErrorCode::PLANNING_ERROR, "Failed to plan on any reference line."); } Status LatticePlanner::PlanOnReferenceLine( const TrajectoryPoint& planning_init_point, Frame* frame, ReferenceLineInfo* reference_line_info) { static size_t num_planning_cycles = 0; static size_t num_planning_succeeded_cycles = 0; double start_time = Clock::NowInSeconds(); double current_time = start_time; ADEBUG << "Number of planning cycles: " << num_planning_cycles << " " << num_planning_succeeded_cycles; ++num_planning_cycles; reference_line_info->set_is_on_reference_line(); // 1. obtain a reference line and transform it to the PathPoint format. auto ptr_reference_line = std::make_shared<std::vector<PathPoint>>(ToDiscretizedReferenceLine( reference_line_info->reference_line().reference_points())); // 2. compute the matched point of the init planning point on the reference // line. PathPoint matched_point = PathMatcher::MatchToPath( *ptr_reference_line, planning_init_point.path_point().x(), planning_init_point.path_point().y()); // 3. according to the matched point, compute the init state in Frenet frame. std::array<double, 3> init_s; std::array<double, 3> init_d; ComputeInitFrenetState(matched_point, planning_init_point, &init_s, &init_d); ADEBUG << "ReferenceLine and Frenet Conversion Time = " << (Clock::NowInSeconds() - current_time) * 1000; current_time = Clock::NowInSeconds(); auto ptr_prediction_querier = std::make_shared<PredictionQuerier>( frame->obstacles(), ptr_reference_line); // 4. parse the decision and get the planning target. auto ptr_path_time_graph = std::make_shared<PathTimeGraph>( ptr_prediction_querier->GetObstacles(), *ptr_reference_line, reference_line_info, init_s[0], init_s[0] + FLAGS_speed_lon_decision_horizon, 0.0, FLAGS_trajectory_time_length, init_d); double speed_limit = reference_line_info->reference_line().GetSpeedLimitFromS(init_s[0]); reference_line_info->SetLatticeCruiseSpeed(speed_limit); PlanningTarget planning_target = reference_line_info->planning_target(); if (planning_target.has_stop_point()) { ADEBUG << "Planning target stop s: " << planning_target.stop_point().s() << "Current ego s: " << init_s[0]; } ADEBUG << "Decision_Time = " << (Clock::NowInSeconds() - current_time) * 1000; current_time = Clock::NowInSeconds(); // 5. generate 1d trajectory bundle for longitudinal and lateral respectively. Trajectory1dGenerator trajectory1d_generator( init_s, init_d, ptr_path_time_graph, ptr_prediction_querier); std::vector<std::shared_ptr<Curve1d>> lon_trajectory1d_bundle; std::vector<std::shared_ptr<Curve1d>> lat_trajectory1d_bundle; trajectory1d_generator.GenerateTrajectoryBundles( planning_target, &lon_trajectory1d_bundle, &lat_trajectory1d_bundle); ADEBUG << "Trajectory_Generation_Time = " << (Clock::NowInSeconds() - current_time) * 1000; current_time = Clock::NowInSeconds(); // 6. first, evaluate the feasibility of the 1d trajectories according to // dynamic constraints. // second, evaluate the feasible longitudinal and lateral trajectory pairs // and sort them according to the cost. TrajectoryEvaluator trajectory_evaluator( init_s, planning_target, lon_trajectory1d_bundle, lat_trajectory1d_bundle, ptr_path_time_graph, ptr_reference_line); ADEBUG << "Trajectory_Evaluator_Construction_Time = " << (Clock::NowInSeconds() - current_time) * 1000; current_time = Clock::NowInSeconds(); ADEBUG << "number of trajectory pairs = " << trajectory_evaluator.num_of_trajectory_pairs() << " number_lon_traj = " << lon_trajectory1d_bundle.size() << " number_lat_traj = " << lat_trajectory1d_bundle.size(); // Get instance of collision checker and constraint checker CollisionChecker collision_checker(frame->obstacles(), init_s[0], init_d[0], *ptr_reference_line, reference_line_info, ptr_path_time_graph); // 7. always get the best pair of trajectories to combine; return the first // collision-free trajectory. size_t constraint_failure_count = 0; size_t collision_failure_count = 0; size_t combined_constraint_failure_count = 0; size_t lon_vel_failure_count = 0; size_t lon_acc_failure_count = 0; size_t lon_jerk_failure_count = 0; size_t curvature_failure_count = 0; size_t lat_acc_failure_count = 0; size_t lat_jerk_failure_count = 0; size_t num_lattice_traj = 0; while (trajectory_evaluator.has_more_trajectory_pairs()) { double trajectory_pair_cost = trajectory_evaluator.top_trajectory_pair_cost(); auto trajectory_pair = trajectory_evaluator.next_top_trajectory_pair(); // combine two 1d trajectories to one 2d trajectory auto combined_trajectory = TrajectoryCombiner::Combine( *ptr_reference_line, *trajectory_pair.first, *trajectory_pair.second, planning_init_point.relative_time()); // check longitudinal and lateral acceleration // considering trajectory curvatures auto result = ConstraintChecker::ValidTrajectory(combined_trajectory); if (result != ConstraintChecker::Result::VALID) { ++combined_constraint_failure_count; switch (result) { case ConstraintChecker::Result::LON_VELOCITY_OUT_OF_BOUND: lon_vel_failure_count += 1; break; case ConstraintChecker::Result::LON_ACCELERATION_OUT_OF_BOUND: lon_acc_failure_count += 1; break; case ConstraintChecker::Result::LON_JERK_OUT_OF_BOUND: lon_jerk_failure_count += 1; break; case ConstraintChecker::Result::CURVATURE_OUT_OF_BOUND: curvature_failure_count += 1; break; case ConstraintChecker::Result::LAT_ACCELERATION_OUT_OF_BOUND: lat_acc_failure_count += 1; break; case ConstraintChecker::Result::LAT_JERK_OUT_OF_BOUND: lat_jerk_failure_count += 1; break; case ConstraintChecker::Result::VALID: default: // Intentional empty break; } continue; } // check collision with other obstacles if (collision_checker.InCollision(combined_trajectory)) { ++collision_failure_count; continue; } // put combine trajectory into debug data const auto& combined_trajectory_points = combined_trajectory; num_lattice_traj += 1; reference_line_info->SetTrajectory(combined_trajectory); reference_line_info->SetCost(reference_line_info->PriorityCost() + trajectory_pair_cost); reference_line_info->SetDrivable(true); // Print the chosen end condition and start condition ADEBUG << "Starting Lon. State: s = " << init_s[0] << " ds = " << init_s[1] << " dds = " << init_s[2]; // cast auto lattice_traj_ptr = std::dynamic_pointer_cast<LatticeTrajectory1d>(trajectory_pair.first); if (!lattice_traj_ptr) { ADEBUG << "Dynamically casting trajectory1d ptr. failed."; } if (lattice_traj_ptr->has_target_position()) { ADEBUG << "Ending Lon. State s = " << lattice_traj_ptr->target_position() << " ds = " << lattice_traj_ptr->target_velocity() << " t = " << lattice_traj_ptr->target_time(); } ADEBUG << "InputPose"; ADEBUG << "XY: " << planning_init_point.ShortDebugString(); ADEBUG << "S: (" << init_s[0] << ", " << init_s[1] << "," << init_s[2] << ")"; ADEBUG << "L: (" << init_d[0] << ", " << init_d[1] << "," << init_d[2] << ")"; ADEBUG << "Reference_line_priority_cost = " << reference_line_info->PriorityCost(); ADEBUG << "Total_Trajectory_Cost = " << trajectory_pair_cost; ADEBUG << "OutputTrajectory"; for (uint i = 0; i < 10; ++i) { ADEBUG << combined_trajectory_points[i].ShortDebugString(); } break; /* auto combined_trajectory_path = ptr_debug->mutable_planning_data()->add_trajectory_path(); for (uint i = 0; i < combined_trajectory_points.size(); ++i) { combined_trajectory_path->add_trajectory_point()->CopyFrom( combined_trajectory_points[i]); } combined_trajectory_path->set_lattice_trajectory_cost(trajectory_pair_cost); */ } ADEBUG << "Trajectory_Evaluation_Time = " << (Clock::NowInSeconds() - current_time) * 1000; ADEBUG << "Step CombineTrajectory Succeeded"; ADEBUG << "1d trajectory not valid for constraint [" << constraint_failure_count << "] times"; ADEBUG << "Combined trajectory not valid for [" << combined_constraint_failure_count << "] times"; ADEBUG << "Trajectory not valid for collision [" << collision_failure_count << "] times"; ADEBUG << "Total_Lattice_Planning_Frame_Time = " << (Clock::NowInSeconds() - start_time) * 1000; if (num_lattice_traj > 0) { ADEBUG << "Planning succeeded"; num_planning_succeeded_cycles += 1; reference_line_info->SetDrivable(true); return Status::OK(); } else { AERROR << "Planning failed"; if (FLAGS_enable_backup_trajectory) { AERROR << "Use backup trajectory"; BackupTrajectoryGenerator backup_trajectory_generator( init_s, init_d, planning_init_point.relative_time(), std::make_shared<CollisionChecker>(collision_checker), &trajectory1d_generator); DiscretizedTrajectory trajectory = backup_trajectory_generator.GenerateTrajectory(*ptr_reference_line); reference_line_info->AddCost(FLAGS_backup_trajectory_cost); reference_line_info->SetTrajectory(trajectory); reference_line_info->SetDrivable(true); return Status::OK(); } else { reference_line_info->SetCost(std::numeric_limits<double>::infinity()); } return Status(ErrorCode::PLANNING_ERROR, "No feasible trajectories"); } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/lattice/lattice_planner.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <memory> #include <string> #include "modules/common/status/status.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/reference_line_info.h" #include "modules/planning/planner/planner.h" #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { class LatticePlanner : public PlannerWithReferenceLine { public: LatticePlanner() = delete; explicit LatticePlanner(const std::shared_ptr<DependencyInjector>& injector) : PlannerWithReferenceLine(injector) {} virtual ~LatticePlanner() = default; std::string Name() override { return "LATTICE"; } common::Status Init(const PlanningConfig& config) override { return common::Status::OK(); } void Stop() override {} /** * @brief Override function Plan in parent class Planner. * @param planning_init_point The trajectory point where planning starts. * @param frame Current planning frame. * @return OK if planning succeeds; error otherwise. */ common::Status Plan(const common::TrajectoryPoint& planning_init_point, Frame* frame, ADCTrajectory* ptr_computed_trajectory) override; /** * @brief Override function Plan in parent class Planner. * @param planning_init_point The trajectory point where planning starts. * @param frame Current planning frame. * @param reference_line_info The computed reference line. * @return OK if planning succeeds; error otherwise. */ common::Status PlanOnReferenceLine( const common::TrajectoryPoint& planning_init_point, Frame* frame, ReferenceLineInfo* reference_line_info) override; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/lattice/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "lattice_planner", srcs = ["lattice_planner.cc"], hdrs = ["lattice_planner.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//cyber", "//modules/common/math", "//modules/common/vehicle_state:vehicle_state_provider", "//modules/planning/common:planning_gflags", "//modules/planning/constraint_checker", "//modules/planning/constraint_checker:collision_checker", "//modules/planning/lattice/behavior:path_time_graph", "//modules/planning/lattice/trajectory_generation:backup_trajectory_generator", "//modules/planning/lattice/trajectory_generation:lattice_trajectory1d", "//modules/planning/lattice/trajectory_generation:trajectory1d_generator", "//modules/planning/lattice/trajectory_generation:trajectory_combiner", "//modules/planning/lattice/trajectory_generation:trajectory_evaluator", "//modules/planning/planner", "//modules/common_msgs/planning_msgs:planning_cc_proto", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/rtk/rtk_replay_planner_test.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planner/rtk/rtk_replay_planner.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/common/configs/config_gflags.h" #include "modules/planning/common/planning_gflags.h" using apollo::common::TrajectoryPoint; namespace apollo { namespace planning { TEST(RTKReplayPlannerTest, ComputeTrajectory) { FLAGS_rtk_trajectory_filename = "modules/planning/testdata/garage.csv"; FLAGS_enable_map_reference_unify = false; auto injector = std::make_shared<DependencyInjector>(); RTKReplayPlanner planner(injector); TrajectoryPoint start_point; common::PointENU point; point.set_x(586385.782842); point.set_y(4140674.76063); start_point.mutable_path_point()->set_x(586385.782842); start_point.mutable_path_point()->set_y(4140674.76063); ReferenceLine ref; hdmap::RouteSegments segments; localization::LocalizationEstimate localization; canbus::Chassis chassis; localization.mutable_pose()->mutable_position()->set_x(586385.782842); localization.mutable_pose()->mutable_position()->set_y(4140674.76063); localization.mutable_pose()->mutable_angular_velocity()->set_x(0.0); localization.mutable_pose()->mutable_angular_velocity()->set_y(0.0); localization.mutable_pose()->mutable_angular_velocity()->set_z(0.0); localization.mutable_pose()->mutable_linear_acceleration()->set_x(0.0); localization.mutable_pose()->mutable_linear_acceleration()->set_y(0.0); localization.mutable_pose()->mutable_linear_acceleration()->set_z(0.0); injector->vehicle_state()->Update(localization, chassis); common::VehicleState state; state.set_x(point.x()); state.set_y(point.y()); state.set_z(point.z()); ReferenceLineInfo info(state, start_point, ref, segments); auto status = planner.PlanOnReferenceLine(start_point, nullptr, &info); const auto& trajectory = info.trajectory(); EXPECT_TRUE(status.ok()); EXPECT_FALSE(trajectory.empty()); EXPECT_EQ(trajectory.size(), FLAGS_rtk_trajectory_forward); auto first_point = trajectory.begin(); EXPECT_DOUBLE_EQ(first_point->path_point().x(), 586385.782841); EXPECT_DOUBLE_EQ(first_point->path_point().y(), 4140674.76065); auto last_point = trajectory.rbegin(); EXPECT_DOUBLE_EQ(last_point->path_point().x(), 586355.063786); EXPECT_DOUBLE_EQ(last_point->path_point().y(), 4140681.98605); } TEST(RTKReplayPlannerTest, ErrorTest) { FLAGS_rtk_trajectory_filename = "modules/planning/testdata/garage_no_file.csv"; FLAGS_enable_map_reference_unify = false; auto injector = std::make_shared<DependencyInjector>(); RTKReplayPlanner planner(injector); FLAGS_rtk_trajectory_filename = "modules/planning/testdata/garage_error.csv"; RTKReplayPlanner planner_with_error_csv(injector); TrajectoryPoint start_point; start_point.mutable_path_point()->set_x(586385.782842); start_point.mutable_path_point()->set_y(4140674.76063); common::PointENU point; point.set_x(586385.782842); point.set_y(4140674.76063); localization::LocalizationEstimate localization; canbus::Chassis chassis; localization.mutable_pose()->mutable_position()->set_x(586385.782842); localization.mutable_pose()->mutable_position()->set_y(4140674.76063); localization.mutable_pose()->mutable_angular_velocity()->set_x(0.0); localization.mutable_pose()->mutable_angular_velocity()->set_y(0.0); localization.mutable_pose()->mutable_angular_velocity()->set_z(0.0); localization.mutable_pose()->mutable_linear_acceleration()->set_x(0.0); localization.mutable_pose()->mutable_linear_acceleration()->set_y(0.0); localization.mutable_pose()->mutable_linear_acceleration()->set_z(0.0); injector->vehicle_state()->Update(localization, chassis); ReferenceLine ref; hdmap::RouteSegments segments; common::VehicleState state; state.set_x(point.x()); state.set_y(point.y()); state.set_z(point.z()); ReferenceLineInfo info(state, start_point, ref, segments); EXPECT_TRUE( !(planner_with_error_csv.PlanOnReferenceLine(start_point, nullptr, &info)) .ok()); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/rtk/rtk_replay_planner.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planner/rtk/rtk_replay_planner.h" #include <memory> #include <utility> #include "absl/strings/str_split.h" #include "cyber/common/log.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; RTKReplayPlanner::RTKReplayPlanner( const std::shared_ptr<DependencyInjector>& injector) : PlannerWithReferenceLine(injector) { ReadTrajectoryFile(FLAGS_rtk_trajectory_filename); } Status RTKReplayPlanner::Init(const PlanningConfig&) { return Status::OK(); } Status RTKReplayPlanner::Plan(const TrajectoryPoint& planning_start_point, Frame* frame, ADCTrajectory* ptr_computed_trajectory) { auto status = Status::OK(); bool has_plan = false; auto it = std::find_if( frame->mutable_reference_line_info()->begin(), frame->mutable_reference_line_info()->end(), [](const ReferenceLineInfo& ref) { return ref.IsChangeLanePath(); }); if (it != frame->mutable_reference_line_info()->end()) { status = PlanOnReferenceLine(planning_start_point, frame, &(*it)); has_plan = (it->IsDrivable() && it->IsChangeLanePath() && it->trajectory().GetSpatialLength() > FLAGS_change_lane_min_length); if (!has_plan) { AERROR << "Fail to plan for lane change."; } } if (!has_plan || !FLAGS_prioritize_change_lane) { for (auto& reference_line_info : *frame->mutable_reference_line_info()) { if (reference_line_info.IsChangeLanePath()) { continue; } status = PlanOnReferenceLine(planning_start_point, frame, &reference_line_info); if (status != Status::OK()) { AERROR << "planner failed to make a driving plan for: " << reference_line_info.Lanes().Id(); } } } return status; } Status RTKReplayPlanner::PlanOnReferenceLine( const TrajectoryPoint& planning_init_point, Frame*, ReferenceLineInfo* reference_line_info) { if (complete_rtk_trajectory_.empty() || complete_rtk_trajectory_.size() < 2) { const std::string msg = "RTKReplayPlanner doesn't have a recorded trajectory or " "the recorded trajectory doesn't have enough valid trajectory " "points."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } std::uint32_t matched_index = QueryPositionMatchedPoint(planning_init_point, complete_rtk_trajectory_); std::uint32_t forward_buffer = static_cast<std::uint32_t>(FLAGS_rtk_trajectory_forward); // end_index is excluded. std::uint32_t end_index = std::min<std::uint32_t>( static_cast<std::uint32_t>(complete_rtk_trajectory_.size()), matched_index + forward_buffer); // auto* trajectory_points = trajectory_pb->mutable_trajectory_point(); std::vector<TrajectoryPoint> trajectory_points( complete_rtk_trajectory_.begin() + matched_index, complete_rtk_trajectory_.begin() + end_index); // reset relative time double zero_time = complete_rtk_trajectory_[matched_index].relative_time(); for (auto& trajectory_point : trajectory_points) { trajectory_point.set_relative_time(trajectory_point.relative_time() - zero_time); } // check if the trajectory has enough points; // if not, append the last points multiple times and // adjust their corresponding time stamps. while (trajectory_points.size() < static_cast<size_t>(FLAGS_rtk_trajectory_forward)) { const auto& last_point = trajectory_points.rbegin(); auto new_point = last_point; new_point->set_relative_time(new_point->relative_time() + FLAGS_rtk_trajectory_resolution); trajectory_points.push_back(*new_point); } reference_line_info->SetTrajectory(DiscretizedTrajectory(trajectory_points)); return Status::OK(); } void RTKReplayPlanner::ReadTrajectoryFile(const std::string& filename) { if (!complete_rtk_trajectory_.empty()) { complete_rtk_trajectory_.clear(); } std::ifstream file_in(filename.c_str()); if (!file_in.is_open()) { AERROR << "RTKReplayPlanner cannot open trajectory file: " << filename; return; } std::string line; // skip the header line. getline(file_in, line); while (true) { getline(file_in, line); if (line == "") { break; } const std::vector<std::string> tokens = absl::StrSplit(line, absl::ByAnyChar("\t ")); if (tokens.size() < 11) { AERROR << "RTKReplayPlanner parse line failed; the data dimension does " "not match."; AERROR << line; continue; } TrajectoryPoint point; point.mutable_path_point()->set_x(std::stod(tokens[0])); point.mutable_path_point()->set_y(std::stod(tokens[1])); point.mutable_path_point()->set_z(std::stod(tokens[2])); point.set_v(std::stod(tokens[3])); point.set_a(std::stod(tokens[4])); point.mutable_path_point()->set_kappa(std::stod(tokens[5])); point.mutable_path_point()->set_dkappa(std::stod(tokens[6])); point.set_relative_time(std::stod(tokens[7])); point.mutable_path_point()->set_theta(std::stod(tokens[8])); point.mutable_path_point()->set_s(std::stod(tokens[10])); complete_rtk_trajectory_.push_back(std::move(point)); } file_in.close(); } std::uint32_t RTKReplayPlanner::QueryPositionMatchedPoint( const TrajectoryPoint& start_point, const std::vector<TrajectoryPoint>& trajectory) const { auto func_distance_square = [](const TrajectoryPoint& point, const double x, const double y) { double dx = point.path_point().x() - x; double dy = point.path_point().y() - y; return dx * dx + dy * dy; }; double d_min = func_distance_square(trajectory.front(), start_point.path_point().x(), start_point.path_point().y()); std::uint32_t index_min = 0; for (std::uint32_t i = 1; i < trajectory.size(); ++i) { double d_temp = func_distance_square(trajectory[i], start_point.path_point().x(), start_point.path_point().y()); if (d_temp < d_min) { d_min = d_temp; index_min = i; } } return index_min; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/rtk/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "rtk_planner", srcs = ["rtk_replay_planner.cc"], hdrs = ["rtk_replay_planner.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//cyber", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/util", "//modules/common/util:util_tool", "//modules/common/vehicle_state:vehicle_state_provider", "//modules/planning/common:planning_common", "//modules/planning/math/curve1d:quartic_polynomial_curve1d", "//modules/planning/planner", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/proto:planning_config_cc_proto", "@com_github_gflags_gflags//:gflags", "@com_google_absl//:absl", "@eigen", ], ) cc_test( name = "rtk_replay_planner_test", size = "small", srcs = ["rtk_replay_planner_test.cc"], data = ["//modules/planning:planning_testdata"], linkopts = ["-lgomp"], deps = [ ":rtk_planner", "//cyber", "//modules/common/util", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cpplint()
0
apollo_public_repos/apollo/modules/planning/planner
apollo_public_repos/apollo/modules/planning/planner/rtk/rtk_replay_planner.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include <string> #include <vector> #include "modules/planning/common/frame.h" #include "modules/planning/common/reference_line_info.h" #include "modules/planning/planner/planner.h" #include "modules/planning/proto/planning_config.pb.h" /** * @namespace apollo::planning * @brief apollo::planning */ namespace apollo { namespace planning { /** * @class RTKReplayPlanner * @brief RTKReplayPlanner is a derived class of Planner. * It reads a recorded trajectory from a trajectory file and * outputs proper segment of the trajectory according to vehicle * position. */ class RTKReplayPlanner : public PlannerWithReferenceLine { public: /** * @brief Constructor */ explicit RTKReplayPlanner( const std::shared_ptr<DependencyInjector>& injector); /** * @brief Destructor */ virtual ~RTKReplayPlanner() = default; std::string Name() override { return "RTK"; } apollo::common::Status Init(const PlanningConfig& config) override; void Stop() override {} /** * @brief Override function Plan in parent class Planner. * @param planning_init_point The trajectory point where planning starts. * @param frame Current planning frame. * @return OK if planning succeeds; error otherwise. */ apollo::common::Status Plan( const common::TrajectoryPoint& planning_init_point, Frame* frame, ADCTrajectory* ptr_computed_trajectory) override; /** * @brief Override function Plan in parent class Planner. * @param planning_init_point The trajectory point where planning starts. * @param frame Current planning frame. * @param reference_line_info The computed reference line. * @return OK if planning succeeds; error otherwise. */ apollo::common::Status PlanOnReferenceLine( const common::TrajectoryPoint& planning_init_point, Frame* frame, ReferenceLineInfo* reference_line_info) override; /** * @brief Read the recorded trajectory file. * @param filename The name of the trajectory file. */ void ReadTrajectoryFile(const std::string& filename); private: std::uint32_t QueryPositionMatchedPoint( const common::TrajectoryPoint& start_point, const std::vector<common::TrajectoryPoint>& trajectory) const; std::vector<common::TrajectoryPoint> complete_rtk_trajectory_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/dag/planning.dag
# Define all coms in DAG streaming. module_config { module_library : "/apollo/bazel-bin/modules/planning/libplanning_component.so" components { class_name : "PlanningComponent" config { name: "planning" config_file_path: "/apollo/modules/planning/conf/planning_config.pb.txt" flag_file_path: "/apollo/modules/planning/conf/planning.conf" readers: [ { channel: "/apollo/prediction" }, { channel: "/apollo/canbus/chassis" qos_profile: { depth : 15 } pending_queue_size: 50 }, { channel: "/apollo/localization/pose" qos_profile: { depth : 15 } pending_queue_size: 50 } ] } } }
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/dag/planning_navi.dag
# Define all coms in DAG streaming. module_config { module_library : "/apollo/bazel-bin/modules/planning/libplanning_component.so" components { class_name : "PlanningComponent" config { name: "planning" config_file_path: "/apollo/modules/planning/conf/planning_config_navi.pb.txt" flag_file_path: "/apollo/modules/planning/conf/planning_navi.conf" readers: [ { channel: "/apollo/prediction" }, { channel: "/apollo/canbus/chassis" qos_profile: { depth : 15 } pending_queue_size: 50 }, { channel: "/apollo/localization/pose" qos_profile: { depth : 15 } pending_queue_size: 50 } ] } } }
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_path_decider.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides the implementation of the class "NaviPathDecider". */ #include "modules/planning/navi/decider/navi_path_decider.h" #include <algorithm> #include <utility> #include "cyber/common/log.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/vec2d.h" #include "modules/planning/common/planning_gflags.h" #include "modules/common_msgs/planning_msgs/sl_boundary.pb.h" namespace apollo { namespace planning { using apollo::common::Status; using apollo::common::math::Box2d; using apollo::common::math::Vec2d; NaviPathDecider::NaviPathDecider() : NaviTask("NaviPathDecider") { // TODO(all): Add your other initialization. } bool NaviPathDecider::Init(const PlanningConfig& config) { move_dest_lane_config_talbe_.clear(); max_speed_levels_.clear(); PlannerNaviConfig planner_navi_conf = config.navigation_planning_config().planner_navi_config(); config_ = planner_navi_conf.navi_path_decider_config(); auto move_dest_lane_config_talbe = config_.move_dest_lane_config_talbe(); for (const auto& item : move_dest_lane_config_talbe.lateral_shift()) { double max_speed_level = item.max_speed(); double max_move_dest_lane_shift_y = item.max_move_dest_lane_shift_y(); if (move_dest_lane_config_talbe_.find(max_speed_level) == move_dest_lane_config_talbe_.end()) { move_dest_lane_config_talbe_.emplace( std::make_pair(max_speed_level, max_move_dest_lane_shift_y)); max_speed_levels_.push_back(max_speed_level); } } AINFO << "Maximum speeds and move to dest lane config: "; for (const auto& data : move_dest_lane_config_talbe_) { auto max_speed = data.first; auto max_move_dest_lane_shift_y = data.second; AINFO << "[max_speed : " << max_speed << " ,max move dest lane shift y : " << max_move_dest_lane_shift_y << "]"; } max_keep_lane_distance_ = config_.max_keep_lane_distance(); max_keep_lane_shift_y_ = config_.max_keep_lane_shift_y(); min_keep_lane_offset_ = config_.min_keep_lane_offset(); keep_lane_shift_compensation_ = config_.keep_lane_shift_compensation(); start_plan_point_from_ = config_.start_plan_point_from(); move_dest_lane_compensation_ = config_.move_dest_lane_compensation(); is_init_ = obstacle_decider_.Init(config); return is_init_; } Status NaviPathDecider::Execute(Frame* frame, ReferenceLineInfo* const reference_line_info) { NaviTask::Execute(frame, reference_line_info); vehicle_state_ = frame->vehicle_state(); cur_reference_line_lane_id_ = reference_line_info->Lanes().Id(); auto ret = Process(reference_line_info->reference_line(), frame->PlanningStartPoint(), frame->obstacles(), reference_line_info->path_decision(), reference_line_info->mutable_path_data()); RecordDebugInfo(reference_line_info->path_data()); if (ret != Status::OK()) { reference_line_info->SetDrivable(false); AERROR << "Reference Line " << reference_line_info->Lanes().Id() << " is not drivable after " << Name(); } return ret; } apollo::common::Status NaviPathDecider::Process( const ReferenceLine& reference_line, const common::TrajectoryPoint& init_point, const std::vector<const Obstacle*>& obstacles, PathDecision* const path_decision, PathData* const path_data) { CHECK_NOTNULL(path_decision); CHECK_NOTNULL(path_data); start_plan_point_.set_x(vehicle_state_.x()); start_plan_point_.set_y(vehicle_state_.y()); start_plan_point_.set_theta(vehicle_state_.heading()); start_plan_v_ = vehicle_state_.linear_velocity(); start_plan_a_ = vehicle_state_.linear_acceleration(); if (start_plan_point_from_ == 1) { // start plan point from planning schedule start_plan_point_.set_x(init_point.path_point().x()); start_plan_point_.set_y(init_point.path_point().y()); start_plan_point_.set_theta(init_point.path_point().theta()); start_plan_v_ = init_point.v(); start_plan_a_ = init_point.a(); } // intercept path points from reference line std::vector<apollo::common::PathPoint> path_points; if (!GetBasicPathData(reference_line, &path_points)) { AERROR << "Get path points from reference line failed"; return Status(apollo::common::ErrorCode::PLANNING_ERROR, "NaviPathDecider GetBasicPathData"); } // according to the position of the start plan point and the reference line, // the path trajectory intercepted from the reference line is shifted on the // y-axis to adc. double dest_ref_line_y = path_points[0].y(); ADEBUG << "in current plan cycle, adc to ref line distance : " << dest_ref_line_y << "lane id : " << cur_reference_line_lane_id_; MoveToDestLane(dest_ref_line_y, &path_points); KeepLane(dest_ref_line_y, &path_points); path_data->SetReferenceLine(&(reference_line_info_->reference_line())); if (!path_data->SetDiscretizedPath(DiscretizedPath(std::move(path_points)))) { AERROR << "Set path data failed."; return Status(apollo::common::ErrorCode::PLANNING_ERROR, "NaviPathDecider SetDiscretizedPath"); } return Status::OK(); } void NaviPathDecider::MoveToDestLane( const double dest_ref_line_y, std::vector<common::PathPoint>* const path_points) { double dest_lateral_distance = std::fabs(dest_ref_line_y); if (dest_lateral_distance < max_keep_lane_distance_) { return; } // calculate lateral shift range and theta chage ratio double max_shift_y = CalculateDistanceToDestLane(); double actual_start_point_y = std::copysign(max_shift_y, dest_ref_line_y); // lateral shift path_points to the max_y double lateral_shift_value = -dest_ref_line_y + actual_start_point_y; // The steering wheel is more sensitive to the left than to the right and // requires a compensation value to the right lateral_shift_value = lateral_shift_value > 0.0 ? (lateral_shift_value - move_dest_lane_compensation_) : lateral_shift_value; ADEBUG << "in current plan cycle move to dest lane, adc shift to dest " "reference line : " << lateral_shift_value; std::transform(path_points->begin(), path_points->end(), path_points->begin(), [lateral_shift_value](common::PathPoint& old_path_point) { common::PathPoint new_path_point = old_path_point; double new_path_point_y = old_path_point.y() + lateral_shift_value; new_path_point.set_y(new_path_point_y); return new_path_point; }); } void NaviPathDecider::KeepLane( const double dest_ref_line_y, std::vector<common::PathPoint>* const path_points) { double dest_lateral_distance = std::fabs(dest_ref_line_y); if (dest_lateral_distance <= max_keep_lane_distance_) { auto& reference_line = reference_line_info_->reference_line(); auto obstacles = frame_->obstacles(); auto* path_decision = reference_line_info_->path_decision(); double actual_dest_point_y = NudgeProcess(reference_line, *path_points, obstacles, *path_decision, vehicle_state_); double actual_dest_lateral_distance = std::fabs(actual_dest_point_y); double actual_shift_y = 0.0; if (actual_dest_lateral_distance > min_keep_lane_offset_) { double lateral_shift_value = 0.0; lateral_shift_value = (actual_dest_lateral_distance < max_keep_lane_shift_y_ + min_keep_lane_offset_ - keep_lane_shift_compensation_) ? (actual_dest_lateral_distance - min_keep_lane_offset_ + keep_lane_shift_compensation_) : max_keep_lane_shift_y_; actual_shift_y = std::copysign(lateral_shift_value, actual_dest_point_y); } ADEBUG << "in current plan cycle keep lane, actual dest : " << actual_dest_point_y << " adc shift to dest : " << actual_shift_y; std::transform( path_points->begin(), path_points->end(), path_points->begin(), [actual_shift_y](common::PathPoint& old_path_point) { common::PathPoint new_path_point = old_path_point; double new_path_point_y = old_path_point.y() + actual_shift_y; new_path_point.set_y(new_path_point_y); return new_path_point; }); } } void NaviPathDecider::RecordDebugInfo(const PathData& path_data) { const auto& path_points = path_data.discretized_path(); auto* ptr_optimized_path = reference_line_info_->mutable_debug() ->mutable_planning_data() ->add_path(); ptr_optimized_path->set_name(Name()); ptr_optimized_path->mutable_path_point()->CopyFrom( {path_points.begin(), path_points.end()}); } bool NaviPathDecider::GetBasicPathData( const ReferenceLine& reference_line, std::vector<common::PathPoint>* const path_points) { CHECK_NOTNULL(path_points); double min_path_len = config_.min_path_length(); // get min path plan length s = v0 * t + 1 / 2.0 * a * t^2 double path_len = start_plan_v_ * config_.min_look_forward_time() + start_plan_a_ * pow(config_.min_look_forward_time(), 2) / 2.0; path_len = std::max(path_len, min_path_len); const double reference_line_len = reference_line.Length(); if (reference_line_len < path_len) { AERROR << "Reference line is too short to generate path trajectory( s = " << reference_line_len << ")."; return false; } // get the start plan point project s on reference line and get the length of // reference line auto start_plan_point_project = reference_line.GetReferencePoint( start_plan_point_.x(), start_plan_point_.y()); common::SLPoint sl_point; if (!reference_line.XYToSL(start_plan_point_project.ToPathPoint(0.0), &sl_point)) { AERROR << "Failed to get start plan point s from reference " "line."; return false; } auto start_plan_point_project_s = sl_point.has_s() ? sl_point.s() : 0.0; // get basic path points form reference_line ADEBUG << "Basic path data len ; " << reference_line_len; static constexpr double KDenseSampleUnit = 0.50; static constexpr double KSparseSmapleUnit = 2.0; for (double s = start_plan_point_project_s; s < reference_line_len; s += ((s < path_len) ? KDenseSampleUnit : KSparseSmapleUnit)) { const auto& ref_point = reference_line.GetReferencePoint(s); auto path_point = ref_point.ToPathPoint(s - start_plan_point_project_s); path_points->emplace_back(path_point); } if (path_points->empty()) { AERROR << "path poins is empty."; return false; } return true; } bool NaviPathDecider::IsSafeChangeLane(const ReferenceLine& reference_line, const PathDecision& path_decision) { const auto& adc_param = common::VehicleConfigHelper::GetConfig().vehicle_param(); Vec2d adc_position(start_plan_point_.x(), start_plan_point_.y()); Vec2d vec_to_center( (adc_param.front_edge_to_center() - adc_param.back_edge_to_center()) / 2.0, (adc_param.left_edge_to_center() - adc_param.right_edge_to_center()) / 2.0); Vec2d adc_center(adc_position + vec_to_center.rotate(start_plan_point_.theta())); Box2d adc_box(adc_center, start_plan_point_.theta(), adc_param.length(), adc_param.width()); SLBoundary adc_sl_boundary; if (!reference_line.GetSLBoundary(adc_box, &adc_sl_boundary)) { AERROR << "Failed to get ADC boundary from box: " << adc_box.DebugString(); return false; } for (const auto* obstacle : path_decision.obstacles().Items()) { const auto& sl_boundary = obstacle->PerceptionSLBoundary(); static constexpr double kLateralShift = 6.0; if (sl_boundary.start_l() < -kLateralShift || sl_boundary.end_l() > kLateralShift) { continue; } static constexpr double kSafeTime = 3.0; static constexpr double kForwardMinSafeDistance = 6.0; static constexpr double kBackwardMinSafeDistance = 8.0; const double kForwardSafeDistance = std::max( kForwardMinSafeDistance, ((vehicle_state_.linear_velocity() - obstacle->speed()) * kSafeTime)); const double kBackwardSafeDistance = std::max( kBackwardMinSafeDistance, ((obstacle->speed() - vehicle_state_.linear_velocity()) * kSafeTime)); if (sl_boundary.end_s() > adc_sl_boundary.start_s() - kBackwardSafeDistance && sl_boundary.start_s() < adc_sl_boundary.end_s() + kForwardSafeDistance) { return false; } } return true; } double NaviPathDecider::NudgeProcess( const ReferenceLine& reference_line, const std::vector<common::PathPoint>& path_data_points, const std::vector<const Obstacle*>& obstacles, const PathDecision& path_decision, const common::VehicleState& vehicle_state) { double nudge_position_y = 0.0; // get nudge latteral position int lane_obstacles_num = 0; static constexpr double KNudgeEpsilon = 1e-6; double nudge_distance = obstacle_decider_.GetNudgeDistance( obstacles, reference_line, path_decision, path_data_points, vehicle_state, &lane_obstacles_num); // adjust plan start point if (std::fabs(nudge_distance) > KNudgeEpsilon) { ADEBUG << "need latteral nudge distance : " << nudge_distance; nudge_position_y = nudge_distance; last_lane_id_to_nudge_flag_[cur_reference_line_lane_id_] = true; } else { // no nudge distance but current lane has obstacles ,keepping path in // the last nudge path direction bool last_plan_has_nudge = false; if (last_lane_id_to_nudge_flag_.find(cur_reference_line_lane_id_) != last_lane_id_to_nudge_flag_.end()) { last_plan_has_nudge = last_lane_id_to_nudge_flag_[cur_reference_line_lane_id_]; } if (last_plan_has_nudge && lane_obstacles_num != 0) { ADEBUG << "Keepping last nudge path direction"; nudge_position_y = vehicle_state_.y(); } else { // not need nudge or not need nudge keepping last_lane_id_to_nudge_flag_[cur_reference_line_lane_id_] = false; nudge_position_y = path_data_points[0].y(); } } return nudge_position_y; } double NaviPathDecider::CalculateDistanceToDestLane() { // match an appropriate lateral shift param from the configuration file // based on the current state of the vehicle state double move_distance = 0.0; double max_adc_speed = start_plan_v_ + start_plan_a_ * 1.0 / FLAGS_planning_loop_rate; auto max_speed_level_itr = std::upper_bound( max_speed_levels_.begin(), max_speed_levels_.end(), max_adc_speed); if (max_speed_level_itr != max_speed_levels_.end()) { auto max_speed_level = *max_speed_level_itr; move_distance = move_dest_lane_config_talbe_[max_speed_level]; } return move_distance; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_task.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <string> #include "modules/common/status/status.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/reference_line_info.h" namespace apollo { namespace planning { class NaviTask { public: explicit NaviTask(const std::string& name); virtual ~NaviTask() = default; virtual const std::string& Name() const; virtual apollo::common::Status Execute( Frame* frame, ReferenceLineInfo* reference_line_info); virtual bool Init(const PlanningConfig& config); protected: bool is_init_ = false; Frame* frame_ = nullptr; ReferenceLineInfo* reference_line_info_ = nullptr; private: const std::string name_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_task.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/navi/decider/navi_task.h" #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { using apollo::common::Status; NaviTask::NaviTask(const std::string& name) : name_(name) {} const std::string& NaviTask::Name() const { return name_; } bool NaviTask::Init(const PlanningConfig& config) { return true; } Status NaviTask::Execute(Frame* frame, ReferenceLineInfo* reference_line_info) { frame_ = frame; reference_line_info_ = reference_line_info; return Status::OK(); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_path_decider_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides several unit tests for the class "NaviPathDecider". */ #include "modules/planning/navi/decider/navi_path_decider.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "modules/common/util/point_factory.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/planning_gflags.h" using apollo::common::util::PointFactory; namespace apollo { namespace planning { class NaviPathDeciderTest : public ::testing::Test { public: static void SetUpTestCase() { AINFO << "NaviPathDeciderTest : SetUpTestCase"; } static void GeneratePathData( double s, double init_y, double kappa, std::vector<common::PathPoint>* const path_points) { for (double x = 0.0, y = init_y; x < s; ++x) { path_points->clear(); path_points->push_back( PointFactory::ToPathPoint(x, y, 0.0, 0.0, 0.0, kappa)); } } static void InitPlannigConfig(PlanningConfig* const plannig_config) { auto* navi_planner_config = plannig_config->mutable_navigation_planning_config() ->mutable_planner_navi_config(); auto* navi_path_decider_config = navi_planner_config->mutable_navi_path_decider_config(); navi_path_decider_config->set_min_path_length(5.0); navi_path_decider_config->set_min_look_forward_time(2.0); navi_path_decider_config->set_max_keep_lane_distance(0.4); navi_path_decider_config->set_max_keep_lane_shift_y(0.15); navi_path_decider_config->set_min_keep_lane_offset(0.20); navi_path_decider_config->set_keep_lane_shift_compensation(0.01); navi_path_decider_config->set_move_dest_lane_compensation(0.35); navi_path_decider_config->clear_move_dest_lane_config_talbe(); auto* move_dest_lane_cfg_table = navi_path_decider_config->mutable_move_dest_lane_config_talbe(); auto* move_shift_config = move_dest_lane_cfg_table->add_lateral_shift(); move_shift_config->set_max_speed(34); move_shift_config->set_max_move_dest_lane_shift_y(0.45); } }; TEST_F(NaviPathDeciderTest, Init) { NaviPathDecider navi_path_decider; PlanningConfig config; InitPlannigConfig(&config); EXPECT_TRUE(navi_path_decider.Init(config)); } TEST_F(NaviPathDeciderTest, Execute) {} TEST_F(NaviPathDeciderTest, MoveToDestLane) { NaviPathDecider navi_path_decider; PlanningConfig config; InitPlannigConfig(&config); navi_path_decider.Init(config); // generate path point static constexpr double kMaxS = 152.0; std::vector<common::PathPoint> path_points; // 1.std::fabs(target_path_init_y) < max_keep_lane_distance not need move to // dest lane GeneratePathData(kMaxS, 0.03, 0.03, &path_points); double dest_y = path_points[0].y(); double expect_y = path_points[0].y(); navi_path_decider.MoveToDestLane(dest_y, &path_points); EXPECT_DOUBLE_EQ(path_points[0].y(), expect_y); // 2.std::fabs(target_path_init_y) > max_keep_lane_distance need move to dest // lane 2.1 move to left, not need compensation navi_path_decider.start_plan_v_ = 10.0; navi_path_decider.start_plan_a_ = 1.0; GeneratePathData(kMaxS, 0.9, 0.03, &path_points); dest_y = path_points[0].y(); auto navi_path_decider_cfg = config.navigation_planning_config() .planner_navi_config() .navi_path_decider_config(); expect_y = navi_path_decider_cfg.move_dest_lane_config_talbe() .lateral_shift(0) .max_move_dest_lane_shift_y(); navi_path_decider.MoveToDestLane(dest_y, &path_points); EXPECT_DOUBLE_EQ(path_points[0].y(), expect_y); // 2.std::fabs(target_path_init_y) > max_keep_lane_distance need move to dest // lane 2.2 move to right, need compensation navi_path_decider.start_plan_v_ = 10.0; navi_path_decider.start_plan_a_ = 1.0; GeneratePathData(kMaxS, -0.9, 0.03, &path_points); dest_y = path_points[0].y(); expect_y = -navi_path_decider_cfg.move_dest_lane_config_talbe() .lateral_shift(0) .max_move_dest_lane_shift_y() - navi_path_decider_cfg.move_dest_lane_compensation(); navi_path_decider.MoveToDestLane(dest_y, &path_points); EXPECT_DOUBLE_EQ(path_points[0].y(), expect_y); } TEST_F(NaviPathDeciderTest, KeepLane) { NaviPathDecider navi_path_decider; PlanningConfig config; InitPlannigConfig(&config); navi_path_decider.Init(config); // generate path point static constexpr double kMaxS = 152.0; std::vector<common::PathPoint> path_points; // 1.std::fabs(target_path_init_y) > max_keep_lane_distance not need keep lane GeneratePathData(kMaxS, 0.90, 0.03, &path_points); double dest_y = path_points[0].y(); double expect_y = path_points[0].y(); navi_path_decider.KeepLane(dest_y, &path_points); EXPECT_DOUBLE_EQ(path_points[0].y(), expect_y); // 2. std::fabs(target_path_init_y)<= max_keep_lane_distance need keep lane // 2.1 std::fabs(target_path_init_y) < keep_lane_offset, not need adjust // reference points const common::TrajectoryPoint plan_start_point; const common::VehicleState vehicle_state; ReferenceLine ref_line; apollo::hdmap::RouteSegments route_segments; navi_path_decider.reference_line_info_ = new ReferenceLineInfo( vehicle_state, plan_start_point, ref_line, route_segments); LocalView local_view; navi_path_decider.frame_ = new Frame(1, local_view, plan_start_point, vehicle_state, nullptr); CHECK_NOTNULL(navi_path_decider.reference_line_info_); CHECK_NOTNULL(navi_path_decider.frame_); GeneratePathData(kMaxS, 0.19, 0.03, &path_points); dest_y = path_points[0].y(); expect_y = path_points[0].y(); navi_path_decider.KeepLane(dest_y, &path_points); EXPECT_DOUBLE_EQ(path_points[0].y(), expect_y); // 2.2 min_keep_lane_offset + max_keep_lane_shift_y - // keep_lane_shift_compensation > std::fabs(target_path_init_y) > // min_keep_lane_offset, need adjust reference points GeneratePathData(kMaxS, 0.29, 0.03, &path_points); dest_y = path_points[0].y(); auto navi_path_decider_cfg = config.navigation_planning_config() .planner_navi_config() .navi_path_decider_config(); expect_y = dest_y - navi_path_decider_cfg.min_keep_lane_offset() + navi_path_decider_cfg.keep_lane_shift_compensation() + dest_y; navi_path_decider.KeepLane(dest_y, &path_points); EXPECT_DOUBLE_EQ(path_points[0].y(), expect_y); // 2.2 min_keep_lane_offset + max_keep_lane_shift_y - // keep_lane_shift_compensation <= std::fabs(target_path_init_y) // min_keep_lane_offset, need adjust reference points GeneratePathData(kMaxS, 0.34, 0.03, &path_points); dest_y = path_points[0].y(); expect_y = path_points[0].y(); expect_y = navi_path_decider_cfg.max_keep_lane_shift_y() + dest_y; navi_path_decider.KeepLane(dest_y, &path_points); EXPECT_DOUBLE_EQ(path_points[0].y(), expect_y); delete navi_path_decider.reference_line_info_; navi_path_decider.reference_line_info_ = nullptr; delete navi_path_decider.frame_; navi_path_decider.frame_ = nullptr; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_obstacle_decider.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides the implementation of the class * "NaviObstacleDecider". */ #include "modules/planning/navi/decider/navi_obstacle_decider.h" #include <algorithm> #include <limits> #include <utility> #include "cyber/common/log.h" #include "modules/common/math/line_segment2d.h" #include "modules/common/math/linear_interpolation.h" #include "modules/common/math/path_matcher.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::PathPoint; using apollo::common::math::PathMatcher; using apollo::common::math::Vec2d; namespace { constexpr double kEpislon = 1e-6; } // namespace NaviObstacleDecider::NaviObstacleDecider() : NaviTask("NaviObstacleDecider") {} bool NaviObstacleDecider::Init(const PlanningConfig& config) { PlannerNaviConfig planner_navi_conf = config.navigation_planning_config().planner_navi_config(); config_ = planner_navi_conf.navi_obstacle_decider_config(); return true; } double NaviObstacleDecider::GetMinLaneWidth( const std::vector<common::PathPoint>& path_data_points, const ReferenceLine& reference_line) { double min_lane_width = std::numeric_limits<double>::max(); double lane_left_width = 0.0; double lane_right_width = 0.0; for (const auto& path_data_point : path_data_points) { bool ret = reference_line.GetLaneWidth(path_data_point.s(), &lane_left_width, &lane_right_width); if (ret) { double lane_width = lane_left_width + lane_right_width; if (lane_width < min_lane_width) { min_lane_width = lane_width; } } } return min_lane_width; } void NaviObstacleDecider::AddObstacleOffsetDirection( const common::PathPoint& projection_point, const std::vector<common::PathPoint>& path_data_points, const Obstacle* current_obstacle, const double proj_len, double* dist) { Vec2d p1(projection_point.x(), projection_point.y()); Vec2d p2(0.0, 0.0); if ((proj_len + 1) > path_data_points.back().s()) { p2.set_x(path_data_points.back().x()); p2.set_y(path_data_points.back().y()); } else { auto point = PathMatcher::MatchToPath(path_data_points, (proj_len + 1)); p2.set_x(point.x()); p2.set_y(point.y()); } auto d = ((current_obstacle->Perception().position().x() - p1.x()) * (p2.y() - p1.y())) - ((current_obstacle->Perception().position().y() - p1.y()) * (p2.x() - p1.x())); if (d > 0) { *dist = *dist * -1; } } bool NaviObstacleDecider::IsNeedFilterObstacle( const Obstacle* current_obstacle, const PathPoint& vehicle_projection_point, const std::vector<common::PathPoint>& path_data_points, const common::VehicleState& vehicle_state, PathPoint* projection_point_ptr) { bool is_filter = true; *projection_point_ptr = PathMatcher::MatchToPath( path_data_points, current_obstacle->Perception().position().x(), current_obstacle->Perception().position().y()); ADEBUG << "obstacle distance : " << projection_point_ptr->s() << "vehicle distance : " << vehicle_projection_point.s(); if ((projection_point_ptr->s() - vehicle_projection_point.s()) > (config_.judge_dis_coeff() * vehicle_state.linear_velocity() + config_.basis_dis_value())) { return is_filter; } double vehicle_frontedge_position = vehicle_projection_point.s() + VehicleParam().length(); double vehicle_backedge_position = vehicle_projection_point.s(); double obstacle_start_position = projection_point_ptr->s() - current_obstacle->Perception().length() / 2.0; double obstacle_end_position = projection_point_ptr->s() + current_obstacle->Perception().length() / 2.0; if ((vehicle_backedge_position - obstacle_end_position) > config_.safe_distance()) { return is_filter; } if ((obstacle_start_position - vehicle_frontedge_position) > config_.safe_distance()) { if (!current_obstacle->IsStatic()) { if (current_obstacle->Perception().velocity().x() > 0.0) { return is_filter; } } } is_filter = false; return is_filter; } void NaviObstacleDecider::ProcessObstacle( const std::vector<const Obstacle*>& obstacles, const std::vector<common::PathPoint>& path_data_points, const PathDecision& path_decision, const double min_lane_width, const common::VehicleState& vehicle_state) { auto func_distance = [](const PathPoint& point, const double x, const double y) { double dx = point.x() - x; double dy = point.y() - y; return sqrt(dx * dx + dy * dy); }; PathPoint projection_point; PathPoint vehicle_projection_point = PathMatcher::MatchToPath(path_data_points, 0, 0); for (const auto& current_obstacle : obstacles) { bool is_continue = IsNeedFilterObstacle( current_obstacle, vehicle_projection_point, path_data_points, vehicle_state, &projection_point); if (is_continue) { continue; } auto dist = func_distance(projection_point, current_obstacle->Perception().position().x(), current_obstacle->Perception().position().y()); if (dist < (config_.max_nudge_distance() + current_obstacle->Perception().width() + VehicleParam().left_edge_to_center())) { auto proj_len = projection_point.s(); if (std::fabs(proj_len) <= kEpislon || proj_len >= path_data_points.back().s()) { continue; } AddObstacleOffsetDirection(projection_point, path_data_points, current_obstacle, proj_len, &dist); obstacle_lat_dist_.emplace(std::pair<double, double>( current_obstacle->Perception().width(), dist)); } } } double NaviObstacleDecider::GetObstacleActualOffsetDistance( std::map<double, double>::iterator iter, const double right_nudge_lane, const double left_nudge_lane, int* lane_obstacles_num) { auto obs_width = iter->first; auto lat_dist = iter->second; ADEBUG << "get obstacle width : " << obs_width << "get latitude distance : " << lat_dist; auto actual_dist = std::fabs(lat_dist) - obs_width / 2.0 - VehicleParam().left_edge_to_center(); if (last_nudge_dist_ > 0) { if (lat_dist < 0) { if (actual_dist < std::fabs(right_nudge_lane) + config_.safe_distance()) { *lane_obstacles_num = *lane_obstacles_num + 1; } } } else if (last_nudge_dist_ < 0) { if (lat_dist > 0) { if (actual_dist < std::fabs(left_nudge_lane) + config_.safe_distance()) { *lane_obstacles_num = *lane_obstacles_num + 1; } } } if ((last_lane_obstacles_num_ != 0) && (*lane_obstacles_num == 0) && (!is_obstacle_stable_)) { is_obstacle_stable_ = true; statist_count_ = 0; ADEBUG << "begin keep obstacles"; } if (is_obstacle_stable_) { ++statist_count_; if (statist_count_ > config_.cycles_number()) { is_obstacle_stable_ = false; } else { *lane_obstacles_num = last_lane_obstacles_num_; } ADEBUG << "statist_count_ : " << statist_count_; } last_lane_obstacles_num_ = *lane_obstacles_num; ADEBUG << "last_nudge_dist : " << last_nudge_dist_ << "lat_dist : " << lat_dist << "actual_dist : " << actual_dist; return actual_dist; } void NaviObstacleDecider::RecordLastNudgeDistance(const double nudge_dist) { double tolerance = config_.nudge_allow_tolerance(); if (std::fabs(nudge_dist) > tolerance) { if (std::fabs(nudge_dist) > std::fabs(last_nudge_dist_)) { last_nudge_dist_ = nudge_dist; } no_nudge_num_ = 0; } else { ++no_nudge_num_; } if (no_nudge_num_ >= config_.cycles_number()) { last_nudge_dist_ = 0.0; } } void NaviObstacleDecider::SmoothNudgeDistance( const common::VehicleState& vehicle_state, double* nudge_dist) { CHECK_NOTNULL(nudge_dist); if (vehicle_state.linear_velocity() < config_.max_allow_nudge_speed()) { ++limit_speed_num_; } else { limit_speed_num_ = 0; } if (limit_speed_num_ < config_.cycles_number()) { *nudge_dist = 0; } if (std::fabs(*nudge_dist) > config_.nudge_allow_tolerance()) { ++eliminate_clutter_num_; } else { eliminate_clutter_num_ = 0; } if (eliminate_clutter_num_ < config_.cycles_number()) { *nudge_dist = 0; } ADEBUG << "eliminate_clutter_num_: " << eliminate_clutter_num_; } double NaviObstacleDecider::GetNudgeDistance( const std::vector<const Obstacle*>& obstacles, const ReferenceLine& reference_line, const PathDecision& path_decision, const std::vector<common::PathPoint>& path_data_points, const common::VehicleState& vehicle_state, int* lane_obstacles_num) { CHECK_NOTNULL(lane_obstacles_num); // Calculating the left and right nudgeable distance on the lane double left_nudge_lane = 0.0; double right_nudge_lane = 0.0; double routing_y = path_data_points[0].y(); double min_lane_width = GetMinLaneWidth(path_data_points, reference_line); ADEBUG << "get min_lane_width: " << min_lane_width; if (routing_y <= 0.0) { left_nudge_lane = min_lane_width / 2.0 - std::fabs(routing_y) - VehicleParam().left_edge_to_center(); right_nudge_lane = -1.0 * (min_lane_width / 2.0 + std::fabs(routing_y) - VehicleParam().right_edge_to_center()); } else { left_nudge_lane = min_lane_width / 2.0 + std::fabs(routing_y) - VehicleParam().left_edge_to_center(); right_nudge_lane = -1.0 * (min_lane_width / 2.0 - std::fabs(routing_y) - VehicleParam().right_edge_to_center()); } // Calculating the left and right nudgable distance according to the // position of the obstacle. double left_nudge_obstacle = 0.0; double right_nudge_obstacle = 0.0; // Calculation of the number of current Lane obstacles obstacle_lat_dist_.clear(); ProcessObstacle(obstacles, path_data_points, path_decision, min_lane_width, vehicle_state); for (auto iter = obstacle_lat_dist_.begin(); iter != obstacle_lat_dist_.end(); ++iter) { auto actual_dist = GetObstacleActualOffsetDistance( iter, right_nudge_lane, left_nudge_lane, lane_obstacles_num); auto lat_dist = iter->second; if (actual_dist > config_.min_nudge_distance() && actual_dist < config_.max_nudge_distance()) { auto need_nudge_dist = config_.max_nudge_distance() - actual_dist; if (lat_dist >= 0.0) { right_nudge_obstacle = -1.0 * std::max(std::fabs(right_nudge_obstacle), need_nudge_dist); } else { left_nudge_obstacle = std::max(std::fabs(left_nudge_obstacle), need_nudge_dist); } } } ADEBUG << "get left_nudge_lane: " << left_nudge_lane << "get right_nudge_lane : " << right_nudge_lane << "get left_nudge_obstacle: " << left_nudge_obstacle << "get right_nudge_obstacle : " << right_nudge_obstacle; // Get the appropriate value of the nudge distance double nudge_dist = 0.0; if (std::fabs(left_nudge_obstacle) > kEpislon && std::fabs(right_nudge_obstacle) <= kEpislon) { nudge_dist = std::min(left_nudge_lane, left_nudge_obstacle); } else if (std::fabs(right_nudge_obstacle) > kEpislon && std::fabs(left_nudge_obstacle) <= kEpislon) { nudge_dist = std::max(right_nudge_lane, right_nudge_obstacle); } ADEBUG << "get nudge distance : " << nudge_dist << "get lane_obstacles_num : " << *lane_obstacles_num; RecordLastNudgeDistance(nudge_dist); SmoothNudgeDistance(vehicle_state, &nudge_dist); KeepNudgePosition(nudge_dist, lane_obstacles_num); ADEBUG << "last nudge distance : " << nudge_dist; return nudge_dist; } void NaviObstacleDecider::KeepNudgePosition(const double nudge_dist, int* lane_obstacles_num) { if (std::fabs(nudge_dist) > config_.nudge_allow_tolerance() && std::fabs(last_nudge_dist_) < config_.nudge_allow_tolerance() && !keep_nudge_flag_) { cycles_count_ = 0; keep_nudge_flag_ = true; } if (keep_nudge_flag_) { ++cycles_count_; if (cycles_count_ > config_.max_keep_nudge_cycles()) { *lane_obstacles_num = 0; keep_nudge_flag_ = false; } else { *lane_obstacles_num = 1; } } ADEBUG << "get lane_obstacles_num : " << *lane_obstacles_num; } void NaviObstacleDecider::GetUnsafeObstaclesInfo( const std::vector<common::PathPoint>& path_data_points, const std::vector<const Obstacle*>& obstacles) { // Find start point of the reference line. double reference_line_y = path_data_points[0].y(); // Judging unsafed range according to the position of the reference line. double unsafe_refline_pos_y = 0.0; double unsafe_car_pos_y = 0.0; std::pair<double, double> unsafe_range; if (reference_line_y < 0.0) { unsafe_refline_pos_y = reference_line_y - VehicleParam().right_edge_to_center() - config_.speed_decider_detect_range(); unsafe_car_pos_y = VehicleParam().right_edge_to_center() + config_.speed_decider_detect_range(); unsafe_range = std::make_pair(unsafe_refline_pos_y, unsafe_car_pos_y); } else { unsafe_refline_pos_y = reference_line_y + VehicleParam().left_edge_to_center() + config_.speed_decider_detect_range(); unsafe_car_pos_y = -1.0 * (VehicleParam().left_edge_to_center() + config_.speed_decider_detect_range()); unsafe_range = std::make_pair(unsafe_car_pos_y, unsafe_refline_pos_y); } // Get obstacles'ID. unsafe_obstacle_info_.clear(); PathPoint vehicle_projection_point = PathMatcher::MatchToPath(path_data_points, 0, 0); for (const auto& iter : obstacles) { const double obstacle_y = iter->Perception().position().y(); if ((obstacle_y > unsafe_range.first && obstacle_y < unsafe_range.second) || std::abs(iter->Perception().velocity().y()) > config_.lateral_velocity_value()) { auto projection_point = PathMatcher::MatchToPath( path_data_points, iter->Perception().position().x(), obstacle_y); if (vehicle_projection_point.s() >= projection_point.s()) { continue; } auto front_distance = (projection_point.s() - iter->Perception().length() / 2.0) - vehicle_projection_point.s(); auto ref_theta = projection_point.theta(); auto project_velocity = iter->Perception().velocity().x() * std::cos(ref_theta) + iter->Perception().velocity().y() * std::sin(ref_theta); ADEBUG << "Lateral speed : " << iter->Perception().velocity().y(); unsafe_obstacle_info_.emplace_back(iter->Id(), front_distance, project_velocity); } } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_path_decider.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides the declaration of the class "NaviPathDecider". */ #pragma once #include <map> #include <string> #include <vector> #include "gflags/gflags.h" #include "gtest/gtest_prod.h" #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/status/status.h" #include "modules/planning/navi/decider/navi_obstacle_decider.h" #include "modules/planning/navi/decider/navi_task.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/proto/task_config.pb.h" #include "modules/planning/reference_line/reference_line.h" /** * @namespace apollo::planning * @brief apollo::planning */ namespace apollo { namespace planning { /** * @class NaviPathDecider * @brief NaviPathDecider is used to generate the local driving path of the .* vehicle in navigation mode. * Note that NaviPathDecider is only used in navigation mode (turn on navigation * mode by setting "FLAGS_use_navigation_mode" to "true") and do not use it in * standard mode. */ class NaviPathDecider : public NaviTask { public: NaviPathDecider(); virtual ~NaviPathDecider() = default; bool Init(const PlanningConfig &config) override; /** * @brief Overrided implementation of the virtual function "Execute" in the * base class "Task". * @param frame Current planning frame. * @param reference_line_info Currently available reference line information. * @return Status::OK() if a suitable path is created; error otherwise. */ apollo::common::Status Execute( Frame *frame, ReferenceLineInfo *reference_line_info) override; private: /** * @brief generate path information for trajectory plan in navigation mode. * @param reference_line the reference line. * @param init_point start planning point. * @param obstacles unhandled obstacle information. * @param path_decision path decision information provided by perception. * @param path_data output path plan information based on FLU coordinate * system * @return Status::OK() if a suitable path is created; error otherwise. */ apollo::common::Status Process(const ReferenceLine &reference_line, const common::TrajectoryPoint &init_point, const std::vector<const Obstacle *> &obstacles, PathDecision *const path_decision, PathData *const path_data); /** * @brief take a section of the reference line as the initial path trajectory. * @param reference_line input reference line. * @param path_points output points intercepted from the reference line * @return if success return true or return false. */ bool GetBasicPathData(const ReferenceLine &reference_line, std::vector<common::PathPoint> *const path_points); /** * @brief if adc is not on the dest lane, move to dest lane slowly. * @param the y of adc project point to dest lane reference line. * @param path point intercepted from the reference line */ void MoveToDestLane(const double dest_ref_line_y, std::vector<common::PathPoint> *const path_points); /** * @brief if adc is on the dest lane, keep lane. * @param the y of adc project point to dest lane reference line. * @param path point intercepted from the reference line */ void KeepLane(const double dest_ref_line_y, std::vector<common::PathPoint> *const path_points); void RecordDebugInfo(const PathData &path_data); /** * @brief check whether it is safe to change lanes * @param reference_line input change lane reference line * @param path_decision input all abstacles info * @return true if safe to change lane or return false. */ bool IsSafeChangeLane(const ReferenceLine &reference_line, const PathDecision &path_decision); /** * @brief calculate the lateral target position with slight avoidance * @path_data_points the basic path data intercepted from the reference line * @param reference_line input reference line * @param obstacles unhandled obstacle information. * @param path_decision path decision information provided by perception. * @vehicle_state adc status * @return the y coordinate value of nudging target position */ double NudgeProcess(const ReferenceLine &reference_line, const std::vector<common::PathPoint> &path_data_points, const std::vector<const Obstacle *> &obstacles, const PathDecision &path_decision, const common::VehicleState &vehicle_state); /** * @brief calculate latreal shift distance by vehicle state and config */ double CalculateDistanceToDestLane(); private: double max_keep_lane_distance_ = 0.0; double min_keep_lane_offset_ = 0.0; double max_keep_lane_shift_y_ = 0.0; double keep_lane_shift_compensation_ = 0.0; double move_dest_lane_compensation_ = 0.0; uint32_t start_plan_point_from_ = 0; std::map<double, double> move_dest_lane_config_talbe_; std::vector<double> max_speed_levels_; double start_plan_v_ = 0.0; double start_plan_a_ = 0.0; apollo::common::PathPoint start_plan_point_; std::string cur_reference_line_lane_id_; std::map<std::string, bool> last_lane_id_to_nudge_flag_; NaviObstacleDecider obstacle_decider_; common::VehicleState vehicle_state_; NaviPathDeciderConfig config_; FRIEND_TEST(NaviPathDeciderTest, MoveToDestLane); FRIEND_TEST(NaviPathDeciderTest, KeepLane); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_speed_ts_graph_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides several unit tests for the class * "NaviSpeedTsGraph". */ #include "modules/planning/navi/decider/navi_speed_ts_graph.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace apollo { namespace planning { using apollo::common::Status; TEST(NaviSpeedTsGraph, Solve1) { NaviSpeedTsGraph graph; graph.Reset(1.0, 100.0, 0.0, 0.0, 0.0); NaviSpeedTsConstraints constraints; constraints.v_max = 20.0; constraints.v_preffered = 10.0; constraints.a_max = 4.0; constraints.a_preffered = 2.0; constraints.b_max = 5.0; constraints.b_preffered = 2.0; graph.UpdateConstraints(constraints); std::vector<NaviSpeedTsPoint> points; EXPECT_EQ(Status::OK(), graph.Solve(&points)); EXPECT_NEAR(0.0, points.front().s, 0.1); EXPECT_NEAR(0.0, points.front().t, 0.1); EXPECT_NEAR(0.0, points.front().v, 0.1); EXPECT_NEAR(25.0, points[25].s, 0.1); EXPECT_NEAR(5.0, points[25].t, 0.1); EXPECT_NEAR(10.0, points[25].v, 0.1); for (const auto& point : points) if (point.s > 25.0) { EXPECT_NEAR(10.0, point.v, 0.1); } } TEST(NaviSpeedTsGraph, Solve2) { NaviSpeedTsGraph graph; graph.Reset(1.0, 100.0, 0.0, 0.0, 0.0); auto get_safe_distance = [](double v) { return 1.0 * v + 2.0; }; NaviSpeedTsConstraints constraints; constraints.v_max = 20.0; constraints.v_preffered = 10.0; constraints.a_max = 4.0; constraints.a_preffered = 2.0; constraints.b_max = 5.0; constraints.b_preffered = 2.0; graph.UpdateConstraints(constraints); graph.UpdateObstacleConstraints(40.0, get_safe_distance(0.0), 0.5, 0.0, 10.0); std::vector<NaviSpeedTsPoint> points; EXPECT_EQ(Status::OK(), graph.Solve(&points)); EXPECT_NEAR(0.0, points.front().s, 0.1); EXPECT_NEAR(0.0, points.front().t, 0.1); EXPECT_NEAR(0.0, points.front().v, 0.1); for (const auto& point : points) if (point.s > 38.0) { EXPECT_NEAR(0.0, point.v, 0.1); } EXPECT_NEAR(0.0, points.back().v, 0.1); } TEST(NaviSpeedTsGraph, Solve3) { NaviSpeedTsGraph graph; graph.Reset(1.0, 100.0, 5.0, 0.0, 0.0); auto get_safe_distance = [](double v) { return 1.0 * v + 2.0; }; NaviSpeedTsConstraints constraints; constraints.v_max = 20.0; constraints.v_preffered = 10.0; constraints.a_max = 4.0; constraints.a_preffered = 2.0; constraints.b_max = 5.0; constraints.b_preffered = 2.0; graph.UpdateConstraints(constraints); graph.UpdateObstacleConstraints(10.0, get_safe_distance(5.0), 0.5, 5.0, 10.0); std::vector<NaviSpeedTsPoint> points; EXPECT_EQ(Status::OK(), graph.Solve(&points)); EXPECT_NEAR(0.0, points.front().s, 0.1); EXPECT_NEAR(0.0, points.front().t, 0.1); EXPECT_NEAR(5.0, points.front().v, 0.1); for (const auto& point : points) { if (point.s > 15.0) { auto obstacle_distance = 5.0 * point.t + 10.0; EXPECT_GE(obstacle_distance, point.s); EXPECT_NEAR(5.0, point.v, 0.1); } } } TEST(NaviSpeedTsGraph, ErrorTest) {} } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_speed_decider.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides the declaration of the class "NaviSpeedDecider". */ #pragma once #include <string> #include <vector> #include "gtest/gtest.h" #include "modules/common/status/status.h" #include "modules/planning/common/speed/speed_data.h" #include "modules/planning/navi/decider/navi_obstacle_decider.h" #include "modules/planning/navi/decider/navi_speed_ts_graph.h" #include "modules/planning/navi/decider/navi_task.h" #include "modules/planning/proto/planning_config.pb.h" /** * @namespace apollo::planning * @brief apollo::planning */ namespace apollo { namespace planning { /** * @class NaviSpeedDecider * @brief NaviSpeedDecider is used to generate an appropriate speed curve * of the vehicle in navigation mode. * Note that NaviSpeedDecider is only used in navigation mode (turn on * navigation mode by setting "FLAGS_use_navigation_mode" to "true") and do not * use it in standard mode. */ class NaviSpeedDecider : public NaviTask { public: NaviSpeedDecider(); virtual ~NaviSpeedDecider() = default; bool Init(const PlanningConfig& config) override; /** * @brief Overrided implementation of the virtual function "Execute" in the * base class "Task". * @param frame Current planning frame. * @param reference_line_info Currently available reference line information. * @return Status::OK() if a suitable path is created; error otherwise. */ apollo::common::Status Execute( Frame* frame, ReferenceLineInfo* reference_line_info) override; private: /** * @brief Create speed-data. * @param start_v V of planning start point. * @param start_a A of planning start point. * @param start_da Da of planning start point. * @param path_points Current path data. * @param obstacles Current obstacles. * @param find_obstacle Find obstacle from id. * @param speed_data Output. * @return Status::OK() if a suitable speed-data is created; error otherwise. */ apollo::common::Status MakeSpeedDecision( double start_v, double start_a, double start_da, const std::vector<common::PathPoint>& path_points, const std::vector<const Obstacle*>& obstacles, const std::function<const Obstacle*(const std::string& id)>& find_obstacle, SpeedData* const speed_data); /** * @brief Add t-s constraints base on range of perception. * @return Status::OK() if success; error otherwise. */ apollo::common::Status AddPerceptionRangeConstraints(); /** * @brief Add t-s constraints base on obstacles. * @param vehicle_speed Current speed of vehicle. * @param path_length The length of path, just as an obstacle. * @param path_points Current path data. * @param obstacles Current obstacles. * @param find_obstacle Find obstacle from id. * @return Status::OK() if success; error otherwise. */ apollo::common::Status AddObstaclesConstraints( double vehicle_speed, double path_length, const std::vector<common::PathPoint>& path_points, const std::vector<const Obstacle*>& obstacles, const std::function<const Obstacle*(const std::string& id)>& find_obstacle); /** * @brief Add t-s constraints base on traffic decision. * @return Status::OK() if success; error otherwise. */ apollo::common::Status AddTrafficDecisionConstraints(); /** * @brief Add t-s constraints base on centric acceleration. * @param path_points Current path data. * @return Status::OK() if success; error otherwise. */ apollo::common::Status AddCentricAccelerationConstraints( const std::vector<common::PathPoint>& path_points); /** * @brief Add t-s constraints base on configs, which has max-speed etc. * @return Status::OK() if success; error otherwise. */ apollo::common::Status AddConfiguredConstraints(); void RecordDebugInfo(const SpeedData& speed_data); private: double preferred_speed_; double max_speed_; double preferred_accel_; double preferred_decel_; double preferred_jerk_; double max_accel_; double max_decel_; double obstacle_buffer_; double safe_distance_base_; double safe_distance_ratio_; double following_accel_ratio_; double soft_centric_accel_limit_; double hard_centric_accel_limit_; double hard_speed_limit_; double hard_accel_limit_; bool enable_safe_path_; bool enable_planning_start_point_; bool enable_accel_auto_compensation_; double kappa_preview_; double kappa_threshold_; NaviObstacleDecider obstacle_decider_; NaviSpeedTsGraph ts_graph_; double prev_v_ = 0.0; double accel_compensation_ratio_ = 1.0; double decel_compensation_ratio_ = 1.0; FRIEND_TEST(NaviSpeedDeciderTest, CreateSpeedData); FRIEND_TEST(NaviSpeedDeciderTest, CreateSpeedDataForStaticObstacle); FRIEND_TEST(NaviSpeedDeciderTest, CreateSpeedDataForObstacles); FRIEND_TEST(NaviSpeedDeciderTest, CreateSpeedDataForCurve); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_speed_ts_graph.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides the declaration of the class "NaviSpeedTsGraph". */ #pragma once #include <limits> #include <vector> #include "modules/common/status/status.h" /** * @namespace apollo::planning * @brief apollo::planning */ namespace apollo { namespace planning { /** * @struct NaviSpeedTsConstraints * @brief NaviSpeedTsConstraints is used to describe constraints of a t-s point. */ struct NaviSpeedTsConstraints { // The minimum timestamp of the point. double t_min = 0.0; // The maximum speed of the point. double v_max = std::numeric_limits<double>::max(); // The preferred speed of the point. double v_preffered = std::numeric_limits<double>::max(); // The maximum acceleration of the point. double a_max = std::numeric_limits<double>::max(); // The preferred acceleration of the point. double a_preffered = std::numeric_limits<double>::max(); // The maximum deceleration of the point. double b_max = std::numeric_limits<double>::max(); // The preferred deceleration of the point. double b_preffered = std::numeric_limits<double>::max(); // TODO(all): ignore double da_max = std::numeric_limits<double>::max(); // TODO(all): ignore double da_preffered = std::numeric_limits<double>::max(); }; /** * @struct NaviSpeedTsPoint * @brief NaviSpeedTsPoint is used to describe a t-s point. */ struct NaviSpeedTsPoint { double s; double t; double v; double a; double da; }; /** * @class NaviSpeedTsGraph * @brief NaviSpeedTsGraph is used to generate a t-s graph with some limits * and preferred. */ class NaviSpeedTsGraph { public: NaviSpeedTsGraph(); /** * @brief Reset points's num and time step etc. * @param s_step S step between two points. * @param s_max Max of s-axis. * @param start_v V of the start point. * @param start_a A of the start point. * @param start_da Da of the start point. */ void Reset(double s_step, double s_max, double start_v, double start_a, double start_da); /** * @brief Assign constraints to all points. * @param constraints constraints for all points. */ void UpdateConstraints(const NaviSpeedTsConstraints& constraints); /** * @brief Assign constraints to a range. * @param start_s S fo the start point. * @param end_s S fo the end point. * @param constraints constraints for points. */ void UpdateRangeConstraints(double start_s, double end_s, const NaviSpeedTsConstraints& constraints); /** * @brief Assign constraints for an obstacle. * @param distance The distance from vehicle to the obstacle. * @param safe_distance The safe distance from vehicle to the obstacle. * @param following_accel_ratio Decide the level of acceleration when * following obstacle. * @param v Speed of the obstacle. * @param cruise_speed Cruise speed of vehicle. * @param constraints constraints for the point. */ void UpdateObstacleConstraints(double distance, double safe_distance, double following_accel_ratio, double v, double cruise_speed); /** * @brief Solving the t-s curve. * @param points buffer of t-s points for output. * @return Status::OK() if success; error otherwise. */ apollo::common::Status Solve(std::vector<NaviSpeedTsPoint>* points); private: std::vector<NaviSpeedTsConstraints> constraints_; double s_step_; double start_v_; double start_a_; double start_da_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_obstacle_decider_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides several unit tests for the class * "NaviObstacleDecider". */ #include "modules/planning/navi/decider/navi_obstacle_decider.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "modules/common/util/point_factory.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/common_msgs/perception_msgs/perception_obstacle.pb.h" #include "modules/planning/common/planning_gflags.h" #include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h" using apollo::common::util::PointFactory; using apollo::perception::PerceptionObstacle; using apollo::prediction::ObstaclePriority; namespace apollo { namespace planning { TEST(NaviObstacleDeciderTest, ComputeNudgeDist1) { NaviObstacleDecider obstacle_decider; std::vector<const Obstacle*> vec_obstacle; std::vector<common::PathPoint> vec_points; PerceptionObstacle perception_obstacle; PathDecision path_decision; SLBoundary obstacle_boundary; ReferenceLine reference_line; common::VehicleState vehicle_state; perception_obstacle.set_width(1.0); perception_obstacle.set_length(1.0); perception_obstacle.mutable_position()->set_x(2.0); perception_obstacle.mutable_position()->set_y(1.0); Obstacle b1("1", perception_obstacle, ObstaclePriority::NORMAL, false); vec_points.push_back(PointFactory::ToPathPoint(0.0, 0.0)); vec_points.push_back(PointFactory::ToPathPoint(0.0, 3.0, 0.0, 3.0)); vec_obstacle.emplace_back(&b1); obstacle_boundary.set_start_l(1.5); b1.SetPerceptionSlBoundary(obstacle_boundary); path_decision.AddObstacle(b1); vehicle_state.set_linear_velocity(5.556); int lane_obstacles_num = 0; obstacle_decider.SetLastNudgeDistance(2); double nudge_dist; for (int i = 0; i < 6; i++) { lane_obstacles_num = 0; nudge_dist = obstacle_decider.GetNudgeDistance( vec_obstacle, reference_line, path_decision, vec_points, vehicle_state, &lane_obstacles_num); } EXPECT_FLOAT_EQ(nudge_dist, 0.755); EXPECT_FLOAT_EQ(lane_obstacles_num, 1); } TEST(NaviObstacleDeciderTest, ComputeNudgeDist2) { NaviObstacleDecider obstacle_decider; std::vector<const Obstacle*> vec_obstacle; std::vector<common::PathPoint> vec_points; PerceptionObstacle perception_obstacle; PathDecision path_decision; SLBoundary obstacle_boundary; ReferenceLine reference_line; common::VehicleState vehicle_state; perception_obstacle.set_width(1.0); perception_obstacle.set_length(1.0); perception_obstacle.mutable_position()->set_x(-2.0); perception_obstacle.mutable_position()->set_y(1.0); Obstacle b1("1", perception_obstacle, ObstaclePriority::NORMAL, false); b1.SetPerceptionSlBoundary(obstacle_boundary); path_decision.AddObstacle(b1); vec_points.push_back(PointFactory::ToPathPoint(0.0, 0.0)); vec_points.push_back(PointFactory::ToPathPoint(0.0, 3.0, 0.0, 3.0)); vec_obstacle.emplace_back(&b1); vehicle_state.set_linear_velocity(5.556); int lane_obstacles_num = 0; obstacle_decider.SetLastNudgeDistance(-2); double nudge_dist; for (int i = 0; i < 6; i++) { lane_obstacles_num = 0; nudge_dist = obstacle_decider.GetNudgeDistance( vec_obstacle, reference_line, path_decision, vec_points, vehicle_state, &lane_obstacles_num); } EXPECT_FLOAT_EQ(nudge_dist, -0.755); EXPECT_FLOAT_EQ(lane_obstacles_num, 1); } TEST(NaviObstacleDeciderTest, ComputeNudgeDist3) { NaviObstacleDecider obstacle_decider; std::vector<const Obstacle*> vec_obstacle; std::vector<common::PathPoint> vec_points; PerceptionObstacle perception_obstacle; PathDecision path_decision; SLBoundary obstacle_boundary; ReferenceLine reference_line; common::VehicleState vehicle_state; // obstacle 1 perception_obstacle.set_width(1.0); perception_obstacle.set_length(1.0); perception_obstacle.mutable_position()->set_x(3.0); perception_obstacle.mutable_position()->set_y(0.0); Obstacle b1("1", perception_obstacle, ObstaclePriority::NORMAL, false); obstacle_boundary.set_start_l(1.6); b1.SetPerceptionSlBoundary(obstacle_boundary); path_decision.AddObstacle(b1); // obstacle 2 perception_obstacle.set_width(2.6); perception_obstacle.set_length(1.0); perception_obstacle.mutable_position()->set_x(4.0); perception_obstacle.mutable_position()->set_y(0.0); Obstacle b2("2", perception_obstacle, ObstaclePriority::NORMAL, false); obstacle_boundary.set_start_l(1.5); b2.SetPerceptionSlBoundary(obstacle_boundary); path_decision.AddObstacle(b2); const double s1 = 0; const double s2 = s1 + std::sqrt(1.0 + 1.0); const double s3 = s2 + std::sqrt(1.0 + 1.0); const double s4 = s3 + std::sqrt(1.0 + 1.0); const double s5 = s4 + std::sqrt(1.0 + 1.0); vec_points.push_back(PointFactory::ToPathPoint(0.0, 0.0, 0.0, s1)); vec_points.push_back(PointFactory::ToPathPoint(1.0, 1.0, 0.0, s2)); vec_points.push_back(PointFactory::ToPathPoint(2.0, 2.0, 0.0, s3)); vec_points.push_back(PointFactory::ToPathPoint(3.0, 3.0, 0.0, s4)); vec_points.push_back(PointFactory::ToPathPoint(4.0, 4.0, 0.0, s5)); vec_obstacle.emplace_back(&b1); vec_obstacle.emplace_back(&b2); vehicle_state.set_linear_velocity(5.556); int lane_obstacles_num = 0; obstacle_decider.SetLastNudgeDistance(2); double nudge_dist; for (int i = 0; i < 6; i++) { lane_obstacles_num = 0; nudge_dist = obstacle_decider.GetNudgeDistance( vec_obstacle, reference_line, path_decision, vec_points, vehicle_state, &lane_obstacles_num); } EXPECT_FLOAT_EQ(nudge_dist, 0.72657289); EXPECT_FLOAT_EQ(lane_obstacles_num, 2); } TEST(NaviObstacleDeciderTest, ComputeNudgeDist4) { NaviObstacleDecider obstacle_decider; std::vector<const Obstacle*> vec_obstacle; std::vector<common::PathPoint> vec_points; PerceptionObstacle perception_obstacle; PathDecision path_decision; SLBoundary obstacle_boundary; ReferenceLine reference_line; common::VehicleState vehicle_state; perception_obstacle.set_width(1.0); perception_obstacle.set_length(1.0); perception_obstacle.mutable_position()->set_x(-3.0); perception_obstacle.mutable_position()->set_y(1.0); Obstacle b1("1", perception_obstacle, ObstaclePriority::NORMAL, false); b1.SetPerceptionSlBoundary(obstacle_boundary); path_decision.AddObstacle(b1); vec_points.push_back(PointFactory::ToPathPoint(0.0, 0.0)); vec_points.push_back(PointFactory::ToPathPoint(0.0, 3.0, 0.0, 3.0)); vec_obstacle.emplace_back(&b1); vehicle_state.set_linear_velocity(20); int lane_obstacles_num = 0; double nudge_dist; for (int i = 0; i < 6; i++) { lane_obstacles_num = 0; nudge_dist = obstacle_decider.GetNudgeDistance( vec_obstacle, reference_line, path_decision, vec_points, vehicle_state, &lane_obstacles_num); } EXPECT_FLOAT_EQ(nudge_dist, 0); EXPECT_FLOAT_EQ(lane_obstacles_num, 0); } TEST(NaviObstacleDeciderTest, GetUnsafeObstaclesID) { NaviObstacleDecider obstacle_decider; std::vector<const Obstacle*> vec_obstacle; std::vector<common::PathPoint> vec_points; PerceptionObstacle perception_obstacle; // obstacle 1 perception_obstacle.set_width(1.0); perception_obstacle.set_length(1.0); perception_obstacle.mutable_position()->set_x(2.0); perception_obstacle.mutable_position()->set_y(3.0); perception_obstacle.mutable_velocity()->set_x(10.0); perception_obstacle.mutable_velocity()->set_y(0.0); Obstacle b1("5", perception_obstacle, ObstaclePriority::NORMAL, false); // obstacle 2 perception_obstacle.set_width(2.6); perception_obstacle.set_length(1.0); perception_obstacle.mutable_position()->set_x(1.0); perception_obstacle.mutable_position()->set_y(-1.0); perception_obstacle.mutable_velocity()->set_x(5.0); perception_obstacle.mutable_velocity()->set_y(0.0); Obstacle b2("6", perception_obstacle, ObstaclePriority::NORMAL, false); const double s1 = 0.0; const double s2 = s1 + 1.0; const double s3 = s2 + 1.0; const double s4 = s3 + 1.0; const double s5 = s4 + 1.0; vec_points.push_back(PointFactory::ToPathPoint(0.0, 2.0, 0.0, s1)); vec_points.push_back(PointFactory::ToPathPoint(1.0, 2.0, 0.0, s2)); vec_points.push_back(PointFactory::ToPathPoint(2.0, 2.0, 0.0, s3)); vec_points.push_back(PointFactory::ToPathPoint(3.0, 2.0, 0.0, s4)); vec_points.push_back(PointFactory::ToPathPoint(4.0, 2.0, 0.0, s5)); vec_obstacle.emplace_back(&b1); vec_obstacle.emplace_back(&b2); std::vector<std::tuple<std::string, double, double>> unsafe_obstacle_info; obstacle_decider.GetUnsafeObstaclesInfo(vec_points, vec_obstacle); unsafe_obstacle_info = obstacle_decider.UnsafeObstacles(); EXPECT_EQ(std::get<0>(unsafe_obstacle_info[0]), "5"); EXPECT_EQ(std::get<0>(unsafe_obstacle_info[1]), "6"); EXPECT_EQ(std::get<1>(unsafe_obstacle_info[0]), 1.5); EXPECT_EQ(std::get<1>(unsafe_obstacle_info[1]), 0.5); EXPECT_EQ(std::get<2>(unsafe_obstacle_info[0]), 10); EXPECT_EQ(std::get<2>(unsafe_obstacle_info[1]), 5); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_speed_ts_graph.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides the implementation of the class "NaviSpeedTsGraph". */ #include "modules/planning/navi/decider/navi_speed_ts_graph.h" #include <algorithm> #include "cyber/common/log.h" #include "modules/common/math/math_utils.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::math::Clamp; namespace { constexpr double kDoubleEpsilon = 1.0e-6; constexpr double kDefaultSStep = 1.0; constexpr double kDefaultSMax = 2.0; constexpr double kDefaultSafeDistanceRatio = 1.0; constexpr double kDefaultSafeDistanceBase = 2.0; constexpr double kSafeDistanceSmooth = 3.0; constexpr double kFollowSpeedSmooth = 0.25; constexpr double kInfinityValue = 1.0e8; } // namespace static void CheckConstraints(const NaviSpeedTsConstraints& constraints) { CHECK_GE(constraints.t_min, 0.0); CHECK_GE(constraints.v_max, 0.0); CHECK_GE(constraints.v_max, constraints.v_preffered); CHECK_GE(constraints.a_max, 0.0); CHECK_GE(constraints.a_max, constraints.a_preffered); CHECK_GE(constraints.b_max, 0.0); CHECK_GE(constraints.b_max, constraints.b_preffered); CHECK_GE(constraints.da_max, 0.0); CHECK_GE(constraints.da_max, constraints.da_preffered); } static void CombineConstraints(const NaviSpeedTsConstraints& constraints, NaviSpeedTsConstraints* dst) { dst->t_min = std::max(constraints.t_min, dst->t_min); dst->v_max = std::min(constraints.v_max, dst->v_max); dst->v_preffered = std::min(constraints.v_preffered, dst->v_preffered); dst->a_max = std::min(constraints.a_max, dst->a_max); dst->a_preffered = std::min(constraints.a_preffered, dst->a_preffered); dst->b_max = std::min(constraints.b_max, dst->b_max); dst->b_preffered = std::min(constraints.b_preffered, dst->b_preffered); dst->da_max = std::min(constraints.da_max, dst->da_max); dst->da_preffered = std::min(constraints.da_preffered, dst->da_preffered); } NaviSpeedTsGraph::NaviSpeedTsGraph() { Reset(kDefaultSStep, kDefaultSMax, 0.0, 0.0, 0.0); } void NaviSpeedTsGraph::Reset(double s_step, double s_max, double start_v, double start_a, double start_da) { CHECK_GT(s_step, 0.0); CHECK_GE(s_max, s_step); CHECK_GE(start_v, 0.0); s_step_ = s_step; start_v_ = start_v; start_a_ = start_a; start_da_ = start_da; auto point_num = (size_t)((s_max + s_step_) / s_step_); constraints_.clear(); constraints_.resize(point_num); } void NaviSpeedTsGraph::UpdateConstraints( const NaviSpeedTsConstraints& constraints) { CheckConstraints(constraints); for (auto& pc : constraints_) { CombineConstraints(constraints, &pc); } } void NaviSpeedTsGraph::UpdateRangeConstraints( double start_s, double end_s, const NaviSpeedTsConstraints& constraints) { CHECK_GE(start_s, 0.0); CHECK_GE(end_s, start_s); CheckConstraints(constraints); auto start_idx = (size_t)(std::floor(start_s / s_step_)); auto end_idx = (size_t)(std::ceil(end_s / s_step_)); if (start_idx == end_idx) { CombineConstraints(constraints, &constraints_[start_idx]); } else { for (size_t i = start_idx; i < end_idx && i < constraints_.size(); i++) CombineConstraints(constraints, &constraints_[i]); } } void NaviSpeedTsGraph::UpdateObstacleConstraints(double distance, double safe_distance, double following_accel_ratio, double v, double cruise_speed) { CHECK_GE(distance, 0.0); CHECK_GE(safe_distance, 0.0); CHECK_GT(following_accel_ratio, 0.0); // smooth obstacle following if (distance > safe_distance && distance - safe_distance < kSafeDistanceSmooth && std::abs(v - start_v_) < kFollowSpeedSmooth) { distance = safe_distance; v = start_v_; } // TODO(all): if v < 0 v = std::max(v, 0.0); // update t_min double s = 0.0; for (auto& pc : constraints_) { auto t = (s - distance) / v; if (t >= 0.0) { NaviSpeedTsConstraints constraints; constraints.t_min = t; CombineConstraints(constraints, &pc); } s += s_step_; } // update v_preffered auto od = distance - safe_distance; auto v0 = start_v_; auto v1 = v; auto r0 = (distance - safe_distance) / (distance + safe_distance); auto vm = std::max(cruise_speed * r0, 0.0) + (1.0 + following_accel_ratio * r0) * v1; auto ra = (v1 - vm) * (v1 - vm) * (v1 + v0 - 2.0 * vm) / (od * od); auto rb = (v1 - vm) * (v1 + 2.0 * v0 - 3.0 * vm) / od; auto rc = v0; auto t1 = -1.0 * od / (v1 - vm); auto s1 = ra * t1 * t1 * t1 + rb * t1 * t1 + rc * t1; double t; double prev_v; bool first = true; for (auto& pc : constraints_) { NaviSpeedTsConstraints constraints; if (first) { first = false; auto cur_v = rc; t = 0.0; s = 0.0; prev_v = cur_v; constraints.v_preffered = cur_v; } else if (s <= s1 && t <= t1) { auto a = 6.0 * ra * t + 2.0 * rb; t += (std::sqrt(prev_v * prev_v + 2.0 * a * s_step_) - prev_v) / a; auto cur_v = 3.0 * ra * t * t + 2.0 * rb * t + rc; s += s_step_; prev_v = cur_v; constraints.v_preffered = std::max(cur_v, 0.0); } else { auto cur_v = v; t += 2.0 * s_step_ / (prev_v + cur_v); s += s_step_; prev_v = cur_v; constraints.v_preffered = cur_v; } CombineConstraints(constraints, &pc); } } Status NaviSpeedTsGraph::Solve(std::vector<NaviSpeedTsPoint>* output) { CHECK_NOTNULL(output); // make constraints of the first point auto& constraints = constraints_[0]; constraints.v_max = start_v_; constraints.v_preffered = start_v_; constraints.a_max = start_a_; constraints.a_preffered = start_a_; constraints.da_max = start_da_; constraints.da_preffered = start_da_; // preprocess v_max base on b_max for (ssize_t i = constraints_.size() - 2; i >= 0; i--) { const auto& next = constraints_[i + 1]; auto& cur = constraints_[i]; cur.v_max = std::min(std::sqrt(next.v_max * next.v_max + 2 * next.b_max * s_step_), cur.v_max); cur.v_preffered = std::min(cur.v_max, cur.v_preffered); } // preprocess v_max base on a_max for (size_t i = 1; i < constraints_.size(); i++) { const auto& prev = constraints_[i - 1]; auto& cur = constraints_[i]; cur.v_max = std::min(std::sqrt(prev.v_max * prev.v_max + 2 * cur.a_max * s_step_), cur.v_max); cur.v_preffered = std::min(cur.v_max, cur.v_preffered); } // preprocess v_preffered base on b_preffered for (ssize_t i = constraints_.size() - 2; i >= 0; i--) { const auto& next = constraints_[i + 1]; auto& cur = constraints_[i]; cur.v_preffered = std::min(std::sqrt(next.v_preffered * next.v_preffered + 2 * next.b_preffered * s_step_), cur.v_preffered); } // preprocess v_preffered base on a_preffered for (size_t i = 1; i < constraints_.size(); i++) { const auto& prev = constraints_[i - 1]; auto& cur = constraints_[i]; cur.v_preffered = std::min(std::sqrt(prev.v_preffered * prev.v_preffered + 2 * cur.a_preffered * s_step_), cur.v_preffered); } auto& points = *output; points.resize(constraints_.size()); // compute the first point auto& point = points[0]; point.s = 0.0; point.t = 0.0; point.v = start_v_; point.a = start_a_; point.da = start_da_; // compute the remaining points for (size_t i = 1; i < points.size(); i++) { const auto& prev = points[i - 1]; const auto& constraints = constraints_[i]; auto& cur = points[i]; // compute t_min base on v_max auto t_min = std::max(prev.t, constraints.t_min); auto v_max = constraints.v_max; t_min = std::max(prev.t + 2.0 * s_step_ / (prev.v + v_max), t_min); // compute t_max base on b_max auto t_max = std::numeric_limits<double>::infinity(); auto b_max = constraints.b_max; auto r0 = prev.v * prev.v - 2 * b_max * s_step_; if (r0 > 0.0) { t_max = prev.t + (prev.v - std::sqrt(r0)) / b_max; } // if t_max < t_min if (t_max < t_min) { AERROR << "failure to satisfy the constraints."; return Status(ErrorCode::PLANNING_ERROR, "failure to satisfy the constraints."); } // compute t_preffered base on v_preffered auto v_preffered = constraints.v_preffered; auto t_preffered = prev.t + 2 * s_step_ / (prev.v + v_preffered); cur.s = prev.s + s_step_; cur.t = Clamp(t_preffered, t_min, t_max); auto dt = cur.t - prev.t; cur.v = std::max(2.0 * s_step_ / dt - prev.v, 0.0); // if t is infinity if (std::isinf(cur.t)) { points.resize(i + 1); break; } } for (size_t i = 1; i < points.size() - 1; i++) { const auto& prev = points[i - 1]; const auto& next = points[i + 1]; auto& cur = points[i]; auto ds = next.s - prev.s; auto dt = next.t - prev.t; cur.v = ds / dt; } auto& first = points[0]; const auto& second = points[1]; first.a = (second.v - first.v) / (2.0 * (second.t - first.t)); for (size_t i = 1; i < points.size() - 1; i++) { const auto& prev = points[i - 1]; const auto& next = points[i + 1]; auto& cur = points[i]; auto dv = next.v - prev.v; auto dt = next.t - prev.t; cur.a = dv / dt; } for (size_t i = 1; i < points.size() - 1; i++) { const auto& prev = points[i - 1]; const auto& next = points[i + 1]; auto& cur = points[i]; auto da = next.a - prev.a; auto dt = next.t - prev.t; cur.da = da / dt; } for (size_t i = 0; i < points.size(); i++) { auto& point = points[i]; point.s = std::min(kInfinityValue, point.s); point.t = std::min(kInfinityValue, point.t); point.v = std::min(kInfinityValue, point.v); point.a = std::min(kInfinityValue, point.a); point.da = std::min(kInfinityValue, point.da); if (std::abs(point.t - kInfinityValue) < kDoubleEpsilon) points.resize(i + 1); } return Status::OK(); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_speed_decider.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides the implementation of the class "NaviSpeedDecider". */ #include "modules/planning/navi/decider/navi_speed_decider.h" #include <algorithm> #include <limits> #include "cyber/common/log.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::PathPoint; using apollo::common::Status; using apollo::common::VehicleConfigHelper; using apollo::common::math::Clamp; namespace { constexpr double kTsGraphSStep = 0.4; constexpr size_t kFallbackSpeedPointNum = 4; constexpr double kSpeedPointSLimit = 200.0; constexpr double kSpeedPointTimeLimit = 50.0; constexpr double kZeroSpeedEpsilon = 1.0e-3; constexpr double kZeroAccelEpsilon = 1.0e-3; constexpr double kDecelCompensationLimit = 2.0; constexpr double kKappaAdjustRatio = 20.0; } // namespace NaviSpeedDecider::NaviSpeedDecider() : NaviTask("NaviSpeedDecider") {} bool NaviSpeedDecider::Init(const PlanningConfig& planning_config) { CHECK_GT(FLAGS_planning_upper_speed_limit, 0.0); NavigationPlanningConfig config = planning_config.navigation_planning_config(); ACHECK(config.has_planner_navi_config()); ACHECK(config.planner_navi_config().has_navi_speed_decider_config()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_preferred_accel()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_preferred_decel()); ACHECK( config.planner_navi_config().navi_speed_decider_config().has_max_accel()); ACHECK( config.planner_navi_config().navi_speed_decider_config().has_max_decel()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_preferred_jerk()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_obstacle_buffer()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_safe_distance_base()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_safe_distance_ratio()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_following_accel_ratio()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_soft_centric_accel_limit()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_hard_centric_accel_limit()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_hard_speed_limit()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_hard_accel_limit()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_enable_safe_path()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_enable_planning_start_point()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_enable_accel_auto_compensation()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_kappa_preview()); ACHECK(config.planner_navi_config() .navi_speed_decider_config() .has_kappa_threshold()); max_speed_ = FLAGS_planning_upper_speed_limit; preferred_accel_ = std::abs(config.planner_navi_config() .navi_speed_decider_config() .preferred_accel()); preferred_decel_ = std::abs(config.planner_navi_config() .navi_speed_decider_config() .preferred_decel()); preferred_jerk_ = std::abs(config.planner_navi_config() .navi_speed_decider_config() .preferred_jerk()); max_accel_ = std::abs( config.planner_navi_config().navi_speed_decider_config().max_accel()); max_decel_ = std::abs( config.planner_navi_config().navi_speed_decider_config().max_decel()); preferred_accel_ = std::min(max_accel_, preferred_accel_); preferred_decel_ = std::min(max_decel_, preferred_accel_); obstacle_buffer_ = std::abs(config.planner_navi_config() .navi_speed_decider_config() .obstacle_buffer()); safe_distance_base_ = std::abs(config.planner_navi_config() .navi_speed_decider_config() .safe_distance_base()); safe_distance_ratio_ = std::abs(config.planner_navi_config() .navi_speed_decider_config() .safe_distance_ratio()); following_accel_ratio_ = std::abs(config.planner_navi_config() .navi_speed_decider_config() .following_accel_ratio()); soft_centric_accel_limit_ = std::abs(config.planner_navi_config() .navi_speed_decider_config() .soft_centric_accel_limit()); hard_centric_accel_limit_ = std::abs(config.planner_navi_config() .navi_speed_decider_config() .hard_centric_accel_limit()); soft_centric_accel_limit_ = std::min(hard_centric_accel_limit_, soft_centric_accel_limit_); hard_speed_limit_ = std::abs(config.planner_navi_config() .navi_speed_decider_config() .hard_speed_limit()); hard_accel_limit_ = std::abs(config.planner_navi_config() .navi_speed_decider_config() .hard_accel_limit()); enable_safe_path_ = config.planner_navi_config() .navi_speed_decider_config() .enable_safe_path(); enable_planning_start_point_ = config.planner_navi_config() .navi_speed_decider_config() .enable_planning_start_point(); enable_accel_auto_compensation_ = config.planner_navi_config() .navi_speed_decider_config() .enable_accel_auto_compensation(); kappa_preview_ = config.planner_navi_config().navi_speed_decider_config().kappa_preview(); kappa_threshold_ = config.planner_navi_config() .navi_speed_decider_config() .kappa_threshold(); return obstacle_decider_.Init(planning_config); } Status NaviSpeedDecider::Execute(Frame* frame, ReferenceLineInfo* reference_line_info) { NaviTask::Execute(frame, reference_line_info); // get cruise speed const auto& planning_target = reference_line_info_->planning_target(); preferred_speed_ = planning_target.has_cruise_speed() ? std::abs(planning_target.cruise_speed()) : 0.0; preferred_speed_ = std::min(max_speed_, preferred_speed_); // expected status of vehicle const auto& planning_start_point = frame->PlanningStartPoint(); auto expected_v = planning_start_point.has_v() ? planning_start_point.v() : 0.0; auto expected_a = planning_start_point.has_a() ? planning_start_point.a() : 0.0; // current status of vehicle const auto& vehicle_state = frame->vehicle_state(); auto current_v = vehicle_state.has_linear_velocity() ? vehicle_state.linear_velocity() : 0.0; auto current_a = vehicle_state.has_linear_acceleration() ? vehicle_state.linear_acceleration() : 0.0; // get the start point double start_v; double start_a; double start_da; if (enable_planning_start_point_) { start_v = std::max(0.0, expected_v); start_a = expected_a; start_da = 0.0; } else { start_v = std::max(0.0, current_v); start_a = current_a; start_da = 0.0; } // acceleration auto compensation if (enable_accel_auto_compensation_) { if (prev_v_ > 0.0 && current_v > 0.0 && prev_v_ > expected_v) { auto raw_ratio = (prev_v_ - expected_v) / (prev_v_ - current_v); raw_ratio = Clamp(raw_ratio, 0.0, kDecelCompensationLimit); decel_compensation_ratio_ = (decel_compensation_ratio_ + raw_ratio) / 2.0; decel_compensation_ratio_ = Clamp(decel_compensation_ratio_, 1.0, kDecelCompensationLimit); ADEBUG << "change decel_compensation_ratio: " << decel_compensation_ratio_ << " raw: " << raw_ratio; } prev_v_ = current_v; } // get the path auto& discretized_path = reference_line_info_->path_data().discretized_path(); auto ret = MakeSpeedDecision( start_v, start_a, start_da, discretized_path, frame_->obstacles(), [&](const std::string& id) { return frame_->Find(id); }, reference_line_info_->mutable_speed_data()); RecordDebugInfo(reference_line_info->speed_data()); if (ret != Status::OK()) { reference_line_info->SetDrivable(false); AERROR << "Reference Line " << reference_line_info->Lanes().Id() << " is not drivable after " << Name(); } return ret; } Status NaviSpeedDecider::MakeSpeedDecision( double start_v, double start_a, double start_da, const std::vector<PathPoint>& path_points, const std::vector<const Obstacle*>& obstacles, const std::function<const Obstacle*(const std::string&)>& find_obstacle, SpeedData* const speed_data) { CHECK_NOTNULL(speed_data); CHECK_GE(path_points.size(), 2U); auto start_s = path_points.front().has_s() ? path_points.front().s() : 0.0; auto end_s = path_points.back().has_s() ? path_points.back().s() : start_s; auto planning_length = end_s - start_s; ADEBUG << "start to make speed decision, start_v: " << start_v << " start_a: " << start_a << " start_da: " << start_da << " start_s: " << start_s << " planning_length: " << planning_length; if (start_v > max_speed_) { const std::string msg = "exceeding maximum allowable speed."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } start_v = std::max(0.0, start_v); auto s_step = planning_length > kTsGraphSStep ? kTsGraphSStep : planning_length / kFallbackSpeedPointNum; // init t-s graph ts_graph_.Reset(s_step, planning_length, start_v, start_a, start_da); // add t-s constraints auto ret = AddPerceptionRangeConstraints(); if (ret != Status::OK()) { AERROR << "Add t-s constraints base on range of perception failed"; return ret; } ret = AddObstaclesConstraints(start_v, planning_length, path_points, obstacles, find_obstacle); if (ret != Status::OK()) { AERROR << "Add t-s constraints base on obstacles failed"; return ret; } ret = AddCentricAccelerationConstraints(path_points); if (ret != Status::OK()) { AERROR << "Add t-s constraints base on centric acceleration failed"; return ret; } ret = AddConfiguredConstraints(); if (ret != Status::OK()) { AERROR << "Add t-s constraints base on configs failed"; return ret; } // create speed-points std::vector<NaviSpeedTsPoint> ts_points; if (ts_graph_.Solve(&ts_points) != Status::OK()) { AERROR << "Solve speed points failed"; speed_data->clear(); speed_data->AppendSpeedPoint(0.0 + start_s, 0.0, 0.0, -max_decel_, 0.0); speed_data->AppendSpeedPoint(0.0 + start_s, 1.0, 0.0, -max_decel_, 0.0); return Status::OK(); } speed_data->clear(); for (auto& ts_point : ts_points) { if (ts_point.s > kSpeedPointSLimit || ts_point.t > kSpeedPointTimeLimit) break; if (ts_point.v > hard_speed_limit_) { AERROR << "The v: " << ts_point.v << " of point with s: " << ts_point.s << " and t: " << ts_point.t << "is greater than hard_speed_limit " << hard_speed_limit_; ts_point.v = hard_speed_limit_; } if (std::abs(ts_point.v) < kZeroSpeedEpsilon) { ts_point.v = 0.0; } if (ts_point.a > hard_accel_limit_) { AERROR << "The a: " << ts_point.a << " of point with s: " << ts_point.s << " and t: " << ts_point.t << "is greater than hard_accel_limit " << hard_accel_limit_; ts_point.a = hard_accel_limit_; } if (std::abs(ts_point.a) < kZeroAccelEpsilon) { ts_point.a = 0.0; } // apply acceleration adjust if (enable_accel_auto_compensation_) { if (ts_point.a > 0) ts_point.a *= accel_compensation_ratio_; else ts_point.a *= decel_compensation_ratio_; } speed_data->AppendSpeedPoint(ts_point.s + start_s, ts_point.t, ts_point.v, ts_point.a, ts_point.da); } if (speed_data->size() == 1) { const auto& prev = speed_data->back(); speed_data->AppendSpeedPoint(prev.s(), prev.t() + 1.0, 0.0, 0.0, 0.0); } return Status::OK(); } Status NaviSpeedDecider::AddPerceptionRangeConstraints() { // TODO(all): return Status::OK(); } Status NaviSpeedDecider::AddObstaclesConstraints( double vehicle_speed, double path_length, const std::vector<PathPoint>& path_points, const std::vector<const Obstacle*>& obstacles, const std::function<const Obstacle*(const std::string&)>& find_obstacle) { const auto& vehicle_config = VehicleConfigHelper::Instance()->GetConfig(); auto front_edge_to_center = vehicle_config.vehicle_param().front_edge_to_center(); auto get_obstacle_distance = [&](double d) -> double { return std::max(0.0, d - front_edge_to_center - obstacle_buffer_); }; auto get_safe_distance = [&](double v) -> double { return safe_distance_ratio_ * v + safe_distance_base_ + front_edge_to_center + obstacle_buffer_; }; // add obstacles from perception obstacle_decider_.GetUnsafeObstaclesInfo(path_points, obstacles); for (const auto& info : obstacle_decider_.UnsafeObstacles()) { const auto& id = std::get<0>(info); const auto* obstacle = find_obstacle(id); if (obstacle != nullptr) { auto s = std::get<1>(info); auto obstacle_distance = get_obstacle_distance(s); auto obstacle_speed = std::max(std::get<2>(info), 0.0); auto safe_distance = get_safe_distance(obstacle_speed); AINFO << "obstacle with id: " << id << " s: " << s << " distance: " << obstacle_distance << " speed: " << obstacle_speed << " safe_distance: " << safe_distance; ts_graph_.UpdateObstacleConstraints(obstacle_distance, safe_distance, following_accel_ratio_, obstacle_speed, preferred_speed_); } } // the end of path just as an obstacle if (enable_safe_path_) { auto obstacle_distance = get_obstacle_distance(path_length); auto safe_distance = get_safe_distance(0.0); ts_graph_.UpdateObstacleConstraints(obstacle_distance, safe_distance, following_accel_ratio_, 0.0, preferred_speed_); } return Status::OK(); } Status AddTrafficDecisionConstraints() { // TODO(all): return Status::OK(); } Status NaviSpeedDecider::AddCentricAccelerationConstraints( const std::vector<PathPoint>& path_points) { if (path_points.size() < 2) { const std::string msg = "Too few path points"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } double max_kappa = 0.0; double max_kappa_v = std::numeric_limits<double>::max(); double preffered_kappa_v = std::numeric_limits<double>::max(); double max_kappa_s = 0.0; const auto bs = path_points[0].has_s() ? path_points[0].s() : 0.0; struct CLimit { double s; double v_max; double v_preffered; }; std::vector<CLimit> c_limits; c_limits.resize(path_points.size() - 1); for (size_t i = 1; i < path_points.size(); i++) { const auto& prev = path_points[i - 1]; const auto& cur = path_points[i]; auto start_s = prev.has_s() ? prev.s() - bs : 0.0; start_s = std::max(0.0, start_s); auto end_s = cur.has_s() ? cur.s() - bs : 0.0; end_s = std::max(0.0, end_s); auto start_k = prev.has_kappa() ? prev.kappa() : 0.0; auto end_k = cur.has_kappa() ? cur.kappa() : 0.0; auto kappa = std::abs((start_k + end_k) / 2.0); if (std::abs(kappa) < kappa_threshold_) { kappa /= kKappaAdjustRatio; } auto v_preffered = std::min(std::sqrt(soft_centric_accel_limit_ / kappa), std::numeric_limits<double>::max()); auto v_max = std::min(std::sqrt(hard_centric_accel_limit_ / kappa), std::numeric_limits<double>::max()); c_limits[i - 1].s = end_s; c_limits[i - 1].v_max = v_max; c_limits[i - 1].v_preffered = v_preffered; if (kappa > max_kappa) { max_kappa = kappa; max_kappa_v = v_max; preffered_kappa_v = v_preffered; max_kappa_s = start_s; } } // kappa preview for (size_t i = 0; i < c_limits.size(); i++) { for (size_t j = i; j - i < (size_t)(kappa_preview_ / kTsGraphSStep) && j < c_limits.size(); j++) c_limits[i].v_preffered = std::min(c_limits[j].v_preffered, c_limits[i].v_preffered); } double start_s = 0.0; for (size_t i = 0; i < c_limits.size(); i++) { auto end_s = c_limits[i].s; auto v_max = c_limits[i].v_max; auto v_preffered = c_limits[i].v_preffered; NaviSpeedTsConstraints constraints; constraints.v_max = v_max; constraints.v_preffered = v_preffered; ts_graph_.UpdateRangeConstraints(start_s, end_s, constraints); start_s = end_s; } AINFO << "add speed limit for centric acceleration with kappa: " << max_kappa << " v_max: " << max_kappa_v << " v_preffered: " << preffered_kappa_v << " s: " << max_kappa_s; return Status::OK(); } Status NaviSpeedDecider::AddConfiguredConstraints() { NaviSpeedTsConstraints constraints; constraints.v_max = max_speed_; constraints.v_preffered = preferred_speed_; constraints.a_max = max_accel_; constraints.a_preffered = preferred_accel_; constraints.b_max = max_decel_; constraints.b_preffered = preferred_decel_; constraints.da_preffered = preferred_jerk_; ts_graph_.UpdateConstraints(constraints); return Status::OK(); } void NaviSpeedDecider::RecordDebugInfo(const SpeedData& speed_data) { auto* debug = reference_line_info_->mutable_debug(); auto ptr_speed_plan = debug->mutable_planning_data()->add_speed_plan(); ptr_speed_plan->set_name(Name()); ptr_speed_plan->mutable_speed_point()->CopyFrom( {speed_data.begin(), speed_data.end()}); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_speed_decider_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides several unit tests for the class * "NaviSpeedDecider". */ #include "modules/planning/navi/decider/navi_speed_decider.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "modules/common/util/point_factory.h" #include "modules/planning/common/planning_gflags.h" using apollo::common::PathPoint; using apollo::common::Status; using apollo::common::util::PointFactory; using apollo::perception::PerceptionObstacle; using apollo::prediction::ObstaclePriority; namespace apollo { namespace planning { static PathPoint GenPathPoint(double s, double kappa = 0.0) { return PointFactory::ToPathPoint(s, 0.0, 0.0, s, 0.0, kappa); } TEST(NaviSpeedDeciderTest, CreateSpeedData) { NaviSpeedDecider speed_decider; speed_decider.preferred_speed_ = 10.0; speed_decider.max_speed_ = 20.0; speed_decider.preferred_accel_ = 2.0; speed_decider.preferred_decel_ = 2.0; speed_decider.preferred_jerk_ = 2.0; speed_decider.max_accel_ = 5.0; speed_decider.max_decel_ = 5.0; speed_decider.obstacle_buffer_ = 1.0; speed_decider.safe_distance_base_ = 2.0; speed_decider.safe_distance_ratio_ = 1.0; speed_decider.following_accel_ratio_ = 0.5; speed_decider.soft_centric_accel_limit_ = 1.2; speed_decider.hard_centric_accel_limit_ = 1.5; speed_decider.hard_speed_limit_ = 100.0; speed_decider.hard_accel_limit_ = 10.0; speed_decider.enable_safe_path_ = true; speed_decider.enable_planning_start_point_ = true; speed_decider.kappa_preview_ = 0.0; speed_decider.kappa_threshold_ = 0.0; PerceptionObstacle perception_obstacle; std::map<std::string, Obstacle> obstacle_buf; std::vector<const Obstacle*> obstacles; std::vector<PathPoint> path_points; path_points.emplace_back(GenPathPoint(0.0)); path_points.emplace_back(GenPathPoint(100.0)); SpeedData speed_data; EXPECT_EQ(Status::OK(), speed_decider.MakeSpeedDecision( 0.0, 0.0, 0.0, path_points, obstacles, [&](const std::string& id) mutable { return &obstacle_buf[id]; }, &speed_data)); for (auto& p : speed_data) { if (p.s() > 2.0 && p.s() < 24.0) { EXPECT_NEAR(2.0, p.a(), 0.1); } if (p.s() > 26.0 && p.s() < 60.0) { EXPECT_NEAR(10.0, p.v(), 0.1); } } } TEST(NaviSpeedDeciderTest, CreateSpeedDataForStaticObstacle) { NaviSpeedDecider speed_decider; speed_decider.preferred_speed_ = 10.0; speed_decider.max_speed_ = 20.0; speed_decider.preferred_accel_ = 1.0; speed_decider.preferred_decel_ = 1.0; speed_decider.preferred_jerk_ = 2.0; speed_decider.max_accel_ = 5.0; speed_decider.max_decel_ = 5.0; speed_decider.obstacle_buffer_ = 1.0; speed_decider.safe_distance_base_ = 2.0; speed_decider.safe_distance_ratio_ = 1.0; speed_decider.following_accel_ratio_ = 0.5; speed_decider.soft_centric_accel_limit_ = 1.2; speed_decider.hard_centric_accel_limit_ = 1.5; speed_decider.hard_speed_limit_ = 100.0; speed_decider.hard_accel_limit_ = 10.0; speed_decider.enable_safe_path_ = false; speed_decider.enable_planning_start_point_ = true; speed_decider.kappa_preview_ = 0.0; speed_decider.kappa_threshold_ = 0.0; PerceptionObstacle perception_obstacle; std::map<std::string, Obstacle> obstacle_buf; std::vector<const Obstacle*> obstacles; std::vector<PathPoint> path_points; path_points.emplace_back(GenPathPoint(0.0)); path_points.emplace_back(GenPathPoint(200.0)); // obstacle1 perception_obstacle.mutable_position()->set_x(30.0); perception_obstacle.mutable_position()->set_y(1.0); perception_obstacle.mutable_velocity()->set_x(0.0); perception_obstacle.mutable_velocity()->set_y(0.0); perception_obstacle.set_length(3.0); perception_obstacle.set_width(3.0); std::string id = "1"; obstacle_buf.emplace( id, Obstacle(id, perception_obstacle, ObstaclePriority::NORMAL, false)); obstacles.emplace_back(&obstacle_buf[id]); SpeedData speed_data; EXPECT_EQ(Status::OK(), speed_decider.MakeSpeedDecision( 0.0, 0.0, 0.0, path_points, obstacles, [&](const std::string& id) mutable { return &obstacle_buf[id]; }, &speed_data)); for (auto& p : speed_data) { if (p.s() > 16.7) { EXPECT_NEAR(0.0, p.v(), 1.0); } } } TEST(NaviSpeedDeciderTest, CreateSpeedDataForObstacles) { NaviSpeedDecider speed_decider; speed_decider.preferred_speed_ = 10.0; speed_decider.max_speed_ = 20.0; speed_decider.preferred_accel_ = 1.0; speed_decider.preferred_decel_ = 1.0; speed_decider.preferred_jerk_ = 2.0; speed_decider.max_accel_ = 5.0; speed_decider.max_decel_ = 5.0; speed_decider.obstacle_buffer_ = 1.0; speed_decider.safe_distance_base_ = 2.0; speed_decider.safe_distance_ratio_ = 1.0; speed_decider.following_accel_ratio_ = 0.5; speed_decider.soft_centric_accel_limit_ = 1.2; speed_decider.hard_centric_accel_limit_ = 1.5; speed_decider.hard_speed_limit_ = 100.0; speed_decider.hard_accel_limit_ = 10.0; speed_decider.enable_safe_path_ = true; speed_decider.enable_planning_start_point_ = true; speed_decider.kappa_preview_ = 0.0; speed_decider.kappa_threshold_ = 0.0; PerceptionObstacle perception_obstacle; std::map<std::string, Obstacle> obstacle_buf; std::vector<const Obstacle*> obstacles; std::vector<PathPoint> path_points; path_points.emplace_back(GenPathPoint(0.0)); path_points.emplace_back(GenPathPoint(100.0)); // obstacle1 perception_obstacle.mutable_position()->set_x(50.0); perception_obstacle.mutable_position()->set_y(1.0); perception_obstacle.mutable_velocity()->set_x(0.0); perception_obstacle.mutable_velocity()->set_y(0.0); perception_obstacle.set_length(3.0); perception_obstacle.set_width(3.0); std::string id = "1"; obstacle_buf.emplace( id, Obstacle(id, perception_obstacle, ObstaclePriority::NORMAL, false)); obstacles.emplace_back(&obstacle_buf[id]); // obstacle2 perception_obstacle.mutable_position()->set_x(20.0); perception_obstacle.mutable_position()->set_y(1.0); perception_obstacle.mutable_velocity()->set_x(5.0); perception_obstacle.mutable_velocity()->set_y(0.0); perception_obstacle.set_length(3.0); perception_obstacle.set_width(3.0); id = "2"; obstacle_buf.emplace( id, Obstacle(id, perception_obstacle, ObstaclePriority::NORMAL, false)); obstacles.emplace_back(&obstacle_buf[id]); SpeedData speed_data; EXPECT_EQ(Status::OK(), speed_decider.MakeSpeedDecision( 10.0, 0.0, 0.0, path_points, obstacles, [&](const std::string& id) mutable { return &obstacle_buf[id]; }, &speed_data)); for (auto& p : speed_data) { if (p.s() > 15.0 && p.s() < 26.0) { EXPECT_NEAR(5.0, p.v(), 0.5); } if (p.s() > 37.0) { EXPECT_NEAR(0.0, p.v(), 1.0); } } } TEST(NaviSpeedDeciderTest, CreateSpeedDataForCurve) { NaviSpeedDecider speed_decider; speed_decider.preferred_speed_ = 12.0; speed_decider.max_speed_ = 30.0; speed_decider.preferred_accel_ = 2.0; speed_decider.preferred_decel_ = 1.5; speed_decider.preferred_jerk_ = 2.0; speed_decider.max_accel_ = 5.0; speed_decider.max_decel_ = 5.0; speed_decider.obstacle_buffer_ = 1.0; speed_decider.safe_distance_base_ = 2.0; speed_decider.safe_distance_ratio_ = 1.0; speed_decider.following_accel_ratio_ = 0.5; speed_decider.soft_centric_accel_limit_ = 1.0; speed_decider.hard_centric_accel_limit_ = 1.5; speed_decider.hard_speed_limit_ = 100.0; speed_decider.hard_accel_limit_ = 10.0; speed_decider.enable_safe_path_ = false; speed_decider.enable_planning_start_point_ = true; speed_decider.kappa_preview_ = 0.0; speed_decider.kappa_threshold_ = 0.0; PerceptionObstacle perception_obstacle; std::map<std::string, Obstacle> obstacle_buf; std::vector<const Obstacle*> obstacles; std::vector<PathPoint> path_points; double s = 0.0; path_points.emplace_back(GenPathPoint(s, 0.0)); s += 50.0; path_points.emplace_back(GenPathPoint(s, 0.0)); for (size_t i = 1; i <= 5; i++) { s += 1.0; path_points.emplace_back(GenPathPoint(s, 0.03 * static_cast<double>(i))); } for (size_t i = 1; i <= 5; i++) { s += 1.0; path_points.emplace_back(GenPathPoint(s, 0.15)); } for (size_t i = 1; i <= 5; i++) { s += 1.0; path_points.emplace_back( GenPathPoint(s, 0.03 * static_cast<double>(5 - i))); } s += 1.0; path_points.emplace_back(GenPathPoint(s, 0.0)); s += 10.0; path_points.emplace_back(GenPathPoint(s, 0.0)); for (size_t i = 1; i <= 10; i++) { s += 1.0; path_points.emplace_back(GenPathPoint(s, -0.07)); } for (size_t i = 1; i <= 10; i++) { s += 1.0; path_points.emplace_back(GenPathPoint(s, 0.07)); } s += 1.0; path_points.emplace_back(GenPathPoint(s, 0.0)); s += 20.0; path_points.emplace_back(GenPathPoint(s, 0.0)); SpeedData speed_data; EXPECT_EQ(Status::OK(), speed_decider.MakeSpeedDecision( 12.1, 0.0, 0.0, path_points, obstacles, [&](const std::string& id) mutable { return &obstacle_buf[id]; }, &speed_data)); for (auto& p : speed_data) { if (p.s() > 56.0 && p.s() < 59.0) { EXPECT_NEAR(2.6, p.v(), 0.1); } if (p.s() > 88.0 && p.s() < 95.0) { EXPECT_NEAR(3.7, p.v(), 0.1); } } } TEST(NaviSpeedDeciderTest, ErrorTest) {} } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) PLANNING_COPTS = ["-DMODULE_NAME=\\\"planning\\\""] cc_library( name = "navi_task", srcs = ["navi_task.cc"], hdrs = ["navi_task.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/status", "//modules/planning/common:frame", "//modules/planning/common:planning_gflags", "//modules/planning/common:reference_line_info", "//modules/planning/proto:planning_config_cc_proto", ], ) cc_library( name = "navi_path_decider", srcs = ["navi_path_decider.cc"], hdrs = ["navi_path_decider.h"], copts = PLANNING_COPTS, deps = [ ":navi_task", "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/status", "//modules/planning/common:frame", "//modules/planning/common:planning_gflags", "//modules/planning/common:reference_line_info", "//modules/planning/navi/decider:navi_obstacle_decider", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/proto:planning_config_cc_proto", "//modules/planning/tasks:task", ], ) cc_library( name = "navi_speed_decider", srcs = [ "navi_speed_decider.cc", "navi_speed_ts_graph.cc", ], hdrs = [ "navi_speed_decider.h", "navi_speed_ts_graph.h", ], copts = PLANNING_COPTS, deps = [ ":navi_task", "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/status", "//modules/planning/common:frame", "//modules/planning/common:planning_gflags", "//modules/planning/common:reference_line_info", "//modules/planning/navi/decider:navi_obstacle_decider", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/proto:planning_config_cc_proto", "//modules/planning/tasks:task", ], ) cc_library( name = "navi_obstacle_decider", srcs = ["navi_obstacle_decider.cc"], hdrs = ["navi_obstacle_decider.h"], copts = PLANNING_COPTS, deps = [ ":navi_task", "//cyber", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/planning/common:frame", "//modules/planning/common:obstacle", "//modules/planning/common:planning_gflags", "//modules/planning/tasks:task", ], ) cc_test( name = "navi_decider_test", size = "small", srcs = [ "navi_obstacle_decider_test.cc", "navi_path_decider_test.cc", "navi_speed_decider_test.cc", "navi_speed_ts_graph_test.cc", ], data = ["//modules/planning:planning_testdata"], deps = [ ":navi_obstacle_decider", ":navi_path_decider", ":navi_speed_decider", "//modules/common/util", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/navi
apollo_public_repos/apollo/modules/planning/navi/decider/navi_obstacle_decider.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file * @brief This file provides the declaration of the class "NaviSpeedDecider". */ #pragma once #include <map> #include <string> #include <tuple> #include <vector> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/vec2d.h" #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/navi/decider/navi_task.h" /** * @namespace apollo::planning * @brief apollo::planning */ namespace apollo { namespace planning { /** * @class NaviObstacleDecider * @brief NaviObstacleDecider is used to make appropriate decisions for * obstacles around the vehicle in navigation mode. * Note that NaviObstacleDecider is only used in navigation mode (turn on * navigation mode by setting "FLAGS_use_navigation_mode" to "true") and do not * use it in standard mode. */ class NaviObstacleDecider : public NaviTask { public: NaviObstacleDecider(); virtual ~NaviObstacleDecider() = default; /** * @brief Initialization parameters * @return Initialization success or not */ bool Init(const PlanningConfig &config) override; /** * @brief get the actual nudgable distance according to the * position of the obstacle * @return actual nudgable distance */ double GetNudgeDistance( const std::vector<const Obstacle *> &obstacles, const ReferenceLine &reference_line, const PathDecision &path_decision, const std::vector<common::PathPoint> &path_data_points, const common::VehicleState &vehicle_state, int *lane_obstacles_num); /** * @brief get the unsafe obstacles between trajectory and reference line. * */ void GetUnsafeObstaclesInfo( const std::vector<common::PathPoint> &path_data_points, const std::vector<const Obstacle *> &obstacles); /** * @brief Get unsafe obstacles' ID * @return unsafe_obstacle_ID_ */ const std::vector<std::tuple<std::string, double, double>> &UnsafeObstacles(); private: /** * @brief Get vehicle parameter * @return vehicle parameter */ const apollo::common::VehicleParam &VehicleParam(); /** * @brief Set last nudge dist * @ */ void SetLastNudgeDistance(double dist); /** * @brief process path's obstacles info * @return Number of obstacles in the current lane */ void ProcessObstacle(const std::vector<const Obstacle *> &obstacles, const std::vector<common::PathPoint> &path_data_points, const PathDecision &path_decision, const double min_lane_width, const common::VehicleState &vehicle_state); /** * @brief According to the relation between the obstacle and the path data, * the sign is added to the distance away from the path data.Take positive on * the left and negative on the right */ void AddObstacleOffsetDirection( const common::PathPoint &projection_point, const std::vector<common::PathPoint> &path_data_points, const Obstacle *current_obstacle, const double proj_len, double *dist); /** * @brief Remove safe obstacles * @return whether filter the obstacle */ bool IsNeedFilterObstacle( const Obstacle *current_obstacle, const common::PathPoint &vehicle_projection_point, const std::vector<common::PathPoint> &path_data_points, const common::VehicleState &vehicle_state, common::PathPoint *projection_point_ptr); /** * @brief Get the minimum path width * @return minimum path width */ double GetMinLaneWidth(const std::vector<common::PathPoint> &path_data_points, const ReferenceLine &reference_line); /** * @brief Record last nudge * */ void RecordLastNudgeDistance(const double nudge_dist); /** * @brief Get the actual distance between the vehicle and the obstacle based * on path data * @return Actual distance */ double GetObstacleActualOffsetDistance( std::map<double, double>::iterator iter, const double right_nedge_lane, const double left_nudge_lane, int *lane_obstacles_num); /** * @brief Eliminate the influence of clutter signals on Nudge */ void SmoothNudgeDistance(const common::VehicleState &vehicle_state, double *nudge_dist); void KeepNudgePosition(const double nudge_dist, int *lane_obstacles_num); private: NaviObstacleDeciderConfig config_; std::map<double, double> obstacle_lat_dist_; std::vector<std::tuple<std::string, double, double>> unsafe_obstacle_info_; double last_nudge_dist_ = 0.0; unsigned int no_nudge_num_ = 0; unsigned int limit_speed_num_ = 0; unsigned int eliminate_clutter_num_ = 0; unsigned int last_lane_obstacles_num_ = 0; unsigned int statist_count_ = 0; unsigned int cycles_count_ = 0; bool is_obstacle_stable_ = false; bool keep_nudge_flag_ = false; FRIEND_TEST(NaviObstacleDeciderTest, ComputeNudgeDist1); FRIEND_TEST(NaviObstacleDeciderTest, ComputeNudgeDist2); FRIEND_TEST(NaviObstacleDeciderTest, ComputeNudgeDist3); FRIEND_TEST(NaviObstacleDeciderTest, ComputeNudgeDist4); FRIEND_TEST(NaviObstacleDeciderTest, GetUnsafeObstaclesID); // TODO(all): Add your member functions and variables. }; inline const apollo::common::VehicleParam &NaviObstacleDecider::VehicleParam() { const auto &vehicle_param = apollo::common::VehicleConfigHelper::Instance() ->GetConfig() .vehicle_param(); return vehicle_param; } inline const std::vector<std::tuple<std::string, double, double>> &NaviObstacleDecider::UnsafeObstacles() { return unsafe_obstacle_info_; } inline void NaviObstacleDecider::SetLastNudgeDistance(double dist) { last_nudge_dist_ = dist; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/tools/distance_approach_problem_wrapper.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "cyber/common/file.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/open_space/coarse_trajectory_generator/hybrid_a_star.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_problem.h" #include "modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_problem.h" namespace apollo { namespace planning { using apollo::common::math::Vec2d; class ObstacleContainer { public: ObstacleContainer() = default; bool VPresentationObstacle( const double* ROI_distance_approach_parking_boundary) { obstacles_num_ = 4; obstacles_edges_num_.resize(4, 1); obstacles_edges_num_ << 2, 1, 2, 1; size_t index = 0; for (size_t i = 0; i < obstacles_num_; i++) { std::vector<Vec2d> vertices_cw; for (int j = 0; j < obstacles_edges_num_(i, 0) + 1; j++) { Vec2d vertice = Vec2d(ROI_distance_approach_parking_boundary[index], ROI_distance_approach_parking_boundary[index + 1]); index += 2; vertices_cw.emplace_back(vertice); } obstacles_vertices_vec_.emplace_back(vertices_cw); } return true; } bool HPresentationObstacle() { obstacles_A_ = Eigen::MatrixXd::Zero(obstacles_edges_num_.sum(), 2); obstacles_b_ = Eigen::MatrixXd::Zero(obstacles_edges_num_.sum(), 1); // vertices using H-representation if (!ObsHRep(obstacles_num_, obstacles_edges_num_, obstacles_vertices_vec_, &obstacles_A_, &obstacles_b_)) { AINFO << "Fail to present obstacle in hyperplane"; return false; } return true; } bool ObsHRep(const size_t obstacles_num, const Eigen::MatrixXi& obstacles_edges_num, const std::vector<std::vector<Vec2d>>& obstacles_vertices_vec, Eigen::MatrixXd* A_all, Eigen::MatrixXd* b_all) { if (obstacles_num != obstacles_vertices_vec.size()) { AINFO << "obstacles_num != obstacles_vertices_vec.size()"; return false; } A_all->resize(obstacles_edges_num.sum(), 2); b_all->resize(obstacles_edges_num.sum(), 1); int counter = 0; double kEpsilon = 1.0e-5; // start building H representation for (size_t i = 0; i < obstacles_num; ++i) { size_t current_vertice_num = obstacles_edges_num(i, 0); Eigen::MatrixXd A_i(current_vertice_num, 2); Eigen::MatrixXd b_i(current_vertice_num, 1); // take two subsequent vertices, and computer hyperplane for (size_t j = 0; j < current_vertice_num; ++j) { Vec2d v1 = obstacles_vertices_vec[i][j]; Vec2d v2 = obstacles_vertices_vec[i][j + 1]; Eigen::MatrixXd A_tmp(2, 1), b_tmp(1, 1), ab(2, 1); // find hyperplane passing through v1 and v2 if (std::abs(v1.x() - v2.x()) < kEpsilon) { if (v2.y() < v1.y()) { A_tmp << 1, 0; b_tmp << v1.x(); } else { A_tmp << -1, 0; b_tmp << -v1.x(); } } else if (std::abs(v1.y() - v2.y()) < kEpsilon) { if (v1.x() < v2.x()) { A_tmp << 0, 1; b_tmp << v1.y(); } else { A_tmp << 0, -1; b_tmp << -v1.y(); } } else { Eigen::MatrixXd tmp1(2, 2); tmp1 << v1.x(), 1, v2.x(), 1; Eigen::MatrixXd tmp2(2, 1); tmp2 << v1.y(), v2.y(); ab = tmp1.inverse() * tmp2; double a = ab(0, 0); double b = ab(1, 0); if (v1.x() < v2.x()) { A_tmp << -a, 1; b_tmp << b; } else { A_tmp << a, -1; b_tmp << -b; } } // store vertices A_i.block(j, 0, 1, 2) = A_tmp.transpose(); b_i.block(j, 0, 1, 1) = b_tmp; } A_all->block(counter, 0, A_i.rows(), 2) = A_i; b_all->block(counter, 0, b_i.rows(), 1) = b_i; counter += static_cast<int>(current_vertice_num); } return true; } void AddObstacle(const double* ROI_distance_approach_parking_boundary) { // the obstacles are hard coded into vertice sets of 3, 2, 3, 2 if (!(VPresentationObstacle(ROI_distance_approach_parking_boundary) && HPresentationObstacle())) { AINFO << "obstacle presentation fails"; } } const std::vector<std::vector<Vec2d>>& GetObstacleVec() const { return obstacles_vertices_vec_; } const Eigen::MatrixXd& GetAMatrix() const { return obstacles_A_; } const Eigen::MatrixXd& GetbMatrix() const { return obstacles_b_; } size_t GetObstaclesNum() const { return obstacles_num_; } const Eigen::MatrixXi& GetObstaclesEdgesNum() const { return obstacles_edges_num_; } private: size_t obstacles_num_ = 0; Eigen::MatrixXi obstacles_edges_num_; std::vector<std::vector<Vec2d>> obstacles_vertices_vec_; Eigen::MatrixXd obstacles_A_; Eigen::MatrixXd obstacles_b_; }; class ResultContainer { public: ResultContainer() = default; void LoadHybridAResult() { x_ = std::move(result_.x); y_ = std::move(result_.y); phi_ = std::move(result_.phi); v_ = std::move(result_.v); a_ = std::move(result_.a); steer_ = std::move(result_.steer); } std::vector<double>* GetX() { return &x_; } std::vector<double>* GetY() { return &y_; } std::vector<double>* GetPhi() { return &phi_; } std::vector<double>* GetV() { return &v_; } std::vector<double>* GetA() { return &a_; } std::vector<double>* GetSteer() { return &steer_; } HybridAStartResult* PrepareHybridAResult() { return &result_; } Eigen::MatrixXd* PrepareStateResult() { return &state_result_ds_; } Eigen::MatrixXd* PrepareControlResult() { return &control_result_ds_; } Eigen::MatrixXd* PrepareTimeResult() { return &time_result_ds_; } Eigen::MatrixXd* PrepareLResult() { return &dual_l_result_ds_; } Eigen::MatrixXd* PrepareNResult() { return &dual_n_result_ds_; } double* GetHybridTime() { return &hybrid_time_; } double* GetDualTime() { return &dual_time_; } double* GetIpoptTime() { return &ipopt_time_; } private: HybridAStartResult result_; std::vector<double> x_; std::vector<double> y_; std::vector<double> phi_; std::vector<double> v_; std::vector<double> a_; std::vector<double> steer_; Eigen::MatrixXd state_result_ds_; Eigen::MatrixXd control_result_ds_; Eigen::MatrixXd time_result_ds_; Eigen::MatrixXd dual_l_result_ds_; Eigen::MatrixXd dual_n_result_ds_; double hybrid_time_; double dual_time_; double ipopt_time_; }; extern "C" { HybridAStar* CreateHybridAPtr() { apollo::planning::PlannerOpenSpaceConfig planner_open_space_config_; ACHECK(apollo::cyber::common::GetProtoFromFile( FLAGS_planner_open_space_config_filename, &planner_open_space_config_)) << "Failed to load open space config file " << FLAGS_planner_open_space_config_filename; return new HybridAStar(planner_open_space_config_); } ObstacleContainer* DistanceCreateObstaclesPtr() { return new ObstacleContainer(); } ResultContainer* DistanceCreateResultPtr() { return new ResultContainer(); } void AddObstacle(ObstacleContainer* obstacles_ptr, const double* ROI_distance_approach_parking_boundary) { obstacles_ptr->AddObstacle(ROI_distance_approach_parking_boundary); } double InterpolateUsingLinearApproximation(const double p0, const double p1, const double w) { return p0 * (1.0 - w) + p1 * w; } std::vector<double> VectorLinearInterpolation(const std::vector<double>& x, int extend_size) { // interplation example: // x: [x0, x1, x2], extend_size: 3 // output: [y0(x0), y1, y2, y3(x1), y4, y5, y6(x2)] size_t origin_last = x.size() - 1; std::vector<double> res(origin_last * extend_size + 1, 0.0); for (size_t i = 0; i < origin_last * extend_size; ++i) { size_t idx0 = i / extend_size; size_t idx1 = idx0 + 1; double w = static_cast<double>(i % extend_size) / static_cast<double>(extend_size); res[i] = InterpolateUsingLinearApproximation(x[idx0], x[idx1], w); } res.back() = x.back(); return res; } bool DistanceSmoothing( const apollo::planning::PlannerOpenSpaceConfig& planner_open_space_config, const ObstacleContainer& obstacles, double sx, double sy, double sphi, double ex, double ey, double ephi, const std::vector<double>& XYbounds, HybridAStartResult* hybrid_a_star_result, Eigen::MatrixXd* state_result_ds_, Eigen::MatrixXd* control_result_ds_, Eigen::MatrixXd* time_result_ds_, Eigen::MatrixXd* dual_l_result_ds_, Eigen::MatrixXd* dual_n_result_ds_, double& dual_time, double& ipopt_time) { // load Warm Start result(horizon is the "N", not the size of step points) size_t horizon_ = hybrid_a_star_result->x.size() - 1; // nominal sampling time float ts_ = planner_open_space_config.delta_t(); Eigen::VectorXd x; Eigen::VectorXd y; Eigen::VectorXd phi; Eigen::VectorXd v; Eigen::VectorXd steer; Eigen::VectorXd a; // TODO(Runxin): extend logics in future if (horizon_ <= 10 && horizon_ > 2 && planner_open_space_config.enable_linear_interpolation()) { // TODO(Runxin): extend this number int extend_size = 5; // modify state and control vectors sizes horizon_ = extend_size * horizon_; // modify delta t ts_ = ts_ / static_cast<float>(extend_size); std::vector<double> x_extend = VectorLinearInterpolation(hybrid_a_star_result->x, extend_size); x = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(x_extend.data(), horizon_ + 1); std::vector<double> y_extend = VectorLinearInterpolation(hybrid_a_star_result->y, extend_size); y = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(y_extend.data(), horizon_ + 1); std::vector<double> phi_extend = VectorLinearInterpolation(hybrid_a_star_result->phi, extend_size); phi = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(phi_extend.data(), horizon_ + 1); std::vector<double> v_extend = VectorLinearInterpolation(hybrid_a_star_result->v, extend_size); v = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(v_extend.data(), horizon_ + 1); steer = Eigen::VectorXd(horizon_); a = Eigen::VectorXd(horizon_); for (size_t i = 0; i < static_cast<size_t>(horizon_); ++i) { steer[i] = hybrid_a_star_result->steer[i / extend_size]; a[i] = hybrid_a_star_result->a[i / extend_size]; } ADEBUG << "hybrid A x: "; for (size_t i = 0; i < hybrid_a_star_result->x.size(); ++i) { ADEBUG << "i: " << i << ", val: " << hybrid_a_star_result->x[i]; } ADEBUG << "interpolated x: \n" << x; ADEBUG << "hybrid A steer: "; for (size_t i = 0; i < hybrid_a_star_result->steer.size(); ++i) { ADEBUG << "i: " << i << ", val: " << hybrid_a_star_result->steer[i]; } ADEBUG << "interpolated steer: \n" << steer; } else { x = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>( hybrid_a_star_result->x.data(), horizon_ + 1); y = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>( hybrid_a_star_result->y.data(), horizon_ + 1); phi = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>( hybrid_a_star_result->phi.data(), horizon_ + 1); v = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>( hybrid_a_star_result->v.data(), horizon_ + 1); steer = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>( hybrid_a_star_result->steer.data(), horizon_); a = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>( hybrid_a_star_result->a.data(), horizon_); } Eigen::MatrixXd xWS = Eigen::MatrixXd::Zero(4, horizon_ + 1); Eigen::MatrixXd uWS = Eigen::MatrixXd::Zero(2, horizon_); xWS.row(0) = x; xWS.row(1) = y; xWS.row(2) = phi; xWS.row(3) = v; uWS.row(0) = steer; uWS.row(1) = a; Eigen::MatrixXd x0(4, 1); x0 << sx, sy, sphi, 0.0; Eigen::MatrixXd xF(4, 1); xF << ex, ey, ephi, 0.0; Eigen::MatrixXd last_time_u(2, 1); last_time_u << 0.0, 0.0; common::VehicleParam vehicle_param_ = common::VehicleConfigHelper::GetConfig().vehicle_param(); // load vehicle configuration Eigen::MatrixXd ego_(4, 1); double front_to_center = vehicle_param_.front_edge_to_center(); double back_to_center = vehicle_param_.back_edge_to_center(); double left_to_center = vehicle_param_.left_edge_to_center(); double right_to_center = vehicle_param_.right_edge_to_center(); ego_ << front_to_center, right_to_center, back_to_center, left_to_center; // result for distance approach problem Eigen::MatrixXd l_warm_up; Eigen::MatrixXd n_warm_up; Eigen::MatrixXd s_warm_up = Eigen::MatrixXd::Zero(obstacles.GetObstaclesNum(), horizon_ + 1); DualVariableWarmStartProblem* dual_variable_warm_start_ptr = new DualVariableWarmStartProblem(planner_open_space_config); const auto t1 = std::chrono::system_clock::now(); if (FLAGS_use_dual_variable_warm_start) { bool dual_variable_warm_start_status = dual_variable_warm_start_ptr->Solve( horizon_, ts_, ego_, obstacles.GetObstaclesNum(), obstacles.GetObstaclesEdgesNum(), obstacles.GetAMatrix(), obstacles.GetbMatrix(), xWS, &l_warm_up, &n_warm_up, &s_warm_up); if (dual_variable_warm_start_status) { AINFO << "Dual variable problem solved successfully!"; } else { AERROR << "Dual variable problem solving failed"; return false; } } else { l_warm_up = Eigen::MatrixXd::Zero(obstacles.GetObstaclesEdgesNum().sum(), horizon_ + 1); n_warm_up = Eigen::MatrixXd::Zero(4 * obstacles.GetObstaclesNum(), horizon_ + 1); } const auto t2 = std::chrono::system_clock::now(); dual_time = std::chrono::duration<double>(t2 - t1).count() * 1000; DistanceApproachProblem* distance_approach_ptr = new DistanceApproachProblem(planner_open_space_config); bool status = distance_approach_ptr->Solve( x0, xF, last_time_u, horizon_, ts_, ego_, xWS, uWS, l_warm_up, n_warm_up, s_warm_up, XYbounds, obstacles.GetObstaclesNum(), obstacles.GetObstaclesEdgesNum(), obstacles.GetAMatrix(), obstacles.GetbMatrix(), state_result_ds_, control_result_ds_, time_result_ds_, dual_l_result_ds_, dual_n_result_ds_); const auto t3 = std::chrono::system_clock::now(); ipopt_time = std::chrono::duration<double>(t3 - t2).count() * 1000; if (!status) { AERROR << "Distance fail"; return false; } return true; } bool DistancePlan(HybridAStar* hybridA_ptr, ObstacleContainer* obstacles_ptr, ResultContainer* result_ptr, double sx, double sy, double sphi, double ex, double ey, double ephi, double* XYbounds) { apollo::planning::PlannerOpenSpaceConfig planner_open_space_config_; ACHECK(apollo::cyber::common::GetProtoFromFile( FLAGS_planner_open_space_config_filename, &planner_open_space_config_)) << "Failed to load open space config file " << FLAGS_planner_open_space_config_filename; AINFO << "FLAGS_planner_open_space_config_filename: " << FLAGS_planner_open_space_config_filename; double hybrid_total = 0.0; double dual_total = 0.0; double ipopt_total = 0.0; std::string flag_file_path = "/apollo/modules/planning/conf/planning.conf"; google::SetCommandLineOption("flagfile", flag_file_path.c_str()); HybridAStartResult hybrid_astar_result; std::vector<double> XYbounds_(XYbounds, XYbounds + 4); const auto start_timestamp = std::chrono::system_clock::now(); if (!hybridA_ptr->Plan(sx, sy, sphi, ex, ey, ephi, XYbounds_, obstacles_ptr->GetObstacleVec(), &hybrid_astar_result)) { AINFO << "Hybrid A Star fails"; return false; } const auto end_timestamp = std::chrono::system_clock::now(); std::chrono::duration<double> time_diff = end_timestamp - start_timestamp; hybrid_total = time_diff.count() * 1000; if (FLAGS_enable_parallel_trajectory_smoothing) { std::vector<HybridAStartResult> partition_trajectories; if (!hybridA_ptr->TrajectoryPartition(hybrid_astar_result, &partition_trajectories)) { return false; } size_t size = partition_trajectories.size(); std::vector<Eigen::MatrixXd> state_result_ds_vec; std::vector<Eigen::MatrixXd> control_result_ds_vec; std::vector<Eigen::MatrixXd> time_result_ds_vec; std::vector<Eigen::MatrixXd> dual_l_result_ds_vec; std::vector<Eigen::MatrixXd> dual_n_result_ds_vec; state_result_ds_vec.resize(size); control_result_ds_vec.resize(size); time_result_ds_vec.resize(size); dual_l_result_ds_vec.resize(size); dual_n_result_ds_vec.resize(size); std::vector<std::future<bool>> results; // In parallel // TODO(Jinyun): fix memory issue // for (size_t i = 0; i < size; ++i) { // double piece_wise_sx = partition_trajectories[i].x.front(); // double piece_wise_sy = partition_trajectories[i].y.front(); // double piece_wise_sphi = partition_trajectories[i].phi.front(); // double piece_wise_ex = partition_trajectories[i].x.back(); // double piece_wise_ey = partition_trajectories[i].y.back(); // double piece_wise_ephi = partition_trajectories[i].phi.back(); // auto* ith_trajectories = &partition_trajectories[i]; // auto* ith_state_result = &state_result_ds_vec[i]; // auto* ith_control_result = &control_result_ds_vec[i]; // auto* ith_time_result = &time_result_ds_vec[i]; // auto* ith_dual_l_result = &dual_l_result_ds_vec[i]; // auto* ith_dual_n_result = &dual_n_result_ds_vec[i]; // results.push_back( // cyber::Async(&DistanceSmoothing, // std::ref(planner_open_space_config_), // std::ref(*obstacles_ptr), piece_wise_sx, // piece_wise_sy, piece_wise_sphi, piece_wise_ex, // piece_wise_ey, piece_wise_ephi, std::ref(XYbounds_), // ith_trajectories, ith_state_result, // ith_control_result, ith_time_result, // ith_dual_l_result, ith_dual_n_result)); // } // for (auto& result : results) { // if (!result.get()) { // AERROR << "Failure in a piece of trajectory."; // return false; // } // } // In for loop double dual_tmp = 0.0; double ipopt_tmp = 0.0; for (size_t i = 0; i < size; ++i) { double piece_wise_sx = partition_trajectories[i].x.front(); double piece_wise_sy = partition_trajectories[i].y.front(); double piece_wise_sphi = partition_trajectories[i].phi.front(); double piece_wise_ex = partition_trajectories[i].x.back(); double piece_wise_ey = partition_trajectories[i].y.back(); double piece_wise_ephi = partition_trajectories[i].phi.back(); if (planner_open_space_config_.enable_check_parallel_trajectory()) { AINFO << "trajectory idx: " << i; AINFO << "trajectory pt number: " << partition_trajectories[i].x.size(); } if (!DistanceSmoothing(planner_open_space_config_, *obstacles_ptr, piece_wise_sx, piece_wise_sy, piece_wise_sphi, piece_wise_ex, piece_wise_ey, piece_wise_ephi, XYbounds_, &partition_trajectories[i], &state_result_ds_vec[i], &control_result_ds_vec[i], &time_result_ds_vec[i], &dual_l_result_ds_vec[i], &dual_n_result_ds_vec[i], dual_tmp, ipopt_tmp)) { return false; } dual_total += dual_tmp; ipopt_total += ipopt_tmp; } // Retrieve result in one single trajectory size_t trajectory_point_size = 0; for (size_t i = 0; i < size; ++i) { if (state_result_ds_vec[i].cols() < 2) { AERROR << "state horizon smaller than 2"; return false; } AINFO << "trajectory idx: " << "idx range: " << trajectory_point_size << ", " << trajectory_point_size + static_cast<size_t>(state_result_ds_vec[i].cols()) - 1; trajectory_point_size += static_cast<size_t>(state_result_ds_vec[i].cols()) - 1; } ++trajectory_point_size; const uint64_t state_dimension = state_result_ds_vec.front().rows(); Eigen::MatrixXd state_result_ds; state_result_ds.resize(state_dimension, trajectory_point_size); uint64_t k = 0; for (size_t i = 0; i < size; ++i) { // leave out the last repeated point so set column minus one uint64_t state_col_num = state_result_ds_vec[i].cols() - 1; for (uint64_t j = 0; j < state_col_num; ++j) { state_result_ds.col(k) = state_result_ds_vec[i].col(j); ++k; } } state_result_ds.col(k) = state_result_ds_vec.back().col(state_result_ds_vec.back().cols() - 1); const uint64_t control_dimension = control_result_ds_vec.front().rows(); Eigen::MatrixXd control_result_ds; control_result_ds.resize(control_dimension, trajectory_point_size - 1); k = 0; for (size_t i = 0; i < size; ++i) { uint64_t control_col_num = control_result_ds_vec[i].cols() - 1; for (uint64_t j = 0; j < control_col_num; ++j) { control_result_ds.col(k) = control_result_ds_vec[i].col(j); ++k; } } const uint64_t time_dimension = time_result_ds_vec.front().rows(); Eigen::MatrixXd time_result_ds; time_result_ds.resize(time_dimension, trajectory_point_size - 1); k = 0; for (size_t i = 0; i < size; ++i) { uint64_t time_col_num = time_result_ds_vec[i].cols() - 1; for (uint64_t j = 0; j < time_col_num; ++j) { time_result_ds.col(k) = time_result_ds_vec[i].col(j); ++k; } } *(result_ptr->PrepareHybridAResult()) = hybrid_astar_result; *(result_ptr->PrepareStateResult()) = state_result_ds; *(result_ptr->PrepareControlResult()) = control_result_ds; *(result_ptr->PrepareTimeResult()) = time_result_ds; *(result_ptr->GetHybridTime()) = hybrid_total; *(result_ptr->GetDualTime()) = dual_total; *(result_ptr->GetIpoptTime()) = ipopt_total; } else { Eigen::MatrixXd state_result_ds; Eigen::MatrixXd control_result_ds; Eigen::MatrixXd time_result_ds; Eigen::MatrixXd dual_l_result_ds; Eigen::MatrixXd dual_n_result_ds; if (!DistanceSmoothing(planner_open_space_config_, *obstacles_ptr, sx, sy, sphi, ex, ey, ephi, XYbounds_, &hybrid_astar_result, &state_result_ds, &control_result_ds, &time_result_ds, &dual_l_result_ds, &dual_n_result_ds, dual_total, ipopt_total)) { return false; } *(result_ptr->PrepareHybridAResult()) = hybrid_astar_result; *(result_ptr->PrepareStateResult()) = state_result_ds; *(result_ptr->PrepareControlResult()) = control_result_ds; *(result_ptr->PrepareTimeResult()) = time_result_ds; *(result_ptr->PrepareLResult()) = dual_l_result_ds; *(result_ptr->PrepareNResult()) = dual_n_result_ds; *(result_ptr->GetHybridTime()) = hybrid_total; *(result_ptr->GetDualTime()) = dual_total; *(result_ptr->GetIpoptTime()) = ipopt_total; } return true; } void DistanceGetResult(ResultContainer* result_ptr, ObstacleContainer* obstacles_ptr, double* x, double* y, double* phi, double* v, double* a, double* steer, double* opt_x, double* opt_y, double* opt_phi, double* opt_v, double* opt_a, double* opt_steer, double* opt_time, double* opt_dual_l, double* opt_dual_n, size_t* output_size, double* hybrid_time, double* dual_time, double* ipopt_time) { result_ptr->LoadHybridAResult(); size_t size = result_ptr->GetX()->size(); size_t size_by_distance = result_ptr->PrepareStateResult()->cols(); AERROR_IF(size != size_by_distance) << "sizes by hybrid A and distance approach not consistent"; for (size_t i = 0; i < size; ++i) { x[i] = result_ptr->GetX()->at(i); y[i] = result_ptr->GetY()->at(i); phi[i] = result_ptr->GetPhi()->at(i); v[i] = result_ptr->GetV()->at(i); } for (size_t i = 0; i + 1 < size; ++i) { a[i] = result_ptr->GetA()->at(i); steer[i] = result_ptr->GetSteer()->at(i); } output_size[0] = size; size_t obstacles_edges_sum = obstacles_ptr->GetObstaclesEdgesNum().sum(); size_t obstacles_num_to_car = 4 * obstacles_ptr->GetObstaclesNum(); for (size_t i = 0; i < size_by_distance; ++i) { opt_x[i] = (*(result_ptr->PrepareStateResult()))(0, i); opt_y[i] = (*(result_ptr->PrepareStateResult()))(1, i); opt_phi[i] = (*(result_ptr->PrepareStateResult()))(2, i); opt_v[i] = (*(result_ptr->PrepareStateResult()))(3, i); } if (result_ptr->PrepareTimeResult() != 0) { for (size_t i = 0; i + 1 < size_by_distance; ++i) { opt_time[i] = (*(result_ptr->PrepareTimeResult()))(0, i); } } if (result_ptr->PrepareLResult()->cols() != 0 && result_ptr->PrepareNResult() != 0) { for (size_t i = 0; i + 1 < size_by_distance; ++i) { for (size_t j = 0; j < obstacles_edges_sum; ++j) { opt_dual_l[i * obstacles_edges_sum + j] = (*(result_ptr->PrepareLResult()))(j, i); } for (size_t k = 0; k < obstacles_num_to_car; ++k) { opt_dual_n[i * obstacles_num_to_car + k] = (*(result_ptr->PrepareNResult()))(k, i); } } } for (size_t i = 0; i + 1 < size_by_distance; ++i) { opt_a[i] = (*(result_ptr->PrepareControlResult()))(1, i); opt_steer[i] = (*(result_ptr->PrepareControlResult()))(0, i); } hybrid_time[0] = *(result_ptr->GetHybridTime()); dual_time[0] = *(result_ptr->GetDualTime()); ipopt_time[0] = *(result_ptr->GetIpoptTime()); } }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/tools/open_space_roi_wrapper.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "Eigen/Dense" #include "cyber/common/file.h" #include "modules/common/math/box2d.h" #include "modules/common/math/vec2d.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/map/pnc_map/path.h" #include "modules/map/pnc_map/pnc_map.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/proto/planner_open_space_config.pb.h" namespace apollo { namespace planning { using apollo::common::math::Polygon2d; using apollo::common::math::Vec2d; using apollo::hdmap::HDMapUtil; using apollo::hdmap::LaneSegment; using apollo::hdmap::ParkingSpaceInfoConstPtr; using apollo::hdmap::Path; constexpr double kMathEpsilon = 1e-10; class OpenSpaceROITest { public: bool OpenSpaceROI() { // left or right of the parking lot is decided when viewing the parking spot // open upward Vec2d left_top = target_parking_spot_->polygon().points().at(3); Vec2d left_down = target_parking_spot_->polygon().points().at(0); Vec2d right_top = target_parking_spot_->polygon().points().at(2); Vec2d right_down = target_parking_spot_->polygon().points().at(1); double left_top_s = 0.0; double left_top_l = 0.0; double right_top_s = 0.0; double right_top_l = 0.0; if (!(nearby_path_->GetProjection(left_top, &left_top_s, &left_top_l) && nearby_path_->GetProjection(right_top, &right_top_s, &right_top_l))) { AERROR << "fail to get parking spot points' projections " "on reference line"; return false; } // start or end, left or right is decided by the vehicle's heading double center_line_s = (left_top_s + right_top_s) / 2; double start_s = center_line_s - planner_open_space_config_.roi_config().roi_longitudinal_range_start(); double end_s = center_line_s + planner_open_space_config_.roi_config().roi_longitudinal_range_end(); hdmap::MapPathPoint end_point = nearby_path_->GetSmoothPoint(end_s); hdmap::MapPathPoint start_point = nearby_path_->GetSmoothPoint(start_s); double start_left_width = nearby_path_->GetRoadLeftWidth(start_s); double start_right_width = nearby_path_->GetRoadRightWidth(start_s); double end_left_width = nearby_path_->GetRoadLeftWidth(end_s); double end_right_width = nearby_path_->GetRoadRightWidth(end_s); double start_right_vec_cos = std::cos(start_point.heading() - M_PI / 2); double start_right_vec_sin = std::sin(start_point.heading() - M_PI / 2); double start_left_vec_cos = std::cos(start_point.heading() + M_PI / 2); double start_left_vec_sin = std::sin(start_point.heading() + M_PI / 2); double end_right_vec_cos = std::cos(end_point.heading() - M_PI / 2); double end_right_vec_sin = std::sin(end_point.heading() - M_PI / 2); double end_left_vec_cos = std::cos(end_point.heading() + M_PI / 2); double end_left_vec_sin = std::sin(end_point.heading() + M_PI / 2); Vec2d start_right = Vec2d(start_right_width * start_right_vec_cos, start_right_width * start_right_vec_sin); start_right = start_right + start_point; Vec2d start_left = Vec2d(start_left_width * start_left_vec_cos, start_left_width * start_left_vec_sin); start_left = start_left + start_point; Vec2d end_right = Vec2d(end_right_width * end_right_vec_cos, end_right_width * end_right_vec_sin); end_right = end_right + end_point; Vec2d end_left = Vec2d(end_left_width * end_left_vec_cos, end_left_width * end_left_vec_sin); end_left = end_left + end_point; // rotate the points to have the lane to be horizontal to x axis and scale // them base on the origin point origin_heading_ = nearby_path_->GetSmoothPoint(center_line_s).heading(); origin_point_.set_x(left_top.x()); origin_point_.set_y(left_top.y()); left_top -= origin_point_; left_down -= origin_point_; right_top -= origin_point_; right_down -= origin_point_; start_right -= origin_point_; start_left -= origin_point_; end_right -= origin_point_; end_left -= origin_point_; AINFO << "left_down x " << left_down.x(); AINFO << "right_down x " << right_down.x(); AINFO << "left_top x " << left_top.x(); left_top.SelfRotate(-origin_heading_); left_down.SelfRotate(-origin_heading_); right_top.SelfRotate(-origin_heading_); right_down.SelfRotate(-origin_heading_); start_right.SelfRotate(-origin_heading_); start_left.SelfRotate(-origin_heading_); end_right.SelfRotate(-origin_heading_); end_left.SelfRotate(-origin_heading_); // get end_pose of the parking spot parking_spot_heading_ = (left_down - left_top).Angle(); double end_x = (left_top.x() + right_top.x()) / 2; double end_y = 0.0; if (parking_spot_heading_ > kMathEpsilon) { if (planner_open_space_config_.roi_config().parking_inwards()) { end_y = left_top.y() + (left_down.y() - left_top.y()) / 4; } else { end_y = left_top.y() + 3 * (left_down.y() - left_top.y()) / 4; } } else { if (planner_open_space_config_.roi_config().parking_inwards()) { end_y = left_down.y() + 3 * (left_top.y() - left_down.y()) / 4; } else { end_y = left_down.y() + (left_top.y() - left_down.y()) / 4; } } open_space_end_pose_.emplace_back(end_x); open_space_end_pose_.emplace_back(end_y); if (planner_open_space_config_.roi_config().parking_inwards()) { open_space_end_pose_.emplace_back(parking_spot_heading_); } else { open_space_end_pose_.emplace_back( common::math::NormalizeAngle(parking_spot_heading_ + M_PI)); } open_space_end_pose_.emplace_back(0.0); // get xy boundary of the ROI double x_min = std::min({start_left.x(), start_right.x()}); double x_max = std::max({end_left.x(), end_right.x()}); double y_min = std::min({left_down.y(), start_right.y(), start_left.y()}); double y_max = std::max({left_down.y(), start_right.y(), start_left.y()}); ROI_xy_boundary_.emplace_back(x_min); ROI_xy_boundary_.emplace_back(x_max); ROI_xy_boundary_.emplace_back(y_min); ROI_xy_boundary_.emplace_back(y_max); // If smaller than zero, the parking spot is on the right of the lane // Left, right, down or up of the boundary is decided when viewing the // parking spot upward std::vector<Vec2d> left_boundary; std::vector<Vec2d> down_boundary; std::vector<Vec2d> right_boundary; std::vector<Vec2d> up_boundary; if (left_top_l < 0) { start_right.set_x(-left_top_l * start_right_vec_cos); start_right.set_y(-left_top_l * start_right_vec_sin); start_right = start_right + start_point; end_right.set_x(-left_top_l * end_right_vec_cos); end_right.set_y(-left_top_l * end_right_vec_sin); end_right = end_right + end_point; start_right -= origin_point_; end_right -= origin_point_; start_right.SelfRotate(-origin_heading_); end_right.SelfRotate(-origin_heading_); left_boundary.push_back(start_right); left_boundary.push_back(left_top); left_boundary.push_back(left_down); down_boundary.push_back(left_down); down_boundary.push_back(right_down); right_boundary.push_back(right_down); right_boundary.push_back(right_top); right_boundary.push_back(end_right); up_boundary.push_back(end_left); up_boundary.push_back(start_left); } else { start_left.set_x(left_top_l * start_left_vec_cos); start_left.set_y(left_top_l * start_left_vec_sin); start_left = start_left + start_point; end_left.set_x(left_top_l * end_left_vec_cos); end_left.set_y(left_top_l * end_left_vec_sin); end_left = end_left + end_point; start_left -= origin_point_; end_left -= origin_point_; start_left.SelfRotate(-origin_heading_); end_left.SelfRotate(-origin_heading_); left_boundary.push_back(end_left); left_boundary.push_back(left_top); left_boundary.push_back(left_down); down_boundary.push_back(left_down); down_boundary.push_back(right_down); right_boundary.push_back(right_down); right_boundary.push_back(right_top); right_boundary.push_back(start_left); up_boundary.push_back(start_right); up_boundary.push_back(end_right); } ROI_parking_boundary_.emplace_back(left_boundary); ROI_parking_boundary_.emplace_back(down_boundary); ROI_parking_boundary_.emplace_back(right_boundary); ROI_parking_boundary_.emplace_back(up_boundary); return true; } bool NoRotateOpenSpaceROI() { // left or right of the parking lot is decided when viewing the parking spot // open upward Vec2d left_top = target_parking_spot_->polygon().points().at(3); Vec2d left_down = target_parking_spot_->polygon().points().at(0); Vec2d right_top = target_parking_spot_->polygon().points().at(2); Vec2d right_down = target_parking_spot_->polygon().points().at(1); double left_top_s = 0.0; double left_top_l = 0.0; double right_top_s = 0.0; double right_top_l = 0.0; if (!(nearby_path_->GetProjection(left_top, &left_top_s, &left_top_l) && nearby_path_->GetProjection(right_top, &right_top_s, &right_top_l))) { AERROR << "fail to get parking spot points' projections " "on reference line"; return false; } // start or end, left or right is decided by the vehicle's heading double center_line_s = (left_top_s + right_top_s) / 2; double start_s = center_line_s - planner_open_space_config_.roi_config().roi_longitudinal_range_start(); double end_s = center_line_s + planner_open_space_config_.roi_config().roi_longitudinal_range_end(); hdmap::MapPathPoint end_point = nearby_path_->GetSmoothPoint(end_s); hdmap::MapPathPoint start_point = nearby_path_->GetSmoothPoint(start_s); double start_left_width = nearby_path_->GetRoadLeftWidth(start_s); double start_right_width = nearby_path_->GetRoadRightWidth(start_s); double end_left_width = nearby_path_->GetRoadLeftWidth(end_s); double end_right_width = nearby_path_->GetRoadRightWidth(end_s); double start_right_vec_cos = std::cos(start_point.heading() - M_PI / 2); double start_right_vec_sin = std::sin(start_point.heading() - M_PI / 2); double start_left_vec_cos = std::cos(start_point.heading() + M_PI / 2); double start_left_vec_sin = std::sin(start_point.heading() + M_PI / 2); double end_right_vec_cos = std::cos(end_point.heading() - M_PI / 2); double end_right_vec_sin = std::sin(end_point.heading() - M_PI / 2); double end_left_vec_cos = std::cos(end_point.heading() + M_PI / 2); double end_left_vec_sin = std::sin(end_point.heading() + M_PI / 2); Vec2d start_right = Vec2d(start_right_width * start_right_vec_cos, start_right_width * start_right_vec_sin); start_right = start_right + start_point; Vec2d start_left = Vec2d(start_left_width * start_left_vec_cos, start_left_width * start_left_vec_sin); start_left = start_left + start_point; Vec2d end_right = Vec2d(end_right_width * end_right_vec_cos, end_right_width * end_right_vec_sin); end_right = end_right + end_point; Vec2d end_left = Vec2d(end_left_width * end_left_vec_cos, end_left_width * end_left_vec_sin); end_left = end_left + end_point; // get end_pose of the parking spot double heading = (left_down - left_top).Angle(); double x = (left_top.x() + right_top.x()) / 2; double y = 0.0; if (heading > kMathEpsilon) { y = left_top.y() + (-left_top.y() + left_down.y()) / 4; } else { y = left_down.y() + 3 * (left_top.y() - left_down.y()) / 4; } open_space_end_pose_.emplace_back(x); open_space_end_pose_.emplace_back(y); open_space_end_pose_.emplace_back(heading); open_space_end_pose_.emplace_back(0.0); // get xy boundary of the ROI double x_min = std::min({start_left.x(), start_right.x()}); double x_max = std::max({end_left.x(), end_right.x()}); double y_min = std::min({left_down.y(), start_right.y(), start_left.y()}); double y_max = std::max({left_down.y(), start_right.y(), start_left.y()}); ROI_xy_boundary_.emplace_back(x_min); ROI_xy_boundary_.emplace_back(x_max); ROI_xy_boundary_.emplace_back(y_min); ROI_xy_boundary_.emplace_back(y_max); // If smaller than zero, the parking spot is on the right of the lane // Left, right, down or up of the boundary is decided when viewing the // parking spot upward std::vector<Vec2d> left_boundary; std::vector<Vec2d> down_boundary; std::vector<Vec2d> right_boundary; std::vector<Vec2d> up_boundary; if (left_top_l < 0) { start_right.set_x(-left_top_l * start_right_vec_cos); start_right.set_y(-left_top_l * start_right_vec_sin); start_right = start_right + start_point; end_right.set_x(-left_top_l * end_right_vec_cos); end_right.set_y(-left_top_l * end_right_vec_sin); end_right = end_right + end_point; left_boundary.push_back(start_right); left_boundary.push_back(left_top); left_boundary.push_back(left_down); down_boundary.push_back(left_down); down_boundary.push_back(right_down); right_boundary.push_back(right_down); right_boundary.push_back(right_top); right_boundary.push_back(end_right); up_boundary.push_back(end_left); up_boundary.push_back(start_left); } else { start_left.set_x(left_top_l * start_left_vec_cos); start_left.set_y(left_top_l * start_left_vec_sin); start_left = start_left + start_point; end_left.set_x(left_top_l * end_left_vec_cos); end_left.set_y(left_top_l * end_left_vec_sin); end_left = end_left + end_point; left_boundary.push_back(end_left); left_boundary.push_back(left_top); left_boundary.push_back(left_down); down_boundary.push_back(left_down); down_boundary.push_back(right_down); right_boundary.push_back(right_down); right_boundary.push_back(right_top); right_boundary.push_back(start_left); up_boundary.push_back(start_right); up_boundary.push_back(end_right); } No_rotate_ROI_parking_boundary_.emplace_back(left_boundary); No_rotate_ROI_parking_boundary_.emplace_back(down_boundary); No_rotate_ROI_parking_boundary_.emplace_back(right_boundary); No_rotate_ROI_parking_boundary_.emplace_back(up_boundary); return true; } bool VPresentationObstacle(const std::string& lane_id, const std::string& parking_id) { if (!LoadMap(lane_id, parking_id)) { AINFO << "fail at loading map"; return false; } ACHECK(cyber::common::GetProtoFromFile( FLAGS_planner_open_space_config_filename, &planner_open_space_config_)) << "Failed to load open space config file " << FLAGS_planner_open_space_config_filename; // load info from pnc map if (!OpenSpaceROI()) { AINFO << "fail at ROI()"; return false; } if (!NoRotateOpenSpaceROI()) { AINFO << "fail at ROI()"; return false; } size_t parking_boundaries_num = ROI_parking_boundary_.size(); if (parking_boundaries_num != 4) { AERROR << "parking boundary obstacles size not right"; return false; } obstacles_num_ = parking_boundaries_num; // load vertice vector for distance approach Eigen::MatrixXd parking_boundaries_obstacles_edges_num(4, 1); // the order is decided by the ROI() parking_boundaries_obstacles_edges_num << 2, 1, 2, 1; obstacles_edges_num_.resize(parking_boundaries_obstacles_edges_num.rows(), 1); obstacles_edges_num_ << parking_boundaries_obstacles_edges_num; return true; } bool LoadPathBoundary() { return true; } bool LoadMap(const std::string& lane_id, const std::string& parking_id) { std::cout << lane_id << std::endl; std::cout << parking_id << std::endl; auto map_ptr = HDMapUtil::BaseMapPtr(); hdmap::Id nearby_lane_id; nearby_lane_id.set_id(lane_id); hdmap::Id target_lane_id; target_lane_id.set_id(parking_id); auto nearby_lane = map_ptr->GetLaneById(nearby_lane_id); if (nearby_lane == nullptr) { std::cout << "No such lane found " << lane_id << std::endl; return false; } std::cout << "the lane found is " << nearby_lane->id().id() << std::endl; LaneSegment nearby_lanesegment = LaneSegment(nearby_lane, nearby_lane->accumulate_s().front(), nearby_lane->accumulate_s().back()); std::vector<LaneSegment> segments_vector; segments_vector.push_back(nearby_lanesegment); nearby_path_ = std::unique_ptr<Path>(new Path(segments_vector)); const auto& parking_space_overlaps = nearby_path_->parking_space_overlaps(); if (parking_space_overlaps.empty()) { std::cout << "No parking overlaps found on the lane requested" << std::endl; return false; } for (const auto parking_overlap : parking_space_overlaps) { if (parking_overlap.object_id != parking_id) { target_parking_spot_ = map_ptr->GetParkingSpaceById(target_lane_id); std::cout << "parking_overlap.object_id is " << target_lane_id.id() << std::endl; } } if (target_parking_spot_ == nullptr) { std::cout << "No such parking spot found " << parking_id << std::endl; return false; } parking_spot_box_ = target_parking_spot_->polygon(); return true; } std::vector<double>* GetROIXYBoundary() { return &ROI_xy_boundary_; } std::vector<std::vector<Vec2d>>* GetROIParkingBoundary() { return &ROI_parking_boundary_; } std::vector<std::vector<Vec2d>>* GetNoRotateROIParkingBoundary() { return &No_rotate_ROI_parking_boundary_; } std::vector<double>* GetEndPose() { return &open_space_end_pose_; } double GetOriginHeading() { return origin_heading_; } Vec2d GetOriginPose() { return origin_point_; } Polygon2d GetParkingSpotBox() { return parking_spot_box_; } private: apollo::planning::PlannerOpenSpaceConfig planner_open_space_config_; ParkingSpaceInfoConstPtr target_parking_spot_ = nullptr; Polygon2d parking_spot_box_; std::unique_ptr<Path> nearby_path_ = nullptr; size_t obstacles_num_ = 0; Eigen::MatrixXd obstacles_edges_num_; std::vector<double> ROI_xy_boundary_; std::vector<std::vector<Vec2d>> ROI_parking_boundary_; std::vector<std::vector<Vec2d>> No_rotate_ROI_parking_boundary_; std::vector<double> open_space_end_pose_; double origin_heading_; Vec2d origin_point_; double parking_spot_heading_; }; extern "C" { OpenSpaceROITest* CreateROITestPtr() { return new OpenSpaceROITest(); } // all data in form of array bool ROITest(OpenSpaceROITest* test_ptr, char* lane_id, char* parking_id, double* unrotated_roi_boundary_x, double* unrotated_roi_boundary_y, double* roi_boundary_x, double* roi_boundary_y, double* parking_spot_x, double* parking_spot_y, double* end_pose, double* xy_boundary, double* origin_pose) { std::string lane_id_str(lane_id); std::string parking_id_str(parking_id); if (!test_ptr->VPresentationObstacle(lane_id_str, parking_id_str)) { AINFO << "VPresentationObstacle fail"; return false; } std::vector<std::vector<Vec2d>>* unrotated_roi_boundary_ = test_ptr->GetNoRotateROIParkingBoundary(); std::vector<std::vector<Vec2d>>* roi_boundary_ = test_ptr->GetROIParkingBoundary(); Polygon2d parking_spot_ = test_ptr->GetParkingSpotBox(); std::vector<double>* end_pose_ = test_ptr->GetEndPose(); std::vector<double>* xy_boundary_ = test_ptr->GetROIXYBoundary(); double origin_heading_ = test_ptr->GetOriginHeading(); Vec2d origin_point_ = test_ptr->GetOriginPose(); // load all into array size_t index = 0; for (size_t i = 0; i < unrotated_roi_boundary_->size(); i++) { std::vector<Vec2d> boundary = unrotated_roi_boundary_->at(i); for (size_t j = 0; j < boundary.size(); j++) { unrotated_roi_boundary_x[index] = boundary[j].x(); unrotated_roi_boundary_y[index] = boundary[j].y(); index++; } } index = 0; for (size_t i = 0; i < roi_boundary_->size(); i++) { std::vector<Vec2d> boundary = roi_boundary_->at(i); for (size_t j = 0; j < boundary.size(); j++) { roi_boundary_x[index] = boundary[j].x(); roi_boundary_y[index] = boundary[j].y(); index++; } } index = 0; std::vector<Vec2d> parking_spot_vec_ = parking_spot_.points(); for (size_t i = 0; i < parking_spot_vec_.size(); i++) { parking_spot_x[index] = parking_spot_vec_[i].x(); parking_spot_y[index] = parking_spot_vec_[i].y(); index++; } for (size_t i = 0; i < end_pose_->size(); i++) { end_pose[i] = end_pose_->at(i); } for (size_t i = 0; i < xy_boundary_->size(); i++) { xy_boundary[i] = xy_boundary_->at(i); } // x, y, heading origin_pose[0] = origin_point_.x(); origin_pose[1] = origin_point_.y(); origin_pose[2] = origin_heading_; return true; } }; } // namespace planning } // namespace apollo
0