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
apollo_public_repos/apollo/modules/planning/common/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 = "indexed_list", hdrs = ["indexed_list.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/util:util_tool", "@boost", ], ) cc_test( name = "indexed_list_test", size = "small", srcs = ["indexed_list_test.cc"], deps = [ ":indexed_list", "//modules/common/util", "@boost", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "indexed_queue", hdrs = ["indexed_queue.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/util:util_tool", ], ) cc_test( name = "indexed_queue_test", size = "small", srcs = ["indexed_queue_test.cc"], deps = [ ":indexed_queue", "//modules/common/util", "@com_google_googletest//:gtest_main", ], ) filegroup( name = "common_testdata", srcs = glob([ "testdata/**", ]), ) cc_library( name = "obstacle", srcs = ["obstacle.cc"], hdrs = ["obstacle.h"], copts = PLANNING_COPTS, deps = [ ":indexed_list", "//modules/common/configs:vehicle_config_helper", "//modules/common/util:util_tool", "//modules/planning/common/speed:st_boundary", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/reference_line", "//modules/common_msgs/prediction_msgs:feature_cc_proto", "//modules/common_msgs/prediction_msgs:lane_graph_cc_proto", "//modules/common_msgs/prediction_msgs:prediction_obstacle_cc_proto", "//modules/common_msgs/prediction_msgs:prediction_point_cc_proto", "//modules/common_msgs/prediction_msgs:scenario_cc_proto", ], ) cc_test( name = "obstacle_test", size = "small", srcs = ["obstacle_test.cc"], data = [ "//modules/planning/common:common_testdata", ], deps = [ ":obstacle", "//modules/common/util", "//modules/common_msgs/perception_msgs:perception_lane_cc_proto", "@boost", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "obstacle_blocking_analyzer", srcs = ["obstacle_blocking_analyzer.cc"], hdrs = ["obstacle_blocking_analyzer.h"], copts = PLANNING_COPTS, deps = [ ":frame", "//modules/common/configs:vehicle_config_helper", "//modules/planning/reference_line", ], ) cc_library( name = "path_boundary", srcs = ["path_boundary.cc"], hdrs = ["path_boundary.h"], ) cc_library( name = "planning_context", srcs = ["planning_context.cc"], hdrs = ["planning_context.h"], copts = PLANNING_COPTS, deps = [ "//cyber", "//modules/planning/common/path:path_data", "//modules/planning/proto:planning_status_cc_proto", "@eigen", ], ) cc_library( name = "path_decision", srcs = ["path_decision.cc"], hdrs = ["path_decision.h"], copts = PLANNING_COPTS, deps = [ ":obstacle", "//modules/planning/reference_line", ], ) cc_library( name = "planning_gflags", srcs = ["planning_gflags.cc"], hdrs = ["planning_gflags.h"], copts = PLANNING_COPTS, deps = [ "@com_github_gflags_gflags//:gflags", ], ) cc_library( name = "reference_line_info", srcs = ["reference_line_info.cc"], hdrs = ["reference_line_info.h"], copts = PLANNING_COPTS, deps = [ ":ego_info", ":path_boundary", ":path_decision", ":planning_gflags", ":st_graph_data", "//cyber", "//modules/common/math", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/util", "//modules/common/vehicle_state:vehicle_state_provider", "//modules/map/pnc_map", "//modules/common_msgs/map_msgs:map_cc_proto", "//modules/planning/common/path:path_data", "//modules/planning/common/speed:speed_data", "//modules/planning/common/trajectory:discretized_trajectory", "//modules/planning/common/trajectory:publishable_trajectory", "//modules/planning/proto:lattice_structure_cc_proto", "//modules/planning/reference_line", "@eigen", ], ) cc_test( name = "reference_line_info_test", size = "small", srcs = ["reference_line_info_test.cc"], deps = [ ":reference_line_info", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "speed_profile_generator", srcs = ["speed_profile_generator.cc"], hdrs = ["speed_profile_generator.h"], copts = PLANNING_COPTS, deps = [ ":frame", ":reference_line_info", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/planning/common/speed:speed_data", "//modules/planning/math/curve1d", "//modules/planning/math/curve1d:polynomial_curve1d", "//modules/planning/math/curve1d:quartic_polynomial_curve1d", "//modules/planning/math/curve1d:quintic_polynomial_curve1d", "//modules/planning/math/piecewise_jerk:piecewise_jerk_speed_problem", "//modules/planning/proto:planning_config_cc_proto", ], ) cc_test( name = "speed_profile_generator_test", size = "small", srcs = ["speed_profile_generator_test.cc"], deps = [ ":speed_profile_generator", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "local_view", hdrs = ["local_view.h"], copts = PLANNING_COPTS, deps = [ "//modules/common_msgs/chassis_msgs:chassis_cc_proto", "//modules/common_msgs/localization_msgs:localization_cc_proto", "//modules/common_msgs/planning_msgs:navigation_cc_proto", "//modules/common_msgs/perception_msgs:traffic_light_detection_cc_proto", "//modules/common_msgs/planning_msgs:pad_msg_cc_proto", "//modules/common_msgs/prediction_msgs:prediction_obstacle_cc_proto", "//modules/common_msgs/routing_msgs:routing_cc_proto", "//modules/common_msgs/storytelling_msgs:story_cc_proto", ], ) cc_library( name = "frame", srcs = ["frame.cc"], hdrs = ["frame.h"], copts = PLANNING_COPTS, deps = [ ":feature_output", ":local_view", ":obstacle", ":open_space_info", ":reference_line_info", "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common/monitor_log", "//modules/common/vehicle_state:vehicle_state_provider", "//modules/map/hdmap:hdmap_util", "//modules/map/pnc_map", "//modules/planning/common/trajectory:discretized_trajectory", "//modules/planning/common/trajectory:publishable_trajectory", "//modules/planning/common/util:util_lib", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/proto:planning_config_cc_proto", "//modules/planning/reference_line:reference_line_provider", "@eigen", ], ) cc_test( name = "frame_test", size = "small", srcs = ["frame_test.cc"], data = [ "//modules/planning/common:common_testdata", ], deps = [ ":frame", "//modules/common/util", "//modules/map/hdmap:hdmap_util", "//modules/planning/proto:planning_config_cc_proto", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "history", srcs = ["history.cc"], hdrs = ["history.h"], copts = PLANNING_COPTS, deps = [ ":planning_gflags", "//cyber", "//modules/common_msgs/planning_msgs:decision_cc_proto", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@eigen", ], ) cc_test( name = "history_test", size = "small", srcs = ["history_test.cc"], deps = [ ":history", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "speed_limit", srcs = ["speed_limit.cc"], hdrs = ["speed_limit.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/math", ], ) cc_test( name = "speed_limit_test", size = "small", srcs = ["speed_limit_test.cc"], deps = [ ":speed_limit", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "ego_info", srcs = ["ego_info.cc"], hdrs = ["ego_info.h"], copts = PLANNING_COPTS, deps = [ ":obstacle", "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common_msgs/config_msgs:vehicle_config_cc_proto", "//modules/common/math", "//modules/common/vehicle_state/proto:vehicle_state_cc_proto", "//modules/planning/reference_line", "//modules/common_msgs/prediction_msgs:feature_cc_proto", "//modules/common_msgs/prediction_msgs:lane_graph_cc_proto", "//modules/common_msgs/prediction_msgs:prediction_obstacle_cc_proto", "//modules/common_msgs/prediction_msgs:prediction_point_cc_proto", "//modules/common_msgs/prediction_msgs:scenario_cc_proto", "@eigen", ], ) cc_test( name = "ego_info_test", size = "small", srcs = ["ego_info_test.cc"], deps = [ ":ego_info", ":frame", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "planning_common", copts = PLANNING_COPTS, deps = [ ":ego_info", ":frame", ":planning_gflags", ":speed_limit", ":st_graph_data", "//cyber", "//modules/common_msgs/localization_msgs:localization_cc_proto", "@eigen", ], ) cc_library( name = "trajectory_stitcher", srcs = ["trajectory_stitcher.cc"], hdrs = ["trajectory_stitcher.h"], copts = PLANNING_COPTS, deps = [ "//cyber", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/vehicle_model", "//modules/planning/common:planning_gflags", "//modules/planning/common/trajectory:publishable_trajectory", "//modules/planning/reference_line", "@com_google_absl//:absl", ], ) cc_library( name = "open_space_info", srcs = ["open_space_info.cc"], hdrs = ["open_space_info.h"], deps = [ "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common/vehicle_state/proto:vehicle_state_cc_proto", "//modules/map/hdmap:hdmap_util", "//modules/map/pnc_map", "//modules/planning/common:indexed_queue", "//modules/planning/common:obstacle", "//modules/planning/common:planning_gflags", "//modules/planning/common/trajectory:discretized_trajectory", "//modules/planning/common/trajectory:publishable_trajectory", "@eigen", ], ) cc_test( name = "open_space_info_test", size = "small", srcs = ["open_space_info_test.cc"], deps = [ "open_space_info", "@boost", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "st_graph_data", srcs = ["st_graph_data.cc"], hdrs = ["st_graph_data.h"], copts = PLANNING_COPTS, deps = [ ":planning_gflags", ":speed_limit", "//modules/planning/common/speed:st_boundary", "//modules/planning/proto:st_drivable_boundary_cc_proto", ], ) cc_test( name = "st_graph_data_test", size = "small", srcs = ["st_graph_data_test.cc"], deps = [ ":st_graph_data", "//cyber", "//modules/common/util", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "feature_output", srcs = ["feature_output.cc"], hdrs = ["feature_output.h"], copts = PLANNING_COPTS, deps = [ "//cyber", "//modules/common/util", "//modules/planning/common:planning_gflags", "//modules/planning/proto:learning_data_cc_proto", ], ) cc_library( name = "message_process", srcs = ["message_process.cc"], hdrs = ["message_process.h"], copts = PLANNING_COPTS, deps = [ ":dependency_injector", ":feature_output", "//cyber", "//modules/common_msgs/chassis_msgs:chassis_cc_proto", "//modules/common/adapters:adapter_gflags", "//modules/common/configs:config_gflags", "//modules/common_msgs/dreamview_msgs:hmi_status_cc_proto", "//modules/common_msgs/localization_msgs:localization_cc_proto", "//modules/common_msgs/perception_msgs:perception_obstacle_cc_proto", "//modules/common_msgs/perception_msgs:traffic_light_detection_cc_proto", "//modules/planning/common/util:math_util_lib", "//modules/planning/common/util:util_lib", "//modules/planning/proto:learning_data_cc_proto", "//modules/common_msgs/prediction_msgs:prediction_obstacle_cc_proto", "//modules/common/util:util_tool", "//modules/common_msgs/routing_msgs:routing_cc_proto", "//modules/common_msgs/storytelling_msgs:story_cc_proto", "@boost", "@com_google_absl//:absl", ], ) cc_library( name = "trajectory_evaluator", srcs = ["trajectory_evaluator.cc"], hdrs = ["trajectory_evaluator.h"], copts = PLANNING_COPTS, deps = [ "//cyber", "//modules/planning/common:planning_gflags", "//modules/planning/common/util:util_lib", "//modules/planning/pipeline:evaluator_logger", "//modules/planning/proto:learning_data_cc_proto", ], ) cc_library( name = "dependency_injector", hdrs = ["dependency_injector.h"], copts = PLANNING_COPTS, deps = [ ":ego_info", ":frame", ":history", ":learning_based_data", ":planning_context", ], ) cc_library( name = "learning_based_data", srcs = ["learning_based_data.cc"], hdrs = ["learning_based_data.h"], copts = PLANNING_COPTS, deps = [ "//cyber", "//modules/planning/proto:learning_data_cc_proto", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/common/path_decision.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/common/path_decision.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/util/util.h" #include "modules/common_msgs/perception_msgs/perception_obstacle.pb.h" namespace apollo { namespace planning { Obstacle *PathDecision::AddObstacle(const Obstacle &obstacle) { return obstacles_.Add(obstacle.Id(), obstacle); } const IndexedObstacles &PathDecision::obstacles() const { return obstacles_; } Obstacle *PathDecision::Find(const std::string &object_id) { return obstacles_.Find(object_id); } const Obstacle *PathDecision::Find(const std::string &object_id) const { return obstacles_.Find(object_id); } const perception::PerceptionObstacle *PathDecision::FindPerceptionObstacle( const std::string &perception_obstacle_id) const { for (const auto *obstacle : obstacles_.Items()) { if (std::to_string(obstacle->Perception().id()) == perception_obstacle_id) { return &(obstacle->Perception()); } } return nullptr; } void PathDecision::SetSTBoundary(const std::string &id, const STBoundary &boundary) { auto *obstacle = obstacles_.Find(id); if (!obstacle) { AERROR << "Failed to find obstacle : " << id; return; } else { obstacle->set_path_st_boundary(boundary); } } bool PathDecision::AddLateralDecision(const std::string &tag, const std::string &object_id, const ObjectDecisionType &decision) { auto *obstacle = obstacles_.Find(object_id); if (!obstacle) { AERROR << "failed to find obstacle"; return false; } obstacle->AddLateralDecision(tag, decision); return true; } void PathDecision::EraseStBoundaries() { for (const auto *obstacle : obstacles_.Items()) { auto *obstacle_ptr = obstacles_.Find(obstacle->Id()); obstacle_ptr->EraseStBoundary(); } } bool PathDecision::AddLongitudinalDecision(const std::string &tag, const std::string &object_id, const ObjectDecisionType &decision) { auto *obstacle = obstacles_.Find(object_id); if (!obstacle) { AERROR << "failed to find obstacle"; return false; } obstacle->AddLongitudinalDecision(tag, decision); return true; } bool PathDecision::MergeWithMainStop(const ObjectStop &obj_stop, const std::string &obj_id, const ReferenceLine &reference_line, const SLBoundary &adc_sl_boundary) { common::PointENU stop_point = obj_stop.stop_point(); common::SLPoint stop_line_sl; reference_line.XYToSL(stop_point, &stop_line_sl); double stop_line_s = stop_line_sl.s(); if (stop_line_s < 0.0 || stop_line_s > reference_line.Length()) { AERROR << "Ignore object:" << obj_id << " fence route_s[" << stop_line_s << "] not in range[0, " << reference_line.Length() << "]"; return false; } // check stop_line_s vs adc_s, ignore if it is further way than main stop const auto &vehicle_config = common::VehicleConfigHelper::GetConfig(); stop_line_s = std::fmax( stop_line_s, adc_sl_boundary.end_s() - vehicle_config.vehicle_param().front_edge_to_center()); if (stop_line_s >= stop_reference_line_s_) { ADEBUG << "stop point is farther than current main stop point."; return false; } main_stop_.Clear(); main_stop_.set_reason_code(obj_stop.reason_code()); main_stop_.set_reason("stop by " + obj_id); main_stop_.mutable_stop_point()->set_x(obj_stop.stop_point().x()); main_stop_.mutable_stop_point()->set_y(obj_stop.stop_point().y()); main_stop_.set_stop_heading(obj_stop.stop_heading()); stop_reference_line_s_ = stop_line_s; ADEBUG << " main stop obstacle id:" << obj_id << " stop_line_s:" << stop_line_s << " stop_point: (" << obj_stop.stop_point().x() << obj_stop.stop_point().y() << " ) stop_heading: " << obj_stop.stop_heading(); return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/common/obstacle.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 <list> #include <memory> #include <string> #include <unordered_map> #include <vector> #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/math/box2d.h" #include "modules/common/math/vec2d.h" #include "modules/common_msgs/perception_msgs/perception_obstacle.pb.h" #include "modules/planning/common/indexed_list.h" #include "modules/planning/common/speed/st_boundary.h" #include "modules/common_msgs/planning_msgs/decision.pb.h" #include "modules/common_msgs/planning_msgs/sl_boundary.pb.h" #include "modules/planning/reference_line/reference_line.h" #include "modules/common_msgs/prediction_msgs/prediction_obstacle.pb.h" namespace apollo { namespace planning { /** * @class Obstacle * @brief This is the class that associates an Obstacle with its path * properties. An obstacle's path properties relative to a path. * The `s` and `l` values are examples of path properties. * The decision of an obstacle is also associated with a path. * * The decisions have two categories: lateral decision and longitudinal * decision. * Lateral decision includes: nudge, ignore. * Lateral decision safety priority: nudge > ignore. * Longitudinal decision includes: stop, yield, follow, overtake, ignore. * Decision safety priorities order: stop > yield >= follow > overtake > ignore * * Ignore decision belongs to both lateral decision and longitudinal decision, * and it has the lowest priority. */ class Obstacle { public: Obstacle() = default; Obstacle(const std::string& id, const perception::PerceptionObstacle& perception_obstacle, const prediction::ObstaclePriority::Priority& obstacle_priority, const bool is_static); Obstacle(const std::string& id, const perception::PerceptionObstacle& perception_obstacle, const prediction::Trajectory& trajectory, const prediction::ObstaclePriority::Priority& obstacle_priority, const bool is_static); const std::string& Id() const { return id_; } void SetId(const std::string& id) { id_ = id; } double speed() const { return speed_; } int32_t PerceptionId() const { return perception_id_; } bool IsStatic() const { return is_static_; } bool IsVirtual() const { return is_virtual_; } common::TrajectoryPoint GetPointAtTime(const double time) const; common::math::Box2d GetBoundingBox( const common::TrajectoryPoint& point) const; const common::math::Box2d& PerceptionBoundingBox() const { return perception_bounding_box_; } const common::math::Polygon2d& PerceptionPolygon() const { return perception_polygon_; } const prediction::Trajectory& Trajectory() const { return trajectory_; } common::TrajectoryPoint* AddTrajectoryPoint() { return trajectory_.add_trajectory_point(); } bool HasTrajectory() const { return !(trajectory_.trajectory_point().empty()); } const perception::PerceptionObstacle& Perception() const { return perception_obstacle_; } /** * @brief This is a helper function that can create obstacles from prediction * data. The original prediction may have multiple trajectories for each * obstacle. But this function will create one obstacle for each trajectory. * @param predictions The prediction results * @return obstacles The output obstacles saved in a list of unique_ptr. */ static std::list<std::unique_ptr<Obstacle>> CreateObstacles( const prediction::PredictionObstacles& predictions); static std::unique_ptr<Obstacle> CreateStaticVirtualObstacles( const std::string& id, const common::math::Box2d& obstacle_box); static bool IsValidPerceptionObstacle( const perception::PerceptionObstacle& obstacle); static bool IsValidTrajectoryPoint(const common::TrajectoryPoint& point); inline bool IsCautionLevelObstacle() const { return is_caution_level_obstacle_; } // const Obstacle* obstacle() const; /** * return the merged lateral decision * Lateral decision is one of {Nudge, Ignore} **/ const ObjectDecisionType& LateralDecision() const; /** * @brief return the merged longitudinal decision * Longitudinal decision is one of {Stop, Yield, Follow, Overtake, Ignore} **/ const ObjectDecisionType& LongitudinalDecision() const; std::string DebugString() const; const SLBoundary& PerceptionSLBoundary() const; const STBoundary& reference_line_st_boundary() const; const STBoundary& path_st_boundary() const; const std::vector<std::string>& decider_tags() const; const std::vector<ObjectDecisionType>& decisions() const; void AddLongitudinalDecision(const std::string& decider_tag, const ObjectDecisionType& decision); void AddLateralDecision(const std::string& decider_tag, const ObjectDecisionType& decision); bool HasLateralDecision() const; void set_path_st_boundary(const STBoundary& boundary); bool is_path_st_boundary_initialized() { return path_st_boundary_initialized_; } void SetStBoundaryType(const STBoundary::BoundaryType type); void EraseStBoundary(); void SetReferenceLineStBoundary(const STBoundary& boundary); void SetReferenceLineStBoundaryType(const STBoundary::BoundaryType type); void EraseReferenceLineStBoundary(); bool HasLongitudinalDecision() const; bool HasNonIgnoreDecision() const; /** * @brief Calculate stop distance with the obstacle using the ADC's minimum * turning radius */ double MinRadiusStopDistance(const common::VehicleParam& vehicle_param) const; /** * @brief Check if this object can be safely ignored. * The object will be ignored if the lateral decision is ignore and the * longitudinal decision is ignore * return longitudinal_decision_ == ignore && lateral_decision == ignore. */ bool IsIgnore() const; bool IsLongitudinalIgnore() const; bool IsLateralIgnore() const; void BuildReferenceLineStBoundary(const ReferenceLine& reference_line, const double adc_start_s); void SetPerceptionSlBoundary(const SLBoundary& sl_boundary); /** * @brief check if an ObjectDecisionType is a longitudinal decision. **/ static bool IsLongitudinalDecision(const ObjectDecisionType& decision); /** * @brief check if an ObjectDecisionType is a lateral decision. **/ static bool IsLateralDecision(const ObjectDecisionType& decision); void SetBlockingObstacle(bool blocking) { is_blocking_obstacle_ = blocking; } bool IsBlockingObstacle() const { return is_blocking_obstacle_; } /* * @brief IsLaneBlocking is only meaningful when IsStatic() == true. */ bool IsLaneBlocking() const { return is_lane_blocking_; } void CheckLaneBlocking(const ReferenceLine& reference_line); bool IsLaneChangeBlocking() const { return is_lane_change_blocking_; } void SetLaneChangeBlocking(const bool is_distance_clear); private: FRIEND_TEST(MergeLongitudinalDecision, AllDecisions); static ObjectDecisionType MergeLongitudinalDecision( const ObjectDecisionType& lhs, const ObjectDecisionType& rhs); FRIEND_TEST(MergeLateralDecision, AllDecisions); static ObjectDecisionType MergeLateralDecision(const ObjectDecisionType& lhs, const ObjectDecisionType& rhs); bool BuildTrajectoryStBoundary(const ReferenceLine& reference_line, const double adc_start_s, STBoundary* const st_boundary); bool IsValidObstacle( const perception::PerceptionObstacle& perception_obstacle); private: std::string id_; int32_t perception_id_ = 0; bool is_static_ = false; bool is_virtual_ = false; double speed_ = 0.0; bool path_st_boundary_initialized_ = false; prediction::Trajectory trajectory_; perception::PerceptionObstacle perception_obstacle_; common::math::Box2d perception_bounding_box_; common::math::Polygon2d perception_polygon_; std::vector<ObjectDecisionType> decisions_; std::vector<std::string> decider_tags_; SLBoundary sl_boundary_; STBoundary reference_line_st_boundary_; STBoundary path_st_boundary_; ObjectDecisionType lateral_decision_; ObjectDecisionType longitudinal_decision_; // for keep_clear usage only bool is_blocking_obstacle_ = false; bool is_lane_blocking_ = false; bool is_lane_change_blocking_ = false; bool is_caution_level_obstacle_ = false; double min_radius_stop_distance_ = -1.0; struct ObjectTagCaseHash { size_t operator()( const planning::ObjectDecisionType::ObjectTagCase tag) const { return static_cast<size_t>(tag); } }; static const std::unordered_map<ObjectDecisionType::ObjectTagCase, int, ObjectTagCaseHash> s_lateral_decision_safety_sorter_; static const std::unordered_map<ObjectDecisionType::ObjectTagCase, int, ObjectTagCaseHash> s_longitudinal_decision_safety_sorter_; }; typedef IndexedList<std::string, Obstacle> IndexedObstacles; typedef ThreadSafeIndexedList<std::string, Obstacle> ThreadSafeIndexedObstacles; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/common/path_decision.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 <limits> #include <string> #include "modules/planning/common/indexed_list.h" #include "modules/planning/common/obstacle.h" #include "modules/common_msgs/planning_msgs/decision.pb.h" namespace apollo { namespace planning { /** * @class PathDecision * * @brief PathDecision represents all obstacle decisions on one path. */ class PathDecision { public: PathDecision() = default; Obstacle *AddObstacle(const Obstacle &obstacle); const IndexedList<std::string, Obstacle> &obstacles() const; bool AddLateralDecision(const std::string &tag, const std::string &object_id, const ObjectDecisionType &decision); bool AddLongitudinalDecision(const std::string &tag, const std::string &object_id, const ObjectDecisionType &decision); const Obstacle *Find(const std::string &object_id) const; const perception::PerceptionObstacle *FindPerceptionObstacle( const std::string &perception_obstacle_id) const; Obstacle *Find(const std::string &object_id); void SetSTBoundary(const std::string &id, const STBoundary &boundary); void EraseStBoundaries(); MainStop main_stop() const { return main_stop_; } double stop_reference_line_s() const { return stop_reference_line_s_; } bool MergeWithMainStop(const ObjectStop &obj_stop, const std::string &obj_id, const ReferenceLine &ref_line, const SLBoundary &adc_sl_boundary); private: IndexedList<std::string, Obstacle> obstacles_; MainStop main_stop_; double stop_reference_line_s_ = std::numeric_limits<double>::max(); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/common/indexed_queue.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 <queue> #include <unordered_map> #include <utility> #include "modules/common/util/map_util.h" namespace apollo { namespace planning { template <typename I, typename T> class IndexedQueue { public: // Get infinite capacity with 0. explicit IndexedQueue(size_t capacity) : capacity_(capacity) {} const T *Find(const I id) const { auto *result = apollo::common::util::FindOrNull(map_, id); return result ? result->get() : nullptr; } const T *Latest() const { if (queue_.empty()) { return nullptr; } return Find(queue_.back().first); } bool Add(const I id, std::unique_ptr<T> ptr) { if (Find(id)) { return false; } if (capacity_ > 0 && queue_.size() == capacity_) { map_.erase(queue_.front().first); queue_.pop(); } queue_.emplace(id, ptr.get()); map_[id] = std::move(ptr); return true; } void Clear() { while (!queue_.empty()) { queue_.pop(); } map_.clear(); } public: size_t capacity_ = 0; std::queue<std::pair<I, const T *>> queue_; std::unordered_map<I, std::unique_ptr<T>> map_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/common/planning_gflags.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/common/planning_gflags.h" #include <limits> DEFINE_bool(planning_test_mode, false, "Enable planning test mode."); DEFINE_int32(planning_loop_rate, 10, "Loop rate for planning node"); DEFINE_int32(history_max_record_num, 5, "the number of planning history frame to keep"); DEFINE_int32(max_frame_history_num, 1, "The maximum history frame number"); // scenario related DEFINE_string(scenario_bare_intersection_unprotected_config_file, "/apollo/modules/planning/conf/" "scenario/bare_intersection_unprotected_config.pb.txt", "The bare_intersection_unprotected scenario configuration file"); DEFINE_string(scenario_lane_follow_config_file, "/apollo/modules/planning/conf/" "scenario/lane_follow_config.pb.txt", "The lane_follow scenario configuration file"); DEFINE_string(scenario_lane_follow_hybrid_config_file, "/apollo/modules/planning/conf/" "scenario/lane_follow_hybrid_config.pb.txt", "The lane_follow scenario configuration file for HYBRID"); DEFINE_string(scenario_learning_model_sample_config_file, "/apollo/modules/planning/conf/" "scenario/learning_model_sample_config.pb.txt", "learning_model_sample scenario config file"); DEFINE_string(scenario_narrow_street_u_turn_config_file, "/apollo/modules/planning/conf/" "scenario/narrow_street_u_turn_config.pb.txt", "narrow_street_u_turn scenario config file"); DEFINE_string(scenario_park_and_go_config_file, "/apollo/modules/planning/conf/" "scenario/park_and_go_config.pb.txt", "park_and_go scenario config file"); DEFINE_string(scenario_pull_over_config_file, "/apollo/modules/planning/conf/" "scenario/pull_over_config.pb.txt", "The pull_over scenario configuration file"); DEFINE_string(scenario_emergency_pull_over_config_file, "/apollo/modules/planning/conf/" "scenario/emergency_pull_over_config.pb.txt", "The emergency_pull_over scenario configuration file"); DEFINE_string(scenario_emergency_stop_config_file, "/apollo/modules/planning/conf/" "scenario/emergency_stop_config.pb.txt", "The emergency_stop scenario configuration file"); DEFINE_string(scenario_stop_sign_unprotected_config_file, "/apollo/modules/planning/conf/" "scenario/stop_sign_unprotected_config.pb.txt", "stop_sign_unprotected scenario configuration file"); DEFINE_string(scenario_traffic_light_protected_config_file, "/apollo/modules/planning/conf/" "scenario/traffic_light_protected_config.pb.txt", "traffic_light_protected scenario config file"); DEFINE_string(scenario_traffic_light_unprotected_left_turn_config_file, "/apollo/modules/planning/conf/" "scenario/traffic_light_unprotected_left_turn_config.pb.txt", "traffic_light_unprotected_left_turn scenario config file"); DEFINE_string(scenario_traffic_light_unprotected_right_turn_config_file, "/apollo/modules/planning/conf/" "scenario/traffic_light_unprotected_right_turn_config.pb.txt", "traffic_light_unprotected_right_turn scenario config file"); DEFINE_string(scenario_valet_parking_config_file, "/apollo/modules/planning/conf/" "scenario/valet_parking_config.pb.txt", "valet_parking scenario config file"); DEFINE_string(scenario_deadend_turnaround_config_file, "/apollo/modules/planning/conf/" "scenario/deadend_turnaround_config.pb.txt", "deadend_turnaround scenario config file"); DEFINE_string(scenario_yield_sign_config_file, "/apollo/modules/planning/conf/" "scenario/yield_sign_config.pb.txt", "yield_sign scenario config file"); DEFINE_bool(enable_scenario_bare_intersection, true, "enable bare_intersection scenarios in planning"); DEFINE_bool(enable_scenario_park_and_go, true, "enable park-and-go scenario in planning"); DEFINE_bool(enable_scenario_pull_over, false, "enable pull-over scenario in planning"); DEFINE_bool(enable_scenario_emergency_pull_over, true, "enable emergency-pull-over scenario in planning"); DEFINE_bool(enable_scenario_emergency_stop, true, "enable emergency-stop scenario in planning"); DEFINE_bool(enable_scenario_side_pass_multiple_parked_obstacles, true, "enable ADC to side-pass multiple parked obstacles without" "worrying if the obstacles are blocked by others."); DEFINE_bool(enable_scenario_stop_sign, true, "enable stop_sign scenarios in planning"); DEFINE_bool(enable_scenario_traffic_light, true, "enable traffic_light scenarios in planning"); DEFINE_bool(enable_scenario_yield_sign, true, "enable yield_sign scenarios in planning"); DEFINE_bool(enable_force_pull_over_open_space_parking_test, false, "enable force_pull_over_open_space_parking_test"); DEFINE_string(traffic_rule_config_filename, "/apollo/modules/planning/conf/traffic_rule_config.pb.txt", "Traffic rule config filename"); DEFINE_string(smoother_config_filename, "/apollo/modules/planning/conf/qp_spline_smoother_config.pb.txt", "The configuration file for qp_spline smoother"); DEFINE_string(rtk_trajectory_filename, "modules/planning/data/garage.csv", "Loop rate for planning node"); DEFINE_uint64(rtk_trajectory_forward, 800, "The number of points to be included in RTK trajectory " "after the matched point"); DEFINE_double(rtk_trajectory_resolution, 0.01, "The time resolution of output trajectory for rtk planner."); DEFINE_bool(publish_estop, false, "publish estop decision in planning"); DEFINE_bool(enable_trajectory_stitcher, true, "enable stitching trajectory"); DEFINE_bool(enable_reference_line_stitching, true, "Enable stitching reference line, which can reducing computing " "time and improve stability"); DEFINE_double(look_forward_extend_distance, 50, "The step size when extending reference line."); DEFINE_double(reference_line_stitch_overlap_distance, 20, "The overlap distance with the existing reference line when " "stitching the existing reference line"); DEFINE_bool(enable_smooth_reference_line, true, "enable smooth the map reference line"); DEFINE_bool(prioritize_change_lane, false, "change lane strategy has higher priority, always use a valid " "change lane path if such path exists"); DEFINE_double(change_lane_min_length, 30.0, "meters. If the change lane target has longer length than this " "threshold, it can shortcut the default lane."); DEFINE_bool(enable_reference_line_provider_thread, true, "Enable reference line provider thread."); DEFINE_double(default_reference_line_width, 4.0, "Default reference line width"); DEFINE_double(smoothed_reference_line_max_diff, 5.0, "Maximum position difference between the smoothed and the raw " "reference lines."); DEFINE_double(planning_upper_speed_limit, 31.3, "Maximum speed (m/s) in planning."); DEFINE_double(trajectory_time_length, 8.0, "Trajectory time length"); DEFINE_double(threshold_distance_for_destination, 0.01, "threshold distance for destination"); DEFINE_double(buffer_in_routing, 0.0, "buffer for select in lane for boundary"); DEFINE_double(buffer_out_routing, -7.0, "buffer for select out lane for boundary"); // planning trajectory output time density control DEFINE_double( trajectory_time_min_interval, 0.02, "(seconds) Trajectory time interval when publish. The is the min value."); DEFINE_double( trajectory_time_max_interval, 0.1, "(seconds) Trajectory time interval when publish. The is the max value."); DEFINE_double( trajectory_time_high_density_period, 1.0, "(seconds) Keep high density in the next this amount of seconds. "); DEFINE_bool(enable_trajectory_check, false, "Enable sanity check for planning trajectory."); DEFINE_double(speed_lower_bound, -0.1, "The lowest speed allowed."); DEFINE_double(speed_upper_bound, 40.0, "The highest speed allowed."); DEFINE_double(longitudinal_acceleration_lower_bound, -6.0, "The lowest longitudinal acceleration allowed."); DEFINE_double(longitudinal_acceleration_upper_bound, 4.0, "The highest longitudinal acceleration allowed."); DEFINE_double(lateral_acceleration_bound, 4.0, "Bound of lateral acceleration; symmetric for left and right"); DEFINE_double(longitudinal_jerk_lower_bound, -4.0, "The lower bound of longitudinal jerk."); DEFINE_double(longitudinal_jerk_upper_bound, 2.0, "The upper bound of longitudinal jerk."); DEFINE_double(lateral_jerk_bound, 4.0, "Bound of lateral jerk; symmetric for left and right"); DEFINE_double(kappa_bound, 0.1979, "The bound for trajectory curvature"); // ST Boundary DEFINE_double(st_max_s, 100, "the maximum s of st boundary"); DEFINE_double(st_max_t, 8, "the maximum t of st boundary"); // Decision Part DEFINE_bool(enable_nudge_slowdown, true, "True to slow down when nudge obstacles."); DEFINE_double(static_obstacle_nudge_l_buffer, 0.3, "minimum l-distance to nudge a static obstacle (meters)"); DEFINE_double(nonstatic_obstacle_nudge_l_buffer, 0.4, "minimum l-distance to nudge a non-static obstacle (meters)"); DEFINE_double(lane_change_obstacle_nudge_l_buffer, 0.3, "minimum l-distance to nudge when changing lane (meters)"); DEFINE_double(lateral_ignore_buffer, 3.0, "If an obstacle's lateral distance is further away than this " "distance, ignore it"); DEFINE_double(max_stop_distance_obstacle, 10.0, "max stop distance from in-lane obstacle (meters)"); DEFINE_double(min_stop_distance_obstacle, 6.0, "min stop distance from in-lane obstacle (meters)"); DEFINE_double(follow_min_distance, 3.0, "min follow distance for vehicles/bicycles/moving objects"); DEFINE_double(follow_min_obs_lateral_distance, 2.5, "obstacle min lateral distance to follow"); DEFINE_double(yield_distance, 5.0, "min yield distance for vehicles/moving objects " "other than pedestrians/bicycles"); DEFINE_double(follow_time_buffer, 2.5, "time buffer in second to calculate the following distance."); DEFINE_double(follow_min_time_sec, 2.0, "min follow time in st region before considering a valid follow," " this is to differentiate a moving obstacle cross adc's" " current lane and move to a different direction"); DEFINE_double(signal_expire_time_sec, 5.0, "traffic light signal info read expire time in sec"); DEFINE_string(destination_obstacle_id, "DEST", "obstacle id for converting destination to an obstacle"); DEFINE_double(destination_check_distance, 5.0, "if the distance between destination and ADC is less than this," " it is considered to reach destination"); DEFINE_double(virtual_stop_wall_length, 0.1, "virtual stop wall length (meters)"); DEFINE_double(virtual_stop_wall_height, 2.0, "virtual stop wall height (meters)"); // Path Deciders DEFINE_bool(enable_skip_path_tasks, false, "skip all path tasks and use trimmed previous path"); DEFINE_double(obstacle_lat_buffer, 0.4, "obstacle lateral buffer (meters) for deciding path boundaries"); DEFINE_double(obstacle_lon_start_buffer, 3.0, "obstacle longitudinal start buffer (meters) for deciding " "path boundaries"); DEFINE_double(obstacle_lon_end_buffer, 2.0, "obstacle longitudinal end buffer (meters) for deciding " "path boundaries"); DEFINE_double(static_obstacle_speed_threshold, 0.5, "The speed threshold to decide whether an obstacle is static " "or not."); DEFINE_double(lane_borrow_max_speed, 5.0, "The speed threshold for lane-borrow"); DEFINE_int32(long_term_blocking_obstacle_cycle_threshold, 3, "The cycle threshold for long-term blocking obstacle."); // Prediction Part DEFINE_double(prediction_total_time, 5.0, "Total prediction time"); DEFINE_bool(align_prediction_time, false, "enable align prediction data based planning time"); // Trajectory // according to DMV's rule, turn signal should be on within 200 ft from // intersection. DEFINE_double( turn_signal_distance, 100.00, "In meters. If there is a turn within this distance, use turn signal"); DEFINE_int32(trajectory_point_num_for_debug, 10, "number of output trajectory points for debugging"); DEFINE_double(lane_change_prepare_length, 80.0, "The distance of lane-change preparation on current lane."); DEFINE_double(min_lane_change_prepare_length, 10.0, "The minimal distance needed of lane-change on current lane."); DEFINE_double(allowed_lane_change_failure_time, 2.0, "The time allowed for lane-change failure before updating" "preparation distance."); DEFINE_bool(enable_smarter_lane_change, false, "enable smarter lane change with longer preparation distance."); // QpSt optimizer DEFINE_double(slowdown_profile_deceleration, -4.0, "The deceleration to generate slowdown profile. unit: m/s^2."); // SQP solver DEFINE_bool(enable_sqp_solver, true, "True to enable SQP solver."); /// thread pool DEFINE_bool(use_multi_thread_to_add_obstacles, false, "use multiple thread to add obstacles."); DEFINE_bool(enable_multi_thread_in_dp_st_graph, false, "Enable multiple thread to calculation curve cost in dp_st_graph."); /// Lattice Planner DEFINE_double(numerical_epsilon, 1e-6, "Epsilon in lattice planner."); DEFINE_double(default_cruise_speed, 5.0, "default cruise speed"); DEFINE_double(trajectory_time_resolution, 0.1, "Trajectory time resolution in planning"); DEFINE_double(trajectory_space_resolution, 1.0, "Trajectory space resolution in planning"); DEFINE_double(speed_lon_decision_horizon, 200.0, "Longitudinal horizon for speed decision making (meter)"); DEFINE_uint64(num_velocity_sample, 6, "The number of velocity samples in end condition sampler."); DEFINE_bool(enable_backup_trajectory, true, "If generate backup trajectory when planning fail"); DEFINE_double(backup_trajectory_cost, 1000.0, "Default cost of backup trajectory"); DEFINE_double(min_velocity_sample_gap, 1.0, "Minimal sampling gap for velocity"); DEFINE_double(lon_collision_buffer, 2.0, "The longitudinal buffer to keep distance to other vehicles"); DEFINE_double(lat_collision_buffer, 0.1, "The lateral buffer to keep distance to other vehicles"); DEFINE_uint64(num_sample_follow_per_timestamp, 3, "The number of sample points for each timestamp to follow"); // Lattice Evaluate Parameters DEFINE_double(weight_lon_objective, 10.0, "Weight of longitudinal travel cost"); DEFINE_double(weight_lon_jerk, 1.0, "Weight of longitudinal jerk cost"); DEFINE_double(weight_lon_collision, 5.0, "Weight of longitudinal collision cost"); DEFINE_double(weight_lat_offset, 2.0, "Weight of lateral offset cost"); DEFINE_double(weight_lat_comfort, 10.0, "Weight of lateral comfort cost"); DEFINE_double(weight_centripetal_acceleration, 1.5, "Weight of centripetal acceleration"); DEFINE_double(cost_non_priority_reference_line, 5.0, "The cost of planning on non-priority reference line."); DEFINE_double(weight_same_side_offset, 1.0, "Weight of same side lateral offset cost"); DEFINE_double(weight_opposite_side_offset, 10.0, "Weight of opposite side lateral offset cost"); DEFINE_double(weight_dist_travelled, 10.0, "Weight of travelled distance cost"); DEFINE_double(weight_target_speed, 1.0, "Weight of target speed cost"); DEFINE_double(lat_offset_bound, 3.0, "The bound of lateral offset"); DEFINE_double(lon_collision_yield_buffer, 1.0, "Longitudinal collision buffer for yield"); DEFINE_double(lon_collision_overtake_buffer, 5.0, "Longitudinal collision buffer for overtake"); DEFINE_double(lon_collision_cost_std, 0.5, "The standard deviation of longitudinal collision cost function"); DEFINE_double(default_lon_buffer, 5.0, "Default longitudinal buffer to sample path-time points."); DEFINE_double(time_min_density, 1.0, "Minimal time density to search sample points."); DEFINE_double(comfort_acceleration_factor, 0.5, "Factor for comfort acceleration."); DEFINE_double(polynomial_minimal_param, 0.01, "Minimal time parameter in polynomials."); DEFINE_double(lattice_stop_buffer, 0.02, "The buffer before the stop s to check trajectories."); DEFINE_bool(lateral_optimization, true, "whether using optimization for lateral trajectory generation"); DEFINE_double(weight_lateral_offset, 1.0, "weight for lateral offset " "in lateral trajectory optimization"); DEFINE_double(weight_lateral_derivative, 500.0, "weight for lateral derivative " "in lateral trajectory optimization"); DEFINE_double(weight_lateral_second_order_derivative, 1000.0, "weight for lateral second order derivative " "in lateral trajectory optimization"); DEFINE_double(weight_lateral_third_order_derivative, 1000.0, "weight for lateral third order derivative " "in lateral trajectory optimization"); DEFINE_double( weight_lateral_obstacle_distance, 0.0, "weight for lateral obstacle distance in lateral trajectory optimization"); DEFINE_double(lateral_third_order_derivative_max, 0.1, "the maximal allowance for lateral third order derivative"); DEFINE_double(lateral_derivative_bound_default, 2.0, "the default value for lateral derivative bound."); DEFINE_double(max_s_lateral_optimization, 60.0, "The maximal s for lateral optimization."); DEFINE_double(default_delta_s_lateral_optimization, 1.0, "The default delta s for lateral optimization."); DEFINE_double(bound_buffer, 0.1, "buffer to boundary for lateral optimization"); DEFINE_double(nudge_buffer, 0.3, "buffer to nudge for lateral optimization"); DEFINE_double(fallback_total_time, 3.0, "total fallback trajectory time"); DEFINE_double(fallback_time_unit, 0.1, "fallback trajectory unit time in seconds"); DEFINE_double(speed_bump_speed_limit, 4.4704, "the speed limit when passing a speed bump, m/s. The default " "speed limit is 10 mph."); DEFINE_double(default_city_road_speed_limit, 15.67, "default speed limit (m/s) for city road. 35 mph."); DEFINE_double(default_highway_speed_limit, 29.06, "default speed limit (m/s) for highway. 65 mph."); // navigation mode DEFINE_bool(enable_planning_pad_msg, false, "To control whether to enable planning pad message."); // TODO(all): open space planner, merge with planning conf DEFINE_string(planner_open_space_config_filename, "/apollo/modules/planning/conf/planner_open_space_config.pb.txt", "The open space planner configuration file"); DEFINE_double(open_space_planning_period, 4.0, "estimated time for open space planner planning period"); DEFINE_double(open_space_prediction_time_horizon, 2.0, "the time in second we use from the trajectory of obstacles " "given by prediction"); DEFINE_bool(enable_perception_obstacles, true, "enable the open space planner to take perception obstacles into " "consideration"); DEFINE_bool(enable_open_space_planner_thread, true, "Enable thread in open space planner for trajectory publish."); DEFINE_bool(use_dual_variable_warm_start, true, "whether or not enable dual variable warm start "); DEFINE_bool(use_gear_shift_trajectory, false, "allow some time for the vehicle to shift gear"); DEFINE_uint64(open_space_trajectory_stitching_preserved_length, std::numeric_limits<uint32_t>::infinity(), "preserved points number in trajectory stitching for open space " "trajectory"); DEFINE_bool( enable_smoother_failsafe, false, "whether to use warm start result as final output when smoother fails"); DEFINE_bool(use_s_curve_speed_smooth, false, "Whether use s-curve (piecewise_jerk) for smoothing Hybrid Astar " "speed/acceleration."); DEFINE_bool( use_iterative_anchoring_smoother, false, "Whether use iterative_anchoring_smoother for open space planning "); DEFINE_bool( enable_parallel_trajectory_smoothing, false, "Whether to partition the trajectory first and do smoothing in parallel"); DEFINE_bool(enable_osqp_debug, false, "True to turn on OSQP verbose debug output in log."); DEFINE_bool(export_chart, false, "export chart in planning"); DEFINE_bool(enable_record_debug, true, "True to enable record debug info in chart format"); DEFINE_double( default_front_clear_distance, 300.0, "default front clear distance value in case there is no obstacle around."); DEFINE_double(max_trajectory_len, 1000.0, "(unit: meter) max possible trajectory length."); DEFINE_bool(enable_rss_fallback, false, "trigger rss fallback"); DEFINE_bool(enable_rss_info, true, "enable rss_info in trajectory_pb"); DEFINE_double(rss_max_front_obstacle_distance, 3000.0, "(unit: meter) for max front obstacle distance."); DEFINE_bool( enable_planning_smoother, false, "True to enable planning smoother among different planning cycles."); DEFINE_double(smoother_stop_distance, 10.0, "(unit: meter) for ADC stop, if it is close to the stop point " "within this threshold, current planning will be smoothed."); DEFINE_bool(enable_parallel_hybrid_a, false, "True to enable hybrid a* parallel implementation."); DEFINE_double(open_space_standstill_acceleration, 0.0, "(unit: meter/sec^2) for open space stand still at destination"); DEFINE_bool(enable_dp_reference_speed, true, "True to penalize dp result towards default cruise speed"); DEFINE_double(message_latency_threshold, 0.02, "Threshold for message delay"); DEFINE_bool(enable_lane_change_urgency_checking, false, "True to check the urgency of lane changing"); DEFINE_double(short_path_length_threshold, 20.0, "Threshold for too short path length"); DEFINE_uint64(trajectory_stitching_preserved_length, 20, "preserved points number in trajectory stitching"); DEFINE_double(side_pass_driving_width_l_buffer, 0.1, "(unit: meter) for side pass driving width l buffer"); DEFINE_bool(use_st_drivable_boundary, false, "True to use st_drivable boundary in speed planning"); DEFINE_bool(enable_reuse_path_in_lane_follow, false, "True to enable reuse path in lane follow"); DEFINE_bool( use_smoothed_dp_guide_line, false, "True to penalize speed optimization result to be close to dp guide line"); DEFINE_bool(use_soft_bound_in_nonlinear_speed_opt, true, "False to disallow soft bound in nonlinear speed opt"); DEFINE_bool(use_front_axe_center_in_path_planning, false, "If using front axe center in path planning, the path can be " "more agile."); DEFINE_bool(use_road_boundary_from_map, false, "get road boundary from HD map"); DEFINE_bool(planning_offline_learning, false, "offline learning. read record files and dump learning_data"); DEFINE_string(planning_data_dir, "/apollo/modules/planning/data/", "Prefix of files to store feature data"); DEFINE_string(planning_offline_bags, "", "a list of source files or directories for offline mode. " "The items need to be separated by colon ':'. "); DEFINE_int32(learning_data_obstacle_history_time_sec, 3.0, "time sec (second) of history trajectory points for a obstacle"); DEFINE_int32(learning_data_frame_num_per_file, 100, "number of learning_data_frame to write out in one data file."); DEFINE_string( planning_birdview_img_feature_renderer_config_file, "/apollo/modules/planning/conf/planning_semantic_map_config.pb.txt", "config file for renderer singleton"); DEFINE_bool( skip_path_reference_in_side_pass, false, "skipping using learning model output as path reference in side pass"); DEFINE_bool( skip_path_reference_in_change_lane, true, "skipping using learning model output as path reference in change lane"); DEFINE_int32(min_past_history_points_len, 0, "minimun past history points length for trainsition from " "rule-based planning to learning-based planning");
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/common/planning_gflags.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 "gflags/gflags.h" DECLARE_bool(planning_test_mode); DECLARE_int32(history_max_record_num); DECLARE_int32(max_frame_history_num); // scenarios related DECLARE_string(scenario_bare_intersection_unprotected_config_file); DECLARE_string(scenario_emergency_pull_over_config_file); DECLARE_string(scenario_emergency_stop_config_file); DECLARE_string(scenario_lane_follow_config_file); DECLARE_string(scenario_lane_follow_hybrid_config_file); DECLARE_string(scenario_learning_model_sample_config_file); DECLARE_string(scenario_narrow_street_u_turn_config_file); DECLARE_string(scenario_park_and_go_config_file); DECLARE_string(scenario_pull_over_config_file); DECLARE_string(scenario_stop_sign_unprotected_config_file); DECLARE_string(scenario_traffic_light_protected_config_file); DECLARE_string(scenario_traffic_light_unprotected_left_turn_config_file); DECLARE_string(scenario_traffic_light_unprotected_right_turn_config_file); DECLARE_string(scenario_valet_parking_config_file); DECLARE_string(scenario_yield_sign_config_file); DECLARE_bool(enable_scenario_bare_intersection); DECLARE_bool(enable_scenario_emergency_pull_over); DECLARE_bool(enable_scenario_emergency_stop); DECLARE_bool(enable_scenario_park_and_go); DECLARE_bool(enable_scenario_pull_over); DECLARE_bool(enable_scenario_stop_sign); DECLARE_bool(enable_scenario_traffic_light); DECLARE_bool(enable_scenario_yield_sign); DECLARE_bool(enable_scenario_side_pass_multiple_parked_obstacles); DECLARE_bool(enable_force_pull_over_open_space_parking_test); DECLARE_string(traffic_rule_config_filename); DECLARE_string(smoother_config_filename); DECLARE_int32(planning_loop_rate); DECLARE_string(rtk_trajectory_filename); DECLARE_uint64(rtk_trajectory_forward); DECLARE_double(rtk_trajectory_resolution); DECLARE_bool(enable_reference_line_stitching); DECLARE_double(look_forward_extend_distance); DECLARE_double(reference_line_stitch_overlap_distance); DECLARE_bool(enable_smooth_reference_line); DECLARE_bool(prioritize_change_lane); DECLARE_double(change_lane_min_length); DECLARE_bool(publish_estop); DECLARE_bool(enable_trajectory_stitcher); // parameter for reference line DECLARE_bool(enable_reference_line_provider_thread); DECLARE_double(default_reference_line_width); DECLARE_double(smoothed_reference_line_max_diff); // parameters for trajectory planning DECLARE_double(planning_upper_speed_limit); DECLARE_double(trajectory_time_length); DECLARE_double(trajectory_time_min_interval); DECLARE_double(trajectory_time_max_interval); DECLARE_double(trajectory_time_high_density_period); // parameters for trajectory sanity check DECLARE_bool(enable_trajectory_check); DECLARE_double(speed_lower_bound); DECLARE_double(speed_upper_bound); DECLARE_double(longitudinal_acceleration_lower_bound); DECLARE_double(longitudinal_acceleration_upper_bound); DECLARE_double(longitudinal_jerk_lower_bound); DECLARE_double(longitudinal_jerk_upper_bound); DECLARE_double(lateral_jerk_bound); DECLARE_double(kappa_bound); // STBoundary DECLARE_double(st_max_s); DECLARE_double(st_max_t); // Decision Part DECLARE_bool(enable_nudge_slowdown); DECLARE_double(static_obstacle_nudge_l_buffer); DECLARE_double(nonstatic_obstacle_nudge_l_buffer); DECLARE_double(lane_change_obstacle_nudge_l_buffer); DECLARE_double(lateral_ignore_buffer); DECLARE_double(min_stop_distance_obstacle); DECLARE_double(max_stop_distance_obstacle); DECLARE_double(follow_min_distance); DECLARE_double(follow_min_obs_lateral_distance); DECLARE_double(yield_distance); DECLARE_double(follow_time_buffer); DECLARE_double(follow_min_time_sec); DECLARE_double(signal_expire_time_sec); // Path Deciders DECLARE_bool(enable_skip_path_tasks); DECLARE_bool(enable_reuse_path_in_lane_follow); DECLARE_double(obstacle_lat_buffer); DECLARE_double(obstacle_lon_start_buffer); DECLARE_double(obstacle_lon_end_buffer); DECLARE_double(static_obstacle_speed_threshold); DECLARE_double(lane_borrow_max_speed); DECLARE_int32(long_term_blocking_obstacle_cycle_threshold); DECLARE_string(destination_obstacle_id); DECLARE_double(destination_check_distance); DECLARE_double(virtual_stop_wall_length); DECLARE_double(virtual_stop_wall_height); DECLARE_double(prediction_total_time); DECLARE_bool(align_prediction_time); DECLARE_int32(trajectory_point_num_for_debug); DECLARE_double(lane_change_prepare_length); DECLARE_double(min_lane_change_prepare_length); DECLARE_double(allowed_lane_change_failure_time); DECLARE_bool(enable_smarter_lane_change); DECLARE_double(turn_signal_distance); // QpSt optimizer DECLARE_double(slowdown_profile_deceleration); DECLARE_bool(enable_sqp_solver); /// thread pool DECLARE_bool(use_multi_thread_to_add_obstacles); DECLARE_bool(enable_multi_thread_in_dp_st_graph); DECLARE_double(numerical_epsilon); DECLARE_double(default_cruise_speed); DECLARE_double(trajectory_time_resolution); DECLARE_double(trajectory_space_resolution); DECLARE_double(lateral_acceleration_bound); DECLARE_double(speed_lon_decision_horizon); DECLARE_uint64(num_velocity_sample); DECLARE_bool(enable_backup_trajectory); DECLARE_double(backup_trajectory_cost); DECLARE_double(min_velocity_sample_gap); DECLARE_double(lon_collision_buffer); DECLARE_double(lat_collision_buffer); DECLARE_uint64(num_sample_follow_per_timestamp); DECLARE_bool(lateral_optimization); DECLARE_double(weight_lateral_offset); DECLARE_double(weight_lateral_derivative); DECLARE_double(weight_lateral_second_order_derivative); DECLARE_double(weight_lateral_third_order_derivative); DECLARE_double(weight_lateral_obstacle_distance); DECLARE_double(lateral_third_order_derivative_max); DECLARE_double(lateral_derivative_bound_default); // Lattice Evaluate Parameters DECLARE_double(weight_lon_objective); DECLARE_double(weight_lon_jerk); DECLARE_double(weight_lon_collision); DECLARE_double(weight_lat_offset); DECLARE_double(weight_lat_comfort); DECLARE_double(weight_centripetal_acceleration); DECLARE_double(cost_non_priority_reference_line); DECLARE_double(weight_same_side_offset); DECLARE_double(weight_opposite_side_offset); DECLARE_double(weight_dist_travelled); DECLARE_double(weight_target_speed); DECLARE_double(lat_offset_bound); DECLARE_double(lon_collision_yield_buffer); DECLARE_double(lon_collision_overtake_buffer); DECLARE_double(lon_collision_cost_std); DECLARE_double(default_lon_buffer); DECLARE_double(time_min_density); DECLARE_double(comfort_acceleration_factor); DECLARE_double(polynomial_minimal_param); DECLARE_double(lattice_stop_buffer); DECLARE_double(max_s_lateral_optimization); DECLARE_double(default_delta_s_lateral_optimization); DECLARE_double(bound_buffer); DECLARE_double(nudge_buffer); DECLARE_double(fallback_total_time); DECLARE_double(fallback_time_unit); DECLARE_double(speed_bump_speed_limit); DECLARE_double(default_city_road_speed_limit); DECLARE_double(default_highway_speed_limit); // navigation mode DECLARE_bool(enable_planning_pad_msg); // open space planner DECLARE_string(planner_open_space_config_filename); DECLARE_double(open_space_planning_period); DECLARE_double(open_space_prediction_time_horizon); DECLARE_bool(enable_perception_obstacles); DECLARE_bool(enable_open_space_planner_thread); DECLARE_bool(use_dual_variable_warm_start); DECLARE_bool(use_gear_shift_trajectory); DECLARE_uint64(open_space_trajectory_stitching_preserved_length); DECLARE_bool(enable_smoother_failsafe); DECLARE_bool(use_s_curve_speed_smooth); DECLARE_bool(use_iterative_anchoring_smoother); DECLARE_bool(enable_parallel_trajectory_smoothing); DECLARE_bool(enable_osqp_debug); DECLARE_bool(export_chart); DECLARE_bool(enable_record_debug); DECLARE_double(default_front_clear_distance); DECLARE_double(max_trajectory_len); DECLARE_bool(enable_rss_fallback); DECLARE_bool(enable_rss_info); DECLARE_double(rss_max_front_obstacle_distance); DECLARE_bool(enable_planning_smoother); DECLARE_double(smoother_stop_distance); DECLARE_double(side_pass_driving_width_l_buffer); DECLARE_bool(enable_parallel_hybrid_a); DECLARE_double(open_space_standstill_acceleration); DECLARE_bool(enable_dp_reference_speed); DECLARE_double(message_latency_threshold); DECLARE_bool(enable_lane_change_urgency_checking); DECLARE_double(short_path_length_threshold); DECLARE_uint64(trajectory_stitching_preserved_length); DECLARE_bool(use_st_drivable_boundary); DECLARE_bool(use_smoothed_dp_guide_line); DECLARE_bool(use_soft_bound_in_nonlinear_speed_opt); DECLARE_bool(use_front_axe_center_in_path_planning); DECLARE_bool(use_road_boundary_from_map); DECLARE_double(threshold_distance_for_destination); DECLARE_double(buffer_in_routing); DECLARE_double(buffer_out_routing); // learning related DECLARE_bool(planning_offline_learning); DECLARE_string(planning_data_dir); DECLARE_string(planning_offline_bags); DECLARE_int32(learning_data_obstacle_history_time_sec); DECLARE_int32(learning_data_frame_num_per_file); DECLARE_string(planning_birdview_img_feature_renderer_config_file); DECLARE_int32(min_past_history_points_len); // hybrid model DECLARE_bool(skip_path_reference_in_side_pass); DECLARE_bool(skip_path_reference_in_change_lane);
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/common/open_space_info.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 <string> #include <utility> #include <vector> #include "Eigen/Dense" #include "cyber/common/log.h" #include "modules/common_msgs/chassis_msgs/chassis.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/vec2d.h" #include "modules/common/vehicle_state/proto/vehicle_state.pb.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/common_msgs/map_msgs/map_id.pb.h" #include "modules/planning/common/indexed_queue.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/common_msgs/planning_msgs/planning_internal.pb.h" namespace apollo { namespace planning { typedef std::pair<DiscretizedTrajectory, canbus::Chassis::GearPosition> TrajGearPair; struct GearSwitchStates { bool gear_switching_flag = false; bool gear_shift_period_finished = true; bool gear_shift_period_started = true; double gear_shift_period_time = 0.0; double gear_shift_start_time = 0.0; apollo::canbus::Chassis::GearPosition gear_shift_position = canbus::Chassis::GEAR_DRIVE; }; class OpenSpaceInfo { public: OpenSpaceInfo() = default; ~OpenSpaceInfo() = default; const std::string target_parking_spot_id() const { return target_parking_spot_id_; } std::string *mutable_target_parking_spot_id() { return &target_parking_spot_id_; } const hdmap::ParkingSpaceInfoConstPtr target_parking_spot() const { return target_parking_spot_; } hdmap::ParkingSpaceInfoConstPtr *mutable_target_parking_spot() { return &target_parking_spot_; } const hdmap::LaneInfoConstPtr target_parking_lane() const { return target_parking_lane_; } void set_target_parking_lane(hdmap::LaneInfoConstPtr lane_info_const_ptr) { target_parking_lane_ = lane_info_const_ptr; } double open_space_pre_stop_fence_s() const { return open_space_pre_stop_fence_s_; } void set_open_space_pre_stop_fence_s(const double s) { open_space_pre_stop_fence_s_ = s; } bool pre_stop_rightaway_flag() const { return pre_stop_rightaway_flag_; } void set_pre_stop_rightaway_flag(const bool flag) { pre_stop_rightaway_flag_ = flag; } const hdmap::MapPathPoint &pre_stop_rightaway_point() const { return pre_stop_rightaway_point_; } hdmap::MapPathPoint *mutable_pre_stop_rightaway_point() { return &pre_stop_rightaway_point_; } bool is_on_open_space_trajectory() const { return is_on_open_space_trajectory_; } void set_is_on_open_space_trajectory(const bool flag) { is_on_open_space_trajectory_ = flag; } size_t obstacles_num() const { return obstacles_num_; } void set_obstacles_num(const size_t obstacles_num) { obstacles_num_ = obstacles_num; } const Eigen::MatrixXi &obstacles_edges_num() const { return obstacles_edges_num_; } Eigen::MatrixXi *mutable_obstacles_edges_num() { return &obstacles_edges_num_; } const std::vector<std::vector<common::math::Vec2d>> &obstacles_vertices_vec() const { return obstacles_vertices_vec_; } std::vector<std::vector<common::math::Vec2d>> *mutable_obstacles_vertices_vec() { return &obstacles_vertices_vec_; } const Eigen::MatrixXd &obstacles_A() const { return obstacles_A_; } Eigen::MatrixXd *mutable_obstacles_A() { return &obstacles_A_; } const Eigen::MatrixXd &obstacles_b() const { return obstacles_b_; } Eigen::MatrixXd *mutable_obstacles_b() { return &obstacles_b_; } double origin_heading() const { return origin_heading_; } void set_origin_heading(const double original_heading) { origin_heading_ = original_heading; } const common::math::Vec2d &origin_point() const { return origin_point_; } common::math::Vec2d *mutable_origin_point() { return &origin_point_; } const std::vector<double> &ROI_xy_boundary() const { return ROI_xy_boundary_; } std::vector<double> *mutable_ROI_xy_boundary() { return &ROI_xy_boundary_; } const std::vector<double> &open_space_end_pose() const { return open_space_end_pose_; } std::vector<double> *mutable_open_space_end_pose() { return &open_space_end_pose_; } const DiscretizedTrajectory &optimizer_trajectory_data() const { return optimizer_trajectory_data_; } DiscretizedTrajectory *mutable_optimizer_trajectory_data() { return &optimizer_trajectory_data_; } const std::vector<common::TrajectoryPoint> &stitching_trajectory_data() const { return stitching_trajectory_data_; } std::vector<common::TrajectoryPoint> *mutable_stitching_trajectory_data() { return &stitching_trajectory_data_; } const DiscretizedTrajectory &stitched_trajectory_result() const { return stitched_trajectory_result_; } DiscretizedTrajectory *mutable_stitched_trajectory_result() { return &stitched_trajectory_result_; } bool open_space_provider_success() const { return open_space_provider_success_; } void set_open_space_provider_success(const bool flag) { open_space_provider_success_ = flag; } bool destination_reached() const { return destination_reached_; } void set_destination_reached(const bool flag) { destination_reached_ = flag; } const DiscretizedTrajectory &interpolated_trajectory_result() const { return interpolated_trajectory_result_; } DiscretizedTrajectory *mutable_interpolated_trajectory_result() { return &interpolated_trajectory_result_; } const std::vector<TrajGearPair> &partitioned_trajectories() const { // TODO(Runxin): export to chart return partitioned_trajectories_; } std::vector<TrajGearPair> *mutable_partitioned_trajectories() { return &partitioned_trajectories_; } const GearSwitchStates &gear_switch_states() const { return gear_switch_states_; } GearSwitchStates *mutable_gear_switch_states() { return &gear_switch_states_; } const TrajGearPair &chosen_partitioned_trajectory() const { // TODO(Runxin): export to chart return chosen_partitioned_trajectory_; } TrajGearPair *mutable_chosen_partitioned_trajectory() { return &chosen_partitioned_trajectory_; } bool fallback_flag() const { return fallback_flag_; } void set_fallback_flag(const bool flag) { fallback_flag_ = flag; } TrajGearPair *mutable_fallback_trajectory() { return &fallback_trajectory_; } const TrajGearPair &fallback_trajectory() const { return fallback_trajectory_; } void set_fallback_trajectory(const TrajGearPair &traj_gear_pair) { fallback_trajectory_ = traj_gear_pair; } std::pair<PublishableTrajectory, canbus::Chassis::GearPosition> *mutable_publishable_trajectory_data() { return &publishable_trajectory_data_; } const std::pair<PublishableTrajectory, canbus::Chassis::GearPosition> &publishable_trajectory_data() const { return publishable_trajectory_data_; } // TODO(QiL, Jinyun) refactor and merge this with debug common::TrajectoryPoint *mutable_future_collision_point() { return &future_collision_point_; } const common::TrajectoryPoint &future_collision_point() const { return future_collision_point_; } // TODO(QiL, Jinyun): refactor open_space_info vs debug apollo::planning_internal::Debug *mutable_debug() { return debug_; } void set_debug(apollo::planning_internal::Debug *debug) { debug_ = debug; } const apollo::planning_internal::Debug &debug() const { return *debug_; } const apollo::planning_internal::Debug debug_instance() const { return debug_instance_; } apollo::planning_internal::Debug *mutable_debug_instance() { return &debug_instance_; } void sync_debug_instance() { // Remove existing obstacle vectors to prevent repeating obstacle // vectors. if (!debug_->planning_data().open_space().obstacles().empty()) { debug_instance_.mutable_planning_data() ->mutable_open_space() ->clear_obstacles(); } debug_instance_.MergeFrom(*debug_); } void RecordDebug(apollo::planning_internal::Debug *ptr_debug); void set_time_latency(double time_latency) { time_latency_ = time_latency; } private: std::string target_parking_spot_id_; hdmap::ParkingSpaceInfoConstPtr target_parking_spot_ = nullptr; hdmap::LaneInfoConstPtr target_parking_lane_ = nullptr; double open_space_pre_stop_fence_s_ = 0.0; bool pre_stop_rightaway_flag_ = false; hdmap::MapPathPoint pre_stop_rightaway_point_; bool is_on_open_space_trajectory_ = false; // @brief obstacles total num including perception obstacles and parking space // boundary size_t obstacles_num_ = 0; // @brief the dimension needed for A and b matrix dimension in H // representation Eigen::MatrixXi obstacles_edges_num_; // @brief in the order of [x_min, x_max, y_min, y_max]; std::vector<double> ROI_xy_boundary_; // @brief open_space end configuration in order of x, y, heading and speed. // Speed is set to be always zero now for parking std::vector<double> open_space_end_pose_; // @brief vector storing the vertices of obstacles in counter-clock-wise order std::vector<std::vector<common::math::Vec2d>> obstacles_vertices_vec_; // @brief Linear inequality representation of the obstacles Ax>b Eigen::MatrixXd obstacles_A_; Eigen::MatrixXd obstacles_b_; // @brief origin heading for planning space rotation double origin_heading_ = 0.0; // @brief origin point for scaling down the numeric value of the optimization // problem in order of x , y common::math::Vec2d origin_point_; DiscretizedTrajectory optimizer_trajectory_data_; std::vector<common::TrajectoryPoint> stitching_trajectory_data_; DiscretizedTrajectory stitched_trajectory_result_; bool open_space_provider_success_ = false; bool destination_reached_ = false; DiscretizedTrajectory interpolated_trajectory_result_; std::vector<TrajGearPair> partitioned_trajectories_; GearSwitchStates gear_switch_states_; TrajGearPair chosen_partitioned_trajectory_; bool fallback_flag_ = true; TrajGearPair fallback_trajectory_; common::TrajectoryPoint future_collision_point_; std::pair<PublishableTrajectory, canbus::Chassis::GearPosition> publishable_trajectory_data_; // the pointer from ADCtrajectory apollo::planning_internal::Debug *debug_; // the instance inside debug, // if ADCtrajectory is NULL, blank; else same to ADCtrajectory apollo::planning_internal::Debug debug_instance_; double time_latency_ = 0.0; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/common/speed_profile_generator.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 speed_profile_generator.cc **/ #include "modules/planning/common/speed_profile_generator.h" #include <algorithm> #include <utility> #include "cyber/common/log.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/math/piecewise_jerk/piecewise_jerk_speed_problem.h" namespace apollo { namespace planning { using apollo::common::SpeedPoint; SpeedData SpeedProfileGenerator::GenerateFallbackSpeed( const EgoInfo* ego_info, const double stop_distance) { AERROR << "Fallback using piecewise jerk speed!"; const double init_v = ego_info->start_point().v(); const double init_a = ego_info->start_point().a(); AWARN << "init_v = " << init_v << ", init_a = " << init_a; const auto& veh_param = common::VehicleConfigHelper::GetConfig().vehicle_param(); // if already stopped if (init_v <= 0.0 && init_a <= 0.0) { AWARN << "Already stopped! Nothing to do in GenerateFallbackSpeed()"; SpeedData speed_data; speed_data.AppendSpeedPoint(0.0, 0.0, 0.0, 0.0, 0.0); FillEnoughSpeedPoints(&speed_data); return speed_data; } std::array<double, 3> init_s = {0.0, init_v, init_a}; // TODO(all): dt is too small; double delta_t = FLAGS_fallback_time_unit; double total_time = FLAGS_fallback_total_time; const size_t num_of_knots = static_cast<size_t>(total_time / delta_t) + 1; PiecewiseJerkSpeedProblem piecewise_jerk_problem(num_of_knots, delta_t, init_s); std::vector<double> end_state_ref(num_of_knots, stop_distance); piecewise_jerk_problem.set_x_ref(1.0, std::move(end_state_ref)); piecewise_jerk_problem.set_scale_factor({1.0, 10.0, 100.0}); piecewise_jerk_problem.set_x_bounds(0.0, std::fmax(stop_distance, 100.0)); piecewise_jerk_problem.set_dx_bounds( 0.0, std::fmax(FLAGS_planning_upper_speed_limit, init_v)); piecewise_jerk_problem.set_ddx_bounds(veh_param.max_deceleration(), veh_param.max_acceleration()); piecewise_jerk_problem.set_dddx_bound(FLAGS_longitudinal_jerk_lower_bound, FLAGS_longitudinal_jerk_upper_bound); // Solve the problem if (!piecewise_jerk_problem.Optimize()) { AERROR << "Piecewise jerk fallback speed optimizer failed!"; return GenerateStopProfile(init_v, init_a); } // Extract output const std::vector<double>& s = piecewise_jerk_problem.opt_x(); const std::vector<double>& ds = piecewise_jerk_problem.opt_dx(); const std::vector<double>& dds = piecewise_jerk_problem.opt_ddx(); for (size_t i = 0; i < num_of_knots; ++i) { ADEBUG << "For[" << delta_t * static_cast<double>(i) << "], s = " << s[i] << ", v = " << ds[i] << ", a = " << dds[i]; } SpeedData speed_data; speed_data.AppendSpeedPoint(s[0], 0.0, ds[0], dds[0], 0.0); for (size_t i = 1; i < num_of_knots; ++i) { // Avoid the very last points when already stopped if (s[i] - s[i - 1] <= 0.0 || ds[i] <= 0.0) { break; } speed_data.AppendSpeedPoint(s[i], delta_t * static_cast<double>(i), ds[i], dds[i], (dds[i] - dds[i - 1]) / delta_t); } FillEnoughSpeedPoints(&speed_data); return speed_data; } void SpeedProfileGenerator::FillEnoughSpeedPoints(SpeedData* const speed_data) { const SpeedPoint last_point = speed_data->back(); if (last_point.t() >= FLAGS_fallback_total_time) { return; } for (double t = last_point.t() + FLAGS_fallback_time_unit; t < FLAGS_fallback_total_time; t += FLAGS_fallback_time_unit) { speed_data->AppendSpeedPoint(last_point.s(), t, 0.0, 0.0, 0.0); } } SpeedData SpeedProfileGenerator::GenerateStopProfile(const double init_speed, const double init_acc) { AERROR << "Slowing down the car within a constant deceleration with fallback " "stopping profile."; SpeedData speed_data; const double max_t = FLAGS_fallback_total_time; const double unit_t = FLAGS_fallback_time_unit; double pre_s = 0.0; double pre_v = init_speed; double acc = FLAGS_slowdown_profile_deceleration; speed_data.AppendSpeedPoint(0.0, 0.0, init_speed, init_acc, 0.0); for (double t = unit_t; t < max_t; t += unit_t) { double s = 0.0; double v = 0.0; s = std::fmax(pre_s, pre_s + 0.5 * (pre_v + (pre_v + unit_t * acc)) * unit_t); v = std::fmax(0.0, pre_v + unit_t * acc); speed_data.AppendSpeedPoint(s, t, v, acc, 0.0); pre_s = s; pre_v = v; } FillEnoughSpeedPoints(&speed_data); return speed_data; } SpeedData SpeedProfileGenerator::GenerateFixedDistanceCreepProfile( const double distance, const double max_speed) { static constexpr double kConstDeceleration = -0.8; // (~3sec to fully stop) static constexpr double kProceedingSpeed = 2.23; // (5mph proceeding speed) const double proceeding_speed = std::fmin(max_speed, kProceedingSpeed); const double distance_to_start_deceleration = proceeding_speed * proceeding_speed / kConstDeceleration / 2; bool is_const_deceleration_mode = distance < distance_to_start_deceleration; double a = kConstDeceleration; double t = 0.0; double s = 0.0; double v = proceeding_speed; static constexpr double kDeltaT = 0.1; SpeedData speed_data; while (s < distance && v > 0) { if (is_const_deceleration_mode) { speed_data.AppendSpeedPoint(s, t, v, a, 0.0); t += kDeltaT; double v_new = std::max(0.0, v + a * t); s += kDeltaT * (v + v_new) / 2; v = v_new; } else { speed_data.AppendSpeedPoint(s, t, v, 0.0, 0.0); t += kDeltaT; s += kDeltaT * v; if (distance - s < distance_to_start_deceleration) is_const_deceleration_mode = true; } } return speed_data; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/common/st_graph_data.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: st_graph_data.h * @brief: data with map info and obstacle info **/ #pragma once #include <tuple> #include <vector> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/planning/common/speed/st_boundary.h" #include "modules/planning/common/speed_limit.h" #include "modules/planning/proto/st_drivable_boundary.pb.h" namespace apollo { namespace planning { constexpr double kObsSpeedIgnoreThreshold = 100.0; class StGraphData { public: StGraphData() = default; void LoadData(const std::vector<const STBoundary*>& st_boundaries, const double min_s_on_st_boundaries, const apollo::common::TrajectoryPoint& init_point, const SpeedLimit& speed_limit, const double cruise_speed, const double path_data_length, const double total_time_by_conf, planning_internal::STGraphDebug* st_graph_debug); bool is_initialized() const { return init_; } const std::vector<const STBoundary*>& st_boundaries() const; double min_s_on_st_boundaries() const; const apollo::common::TrajectoryPoint& init_point() const; const SpeedLimit& speed_limit() const; double cruise_speed() const; double path_length() const; double total_time_by_conf() const; planning_internal::STGraphDebug* mutable_st_graph_debug(); bool SetSTDrivableBoundary( const std::vector<std::tuple<double, double, double>>& s_boundary, const std::vector<std::tuple<double, double, double>>& v_obs_info); const STDrivableBoundary& st_drivable_boundary() const; private: bool init_ = false; std::vector<const STBoundary*> st_boundaries_; double min_s_on_st_boundaries_ = 0.0; apollo::common::TrajectoryPoint init_point_; SpeedLimit speed_limit_; double cruise_speed_ = 0.0; double path_data_length_ = 0.0; double path_length_by_conf_ = 0.0; double total_time_by_conf_ = 0.0; planning_internal::STGraphDebug* st_graph_debug_ = nullptr; STDrivableBoundary st_drivable_boundary_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/common/indexed_list.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 indexed_list.h **/ #pragma once #include <unordered_map> #include <vector> #include <boost/thread/shared_mutex.hpp> #include "cyber/common/log.h" #include "modules/common/util/map_util.h" namespace apollo { namespace planning { template <typename I, typename T> class IndexedList { public: /** * @brief copy object into the container. If the id is already exist, * overwrite the object in the container. * @param id the id of the object * @param object the const reference of the objected to be copied to the * container. * @return The pointer to the object in the container. */ T* Add(const I id, const T& object) { auto obs = Find(id); if (obs) { AWARN << "object " << id << " is already in container"; *obs = object; return obs; } else { object_dict_.insert({id, object}); auto* ptr = &object_dict_.at(id); object_list_.push_back(ptr); return ptr; } } /** * @brief Find object by id in the container * @param id the id of the object * @return the raw pointer to the object if found. * @return nullptr if the object is not found. */ T* Find(const I id) { return apollo::common::util::FindOrNull(object_dict_, id); } /** * @brief Find object by id in the container * @param id the id of the object * @return the raw pointer to the object if found. * @return nullptr if the object is not found. */ const T* Find(const I id) const { return apollo::common::util::FindOrNull(object_dict_, id); } /** * @brief List all the items in the container. * @return the list of const raw pointers of the objects in the container. */ const std::vector<const T*>& Items() const { return object_list_; } /** * @brief List all the items in the container. * @return the unordered_map of ids and objects in the container. */ const std::unordered_map<I, T>& Dict() const { return object_dict_; } /** * @brief Copy the container with objects. */ IndexedList& operator=(const IndexedList& other) { this->object_list_.clear(); this->object_dict_.clear(); for (const auto& item : other.Dict()) { Add(item.first, item.second); } return *this; } private: std::vector<const T*> object_list_; std::unordered_map<I, T> object_dict_; }; template <typename I, typename T> class ThreadSafeIndexedList : public IndexedList<I, T> { public: T* Add(const I id, const T& object) { boost::unique_lock<boost::shared_mutex> writer_lock(mutex_); return IndexedList<I, T>::Add(id, object); } T* Find(const I id) { boost::shared_lock<boost::shared_mutex> reader_lock(mutex_); return IndexedList<I, T>::Find(id); } std::vector<const T*> Items() const { boost::shared_lock<boost::shared_mutex> reader_lock(mutex_); return IndexedList<I, T>::Items(); } private: mutable boost::shared_mutex mutex_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/common/ego_info.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 ego_info.h **/ #pragma once #include <vector> #include "cyber/common/macros.h" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/vehicle_state/proto/vehicle_state.pb.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/reference_line/reference_line.h" namespace apollo { namespace planning { class EgoInfo { public: EgoInfo(); ~EgoInfo() = default; bool Update(const common::TrajectoryPoint& start_point, const common::VehicleState& vehicle_state); void Clear(); common::TrajectoryPoint start_point() const { return start_point_; } common::VehicleState vehicle_state() const { return vehicle_state_; } double front_clear_distance() const { return front_clear_distance_; } common::math::Box2d ego_box() const { return ego_box_; } void CalculateFrontObstacleClearDistance( const std::vector<const Obstacle*>& obstacles); private: FRIEND_TEST(EgoInfoTest, EgoInfoSimpleTest); void set_vehicle_state(const common::VehicleState& vehicle_state) { vehicle_state_ = vehicle_state; } void set_start_point(const common::TrajectoryPoint& start_point) { start_point_ = start_point; const auto& param = ego_vehicle_config_.vehicle_param(); start_point_.set_a( std::fmax(std::fmin(start_point_.a(), param.max_acceleration()), param.max_deceleration())); } void CalculateEgoBox(const common::VehicleState& vehicle_state); // stitched point (at stitching mode) // or real vehicle point (at non-stitching mode) common::TrajectoryPoint start_point_; // ego vehicle state common::VehicleState vehicle_state_; double front_clear_distance_ = FLAGS_default_front_clear_distance; common::VehicleConfig ego_vehicle_config_; common::math::Box2d ego_box_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/util/math_util.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. *****************************************************************************/ #include "modules/planning/common/util/math_util.h" #include <utility> #include "modules/common/math/math_utils.h" namespace apollo { namespace planning { namespace util { std::pair<double, double> WorldCoordToObjCoord( std::pair<double, double> input_world_coord, std::pair<double, double> obj_world_coord, double obj_world_angle) { double x_diff = input_world_coord.first - obj_world_coord.first; double y_diff = input_world_coord.second - obj_world_coord.second; double rho = std::sqrt(x_diff * x_diff + y_diff * y_diff); double theta = std::atan2(y_diff, x_diff) - obj_world_angle; return std::make_pair(std::cos(theta) * rho, std::sin(theta) * rho); } double WorldAngleToObjAngle(double input_world_angle, double obj_world_angle) { return common::math::NormalizeAngle(input_world_angle - obj_world_angle); } } // namespace util } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/util/common.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/common/util/common.h" namespace apollo { namespace planning { namespace util { using apollo::common::util::WithinBound; /* * @brief: build virtual obstacle of stop wall, and add STOP decision */ int BuildStopDecision(const std::string& stop_wall_id, const double stop_line_s, const double stop_distance, const StopReasonCode& stop_reason_code, const std::vector<std::string>& wait_for_obstacles, const std::string& decision_tag, Frame* const frame, ReferenceLineInfo* const reference_line_info) { CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); // check const auto& reference_line = reference_line_info->reference_line(); if (!WithinBound(0.0, reference_line.Length(), stop_line_s)) { AERROR << "stop_line_s[" << stop_line_s << "] is not on reference line"; return 0; } // create virtual stop wall const auto* obstacle = frame->CreateStopObstacle(reference_line_info, stop_wall_id, stop_line_s); if (!obstacle) { AERROR << "Failed to create obstacle [" << stop_wall_id << "]"; return -1; } const Obstacle* stop_wall = reference_line_info->AddObstacle(obstacle); if (!stop_wall) { AERROR << "Failed to add obstacle[" << stop_wall_id << "]"; return -1; } // build stop decision const double stop_s = stop_line_s - stop_distance; const auto& stop_point = reference_line.GetReferencePoint(stop_s); const double stop_heading = reference_line.GetReferencePoint(stop_s).heading(); ObjectDecisionType stop; auto* stop_decision = stop.mutable_stop(); stop_decision->set_reason_code(stop_reason_code); stop_decision->set_distance_s(-stop_distance); stop_decision->set_stop_heading(stop_heading); stop_decision->mutable_stop_point()->set_x(stop_point.x()); stop_decision->mutable_stop_point()->set_y(stop_point.y()); stop_decision->mutable_stop_point()->set_z(0.0); for (size_t i = 0; i < wait_for_obstacles.size(); ++i) { stop_decision->add_wait_for_obstacle(wait_for_obstacles[i]); } auto* path_decision = reference_line_info->path_decision(); path_decision->AddLongitudinalDecision(decision_tag, stop_wall->Id(), stop); return 0; } int BuildStopDecision(const std::string& stop_wall_id, const std::string& lane_id, const double lane_s, const double stop_distance, const StopReasonCode& stop_reason_code, const std::vector<std::string>& wait_for_obstacles, const std::string& decision_tag, Frame* const frame, ReferenceLineInfo* const reference_line_info) { CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); const auto& reference_line = reference_line_info->reference_line(); // create virtual stop wall const auto* obstacle = frame->CreateStopObstacle(stop_wall_id, lane_id, lane_s); if (!obstacle) { AERROR << "Failed to create obstacle [" << stop_wall_id << "]"; return -1; } const Obstacle* stop_wall = reference_line_info->AddObstacle(obstacle); if (!stop_wall) { AERROR << "Failed to create obstacle for: " << stop_wall_id; return -1; } const auto& stop_wall_box = stop_wall->PerceptionBoundingBox(); if (!reference_line.IsOnLane(stop_wall_box.center())) { ADEBUG << "stop point is not on lane. SKIP STOP decision"; return 0; } // build stop decision auto stop_point = reference_line.GetReferencePoint( stop_wall->PerceptionSLBoundary().start_s() - stop_distance); ObjectDecisionType stop; auto* stop_decision = stop.mutable_stop(); stop_decision->set_reason_code(stop_reason_code); stop_decision->set_distance_s(-stop_distance); stop_decision->set_stop_heading(stop_point.heading()); stop_decision->mutable_stop_point()->set_x(stop_point.x()); stop_decision->mutable_stop_point()->set_y(stop_point.y()); stop_decision->mutable_stop_point()->set_z(0.0); auto* path_decision = reference_line_info->path_decision(); path_decision->AddLongitudinalDecision(decision_tag, stop_wall->Id(), stop); return 0; } } // namespace util } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/util/math_util.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. *****************************************************************************/ #pragma once #include <utility> namespace apollo { namespace planning { namespace util { // Helper function to convert world coordinates to relative coordinates // around the obstacle of interest. std::pair<double, double> WorldCoordToObjCoord( std::pair<double, double> input_world_coord, std::pair<double, double> obj_world_coord, double obj_world_angle); double WorldAngleToObjAngle(double input_world_angle, double obj_world_angle); } // namespace util } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/util/util.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/common/util/util.h" #include <limits> #include <vector> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/pnc_map/path.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace util { using apollo::common::VehicleState; using apollo::hdmap::PathOverlap; using apollo::routing::RoutingResponse; bool IsVehicleStateValid(const VehicleState& vehicle_state) { if (std::isnan(vehicle_state.x()) || std::isnan(vehicle_state.y()) || std::isnan(vehicle_state.z()) || std::isnan(vehicle_state.heading()) || std::isnan(vehicle_state.kappa()) || std::isnan(vehicle_state.linear_velocity()) || std::isnan(vehicle_state.linear_acceleration())) { return false; } return true; } bool IsDifferentRouting(const RoutingResponse& first, const RoutingResponse& second) { if (first.has_header() && second.has_header()) { return first.header().sequence_num() != second.header().sequence_num(); } return true; } double GetADCStopDeceleration( apollo::common::VehicleStateProvider* vehicle_state, const double adc_front_edge_s, const double stop_line_s) { double adc_speed = vehicle_state->linear_velocity(); const double max_adc_stop_speed = common::VehicleConfigHelper::Instance() ->GetConfig() .vehicle_param() .max_abs_speed_when_stopped(); if (adc_speed < max_adc_stop_speed) { return 0.0; } double stop_distance = 0; if (stop_line_s > adc_front_edge_s) { stop_distance = stop_line_s - adc_front_edge_s; } if (stop_distance < 1e-5) { return std::numeric_limits<double>::max(); } return (adc_speed * adc_speed) / (2 * stop_distance); } /* * @brief: check if a stop_sign_overlap is still along reference_line */ bool CheckStopSignOnReferenceLine(const ReferenceLineInfo& reference_line_info, const std::string& stop_sign_overlap_id) { const std::vector<PathOverlap>& stop_sign_overlaps = reference_line_info.reference_line().map_path().stop_sign_overlaps(); auto stop_sign_overlap_it = std::find_if(stop_sign_overlaps.begin(), stop_sign_overlaps.end(), [&stop_sign_overlap_id](const PathOverlap& overlap) { return overlap.object_id == stop_sign_overlap_id; }); return (stop_sign_overlap_it != stop_sign_overlaps.end()); } /* * @brief: check if a traffic_light_overlap is still along reference_line */ bool CheckTrafficLightOnReferenceLine( const ReferenceLineInfo& reference_line_info, const std::string& traffic_light_overlap_id) { const std::vector<PathOverlap>& traffic_light_overlaps = reference_line_info.reference_line().map_path().signal_overlaps(); auto traffic_light_overlap_it = std::find_if(traffic_light_overlaps.begin(), traffic_light_overlaps.end(), [&traffic_light_overlap_id](const PathOverlap& overlap) { return overlap.object_id == traffic_light_overlap_id; }); return (traffic_light_overlap_it != traffic_light_overlaps.end()); } /* * @brief: check if ADC is till inside a pnc-junction */ bool CheckInsideJunction(const ReferenceLineInfo& reference_line_info) { const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const double adc_back_edge_s = reference_line_info.AdcSlBoundary().start_s(); hdmap::PathOverlap junction_overlap; reference_line_info.GetJunction(adc_front_edge_s, &junction_overlap); if (junction_overlap.object_id.empty()) { return false; } static constexpr double kIntersectionPassDist = 2.0; // unit: m const double distance_adc_pass_intersection = adc_back_edge_s - junction_overlap.end_s; ADEBUG << "distance_adc_pass_intersection[" << distance_adc_pass_intersection << "] junction_overlap[" << junction_overlap.object_id << "] start_s[" << junction_overlap.start_s << "]"; return distance_adc_pass_intersection < kIntersectionPassDist; } /* * @brief: get files at a path */ void GetFilesByPath(const boost::filesystem::path& path, std::vector<std::string>* files) { ACHECK(files); if (!boost::filesystem::exists(path)) { return; } if (boost::filesystem::is_regular_file(path)) { AINFO << "Found record file: " << path.c_str(); files->push_back(path.c_str()); return; } if (boost::filesystem::is_directory(path)) { for (auto& entry : boost::make_iterator_range( boost::filesystem::directory_iterator(path), {})) { GetFilesByPath(entry.path(), files); } } } } // namespace util } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/util/common.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. *****************************************************************************/ #pragma once #include <string> #include <vector> #include "modules/planning/common/frame.h" #include "modules/planning/common/reference_line_info.h" namespace apollo { namespace planning { namespace util { int BuildStopDecision(const std::string& stop_wall_id, const double stop_line_s, const double stop_distance, const StopReasonCode& stop_reason_code, const std::vector<std::string>& wait_for_obstacles, const std::string& decision_tag, Frame* const frame, ReferenceLineInfo* const reference_line_info); int BuildStopDecision(const std::string& stop_wall_id, const std::string& lane_id, const double lane_s, const double stop_distance, const StopReasonCode& stop_reason_code, const std::vector<std::string>& wait_for_obstacles, const std::string& decision_tag, Frame* const frame, ReferenceLineInfo* const reference_line_info); } // namespace util } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/util/util.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. *****************************************************************************/ #pragma once #include <string> #include <vector> #include <boost/filesystem.hpp> #include <boost/range/iterator_range.hpp> #include "modules/common/vehicle_state/proto/vehicle_state.pb.h" #include "modules/common_msgs/routing_msgs/routing.pb.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/reference_line_info.h" namespace apollo { namespace planning { namespace util { bool IsVehicleStateValid(const apollo::common::VehicleState& vehicle_state); bool IsDifferentRouting(const apollo::routing::RoutingResponse& first, const apollo::routing::RoutingResponse& second); double GetADCStopDeceleration( apollo::common::VehicleStateProvider* vehicle_state, const double adc_front_edge_s, const double stop_line_s); bool CheckStopSignOnReferenceLine(const ReferenceLineInfo& reference_line_info, const std::string& stop_sign_overlap_id); bool CheckTrafficLightOnReferenceLine( const ReferenceLineInfo& reference_line_info, const std::string& traffic_light_overlap_id); bool CheckInsideJunction(const ReferenceLineInfo& reference_line_info); void GetFilesByPath(const boost::filesystem::path& path, std::vector<std::string>* files); } // namespace util } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/util/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) PLANNING_COPTS = ["-DMODULE_NAME=\\\"planning\\\""] cc_library( name = "util_lib", srcs = ["util.cc"], hdrs = ["util.h"], copts = PLANNING_COPTS, deps = [ "//cyber", "//modules/common/util", "//modules/common/vehicle_state:vehicle_state_provider", "//modules/common/vehicle_state/proto:vehicle_state_cc_proto", "//modules/planning/common:planning_gflags", "//modules/planning/common:reference_line_info", "//modules/common_msgs/planning_msgs:planning_cc_proto", ], ) cc_library( name = "common_lib", srcs = ["common.cc"], hdrs = ["common.h"], copts = PLANNING_COPTS, deps = [ "//cyber", "//modules/common/util", "//modules/planning/common:frame", "//modules/planning/common:reference_line_info", ], ) cc_library( name = "math_util_lib", srcs = ["math_util.cc"], hdrs = ["math_util.h"], copts = PLANNING_COPTS, deps = [ "//cyber", "//modules/common/math", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/speed/st_point.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 st_point.cpp **/ #include "modules/planning/common/speed/st_point.h" #include "modules/common/util/string_util.h" namespace apollo { namespace planning { using apollo::common::util::StrFormat; STPoint::STPoint(const double s, const double t) : Vec2d(t, s) {} STPoint::STPoint(const common::math::Vec2d& vec2d_point) : Vec2d(vec2d_point) {} double STPoint::s() const { return y_; } double STPoint::t() const { return x_; } void STPoint::set_s(const double s) { y_ = s; } void STPoint::set_t(const double t) { x_ = t; } std::string STPoint::DebugString() const { return StrFormat("{ \"s\" : %.6f, \"t\" : %.6f }", s(), t()); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/speed/speed_data.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/common/speed/speed_data.h" #include <algorithm> #include <mutex> #include <utility> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "modules/common/math/linear_interpolation.h" #include "modules/common/util/point_factory.h" #include "modules/common/util/string_util.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::SpeedPoint; SpeedData::SpeedData(std::vector<SpeedPoint> speed_points) : std::vector<SpeedPoint>(std::move(speed_points)) { std::sort(begin(), end(), [](const SpeedPoint& p1, const SpeedPoint& p2) { return p1.t() < p2.t(); }); } void SpeedData::AppendSpeedPoint(const double s, const double time, const double v, const double a, const double da) { static std::mutex mutex_speedpoint; UNIQUE_LOCK_MULTITHREAD(mutex_speedpoint); if (!empty()) { ACHECK(back().t() < time); } push_back(common::util::PointFactory::ToSpeedPoint(s, time, v, a, da)); } bool SpeedData::EvaluateByTime(const double t, common::SpeedPoint* const speed_point) const { if (size() < 2) { return false; } if (!(front().t() < t + 1.0e-6 && t - 1.0e-6 < back().t())) { return false; } auto comp = [](const common::SpeedPoint& sp, const double t) { return sp.t() < t; }; auto it_lower = std::lower_bound(begin(), end(), t, comp); if (it_lower == end()) { *speed_point = back(); } else if (it_lower == begin()) { *speed_point = front(); } else { const auto& p0 = *(it_lower - 1); const auto& p1 = *it_lower; double t0 = p0.t(); double t1 = p1.t(); speed_point->Clear(); speed_point->set_s(common::math::lerp(p0.s(), t0, p1.s(), t1, t)); speed_point->set_t(t); if (p0.has_v() && p1.has_v()) { speed_point->set_v(common::math::lerp(p0.v(), t0, p1.v(), t1, t)); } if (p0.has_a() && p1.has_a()) { speed_point->set_a(common::math::lerp(p0.a(), t0, p1.a(), t1, t)); } if (p0.has_da() && p1.has_da()) { speed_point->set_da(common::math::lerp(p0.da(), t0, p1.da(), t1, t)); } } return true; } bool SpeedData::EvaluateByS(const double s, common::SpeedPoint* const speed_point) const { if (size() < 2) { return false; } if (!(front().s() < s + 1.0e-6 && s - 1.0e-6 < back().s())) { return false; } auto comp = [](const common::SpeedPoint& sp, const double s) { return sp.s() < s; }; auto it_lower = std::lower_bound(begin(), end(), s, comp); if (it_lower == end()) { *speed_point = back(); } else if (it_lower == begin()) { *speed_point = front(); } else { const auto& p0 = *(it_lower - 1); const auto& p1 = *it_lower; double s0 = p0.s(); double s1 = p1.s(); speed_point->Clear(); speed_point->set_s(s); speed_point->set_t(common::math::lerp(p0.t(), s0, p1.t(), s1, s)); if (p0.has_v() && p1.has_v()) { speed_point->set_v(common::math::lerp(p0.v(), s0, p1.v(), s1, s)); } if (p0.has_a() && p1.has_a()) { speed_point->set_a(common::math::lerp(p0.a(), s0, p1.a(), s1, s)); } if (p0.has_da() && p1.has_da()) { speed_point->set_da(common::math::lerp(p0.da(), s0, p1.da(), s1, s)); } } return true; } double SpeedData::TotalTime() const { if (empty()) { return 0.0; } return back().t() - front().t(); } double SpeedData::TotalLength() const { if (empty()) { return 0.0; } return back().s() - front().s(); } std::string SpeedData::DebugString() const { const auto limit = std::min( size(), static_cast<size_t>(FLAGS_trajectory_point_num_for_debug)); return absl::StrCat( "[\n", absl::StrJoin(begin(), begin() + limit, ",\n", apollo::common::util::DebugStringFormatter()), "]\n"); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/speed/speed_data.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/basic_msgs/pnc_point.pb.h" namespace apollo { namespace planning { class SpeedData : public std::vector<common::SpeedPoint> { public: SpeedData() = default; virtual ~SpeedData() = default; explicit SpeedData(std::vector<common::SpeedPoint> speed_points); void AppendSpeedPoint(const double s, const double time, const double v, const double a, const double da); bool EvaluateByTime(const double time, common::SpeedPoint* const speed_point) const; // Assuming spatial traversed distance is monotonous, which is the case for // current usage on city driving scenario bool EvaluateByS(const double s, common::SpeedPoint* const speed_point) const; double TotalTime() const; // Assuming spatial traversed distance is monotonous double TotalLength() const; virtual std::string DebugString() const; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/speed/st_boundary.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/common/speed/st_boundary.h" #include "cyber/common/log.h" #include "modules/common/math/math_utils.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::math::LineSegment2d; using apollo::common::math::Vec2d; STBoundary::STBoundary( const std::vector<std::pair<STPoint, STPoint>>& point_pairs, bool is_accurate_boundary) { ACHECK(IsValid(point_pairs)) << "The input point_pairs are NOT valid"; std::vector<std::pair<STPoint, STPoint>> reduced_pairs(point_pairs); if (!is_accurate_boundary) { RemoveRedundantPoints(&reduced_pairs); } for (const auto& item : reduced_pairs) { // use same t for both points const double t = item.first.t(); lower_points_.emplace_back(item.first.s(), t); upper_points_.emplace_back(item.second.s(), t); } for (const auto& point : lower_points_) { points_.emplace_back(point.t(), point.s()); } for (auto rit = upper_points_.rbegin(); rit != upper_points_.rend(); ++rit) { points_.emplace_back(rit->t(), rit->s()); } BuildFromPoints(); for (const auto& point : lower_points_) { min_s_ = std::fmin(min_s_, point.s()); } for (const auto& point : upper_points_) { max_s_ = std::fmax(max_s_, point.s()); } min_t_ = lower_points_.front().t(); max_t_ = lower_points_.back().t(); obstacle_road_right_ending_t_ = std::numeric_limits<double>::lowest(); } STBoundary STBoundary::CreateInstance( const std::vector<STPoint>& lower_points, const std::vector<STPoint>& upper_points) { if (lower_points.size() != upper_points.size() || lower_points.size() < 2) { return STBoundary(); } std::vector<std::pair<STPoint, STPoint>> point_pairs; for (size_t i = 0; i < lower_points.size(); ++i) { point_pairs.emplace_back( STPoint(lower_points.at(i).s(), lower_points.at(i).t()), STPoint(upper_points.at(i).s(), upper_points.at(i).t())); } return STBoundary(point_pairs); } STBoundary STBoundary::CreateInstanceAccurate( const std::vector<STPoint>& lower_points, const std::vector<STPoint>& upper_points) { if (lower_points.size() != upper_points.size() || lower_points.size() < 2) { return STBoundary(); } std::vector<std::pair<STPoint, STPoint>> point_pairs; for (size_t i = 0; i < lower_points.size(); ++i) { point_pairs.emplace_back( STPoint(lower_points.at(i).s(), lower_points.at(i).t()), STPoint(upper_points.at(i).s(), upper_points.at(i).t())); } return STBoundary(point_pairs, true); } std::string STBoundary::TypeName(BoundaryType type) { if (type == BoundaryType::FOLLOW) { return "FOLLOW"; } else if (type == BoundaryType::KEEP_CLEAR) { return "KEEP_CLEAR"; } else if (type == BoundaryType::OVERTAKE) { return "OVERTAKE"; } else if (type == BoundaryType::STOP) { return "STOP"; } else if (type == BoundaryType::YIELD) { return "YIELD"; } else if (type == BoundaryType::UNKNOWN) { return "UNKNOWN"; } AWARN << "Unknown boundary type " << static_cast<int>(type) << ", treated as UNKNOWN"; return "UNKNOWN"; } bool STBoundary::GetUnblockSRange(const double curr_time, double* s_upper, double* s_lower) const { CHECK_NOTNULL(s_upper); CHECK_NOTNULL(s_lower); *s_upper = FLAGS_speed_lon_decision_horizon; *s_lower = 0.0; if (curr_time < min_t_ || curr_time > max_t_) { return true; } size_t left = 0; size_t right = 0; if (!GetIndexRange(lower_points_, curr_time, &left, &right)) { AERROR << "Fail to get index range."; return false; } if (curr_time > upper_points_[right].t()) { return true; } const double r = (left == right ? 0.0 : (curr_time - upper_points_[left].t()) / (upper_points_[right].t() - upper_points_[left].t())); double upper_cross_s = upper_points_[left].s() + r * (upper_points_[right].s() - upper_points_[left].s()); double lower_cross_s = lower_points_[left].s() + r * (lower_points_[right].s() - lower_points_[left].s()); if (boundary_type_ == BoundaryType::STOP || boundary_type_ == BoundaryType::YIELD || boundary_type_ == BoundaryType::FOLLOW) { *s_upper = lower_cross_s; } else if (boundary_type_ == BoundaryType::OVERTAKE) { *s_lower = std::fmax(*s_lower, upper_cross_s); } else { ADEBUG << "boundary_type is not supported. boundary_type: " << static_cast<int>(boundary_type_); return false; } return true; } bool STBoundary::GetBoundarySRange(const double curr_time, double* s_upper, double* s_lower) const { CHECK_NOTNULL(s_upper); CHECK_NOTNULL(s_lower); if (curr_time < min_t_ || curr_time > max_t_) { return false; } size_t left = 0; size_t right = 0; if (!GetIndexRange(lower_points_, curr_time, &left, &right)) { AERROR << "Fail to get index range."; return false; } const double r = (left == right ? 0.0 : (curr_time - upper_points_[left].t()) / (upper_points_[right].t() - upper_points_[left].t())); *s_upper = upper_points_[left].s() + r * (upper_points_[right].s() - upper_points_[left].s()); *s_lower = lower_points_[left].s() + r * (lower_points_[right].s() - lower_points_[left].s()); *s_upper = std::fmin(*s_upper, FLAGS_speed_lon_decision_horizon); *s_lower = std::fmax(*s_lower, 0.0); return true; } bool STBoundary::GetBoundarySlopes(const double curr_time, double* ds_upper, double* ds_lower) const { if (ds_upper == nullptr || ds_lower == nullptr) { return false; } if (curr_time < min_t_ || curr_time > max_t_) { return false; } static constexpr double kTimeIncrement = 0.05; double t_prev = curr_time - kTimeIncrement; double prev_s_upper = 0.0; double prev_s_lower = 0.0; bool has_prev = GetBoundarySRange(t_prev, &prev_s_upper, &prev_s_lower); double t_next = curr_time + kTimeIncrement; double next_s_upper = 0.0; double next_s_lower = 0.0; bool has_next = GetBoundarySRange(t_next, &next_s_upper, &next_s_lower); double curr_s_upper = 0.0; double curr_s_lower = 0.0; GetBoundarySRange(curr_time, &curr_s_upper, &curr_s_lower); if (!has_prev && !has_next) { return false; } if (has_prev && has_next) { *ds_upper = ((next_s_upper - curr_s_upper) / kTimeIncrement + (curr_s_upper - prev_s_upper) / kTimeIncrement) * 0.5; *ds_lower = ((next_s_lower - curr_s_lower) / kTimeIncrement + (curr_s_lower - prev_s_lower) / kTimeIncrement) * 0.5; return true; } if (has_prev) { *ds_upper = (curr_s_upper - prev_s_upper) / kTimeIncrement; *ds_lower = (curr_s_lower - prev_s_lower) / kTimeIncrement; } else { *ds_upper = (next_s_upper - curr_s_upper) / kTimeIncrement; *ds_lower = (next_s_lower - curr_s_lower) / kTimeIncrement; } return true; } bool STBoundary::IsPointInBoundary(const STPoint& st_point) const { if (st_point.t() <= min_t_ || st_point.t() >= max_t_) { return false; } size_t left = 0; size_t right = 0; if (!GetIndexRange(lower_points_, st_point.t(), &left, &right)) { AERROR << "failed to get index range."; return false; } const double check_upper = common::math::CrossProd( st_point, upper_points_[left], upper_points_[right]); const double check_lower = common::math::CrossProd( st_point, lower_points_[left], lower_points_[right]); return (check_upper * check_lower < 0); } STBoundary STBoundary::ExpandByS(const double s) const { if (lower_points_.empty()) { return STBoundary(); } std::vector<std::pair<STPoint, STPoint>> point_pairs; for (size_t i = 0; i < lower_points_.size(); ++i) { point_pairs.emplace_back( STPoint(lower_points_[i].s() - s, lower_points_[i].t()), STPoint(upper_points_[i].s() + s, upper_points_[i].t())); } return STBoundary(std::move(point_pairs)); } STBoundary STBoundary::ExpandByT(const double t) const { if (lower_points_.empty()) { AERROR << "The current st_boundary has NO points."; return STBoundary(); } std::vector<std::pair<STPoint, STPoint>> point_pairs; const double left_delta_t = lower_points_[1].t() - lower_points_[0].t(); const double lower_left_delta_s = lower_points_[1].s() - lower_points_[0].s(); const double upper_left_delta_s = upper_points_[1].s() - upper_points_[0].s(); point_pairs.emplace_back( STPoint(lower_points_[0].s() - t * lower_left_delta_s / left_delta_t, lower_points_[0].t() - t), STPoint(upper_points_[0].s() - t * upper_left_delta_s / left_delta_t, upper_points_.front().t() - t)); const double kMinSEpsilon = 1e-3; point_pairs.front().first.set_s( std::fmin(point_pairs.front().second.s() - kMinSEpsilon, point_pairs.front().first.s())); for (size_t i = 0; i < lower_points_.size(); ++i) { point_pairs.emplace_back(lower_points_[i], upper_points_[i]); } size_t length = lower_points_.size(); DCHECK_GE(length, 2U); const double right_delta_t = lower_points_[length - 1].t() - lower_points_[length - 2].t(); const double lower_right_delta_s = lower_points_[length - 1].s() - lower_points_[length - 2].s(); const double upper_right_delta_s = upper_points_[length - 1].s() - upper_points_[length - 2].s(); point_pairs.emplace_back(STPoint(lower_points_.back().s() + t * lower_right_delta_s / right_delta_t, lower_points_.back().t() + t), STPoint(upper_points_.back().s() + t * upper_right_delta_s / right_delta_t, upper_points_.back().t() + t)); point_pairs.back().second.set_s( std::fmax(point_pairs.back().second.s(), point_pairs.back().first.s() + kMinSEpsilon)); return STBoundary(std::move(point_pairs)); } STBoundary::BoundaryType STBoundary::boundary_type() const { return boundary_type_; } void STBoundary::SetBoundaryType(const BoundaryType& boundary_type) { boundary_type_ = boundary_type; } const std::string& STBoundary::id() const { return id_; } void STBoundary::set_id(const std::string& id) { id_ = id; } double STBoundary::characteristic_length() const { return characteristic_length_; } void STBoundary::SetCharacteristicLength(const double characteristic_length) { characteristic_length_ = characteristic_length; } double STBoundary::min_s() const { return min_s_; } double STBoundary::min_t() const { return min_t_; } double STBoundary::max_s() const { return max_s_; } double STBoundary::max_t() const { return max_t_; } STBoundary STBoundary::CutOffByT(const double t) const { std::vector<STPoint> lower_points; std::vector<STPoint> upper_points; for (size_t i = 0; i < lower_points_.size() && i < upper_points_.size(); ++i) { if (lower_points_[i].t() < t) { continue; } lower_points.push_back(lower_points_[i]); upper_points.push_back(upper_points_[i]); } return CreateInstance(lower_points, upper_points); } STPoint STBoundary::upper_left_point() const { DCHECK(!upper_points_.empty()) << "StBoundary has zero points."; return upper_points_.front(); } STPoint STBoundary::upper_right_point() const { DCHECK(!upper_points_.empty()) << "StBoundary has zero points."; return upper_points_.back(); } STPoint STBoundary::bottom_left_point() const { DCHECK(!lower_points_.empty()) << "StBoundary has zero points."; return lower_points_.front(); } STPoint STBoundary::bottom_right_point() const { DCHECK(!lower_points_.empty()) << "StBoundary has zero points."; return lower_points_.back(); } void STBoundary::set_upper_left_point(STPoint st_point) { upper_left_point_ = std::move(st_point); } void STBoundary::set_upper_right_point(STPoint st_point) { upper_right_point_ = std::move(st_point); } void STBoundary::set_bottom_left_point(STPoint st_point) { bottom_left_point_ = std::move(st_point); } void STBoundary::set_bottom_right_point(STPoint st_point) { bottom_right_point_ = std::move(st_point); } /////////////////////////////////////////////////////////////////////////////// // Private functions for internal usage. bool STBoundary::IsValid( const std::vector<std::pair<STPoint, STPoint>>& point_pairs) const { if (point_pairs.size() < 2) { AERROR << "point_pairs.size() must >= 2, but current point_pairs.size() = " << point_pairs.size(); return false; } static constexpr double kStBoundaryEpsilon = 1e-9; static constexpr double kMinDeltaT = 1e-6; for (size_t i = 0; i < point_pairs.size(); ++i) { const auto& curr_lower = point_pairs[i].first; const auto& curr_upper = point_pairs[i].second; if (curr_upper.s() < curr_lower.s()) { AERROR << "ST-boundary's upper-s must >= lower-s"; return false; } if (std::fabs(curr_lower.t() - curr_upper.t()) > kStBoundaryEpsilon) { AERROR << "Points in every ST-point pair should be at the same time."; return false; } if (i + 1 != point_pairs.size()) { const auto& next_lower = point_pairs[i + 1].first; const auto& next_upper = point_pairs[i + 1].second; if (std::fmax(curr_lower.t(), curr_upper.t()) + kMinDeltaT >= std::fmin(next_lower.t(), next_upper.t())) { AERROR << "Latter points should have larger t: " << "curr_lower[" << curr_lower.DebugString() << "] curr_upper[" << curr_upper.DebugString() << "] next_lower[" << next_lower.DebugString() << "] next_upper[" << next_upper.DebugString() << "]"; return false; } } } return true; } bool STBoundary::IsPointNear(const common::math::LineSegment2d& seg, const Vec2d& point, const double max_dist) { return seg.DistanceSquareTo(point) < max_dist * max_dist; } void STBoundary::RemoveRedundantPoints( std::vector<std::pair<STPoint, STPoint>>* point_pairs) { if (!point_pairs || point_pairs->size() <= 2) { return; } const double kMaxDist = 0.1; size_t i = 0; size_t j = 1; while (i < point_pairs->size() && j + 1 < point_pairs->size()) { LineSegment2d lower_seg(point_pairs->at(i).first, point_pairs->at(j + 1).first); LineSegment2d upper_seg(point_pairs->at(i).second, point_pairs->at(j + 1).second); if (!IsPointNear(lower_seg, point_pairs->at(j).first, kMaxDist) || !IsPointNear(upper_seg, point_pairs->at(j).second, kMaxDist)) { ++i; if (i != j) { point_pairs->at(i) = point_pairs->at(j); } } ++j; } point_pairs->at(++i) = point_pairs->back(); point_pairs->resize(i + 1); } bool STBoundary::GetIndexRange(const std::vector<STPoint>& points, const double t, size_t* left, size_t* right) const { CHECK_NOTNULL(left); CHECK_NOTNULL(right); if (t < points.front().t() || t > points.back().t()) { AERROR << "t is out of range. t = " << t; return false; } auto comp = [](const STPoint& p, const double t) { return p.t() < t; }; auto first_ge = std::lower_bound(points.begin(), points.end(), t, comp); size_t index = std::distance(points.begin(), first_ge); if (index == 0) { *left = *right = 0; } else if (first_ge == points.end()) { *left = *right = points.size() - 1; } else { *left = index - 1; *right = index; } return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/speed/st_boundary.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 <limits> #include <string> #include <utility> #include <vector> #include "gtest/gtest_prod.h" #include "modules/common/math/box2d.h" #include "modules/common/math/polygon2d.h" #include "modules/common/math/vec2d.h" #include "modules/planning/common/speed/st_point.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" namespace apollo { namespace planning { class STBoundary : public common::math::Polygon2d { public: /** Constructors: * STBoundary must be initialized with a vector of ST-point pairs. * Each pair refers to a time t, with (lower_s, upper_s). */ STBoundary() = default; explicit STBoundary( const std::vector<std::pair<STPoint, STPoint>>& point_pairs, bool is_accurate_boundary = false); explicit STBoundary(const common::math::Box2d& box) = delete; explicit STBoundary(std::vector<common::math::Vec2d> points) = delete; /** @brief Wrapper of the constructor (old). */ static STBoundary CreateInstance(const std::vector<STPoint>& lower_points, const std::vector<STPoint>& upper_points); /** @brief Wrapper of the constructor. It doesn't use RemoveRedundantPoints * and generates an accurate ST-boundary. */ static STBoundary CreateInstanceAccurate( const std::vector<STPoint>& lower_points, const std::vector<STPoint>& upper_points); /** @brief Default destructor. */ ~STBoundary() = default; bool IsEmpty() const { return lower_points_.empty(); } bool GetUnblockSRange(const double curr_time, double* s_upper, double* s_lower) const; bool GetBoundarySRange(const double curr_time, double* s_upper, double* s_lower) const; bool GetBoundarySlopes(const double curr_time, double* ds_upper, double* ds_lower) const; // if you need to add boundary type, make sure you modify // GetUnblockSRange accordingly. enum class BoundaryType { UNKNOWN, STOP, FOLLOW, YIELD, OVERTAKE, KEEP_CLEAR, }; static std::string TypeName(BoundaryType type); BoundaryType boundary_type() const; const std::string& id() const; double characteristic_length() const; void set_id(const std::string& id); void SetBoundaryType(const BoundaryType& boundary_type); void SetCharacteristicLength(const double characteristic_length); double min_s() const; double min_t() const; double max_s() const; double max_t() const; std::vector<STPoint> upper_points() const { return upper_points_; } std::vector<STPoint> lower_points() const { return lower_points_; } // Used by st-optimizer. bool IsPointInBoundary(const STPoint& st_point) const; STBoundary ExpandByS(const double s) const; STBoundary ExpandByT(const double t) const; // Unused function so far. STBoundary CutOffByT(const double t) const; // Used by Lattice planners. STPoint upper_left_point() const; STPoint upper_right_point() const; STPoint bottom_left_point() const; STPoint bottom_right_point() const; void set_upper_left_point(STPoint st_point); void set_upper_right_point(STPoint st_point); void set_bottom_left_point(STPoint st_point); void set_bottom_right_point(STPoint st_point); void set_obstacle_road_right_ending_t(double road_right_ending_t) { obstacle_road_right_ending_t_ = road_right_ending_t; } double obstacle_road_right_ending_t() const { return obstacle_road_right_ending_t_; } private: /** @brief The sanity check function for a vector of ST-point pairs. */ bool IsValid( const std::vector<std::pair<STPoint, STPoint>>& point_pairs) const; /** @brief Returns true if point is within max_dist distance to seg. */ bool IsPointNear(const common::math::LineSegment2d& seg, const common::math::Vec2d& point, const double max_dist); /** @brief Sometimes a sequence of upper and lower points lie almost on * two straightlines. In this case, the intermediate points are removed, * with only the end-points retained. */ // TODO(all): When slope is high, this may introduce significant errors. // Also, when accumulated for multiple t, the error can get significant. // This function should be reconsidered, because it may be dangerous. void RemoveRedundantPoints( std::vector<std::pair<STPoint, STPoint>>* point_pairs); FRIEND_TEST(StBoundaryTest, remove_redundant_points); /** @brief Given time t, find a segment denoted by left and right idx, that * contains the time t. * - If t is less than all or larger than all, return false. */ bool GetIndexRange(const std::vector<STPoint>& points, const double t, size_t* left, size_t* right) const; FRIEND_TEST(StBoundaryTest, get_index_range); private: BoundaryType boundary_type_ = BoundaryType::UNKNOWN; std::vector<STPoint> upper_points_; std::vector<STPoint> lower_points_; std::string id_; double characteristic_length_ = 1.0; double min_s_ = std::numeric_limits<double>::max(); double max_s_ = std::numeric_limits<double>::lowest(); double min_t_ = std::numeric_limits<double>::max(); double max_t_ = std::numeric_limits<double>::lowest(); STPoint bottom_left_point_; STPoint bottom_right_point_; STPoint upper_left_point_; STPoint upper_right_point_; double obstacle_road_right_ending_t_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/speed/st_boundary_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/common/speed/st_boundary.h" #include "cyber/common/log.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace apollo { namespace planning { TEST(StBoundaryTest, basic_test) { std::vector<STPoint> upper_points; std::vector<STPoint> lower_points; std::vector<std::pair<STPoint, STPoint>> point_pairs; lower_points.emplace_back(0.0, 0.0); lower_points.emplace_back(0.0, 10.0); upper_points.emplace_back(5.0, 0.0); upper_points.emplace_back(5.0, 10.0); point_pairs.emplace_back(lower_points[0], upper_points[0]); point_pairs.emplace_back(lower_points[1], upper_points[1]); STBoundary boundary(point_pairs); EXPECT_EQ(boundary.id(), ""); EXPECT_EQ(boundary.boundary_type(), STBoundary::BoundaryType::UNKNOWN); EXPECT_DOUBLE_EQ(0.0, boundary.min_s()); EXPECT_DOUBLE_EQ(5.0, boundary.max_s()); EXPECT_DOUBLE_EQ(0.0, boundary.min_t()); EXPECT_DOUBLE_EQ(10.0, boundary.max_t()); } TEST(StBoundaryTest, boundary_range) { std::vector<STPoint> upper_points; std::vector<STPoint> lower_points; std::vector<std::pair<STPoint, STPoint>> point_pairs; lower_points.emplace_back(1.0, 0.0); lower_points.emplace_back(1.0, 10.0); upper_points.emplace_back(5.0, 0.0); upper_points.emplace_back(5.0, 10.0); point_pairs.emplace_back(lower_points[0], upper_points[0]); point_pairs.emplace_back(lower_points[1], upper_points[1]); STBoundary boundary(point_pairs); boundary.SetBoundaryType(STBoundary::BoundaryType::YIELD); double t = -10.0; const double dt = 0.01; while (t < 10.0) { double low = 0.0; double high = 0.0; if (t < 0.0) { EXPECT_TRUE(boundary.GetUnblockSRange(t, &high, &low)); EXPECT_DOUBLE_EQ(low, 0.0); EXPECT_DOUBLE_EQ(high, 200.0); EXPECT_FALSE(boundary.GetBoundarySRange(t, &high, &low)); } else { EXPECT_TRUE(boundary.GetUnblockSRange(t, &high, &low)); EXPECT_DOUBLE_EQ(low, 0.0); EXPECT_DOUBLE_EQ(high, 1.0); EXPECT_TRUE(boundary.GetBoundarySRange(t, &high, &low)); EXPECT_DOUBLE_EQ(low, 1.0); EXPECT_DOUBLE_EQ(high, 5.0); } t += dt; } } TEST(StBoundaryTest, get_index_range) { std::vector<STPoint> upper_points; std::vector<STPoint> lower_points; std::vector<std::pair<STPoint, STPoint>> point_pairs; lower_points.emplace_back(43.000164837720789, -517957.08587679861); lower_points.emplace_back(46.100164825451913, -517955.58587660792); upper_points.emplace_back(52.200164801309178, -517957.08587679861); upper_points.emplace_back(55.6001647283625, -517955.58587660792); point_pairs.emplace_back(lower_points[0], upper_points[0]); point_pairs.emplace_back(lower_points[1], upper_points[1]); STBoundary boundary(point_pairs); size_t left = 0; size_t right = 0; EXPECT_TRUE( boundary.GetIndexRange(lower_points, -517957.08587679861, &left, &right)); EXPECT_EQ(left, 0); EXPECT_EQ(right, 0); EXPECT_TRUE( boundary.GetIndexRange(lower_points, -517955.58587660792, &left, &right)); EXPECT_EQ(left, 0); EXPECT_EQ(right, 1); EXPECT_TRUE( boundary.GetIndexRange(lower_points, -517955.58587660792, &left, &right)); EXPECT_EQ(left, 0); EXPECT_EQ(right, 1); EXPECT_FALSE(boundary.GetIndexRange(lower_points, 0.0, &left, &right)); } TEST(StBoundaryTest, remove_redundant_points) { std::vector<std::pair<STPoint, STPoint>> points; points.emplace_back(STPoint(0.0, 0.0), STPoint(1.0, 0.0)); points.emplace_back(STPoint(0.1, 0.2), STPoint(1.1, 0.2)); points.emplace_back(STPoint(0.2, 0.3), STPoint(1.2, 0.3)); points.emplace_back(STPoint(0.3, 0.4), STPoint(1.3, 0.4)); points.emplace_back(STPoint(0.4, 0.5), STPoint(1.4, 0.5)); EXPECT_EQ(points.size(), 5); STBoundary st_boundary; st_boundary.RemoveRedundantPoints(&points); EXPECT_EQ(points.size(), 2); EXPECT_DOUBLE_EQ(points[0].first.s(), 0.0); EXPECT_DOUBLE_EQ(points[0].first.t(), 0.0); EXPECT_DOUBLE_EQ(points[0].second.s(), 1.0); EXPECT_DOUBLE_EQ(points[0].second.t(), 0.0); EXPECT_DOUBLE_EQ(points[1].first.s(), 0.4); EXPECT_DOUBLE_EQ(points[1].first.t(), 0.5); EXPECT_DOUBLE_EQ(points[1].second.s(), 1.4); EXPECT_DOUBLE_EQ(points[1].second.t(), 0.5); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/speed/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 = "st_point", srcs = ["st_point.cc"], hdrs = ["st_point.h"], deps = [ "//modules/common/math", "@com_github_gflags_gflags//:gflags", ], ) cc_library( name = "st_boundary", srcs = ["st_boundary.cc"], hdrs = ["st_boundary.h"], copts = PLANNING_COPTS, deps = [ ":st_point", "//cyber", "//modules/planning/common:planning_gflags", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@com_google_googletest//:gtest", ], ) cc_test( name = "st_boundary_test", size = "small", srcs = ["st_boundary_test.cc"], copts = PLANNING_COPTS, deps = [ ":st_boundary", "//cyber", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "speed_data", srcs = ["speed_data.cc"], hdrs = ["speed_data.h"], deps = [ ":st_point", "//modules/common/math", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/util", "//modules/common/util:util_tool", "//modules/planning/common:planning_context", "//modules/planning/common:planning_gflags", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@com_github_gflags_gflags//:gflags", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/speed/st_point.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 st_point.h **/ #pragma once #include <string> #include "modules/common/math/vec2d.h" namespace apollo { namespace planning { class STPoint : public common::math::Vec2d { // x-axis: t; y-axis: s. public: STPoint() = default; STPoint(const double s, const double t); explicit STPoint(const common::math::Vec2d& vec2d_point); double x() const = delete; double y() const = delete; double s() const; double t() const; void set_s(const double s); void set_t(const double t); std::string DebugString() const; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory1d/constant_deceleration_trajectory1d.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/common/trajectory1d/constant_deceleration_trajectory1d.h" #include <cmath> #include "cyber/common/log.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { ConstantDecelerationTrajectory1d::ConstantDecelerationTrajectory1d( const double init_s, const double init_v, const double a) : init_s_(init_s), init_v_(init_v), deceleration_(-a) { if (init_v_ < -FLAGS_numerical_epsilon) { AERROR << "negative init v = " << init_v_; } init_v_ = std::fabs(init_v_); ACHECK(deceleration_ > 0.0); end_t_ = init_v_ / deceleration_; end_s_ = init_v_ * init_v_ / (2.0 * deceleration_) + init_s_; } double ConstantDecelerationTrajectory1d::Evaluate_s(const double t) const { if (t < end_t_) { double curr_v = init_v_ - deceleration_ * t; double delta_s = (curr_v + init_v_) * t * 0.5; return init_s_ + delta_s; } else { return end_s_; } } double ConstantDecelerationTrajectory1d::Evaluate_v(const double t) const { if (t < end_t_) { return init_v_ - deceleration_ * t; } else { return 0.0; } } double ConstantDecelerationTrajectory1d::Evaluate_a(const double t) const { if (t < end_t_) { return -deceleration_; } else { return 0.0; } } double ConstantDecelerationTrajectory1d::Evaluate_j(const double t) const { return 0.0; } double ConstantDecelerationTrajectory1d::ParamLength() const { return end_t_; } std::string ConstantDecelerationTrajectory1d::ToString() const { return ""; } double ConstantDecelerationTrajectory1d::Evaluate(const std::uint32_t order, const double param) const { switch (order) { case 0: return Evaluate_s(param); case 1: return Evaluate_v(param); case 2: return Evaluate_a(param); case 3: return Evaluate_j(param); } return 0.0; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory1d/piecewise_jerk_trajectory1d.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/common/trajectory1d/piecewise_jerk_trajectory1d.h" #include <algorithm> #include "cyber/common/log.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { PiecewiseJerkTrajectory1d::PiecewiseJerkTrajectory1d(const double p, const double v, const double a) { last_p_ = p; last_v_ = v; last_a_ = a; param_.push_back(0.0); } void PiecewiseJerkTrajectory1d::AppendSegment(const double jerk, const double param) { CHECK_GT(param, FLAGS_numerical_epsilon); param_.push_back(param_.back() + param); segments_.emplace_back(last_p_, last_v_, last_a_, jerk, param); last_p_ = segments_.back().end_position(); last_v_ = segments_.back().end_velocity(); last_a_ = segments_.back().end_acceleration(); } double PiecewiseJerkTrajectory1d::Evaluate(const std::uint32_t order, const double param) const { auto it_lower = std::lower_bound(param_.begin(), param_.end(), param); if (it_lower == param_.begin()) { return segments_[0].Evaluate(order, param); } if (it_lower == param_.end()) { auto index = std::max(0, static_cast<int>(param_.size() - 2)); return segments_.back().Evaluate(order, param - param_[index]); } auto index = std::distance(param_.begin(), it_lower); return segments_[index - 1].Evaluate(order, param - param_[index - 1]); } double PiecewiseJerkTrajectory1d::ParamLength() const { return param_.back(); } std::string PiecewiseJerkTrajectory1d::ToString() const { return ""; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory1d/constant_jerk_trajectory1d.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 <string> #include "modules/planning/math/curve1d/curve1d.h" namespace apollo { namespace planning { class ConstantJerkTrajectory1d : public Curve1d { public: ConstantJerkTrajectory1d(const double p0, const double v0, const double a0, const double jerk, const double param); virtual ~ConstantJerkTrajectory1d() = default; double Evaluate(const std::uint32_t order, const double param) const; double ParamLength() const; std::string ToString() const; double start_position() const; double start_velocity() const; double start_acceleration() const; double end_position() const; double end_velocity() const; double end_acceleration() const; double jerk() const; private: double p0_; double v0_; double a0_; double p1_; double v1_; double a1_; double param_; double jerk_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory1d/standing_still_trajectory1d.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/common/trajectory1d/standing_still_trajectory1d.h" namespace apollo { namespace planning { StandingStillTrajectory1d::StandingStillTrajectory1d(const double p, const double duration) : fixed_position_(p), duration_(duration) {} double StandingStillTrajectory1d::ParamLength() const { return duration_; } std::string StandingStillTrajectory1d::ToString() const { return ""; } double StandingStillTrajectory1d::Evaluate(const std::uint32_t order, const double param) const { // ACHECK(param <= duration_); switch (order) { case 0: return Evaluate_s(param); case 1: return Evaluate_v(param); case 2: return Evaluate_a(param); case 3: return Evaluate_j(param); } return 0.0; } double StandingStillTrajectory1d::Evaluate_s(const double t) const { return fixed_position_; } double StandingStillTrajectory1d::Evaluate_v(const double t) const { return 0.0; } double StandingStillTrajectory1d::Evaluate_a(const double t) const { return 0.0; } double StandingStillTrajectory1d::Evaluate_j(const double t) const { return 0.0; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory1d/piecewise_acceleration_trajectory1d.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 <array> #include <string> #include <vector> #include "modules/planning/math/curve1d/curve1d.h" namespace apollo { namespace planning { class PiecewiseAccelerationTrajectory1d : public Curve1d { public: PiecewiseAccelerationTrajectory1d(const double start_s, const double start_v); virtual ~PiecewiseAccelerationTrajectory1d() = default; void AppendSegment(const double a, const double t_duration); void PopSegment(); double ParamLength() const override; std::string ToString() const override; double Evaluate(const std::uint32_t order, const double param) const override; std::array<double, 4> Evaluate(const double t) const; private: double Evaluate_s(const double t) const; double Evaluate_v(const double t) const; double Evaluate_a(const double t) const; double Evaluate_j(const double t) const; private: // accumulated s std::vector<double> s_; std::vector<double> v_; // accumulated t std::vector<double> t_; std::vector<double> a_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory1d/piecewise_acceleration_trajectory1d.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/common/trajectory1d/piecewise_acceleration_trajectory1d.h" #include <algorithm> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "cyber/common/log.h" #include "modules/common/math/linear_interpolation.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { PiecewiseAccelerationTrajectory1d::PiecewiseAccelerationTrajectory1d( const double start_s, const double start_v) { s_.push_back(start_s); v_.push_back(start_v); a_.push_back(0.0); t_.push_back(0.0); } void PiecewiseAccelerationTrajectory1d::AppendSegment(const double a, const double t_duration) { double s0 = s_.back(); double v0 = v_.back(); double t0 = t_.back(); double v1 = v0 + a * t_duration; ACHECK(v1 >= -FLAGS_numerical_epsilon); double delta_s = (v0 + v1) * t_duration * 0.5; double s1 = s0 + delta_s; double t1 = t0 + t_duration; ACHECK(s1 >= s0 - FLAGS_numerical_epsilon); s1 = std::max(s1, s0); s_.push_back(s1); v_.push_back(v1); a_.push_back(a); t_.push_back(t1); } void PiecewiseAccelerationTrajectory1d::PopSegment() { if (a_.size() > 0) { s_.pop_back(); v_.pop_back(); a_.pop_back(); t_.pop_back(); } } double PiecewiseAccelerationTrajectory1d::ParamLength() const { CHECK_GT(t_.size(), 1U); return t_.back() - t_.front(); } std::string PiecewiseAccelerationTrajectory1d::ToString() const { return absl::StrCat(absl::StrJoin(s_, "\t"), absl::StrJoin(t_, "\t"), absl::StrJoin(v_, "\t"), absl::StrJoin(a_, "\t"), "\n"); } double PiecewiseAccelerationTrajectory1d::Evaluate(const std::uint32_t order, const double param) const { CHECK_GT(t_.size(), 1U); ACHECK(t_.front() <= param && param <= t_.back()); switch (order) { case 0: return Evaluate_s(param); case 1: return Evaluate_v(param); case 2: return Evaluate_a(param); case 3: return Evaluate_j(param); } return 0.0; } double PiecewiseAccelerationTrajectory1d::Evaluate_s(const double t) const { auto it_lower = std::lower_bound(t_.begin(), t_.end(), t); auto index = std::distance(t_.begin(), it_lower); double s0 = s_[index - 1]; double v0 = v_[index - 1]; double t0 = t_[index - 1]; double v1 = v_[index]; double t1 = t_[index]; double v = common::math::lerp(v0, t0, v1, t1, t); double s = (v0 + v) * (t - t0) * 0.5 + s0; return s; } double PiecewiseAccelerationTrajectory1d::Evaluate_v(const double t) const { auto it_lower = std::lower_bound(t_.begin(), t_.end(), t); auto index = std::distance(t_.begin(), it_lower); double v0 = v_[index - 1]; double t0 = t_[index - 1]; double v1 = v_[index]; double t1 = t_[index]; double v = apollo::common::math::lerp(v0, t0, v1, t1, t); return v; } double PiecewiseAccelerationTrajectory1d::Evaluate_a(const double t) const { auto it_lower = std::lower_bound(t_.begin(), t_.end(), t); auto index = std::distance(t_.begin(), it_lower); return a_[index - 1]; } double PiecewiseAccelerationTrajectory1d::Evaluate_j(const double t) const { return 0.0; } std::array<double, 4> PiecewiseAccelerationTrajectory1d::Evaluate( const double t) const { CHECK_GT(t_.size(), 1U); ACHECK(t_.front() <= t && t <= t_.back()); auto it_lower = std::lower_bound(t_.begin(), t_.end(), t); auto index = std::distance(t_.begin(), it_lower); double s0 = s_[index - 1]; double v0 = v_[index - 1]; double t0 = t_[index - 1]; double v1 = v_[index]; double t1 = t_[index]; double v = common::math::lerp(v0, t0, v1, t1, t); double s = (v0 + v) * (t - t0) * 0.5 + s0; double a = a_[index - 1]; double j = 0.0; return {{s, v, a, j}}; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory1d/piecewise_trajectory1d.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/common/trajectory1d/piecewise_trajectory1d.h" #include <cmath> #include "cyber/common/log.h" namespace apollo { namespace planning { double PiecewiseTrajectory1d::Evaluate(const std::uint32_t order, const double param) const { auto it_lower = std::lower_bound(accumulated_param_lengths_.begin(), accumulated_param_lengths_.end(), param); ACHECK(it_lower != accumulated_param_lengths_.end()); size_t index = (size_t)(it_lower - accumulated_param_lengths_.begin()); double param_overhead = 0.0; if (index != 0) { param_overhead = accumulated_param_lengths_[index - 1]; } return trajectory_segments_[index]->Evaluate(order, param - param_overhead); } double PiecewiseTrajectory1d::ParamLength() const { if (accumulated_param_lengths_.empty()) { return 0.0; } return accumulated_param_lengths_.back(); } std::string PiecewiseTrajectory1d::ToString() const { return ""; } void PiecewiseTrajectory1d::AppendSegment( const std::shared_ptr<Curve1d> trajectory) { if (trajectory_segments_.empty()) { trajectory_segments_.push_back(trajectory); } else { double s1 = trajectory->Evaluate(0, 0.0); double v1 = trajectory->Evaluate(1, 0.0); double a1 = trajectory->Evaluate(2, 0.0); double j1 = trajectory->Evaluate(3, 0.0); auto last_trajectory = trajectory_segments_.back(); double last_param_length = last_trajectory->ParamLength(); double s0 = last_trajectory->Evaluate(0, last_param_length); double v0 = last_trajectory->Evaluate(1, last_param_length); double a0 = last_trajectory->Evaluate(2, last_param_length); double j0 = last_trajectory->Evaluate(3, last_param_length); if (std::fabs(s0 - s1) > 1.0e-4) { AWARN << "The appended segment is not smooth in order 0"; } if (std::fabs(v0 - v1) > 1.0e-4) { AWARN << "The appended segment is not smooth in order 1"; } if (std::fabs(a0 - a1) > 1.0e-4) { AWARN << "The appended segment is not smooth in order 2"; } if (std::fabs(j0 - j1) > 1.0e-4) { AWARN << "The appended segment is not smooth in order 3"; } trajectory_segments_.push_back(trajectory); } double accumulated_param_length = trajectory->ParamLength(); if (accumulated_param_lengths_.size() > 0) { accumulated_param_length += accumulated_param_lengths_.back(); } accumulated_param_lengths_.push_back(accumulated_param_length); } void PiecewiseTrajectory1d::PopSegment() { if (trajectory_segments_.empty()) { return; } trajectory_segments_.pop_back(); accumulated_param_lengths_.pop_back(); } size_t PiecewiseTrajectory1d::NumOfSegments() const { return trajectory_segments_.size(); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory1d/constant_deceleration_trajectory1d.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/planning/math/curve1d/curve1d.h" namespace apollo { namespace planning { class ConstantDecelerationTrajectory1d : public Curve1d { public: ConstantDecelerationTrajectory1d(const double init_s, const double init_v, const double a); virtual ~ConstantDecelerationTrajectory1d() = default; double ParamLength() const override; std::string ToString() const override; // handles extrapolation internally double Evaluate(const std::uint32_t order, const double param) const override; private: double Evaluate_s(const double t) const; double Evaluate_v(const double t) const; double Evaluate_a(const double t) const; double Evaluate_j(const double t) const; double init_s_; double init_v_; double deceleration_; double end_t_; double end_s_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory1d/piecewise_trajectory1d.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/planning/math/curve1d/curve1d.h" namespace apollo { namespace planning { class PiecewiseTrajectory1d : public Curve1d { public: PiecewiseTrajectory1d() = default; virtual ~PiecewiseTrajectory1d() = default; double Evaluate(const std::uint32_t order, const double param) const; double ParamLength() const; std::string ToString() const; void AppendSegment(const std::shared_ptr<Curve1d> trajectory); void PopSegment(); size_t NumOfSegments() const; private: std::vector<std::shared_ptr<Curve1d>> trajectory_segments_; std::vector<double> accumulated_param_lengths_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory1d/standing_still_trajectory1d.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/planning/math/curve1d/curve1d.h" namespace apollo { namespace planning { class StandingStillTrajectory1d : public Curve1d { public: StandingStillTrajectory1d(const double p, const double duration); virtual ~StandingStillTrajectory1d() = default; double ParamLength() const override; std::string ToString() const override; double Evaluate(const std::uint32_t order, const double param) const override; private: double Evaluate_s(const double t) const; double Evaluate_v(const double t) const; double Evaluate_a(const double t) const; double Evaluate_j(const double t) const; private: double fixed_position_; double duration_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory1d/constant_jerk_trajectory1d.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/common/trajectory1d/constant_jerk_trajectory1d.h" #include "cyber/common/log.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { ConstantJerkTrajectory1d::ConstantJerkTrajectory1d(const double p0, const double v0, const double a0, const double j, const double param) : p0_(p0), v0_(v0), a0_(a0), param_(param), jerk_(j) { CHECK_GT(param, FLAGS_numerical_epsilon); p1_ = Evaluate(0, param_); v1_ = Evaluate(1, param_); a1_ = Evaluate(2, param_); } double ConstantJerkTrajectory1d::Evaluate(const std::uint32_t order, const double param) const { switch (order) { case 0: { return p0_ + v0_ * param + 0.5 * a0_ * param * param + jerk_ * param * param * param / 6.0; } case 1: { return v0_ + a0_ * param + 0.5 * jerk_ * param * param; } case 2: { return a0_ + jerk_ * param; } case 3: { return jerk_; } default: return 0.0; } } double ConstantJerkTrajectory1d::start_position() const { return p0_; } double ConstantJerkTrajectory1d::start_velocity() const { return v0_; } double ConstantJerkTrajectory1d::start_acceleration() const { return a0_; } double ConstantJerkTrajectory1d::end_position() const { return p1_; } double ConstantJerkTrajectory1d::end_velocity() const { return v1_; } double ConstantJerkTrajectory1d::end_acceleration() const { return a1_; } double ConstantJerkTrajectory1d::ParamLength() const { return param_; } std::string ConstantJerkTrajectory1d::ToString() const { return ""; } double ConstantJerkTrajectory1d::jerk() const { return jerk_; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory1d/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "standing_still_trajectory1d", srcs = ["standing_still_trajectory1d.cc"], hdrs = ["standing_still_trajectory1d.h"], deps = [ "//cyber", "//modules/planning/math/curve1d", ], ) cc_library( name = "piecewise_acceleration_trajectory1d", srcs = ["piecewise_acceleration_trajectory1d.cc"], hdrs = ["piecewise_acceleration_trajectory1d.h"], deps = [ "//modules/common/math", "//modules/planning/common:planning_gflags", "//modules/planning/math/curve1d", ], ) cc_library( name = "constant_deceleration_trajectory1d", srcs = ["constant_deceleration_trajectory1d.cc"], hdrs = ["constant_deceleration_trajectory1d.h"], deps = [ "//cyber", "//modules/planning/common:planning_gflags", "//modules/planning/math/curve1d", ], ) cc_library( name = "piecewise_trajectory1d", srcs = ["piecewise_trajectory1d.cc"], hdrs = ["piecewise_trajectory1d.h"], deps = [ "//modules/common/math", "//modules/planning/math/curve1d", ], ) cc_library( name = "constant_jerk_trajectory1d", srcs = ["constant_jerk_trajectory1d.cc"], hdrs = ["constant_jerk_trajectory1d.h"], deps = [ "//cyber", "//modules/planning/common:planning_gflags", "//modules/planning/math/curve1d", ], ) cc_library( name = "piecewise_jerk_trajectory1d", srcs = ["piecewise_jerk_trajectory1d.cc"], hdrs = ["piecewise_jerk_trajectory1d.h"], deps = [ ":constant_jerk_trajectory1d", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory1d/piecewise_jerk_trajectory1d.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 <string> #include <vector> #include "modules/planning/common/trajectory1d/constant_jerk_trajectory1d.h" #include "modules/planning/math/curve1d/curve1d.h" namespace apollo { namespace planning { class PiecewiseJerkTrajectory1d : public Curve1d { public: PiecewiseJerkTrajectory1d(const double p, const double v, const double a); virtual ~PiecewiseJerkTrajectory1d() = default; double Evaluate(const std::uint32_t order, const double param) const; double ParamLength() const; std::string ToString() const; void AppendSegment(const double jerk, const double param); private: std::vector<ConstantJerkTrajectory1d> segments_; double last_p_; double last_v_; double last_a_; std::vector<double> param_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/path/frenet_frame_path.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 frenet_frame_path.cc **/ #include "modules/planning/common/path/frenet_frame_path.h" #include <algorithm> #include <limits> #include "cyber/common/log.h" #include "modules/common/math/linear_interpolation.h" namespace apollo { namespace planning { using apollo::common::FrenetFramePoint; FrenetFramePath::FrenetFramePath(std::vector<FrenetFramePoint> points) : std::vector<FrenetFramePoint>(std::move(points)) {} double FrenetFramePath::Length() const { if (empty()) { return 0.0; } return back().s() - front().s(); } FrenetFramePoint FrenetFramePath::GetNearestPoint(const SLBoundary& sl) const { auto it_lower = std::lower_bound(begin(), end(), sl.start_s(), LowerBoundComparator); if (it_lower == end()) { return back(); } auto it_upper = std::upper_bound(it_lower, end(), sl.end_s(), UpperBoundComparator); double min_dist = std::numeric_limits<double>::max(); auto min_it = it_upper; for (auto it = it_lower; it != it_upper; ++it) { if (it->l() >= sl.start_l() && it->l() <= sl.end_l()) { return *it; } else if (it->l() > sl.end_l()) { double diff = it->l() - sl.end_l(); if (diff < min_dist) { min_dist = diff; min_it = it; } } else { double diff = sl.start_l() - it->l(); if (diff < min_dist) { min_dist = diff; min_it = it; } } } return *min_it; } FrenetFramePoint FrenetFramePath::EvaluateByS(const double s) const { CHECK_GT(size(), 1U); auto it_lower = std::lower_bound(begin(), end(), s, LowerBoundComparator); if (it_lower == begin()) { return front(); } else if (it_lower == end()) { return back(); } const auto& p0 = *(it_lower - 1); const auto s0 = p0.s(); const auto& p1 = *it_lower; const auto s1 = p1.s(); FrenetFramePoint p; p.set_s(s); p.set_l(common::math::lerp(p0.l(), s0, p1.l(), s1, s)); p.set_dl(common::math::lerp(p0.dl(), s0, p1.dl(), s1, s)); p.set_ddl(common::math::lerp(p0.ddl(), s0, p1.ddl(), s1, s)); return p; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/path/path_data.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 path_data.cc **/ #include "modules/planning/common/path/path_data.h" #include <algorithm> #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "cyber/common/log.h" #include "modules/common/math/cartesian_frenet_conversion.h" #include "modules/common/util/point_factory.h" #include "modules/common/util/string_util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::PathPoint; using apollo::common::PointENU; using apollo::common::SLPoint; using apollo::common::math::CartesianFrenetConverter; using apollo::common::util::PointFactory; bool PathData::SetDiscretizedPath(DiscretizedPath path) { if (reference_line_ == nullptr) { AERROR << "Should NOT set discretized path when reference line is nullptr. " "Please set reference line first."; return false; } discretized_path_ = std::move(path); if (!XYToSL(discretized_path_, &frenet_path_)) { AERROR << "Fail to transfer discretized path to frenet path."; return false; } DCHECK_EQ(discretized_path_.size(), frenet_path_.size()); return true; } bool PathData::SetFrenetPath(FrenetFramePath frenet_path) { if (reference_line_ == nullptr) { AERROR << "Should NOT set frenet path when reference line is nullptr. " "Please set reference line first."; return false; } frenet_path_ = std::move(frenet_path); if (!SLToXY(frenet_path_, &discretized_path_)) { AERROR << "Fail to transfer frenet path to discretized path."; return false; } DCHECK_EQ(discretized_path_.size(), frenet_path_.size()); return true; } bool PathData::SetPathPointDecisionGuide( std::vector<std::tuple<double, PathPointType, double>> path_point_decision_guide) { if (reference_line_ == nullptr) { AERROR << "Should NOT set path_point_decision_guide when reference line is " "nullptr. "; return false; } if (frenet_path_.empty() || discretized_path_.empty()) { AERROR << "Should NOT set path_point_decision_guide when frenet_path or " "world frame trajectory is empty. "; return false; } path_point_decision_guide_ = std::move(path_point_decision_guide); return true; } const DiscretizedPath &PathData::discretized_path() const { return discretized_path_; } const FrenetFramePath &PathData::frenet_frame_path() const { return frenet_path_; } const std::vector<std::tuple<double, PathData::PathPointType, double>> &PathData::path_point_decision_guide() const { return path_point_decision_guide_; } bool PathData::Empty() const { return discretized_path_.empty() && frenet_path_.empty(); } void PathData::SetReferenceLine(const ReferenceLine *reference_line) { Clear(); reference_line_ = reference_line; } common::PathPoint PathData::GetPathPointWithPathS(const double s) const { return discretized_path_.Evaluate(s); } bool PathData::GetPathPointWithRefS(const double ref_s, common::PathPoint *const path_point) const { ACHECK(reference_line_); DCHECK_EQ(discretized_path_.size(), frenet_path_.size()); if (ref_s < 0) { AERROR << "ref_s[" << ref_s << "] should be > 0"; return false; } if (ref_s > frenet_path_.back().s()) { AERROR << "ref_s is larger than the length of frenet_path_ length [" << frenet_path_.back().s() << "]."; return false; } uint32_t index = 0; const double kDistanceEpsilon = 1e-3; for (uint32_t i = 0; i + 1 < frenet_path_.size(); ++i) { if (fabs(ref_s - frenet_path_.at(i).s()) < kDistanceEpsilon) { path_point->CopyFrom(discretized_path_.at(i)); return true; } if (frenet_path_.at(i).s() < ref_s && ref_s <= frenet_path_.at(i + 1).s()) { index = i; break; } } double r = (ref_s - frenet_path_.at(index).s()) / (frenet_path_.at(index + 1).s() - frenet_path_.at(index).s()); const double discretized_path_s = discretized_path_.at(index).s() + r * (discretized_path_.at(index + 1).s() - discretized_path_.at(index).s()); path_point->CopyFrom(discretized_path_.Evaluate(discretized_path_s)); return true; } void PathData::Clear() { discretized_path_.clear(); frenet_path_.clear(); path_point_decision_guide_.clear(); path_reference_.clear(); reference_line_ = nullptr; } std::string PathData::DebugString() const { const auto limit = std::min(discretized_path_.size(), static_cast<size_t>(FLAGS_trajectory_point_num_for_debug)); return absl::StrCat( "[\n", absl::StrJoin(discretized_path_.begin(), discretized_path_.begin() + limit, ",\n", apollo::common::util::DebugStringFormatter()), "]\n"); } bool PathData::SLToXY(const FrenetFramePath &frenet_path, DiscretizedPath *const discretized_path) { std::vector<common::PathPoint> path_points; for (const common::FrenetFramePoint &frenet_point : frenet_path) { const common::SLPoint sl_point = PointFactory::ToSLPoint(frenet_point.s(), frenet_point.l()); common::math::Vec2d cartesian_point; if (!reference_line_->SLToXY(sl_point, &cartesian_point)) { AERROR << "Fail to convert sl point to xy point"; return false; } const ReferencePoint ref_point = reference_line_->GetReferencePoint(frenet_point.s()); const double theta = CartesianFrenetConverter::CalculateTheta( ref_point.heading(), ref_point.kappa(), frenet_point.l(), frenet_point.dl()); ADEBUG << "frenet_point: " << frenet_point.ShortDebugString(); const double kappa = CartesianFrenetConverter::CalculateKappa( ref_point.kappa(), ref_point.dkappa(), frenet_point.l(), frenet_point.dl(), frenet_point.ddl()); double s = 0.0; double dkappa = 0.0; if (!path_points.empty()) { common::math::Vec2d last = PointFactory::ToVec2d(path_points.back()); const double distance = (last - cartesian_point).Length(); s = path_points.back().s() + distance; dkappa = (kappa - path_points.back().kappa()) / distance; } path_points.push_back(PointFactory::ToPathPoint(cartesian_point.x(), cartesian_point.y(), 0.0, s, theta, kappa, dkappa)); } *discretized_path = DiscretizedPath(std::move(path_points)); return true; } bool PathData::XYToSL(const DiscretizedPath &discretized_path, FrenetFramePath *const frenet_path) { ACHECK(reference_line_); std::vector<common::FrenetFramePoint> frenet_frame_points; const double max_len = reference_line_->Length(); for (const auto &path_point : discretized_path) { common::FrenetFramePoint frenet_point = reference_line_->GetFrenetPoint(path_point); if (!frenet_point.has_s()) { SLPoint sl_point; if (!reference_line_->XYToSL(path_point, &sl_point)) { AERROR << "Fail to transfer cartesian point to frenet point."; return false; } common::FrenetFramePoint frenet_point; // NOTICE: does not set dl and ddl here. Add if needed. frenet_point.set_s(std::max(0.0, std::min(sl_point.s(), max_len))); frenet_point.set_l(sl_point.l()); frenet_frame_points.push_back(std::move(frenet_point)); continue; } frenet_point.set_s(std::max(0.0, std::min(frenet_point.s(), max_len))); frenet_frame_points.push_back(std::move(frenet_point)); } *frenet_path = FrenetFramePath(std::move(frenet_frame_points)); return true; } bool PathData::LeftTrimWithRefS(const common::FrenetFramePoint &frenet_point) { ACHECK(reference_line_); std::vector<common::FrenetFramePoint> frenet_frame_points; frenet_frame_points.emplace_back(frenet_point); for (const common::FrenetFramePoint fp : frenet_path_) { if (std::fabs(fp.s() - frenet_point.s()) < 1e-6) { continue; } if (fp.s() > frenet_point.s()) { frenet_frame_points.push_back(fp); } } SetFrenetPath(FrenetFramePath(std::move(frenet_frame_points))); return true; } bool PathData::UpdateFrenetFramePath(const ReferenceLine *reference_line) { reference_line_ = reference_line; return SetDiscretizedPath(discretized_path_); } void PathData::set_path_label(const std::string &label) { path_label_ = label; } const std::string &PathData::path_label() const { return path_label_; } const std::vector<PathPoint> &PathData::path_reference() const { return path_reference_; } void PathData::set_path_reference( const std::vector<PathPoint> &path_reference) { path_reference_ = std::move(path_reference); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/path/path_data.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 path_data.h **/ #pragma once #include <list> #include <string> #include <tuple> #include <utility> #include <vector> #include "modules/planning/common/path/discretized_path.h" #include "modules/planning/common/path/frenet_frame_path.h" #include "modules/planning/reference_line/reference_line.h" namespace apollo { namespace planning { class PathData { public: enum class PathPointType { IN_LANE, OUT_ON_FORWARD_LANE, OUT_ON_REVERSE_LANE, OFF_ROAD, UNKNOWN, }; PathData() = default; bool SetDiscretizedPath(DiscretizedPath path); bool SetFrenetPath(FrenetFramePath frenet_path); void SetReferenceLine(const ReferenceLine *reference_line); bool SetPathPointDecisionGuide( std::vector<std::tuple<double, PathPointType, double>> path_point_decision_guide); const DiscretizedPath &discretized_path() const; const FrenetFramePath &frenet_frame_path() const; const std::vector<std::tuple<double, PathPointType, double>> &path_point_decision_guide() const; common::PathPoint GetPathPointWithPathS(const double s) const; /* * brief: this function will find the path_point in discretized_path whose * projection to reference line has s value closest to ref_s. */ bool GetPathPointWithRefS(const double ref_s, common::PathPoint *const path_point) const; bool LeftTrimWithRefS(const common::FrenetFramePoint &frenet_point); bool UpdateFrenetFramePath(const ReferenceLine *reference_line); void Clear(); bool Empty() const; std::string DebugString() const; void set_path_label(const std::string &label); const std::string &path_label() const; void set_blocking_obstacle_id(const std::string &obs_id) { blocking_obstacle_id_ = obs_id; } const std::string &blocking_obstacle_id() const { return blocking_obstacle_id_; } const bool is_valid_path_reference() const { return is_valid_path_reference_; } void set_is_valid_path_reference(bool is_valid_path_reference) { is_valid_path_reference_ = is_valid_path_reference; } const bool is_optimized_towards_trajectory_reference() const { return is_optimized_towards_trajectory_reference_; } void set_is_optimized_towards_trajectory_reference( bool is_optimized_towards_trajectory_reference) { is_optimized_towards_trajectory_reference_ = is_optimized_towards_trajectory_reference; } const std::vector<common::PathPoint> &path_reference() const; void set_path_reference(const std::vector<common::PathPoint> &path_reference); private: /* * convert frenet path to cartesian path by reference line */ bool SLToXY(const FrenetFramePath &frenet_path, DiscretizedPath *const discretized_path); bool XYToSL(const DiscretizedPath &discretized_path, FrenetFramePath *const frenet_path); const ReferenceLine *reference_line_ = nullptr; DiscretizedPath discretized_path_; FrenetFramePath frenet_path_; /** * @brief speed decision generated by path analyzer for guiding speed limit * generation in speed bounds decider * @param tuple consists of s axis position on reference line; PathPointType * Enum; distance to closest obstacle */ std::vector<std::tuple<double, PathPointType, double>> path_point_decision_guide_; std::string path_label_ = ""; std::string blocking_obstacle_id_; /** * @brief parameters for using the learning model output as a path reference * */ // wheter this PathData is a path reference serving as an optimization target // for later modules bool is_valid_path_reference_ = false; /** * @brief Given a trajectory reference, whether this PathData is optimized * according to the "path" part of the trajectory so that "speed" part of the * trajectory could be used in later modules accordingly * */ bool is_optimized_towards_trajectory_reference_ = false; // path reference std::vector<common::PathPoint> path_reference_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/path/discretized_path.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 discretized_path.h **/ #pragma once #include <utility> #include <vector> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" namespace apollo { namespace planning { class DiscretizedPath : public std::vector<common::PathPoint> { public: DiscretizedPath() = default; explicit DiscretizedPath(std::vector<common::PathPoint> path_points); double Length() const; common::PathPoint Evaluate(const double path_s) const; common::PathPoint EvaluateReverse(const double path_s) const; protected: std::vector<common::PathPoint>::const_iterator QueryLowerBound( const double path_s) const; std::vector<common::PathPoint>::const_iterator QueryUpperBound( const double path_s) const; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/path/frenet_frame_path.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 frenet_frame_path.h **/ #pragma once #include <utility> #include <vector> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common_msgs/planning_msgs/sl_boundary.pb.h" namespace apollo { namespace planning { class FrenetFramePath : public std::vector<common::FrenetFramePoint> { public: FrenetFramePath() = default; explicit FrenetFramePath(std::vector<common::FrenetFramePoint> points); double Length() const; common::FrenetFramePoint EvaluateByS(const double s) const; /** * @brief Get the FrenetFramePoint that is within SLBoundary, or the one with * smallest l() in SLBoundary's s range [start_s(), end_s()] */ common::FrenetFramePoint GetNearestPoint(const SLBoundary &sl) const; private: static bool LowerBoundComparator(const common::FrenetFramePoint &p, const double s) { return p.s() < s; } static bool UpperBoundComparator(const double s, const common::FrenetFramePoint &p) { return s < p.s(); } }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/path/frenet_frame_path_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/common/path/frenet_frame_path.h" #include "gtest/gtest.h" namespace apollo { namespace planning { using apollo::common::FrenetFramePoint; class FrenetFramePathTest : public ::testing::Test { public: void InitFrenetFramePath() { std::vector<double> s{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; std::vector<double> l{1, 2, 1, 0, -1, -2, -1, 0, 1, 2}; std::vector<double> dl{1, 0, -1, 0, -1, 0, 1, 1, 1, 0}; std::vector<double> ddl{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; std::vector<FrenetFramePoint> sl_points; for (size_t i = 0; i < s.size(); ++i) { sl_points.emplace_back(); FrenetFramePoint& point = sl_points.back(); point.set_s(s[i]); point.set_l(l[i]); point.set_dl(dl[i]); point.set_ddl(ddl[i]); } path_.reset(new FrenetFramePath(std::move(sl_points))); } void SetUp() { InitFrenetFramePath(); } std::unique_ptr<FrenetFramePath> path_; }; TEST_F(FrenetFramePathTest, GetNearestPoint) { SLBoundary sl_boundary; { // at the beginning sl_boundary.set_start_s(-2); sl_boundary.set_end_s(-1); sl_boundary.set_start_l(0); sl_boundary.set_end_l(1); auto nearest = path_->GetNearestPoint(sl_boundary); EXPECT_DOUBLE_EQ(nearest.s(), 1.0); EXPECT_DOUBLE_EQ(nearest.l(), 1.0); EXPECT_DOUBLE_EQ(nearest.dl(), 1.0); EXPECT_DOUBLE_EQ(nearest.ddl(), 0.0); } { // at the end sl_boundary.set_start_s(11); sl_boundary.set_end_s(12); sl_boundary.set_start_l(0); sl_boundary.set_end_l(1); auto nearest = path_->GetNearestPoint(sl_boundary); EXPECT_DOUBLE_EQ(nearest.s(), 10.0); EXPECT_DOUBLE_EQ(nearest.l(), 2.0); EXPECT_DOUBLE_EQ(nearest.dl(), 0.0); EXPECT_DOUBLE_EQ(nearest.ddl(), 0.0); } { // in the middle, left side sl_boundary.set_start_s(1); sl_boundary.set_end_s(9); sl_boundary.set_start_l(3); sl_boundary.set_end_l(4); auto nearest = path_->GetNearestPoint(sl_boundary); EXPECT_DOUBLE_EQ(nearest.s(), 2.0); EXPECT_DOUBLE_EQ(nearest.l(), 2.0); EXPECT_DOUBLE_EQ(nearest.dl(), 0.0); EXPECT_DOUBLE_EQ(nearest.ddl(), 0.0); } { // in the middle, right side sl_boundary.set_start_s(1); sl_boundary.set_end_s(9); sl_boundary.set_start_l(-4); sl_boundary.set_end_l(-3); auto nearest = path_->GetNearestPoint(sl_boundary); EXPECT_DOUBLE_EQ(nearest.s(), 6.0); EXPECT_DOUBLE_EQ(nearest.l(), -2.0); EXPECT_DOUBLE_EQ(nearest.dl(), 0.0); EXPECT_DOUBLE_EQ(nearest.ddl(), 0.0); } { // in the middle, cross sl_boundary.set_start_s(1); sl_boundary.set_end_s(9); sl_boundary.set_start_l(-1); sl_boundary.set_end_l(0); auto nearest = path_->GetNearestPoint(sl_boundary); EXPECT_DOUBLE_EQ(nearest.s(), 4.0); EXPECT_DOUBLE_EQ(nearest.l(), 0.0); EXPECT_DOUBLE_EQ(nearest.dl(), 0.0); EXPECT_DOUBLE_EQ(nearest.ddl(), 0.0); } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/path/discretized_path_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/common/path/discretized_path.h" #include "cyber/common/log.h" #include "gtest/gtest.h" #include "modules/common/util/point_factory.h" namespace apollo { namespace planning { using apollo::common::PathPoint; using apollo::common::util::PointFactory; TEST(DiscretizedPathTest, basic_test) { const double s1 = 0.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); PathPoint p1 = PointFactory::ToPathPoint(0.0, 0.0, 0.0, s1); PathPoint p2 = PointFactory::ToPathPoint(1.0, 1.0, 0.0, s2); PathPoint p3 = PointFactory::ToPathPoint(2.0, 2.0, 0.0, s3); PathPoint p4 = PointFactory::ToPathPoint(3.0, 3.0, 0.0, s4); std::vector<PathPoint> path_points{p1, p2, p3, p4}; DiscretizedPath discretized_path(path_points); EXPECT_EQ(discretized_path.size(), 4); EXPECT_DOUBLE_EQ(discretized_path.Length(), std::sqrt(1.0 + 1.0) * 3.0); auto eval_p1 = discretized_path.Evaluate(0.0); EXPECT_DOUBLE_EQ(eval_p1.s(), 0.0); EXPECT_DOUBLE_EQ(eval_p1.x(), 0.0); EXPECT_DOUBLE_EQ(eval_p1.y(), 0.0); auto eval_p2 = discretized_path.Evaluate(0.3 * std::sqrt(2.0)); EXPECT_DOUBLE_EQ(eval_p2.s(), 0.3 * std::sqrt(2.0)); EXPECT_DOUBLE_EQ(eval_p2.x(), 0.3); EXPECT_DOUBLE_EQ(eval_p2.y(), 0.3); auto eval_p3 = discretized_path.Evaluate(1.8); EXPECT_DOUBLE_EQ(eval_p3.s(), 1.8); EXPECT_DOUBLE_EQ(eval_p3.x(), (1.0 + 0.8) / std::sqrt(2)); EXPECT_DOUBLE_EQ(eval_p3.y(), (1.0 + 0.8) / std::sqrt(2)); auto eval_p4 = discretized_path.Evaluate(2.5); EXPECT_DOUBLE_EQ(eval_p4.s(), 2.5); EXPECT_DOUBLE_EQ(eval_p4.x(), (2.0 + 0.5) / std::sqrt(2)); EXPECT_DOUBLE_EQ(eval_p4.y(), (2.0 + 0.5) / std::sqrt(2)); discretized_path.clear(); EXPECT_EQ(discretized_path.size(), 0); } TEST(DiscretizedPathTest, reverse_case) { const double s1 = 0.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); PathPoint p1 = PointFactory::ToPathPoint(0.0, 0.0, 0.0, s1); PathPoint p2 = PointFactory::ToPathPoint(1.0, 1.0, 0.0, s2); PathPoint p3 = PointFactory::ToPathPoint(2.0, 2.0, 0.0, s3); PathPoint p4 = PointFactory::ToPathPoint(3.0, 3.0, 0.0, s4); std::vector<PathPoint> path_points{p1, p2, p3, p4}; DiscretizedPath discretized_path(path_points); EXPECT_EQ(discretized_path.size(), 4); EXPECT_DOUBLE_EQ(discretized_path.Length(), -std::sqrt(1.0 + 1.0) * 3.0); auto eval_p1 = discretized_path.EvaluateReverse(0.0); EXPECT_DOUBLE_EQ(eval_p1.s(), 0.0); EXPECT_DOUBLE_EQ(eval_p1.x(), 0.0); EXPECT_DOUBLE_EQ(eval_p1.y(), 0.0); auto eval_p2 = discretized_path.EvaluateReverse(-0.3 * std::sqrt(2.0)); EXPECT_DOUBLE_EQ(eval_p2.s(), -0.3 * std::sqrt(2.0)); EXPECT_DOUBLE_EQ(eval_p2.x(), 0.3); EXPECT_DOUBLE_EQ(eval_p2.y(), 0.3); auto eval_p3 = discretized_path.EvaluateReverse(-1.8); EXPECT_DOUBLE_EQ(eval_p3.s(), -1.8); EXPECT_DOUBLE_EQ(eval_p3.x(), (1.0 + 0.8) / std::sqrt(2)); EXPECT_DOUBLE_EQ(eval_p3.y(), (1.0 + 0.8) / std::sqrt(2)); auto eval_p4 = discretized_path.EvaluateReverse(-2.5); EXPECT_DOUBLE_EQ(eval_p4.s(), -2.5); EXPECT_DOUBLE_EQ(eval_p4.x(), (2.0 + 0.5) / std::sqrt(2)); EXPECT_DOUBLE_EQ(eval_p4.y(), (2.0 + 0.5) / std::sqrt(2)); discretized_path.clear(); EXPECT_EQ(discretized_path.size(), 0); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/path/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 = "discretized_path", srcs = ["discretized_path.cc"], hdrs = ["discretized_path.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/math", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", ], ) cc_test( name = "discretized_path_test", size = "small", srcs = ["discretized_path_test.cc"], deps = [ ":discretized_path", "//modules/common/util", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "frenet_frame_path", srcs = ["frenet_frame_path.cc"], hdrs = ["frenet_frame_path.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/math", "//modules/common_msgs/planning_msgs:planning_cc_proto", ], ) cc_test( name = "frenet_frame_path_test", size = "small", srcs = ["frenet_frame_path_test.cc"], deps = [ ":frenet_frame_path", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_library( name = "path_data", srcs = ["path_data.cc"], hdrs = ["path_data.h"], copts = PLANNING_COPTS, deps = [ ":discretized_path", ":frenet_frame_path", "//modules/common/math", "//modules/planning/common:planning_gflags", "//modules/planning/reference_line", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/path/discretized_path.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 path.cc **/ #include "modules/planning/common/path/discretized_path.h" #include <algorithm> #include "cyber/common/log.h" #include "modules/common/math/linear_interpolation.h" namespace apollo { namespace planning { using apollo::common::PathPoint; DiscretizedPath::DiscretizedPath(std::vector<PathPoint> path_points) : std::vector<PathPoint>(std::move(path_points)) {} double DiscretizedPath::Length() const { if (empty()) { return 0.0; } return back().s() - front().s(); } PathPoint DiscretizedPath::Evaluate(const double path_s) const { ACHECK(!empty()); auto it_lower = QueryLowerBound(path_s); if (it_lower == begin()) { return front(); } if (it_lower == end()) { return back(); } return common::math::InterpolateUsingLinearApproximation(*(it_lower - 1), *it_lower, path_s); } std::vector<PathPoint>::const_iterator DiscretizedPath::QueryLowerBound( const double path_s) const { auto func = [](const PathPoint &tp, const double path_s) { return tp.s() < path_s; }; return std::lower_bound(begin(), end(), path_s, func); } PathPoint DiscretizedPath::EvaluateReverse(const double path_s) const { ACHECK(!empty()); auto it_upper = QueryUpperBound(path_s); if (it_upper == begin()) { return front(); } if (it_upper == end()) { return back(); } return common::math::InterpolateUsingLinearApproximation(*(it_upper - 1), *it_upper, path_s); } std::vector<PathPoint>::const_iterator DiscretizedPath::QueryUpperBound( const double path_s) const { auto func = [](const double path_s, const PathPoint &tp) { return tp.s() < path_s; }; return std::upper_bound(begin(), end(), path_s, func); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/smoothers/smoother.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 "modules/common/status/status.h" #include "modules/common/vehicle_state/proto/vehicle_state.pb.h" #include "modules/planning/common/frame.h" #include "modules/common_msgs/planning_msgs/decision.pb.h" namespace apollo { namespace planning { class Smoother { public: Smoother() = default; virtual ~Smoother() = default; apollo::common::Status Smooth(const FrameHistory* frame_history, const Frame* current_frame, ADCTrajectory* const current_trajectory_pb); private: bool IsCloseStop(const common::VehicleState& vehicle_state, const MainStop& main_stop); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/smoothers/smoother.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/common/smoothers/smoother.h" #include <string> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/vec2d.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::math::Vec2d; bool Smoother::IsCloseStop(const common::VehicleState& vehicle_state, const MainStop& main_stop) { if (!main_stop.has_stop_point()) { ADEBUG << "not close for main stop:" << main_stop.DebugString(); return false; } Vec2d current_car_pos(vehicle_state.x(), vehicle_state.y()); Vec2d stop_pos(main_stop.stop_point().x(), main_stop.stop_point().y()); auto stop_distance = stop_pos.DistanceTo(current_car_pos); if (stop_distance > FLAGS_smoother_stop_distance) { ADEBUG << "distance between ADC position and stop position:" << stop_distance; return false; } return true; } // TODO(all): extend more smooth policies into different objects // when more use cases happens later. apollo::common::Status Smoother::Smooth( const FrameHistory* frame_history, const Frame* current_frame, ADCTrajectory* const current_trajectory_pb) { if (frame_history == nullptr) { const std::string msg = "frame history is null."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (current_frame == nullptr) { const std::string msg = "frame is null."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (current_trajectory_pb == nullptr) { const std::string msg = "current trajectory pb is null"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } const auto& main_decision = current_trajectory_pb->decision().main_decision(); if (!main_decision.has_stop()) { // skip for current planning is not stop. ADEBUG << "skip smoothing for current planning is not stop"; return Status::OK(); } const auto& vehicle_state = current_frame->vehicle_state(); const double max_adc_stop_speed = common::VehicleConfigHelper::Instance() ->GetConfig() .vehicle_param() .max_abs_speed_when_stopped(); if (vehicle_state.linear_velocity() > max_adc_stop_speed) { ADEBUG << "vehicle speed:" << vehicle_state.linear_velocity() << " skip smoothing for non-stop scenario"; return Status::OK(); } if (!IsCloseStop(vehicle_state, main_decision.stop())) { ADEBUG << "vehicle state:" << vehicle_state.DebugString() << " skip smoothing for ADC is not close to stop point"; return Status::OK(); } auto previous_frame = frame_history->Latest(); if (previous_frame == nullptr) { const std::string msg = "previous frame is null"; AWARN << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } const auto& previous_planning = previous_frame->current_frame_planned_trajectory(); auto header = current_trajectory_pb->header(); *current_trajectory_pb = previous_planning; current_trajectory_pb->mutable_header()->CopyFrom(header); auto smoother_debug = current_trajectory_pb->mutable_debug() ->mutable_planning_data() ->mutable_smoother(); smoother_debug->set_is_smoothed(true); smoother_debug->set_type( planning_internal::SmootherDebug::SMOOTHER_CLOSE_STOP); return Status::OK(); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/smoothers/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "smoother", srcs = ["smoother.cc"], hdrs = ["smoother.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/common/status", "//modules/planning/common:frame", "//modules/planning/common:planning_gflags", "//modules/common_msgs/planning_msgs:planning_cc_proto", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory/discretized_trajectory.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 <vector> #include "cyber/common/log.h" #include "modules/common/math/vec2d.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" namespace apollo { namespace planning { class DiscretizedTrajectory : public std::vector<common::TrajectoryPoint> { public: DiscretizedTrajectory() = default; /** * Create a DiscretizedTrajectory based on protobuf message */ explicit DiscretizedTrajectory(const ADCTrajectory& trajectory); explicit DiscretizedTrajectory( const std::vector<common::TrajectoryPoint>& trajectory_points); void SetTrajectoryPoints( const std::vector<common::TrajectoryPoint>& trajectory_points); virtual ~DiscretizedTrajectory() = default; virtual common::TrajectoryPoint StartPoint() const; virtual double GetTemporalLength() const; virtual double GetSpatialLength() const; virtual common::TrajectoryPoint Evaluate(const double relative_time) const; virtual size_t QueryLowerBoundPoint(const double relative_time, const double epsilon = 1.0e-5) const; virtual size_t QueryNearestPoint(const common::math::Vec2d& position) const; size_t QueryNearestPointWithBuffer(const common::math::Vec2d& position, const double buffer) const; virtual void AppendTrajectoryPoint( const common::TrajectoryPoint& trajectory_point); void PrependTrajectoryPoints( const std::vector<common::TrajectoryPoint>& trajectory_points) { if (!empty() && trajectory_points.size() > 1) { ACHECK(trajectory_points.back().relative_time() < front().relative_time()); } insert(begin(), trajectory_points.begin(), trajectory_points.end()); } const common::TrajectoryPoint& TrajectoryPointAt(const size_t index) const; size_t NumOfPoints() const; virtual void Clear(); }; inline size_t DiscretizedTrajectory::NumOfPoints() const { return size(); } inline void DiscretizedTrajectory::Clear() { clear(); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory/publishable_trajectory.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 publishable_trajectory.h **/ #pragma once #include "modules/planning/common/trajectory/discretized_trajectory.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" namespace apollo { namespace planning { class PublishableTrajectory : public DiscretizedTrajectory { public: PublishableTrajectory() = default; PublishableTrajectory(const double header_time, const DiscretizedTrajectory& discretized_trajectory); /** * Create a publishable trajectory based on a trajectory protobuf */ explicit PublishableTrajectory(const ADCTrajectory& trajectory_pb); double header_time() const; void PopulateTrajectoryProtobuf(ADCTrajectory* trajectory_pb) const; private: double header_time_ = 0.0; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory/discretized_trajectory.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 discretized_trajectory.cc **/ #include "modules/planning/common/trajectory/discretized_trajectory.h" #include <limits> #include "cyber/common/log.h" #include "modules/common/math/linear_interpolation.h" #include "modules/planning/common/planning_context.h" namespace apollo { namespace planning { using apollo::common::TrajectoryPoint; DiscretizedTrajectory::DiscretizedTrajectory( const std::vector<TrajectoryPoint>& trajectory_points) : std::vector<TrajectoryPoint>(trajectory_points) { ACHECK(!trajectory_points.empty()) << "trajectory_points should NOT be empty()"; } DiscretizedTrajectory::DiscretizedTrajectory(const ADCTrajectory& trajectory) { assign(trajectory.trajectory_point().begin(), trajectory.trajectory_point().end()); } TrajectoryPoint DiscretizedTrajectory::Evaluate( const double relative_time) const { auto comp = [](const TrajectoryPoint& p, const double relative_time) { return p.relative_time() < relative_time; }; auto it_lower = std::lower_bound(begin(), end(), relative_time, comp); if (it_lower == begin()) { return front(); } else if (it_lower == end()) { AWARN << "When evaluate trajectory, relative_time(" << relative_time << ") is too large"; return back(); } return common::math::InterpolateUsingLinearApproximation( *(it_lower - 1), *it_lower, relative_time); } size_t DiscretizedTrajectory::QueryLowerBoundPoint(const double relative_time, const double epsilon) const { ACHECK(!empty()); if (relative_time >= back().relative_time()) { return size() - 1; } auto func = [&epsilon](const TrajectoryPoint& tp, const double relative_time) { return tp.relative_time() + epsilon < relative_time; }; auto it_lower = std::lower_bound(begin(), end(), relative_time, func); return std::distance(begin(), it_lower); } size_t DiscretizedTrajectory::QueryNearestPoint( const common::math::Vec2d& position) const { double dist_sqr_min = std::numeric_limits<double>::max(); size_t index_min = 0; for (size_t i = 0; i < size(); ++i) { const common::math::Vec2d curr_point(data()[i].path_point().x(), data()[i].path_point().y()); const double dist_sqr = curr_point.DistanceSquareTo(position); if (dist_sqr < dist_sqr_min) { dist_sqr_min = dist_sqr; index_min = i; } } return index_min; } size_t DiscretizedTrajectory::QueryNearestPointWithBuffer( const common::math::Vec2d& position, const double buffer) const { double dist_sqr_min = std::numeric_limits<double>::max(); size_t index_min = 0; for (size_t i = 0; i < size(); ++i) { const common::math::Vec2d curr_point(data()[i].path_point().x(), data()[i].path_point().y()); const double dist_sqr = curr_point.DistanceSquareTo(position); if (dist_sqr < dist_sqr_min + buffer) { dist_sqr_min = dist_sqr; index_min = i; } } return index_min; } void DiscretizedTrajectory::AppendTrajectoryPoint( const TrajectoryPoint& trajectory_point) { if (!empty()) { CHECK_GT(trajectory_point.relative_time(), back().relative_time()); } push_back(trajectory_point); } const TrajectoryPoint& DiscretizedTrajectory::TrajectoryPointAt( const size_t index) const { CHECK_LT(index, NumOfPoints()); return data()[index]; } TrajectoryPoint DiscretizedTrajectory::StartPoint() const { ACHECK(!empty()); return front(); } double DiscretizedTrajectory::GetTemporalLength() const { if (empty()) { return 0.0; } return back().relative_time() - front().relative_time(); } double DiscretizedTrajectory::GetSpatialLength() const { if (empty()) { return 0.0; } return back().path_point().s() - front().path_point().s(); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory/publishable_trajectory_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/common/trajectory/publishable_trajectory.h" #include "cyber/common/file.h" #include "gtest/gtest.h" #include "modules/common/util/util.h" namespace apollo { namespace planning { TEST(basic_test, DiscretizedTrajectory) { const std::string path_of_standard_trajectory = "modules/planning/testdata/trajectory_data/standard_trajectory.pb.txt"; ADCTrajectory trajectory; EXPECT_TRUE(cyber::common::GetProtoFromFile(path_of_standard_trajectory, &trajectory)); DiscretizedTrajectory discretized_trajectory(trajectory); PublishableTrajectory publishable_trajectory(12349834.26, discretized_trajectory); EXPECT_EQ(publishable_trajectory.header_time(), 12349834.26); ADCTrajectory output_trajectory; publishable_trajectory.PopulateTrajectoryProtobuf(&output_trajectory); for (int i = 0; i < output_trajectory.trajectory_point_size(); ++i) { EXPECT_TRUE(apollo::common::util::IsProtoEqual( output_trajectory.trajectory_point(i), trajectory.trajectory_point(i))); } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "discretized_trajectory", srcs = ["discretized_trajectory.cc"], hdrs = ["discretized_trajectory.h"], deps = [ "//modules/common/math", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/vehicle_state/proto:vehicle_state_cc_proto", "//modules/planning/common:planning_context", "@eigen", ], ) cc_test( name = "discretized_trajectory_test", size = "small", srcs = ["discretized_trajectory_test.cc"], data = [ "//modules/planning:planning_testdata", ], deps = [ ":discretized_trajectory", "//modules/common/util", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "publishable_trajectory", srcs = ["publishable_trajectory.cc"], hdrs = ["publishable_trajectory.h"], deps = [ ":discretized_trajectory", "//modules/common_msgs/planning_msgs:planning_cc_proto", ], ) cc_test( name = "publishable_trajectory_test", size = "small", srcs = ["publishable_trajectory_test.cc"], data = [ "//modules/planning:planning_testdata", ], deps = [ ":publishable_trajectory", "//modules/common/util", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory/discretized_trajectory_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/common/trajectory/discretized_trajectory.h" #include "cyber/common/file.h" #include "gtest/gtest.h" namespace apollo { namespace planning { TEST(basic_test, DiscretizedTrajectory) { const std::string path_of_standard_trajectory = "modules/planning/testdata/trajectory_data/standard_trajectory.pb.txt"; ADCTrajectory trajectory; EXPECT_TRUE(cyber::common::GetProtoFromFile(path_of_standard_trajectory, &trajectory)); DiscretizedTrajectory discretized_trajectory(trajectory); EXPECT_DOUBLE_EQ(discretized_trajectory.GetTemporalLength(), 7.9999999999999885); EXPECT_DOUBLE_EQ(discretized_trajectory.GetSpatialLength(), 44.752319202675167); auto p1 = discretized_trajectory.Evaluate(4.0); EXPECT_DOUBLE_EQ(p1.path_point().x(), 587263.01182131236); EXPECT_DOUBLE_EQ(p1.path_point().y(), 4140966.5720794979); EXPECT_DOUBLE_EQ(p1.relative_time(), 4.0); EXPECT_DOUBLE_EQ(p1.v(), 5.4412586837131443); auto k1 = discretized_trajectory.QueryLowerBoundPoint(2.12); EXPECT_EQ(k1, 62); auto k2 = discretized_trajectory.QueryNearestPoint({587264.0, 4140966.2}); EXPECT_EQ(k2, 80); EXPECT_EQ(discretized_trajectory.NumOfPoints(), 121); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/common
apollo_public_repos/apollo/modules/planning/common/trajectory/publishable_trajectory.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 publishable_trajectory.cpp **/ #include "modules/planning/common/trajectory/publishable_trajectory.h" #include "cyber/common/log.h" namespace apollo { namespace planning { PublishableTrajectory::PublishableTrajectory( const double header_time, const DiscretizedTrajectory& discretized_trajectory) : DiscretizedTrajectory(discretized_trajectory), header_time_(header_time) {} PublishableTrajectory::PublishableTrajectory(const ADCTrajectory& trajectory_pb) : DiscretizedTrajectory(trajectory_pb), header_time_(trajectory_pb.header().timestamp_sec()) {} double PublishableTrajectory::header_time() const { return header_time_; } void PublishableTrajectory::PopulateTrajectoryProtobuf( ADCTrajectory* trajectory_pb) const { CHECK_NOTNULL(trajectory_pb); trajectory_pb->mutable_header()->set_timestamp_sec(header_time_); trajectory_pb->mutable_trajectory_point()->CopyFrom({begin(), end()}); if (!empty()) { const auto& last_tp = back(); trajectory_pb->set_total_path_length(last_tp.path_point().s()); trajectory_pb->set_total_path_time(last_tp.relative_time()); } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/scenarios/scenario.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 <string> #include <unordered_map> #include "modules/common/status/status.h" #include "modules/common/util/factory.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/scenarios/stage.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { namespace scenario { struct ScenarioContext {}; class Scenario { public: enum ScenarioStatus { STATUS_UNKNOWN = 0, STATUS_PROCESSING = 1, STATUS_DONE = 2, }; Scenario(const ScenarioConfig& config, const ScenarioContext* context, const std::shared_ptr<DependencyInjector>& injector); static bool LoadConfig(const std::string& config_file, ScenarioConfig* config); virtual ~Scenario() = default; ScenarioType scenario_type() const { return config_.scenario_type(); } /** * Each scenario should define its own stages object's creation * scenario will call stage's Stage::Process function following a configured * order, The return value of Stage::Process function determines the * transition from one stage to another. */ virtual std::unique_ptr<Stage> CreateStage( const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector) = 0; // Each scenario should define its own transfer condition, i.e., when it // should allow to transfer from other scenario to itself. virtual bool IsTransferable(const Scenario& other_scenario, const Frame& frame) { return true; } virtual ScenarioStatus Process( const common::TrajectoryPoint& planning_init_point, Frame* frame); const ScenarioStatus& GetStatus() const { return scenario_status_; } const StageType GetStage() const { return current_stage_ ? current_stage_->stage_type() : StageType::NO_STAGE; } virtual void Init(); const std::string& Name() const; const std::string& GetMsg() const { return msg_; } protected: ScenarioStatus scenario_status_ = STATUS_UNKNOWN; std::unique_ptr<Stage> current_stage_; ScenarioConfig config_; std::unordered_map<StageType, const ScenarioConfig::StageConfig*, std::hash<int>> stage_config_map_; const ScenarioContext* scenario_context_ = nullptr; std::string name_; std::string msg_; // debug msg std::shared_ptr<DependencyInjector> injector_; }; } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/scenarios/stage.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/scenarios/stage.h" #include <unordered_map> #include <utility> #include "cyber/time/clock.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/speed_profile_generator.h" #include "modules/planning/common/trajectory/publishable_trajectory.h" #include "modules/planning/tasks/task_factory.h" namespace apollo { namespace planning { namespace scenario { using apollo::cyber::Clock; namespace { // constexpr double kPathOptimizationFallbackCost = 2e4; constexpr double kSpeedOptimizationFallbackCost = 2e4; // constexpr double kStraightForwardLineCost = 10.0; } // namespace Stage::Stage(const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) : config_(config), injector_(injector) { // set stage_type in PlanningContext injector->planning_context() ->mutable_planning_status() ->mutable_scenario() ->set_stage_type(stage_type()); name_ = StageType_Name(config_.stage_type()); next_stage_ = config_.stage_type(); std::unordered_map<TaskConfig::TaskType, const TaskConfig*, std::hash<int>> config_map; for (const auto& task_config : config_.task_config()) { config_map[task_config.task_type()] = &task_config; } for (int i = 0; i < config_.task_type_size(); ++i) { auto task_type = config_.task_type(i); ACHECK(config_map.find(task_type) != config_map.end()) << "Task: " << TaskConfig::TaskType_Name(task_type) << " used but not configured"; auto iter = tasks_.find(task_type); if (iter == tasks_.end()) { auto ptr = TaskFactory::CreateTask(*config_map[task_type], injector_); task_list_.push_back(ptr.get()); tasks_[task_type] = std::move(ptr); } else { task_list_.push_back(iter->second.get()); } } } const std::string& Stage::Name() const { return name_; } Task* Stage::FindTask(TaskConfig::TaskType task_type) const { auto iter = tasks_.find(task_type); if (iter == tasks_.end()) { return nullptr; } else { return iter->second.get(); } } bool Stage::ExecuteTaskOnReferenceLine( const common::TrajectoryPoint& planning_start_point, Frame* frame) { for (auto& reference_line_info : *frame->mutable_reference_line_info()) { if (!reference_line_info.IsDrivable()) { AERROR << "The generated path is not drivable"; return false; } for (auto* task : task_list_) { const double start_timestamp = Clock::NowInSeconds(); const auto ret = task->Execute(frame, &reference_line_info); 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); if (!ret.ok()) { AERROR << "Failed to run tasks[" << task->Name() << "], Error message: " << ret.error_message(); break; } } if (reference_line_info.speed_data().empty()) { *reference_line_info.mutable_speed_data() = SpeedProfileGenerator::GenerateFallbackSpeed(injector_->ego_info()); reference_line_info.AddCost(kSpeedOptimizationFallbackCost); reference_line_info.set_trajectory_type(ADCTrajectory::SPEED_FALLBACK); } else { reference_line_info.set_trajectory_type(ADCTrajectory::NORMAL); } DiscretizedTrajectory trajectory; if (!reference_line_info.CombinePathAndSpeedProfile( planning_start_point.relative_time(), planning_start_point.path_point().s(), &trajectory)) { AERROR << "Fail to aggregate planning trajectory."; return false; } reference_line_info.SetTrajectory(trajectory); reference_line_info.SetDrivable(true); return true; } return true; } bool Stage::ExecuteTaskOnReferenceLineForOnlineLearning( const common::TrajectoryPoint& planning_start_point, Frame* frame) { // online learning mode for (auto& reference_line_info : *frame->mutable_reference_line_info()) { reference_line_info.SetDrivable(false); } // FIXME(all): current only pick up the first reference line to use // learning model trajectory auto& picked_reference_line_info = frame->mutable_reference_line_info()->front(); for (auto* task : task_list_) { const double start_timestamp = Clock::NowInSeconds(); const auto ret = task->Execute(frame, &picked_reference_line_info); const double end_timestamp = Clock::NowInSeconds(); const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; ADEBUG << "task[" << task->Name() << "] time spent: " << time_diff_ms << " ms."; RecordDebugInfo(&picked_reference_line_info, task->Name(), time_diff_ms); if (!ret.ok()) { AERROR << "Failed to run tasks[" << task->Name() << "], Error message: " << ret.error_message(); break; } } const std::vector<common::TrajectoryPoint>& adc_future_trajectory_points = picked_reference_line_info.trajectory(); DiscretizedTrajectory trajectory; if (picked_reference_line_info.AdjustTrajectoryWhichStartsFromCurrentPos( planning_start_point, adc_future_trajectory_points, &trajectory)) { picked_reference_line_info.SetTrajectory(trajectory); picked_reference_line_info.SetDrivable(true); picked_reference_line_info.SetCost(0); } return true; } bool Stage::ExecuteTaskOnOpenSpace(Frame* frame) { auto ret = common::Status::OK(); for (auto* task : task_list_) { ret = task->Execute(frame); if (!ret.ok()) { AERROR << "Failed to run tasks[" << task->Name() << "], Error message: " << ret.error_message(); return false; } } if (frame->open_space_info().fallback_flag()) { auto& trajectory = frame->open_space_info().fallback_trajectory().first; auto& gear = frame->open_space_info().fallback_trajectory().second; PublishableTrajectory publishable_trajectory( Clock::NowInSeconds(), trajectory); auto publishable_traj_and_gear = std::make_pair(std::move(publishable_trajectory), gear); *(frame->mutable_open_space_info()->mutable_publishable_trajectory_data()) = std::move(publishable_traj_and_gear); } else { auto& trajectory = frame->open_space_info().chosen_partitioned_trajectory().first; auto& gear = frame->open_space_info().chosen_partitioned_trajectory().second; PublishableTrajectory publishable_trajectory( Clock::NowInSeconds(), trajectory); auto publishable_traj_and_gear = std::make_pair(std::move(publishable_trajectory), gear); *(frame->mutable_open_space_info()->mutable_publishable_trajectory_data()) = std::move(publishable_traj_and_gear); } return true; } Stage::StageStatus Stage::FinishScenario() { next_stage_ = StageType::NO_STAGE; return Stage::FINISHED; } void Stage::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); } } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/scenarios/scenario_manager.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 <unordered_map> #include "modules/planning/proto/planning_config.pb.h" #include "modules/common/status/status.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/scenarios/scenario.h" namespace apollo { namespace planning { namespace scenario { class ScenarioManager final { public: ScenarioManager() = delete; explicit ScenarioManager(const std::shared_ptr<DependencyInjector>& injector); bool Init(const PlanningConfig& planning_config); Scenario* mutable_scenario() { return current_scenario_.get(); } DependencyInjector* injector() { return injector_.get(); } void Update(const common::TrajectoryPoint& ego_point, const Frame& frame); private: void Observe(const Frame& frame); std::unique_ptr<Scenario> CreateScenario(ScenarioType scenario_type); void RegisterScenarios(); ScenarioType SelectBareIntersectionScenario( const Frame& frame, const hdmap::PathOverlap& pnc_junction_overlap); ScenarioType SelectPullOverScenario(const Frame& frame); ScenarioType SelectPadMsgScenario(const Frame& frame); ScenarioType SelectInterceptionScenario(const Frame& frame); ScenarioType SelectStopSignScenario( const Frame& frame, const hdmap::PathOverlap& stop_sign_overlap); ScenarioType SelectTrafficLightScenario( const Frame& frame, const hdmap::PathOverlap& traffic_light_overlap); ScenarioType SelectValetParkingScenario(const Frame& frame); ScenarioType SelectYieldSignScenario( const Frame& frame, const hdmap::PathOverlap& yield_sign_overlap); ScenarioType SelectParkAndGoScenario(const Frame& frame); void ScenarioDispatch(const Frame& frame); ScenarioType ScenarioDispatchLearning(); ScenarioType ScenarioDispatchNonLearning(const Frame& frame); bool IsBareIntersectionScenario(const ScenarioType& scenario_type); bool IsStopSignScenario(const ScenarioType& scenario_type); bool IsTrafficLightScenario(const ScenarioType& scenario_type); bool IsYieldSignScenario(const ScenarioType& scenario_type); void UpdatePlanningContext(const Frame& frame, const ScenarioType& scenario_type); void UpdatePlanningContextBareIntersectionScenario( const Frame& frame, const ScenarioType& scenario_type); void UpdatePlanningContextEmergencyStopcenario( const Frame& frame, const ScenarioType& scenario_type); void UpdatePlanningContextPullOverScenario(const Frame& frame, const ScenarioType& scenario_type); void UpdatePlanningContextStopSignScenario(const Frame& frame, const ScenarioType& scenario_type); void UpdatePlanningContextTrafficLightScenario( const Frame& frame, const ScenarioType& scenario_type); void UpdatePlanningContextYieldSignScenario( const Frame& frame, const ScenarioType& scenario_type); private: std::shared_ptr<DependencyInjector> injector_; PlanningConfig planning_config_; std::unordered_map<ScenarioType, ScenarioConfig, std::hash<int>> config_map_; std::unique_ptr<Scenario> current_scenario_; ScenarioType default_scenario_type_; ScenarioContext scenario_context_; std::unordered_map<ReferenceLineInfo::OverlapType, hdmap::PathOverlap, std::hash<int>> first_encountered_overlap_map_; }; } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/scenarios/scenario_manager.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/scenarios/scenario_manager.h" #include <string> #include <vector> #include <algorithm> #include "modules/common_msgs/map_msgs/map_lane.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/util/point_factory.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/pnc_map/path.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/util/util.h" #include "modules/planning/scenarios/bare_intersection/unprotected/bare_intersection_unprotected_scenario.h" #include "modules/planning/scenarios/emergency/emergency_pull_over/emergency_pull_over_scenario.h" #include "modules/planning/scenarios/emergency/emergency_stop/emergency_stop_scenario.h" #include "modules/planning/scenarios/lane_follow/lane_follow_scenario.h" #include "modules/planning/scenarios/learning_model/learning_model_sample_scenario.h" #include "modules/planning/scenarios/park/pull_over/pull_over_scenario.h" #include "modules/planning/scenarios/park/valet_parking/valet_parking_scenario.h" #include "modules/planning/scenarios/park_and_go/park_and_go_scenario.h" #include "modules/planning/scenarios/stop_sign/unprotected/stop_sign_unprotected_scenario.h" #include "modules/planning/scenarios/traffic_light/protected/traffic_light_protected_scenario.h" #include "modules/planning/scenarios/traffic_light/unprotected_left_turn/traffic_light_unprotected_left_turn_scenario.h" #include "modules/planning/scenarios/traffic_light/unprotected_right_turn/traffic_light_unprotected_right_turn_scenario.h" #include "modules/planning/scenarios/util/util.h" #include "modules/planning/scenarios/yield_sign/yield_sign_scenario.h" namespace apollo { namespace planning { namespace scenario { using apollo::hdmap::HDMapUtil; using apollo::hdmap::PathOverlap; ScenarioManager::ScenarioManager( const std::shared_ptr<DependencyInjector>& injector) : injector_(injector) {} bool ScenarioManager::Init(const PlanningConfig& planning_config) { planning_config_.CopyFrom(planning_config); RegisterScenarios(); default_scenario_type_ = ScenarioType::LANE_FOLLOW; current_scenario_ = CreateScenario(default_scenario_type_); return true; } std::unique_ptr<Scenario> ScenarioManager::CreateScenario( ScenarioType scenario_type) { std::unique_ptr<Scenario> ptr; switch (scenario_type) { case ScenarioType::BARE_INTERSECTION_UNPROTECTED: ptr.reset( new scenario::bare_intersection::BareIntersectionUnprotectedScenario( config_map_[scenario_type], &scenario_context_, injector_)); break; case ScenarioType::EMERGENCY_PULL_OVER: ptr.reset(new emergency_pull_over::EmergencyPullOverScenario( config_map_[scenario_type], &scenario_context_, injector_)); break; case ScenarioType::EMERGENCY_STOP: ptr.reset(new emergency_stop::EmergencyStopScenario( config_map_[scenario_type], &scenario_context_, injector_)); break; case ScenarioType::LANE_FOLLOW: ptr.reset(new lane_follow::LaneFollowScenario( config_map_[scenario_type], &scenario_context_, injector_)); break; case ScenarioType::LEARNING_MODEL_SAMPLE: ptr.reset(new scenario::LearningModelSampleScenario( config_map_[scenario_type], &scenario_context_, injector_)); break; case ScenarioType::PARK_AND_GO: ptr.reset(new scenario::park_and_go::ParkAndGoScenario( config_map_[scenario_type], &scenario_context_, injector_)); break; case ScenarioType::PULL_OVER: ptr.reset(new scenario::pull_over::PullOverScenario( config_map_[scenario_type], &scenario_context_, injector_)); break; case ScenarioType::STOP_SIGN_UNPROTECTED: ptr.reset(new scenario::stop_sign::StopSignUnprotectedScenario( config_map_[scenario_type], &scenario_context_, injector_)); break; case ScenarioType::TRAFFIC_LIGHT_PROTECTED: ptr.reset(new scenario::traffic_light::TrafficLightProtectedScenario( config_map_[scenario_type], &scenario_context_, injector_)); break; case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN: ptr.reset( new scenario::traffic_light::TrafficLightUnprotectedLeftTurnScenario( config_map_[scenario_type], &scenario_context_, injector_)); break; case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN: ptr.reset( new scenario::traffic_light::TrafficLightUnprotectedRightTurnScenario( config_map_[scenario_type], &scenario_context_, injector_)); break; case ScenarioType::VALET_PARKING: ptr.reset(new scenario::valet_parking::ValetParkingScenario( config_map_[scenario_type], &scenario_context_, injector_)); break; case ScenarioType::YIELD_SIGN: ptr.reset(new scenario::yield_sign::YieldSignScenario( config_map_[scenario_type], &scenario_context_, injector_)); break; default: return nullptr; } if (ptr != nullptr) { ptr->Init(); } return ptr; } void ScenarioManager::RegisterScenarios() { // lane_follow if (planning_config_.learning_mode() == PlanningConfig::HYBRID || planning_config_.learning_mode() == PlanningConfig::HYBRID_TEST) { // HYBRID or HYBRID_TEST ACHECK(Scenario::LoadConfig(FLAGS_scenario_lane_follow_hybrid_config_file, &config_map_[ScenarioType::LANE_FOLLOW])); } else { ACHECK(Scenario::LoadConfig(FLAGS_scenario_lane_follow_config_file, &config_map_[ScenarioType::LANE_FOLLOW])); } // bare_intersection ACHECK(Scenario::LoadConfig( FLAGS_scenario_bare_intersection_unprotected_config_file, &config_map_[ScenarioType::BARE_INTERSECTION_UNPROTECTED])); // emergency_pull_over ACHECK(Scenario::LoadConfig(FLAGS_scenario_emergency_pull_over_config_file, &config_map_[ScenarioType::EMERGENCY_PULL_OVER])); // emergency_stop ACHECK(Scenario::LoadConfig(FLAGS_scenario_emergency_stop_config_file, &config_map_[ScenarioType::EMERGENCY_STOP])); // learning model ACHECK( Scenario::LoadConfig(FLAGS_scenario_learning_model_sample_config_file, &config_map_[ScenarioType::LEARNING_MODEL_SAMPLE])); // park_and_go ACHECK(Scenario::LoadConfig(FLAGS_scenario_park_and_go_config_file, &config_map_[ScenarioType::PARK_AND_GO])); // pull_over ACHECK(Scenario::LoadConfig(FLAGS_scenario_pull_over_config_file, &config_map_[ScenarioType::PULL_OVER])); // stop_sign ACHECK( Scenario::LoadConfig(FLAGS_scenario_stop_sign_unprotected_config_file, &config_map_[ScenarioType::STOP_SIGN_UNPROTECTED])); // traffic_light ACHECK(Scenario::LoadConfig( FLAGS_scenario_traffic_light_protected_config_file, &config_map_[ScenarioType::TRAFFIC_LIGHT_PROTECTED])); ACHECK(Scenario::LoadConfig( FLAGS_scenario_traffic_light_unprotected_left_turn_config_file, &config_map_[ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN])); ACHECK(Scenario::LoadConfig( FLAGS_scenario_traffic_light_unprotected_right_turn_config_file, &config_map_[ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN])); // valet parking ACHECK(Scenario::LoadConfig(FLAGS_scenario_valet_parking_config_file, &config_map_[ScenarioType::VALET_PARKING])); // yield_sign ACHECK(Scenario::LoadConfig(FLAGS_scenario_yield_sign_config_file, &config_map_[ScenarioType::YIELD_SIGN])); } ScenarioType ScenarioManager::SelectPullOverScenario(const Frame& frame) { const auto& scenario_config = config_map_[ScenarioType::PULL_OVER].pull_over_config(); const auto& routing = frame.local_view().routing; const auto& routing_end = *(routing->routing_request().waypoint().rbegin()); common::SLPoint dest_sl; const auto& reference_line_info = frame.reference_line_info().front(); const auto& reference_line = reference_line_info.reference_line(); reference_line.XYToSL(routing_end.pose(), &dest_sl); const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const double adc_distance_to_dest = dest_sl.s() - adc_front_edge_s; ADEBUG << "adc_distance_to_dest[" << adc_distance_to_dest << "] destination_s[" << dest_sl.s() << "] adc_front_edge_s[" << adc_front_edge_s << "]"; bool pull_over_scenario = (frame.reference_line_info().size() == 1 && // NO, while changing lane adc_distance_to_dest >= scenario_config.pull_over_min_distance_buffer() && adc_distance_to_dest <= scenario_config.start_pull_over_scenario_distance()); // too close to destination + not found pull-over position if (pull_over_scenario) { const auto& pull_over_status = injector_->planning_context()->planning_status().pull_over(); if (adc_distance_to_dest < scenario_config.max_distance_stop_search() && !pull_over_status.has_position()) { pull_over_scenario = false; } } // check around junction if (pull_over_scenario) { static constexpr double kDistanceToAvoidJunction = 8.0; // meter for (const auto& overlap : first_encountered_overlap_map_) { if (overlap.first == ReferenceLineInfo::PNC_JUNCTION || overlap.first == ReferenceLineInfo::SIGNAL || overlap.first == ReferenceLineInfo::STOP_SIGN || overlap.first == ReferenceLineInfo::YIELD_SIGN) { const double distance_to = overlap.second.start_s - dest_sl.s(); const double distance_passed = dest_sl.s() - overlap.second.end_s; if ((distance_to > 0.0 && distance_to < kDistanceToAvoidJunction) || (distance_passed > 0.0 && distance_passed < kDistanceToAvoidJunction)) { pull_over_scenario = false; break; } } } } // check rightmost driving lane along pull-over path if (pull_over_scenario) { double check_s = adc_front_edge_s; static constexpr double kDistanceUnit = 5.0; while (check_s < dest_sl.s()) { check_s += kDistanceUnit; std::vector<hdmap::LaneInfoConstPtr> lanes; reference_line.GetLaneFromS(check_s, &lanes); if (lanes.empty()) { ADEBUG << "check_s[" << check_s << "] can't find a lane"; continue; } const hdmap::LaneInfoConstPtr lane = lanes[0]; const std::string lane_id = lane->lane().id().id(); ADEBUG << "check_s[" << check_s << "] lane[" << lane_id << "]"; // check neighbor lanes type: NONE/CITY_DRIVING/BIKING/SIDEWALK/PARKING bool rightmost_driving_lane = true; for (const auto& neighbor_lane_id : lane->lane().right_neighbor_forward_lane_id()) { const auto hdmap_ptr = HDMapUtil::BaseMapPtr(); CHECK_NOTNULL(hdmap_ptr); const auto neighbor_lane = hdmap_ptr->GetLaneById(neighbor_lane_id); if (neighbor_lane == nullptr) { ADEBUG << "Failed to find neighbor lane[" << neighbor_lane_id.id() << "]"; continue; } const auto& lane_type = neighbor_lane->lane().type(); if (lane_type == hdmap::Lane::CITY_DRIVING) { ADEBUG << "lane[" << lane_id << "]'s right neighbor forward lane[" << neighbor_lane_id.id() << "] type[" << Lane_LaneType_Name(lane_type) << "] can't pull over"; rightmost_driving_lane = false; break; } } if (!rightmost_driving_lane) { pull_over_scenario = false; break; } } } switch (current_scenario_->scenario_type()) { case ScenarioType::LANE_FOLLOW: if (pull_over_scenario) { return ScenarioType::PULL_OVER; } break; case ScenarioType::BARE_INTERSECTION_UNPROTECTED: case ScenarioType::EMERGENCY_PULL_OVER: case ScenarioType::PARK_AND_GO: case ScenarioType::PULL_OVER: case ScenarioType::STOP_SIGN_PROTECTED: case ScenarioType::STOP_SIGN_UNPROTECTED: case ScenarioType::TRAFFIC_LIGHT_PROTECTED: case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN: case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN: case ScenarioType::VALET_PARKING: case ScenarioType::YIELD_SIGN: if (current_scenario_->GetStatus() != Scenario::ScenarioStatus::STATUS_DONE) { return current_scenario_->scenario_type(); } break; default: break; } return default_scenario_type_; } ScenarioType ScenarioManager::SelectPadMsgScenario(const Frame& frame) { const auto& pad_msg_driving_action = frame.GetPadMsgDrivingAction(); switch (pad_msg_driving_action) { case PadMessage::PULL_OVER: if (FLAGS_enable_scenario_emergency_pull_over) { return ScenarioType::EMERGENCY_PULL_OVER; } break; case PadMessage::STOP: if (FLAGS_enable_scenario_emergency_stop) { return ScenarioType::EMERGENCY_STOP; } break; case PadMessage::RESUME_CRUISE: if (current_scenario_->scenario_type() == ScenarioType::EMERGENCY_PULL_OVER || current_scenario_->scenario_type() == ScenarioType::EMERGENCY_STOP) { return ScenarioType::PARK_AND_GO; } break; default: break; } return default_scenario_type_; } ScenarioType ScenarioManager::SelectInterceptionScenario(const Frame& frame) { ScenarioType scenario_type = default_scenario_type_; hdmap::PathOverlap* traffic_sign_overlap = nullptr; hdmap::PathOverlap* pnc_junction_overlap = nullptr; ReferenceLineInfo::OverlapType overlap_type; const auto& reference_line_info = frame.reference_line_info().front(); const auto& first_encountered_overlaps = reference_line_info.FirstEncounteredOverlaps(); // note: first_encountered_overlaps already sorted for (const auto& overlap : first_encountered_overlaps) { if (overlap.first == ReferenceLineInfo::SIGNAL || overlap.first == ReferenceLineInfo::STOP_SIGN || overlap.first == ReferenceLineInfo::YIELD_SIGN) { overlap_type = overlap.first; traffic_sign_overlap = const_cast<hdmap::PathOverlap*>(&overlap.second); break; } else if (overlap.first == ReferenceLineInfo::PNC_JUNCTION) { pnc_junction_overlap = const_cast<hdmap::PathOverlap*>(&overlap.second); } } // pick a closer one between consecutive bare_intersection and traffic_sign if (traffic_sign_overlap && pnc_junction_overlap) { static constexpr double kJunctionDelta = 10.0; double s_diff = std::fabs(traffic_sign_overlap->start_s - pnc_junction_overlap->start_s); if (s_diff >= kJunctionDelta) { if (pnc_junction_overlap->start_s > traffic_sign_overlap->start_s) { pnc_junction_overlap = nullptr; } else { traffic_sign_overlap = nullptr; } } } if (traffic_sign_overlap) { switch (overlap_type) { case ReferenceLineInfo::STOP_SIGN: if (FLAGS_enable_scenario_stop_sign) { scenario_type = SelectStopSignScenario(frame, *traffic_sign_overlap); } break; case ReferenceLineInfo::SIGNAL: if (FLAGS_enable_scenario_traffic_light) { scenario_type = SelectTrafficLightScenario(frame, *traffic_sign_overlap); } break; case ReferenceLineInfo::YIELD_SIGN: if (FLAGS_enable_scenario_yield_sign) { scenario_type = SelectYieldSignScenario(frame, *traffic_sign_overlap); } break; default: break; } } else if (pnc_junction_overlap) { // bare intersection if (FLAGS_enable_scenario_bare_intersection) { scenario_type = SelectBareIntersectionScenario(frame, *pnc_junction_overlap); } } return scenario_type; } ScenarioType ScenarioManager::SelectStopSignScenario( const Frame& frame, const hdmap::PathOverlap& stop_sign_overlap) { const auto& scenario_config = config_map_[ScenarioType::STOP_SIGN_UNPROTECTED] .stop_sign_unprotected_config(); const auto& reference_line_info = frame.reference_line_info().front(); const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const double adc_distance_to_stop_sign = stop_sign_overlap.start_s - adc_front_edge_s; ADEBUG << "adc_distance_to_stop_sign[" << adc_distance_to_stop_sign << "] stop_sign[" << stop_sign_overlap.object_id << "] stop_sign_overlap_start_s[" << stop_sign_overlap.start_s << "]"; const bool stop_sign_scenario = (adc_distance_to_stop_sign > 0.0 && adc_distance_to_stop_sign <= scenario_config.start_stop_sign_scenario_distance()); const bool stop_sign_all_way = false; // TODO(all) switch (current_scenario_->scenario_type()) { case ScenarioType::LANE_FOLLOW: case ScenarioType::PARK_AND_GO: case ScenarioType::PULL_OVER: if (stop_sign_scenario) { return stop_sign_all_way ? ScenarioType::STOP_SIGN_PROTECTED : ScenarioType::STOP_SIGN_UNPROTECTED; } break; case ScenarioType::BARE_INTERSECTION_UNPROTECTED: case ScenarioType::EMERGENCY_PULL_OVER: case ScenarioType::STOP_SIGN_PROTECTED: case ScenarioType::STOP_SIGN_UNPROTECTED: case ScenarioType::TRAFFIC_LIGHT_PROTECTED: case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN: case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN: case ScenarioType::YIELD_SIGN: case ScenarioType::VALET_PARKING: if (current_scenario_->GetStatus() != Scenario::ScenarioStatus::STATUS_DONE) { return current_scenario_->scenario_type(); } break; default: break; } return default_scenario_type_; } ScenarioType ScenarioManager::SelectTrafficLightScenario( const Frame& frame, const hdmap::PathOverlap& traffic_light_overlap) { // some scenario may need start sooner than the others const double start_check_distance = std::max({config_map_[ScenarioType::TRAFFIC_LIGHT_PROTECTED] .traffic_light_protected_config() .start_traffic_light_scenario_distance(), config_map_[ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN] .traffic_light_unprotected_left_turn_config() .start_traffic_light_scenario_distance(), config_map_[ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN] .traffic_light_unprotected_right_turn_config() .start_traffic_light_scenario_distance()}); const auto& reference_line_info = frame.reference_line_info().front(); const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); // find all the traffic light belong to // the same group as first encountered traffic light std::vector<hdmap::PathOverlap> next_traffic_lights; static constexpr double kTrafficLightGroupingMaxDist = 2.0; // unit: m const std::vector<PathOverlap>& traffic_light_overlaps = reference_line_info.reference_line().map_path().signal_overlaps(); for (const auto& overlap : traffic_light_overlaps) { const double dist = overlap.start_s - traffic_light_overlap.start_s; if (fabs(dist) <= kTrafficLightGroupingMaxDist) { next_traffic_lights.push_back(overlap); } } bool traffic_light_scenario = false; bool red_light = false; // note: need iterate all lights to check no RED/YELLOW/UNKNOWN for (const auto& traffic_light_overlap : next_traffic_lights) { const double adc_distance_to_traffic_light = traffic_light_overlap.start_s - adc_front_edge_s; ADEBUG << "traffic_light[" << traffic_light_overlap.object_id << "] start_s[" << traffic_light_overlap.start_s << "] adc_distance_to_traffic_light[" << adc_distance_to_traffic_light << "]"; // enter traffic-light scenarios: based on distance only if (adc_distance_to_traffic_light <= 0.0 || adc_distance_to_traffic_light > start_check_distance) { continue; } traffic_light_scenario = true; const auto& signal_color = frame.GetSignal(traffic_light_overlap.object_id).color(); ADEBUG << "traffic_light_id[" << traffic_light_overlap.object_id << "] start_s[" << traffic_light_overlap.start_s << "] color[" << signal_color << "]"; if (signal_color != perception::TrafficLight::GREEN) { red_light = true; break; } } bool traffic_light_protected_scenario = false; bool traffic_light_unprotected_left_turn_scenario = false; bool traffic_light_unprotected_right_turn_scenario = false; if (traffic_light_scenario) { const auto& turn_type = reference_line_info.GetPathTurnType(traffic_light_overlap.start_s); const bool right_turn = (turn_type == hdmap::Lane::RIGHT_TURN); const bool left_turn = (turn_type == hdmap::Lane::LEFT_TURN); const double adc_distance_to_traffic_light = traffic_light_overlap.start_s - adc_front_edge_s; if (right_turn && red_light) { // check TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN const auto& scenario_config = config_map_[ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN] .traffic_light_unprotected_right_turn_config(); if (adc_distance_to_traffic_light < scenario_config.start_traffic_light_scenario_distance()) { traffic_light_unprotected_right_turn_scenario = true; } } else if (left_turn) { // check TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN const auto& scenario_config = config_map_[ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN] .traffic_light_unprotected_left_turn_config(); if (adc_distance_to_traffic_light < scenario_config.start_traffic_light_scenario_distance()) { traffic_light_unprotected_left_turn_scenario = true; } } else { // check TRAFFIC_LIGHT_PROTECTED const auto& scenario_config = config_map_[ScenarioType::TRAFFIC_LIGHT_PROTECTED] .traffic_light_protected_config(); if (adc_distance_to_traffic_light < scenario_config.start_traffic_light_scenario_distance()) { traffic_light_protected_scenario = true; } } } switch (current_scenario_->scenario_type()) { case ScenarioType::LANE_FOLLOW: case ScenarioType::PARK_AND_GO: case ScenarioType::PULL_OVER: if (traffic_light_unprotected_left_turn_scenario) { return ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN; } else if (traffic_light_unprotected_right_turn_scenario) { return ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN; } else if (traffic_light_protected_scenario) { return ScenarioType::TRAFFIC_LIGHT_PROTECTED; } break; case ScenarioType::BARE_INTERSECTION_UNPROTECTED: case ScenarioType::EMERGENCY_PULL_OVER: case ScenarioType::STOP_SIGN_PROTECTED: case ScenarioType::STOP_SIGN_UNPROTECTED: case ScenarioType::TRAFFIC_LIGHT_PROTECTED: case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN: case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN: case ScenarioType::YIELD_SIGN: case ScenarioType::VALET_PARKING: if (current_scenario_->GetStatus() != Scenario::ScenarioStatus::STATUS_DONE) { return current_scenario_->scenario_type(); } break; default: break; } return default_scenario_type_; } ScenarioType ScenarioManager::SelectYieldSignScenario( const Frame& frame, const hdmap::PathOverlap& yield_sign_overlap) { const auto& scenario_config = config_map_[ScenarioType::YIELD_SIGN].yield_sign_config(); const auto& reference_line_info = frame.reference_line_info().front(); const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const double adc_distance_to_yield_sign = yield_sign_overlap.start_s - adc_front_edge_s; ADEBUG << "adc_distance_to_yield_sign[" << adc_distance_to_yield_sign << "] yield_sign[" << yield_sign_overlap.object_id << "] yield_sign_overlap_start_s[" << yield_sign_overlap.start_s << "]"; const bool yield_sign_scenario = (adc_distance_to_yield_sign > 0.0 && adc_distance_to_yield_sign <= scenario_config.start_yield_sign_scenario_distance()); switch (current_scenario_->scenario_type()) { case ScenarioType::LANE_FOLLOW: case ScenarioType::PARK_AND_GO: case ScenarioType::PULL_OVER: if (yield_sign_scenario) { return ScenarioType::YIELD_SIGN; } break; case ScenarioType::BARE_INTERSECTION_UNPROTECTED: case ScenarioType::EMERGENCY_PULL_OVER: case ScenarioType::STOP_SIGN_PROTECTED: case ScenarioType::STOP_SIGN_UNPROTECTED: case ScenarioType::TRAFFIC_LIGHT_PROTECTED: case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN: case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN: case ScenarioType::YIELD_SIGN: case ScenarioType::VALET_PARKING: if (current_scenario_->GetStatus() != Scenario::ScenarioStatus::STATUS_DONE) { return current_scenario_->scenario_type(); } break; default: break; } return default_scenario_type_; } ScenarioType ScenarioManager::SelectBareIntersectionScenario( const Frame& frame, const hdmap::PathOverlap& pnc_junction_overlap) { const auto& reference_line_info = frame.reference_line_info().front(); if (reference_line_info.GetIntersectionRightofWayStatus( pnc_junction_overlap)) { return default_scenario_type_; } const auto& scenario_config = config_map_[ScenarioType::BARE_INTERSECTION_UNPROTECTED] .bare_intersection_unprotected_config(); const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const double adc_distance_to_pnc_junction = pnc_junction_overlap.start_s - adc_front_edge_s; ADEBUG << "adc_distance_to_pnc_junction[" << adc_distance_to_pnc_junction << "] pnc_junction[" << pnc_junction_overlap.object_id << "] pnc_junction_overlap_start_s[" << pnc_junction_overlap.start_s << "]"; const bool bare_junction_scenario = (adc_distance_to_pnc_junction > 0.0 && adc_distance_to_pnc_junction <= scenario_config.start_bare_intersection_scenario_distance()); switch (current_scenario_->scenario_type()) { case ScenarioType::LANE_FOLLOW: case ScenarioType::PARK_AND_GO: case ScenarioType::PULL_OVER: if (bare_junction_scenario) { return ScenarioType::BARE_INTERSECTION_UNPROTECTED; } break; case ScenarioType::BARE_INTERSECTION_UNPROTECTED: case ScenarioType::EMERGENCY_PULL_OVER: case ScenarioType::STOP_SIGN_PROTECTED: case ScenarioType::STOP_SIGN_UNPROTECTED: case ScenarioType::TRAFFIC_LIGHT_PROTECTED: case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN: case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN: case ScenarioType::YIELD_SIGN: case ScenarioType::VALET_PARKING: if (current_scenario_->GetStatus() != Scenario::ScenarioStatus::STATUS_DONE) { return current_scenario_->scenario_type(); } break; default: break; } return default_scenario_type_; } ScenarioType ScenarioManager::SelectValetParkingScenario(const Frame& frame) { const auto& scenario_config = config_map_[ScenarioType::VALET_PARKING].valet_parking_config(); // TODO(All) trigger valet parking by route message definition as of now double parking_spot_range_to_start = scenario_config.parking_spot_range_to_start(); if (scenario::valet_parking::ValetParkingScenario::IsTransferable( frame, parking_spot_range_to_start)) { return ScenarioType::VALET_PARKING; } return default_scenario_type_; } ScenarioType ScenarioManager::SelectParkAndGoScenario(const Frame& frame) { bool park_and_go = false; const auto& scenario_config = config_map_[ScenarioType::PARK_AND_GO].park_and_go_config(); const auto vehicle_state_provider = injector_->vehicle_state(); common::VehicleState vehicle_state = vehicle_state_provider->vehicle_state(); auto adc_point = common::util::PointFactory::ToPointENU(vehicle_state); // TODO(SHU) might consider gear == GEAR_PARKING double adc_speed = vehicle_state_provider->linear_velocity(); double s = 0.0; double l = 0.0; const double max_abs_speed_when_stopped = common::VehicleConfigHelper::Instance() ->GetConfig() .vehicle_param() .max_abs_speed_when_stopped(); hdmap::LaneInfoConstPtr lane; // check ego vehicle distance to destination const auto& routing = frame.local_view().routing; const auto& routing_end = *(routing->routing_request().waypoint().rbegin()); common::SLPoint dest_sl; const auto& reference_line_info = frame.reference_line_info().front(); const auto& reference_line = reference_line_info.reference_line(); reference_line.XYToSL(routing_end.pose(), &dest_sl); const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const double adc_distance_to_dest = dest_sl.s() - adc_front_edge_s; ADEBUG << "adc_distance_to_dest:" << adc_distance_to_dest; // if vehicle is static, far enough to destination and (off-lane or not on // city_driving lane) if (std::fabs(adc_speed) < max_abs_speed_when_stopped && adc_distance_to_dest > scenario_config.min_dist_to_dest() && (HDMapUtil::BaseMap().GetNearestLaneWithHeading( adc_point, 2.0, vehicle_state.heading(), M_PI / 3.0, &lane, &s, &l) != 0 || lane->lane().type() != hdmap::Lane::CITY_DRIVING)) { park_and_go = true; } if (park_and_go) { return ScenarioType::PARK_AND_GO; } return default_scenario_type_; } void ScenarioManager::Observe(const Frame& frame) { // init first_encountered_overlap_map_ first_encountered_overlap_map_.clear(); const auto& reference_line_info = frame.reference_line_info().front(); const auto& first_encountered_overlaps = reference_line_info.FirstEncounteredOverlaps(); for (const auto& overlap : first_encountered_overlaps) { if (overlap.first == ReferenceLineInfo::PNC_JUNCTION || overlap.first == ReferenceLineInfo::SIGNAL || overlap.first == ReferenceLineInfo::STOP_SIGN || overlap.first == ReferenceLineInfo::YIELD_SIGN) { first_encountered_overlap_map_[overlap.first] = overlap.second; } } } void ScenarioManager::Update(const common::TrajectoryPoint& ego_point, const Frame& frame) { ACHECK(!frame.reference_line_info().empty()); Observe(frame); ScenarioDispatch(frame); } void ScenarioManager::ScenarioDispatch(const Frame& frame) { ACHECK(!frame.reference_line_info().empty()); ScenarioType scenario_type; int history_points_len = 0; if (injector_->learning_based_data() && injector_->learning_based_data()->GetLatestLearningDataFrame()) { history_points_len = injector_->learning_based_data() ->GetLatestLearningDataFrame() ->adc_trajectory_point_size(); } if ((planning_config_.learning_mode() == PlanningConfig::E2E || planning_config_.learning_mode() == PlanningConfig::E2E_TEST) && history_points_len >= FLAGS_min_past_history_points_len) { scenario_type = ScenarioDispatchLearning(); } else { scenario_type = ScenarioDispatchNonLearning(frame); } ADEBUG << "select scenario: " << ScenarioType_Name(scenario_type); // update PlanningContext UpdatePlanningContext(frame, scenario_type); if (current_scenario_->scenario_type() != scenario_type) { current_scenario_ = CreateScenario(scenario_type); } } ScenarioType ScenarioManager::ScenarioDispatchLearning() { //////////////////////////////////////// // learning model scenario ScenarioType scenario_type = ScenarioType::LEARNING_MODEL_SAMPLE; return scenario_type; } ScenarioType ScenarioManager::ScenarioDispatchNonLearning(const Frame& frame) { //////////////////////////////////////// // default: LANE_FOLLOW ScenarioType scenario_type = default_scenario_type_; //////////////////////////////////////// // Pad Msg scenario scenario_type = SelectPadMsgScenario(frame); if (scenario_type == default_scenario_type_) { // check current_scenario (not switchable) switch (current_scenario_->scenario_type()) { case ScenarioType::LANE_FOLLOW: case ScenarioType::PULL_OVER: break; case ScenarioType::BARE_INTERSECTION_UNPROTECTED: case ScenarioType::EMERGENCY_PULL_OVER: case ScenarioType::PARK_AND_GO: case ScenarioType::STOP_SIGN_PROTECTED: case ScenarioType::STOP_SIGN_UNPROTECTED: case ScenarioType::TRAFFIC_LIGHT_PROTECTED: case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN: case ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN: case ScenarioType::VALET_PARKING: case ScenarioType::YIELD_SIGN: // must continue until finish if (current_scenario_->GetStatus() != Scenario::ScenarioStatus::STATUS_DONE) { scenario_type = current_scenario_->scenario_type(); } break; default: break; } } //////////////////////////////////////// // ParkAndGo / starting scenario if (scenario_type == default_scenario_type_) { if (FLAGS_enable_scenario_park_and_go) { scenario_type = SelectParkAndGoScenario(frame); } } //////////////////////////////////////// // intersection scenarios if (scenario_type == default_scenario_type_) { scenario_type = SelectInterceptionScenario(frame); } //////////////////////////////////////// // pull-over scenario if (scenario_type == default_scenario_type_) { if (FLAGS_enable_scenario_pull_over) { scenario_type = SelectPullOverScenario(frame); } } //////////////////////////////////////// // VALET_PARKING scenario if (scenario_type == default_scenario_type_) { scenario_type = SelectValetParkingScenario(frame); } return scenario_type; } bool ScenarioManager::IsBareIntersectionScenario( const ScenarioType& scenario_type) { return (scenario_type == ScenarioType::BARE_INTERSECTION_UNPROTECTED); } bool ScenarioManager::IsStopSignScenario(const ScenarioType& scenario_type) { return (scenario_type == ScenarioType::STOP_SIGN_PROTECTED || scenario_type == ScenarioType::STOP_SIGN_UNPROTECTED); } bool ScenarioManager::IsTrafficLightScenario( const ScenarioType& scenario_type) { return (scenario_type == ScenarioType::TRAFFIC_LIGHT_PROTECTED || scenario_type == ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN || scenario_type == ScenarioType::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN); } bool ScenarioManager::IsYieldSignScenario(const ScenarioType& scenario_type) { return (scenario_type == ScenarioType::YIELD_SIGN); } void ScenarioManager::UpdatePlanningContext(const Frame& frame, const ScenarioType& scenario_type) { // BareIntersection scenario UpdatePlanningContextBareIntersectionScenario(frame, scenario_type); // EmergencyStop scenario UpdatePlanningContextEmergencyStopcenario(frame, scenario_type); // PullOver & EmergencyPullOver scenarios UpdatePlanningContextPullOverScenario(frame, scenario_type); // StopSign scenario UpdatePlanningContextStopSignScenario(frame, scenario_type); // TrafficLight scenario UpdatePlanningContextTrafficLightScenario(frame, scenario_type); // YieldSign scenario UpdatePlanningContextYieldSignScenario(frame, scenario_type); } // update: bare_intersection status in PlanningContext void ScenarioManager::UpdatePlanningContextBareIntersectionScenario( const Frame& frame, const ScenarioType& scenario_type) { auto* bare_intersection = injector_->planning_context() ->mutable_planning_status() ->mutable_bare_intersection(); if (!IsBareIntersectionScenario(scenario_type)) { bare_intersection->Clear(); return; } if (scenario_type == current_scenario_->scenario_type()) { return; } // set to first_encountered pnc_junction const auto map_itr = first_encountered_overlap_map_.find(ReferenceLineInfo::PNC_JUNCTION); if (map_itr != first_encountered_overlap_map_.end()) { bare_intersection->set_current_pnc_junction_overlap_id( map_itr->second.object_id); ADEBUG << "Update PlanningContext with first_encountered pnc_junction[" << map_itr->second.object_id << "] start_s[" << map_itr->second.start_s << "]"; } } // update: emergency_stop status in PlanningContext void ScenarioManager::UpdatePlanningContextEmergencyStopcenario( const Frame& frame, const ScenarioType& scenario_type) { auto* emergency_stop = injector_->planning_context() ->mutable_planning_status() ->mutable_emergency_stop(); if (scenario_type != ScenarioType::EMERGENCY_STOP) { emergency_stop->Clear(); } } // update: stop_sign status in PlanningContext void ScenarioManager::UpdatePlanningContextStopSignScenario( const Frame& frame, const ScenarioType& scenario_type) { if (!IsStopSignScenario(scenario_type)) { injector_->planning_context() ->mutable_planning_status() ->mutable_stop_sign() ->Clear(); return; } if (scenario_type == current_scenario_->scenario_type()) { return; } // set to first_encountered stop_sign const auto map_itr = first_encountered_overlap_map_.find(ReferenceLineInfo::STOP_SIGN); if (map_itr != first_encountered_overlap_map_.end()) { injector_->planning_context() ->mutable_planning_status() ->mutable_stop_sign() ->set_current_stop_sign_overlap_id(map_itr->second.object_id); ADEBUG << "Update PlanningContext with first_encountered stop sign[" << map_itr->second.object_id << "] start_s[" << map_itr->second.start_s << "]"; } } // update: traffic_light(s) status in PlanningContext void ScenarioManager::UpdatePlanningContextTrafficLightScenario( const Frame& frame, const ScenarioType& scenario_type) { if (!IsTrafficLightScenario(scenario_type)) { injector_->planning_context() ->mutable_planning_status() ->mutable_traffic_light() ->Clear(); return; } if (scenario_type == current_scenario_->scenario_type()) { return; } // get first_encountered traffic_light std::string current_traffic_light_overlap_id; const auto map_itr = first_encountered_overlap_map_.find(ReferenceLineInfo::SIGNAL); if (map_itr != first_encountered_overlap_map_.end()) { current_traffic_light_overlap_id = map_itr->second.object_id; } if (current_traffic_light_overlap_id.empty()) { injector_->planning_context() ->mutable_planning_status() ->mutable_traffic_light() ->Clear(); return; } // find all the traffic light at/within the same location/group const auto& reference_line_info = frame.reference_line_info().front(); const std::vector<PathOverlap>& traffic_light_overlaps = reference_line_info.reference_line().map_path().signal_overlaps(); auto traffic_light_overlap_itr = std::find_if( traffic_light_overlaps.begin(), traffic_light_overlaps.end(), [&current_traffic_light_overlap_id](const hdmap::PathOverlap& overlap) { return overlap.object_id == current_traffic_light_overlap_id; }); if (traffic_light_overlap_itr == traffic_light_overlaps.end()) { injector_->planning_context() ->mutable_planning_status() ->mutable_traffic_light() ->Clear(); return; } static constexpr double kTrafficLightGroupingMaxDist = 2.0; // unit: m const double current_traffic_light_overlap_start_s = traffic_light_overlap_itr->start_s; for (const auto& traffic_light_overlap : traffic_light_overlaps) { const double dist = traffic_light_overlap.start_s - current_traffic_light_overlap_start_s; if (fabs(dist) <= kTrafficLightGroupingMaxDist) { injector_->planning_context() ->mutable_planning_status() ->mutable_traffic_light() ->add_current_traffic_light_overlap_id( traffic_light_overlap.object_id); ADEBUG << "Update PlanningContext with first_encountered traffic_light[" << traffic_light_overlap.object_id << "] start_s[" << traffic_light_overlap.start_s << "]"; } } } // update: yield_sign status in PlanningContext void ScenarioManager::UpdatePlanningContextYieldSignScenario( const Frame& frame, const ScenarioType& scenario_type) { if (!IsYieldSignScenario(scenario_type)) { injector_->planning_context() ->mutable_planning_status() ->mutable_yield_sign() ->Clear(); return; } if (scenario_type == current_scenario_->scenario_type()) { return; } // get first_encountered yield_sign std::string current_yield_sign_overlap_id; const auto map_itr = first_encountered_overlap_map_.find(ReferenceLineInfo::YIELD_SIGN); if (map_itr != first_encountered_overlap_map_.end()) { current_yield_sign_overlap_id = map_itr->second.object_id; } if (current_yield_sign_overlap_id.empty()) { injector_->planning_context() ->mutable_planning_status() ->mutable_yield_sign() ->Clear(); return; } // find all the yield_sign at/within the same location/group const auto& reference_line_info = frame.reference_line_info().front(); const std::vector<PathOverlap>& yield_sign_overlaps = reference_line_info.reference_line().map_path().yield_sign_overlaps(); auto yield_sign_overlap_itr = std::find_if( yield_sign_overlaps.begin(), yield_sign_overlaps.end(), [&current_yield_sign_overlap_id](const hdmap::PathOverlap& overlap) { return overlap.object_id == current_yield_sign_overlap_id; }); if (yield_sign_overlap_itr == yield_sign_overlaps.end()) { injector_->planning_context() ->mutable_planning_status() ->mutable_yield_sign() ->Clear(); return; } static constexpr double kTrafficLightGroupingMaxDist = 2.0; // unit: m const double current_yield_sign_overlap_start_s = yield_sign_overlap_itr->start_s; for (const auto& yield_sign_overlap : yield_sign_overlaps) { const double dist = yield_sign_overlap.start_s - current_yield_sign_overlap_start_s; if (fabs(dist) <= kTrafficLightGroupingMaxDist) { injector_->planning_context() ->mutable_planning_status() ->mutable_yield_sign() ->add_current_yield_sign_overlap_id(yield_sign_overlap.object_id); ADEBUG << "Update PlanningContext with first_encountered yield_sign[" << yield_sign_overlap.object_id << "] start_s[" << yield_sign_overlap.start_s << "]"; } } } // update: pull_over status in PlanningContext void ScenarioManager::UpdatePlanningContextPullOverScenario( const Frame& frame, const ScenarioType& scenario_type) { auto* pull_over = injector_->planning_context() ->mutable_planning_status() ->mutable_pull_over(); if (scenario_type == ScenarioType::PULL_OVER) { pull_over->set_pull_over_type(PullOverStatus::PULL_OVER); pull_over->set_plan_pull_over_path(true); return; } else if (scenario_type == ScenarioType::EMERGENCY_PULL_OVER) { pull_over->set_pull_over_type(PullOverStatus::EMERGENCY_PULL_OVER); return; } pull_over->set_plan_pull_over_path(false); // check pull_over_status left behind // keep it if close to destination, to keep stop fence 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()) { const auto& routing = frame.local_view().routing; if (routing->routing_request().waypoint_size() >= 2) { // keep pull-over stop fence if destination not changed const auto& reference_line_info = frame.reference_line_info().front(); const auto& reference_line = reference_line_info.reference_line(); common::SLPoint dest_sl; const auto& routing_end = *(routing->routing_request().waypoint().rbegin()); reference_line.XYToSL(routing_end.pose(), &dest_sl); common::SLPoint pull_over_sl; reference_line.XYToSL(pull_over_status.position(), &pull_over_sl); static constexpr double kDestMaxDelta = 30.0; // meter if (std::fabs(dest_sl.s() - pull_over_sl.s()) > kDestMaxDelta) { injector_->planning_context() ->mutable_planning_status() ->clear_pull_over(); } } } } } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/scenarios/scenario.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/scenarios/scenario.h" #include "cyber/common/file.h" #include "modules/planning/common/frame.h" namespace apollo { namespace planning { namespace scenario { Scenario::Scenario(const ScenarioConfig& config, const ScenarioContext* context, const std::shared_ptr<DependencyInjector>& injector) : config_(config), scenario_context_(context), injector_(injector) { name_ = ScenarioType_Name(config.scenario_type()); } bool Scenario::LoadConfig(const std::string& config_file, ScenarioConfig* config) { return apollo::cyber::common::GetProtoFromFile(config_file, config); } void Scenario::Init() { ACHECK(!config_.stage_type().empty()); // set scenario_type in PlanningContext auto* scenario = injector_->planning_context() ->mutable_planning_status() ->mutable_scenario(); scenario->Clear(); scenario->set_scenario_type(scenario_type()); for (const auto& stage_config : config_.stage_config()) { stage_config_map_[stage_config.stage_type()] = &stage_config; } for (int i = 0; i < config_.stage_type_size(); ++i) { auto stage_type = config_.stage_type(i); ACHECK(common::util::ContainsKey(stage_config_map_, stage_type)) << "stage type : " << StageType_Name(stage_type) << " has no config"; } ADEBUG << "init stage " << StageType_Name(config_.stage_type(0)); current_stage_ = CreateStage(*stage_config_map_[config_.stage_type(0)], injector_); } Scenario::ScenarioStatus Scenario::Process( const common::TrajectoryPoint& planning_init_point, Frame* frame) { if (current_stage_ == nullptr) { AWARN << "Current stage is a null pointer."; return STATUS_UNKNOWN; } if (current_stage_->stage_type() == StageType::NO_STAGE) { scenario_status_ = STATUS_DONE; return scenario_status_; } auto ret = current_stage_->Process(planning_init_point, frame); switch (ret) { case Stage::ERROR: { AERROR << "Stage '" << current_stage_->Name() << "' returns error"; scenario_status_ = STATUS_UNKNOWN; break; } case Stage::RUNNING: { scenario_status_ = STATUS_PROCESSING; break; } case Stage::FINISHED: { auto next_stage = current_stage_->NextStage(); if (next_stage != current_stage_->stage_type()) { AINFO << "switch stage from " << current_stage_->Name() << " to " << StageType_Name(next_stage); if (next_stage == StageType::NO_STAGE) { scenario_status_ = STATUS_DONE; return scenario_status_; } if (stage_config_map_.find(next_stage) == stage_config_map_.end()) { AERROR << "Failed to find config for stage: " << next_stage; scenario_status_ = STATUS_UNKNOWN; return scenario_status_; } current_stage_ = CreateStage(*stage_config_map_[next_stage], injector_); if (current_stage_ == nullptr) { AWARN << "Current stage is a null pointer."; return STATUS_UNKNOWN; } } if (current_stage_ != nullptr && current_stage_->stage_type() != StageType::NO_STAGE) { scenario_status_ = STATUS_PROCESSING; } else { scenario_status_ = STATUS_DONE; } break; } default: { AWARN << "Unexpected Stage return value: " << ret; scenario_status_ = STATUS_UNKNOWN; } } return scenario_status_; } const std::string& Scenario::Name() const { return name_; } } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/scenarios/stage.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 <map> #include <memory> #include <string> #include <vector> #include "modules/common/status/status.h" #include "modules/common/util/factory.h" #include "modules/planning/common/frame.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { namespace scenario { class Stage { public: enum StageStatus { ERROR = 1, READY = 2, RUNNING = 3, FINISHED = 4, }; Stage(const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector); virtual ~Stage() = default; const ScenarioConfig::StageConfig& config() const { return config_; } StageType stage_type() const { return config_.stage_type(); } /** * @brief Each stage does its business logic inside Process function. * If the stage want to transit to a different stage after finish, * it should set the type of 'next_stage_'. */ virtual StageStatus Process( const common::TrajectoryPoint& planning_init_point, Frame* frame) = 0; /** * @brief The sequence of tasks inside the stage. These tasks usually will be * executed in order. */ const std::vector<Task*>& TaskList() const { return task_list_; } const std::string& Name() const; template <typename T> T* GetContextAs() { return static_cast<T*>(context_); } void SetContext(void* context) { context_ = context; } Task* FindTask(TaskConfig::TaskType task_type) const; StageType NextStage() const { return next_stage_; } protected: bool ExecuteTaskOnReferenceLine( const common::TrajectoryPoint& planning_start_point, Frame* frame); bool ExecuteTaskOnReferenceLineForOnlineLearning( const common::TrajectoryPoint& planning_start_point, Frame* frame); bool ExecuteTaskOnOpenSpace(Frame* frame); virtual Stage::StageStatus FinishScenario(); void RecordDebugInfo(ReferenceLineInfo* reference_line_info, const std::string& name, const double time_diff_ms); protected: std::map<TaskConfig::TaskType, std::unique_ptr<Task>> tasks_; std::vector<Task*> task_list_; ScenarioConfig::StageConfig config_; StageType next_stage_; void* context_ = nullptr; std::string name_; std::shared_ptr<DependencyInjector> injector_; }; #define DECLARE_STAGE(NAME, CONTEXT) \ class NAME : public Stage { \ public: \ explicit NAME(const ScenarioConfig::StageConfig& config) \ : Stage(config) {} \ Stage::StageStatus Process( \ const common::TrajectoryPoint& planning_init_point, \ Frame* frame) override; \ CONTEXT* GetContext() { return GetContextAs<CONTEXT>(); } \ } } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/scenarios/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) PLANNING_COPTS = ["-DMODULE_NAME=\\\"planning\\\""] cc_library( name = "scenario", srcs = ["scenario.cc"], hdrs = ["scenario.h"], copts = PLANNING_COPTS, deps = [ ":stage", "//modules/planning/common:planning_common", "//modules/planning/common/util:util_lib", "//modules/planning/tasks:task", ], ) cc_library( name = "stage", srcs = ["stage.cc"], hdrs = ["stage.h"], copts = PLANNING_COPTS, deps = [ "//modules/planning/common:planning_common", "//modules/planning/common/util:util_lib", "//modules/planning/tasks:task", "//modules/planning/tasks:task_factory", ], ) cc_library( name = "scenario_manager", srcs = ["scenario_manager.cc"], hdrs = ["scenario_manager.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/common/vehicle_state:vehicle_state_provider", "//modules/planning/common:planning_common", "//modules/planning/common:planning_context", "//modules/planning/common/util:util_lib", "//modules/planning/scenarios/bare_intersection/unprotected:bare_intersection_unprotected_scenario", "//modules/planning/scenarios/emergency/emergency_pull_over:emergency_pull_over_scenario", "//modules/planning/scenarios/emergency/emergency_stop:emergency_stop_scenario", "//modules/planning/scenarios/lane_follow", "//modules/planning/scenarios/learning_model", "//modules/planning/scenarios/park/pull_over:pull_over_scenario", "//modules/planning/scenarios/park/valet_parking", "//modules/planning/scenarios/park_and_go:park_and_go_scenario", "//modules/planning/scenarios/stop_sign/unprotected:stop_sign_unprotected_scenario", "//modules/planning/scenarios/traffic_light/protected:traffic_light_protected_scenario", "//modules/planning/scenarios/traffic_light/unprotected_left_turn:traffic_light_unprotected_left_turn_scenario", "//modules/planning/scenarios/traffic_light/unprotected_right_turn:traffic_light_unprotected_right_turn_scenario", "//modules/planning/scenarios/yield_sign:yield_sign_scenario", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/yield_sign/yield_sign_scenario.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 <string> #include <unordered_map> #include <vector> #include "modules/common/util/factory.h" #include "modules/map/hdmap/hdmap.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/planning/scenarios/scenario.h" namespace apollo { namespace planning { namespace scenario { namespace yield_sign { // stage context struct YieldSignContext { ScenarioYieldSignConfig scenario_config; std::vector<std::string> current_yield_sign_overlap_ids; double creep_start_time = 0.0; }; class YieldSignScenario : public Scenario { public: YieldSignScenario(const ScenarioConfig& config, const ScenarioContext* context, const std::shared_ptr<DependencyInjector>& injector) : Scenario(config, context, injector) {} void Init() override; std::unique_ptr<Stage> CreateStage( const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector); YieldSignContext* GetContext() { return &context_; } private: static void RegisterStages(); bool GetScenarioConfig(); private: static apollo::common::util::Factory< StageType, Stage, Stage* (*)(const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector)> s_stage_factory_; bool init_ = false; YieldSignContext context_; }; } // namespace yield_sign } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/yield_sign/stage_approach.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 <string> #include "modules/planning/scenarios/stage.h" #include "modules/planning/scenarios/yield_sign/yield_sign_scenario.h" namespace apollo { namespace planning { namespace scenario { namespace yield_sign { struct YieldSignContext; class YieldSignStageApproach : public Stage { public: YieldSignStageApproach(const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Stage(config, injector) {} private: Stage::StageStatus Process(const common::TrajectoryPoint& planning_init_point, Frame* frame) override; YieldSignContext* GetContext() { return GetContextAs<YieldSignContext>(); } private: Stage::StageStatus FinishStage(); private: ScenarioYieldSignConfig scenario_config_; }; } // namespace yield_sign } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/yield_sign/stage_creep_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/scenarios/yield_sign/stage_creep.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "gtest/gtest.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace scenario { namespace yield_sign { class YieldSignStageCreepTest : public ::testing::Test { public: virtual void SetUp() { config_.set_stage_type(StageType::YIELD_SIGN_CREEP); injector_ = std::make_shared<DependencyInjector>(); } protected: ScenarioConfig::StageConfig config_; std::shared_ptr<DependencyInjector> injector_; }; TEST_F(YieldSignStageCreepTest, Init) { YieldSignStageCreep yield_sign_stage_creep(config_, injector_); EXPECT_EQ(yield_sign_stage_creep.Name(), StageType_Name(StageType::YIELD_SIGN_CREEP)); } } // namespace yield_sign } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/yield_sign/stage_creep.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/proto/planning_config.pb.h" #include "modules/planning/scenarios/stage.h" #include "modules/planning/scenarios/yield_sign/yield_sign_scenario.h" namespace apollo { namespace planning { namespace scenario { namespace yield_sign { struct YieldSignContext; class YieldSignStageCreep : public Stage { public: YieldSignStageCreep(const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Stage(config, injector) {} private: Stage::StageStatus Process(const common::TrajectoryPoint& planning_init_point, Frame* frame) override; YieldSignContext* GetContext() { return Stage::GetContextAs<YieldSignContext>(); } private: Stage::StageStatus FinishStage(); private: ScenarioYieldSignConfig scenario_config_; }; } // namespace yield_sign } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/yield_sign/yield_sign_scenario.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/scenarios/yield_sign/yield_sign_scenario.h" #include "cyber/common/log.h" #include "modules/common_msgs/perception_msgs/perception_obstacle.pb.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/scenarios/yield_sign/stage_approach.h" #include "modules/planning/scenarios/yield_sign/stage_creep.h" namespace apollo { namespace planning { namespace scenario { namespace yield_sign { using apollo::hdmap::HDMapUtil; using StopSignLaneVehicles = std::unordered_map<std::string, std::vector<std::string>>; apollo::common::util::Factory< StageType, Stage, Stage* (*)(const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector)> YieldSignScenario::s_stage_factory_; void YieldSignScenario::Init() { if (init_) { return; } Scenario::Init(); if (!GetScenarioConfig()) { AERROR << "fail to get scenario specific config"; return; } const auto& yield_sign_status = injector_->planning_context()->planning_status().yield_sign(); if (yield_sign_status.current_yield_sign_overlap_id().empty()) { AERROR << "Could not find yield-sign(s)"; return; } context_.current_yield_sign_overlap_ids.clear(); for (int i = 0; i < yield_sign_status.current_yield_sign_overlap_id_size(); i++) { const std::string yield_sign_overlap_id = yield_sign_status.current_yield_sign_overlap_id(i); hdmap::YieldSignInfoConstPtr yield_sign = HDMapUtil::BaseMap().GetYieldSignById( hdmap::MakeMapId(yield_sign_overlap_id)); if (!yield_sign) { AERROR << "Could not find yield sign: " << yield_sign_overlap_id; } context_.current_yield_sign_overlap_ids.push_back(yield_sign_overlap_id); } init_ = true; } void YieldSignScenario::RegisterStages() { if (!s_stage_factory_.Empty()) { s_stage_factory_.Clear(); } s_stage_factory_.Register( StageType::YIELD_SIGN_APPROACH, [](const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) -> Stage* { return new YieldSignStageApproach(config, injector); }); s_stage_factory_.Register( StageType::YIELD_SIGN_CREEP, [](const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) -> Stage* { return new YieldSignStageCreep(config, injector); }); } std::unique_ptr<Stage> YieldSignScenario::CreateStage( const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector) { if (s_stage_factory_.Empty()) { RegisterStages(); } auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(), stage_config, injector); if (ptr) { ptr->SetContext(&context_); } return ptr; } /* * read scenario specific configs and set in context_ for stages to read */ bool YieldSignScenario::GetScenarioConfig() { if (!config_.has_yield_sign_config()) { AERROR << "miss scenario specific config"; return false; } context_.scenario_config.CopyFrom(config_.yield_sign_config()); return true; } } // namespace yield_sign } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/yield_sign/stage_approach_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/scenarios/yield_sign/stage_approach.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "gtest/gtest.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace scenario { namespace yield_sign { class YieldSignStageApproachTest : public ::testing::Test { public: virtual void SetUp() { config_.set_stage_type(StageType::YIELD_SIGN_APPROACH); injector_ = std::make_shared<DependencyInjector>(); } protected: ScenarioConfig::StageConfig config_; std::shared_ptr<DependencyInjector> injector_; }; TEST_F(YieldSignStageApproachTest, Init) { YieldSignStageApproach yield_sign_stage_approach(config_, injector_); EXPECT_EQ( yield_sign_stage_approach.Name(), StageType_Name(StageType::YIELD_SIGN_APPROACH)); } } // namespace yield_sign } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/yield_sign/stage_creep.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/scenarios/yield_sign/stage_creep.h" #include <string> #include "cyber/common/log.h" #include "cyber/time/clock.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/pnc_map/path.h" #include "modules/common_msgs/perception_msgs/perception_obstacle.pb.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/speed_profile_generator.h" #include "modules/planning/common/util/util.h" #include "modules/planning/scenarios/util/util.h" #include "modules/planning/tasks/deciders/creep_decider/creep_decider.h" namespace apollo { namespace planning { namespace scenario { namespace yield_sign { using apollo::common::TrajectoryPoint; using apollo::cyber::Clock; using apollo::hdmap::PathOverlap; Stage::StageStatus YieldSignStageCreep::Process( const TrajectoryPoint& planning_init_point, Frame* frame) { ADEBUG << "stage: Creep"; CHECK_NOTNULL(frame); scenario_config_.CopyFrom(GetContext()->scenario_config); if (!config_.enabled()) { return FinishStage(); } bool plan_ok = ExecuteTaskOnReferenceLine(planning_init_point, frame); if (!plan_ok) { AERROR << "YieldSignStageCreep planning error"; } if (GetContext()->current_yield_sign_overlap_ids.empty()) { return FinishScenario(); } const auto& reference_line_info = frame->reference_line_info().front(); const std::string yield_sign_overlap_id = GetContext()->current_yield_sign_overlap_ids[0]; // get overlap along reference line PathOverlap* current_yield_sign_overlap = scenario::util::GetOverlapOnReferenceLine(reference_line_info, yield_sign_overlap_id, ReferenceLineInfo::YIELD_SIGN); if (!current_yield_sign_overlap) { return FinishScenario(); } // set right_of_way_status const double yield_sign_start_s = current_yield_sign_overlap->start_s; reference_line_info.SetJunctionRightOfWay(yield_sign_start_s, false); const double yield_sign_end_s = current_yield_sign_overlap->end_s; const double wait_time = Clock::NowInSeconds() - GetContext()->creep_start_time; const double timeout_sec = scenario_config_.creep_timeout_sec(); auto* task = dynamic_cast<CreepDecider*>(FindTask(TaskConfig::CREEP_DECIDER)); if (task == nullptr) { AERROR << "task is nullptr"; return FinishStage(); } double creep_stop_s = yield_sign_end_s + task->FindCreepDistance(*frame, reference_line_info); const double distance = creep_stop_s - reference_line_info.AdcSlBoundary().end_s(); if (distance <= 0.0) { auto& rfl_info = frame->mutable_reference_line_info()->front(); *(rfl_info.mutable_speed_data()) = SpeedProfileGenerator::GenerateFixedDistanceCreepProfile(0.0, 0); } if (task->CheckCreepDone(*frame, reference_line_info, yield_sign_end_s, wait_time, timeout_sec)) { return FinishStage(); } return Stage::RUNNING; } Stage::StageStatus YieldSignStageCreep::FinishStage() { return FinishScenario(); } } // namespace yield_sign } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/yield_sign/stage_approach.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/scenarios/yield_sign/stage_approach.h" #include "cyber/common/log.h" #include "cyber/time/clock.h" #include "modules/map/pnc_map/path.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/util/util.h" #include "modules/planning/scenarios/util/util.h" namespace apollo { namespace planning { namespace scenario { namespace yield_sign { using apollo::common::TrajectoryPoint; using apollo::cyber::Clock; using apollo::hdmap::PathOverlap; Stage::StageStatus YieldSignStageApproach::Process( const TrajectoryPoint& planning_init_point, Frame* frame) { ADEBUG << "stage: Approach"; CHECK_NOTNULL(frame); scenario_config_.CopyFrom(GetContext()->scenario_config); bool plan_ok = ExecuteTaskOnReferenceLine(planning_init_point, frame); if (!plan_ok) { AERROR << "YieldSignStageApproach planning error"; } const auto& reference_line_info = frame->reference_line_info().front(); if (GetContext()->current_yield_sign_overlap_ids.empty()) { return FinishScenario(); } for (const auto& yield_sign_overlap_id : GetContext()->current_yield_sign_overlap_ids) { // get overlap along reference line PathOverlap* current_yield_sign_overlap = scenario::util::GetOverlapOnReferenceLine( reference_line_info, yield_sign_overlap_id, ReferenceLineInfo::YIELD_SIGN); if (!current_yield_sign_overlap) { continue; } // set right_of_way_status reference_line_info.SetJunctionRightOfWay( current_yield_sign_overlap->start_s, false); static constexpr double kPassStopLineBuffer = 0.3; // unit: m const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const double distance_adc_pass_stop_sign = adc_front_edge_s - current_yield_sign_overlap->start_s; if (distance_adc_pass_stop_sign > kPassStopLineBuffer) { // passed stop line return FinishStage(); } const double distance_adc_to_stop_line = current_yield_sign_overlap->start_s - adc_front_edge_s; ADEBUG << "yield_sign_overlap_id[" << yield_sign_overlap_id << "] start_s[" << current_yield_sign_overlap->start_s << "] distance_adc_to_stop_line[" << distance_adc_to_stop_line << "]"; bool yield_sign_done = false; if (distance_adc_to_stop_line < scenario_config_.max_valid_stop_distance()) { // close enough, check yield_sign clear yield_sign_done = true; const auto& path_decision = reference_line_info.path_decision(); for (const auto* obstacle : path_decision.obstacles().Items()) { const std::string& obstacle_id = obstacle->Id(); std::string obstacle_type_name = PerceptionObstacle_Type_Name(obstacle->Perception().type()); ADEBUG << "yield_sign[" << yield_sign_overlap_id << "] obstacle_id[" << obstacle_id << "] type[" << obstacle_type_name << "]"; if (obstacle->IsVirtual()) { continue; } if (obstacle->reference_line_st_boundary().IsEmpty()) { continue; } static constexpr double kMinSTBoundaryT = 6.0; // sec if (obstacle->reference_line_st_boundary().min_t() > kMinSTBoundaryT) { continue; } const double kepsilon = 1e-6; double obstacle_traveled_s = obstacle->reference_line_st_boundary().bottom_left_point().s() - obstacle->reference_line_st_boundary().bottom_right_point().s(); ADEBUG << "obstacle[" << obstacle->Id() << "] obstacle_st_min_t[" << obstacle->reference_line_st_boundary().min_t() << "] obstacle_st_min_s[" << obstacle->reference_line_st_boundary().min_s() << "] obstacle_traveled_s[" << obstacle_traveled_s << "]"; // ignore the obstacle which is already on reference line and moving // along the direction of ADC // max st_min_t(sec) to ignore static constexpr double kIgnoreMaxSTMinT = 0.1; // min st_min_s(m) to ignore static constexpr double kIgnoreMinSTMinS = 15.0; if (obstacle_traveled_s < kepsilon && obstacle->reference_line_st_boundary().min_t() < kIgnoreMaxSTMinT && obstacle->reference_line_st_boundary().min_s() > kIgnoreMinSTMinS) { continue; } injector_->planning_context() ->mutable_planning_status() ->mutable_yield_sign() ->add_wait_for_obstacle_id(obstacle->Id()); yield_sign_done = false; } } if (yield_sign_done) { return FinishStage(); } } return Stage::RUNNING; } Stage::StageStatus YieldSignStageApproach::FinishStage() { // update PlanningContext auto* yield_sign_status = injector_->planning_context() ->mutable_planning_status() ->mutable_yield_sign(); yield_sign_status->mutable_done_yield_sign_overlap_id()->Clear(); for (const auto& yield_sign_overlap_id : GetContext()->current_yield_sign_overlap_ids) { yield_sign_status->add_done_yield_sign_overlap_id(yield_sign_overlap_id); } yield_sign_status->clear_wait_for_obstacle_id(); GetContext()->creep_start_time = Clock::NowInSeconds(); next_stage_ = StageType::YIELD_SIGN_CREEP; return Stage::FINISHED; } } // namespace yield_sign } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/yield_sign/yield_sign_scenario_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/scenarios/yield_sign/yield_sign_scenario.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "gtest/gtest.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace scenario { namespace yield_sign { class YieldSignScenarioTest : public ::testing::Test { public: virtual void SetUp() {} protected: std::unique_ptr<YieldSignScenario> scenario_; }; TEST_F(YieldSignScenarioTest, VerifyConf) { FLAGS_scenario_yield_sign_config_file = "/apollo/modules/planning/conf/" "scenario/yield_sign_config.pb.txt"; ScenarioConfig config; EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile( FLAGS_scenario_yield_sign_config_file, &config)); ScenarioContext context; auto injector = std::make_shared<DependencyInjector>(); scenario_.reset(new YieldSignScenario(config, &context, injector)); EXPECT_EQ(scenario_->scenario_type(), ScenarioType::YIELD_SIGN); } } // namespace yield_sign } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/yield_sign/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") load("//third_party/gpus:common.bzl", "if_cuda", "if_rocm") package(default_visibility = ["//visibility:public"]) cc_library( name = "yield_sign_scenario", srcs = [ "stage_approach.cc", "stage_creep.cc", "yield_sign_scenario.cc", ], hdrs = [ "stage_approach.h", "stage_creep.h", "yield_sign_scenario.h", ], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//cyber", "//modules/common/util:util_tool", "//modules/common/vehicle_state:vehicle_state_provider", "//modules/planning/common:planning_common", "//modules/planning/common/util:common_lib", "//modules/planning/common/util:util_lib", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/scenarios:scenario", "//modules/planning/scenarios/util:scenario_util_lib", "@com_github_gflags_gflags//:gflags", "@eigen", ], ) cc_test( name = "yield_sign_scenario_test", size = "small", srcs = ["yield_sign_scenario_test.cc"], data = [ "//modules/planning:planning_conf", ], linkopts = ["-lgomp"], deps = [ ":yield_sign_scenario", "@com_google_googletest//:gtest_main", ] + if_cuda([ "@local_config_cuda//cuda:cudart", ]) + if_rocm([ "@local_config_rocm//rocm:hip", ]), linkstatic = True, ) cc_test( name = "stage_approach_test", size = "small", srcs = ["stage_approach_test.cc"], data = [ "//modules/planning:planning_conf", ], linkopts = ["-lgomp"], deps = [ ":yield_sign_scenario", "@com_google_googletest//:gtest_main", ] + if_cuda([ "@local_config_cuda//cuda:cudart", ]) + if_rocm([ "@local_config_rocm//rocm:hip", ]), linkstatic = True, ) cc_test( name = "stage_creep_test", size = "small", srcs = ["stage_creep_test.cc"], data = [ "//modules/planning:planning_conf", ], linkopts = ["-lgomp"], deps = [ ":yield_sign_scenario", "@com_google_googletest//:gtest_main", ] + if_cuda([ "@local_config_cuda//cuda:cudart", ]) + if_rocm([ "@local_config_rocm//rocm:hip", ]), linkstatic = True, ) cpplint()
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/lane_follow/lane_follow_scenario.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 "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/frame.h" #include "modules/planning/common/reference_line_info.h" #include "modules/planning/common/speed_profile_generator.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/planning/reference_line/reference_line.h" #include "modules/planning/reference_line/reference_point.h" #include "modules/planning/scenarios/scenario.h" #include "modules/planning/scenarios/stage.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { namespace scenario { namespace lane_follow { class LaneFollowScenario : public Scenario { public: LaneFollowScenario(const ScenarioConfig& config, const ScenarioContext* context, const std::shared_ptr<DependencyInjector>& injector) : Scenario(config, context, injector) {} std::unique_ptr<Stage> CreateStage( const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector) override; }; } // namespace lane_follow } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/lane_follow/lane_follow_scenario.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/scenarios/lane_follow/lane_follow_scenario.h" #include "cyber/common/log.h" #include "modules/planning/scenarios/lane_follow/lane_follow_stage.h" namespace apollo { namespace planning { namespace scenario { namespace lane_follow { std::unique_ptr<Stage> LaneFollowScenario::CreateStage( const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector) { if (stage_config.stage_type() != StageType::LANE_FOLLOW_DEFAULT_STAGE) { AERROR << "Follow lane does not support stage type: " << StageType_Name(stage_config.stage_type()); return nullptr; } return std::unique_ptr<Stage>(new LaneFollowStage(stage_config, injector)); } } // namespace lane_follow } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/lane_follow/lane_follow_scenario_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/scenarios/lane_follow/lane_follow_scenario.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "gtest/gtest.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace scenario { namespace lane_follow { class LaneFollowScenarioTest : public ::testing::Test { public: virtual void SetUp() {} protected: std::unique_ptr<LaneFollowScenario> scenario_; }; TEST_F(LaneFollowScenarioTest, Init) { FLAGS_scenario_lane_follow_config_file = "/apollo/modules/planning/conf/scenario/lane_follow_config.pb.txt"; ScenarioConfig config; EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile( FLAGS_scenario_lane_follow_config_file, &config)); ScenarioContext context; auto injector = std::make_shared<DependencyInjector>(); scenario_.reset(new LaneFollowScenario(config, &context, injector)); EXPECT_EQ(scenario_->scenario_type(), ScenarioType::LANE_FOLLOW); } } // namespace lane_follow } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/lane_follow/lane_follow_stage.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 <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/common/speed_profile_generator.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/planning/reference_line/reference_line.h" #include "modules/planning/reference_line/reference_point.h" #include "modules/planning/scenarios/scenario.h" #include "modules/planning/scenarios/stage.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { namespace scenario { namespace lane_follow { class LaneFollowStage : public Stage { public: LaneFollowStage(const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector); StageStatus Process(const common::TrajectoryPoint& planning_init_point, Frame* frame) override; common::Status PlanOnReferenceLine( const common::TrajectoryPoint& planning_start_point, Frame* frame, ReferenceLineInfo* reference_line_info); void PlanFallbackTrajectory( const common::TrajectoryPoint& planning_start_point, Frame* frame, ReferenceLineInfo* reference_line_info); void GenerateFallbackPathProfile(const ReferenceLineInfo* reference_line_info, PathData* path_data); bool RetrieveLastFramePathProfile( const ReferenceLineInfo* reference_line_info, const Frame* frame, PathData* path_data); common::SLPoint GetStopSL(const ObjectStop& stop_decision, const ReferenceLine& reference_line) const; void RecordObstacleDebugInfo(ReferenceLineInfo* reference_line_info); private: ScenarioConfig config_; std::unique_ptr<Stage> stage_; }; } // namespace lane_follow } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/lane_follow/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") load("//third_party/gpus:common.bzl", "if_cuda", "if_rocm") package(default_visibility = ["//visibility:public"]) PLANNING_COPTS = ["-DMODULE_NAME=\\\"planning\\\""] cc_library( name = "lane_follow", copts = PLANNING_COPTS, deps = [ ":lane_follow_scenario", ":lane_follow_stage", ], ) cc_library( name = "lane_follow_stage", srcs = ["lane_follow_stage.cc"], hdrs = ["lane_follow_stage.h"], copts = PLANNING_COPTS, 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:speed_profile_generator", "//modules/planning/constraint_checker", "//modules/planning/math/curve1d:quartic_polynomial_curve1d", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/reference_line", "//modules/planning/reference_line:qp_spline_reference_line_smoother", "//modules/planning/scenarios:scenario", "//modules/planning/tasks/deciders/lane_change_decider", "//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_library( name = "lane_follow_scenario", srcs = ["lane_follow_scenario.cc"], hdrs = ["lane_follow_scenario.h"], copts = PLANNING_COPTS, deps = [ ":lane_follow_stage", "//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:speed_profile_generator", "//modules/planning/constraint_checker", "//modules/planning/math/curve1d:quartic_polynomial_curve1d", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/reference_line", "//modules/planning/reference_line:qp_spline_reference_line_smoother", "//modules/planning/scenarios:scenario", "//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 = "lane_follow_scenario_test", size = "small", srcs = ["lane_follow_scenario_test.cc"], data = [ "//modules/planning:planning_conf", ], linkopts = ["-lgomp"], deps = [ ":lane_follow", "@com_google_googletest//:gtest_main", ] + if_cuda([ "@local_config_cuda//cuda:cudart", ]) + if_rocm([ "@local_config_rocm//rocm:hip", ]), linkstatic = True, ) cpplint()
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/lane_follow/lane_follow_stage.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/scenarios/lane_follow/lane_follow_stage.h" #include <utility> #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/tasks/deciders/lane_change_decider/lane_change_decider.h" #include "modules/planning/tasks/deciders/path_decider/path_decider.h" #include "modules/planning/tasks/deciders/speed_decider/speed_decider.h" #include "modules/planning/tasks/optimizers/path_time_heuristic/path_time_heuristic_optimizer.h" namespace apollo { namespace planning { namespace scenario { namespace lane_follow { using apollo::common::ErrorCode; using apollo::common::SLPoint; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::util::PointFactory; using apollo::cyber::Clock; namespace { constexpr double kPathOptimizationFallbackCost = 2e4; constexpr double kSpeedOptimizationFallbackCost = 2e4; constexpr double kStraightForwardLineCost = 10.0; } // namespace LaneFollowStage::LaneFollowStage( const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Stage(config, injector) {} void LaneFollowStage::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]); } } } Stage::StageStatus LaneFollowStage::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { bool has_drivable_reference_line = false; ADEBUG << "Number of reference lines:\t" << frame->mutable_reference_line_info()->size(); unsigned int count = 0; for (auto& reference_line_info : *frame->mutable_reference_line_info()) { // TODO(SHU): need refactor if (count++ == frame->mutable_reference_line_info()->size()) { break; } ADEBUG << "No: [" << count << "] Reference Line."; ADEBUG << "IsChangeLanePath: " << reference_line_info.IsChangeLanePath(); if (has_drivable_reference_line) { reference_line_info.SetDrivable(false); break; } auto cur_status = PlanOnReferenceLine(planning_start_point, frame, &reference_line_info); if (cur_status.ok()) { if (reference_line_info.IsChangeLanePath()) { ADEBUG << "reference line is lane change ref."; ADEBUG << "FLAGS_enable_smarter_lane_change: " << FLAGS_enable_smarter_lane_change; if (reference_line_info.Cost() < kStraightForwardLineCost && (LaneChangeDecider::IsClearToChangeLane(&reference_line_info) || FLAGS_enable_smarter_lane_change)) { // If the path and speed optimization succeed on target lane while // under smart lane-change or IsClearToChangeLane under older version has_drivable_reference_line = true; reference_line_info.SetDrivable(true); LaneChangeDecider::UpdatePreparationDistance( true, frame, &reference_line_info, injector_->planning_context()); ADEBUG << "\tclear for lane change"; } else { LaneChangeDecider::UpdatePreparationDistance( false, frame, &reference_line_info, injector_->planning_context()); reference_line_info.SetDrivable(false); ADEBUG << "\tlane change failed"; } } else { ADEBUG << "reference line is NOT lane change ref."; has_drivable_reference_line = true; } } else { reference_line_info.SetDrivable(false); } } return has_drivable_reference_line ? StageStatus::RUNNING : StageStatus::ERROR; } Status LaneFollowStage::PlanOnReferenceLine( const TrajectoryPoint& planning_start_point, Frame* frame, ReferenceLineInfo* reference_line_info) { if (!reference_line_info->IsChangeLanePath()) { reference_line_info->AddCost(kStraightForwardLineCost); } ADEBUG << "planning start point:" << planning_start_point.DebugString(); ADEBUG << "Current reference_line_info is IsChangeLanePath: " << reference_line_info->IsChangeLanePath(); auto ret = Status::OK(); for (auto* task : task_list_) { const double start_timestamp = Clock::NowInSeconds(); ret = task->Execute(frame, reference_line_info); 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); if (!ret.ok()) { AERROR << "Failed to run tasks[" << task->Name() << "], Error message: " << ret.error_message(); break; } // TODO(SHU): disable reference line order changes for now // updated reference_line_info, because it is changed in // lane_change_decider by PrioritizeChangeLane(). // reference_line_info = &frame->mutable_reference_line_info()->front(); // ADEBUG << "Current reference_line_info is IsChangeLanePath: " // << reference_line_info->IsChangeLanePath(); } RecordObstacleDebugInfo(reference_line_info); // check path and speed results for path or speed fallback reference_line_info->set_trajectory_type(ADCTrajectory::NORMAL); if (!ret.ok()) { PlanFallbackTrajectory(planning_start_point, frame, reference_line_info); } DiscretizedTrajectory trajectory; if (!reference_line_info->CombinePathAndSpeedProfile( planning_start_point.relative_time(), planning_start_point.path_point().s(), &trajectory)) { const std::string msg = "Fail to aggregate planning trajectory."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // determine if there is a destination on reference line. double dest_stop_s = -1.0; for (const auto* obstacle : reference_line_info->path_decision()->obstacles().Items()) { if (obstacle->LongitudinalDecision().has_stop() && obstacle->LongitudinalDecision().stop().reason_code() == STOP_REASON_DESTINATION) { SLPoint dest_sl = GetStopSL(obstacle->LongitudinalDecision().stop(), reference_line_info->reference_line()); dest_stop_s = dest_sl.s(); } } for (const auto* obstacle : reference_line_info->path_decision()->obstacles().Items()) { if (obstacle->IsVirtual()) { continue; } if (!obstacle->IsStatic()) { continue; } if (obstacle->LongitudinalDecision().has_stop()) { bool add_stop_obstacle_cost = false; if (dest_stop_s < 0.0) { add_stop_obstacle_cost = true; } else { SLPoint stop_sl = GetStopSL(obstacle->LongitudinalDecision().stop(), reference_line_info->reference_line()); if (stop_sl.s() < dest_stop_s) { add_stop_obstacle_cost = true; } } if (add_stop_obstacle_cost) { static constexpr double kReferenceLineStaticObsCost = 1e3; reference_line_info->AddCost(kReferenceLineStaticObsCost); } } } 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 LaneFollowStage::PlanFallbackTrajectory( const TrajectoryPoint& planning_start_point, Frame* frame, ReferenceLineInfo* reference_line_info) { // path and speed fall back if (reference_line_info->path_data().Empty()) { AERROR << "Path fallback due to algorithm failure"; GenerateFallbackPathProfile(reference_line_info, reference_line_info->mutable_path_data()); reference_line_info->AddCost(kPathOptimizationFallbackCost); reference_line_info->set_trajectory_type(ADCTrajectory::PATH_FALLBACK); } if (reference_line_info->trajectory_type() != ADCTrajectory::PATH_FALLBACK) { if (!RetrieveLastFramePathProfile( reference_line_info, frame, reference_line_info->mutable_path_data())) { const auto& candidate_path_data = reference_line_info->GetCandidatePathData(); for (const auto& path_data : candidate_path_data) { if (path_data.path_label().find("self") != std::string::npos) { *reference_line_info->mutable_path_data() = path_data; AERROR << "Use current frame self lane path as fallback "; break; } } } } AERROR << "Speed fallback due to algorithm failure"; *reference_line_info->mutable_speed_data() = SpeedProfileGenerator::GenerateFallbackSpeed(injector_->ego_info()); if (reference_line_info->trajectory_type() != ADCTrajectory::PATH_FALLBACK) { reference_line_info->AddCost(kSpeedOptimizationFallbackCost); reference_line_info->set_trajectory_type(ADCTrajectory::SPEED_FALLBACK); } } void LaneFollowStage::GenerateFallbackPathProfile( const ReferenceLineInfo* reference_line_info, PathData* path_data) { const double unit_s = 1.0; const auto& reference_line = reference_line_info->reference_line(); auto adc_point = injector_->ego_info()->start_point(); DCHECK(adc_point.has_path_point()); const auto adc_point_x = adc_point.path_point().x(); const auto adc_point_y = adc_point.path_point().y(); common::SLPoint adc_point_s_l; if (!reference_line.XYToSL(adc_point.path_point(), &adc_point_s_l)) { AERROR << "Fail to project ADC to reference line when calculating path " "fallback. Straight forward path is generated"; const auto adc_point_heading = adc_point.path_point().theta(); const auto adc_point_kappa = adc_point.path_point().kappa(); const auto adc_point_dkappa = adc_point.path_point().dkappa(); std::vector<common::PathPoint> path_points; double adc_traversed_x = adc_point_x; double adc_traversed_y = adc_point_y; const double max_s = 100.0; for (double s = 0; s < max_s; s += unit_s) { path_points.push_back(PointFactory::ToPathPoint( adc_traversed_x, adc_traversed_y, 0.0, s, adc_point_heading, adc_point_kappa, adc_point_dkappa)); adc_traversed_x += unit_s * std::cos(adc_point_heading); adc_traversed_y += unit_s * std::sin(adc_point_heading); } path_data->SetDiscretizedPath(DiscretizedPath(std::move(path_points))); return; } // Generate a fallback path along the reference line direction const auto adc_s = adc_point_s_l.s(); const auto& adc_ref_point = reference_line.GetReferencePoint(adc_point_x, adc_point_y); const double dx = adc_point_x - adc_ref_point.x(); const double dy = adc_point_y - adc_ref_point.y(); std::vector<common::PathPoint> path_points; const double max_s = reference_line.Length(); for (double s = adc_s; s < max_s; s += unit_s) { const auto& ref_point = reference_line.GetReferencePoint(s); path_points.push_back(PointFactory::ToPathPoint( ref_point.x() + dx, ref_point.y() + dy, 0.0, s - adc_s, ref_point.heading(), ref_point.kappa(), ref_point.dkappa())); } path_data->SetDiscretizedPath(DiscretizedPath(std::move(path_points))); } bool LaneFollowStage::RetrieveLastFramePathProfile( const ReferenceLineInfo* reference_line_info, const Frame* frame, PathData* path_data) { const auto* ptr_last_frame = injector_->frame_history()->Latest(); if (ptr_last_frame == nullptr) { AERROR << "Last frame doesn't succeed, fail to retrieve last frame path data"; return false; } const auto& last_frame_discretized_path = ptr_last_frame->current_frame_planned_path(); path_data->SetDiscretizedPath(last_frame_discretized_path); const auto adc_frenet_frame_point_ = reference_line_info->reference_line().GetFrenetPoint( frame->PlanningStartPoint().path_point()); bool trim_success = path_data->LeftTrimWithRefS(adc_frenet_frame_point_); if (!trim_success) { AERROR << "Fail to trim path_data. adc_frenet_frame_point: " << adc_frenet_frame_point_.ShortDebugString(); return false; } AERROR << "Use last frame good path to do speed fallback"; return true; } SLPoint LaneFollowStage::GetStopSL(const ObjectStop& stop_decision, const ReferenceLine& reference_line) const { SLPoint sl_point; reference_line.XYToSL(stop_decision.stop_point(), &sl_point); return sl_point; } } // namespace lane_follow } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/util/util.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/scenarios/util/util.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/util/util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/pnc_map/path.h" #include "modules/planning/common/planning_context.h" namespace apollo { namespace planning { namespace scenario { namespace util { using apollo::common::math::Box2d; using apollo::common::math::Polygon2d; using apollo::common::math::Vec2d; hdmap::PathOverlap* GetOverlapOnReferenceLine( const ReferenceLineInfo& reference_line_info, const std::string& overlap_id, const ReferenceLineInfo::OverlapType& overlap_type) { if (overlap_type == ReferenceLineInfo::SIGNAL) { // traffic_light_overlap const auto& traffic_light_overlaps = reference_line_info.reference_line().map_path().signal_overlaps(); for (const auto& traffic_light_overlap : traffic_light_overlaps) { if (traffic_light_overlap.object_id == overlap_id) { return const_cast<hdmap::PathOverlap*>(&traffic_light_overlap); } } } else if (overlap_type == ReferenceLineInfo::STOP_SIGN) { // stop_sign_overlap const auto& stop_sign_overlaps = reference_line_info.reference_line().map_path().stop_sign_overlaps(); for (const auto& stop_sign_overlap : stop_sign_overlaps) { if (stop_sign_overlap.object_id == overlap_id) { return const_cast<hdmap::PathOverlap*>(&stop_sign_overlap); } } } else if (overlap_type == ReferenceLineInfo::PNC_JUNCTION) { // pnc_junction_overlap const auto& pnc_junction_overlaps = reference_line_info.reference_line().map_path().pnc_junction_overlaps(); for (const auto& pnc_junction_overlap : pnc_junction_overlaps) { if (pnc_junction_overlap.object_id == overlap_id) { return const_cast<hdmap::PathOverlap*>(&pnc_junction_overlap); } } } else if (overlap_type == ReferenceLineInfo::YIELD_SIGN) { // yield_sign_overlap const auto& yield_sign_overlaps = reference_line_info.reference_line().map_path().yield_sign_overlaps(); for (const auto& yield_sign_overlap : yield_sign_overlaps) { if (yield_sign_overlap.object_id == overlap_id) { return const_cast<hdmap::PathOverlap*>(&yield_sign_overlap); } } } return nullptr; } /** * @brief: check adc parked properly */ PullOverStatus CheckADCPullOver( const common::VehicleStateProvider* vehicle_state_provider, const ReferenceLineInfo& reference_line_info, const ScenarioPullOverConfig& scenario_config, const PlanningContext* planning_context) { const auto& pull_over_status = 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()) { ADEBUG << "pull_over status not set properly: " << pull_over_status.DebugString(); return UNKNOWN; } const auto& reference_line = reference_line_info.reference_line(); common::SLPoint pull_over_sl; reference_line.XYToSL(pull_over_status.position(), &pull_over_sl); const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); double distance = adc_front_edge_s - pull_over_sl.s(); if (distance >= scenario_config.pass_destination_threshold()) { ADEBUG << "ADC passed pull-over spot: distance[" << distance << "]"; return PASS_DESTINATION; } const double adc_speed = vehicle_state_provider->linear_velocity(); const double max_adc_stop_speed = common::VehicleConfigHelper::Instance() ->GetConfig() .vehicle_param() .max_abs_speed_when_stopped(); if (adc_speed > max_adc_stop_speed) { ADEBUG << "ADC not stopped: speed[" << adc_speed << "]"; return APPROACHING; } static constexpr double kStartParkCheckRange = 3.0; // meter if (distance <= -kStartParkCheckRange) { ADEBUG << "ADC still far: distance[" << distance << "]"; return APPROACHING; } const common::math::Vec2d adc_position = {vehicle_state_provider->x(), vehicle_state_provider->y()}; const common::math::Vec2d target_position = {pull_over_status.position().x(), pull_over_status.position().y()}; const bool position_check = CheckPullOverPositionBySL( reference_line_info, scenario_config, adc_position, vehicle_state_provider->heading(), target_position, pull_over_status.theta(), true); return position_check ? PARK_COMPLETE : PARK_FAIL; } /** * @brief: check path data to see properly */ PullOverStatus CheckADCPullOverPathPoint( const ReferenceLineInfo& reference_line_info, const ScenarioPullOverConfig& scenario_config, const common::PathPoint& path_point, const PlanningContext* planning_context) { const auto& pull_over_status = 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()) { ADEBUG << "pull_over status not set properly: " << pull_over_status.DebugString(); return UNKNOWN; } const common::math::Vec2d target_position = {pull_over_status.position().x(), pull_over_status.position().y()}; const bool position_check = CheckPullOverPositionBySL( reference_line_info, scenario_config, {path_point.x(), path_point.y()}, path_point.theta(), target_position, pull_over_status.theta(), false); // check l + theta only return position_check ? PARK_COMPLETE : PARK_FAIL; } bool CheckPullOverPositionBySL(const ReferenceLineInfo& reference_line_info, const ScenarioPullOverConfig& scenario_config, const common::math::Vec2d& adc_position, const double adc_theta, const common::math::Vec2d& target_position, const double target_theta, const bool check_s) { const auto& reference_line = reference_line_info.reference_line(); common::SLPoint target_sl; reference_line.XYToSL(target_position, &target_sl); common::SLPoint adc_position_sl; reference_line.XYToSL(adc_position, &adc_position_sl); const double s_diff = target_sl.s() - adc_position_sl.s(); const double l_diff = std::fabs(target_sl.l() - adc_position_sl.l()); const double theta_diff = std::fabs(common::math::NormalizeAngle(target_theta - adc_theta)); ADEBUG << "adc_position_s[" << adc_position_sl.s() << "] adc_position_l[" << adc_position_sl.l() << "] target_s[" << target_sl.s() << "] target_l[" << target_sl.l() << "] s_diff[" << s_diff << "] l_diff[" << l_diff << "] theta_diff[" << theta_diff << "]"; // check s/l/theta diff bool ret = (l_diff <= scenario_config.max_l_error_to_end_point() && theta_diff <= scenario_config.max_theta_error_to_end_point()); if (check_s) { ret = (ret && s_diff >= 0 && s_diff <= scenario_config.max_s_error_to_end_point()); } return ret; } bool CheckADCReadyToCruise( const common::VehicleStateProvider* vehicle_state_provider, Frame* frame, const ScenarioParkAndGoConfig& scenario_config) { auto vehicle_status = vehicle_state_provider; common::math::Vec2d adc_position = {vehicle_status->x(), vehicle_status->y()}; const double adc_heading = vehicle_status->heading(); common::SLPoint adc_position_sl; // get nearest reference line const auto& reference_line_list = frame->reference_line_info(); 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()); }); reference_line_info->reference_line().XYToSL(adc_position, &adc_position_sl); bool is_near_front_obstacle = CheckADCSurroundObstacles(adc_position, adc_heading, frame, scenario_config.front_obstacle_buffer()); bool heading_align_w_reference_line = CheckADCHeading(adc_position, adc_heading, *reference_line_info, scenario_config.heading_buffer()); ADEBUG << "is_near_front_obstacle: " << is_near_front_obstacle; ADEBUG << "heading_align_w_reference_line: " << heading_align_w_reference_line; // check gear status // TODO(SHU): align with vehicle parameters static constexpr double kMinSpeed = 0.1; // m/s return ((vehicle_status->gear() == canbus::Chassis::GEAR_DRIVE || std::fabs(vehicle_status->vehicle_state().linear_velocity()) < kMinSpeed) && !is_near_front_obstacle && heading_align_w_reference_line && std::fabs(adc_position_sl.l()) < 0.5); } /** * @brief: front obstacle is far enough before PardAndGo cruise stage *(adc_position: center of rear wheel) */ bool CheckADCSurroundObstacles(const common::math::Vec2d adc_position, const double adc_heading, Frame* frame, const double front_obstacle_buffer) { const auto& vehicle_config = common::VehicleConfigHelper::Instance()->GetConfig(); const double adc_length = vehicle_config.vehicle_param().length(); const double adc_width = vehicle_config.vehicle_param().width(); // ADC box Box2d adc_box(adc_position, adc_heading, adc_length + front_obstacle_buffer, adc_width); double shift_distance = front_obstacle_buffer / 2 + vehicle_config.vehicle_param().back_edge_to_center(); Vec2d shift_vec{shift_distance * std::cos(adc_heading), shift_distance * std::sin(adc_heading)}; adc_box.Shift(shift_vec); const auto& adc_polygon = Polygon2d(adc_box); // obstacle boxes auto obstacles = frame->obstacles(); for (const auto& obstacle : obstacles) { if (obstacle->IsVirtual()) { continue; } const auto& obstacle_polygon = obstacle->PerceptionPolygon(); const Polygon2d& nudge_polygon = obstacle_polygon.ExpandByDistance( std::fabs(FLAGS_static_obstacle_nudge_l_buffer)); if (adc_polygon.HasOverlap(nudge_polygon)) { ADEBUG << "blocked obstacle: " << obstacle->Id(); return true; } } return false; } /** * @brief Park_and_go: heading angle should be close to reference line before * PardAndGo cruise stage */ bool CheckADCHeading(const common::math::Vec2d adc_position, const double adc_heading, const ReferenceLineInfo& reference_line_info, const double heading_diff_to_reference_line) { const double kReducedHeadingBuffer = 0.2; // (rad) TODO(Shu) move to config const auto& reference_line = reference_line_info.reference_line(); common::SLPoint adc_position_sl; reference_line.XYToSL(adc_position, &adc_position_sl); // reference line heading angle at s const auto reference_point = reference_line.GetReferencePoint(adc_position_sl.s()); const auto path_point = reference_point.ToPathPoint(adc_position_sl.s()); AINFO << "heading difference: " << common::math::NormalizeAngle(adc_heading - path_point.theta()); double angle_difference = common::math::NormalizeAngle(adc_heading - path_point.theta()); if (angle_difference > -1.0 * (heading_diff_to_reference_line - kReducedHeadingBuffer) && angle_difference < heading_diff_to_reference_line) { return true; } return false; } } // namespace util } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/util/util.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. *****************************************************************************/ #pragma once #include <string> #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/reference_line_info.h" namespace apollo { namespace planning { namespace scenario { namespace util { enum PullOverStatus { UNKNOWN = 0, APPROACHING = 1, PARK_COMPLETE = 2, PARK_FAIL = 3, PASS_DESTINATION = 4, }; hdmap::PathOverlap* GetOverlapOnReferenceLine( const ReferenceLineInfo& reference_line_info, const std::string& overlap_id, const ReferenceLineInfo::OverlapType& overlap_type); PullOverStatus CheckADCPullOver( const common::VehicleStateProvider* vehicle_state_provider, const ReferenceLineInfo& reference_line_info, const ScenarioPullOverConfig& scenario_config, const PlanningContext* planning_context); PullOverStatus CheckADCPullOverPathPoint( const ReferenceLineInfo& reference_line_info, const ScenarioPullOverConfig& scenario_config, const common::PathPoint& path_point, const PlanningContext* planning_context); bool CheckPullOverPositionBySL(const ReferenceLineInfo& reference_line_info, const ScenarioPullOverConfig& scenario_config, const common::math::Vec2d& adc_position, const double adc_theta, const common::math::Vec2d& target_position, const double target_theta, const bool check_s); bool CheckADCReadyToCruise( const common::VehicleStateProvider* vehicle_state_provider, Frame* frame, const ScenarioParkAndGoConfig& scenario_config); bool CheckADCSurroundObstacles(const common::math::Vec2d adc_position, const double adc_heading, Frame* frame, const double front_obstacle_buffer); bool CheckADCHeading(const common::math::Vec2d adc_position, const double adc_heading, const ReferenceLineInfo& reference_line_info, const double heading_buffer); } // namespace util } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/util/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "scenario_util_lib", srcs = ["util.cc"], hdrs = ["util.h"], copts = [ "-DMODULE_NAME=\\\"planning\\\"", ], deps = [ "//cyber", "//modules/common/util:util_tool", "//modules/planning/common:planning_common", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/learning_model/learning_model_sample_scenario_test.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 **/ #include "modules/planning/scenarios/learning_model/learning_model_sample_scenario.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "gtest/gtest.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace scenario { class LearningModelSampleScenarioTest : public ::testing::Test { public: virtual void SetUp() {} protected: std::unique_ptr<LearningModelSampleScenario> scenario_; }; TEST_F(LearningModelSampleScenarioTest, Init) { FLAGS_scenario_learning_model_sample_config_file = "/apollo/modules/planning/conf/scenario/" "learning_model_sample_config.pb.txt"; ScenarioConfig config; EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile( FLAGS_scenario_learning_model_sample_config_file, &config)); ScenarioContext context; auto injector = std::make_shared<DependencyInjector>(); scenario_.reset(new LearningModelSampleScenario(config, &context, injector)); EXPECT_EQ(scenario_->scenario_type(), ScenarioType::LEARNING_MODEL_SAMPLE); } } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/learning_model/learning_model_sample_scenario.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 **/ #include "modules/planning/scenarios/learning_model/learning_model_sample_scenario.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "modules/planning/scenarios/learning_model/stage_run.h" namespace apollo { namespace planning { namespace scenario { apollo::common::util::Factory< StageType, Stage, Stage* (*)(const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector)> LearningModelSampleScenario::s_stage_factory_; void LearningModelSampleScenario::Init() { if (init_) { return; } Scenario::Init(); if (!GetScenarioConfig()) { AERROR << "fail to get scenario specific config"; return; } init_ = true; } void LearningModelSampleScenario::RegisterStages() { if (!s_stage_factory_.Empty()) { s_stage_factory_.Clear(); } s_stage_factory_.Register( StageType::LEARNING_MODEL_RUN, [](const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) -> Stage* { return new LearningModelSampleStageRun(config, injector); }); } std::unique_ptr<Stage> LearningModelSampleScenario::CreateStage( const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector) { if (s_stage_factory_.Empty()) { RegisterStages(); } auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(), stage_config, injector); if (ptr) { ptr->SetContext(&context_); } return ptr; } /* * read scenario specific configs and set in context_ for stages to read */ bool LearningModelSampleScenario::GetScenarioConfig() { if (!config_.has_learning_model_sample_config()) { AERROR << "miss scenario specific config"; return false; } context_.scenario_config.CopyFrom(config_.learning_model_sample_config()); return true; } } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/learning_model/stage_run.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 **/ #include "modules/planning/scenarios/learning_model/stage_run.h" #include "cyber/common/log.h" #include "modules/planning/common/frame.h" namespace apollo { namespace planning { namespace scenario { using apollo::common::TrajectoryPoint; Stage::StageStatus LearningModelSampleStageRun::Process( const TrajectoryPoint& planning_init_point, Frame* frame) { ADEBUG << "stage: Run"; CHECK_NOTNULL(frame); scenario_config_.CopyFrom(GetContext()->scenario_config); bool plan_ok = ExecuteTaskOnReferenceLineForOnlineLearning(planning_init_point, frame); if (!plan_ok) { AERROR << "LearningModelSampleStageRun planning error"; return Stage::RUNNING; } return FinishStage(); } Stage::StageStatus LearningModelSampleStageRun::FinishStage() { return FinishScenario(); } } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/learning_model/stage_run.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 **/ #pragma once #include <memory> #include "modules/planning/scenarios/learning_model/learning_model_sample_scenario.h" #include "modules/planning/scenarios/stage.h" namespace apollo { namespace planning { namespace scenario { struct LearningModelSampleContext; class LearningModelSampleStageRun : public Stage { public: LearningModelSampleStageRun( const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Stage(config, injector) {} private: Stage::StageStatus Process(const common::TrajectoryPoint& planning_init_point, Frame* frame) override; LearningModelSampleContext* GetContext() { return GetContextAs<LearningModelSampleContext>(); } Stage::StageStatus FinishStage(); private: ScenarioLearningModelSampleConfig scenario_config_; }; } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/learning_model/stage_run_test.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. *****************************************************************************/ #include "modules/planning/scenarios/learning_model/stage_run.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "gtest/gtest.h" namespace apollo { namespace planning { namespace scenario { class StageRunTest : public ::testing::Test { public: virtual void SetUp() { config_.set_stage_type(StageType::LEARNING_MODEL_RUN); injector_ = std::make_shared<DependencyInjector>(); } protected: ScenarioConfig::StageConfig config_; std::shared_ptr<DependencyInjector> injector_; }; TEST_F(StageRunTest, Init) { LearningModelSampleStageRun learning_model_stage_run(config_, injector_); EXPECT_EQ(learning_model_stage_run.Name(), StageType_Name(StageType::LEARNING_MODEL_RUN)); } } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/learning_model/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 = "learning_model", copts = PLANNING_COPTS, deps = [ ":learning_model_sample_scenario", ], ) cc_library( name = "learning_model_sample_scenario", srcs = [ "learning_model_sample_scenario.cc", "stage_run.cc", ], hdrs = [ "learning_model_sample_scenario.h", "stage_run.h", ], copts = PLANNING_COPTS, deps = [ "//cyber", "//modules/common/util:util_tool", "//modules/planning/scenarios:scenario", "@eigen", "//third_party:libtorch", ], ) cc_test( name = "learning_model_sample_scenario_test", size = "small", srcs = ["learning_model_sample_scenario_test.cc"], data = [ "//modules/planning:planning_conf", ], linkopts = ["-lgomp"], deps = [ ":learning_model_sample_scenario", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_test( name = "stage_run_test", size = "small", srcs = ["stage_run_test.cc"], data = [ "//modules/planning:planning_conf", ], linkopts = ["-lgomp"], deps = [ ":learning_model_sample_scenario", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cpplint()
0
apollo_public_repos/apollo/modules/planning/scenarios
apollo_public_repos/apollo/modules/planning/scenarios/learning_model/learning_model_sample_scenario.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 **/ #pragma once #include <memory> #include "modules/common/util/factory.h" #include "modules/planning/scenarios/scenario.h" namespace apollo { namespace planning { namespace scenario { // stage context struct LearningModelSampleContext { ScenarioLearningModelSampleConfig scenario_config; }; class LearningModelSampleScenario : public Scenario { public: LearningModelSampleScenario( const ScenarioConfig& config, const ScenarioContext* context, const std::shared_ptr<DependencyInjector>& injector) : Scenario(config, context, injector) {} void Init() override; std::unique_ptr<Stage> CreateStage( const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector) override; private: static void RegisterStages(); bool GetScenarioConfig(); private: static apollo::common::util::Factory< StageType, Stage, Stage* (*)(const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector)> s_stage_factory_; bool init_ = false; LearningModelSampleContext context_; }; } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios/park
apollo_public_repos/apollo/modules/planning/scenarios/park/pull_over/pull_over_scenario_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/scenarios/park/pull_over/pull_over_scenario.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "gtest/gtest.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace scenario { namespace pull_over { class PullOverScenarioTest : public ::testing::Test { public: virtual void SetUp() {} protected: std::unique_ptr<PullOverScenario> scenario_; }; TEST_F(PullOverScenarioTest, Init) { FLAGS_scenario_pull_over_config_file = "/apollo/modules/planning/conf/scenario/pull_over_config.pb.txt"; ScenarioConfig config; EXPECT_TRUE(apollo::cyber::common::GetProtoFromFile( FLAGS_scenario_pull_over_config_file, &config)); ScenarioContext context; auto injector = std::make_shared<DependencyInjector>(); scenario_.reset(new PullOverScenario(config, &context, injector)); EXPECT_EQ(scenario_->scenario_type(), ScenarioType::PULL_OVER); } } // namespace pull_over } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios/park
apollo_public_repos/apollo/modules/planning/scenarios/park/pull_over/stage_approach.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/proto/planning_config.pb.h" #include "modules/planning/scenarios/park/pull_over/pull_over_scenario.h" #include "modules/planning/scenarios/stage.h" namespace apollo { namespace planning { namespace scenario { namespace pull_over { struct PullOverContext; class PullOverStageApproach : public Stage { public: PullOverStageApproach(const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector); StageStatus Process(const common::TrajectoryPoint& planning_init_point, Frame* frame) override; PullOverContext* GetContext() { return Stage::GetContextAs<PullOverContext>(); } Stage::StageStatus FinishStage(const bool success); private: ScenarioPullOverConfig scenario_config_; }; } // namespace pull_over } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios/park
apollo_public_repos/apollo/modules/planning/scenarios/park/pull_over/stage_approach_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/scenarios/park/pull_over/stage_approach.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "gtest/gtest.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace scenario { namespace pull_over { class StageApproachTest : public ::testing::Test { public: virtual void SetUp() { config_.set_stage_type(StageType::PULL_OVER_APPROACH); injector_ = std::make_shared<DependencyInjector>(); } protected: ScenarioConfig::StageConfig config_; std::shared_ptr<DependencyInjector> injector_; }; TEST_F(StageApproachTest, Init) { PullOverStageApproach pull_over_stage_approach(config_, injector_); EXPECT_EQ(pull_over_stage_approach.Name(), StageType_Name(StageType::PULL_OVER_APPROACH)); } } // namespace pull_over } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios/park
apollo_public_repos/apollo/modules/planning/scenarios/park/pull_over/stage_retry_parking_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/scenarios/park/pull_over/stage_retry_parking.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "gtest/gtest.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace scenario { namespace pull_over { class PullOverStageRetryParkingTest : public ::testing::Test { public: virtual void SetUp() { config_.set_stage_type(StageType::PULL_OVER_RETRY_PARKING); injector_ = std::make_shared<DependencyInjector>(); } protected: ScenarioConfig::StageConfig config_; std::shared_ptr<DependencyInjector> injector_; }; TEST_F(PullOverStageRetryParkingTest, Init) { PullOverStageRetryParking pull_over_stage_retry_parking(config_, injector_); EXPECT_EQ( pull_over_stage_retry_parking.Name(), StageType_Name(StageType::PULL_OVER_RETRY_PARKING)); } } // namespace pull_over } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios/park
apollo_public_repos/apollo/modules/planning/scenarios/park/pull_over/stage_approach.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/scenarios/park/pull_over/stage_approach.h" #include <memory> #include <string> #include <vector> #include "cyber/common/log.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/util/common.h" #include "modules/planning/scenarios/util/util.h" #include "modules/planning/tasks/deciders/path_bounds_decider/path_bounds_decider.h" namespace apollo { namespace planning { namespace scenario { namespace pull_over { using apollo::common::TrajectoryPoint; PullOverStageApproach::PullOverStageApproach( const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Stage(config, injector) {} Stage::StageStatus PullOverStageApproach::Process( const TrajectoryPoint& planning_init_point, Frame* frame) { ADEBUG << "stage: Approach"; CHECK_NOTNULL(frame); scenario_config_.CopyFrom(GetContext()->scenario_config); bool plan_ok = ExecuteTaskOnReferenceLine(planning_init_point, frame); if (!plan_ok) { AERROR << "PullOverStageApproach planning error"; } const auto& reference_line_info = frame->reference_line_info().front(); scenario::util::PullOverStatus status = scenario::util::CheckADCPullOver( injector_->vehicle_state(), reference_line_info, scenario_config_, injector_->planning_context()); if (status == scenario::util::PASS_DESTINATION || status == scenario::util::PARK_COMPLETE) { return FinishStage(true); } else if (status == scenario::util::PARK_FAIL) { return FinishStage(false); } // check path_data to fail sooner bool path_fail = false; const auto& candidate_path_data = reference_line_info.GetCandidatePathData(); if (!candidate_path_data.empty()) { for (const auto& path_data : candidate_path_data) { if (path_data.path_label().find("pullover") == std::string::npos) { break; } for (size_t i = path_data.discretized_path().size(); i >= 1; --i) { if (path_data.frenet_frame_path().back().s() - path_data.frenet_frame_path()[i - 1].s() < kNumExtraTailBoundPoint * kPathBoundsDeciderResolution) { continue; } // check the last adc_position planned const auto& path_point = path_data.discretized_path()[i]; scenario::util::PullOverStatus status = scenario::util::CheckADCPullOverPathPoint( reference_line_info, scenario_config_, path_point, injector_->planning_context()); if (status == scenario::util::PARK_FAIL) { path_fail = true; } break; } } } // add a stop fence for adc to pause at a better position if (path_fail) { 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()) { const auto& reference_line = reference_line_info.reference_line(); common::SLPoint pull_over_sl; reference_line.XYToSL(pull_over_status.position(), &pull_over_sl); const double stop_line_s = pull_over_sl.s() - scenario_config_.s_distance_to_stop_for_open_space_parking(); const std::string virtual_obstacle_id = "DEST_PULL_OVER_PREPARKING"; const std::vector<std::string> wait_for_obstacle_ids; planning::util::BuildStopDecision( virtual_obstacle_id, stop_line_s, 1.0, StopReasonCode::STOP_REASON_PREPARKING, wait_for_obstacle_ids, "PULL-OVER-scenario", frame, &(frame->mutable_reference_line_info()->front())); ADEBUG << "Build a stop fence to pause ADC at a better position: id[" << virtual_obstacle_id << "] s[" << stop_line_s << "]"; const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); double distance = stop_line_s - adc_front_edge_s; static constexpr double kPreparkingStopDistance = 1.0; static constexpr double kPreparkingAngleDiff = 0.2; auto ref_point = reference_line.GetReferencePoint(adc_front_edge_s); double angle = common::math::AngleDiff(pull_over_status.theta(), ref_point.heading()); if (distance <= kPreparkingStopDistance && angle <= kPreparkingAngleDiff) { return FinishStage(false); } } } return StageStatus::RUNNING; } Stage::StageStatus PullOverStageApproach::FinishStage(const bool success) { if (success) { return FinishScenario(); } else { next_stage_ = StageType::PULL_OVER_RETRY_APPROACH_PARKING; return Stage::FINISHED; } } } // namespace pull_over } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios/park
apollo_public_repos/apollo/modules/planning/scenarios/park/pull_over/stage_retry_approach_parking.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/scenarios/park/pull_over/pull_over_scenario.h" #include "modules/planning/scenarios/stage.h" namespace apollo { namespace planning { namespace scenario { namespace pull_over { struct PullOverContext; class PullOverStageRetryApproachParking : public Stage { public: PullOverStageRetryApproachParking( const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector); StageStatus Process(const common::TrajectoryPoint& planning_init_point, Frame* frame) override; PullOverContext* GetContext() { return Stage::GetContextAs<PullOverContext>(); } Stage::StageStatus FinishStage(); bool CheckADCStop(const Frame& frame); private: ScenarioPullOverConfig scenario_config_; }; } // namespace pull_over } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios/park
apollo_public_repos/apollo/modules/planning/scenarios/park/pull_over/stage_retry_parking.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/scenarios/park/pull_over/stage_retry_parking.h" #include <memory> #include "cyber/common/log.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/scenarios/util/util.h" namespace apollo { namespace planning { namespace scenario { namespace pull_over { using apollo::common::TrajectoryPoint; PullOverStageRetryParking::PullOverStageRetryParking( const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Stage(config, injector) {} Stage::StageStatus PullOverStageRetryParking::Process( const TrajectoryPoint& planning_init_point, Frame* frame) { ADEBUG << "stage: RetryParking"; CHECK_NOTNULL(frame); scenario_config_.CopyFrom(GetContext()->scenario_config); // Open space planning doesn't use planning_init_point from upstream because // of different stitching strategy frame->mutable_open_space_info()->set_is_on_open_space_trajectory(true); bool plan_ok = ExecuteTaskOnOpenSpace(frame); if (!plan_ok) { AERROR << "PullOverStageRetryParking planning error"; return StageStatus::ERROR; } // set debug info in planning_data const auto& pull_over_status = injector_->planning_context()->planning_status().pull_over(); auto* pull_over_debug = frame->mutable_open_space_info() ->mutable_debug() ->mutable_planning_data() ->mutable_pull_over(); pull_over_debug->mutable_position()->CopyFrom(pull_over_status.position()); pull_over_debug->set_theta(pull_over_status.theta()); pull_over_debug->set_length_front(pull_over_status.length_front()); pull_over_debug->set_length_back(pull_over_status.length_back()); pull_over_debug->set_width_left(pull_over_status.width_left()); pull_over_debug->set_width_right(pull_over_status.width_right()); frame->mutable_open_space_info()->sync_debug_instance(); if (CheckADCPullOverOpenSpace()) { return FinishStage(); } return StageStatus::RUNNING; } Stage::StageStatus PullOverStageRetryParking::FinishStage() { return FinishScenario(); } bool PullOverStageRetryParking::CheckADCPullOverOpenSpace() { 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()) { ADEBUG << "pull_over status not set properly: " << pull_over_status.DebugString(); return false; } const common::math::Vec2d adc_position = {injector_->vehicle_state()->x(), injector_->vehicle_state()->y()}; const common::math::Vec2d target_position = {pull_over_status.position().x(), pull_over_status.position().y()}; const double distance_diff = adc_position.DistanceTo(target_position); const double theta_diff = std::fabs(common::math::NormalizeAngle( pull_over_status.theta() - injector_->vehicle_state()->heading())); ADEBUG << "distance_diff[" << distance_diff << "] theta_diff[" << theta_diff << "]"; // check distance/theta diff return (distance_diff <= scenario_config_.max_distance_error_to_end_point() && theta_diff <= scenario_config_.max_theta_error_to_end_point()); } } // namespace pull_over } // namespace scenario } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/scenarios/park
apollo_public_repos/apollo/modules/planning/scenarios/park/pull_over/pull_over_scenario.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/scenarios/park/pull_over/pull_over_scenario.h" #include "cyber/common/log.h" #include "modules/planning/scenarios/park/pull_over/stage_approach.h" #include "modules/planning/scenarios/park/pull_over/stage_retry_approach_parking.h" #include "modules/planning/scenarios/park/pull_over/stage_retry_parking.h" namespace apollo { namespace planning { namespace scenario { namespace pull_over { apollo::common::util::Factory< StageType, Stage, Stage* (*)(const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector)> PullOverScenario::s_stage_factory_; void PullOverScenario::Init() { if (init_) { return; } Scenario::Init(); if (!GetScenarioConfig()) { AERROR << "fail to get scenario specific config"; return; } init_ = true; } void PullOverScenario::RegisterStages() { if (!s_stage_factory_.Empty()) { s_stage_factory_.Clear(); } s_stage_factory_.Register( StageType::PULL_OVER_APPROACH, [](const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) -> Stage* { return new PullOverStageApproach(config, injector); }); s_stage_factory_.Register( StageType::PULL_OVER_RETRY_APPROACH_PARKING, [](const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) -> Stage* { return new PullOverStageRetryApproachParking(config, injector); }); s_stage_factory_.Register( StageType::PULL_OVER_RETRY_PARKING, [](const ScenarioConfig::StageConfig& config, const std::shared_ptr<DependencyInjector>& injector) -> Stage* { return new PullOverStageRetryParking(config, injector); }); } std::unique_ptr<Stage> PullOverScenario::CreateStage( const ScenarioConfig::StageConfig& stage_config, const std::shared_ptr<DependencyInjector>& injector) { if (s_stage_factory_.Empty()) { RegisterStages(); } auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(), stage_config, injector); if (ptr) { ptr->SetContext(&context_); } return ptr; } /* * read scenario specific configs and set in context_ for stages to read */ bool PullOverScenario::GetScenarioConfig() { if (!config_.has_pull_over_config()) { AERROR << "miss scenario specific config"; return false; } context_.scenario_config.CopyFrom(config_.pull_over_config()); return true; } } // namespace pull_over } // namespace scenario } // namespace planning } // namespace apollo
0