repo_id
stringlengths
19
138
file_path
stringlengths
32
200
content
stringlengths
1
12.9M
__index_level_0__
int64
0
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/learning_model/learning_model_inference_trajectory_task_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/tasks/learning_model/learning_model_inference_trajectory_task.h" #include "gtest/gtest.h" #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { class LearningModelInferenceTrajectoryTaskTest : public ::testing::Test { public: virtual void SetUp() { config_.set_task_type(TaskConfig::LEARNING_MODEL_INFERENCE_TRAJECTORY_TASK); config_.mutable_learning_model_inference_trajectory_task_config(); injector_ = std::make_shared<DependencyInjector>(); } virtual void TearDown() {} protected: TaskConfig config_; std::shared_ptr<DependencyInjector> injector_; }; TEST_F(LearningModelInferenceTrajectoryTaskTest, Init) { LearningModelInferenceTrajectoryTask learning_model_inference_trajectory_task( config_, injector_); EXPECT_EQ(learning_model_inference_trajectory_task.Name(), TaskConfig::TaskType_Name(config_.task_type())); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/learning_model/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "learning_model_inference_task", srcs = ["learning_model_inference_task.cc"], hdrs = ["learning_model_inference_task.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/common/status", "//modules/planning/common:frame", "//modules/planning/common:reference_line_info", "//modules/planning/common:trajectory_evaluator", "//modules/planning/learning_based/img_feature_renderer:birdview_img_feature_renderer", "//modules/planning/learning_based/model_inference:trajectory_imitation_libtorch_inference", "//modules/planning/proto:learning_data_cc_proto", "//modules/planning/proto:planning_config_cc_proto", "//modules/planning/tasks:task", ], ) cc_library( name = "learning_model_inference_trajectory_task", srcs = ["learning_model_inference_trajectory_task.cc"], hdrs = ["learning_model_inference_trajectory_task.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/common/status", "//modules/planning/common:frame", "//modules/planning/common:reference_line_info", "//modules/planning/proto:planning_config_cc_proto", "//modules/planning/tasks:task", ], ) cc_test( name = "learning_model_inference_task_test", size = "small", srcs = ["learning_model_inference_task_test.cc"], deps = [ "learning_model_inference_task", "@com_google_googletest//:gtest_main", ], linkstatic = True, ) cc_test( name = "learning_model_inference_trajectory_task_test", size = "small", srcs = ["learning_model_inference_trajectory_task_test.cc"], deps = [ "learning_model_inference_trajectory_task", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/learning_model/learning_model_inference_task.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/tasks/learning_model/learning_model_inference_task.h" #include <cmath> #include <limits> #include <string> #include "absl/strings/str_cat.h" #include "modules/planning/learning_based/model_inference/trajectory_imitation_libtorch_inference.h" #include "modules/planning/proto/learning_data.pb.h" #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; LearningModelInferenceTask::LearningModelInferenceTask( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Task(config, injector) { ACHECK(config.has_learning_model_inference_task_config()); trajectory_imitation_inference_ = std::make_unique<TrajectoryImitationLibtorchInference>( config.learning_model_inference_task_config()); } Status LearningModelInferenceTask::Execute( Frame* frame, ReferenceLineInfo* reference_line_info) { CHECK_NOTNULL(frame); Task::Execute(frame, reference_line_info); return Process(frame); } Status LearningModelInferenceTask::Process(Frame* frame) { CHECK_NOTNULL(frame); const auto& config = config_.learning_model_inference_task_config(); if (!injector_->learning_based_data() || !injector_->learning_based_data()->GetLatestLearningDataFrame()) { const std::string msg = "learning_data_frame empty"; AERROR << msg; // hybrid model will use rule based planning when learning based data or // learning data frame is empty if (config.allow_empty_learning_based_data()) { return Status::OK(); } return Status(ErrorCode::PLANNING_ERROR, msg); } LearningDataFrame learning_data_frame; learning_data_frame.CopyFrom( *(injector_->learning_based_data()->GetLatestLearningDataFrame())); ADEBUG << "LearningModelInferenceTask: frame_num[" << learning_data_frame.frame_num() << "] adc_trajectory_point_size[" << learning_data_frame.adc_trajectory_point_size() << "]"; if (learning_data_frame.adc_trajectory_point_size() <= 0) { const std::string msg = absl::StrCat("learning_data adc_trajectory_point empty. frame_num[", learning_data_frame.frame_num(), "]"); AERROR << msg; // hybrid model will use rule based planning when learning model output is // not ready if (config.allow_empty_output_trajectory()) { return Status::OK(); } return Status(ErrorCode::PLANNING_ERROR, msg); } const double start_point_timestamp_sec = learning_data_frame .adc_trajectory_point( learning_data_frame.adc_trajectory_point_size() - 1) .timestamp_sec(); ADEBUG << "start_point_timestamp_sec: " << start_point_timestamp_sec; TrajectoryEvaluator trajectory_evaluator; // evaluate adc trajectory trajectory_evaluator.EvaluateADCTrajectory(start_point_timestamp_sec, config.trajectory_delta_t(), &learning_data_frame); // evaluate obstacle trajectory trajectory_evaluator.EvaluateObstacleTrajectory(start_point_timestamp_sec, config.trajectory_delta_t(), &learning_data_frame); // evaluate obstacle prediction trajectory trajectory_evaluator.EvaluateObstaclePredictionTrajectory( start_point_timestamp_sec, config.trajectory_delta_t(), &learning_data_frame); if (!trajectory_imitation_inference_->LoadModel()) { const std::string msg = absl::StrCat( "TrajectoryImitationInference LoadModel() failed. frame_num[", learning_data_frame.frame_num(), "]"); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (!trajectory_imitation_inference_->DoInference(&learning_data_frame)) { const std::string msg = absl::StrCat( "TrajectoryImitationLibtorchInference Inference failed. frame_num[", learning_data_frame.frame_num(), "]"); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } const int adc_future_trajectory_point_size = learning_data_frame.output().adc_future_trajectory_point_size(); ADEBUG << " adc_future_trajectory_point_size[" << adc_future_trajectory_point_size << "]"; if (adc_future_trajectory_point_size < 10) { const std::string msg = absl::StrCat( "too short adc_future_trajectory_point. frame_num[", learning_data_frame.frame_num(), "] adc_future_trajectory_point_size[", adc_future_trajectory_point_size, "]"); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // evaluate adc future trajectory // TODO(all): move to conf constexpr double kADCFutureTrajectoryDeltaTime = 0.02; std::vector<TrajectoryPointFeature> future_trajectory; for (const auto& tp : learning_data_frame.output().adc_future_trajectory_point()) { future_trajectory.push_back(tp); } TrajectoryPointFeature tp; const int last = learning_data_frame.adc_trajectory_point_size() - 1; tp.set_timestamp_sec( learning_data_frame.adc_trajectory_point(last).timestamp_sec()); tp.mutable_trajectory_point()->CopyFrom( learning_data_frame.adc_trajectory_point(last).trajectory_point()); future_trajectory.insert(future_trajectory.begin(), tp); std::vector<TrajectoryPointFeature> evaluated_future_trajectory; trajectory_evaluator.EvaluateADCFutureTrajectory( learning_data_frame.frame_num(), future_trajectory, start_point_timestamp_sec, kADCFutureTrajectoryDeltaTime, &evaluated_future_trajectory); // convert to common::TrajectoryPoint std::vector<common::TrajectoryPoint> adc_future_trajectory; ConvertADCFutureTrajectory(evaluated_future_trajectory, &adc_future_trajectory); ADEBUG << "adc_future_trajectory_size: " << adc_future_trajectory.size(); injector_->learning_based_data() ->set_learning_data_adc_future_trajectory_points(adc_future_trajectory); return Status::OK(); } void LearningModelInferenceTask::ConvertADCFutureTrajectory( const std::vector<TrajectoryPointFeature>& trajectory, std::vector<common::TrajectoryPoint>* adc_future_trajectory) { adc_future_trajectory->clear(); for (const auto& trajectory_point_feature : trajectory) { const auto& tp = trajectory_point_feature.trajectory_point(); // TrajectoryPointFeature => common::TrajectoryPoint apollo::common::TrajectoryPoint trajectory_point; auto path_point = trajectory_point.mutable_path_point(); path_point->set_x(tp.path_point().x()); path_point->set_y(tp.path_point().y()); // path_point->set_z(tp.path_point().z()); path_point->set_theta(tp.path_point().theta()); // path_point->set_s(tp.path_point().s()); // path_point->set_lane_id(tp.path_point().lane_id()); // path_point->set_x_derivative(); // path_point->set_y_derivative(); trajectory_point.set_v(tp.v()); trajectory_point.set_relative_time(tp.relative_time()); // trajectory_point.mutable_gaussian_info()->CopyFrom(tp.gaussian_info()); // trajectory_point.set_steer(); adc_future_trajectory->push_back(trajectory_point); } double accumulated_s = 0.0; adc_future_trajectory->front().mutable_path_point()->set_s(0.0); for (size_t i = 1; i < adc_future_trajectory->size(); ++i) { auto* cur_path_point = (*adc_future_trajectory)[i].mutable_path_point(); const auto& pre_path_point = (*adc_future_trajectory)[i - 1].path_point(); accumulated_s += std::sqrt((cur_path_point->x() - pre_path_point.x()) * (cur_path_point->x() - pre_path_point.x()) + (cur_path_point->y() - pre_path_point.y()) * (cur_path_point->y() - pre_path_point.y())); cur_path_point->set_s(accumulated_s); } for (size_t i = 0; i + 1 < adc_future_trajectory->size(); ++i) { const auto& cur_v = (*adc_future_trajectory)[i].v(); const auto& cur_relative_time = (*adc_future_trajectory)[i].relative_time(); const auto& next_v = (*adc_future_trajectory)[i + 1].v(); const auto& next_relative_time = (*adc_future_trajectory)[i + 1].relative_time(); const double cur_a = (next_v - cur_v) / (next_relative_time - cur_relative_time); (*adc_future_trajectory)[i].set_a(cur_a); } // assuming last point keeps zero acceleration adc_future_trajectory->back().set_a(0.0); for (size_t i = 0; i + 1 < adc_future_trajectory->size(); ++i) { const auto& cur_a = (*adc_future_trajectory)[i].a(); const auto& cur_relative_time = (*adc_future_trajectory)[i].relative_time(); const auto& next_a = (*adc_future_trajectory)[i + 1].a(); const auto& next_relative_time = (*adc_future_trajectory)[i + 1].relative_time(); const double cur_da = (next_a - cur_a) / (next_relative_time - cur_relative_time); (*adc_future_trajectory)[i].set_da(cur_da); } // assuming last point keeps zero acceleration adc_future_trajectory->back().set_da(0.0); for (size_t i = 0; i + 1 < adc_future_trajectory->size(); ++i) { auto* cur_path_point = (*adc_future_trajectory)[i].mutable_path_point(); const auto& next_path_point = (*adc_future_trajectory)[i + 1].path_point(); const double cur_kappa = apollo::common::math::NormalizeAngle(next_path_point.theta() - cur_path_point->theta()) / (next_path_point.s() - cur_path_point->s()); cur_path_point->set_kappa(cur_kappa); } // assuming last point has zero kappa adc_future_trajectory->back().mutable_path_point()->set_kappa(0.0); for (size_t i = 0; i + 1 < adc_future_trajectory->size(); ++i) { auto* cur_path_point = (*adc_future_trajectory)[i].mutable_path_point(); const auto& next_path_point = (*adc_future_trajectory)[i + 1].path_point(); const double cur_dkappa = (next_path_point.kappa() - cur_path_point->kappa()) / (next_path_point.s() - cur_path_point->s()); cur_path_point->set_dkappa(cur_dkappa); } // assuming last point going straight with the last heading adc_future_trajectory->back().mutable_path_point()->set_dkappa(0.0); for (size_t i = 0; i + 1 < adc_future_trajectory->size(); ++i) { auto* cur_path_point = (*adc_future_trajectory)[i].mutable_path_point(); const auto& next_path_point = (*adc_future_trajectory)[i + 1].path_point(); const double cur_ddkappa = (next_path_point.dkappa() - cur_path_point->dkappa()) / (next_path_point.s() - cur_path_point->s()); cur_path_point->set_ddkappa(cur_ddkappa); } // assuming last point going straight with the last heading adc_future_trajectory->back().mutable_path_point()->set_ddkappa(0.0); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/learning_model/learning_model_inference_task.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 <utility> #include <vector> #include "modules/planning/common/trajectory_evaluator.h" #include "modules/planning/learning_based/model_inference/trajectory_imitation_libtorch_inference.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { class LearningModelInferenceTask : public Task { public: LearningModelInferenceTask( const TaskConfig &config, const std::shared_ptr<DependencyInjector> &injector); apollo::common::Status Execute( Frame *frame, ReferenceLineInfo *reference_line_info) override; private: apollo::common::Status Process(Frame *frame); void ConvertADCFutureTrajectory( const std::vector<TrajectoryPointFeature> &trajectory, std::vector<common::TrajectoryPoint> *adc_future_trajectory); std::unique_ptr<TrajectoryImitationLibtorchInference> trajectory_imitation_inference_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/utils/st_gap_estimator.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 * @brief Defines proper safety distance the ADC should keep from target * obstacle considering different information. **/ namespace apollo { namespace planning { class StGapEstimator { public: StGapEstimator() = delete; virtual ~StGapEstimator() = delete; static double EstimateSafeOvertakingGap(); static double EstimateSafeFollowingGap(const double target_obs_speed); static double EstimateSafeYieldingGap(); static double EstimateProperOvertakingGap(const double target_obs_speed, const double adc_speed); static double EstimateProperFollowingGap(const double adc_speed); static double EstimateProperYieldingGap(); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/utils/st_gap_estimator.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/utils/st_gap_estimator.h" #include <algorithm> #include <cmath> #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { // TODO(Jinyun): move to configs static constexpr double kOvertakeTimeBuffer = 3.0; // in seconds static constexpr double kMinOvertakeDistance = 10.0; // in meters static constexpr double kDpSafetyDistance = 20.0; // in meters static constexpr double kDpSafetyTimeBuffer = 3.0; // in meters // TODO(Jinyun): unite gap calculation in dp st and speed decider double StGapEstimator::EstimateSafeOvertakingGap() { return kDpSafetyDistance; } double StGapEstimator::EstimateSafeFollowingGap(const double target_obs_speed) { return target_obs_speed * kDpSafetyTimeBuffer; } double StGapEstimator::EstimateSafeYieldingGap() { return FLAGS_yield_distance; } // TODO(Jinyun): add more variables to overtaking gap calculation double StGapEstimator::EstimateProperOvertakingGap( const double target_obs_speed, const double adc_speed) { const double overtake_distance_s = std::fmax(std::fmax(adc_speed, target_obs_speed) * kOvertakeTimeBuffer, kMinOvertakeDistance); return overtake_distance_s; } // TODO(Jinyun): add more variables to follow gap calculation double StGapEstimator::EstimateProperFollowingGap(const double adc_speed) { return std::fmax(adc_speed * FLAGS_follow_time_buffer, FLAGS_follow_min_distance); } // TODO(Jinyun): add more variables to yielding gap calculation double StGapEstimator::EstimateProperYieldingGap() { return FLAGS_yield_distance; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/utils/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "st_gap_estimator", srcs = ["st_gap_estimator.cc"], hdrs = ["st_gap_estimator.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/planning/common:planning_gflags", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/optimizers/trajectory_optimizer.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/optimizers/trajectory_optimizer.h" #include <memory> namespace apollo { namespace planning { using apollo::common::Status; TrajectoryOptimizer::TrajectoryOptimizer(const TaskConfig& config) : Task(config) {} TrajectoryOptimizer::TrajectoryOptimizer( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Task(config, injector) {} Status TrajectoryOptimizer::Execute(Frame* frame) { Task::Execute(frame); return Process(); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/optimizers/speed_optimizer.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 "modules/common/status/status.h" #include "modules/planning/common/speed/speed_data.h" #include "modules/planning/common/st_graph_data.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { class SpeedOptimizer : public Task { public: explicit SpeedOptimizer(const TaskConfig& config); virtual ~SpeedOptimizer() = default; common::Status Execute(Frame* frame, ReferenceLineInfo* reference_line_info) override; protected: virtual common::Status Process(const PathData& path_data, const common::TrajectoryPoint& init_point, SpeedData* const speed_data) = 0; void RecordDebugInfo(const SpeedData& speed_data); void RecordDebugInfo(const SpeedData& speed_data, planning_internal::STGraphDebug* st_graph_debug); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/optimizers/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 = "path_optimizer", srcs = ["path_optimizer.cc"], hdrs = ["path_optimizer.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/status", "//modules/planning/common:path_decision", "//modules/planning/common:reference_line_info", "//modules/planning/common/path:path_data", "//modules/planning/common/speed:speed_data", "//modules/planning/tasks:task", "@eigen", ], ) cc_library( name = "speed_optimizer", srcs = ["speed_optimizer.cc"], hdrs = ["speed_optimizer.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/status", "//modules/planning/common:path_decision", "//modules/planning/common:planning_gflags", "//modules/planning/common:reference_line_info", "//modules/planning/common:speed_limit", "//modules/planning/common:st_graph_data", "//modules/planning/common/path:path_data", "//modules/planning/common/speed:speed_data", "//modules/planning/tasks:task", "@eigen", ], ) cc_library( name = "trajectory_optimizer", srcs = ["trajectory_optimizer.cc"], hdrs = ["trajectory_optimizer.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/status", "//modules/planning/common:planning_gflags", "//modules/planning/common/trajectory:discretized_trajectory", "//modules/planning/tasks:task", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/optimizers/trajectory_optimizer.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 trajectory_optimizer.h **/ #pragma once #include <memory> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/status/status.h" #include "modules/planning/common/trajectory/discretized_trajectory.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { class TrajectoryOptimizer : public Task { public: explicit TrajectoryOptimizer(const TaskConfig &config); TrajectoryOptimizer(const TaskConfig &config, const std::shared_ptr<DependencyInjector> &injector); virtual ~TrajectoryOptimizer() = default; apollo::common::Status Execute(Frame *frame) override; protected: virtual apollo::common::Status Process() = 0; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/optimizers/path_optimizer.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_optimizer.h **/ #pragma once #include <memory> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/status/status.h" #include "modules/planning/reference_line/reference_line.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { class PathOptimizer : public Task { public: explicit PathOptimizer(const TaskConfig &config); PathOptimizer(const TaskConfig &config, const std::shared_ptr<DependencyInjector> &injector); virtual ~PathOptimizer() = default; apollo::common::Status Execute( Frame *frame, ReferenceLineInfo *reference_line_info) override; protected: virtual apollo::common::Status Process( const SpeedData &speed_data, const ReferenceLine &reference_line, const common::TrajectoryPoint &init_point, const bool path_reusable, PathData *const path_data) = 0; void RecordDebugInfo(const PathData &path_data); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/optimizers/speed_optimizer.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/optimizers/speed_optimizer.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/speed_limit.h" namespace apollo { namespace planning { using apollo::common::Status; using apollo::planning_internal::STGraphDebug; SpeedOptimizer::SpeedOptimizer(const TaskConfig& config) : Task(config) {} Status SpeedOptimizer::Execute(Frame* frame, ReferenceLineInfo* reference_line_info) { Task::Execute(frame, reference_line_info); auto ret = Process(reference_line_info->path_data(), frame->PlanningStartPoint(), reference_line_info->mutable_speed_data()); RecordDebugInfo(reference_line_info->speed_data()); return ret; } void SpeedOptimizer::RecordDebugInfo(const SpeedData& speed_data) { auto* debug = reference_line_info_->mutable_debug(); auto ptr_speed_plan = debug->mutable_planning_data()->add_speed_plan(); ptr_speed_plan->set_name(Name()); ptr_speed_plan->mutable_speed_point()->CopyFrom( {speed_data.begin(), speed_data.end()}); } void SpeedOptimizer::RecordDebugInfo(const SpeedData& speed_data, STGraphDebug* st_graph_debug) { if (!FLAGS_enable_record_debug || !st_graph_debug) { ADEBUG << "Skip record debug info"; return; } st_graph_debug->set_name(Name()); st_graph_debug->mutable_speed_profile()->CopyFrom( {speed_data.begin(), speed_data.end()}); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/optimizers/path_optimizer.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/optimizers/path_optimizer.h" #include <memory> #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::Status; PathOptimizer::PathOptimizer(const TaskConfig& config) : Task(config) {} PathOptimizer::PathOptimizer( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Task(config, injector) {} Status PathOptimizer::Execute(Frame* frame, ReferenceLineInfo* const reference_line_info) { Task::Execute(frame, reference_line_info); auto ret = Process( reference_line_info->speed_data(), reference_line_info->reference_line(), frame->PlanningStartPoint(), reference_line_info->path_reusable(), reference_line_info->mutable_path_data()); RecordDebugInfo(reference_line_info->path_data()); if (ret != Status::OK()) { reference_line_info->SetDrivable(false); AERROR << "Reference Line " << reference_line_info->Lanes().Id() << " is not drivable after " << Name(); } return ret; } void PathOptimizer::RecordDebugInfo(const PathData& path_data) { const auto& path_points = path_data.discretized_path(); auto* ptr_optimized_path = reference_line_info_->mutable_debug() ->mutable_planning_data() ->add_path(); ptr_optimized_path->set_name(Name()); ptr_optimized_path->mutable_path_point()->CopyFrom( {path_points.begin(), path_points.end()}); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/open_space_trajectory_partition/open_space_trajectory_partition.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/optimizers/open_space_trajectory_partition/open_space_trajectory_partition.h" #include <memory> #include <queue> #include "absl/strings/str_cat.h" #include "cyber/time/clock.h" #include "modules/common/math/polygon2d.h" #include "modules/common/status/status.h" #include "modules/planning/common/planning_context.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::PathPoint; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::math::Box2d; using apollo::common::math::NormalizeAngle; using apollo::common::math::Polygon2d; using apollo::common::math::Vec2d; using apollo::cyber::Clock; OpenSpaceTrajectoryPartition::OpenSpaceTrajectoryPartition( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : TrajectoryOptimizer(config, injector) { config_.CopyFrom(config); AINFO << config.DebugString(); open_space_trajectory_partition_config_ = config_.open_space_trajectory_partition_config(); heading_search_range_ = open_space_trajectory_partition_config_.heading_search_range(); heading_track_range_ = open_space_trajectory_partition_config_.heading_track_range(); distance_search_range_ = open_space_trajectory_partition_config_.distance_search_range(); heading_offset_to_midpoint_ = open_space_trajectory_partition_config_.heading_offset_to_midpoint(); lateral_offset_to_midpoint_ = open_space_trajectory_partition_config_.lateral_offset_to_midpoint(); longitudinal_offset_to_midpoint_ = open_space_trajectory_partition_config_.longitudinal_offset_to_midpoint(); vehicle_box_iou_threshold_to_midpoint_ = open_space_trajectory_partition_config_ .vehicle_box_iou_threshold_to_midpoint(); linear_velocity_threshold_on_ego_ = open_space_trajectory_partition_config_ .linear_velocity_threshold_on_ego(); vehicle_param_ = common::VehicleConfigHelper::Instance()->GetConfig().vehicle_param(); ego_length_ = vehicle_param_.length(); ego_width_ = vehicle_param_.width(); shift_distance_ = ego_length_ / 2.0 - vehicle_param_.back_edge_to_center(); wheel_base_ = vehicle_param_.wheel_base(); } void OpenSpaceTrajectoryPartition::Restart() { auto* current_gear_status = frame_->mutable_open_space_info()->mutable_gear_switch_states(); current_gear_status->gear_switching_flag = false; current_gear_status->gear_shift_period_finished = true; current_gear_status->gear_shift_period_started = true; current_gear_status->gear_shift_period_time = 0.0; current_gear_status->gear_shift_start_time = 0.0; current_gear_status->gear_shift_position = canbus::Chassis::GEAR_DRIVE; } Status OpenSpaceTrajectoryPartition::Process() { const auto& open_space_info = frame_->open_space_info(); auto open_space_info_ptr = frame_->mutable_open_space_info(); const auto& stitched_trajectory_result = open_space_info.stitched_trajectory_result(); auto* interpolated_trajectory_result_ptr = open_space_info_ptr->mutable_interpolated_trajectory_result(); InterpolateTrajectory(stitched_trajectory_result, interpolated_trajectory_result_ptr); auto* partitioned_trajectories = open_space_info_ptr->mutable_partitioned_trajectories(); PartitionTrajectory(*interpolated_trajectory_result_ptr, partitioned_trajectories); const auto& open_space_status = injector_->planning_context()->planning_status().open_space(); if (!open_space_status.position_init() && frame_->open_space_info().open_space_provider_success()) { auto* open_space_status = injector_->planning_context() ->mutable_planning_status() ->mutable_open_space(); open_space_status->set_position_init(true); auto* chosen_partitioned_trajectory = open_space_info_ptr->mutable_chosen_partitioned_trajectory(); auto* mutable_trajectory = open_space_info_ptr->mutable_stitched_trajectory_result(); AdjustRelativeTimeAndS(open_space_info.partitioned_trajectories(), 0, 0, mutable_trajectory, chosen_partitioned_trajectory); return Status::OK(); } // Choose the one to follow based on the closest partitioned trajectory size_t trajectories_size = partitioned_trajectories->size(); size_t current_trajectory_index = 0; size_t current_trajectory_point_index = 0; bool flag_change_to_next = false; // Vehicle related information used to choose closest point UpdateVehicleInfo(); std::priority_queue<std::pair<std::pair<size_t, size_t>, double>, std::vector<std::pair<std::pair<size_t, size_t>, double>>, pair_comp_> closest_point_on_trajs; std::vector<std::string> trajectories_encodings; for (size_t i = 0; i < trajectories_size; ++i) { const auto& trajectory = partitioned_trajectories->at(i).first; std::string trajectory_encoding; if (!EncodeTrajectory(trajectory, &trajectory_encoding)) { return Status(ErrorCode::PLANNING_ERROR, "Trajectory empty in trajectory partition"); } trajectories_encodings.emplace_back(std::move(trajectory_encoding)); } for (size_t i = 0; i < trajectories_size; ++i) { const auto& gear = partitioned_trajectories->at(i).second; const auto& trajectory = partitioned_trajectories->at(i).first; size_t trajectory_size = trajectory.size(); CHECK_GT(trajectory_size, 0U); flag_change_to_next = CheckReachTrajectoryEnd( trajectory, gear, trajectories_size, i, &current_trajectory_index, &current_trajectory_point_index); if (flag_change_to_next && !CheckTrajTraversed(trajectories_encodings[current_trajectory_index])) { UpdateTrajHistory(trajectories_encodings[current_trajectory_index]); AINFO << "change to traj " << i << " in " << trajectories_size; break; } // Choose the closest point to track std::priority_queue<std::pair<size_t, double>, std::vector<std::pair<size_t, double>>, comp_> closest_point; for (size_t j = 0; j < trajectory_size; ++j) { const TrajectoryPoint& trajectory_point = trajectory.at(j); const PathPoint& path_point = trajectory_point.path_point(); const double path_point_x = path_point.x(); const double path_point_y = path_point.y(); const double path_point_theta = path_point.theta(); const Vec2d tracking_vector(path_point_x - ego_x_, path_point_y - ego_y_); const double distance = tracking_vector.Length(); const double tracking_direction = tracking_vector.Angle(); const double traj_point_moving_direction = gear == canbus::Chassis::GEAR_REVERSE ? NormalizeAngle(path_point_theta + M_PI) : path_point_theta; const double head_track_difference = std::abs( NormalizeAngle(tracking_direction - vehicle_moving_direction_)); const double heading_search_difference = std::abs(NormalizeAngle( traj_point_moving_direction - vehicle_moving_direction_)); if (distance < distance_search_range_ && heading_search_difference < heading_search_range_ && head_track_difference < heading_track_range_) { // get vehicle box and path point box, compute IOU Box2d path_point_box({path_point_x, path_point_y}, path_point_theta, ego_length_, ego_width_); Vec2d shift_vec{shift_distance_ * std::cos(path_point_theta), shift_distance_ * std::sin(path_point_theta)}; path_point_box.Shift(shift_vec); double iou_ratio = Polygon2d(ego_box_).ComputeIoU(Polygon2d(path_point_box)); closest_point.emplace(j, iou_ratio); } } if (!closest_point.empty()) { size_t closest_point_index = closest_point.top().first; double max_iou_ratio = closest_point.top().second; closest_point_on_trajs.emplace(std::make_pair(i, closest_point_index), max_iou_ratio); } } if (!flag_change_to_next) { bool use_fail_safe_search = false; if (closest_point_on_trajs.empty()) { use_fail_safe_search = true; } else { bool closest_and_not_repeated_traj_found = false; while (!closest_point_on_trajs.empty()) { current_trajectory_index = closest_point_on_trajs.top().first.first; current_trajectory_point_index = closest_point_on_trajs.top().first.second; if (CheckTrajTraversed( trajectories_encodings[current_trajectory_index])) { closest_point_on_trajs.pop(); } else { closest_and_not_repeated_traj_found = true; UpdateTrajHistory(trajectories_encodings[current_trajectory_index]); break; } } if (!closest_and_not_repeated_traj_found) { use_fail_safe_search = true; } } if (use_fail_safe_search) { if (!UseFailSafeSearch(*partitioned_trajectories, trajectories_encodings, &current_trajectory_index, &current_trajectory_point_index)) { const std::string msg = "Fail to find nearest trajectory point to follow"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } } } auto* chosen_partitioned_trajectory = open_space_info_ptr->mutable_chosen_partitioned_trajectory(); auto trajectory = &(chosen_partitioned_trajectory->first); ADEBUG << "chosen_partitioned_trajectory [" << trajectory->size() << "]"; if (FLAGS_use_gear_shift_trajectory) { if (InsertGearShiftTrajectory(flag_change_to_next, current_trajectory_index, open_space_info.partitioned_trajectories(), chosen_partitioned_trajectory) && chosen_partitioned_trajectory->first.size() != 0) { trajectory = &(chosen_partitioned_trajectory->first); ADEBUG << "After InsertGearShiftTrajectory [" << trajectory->size() << "]"; return Status::OK(); } } if (!flag_change_to_next) { double veh_rel_time; size_t time_match_index; double now_time = Clock::Instance()->NowInSeconds(); auto& traj = partitioned_trajectories->at(current_trajectory_index).first; if (last_index_ != -1) { veh_rel_time = traj[last_index_].relative_time() + now_time - last_time_; time_match_index = traj.QueryLowerBoundPoint(veh_rel_time); } else { time_match_index = current_trajectory_point_index; last_time_ = now_time; last_index_ = time_match_index; } if (std::abs(traj[time_match_index].path_point().s() - traj.at(current_trajectory_point_index).path_point().s()) < 2) { current_trajectory_point_index = time_match_index; } else { last_index_ = current_trajectory_point_index; last_time_ = now_time; } } else { last_index_ = -1; } auto* mutable_trajectory = open_space_info_ptr->mutable_stitched_trajectory_result(); AdjustRelativeTimeAndS(open_space_info.partitioned_trajectories(), current_trajectory_index, current_trajectory_point_index, mutable_trajectory, chosen_partitioned_trajectory); return Status::OK(); } void OpenSpaceTrajectoryPartition::InterpolateTrajectory( const DiscretizedTrajectory& stitched_trajectory_result, DiscretizedTrajectory* interpolated_trajectory) { if (FLAGS_use_iterative_anchoring_smoother) { *interpolated_trajectory = stitched_trajectory_result; return; } interpolated_trajectory->clear(); size_t interpolated_pieces_num = open_space_trajectory_partition_config_.interpolated_pieces_num(); CHECK_GT(stitched_trajectory_result.size(), 0U); CHECK_GT(interpolated_pieces_num, 0U); size_t trajectory_to_be_partitioned_intervals_num = stitched_trajectory_result.size() - 1; size_t interpolated_points_num = interpolated_pieces_num - 1; for (size_t i = 0; i < trajectory_to_be_partitioned_intervals_num; ++i) { double relative_time_interval = (stitched_trajectory_result.at(i + 1).relative_time() - stitched_trajectory_result.at(i).relative_time()) / static_cast<double>(interpolated_pieces_num); interpolated_trajectory->push_back(stitched_trajectory_result.at(i)); for (size_t j = 0; j < interpolated_points_num; ++j) { double relative_time = stitched_trajectory_result.at(i).relative_time() + (static_cast<double>(j) + 1.0) * relative_time_interval; interpolated_trajectory->emplace_back( common::math::InterpolateUsingLinearApproximation( stitched_trajectory_result.at(i), stitched_trajectory_result.at(i + 1), relative_time)); } } interpolated_trajectory->push_back(stitched_trajectory_result.back()); } void OpenSpaceTrajectoryPartition::UpdateVehicleInfo() { const common::VehicleState& vehicle_state = frame_->vehicle_state(); ego_theta_ = vehicle_state.heading(); ego_x_ = vehicle_state.x(); ego_y_ = vehicle_state.y(); ego_v_ = vehicle_state.linear_velocity(); Box2d box({ego_x_, ego_y_}, ego_theta_, ego_length_, ego_width_); ego_box_ = std::move(box); Vec2d ego_shift_vec{shift_distance_ * std::cos(ego_theta_), shift_distance_ * std::sin(ego_theta_)}; ego_box_.Shift(ego_shift_vec); vehicle_moving_direction_ = vehicle_state.gear() == canbus::Chassis::GEAR_REVERSE ? NormalizeAngle(ego_theta_ + M_PI) : ego_theta_; } bool OpenSpaceTrajectoryPartition::EncodeTrajectory( const DiscretizedTrajectory& trajectory, std::string* const encoding) { if (trajectory.empty()) { AERROR << "Fail to encode trajectory because it is empty"; return false; } static constexpr double encoding_origin_x = 58700.0; static constexpr double encoding_origin_y = 4141000.0; const auto& init_path_point = trajectory.front().path_point(); const auto& last_path_point = trajectory.back().path_point(); const int init_point_x = static_cast<int>((init_path_point.x() - encoding_origin_x) * 1000.0); const int init_point_y = static_cast<int>((init_path_point.y() - encoding_origin_y) * 1000.0); const int init_point_heading = static_cast<int>(init_path_point.theta() * 10000.0); const int last_point_x = static_cast<int>((last_path_point.x() - encoding_origin_x) * 1000.0); const int last_point_y = static_cast<int>((last_path_point.y() - encoding_origin_y) * 1000.0); const int last_point_heading = static_cast<int>(last_path_point.theta() * 10000.0); *encoding = absl::StrCat( // init point init_point_x, "_", init_point_y, "_", init_point_heading, "/", // last point last_point_x, "_", last_point_y, "_", last_point_heading); return true; } bool OpenSpaceTrajectoryPartition::CheckTrajTraversed( const std::string& trajectory_encoding_to_check) { const auto& open_space_status = injector_->planning_context()->planning_status().open_space(); const int index_history_size = open_space_status.partitioned_trajectories_index_history_size(); if (index_history_size <= 1) { return false; } for (int i = 0; i < index_history_size - 1; i++) { const auto& index_history = open_space_status.partitioned_trajectories_index_history(i); if (index_history == trajectory_encoding_to_check) { return true; } } return false; } void OpenSpaceTrajectoryPartition::UpdateTrajHistory( const std::string& chosen_trajectory_encoding) { auto* open_space_status = injector_->planning_context() ->mutable_planning_status() ->mutable_open_space(); const auto& trajectory_history = injector_->planning_context() ->planning_status() .open_space() .partitioned_trajectories_index_history(); if (trajectory_history.empty()) { open_space_status->add_partitioned_trajectories_index_history( chosen_trajectory_encoding); return; } if (*(trajectory_history.rbegin()) == chosen_trajectory_encoding) { return; } open_space_status->add_partitioned_trajectories_index_history( chosen_trajectory_encoding); } void OpenSpaceTrajectoryPartition::PartitionTrajectory( const DiscretizedTrajectory& raw_trajectory, std::vector<TrajGearPair>* partitioned_trajectories) { CHECK_NOTNULL(partitioned_trajectories); size_t horizon = raw_trajectory.size(); partitioned_trajectories->clear(); partitioned_trajectories->emplace_back(); TrajGearPair* current_trajectory_gear = &(partitioned_trajectories->back()); auto* trajectory = &(current_trajectory_gear->first); auto* gear = &(current_trajectory_gear->second); // Decide initial gear const auto& first_path_point = raw_trajectory.front().path_point(); const auto& second_path_point = raw_trajectory[1].path_point(); double heading_angle = first_path_point.theta(); const Vec2d init_tracking_vector( second_path_point.x() - first_path_point.x(), second_path_point.y() - first_path_point.y()); double tracking_angle = init_tracking_vector.Angle(); *gear = std::abs(common::math::NormalizeAngle(tracking_angle - heading_angle)) < (M_PI_2) ? canbus::Chassis::GEAR_DRIVE : canbus::Chassis::GEAR_REVERSE; // Set accumulated distance Vec2d last_pos_vec(first_path_point.x(), first_path_point.y()); double distance_s = 0.0; bool is_trajectory_last_point = false; for (size_t i = 0; i < horizon - 1; ++i) { const TrajectoryPoint& trajectory_point = raw_trajectory.at(i); const TrajectoryPoint& next_trajectory_point = raw_trajectory.at(i + 1); // Check gear change heading_angle = trajectory_point.path_point().theta(); const Vec2d tracking_vector(next_trajectory_point.path_point().x() - trajectory_point.path_point().x(), next_trajectory_point.path_point().y() - trajectory_point.path_point().y()); tracking_angle = tracking_vector.Angle(); auto cur_gear = std::abs(common::math::NormalizeAngle(tracking_angle - heading_angle)) < (M_PI_2) ? canbus::Chassis::GEAR_DRIVE : canbus::Chassis::GEAR_REVERSE; if (cur_gear != *gear) { is_trajectory_last_point = true; LoadTrajectoryPoint(trajectory_point, is_trajectory_last_point, *gear, &last_pos_vec, &distance_s, trajectory); partitioned_trajectories->emplace_back(); current_trajectory_gear = &(partitioned_trajectories->back()); current_trajectory_gear->second = cur_gear; distance_s = 0.0; is_trajectory_last_point = false; } trajectory = &(current_trajectory_gear->first); gear = &(current_trajectory_gear->second); LoadTrajectoryPoint(trajectory_point, is_trajectory_last_point, *gear, &last_pos_vec, &distance_s, trajectory); } is_trajectory_last_point = true; const TrajectoryPoint& last_trajectory_point = raw_trajectory.back(); LoadTrajectoryPoint(last_trajectory_point, is_trajectory_last_point, *gear, &last_pos_vec, &distance_s, trajectory); } void OpenSpaceTrajectoryPartition::LoadTrajectoryPoint( const TrajectoryPoint& trajectory_point, const bool is_trajectory_last_point, const canbus::Chassis::GearPosition& gear, Vec2d* last_pos_vec, double* distance_s, DiscretizedTrajectory* current_trajectory) { current_trajectory->emplace_back(); TrajectoryPoint* point = &(current_trajectory->back()); point->set_relative_time(trajectory_point.relative_time()); point->mutable_path_point()->set_x(trajectory_point.path_point().x()); point->mutable_path_point()->set_y(trajectory_point.path_point().y()); point->mutable_path_point()->set_theta(trajectory_point.path_point().theta()); point->set_v(trajectory_point.v()); point->mutable_path_point()->set_s(*distance_s); Vec2d cur_pos_vec(trajectory_point.path_point().x(), trajectory_point.path_point().y()); *distance_s += (gear == canbus::Chassis::GEAR_REVERSE ? -1.0 : 1.0) * (cur_pos_vec.DistanceTo(*last_pos_vec)); *last_pos_vec = cur_pos_vec; point->mutable_path_point()->set_kappa((is_trajectory_last_point ? -1 : 1) * std::tan(trajectory_point.steer()) / wheel_base_); point->set_a(trajectory_point.a()); } bool OpenSpaceTrajectoryPartition::CheckReachTrajectoryEnd( const DiscretizedTrajectory& trajectory, const canbus::Chassis::GearPosition& gear, const size_t trajectories_size, const size_t trajectories_index, size_t* current_trajectory_index, size_t* current_trajectory_point_index) { // Check if have reached endpoint of trajectory const TrajectoryPoint& trajectory_end_point = trajectory.back(); const size_t trajectory_size = trajectory.size(); const PathPoint& path_end_point = trajectory_end_point.path_point(); const double path_end_point_x = path_end_point.x(); const double path_end_point_y = path_end_point.y(); const Vec2d tracking_vector(ego_x_ - path_end_point_x, ego_y_ - path_end_point_y); const double path_end_point_theta = path_end_point.theta(); const double included_angle = NormalizeAngle(path_end_point_theta - tracking_vector.Angle()); const double distance_to_trajs_end = std::sqrt((path_end_point_x - ego_x_) * (path_end_point_x - ego_x_) + (path_end_point_y - ego_y_) * (path_end_point_y - ego_y_)); const double lateral_offset = std::abs(distance_to_trajs_end * std::sin(included_angle)); const double longitudinal_offset = std::abs(distance_to_trajs_end * std::cos(included_angle)); const double traj_end_point_moving_direction = gear == canbus::Chassis::GEAR_REVERSE ? NormalizeAngle(path_end_point_theta + M_PI) : path_end_point_theta; const double heading_search_to_trajs_end = std::abs(NormalizeAngle( traj_end_point_moving_direction - vehicle_moving_direction_)); // If close to the end point, start on the next trajectory double end_point_iou_ratio = 0.0; if (lateral_offset < lateral_offset_to_midpoint_ && longitudinal_offset < longitudinal_offset_to_midpoint_ && heading_search_to_trajs_end < heading_offset_to_midpoint_ && std::abs(ego_v_) < linear_velocity_threshold_on_ego_) { // get vehicle box and path point box, compare with a threadhold in IOU Box2d path_end_point_box({path_end_point_x, path_end_point_y}, path_end_point_theta, ego_length_, ego_width_); Vec2d shift_vec{shift_distance_ * std::cos(path_end_point_theta), shift_distance_ * std::sin(path_end_point_theta)}; path_end_point_box.Shift(shift_vec); end_point_iou_ratio = Polygon2d(ego_box_).ComputeIoU(Polygon2d(path_end_point_box)); if (end_point_iou_ratio > vehicle_box_iou_threshold_to_midpoint_) { if (trajectories_index + 1 >= trajectories_size) { *current_trajectory_index = trajectories_size - 1; *current_trajectory_point_index = trajectory_size - 1; } else { *current_trajectory_index = trajectories_index + 1; *current_trajectory_point_index = 0; } AINFO << "Reach the end of a trajectory, switching to next one"; return true; } } ADEBUG << "Vehicle did not reach end of a trajectory with conditions for " "lateral distance_check: " << (lateral_offset < lateral_offset_to_midpoint_) << " and actual lateral distance: " << lateral_offset << "; longitudinal distance_check: " << (longitudinal_offset < longitudinal_offset_to_midpoint_) << " and actual longitudinal distance: " << longitudinal_offset << "; heading_check: " << (heading_search_to_trajs_end < heading_offset_to_midpoint_) << " with actual heading: " << heading_search_to_trajs_end << "; velocity_check: " << (std::abs(ego_v_) < linear_velocity_threshold_on_ego_) << " with actual linear velocity: " << ego_v_ << "; iou_check: " << (end_point_iou_ratio > vehicle_box_iou_threshold_to_midpoint_) << " with actual iou: " << end_point_iou_ratio; return false; } bool OpenSpaceTrajectoryPartition::UseFailSafeSearch( const std::vector<TrajGearPair>& partitioned_trajectories, const std::vector<std::string>& trajectories_encodings, size_t* current_trajectory_index, size_t* current_trajectory_point_index) { AERROR << "Trajectory partition fail, using failsafe search"; const size_t trajectories_size = partitioned_trajectories.size(); std::priority_queue<std::pair<std::pair<size_t, size_t>, double>, std::vector<std::pair<std::pair<size_t, size_t>, double>>, pair_comp_> failsafe_closest_point_on_trajs; for (size_t i = 0; i < trajectories_size; ++i) { const auto& trajectory = partitioned_trajectories.at(i).first; size_t trajectory_size = trajectory.size(); CHECK_GT(trajectory_size, 0U); std::priority_queue<std::pair<size_t, double>, std::vector<std::pair<size_t, double>>, comp_> failsafe_closest_point; for (size_t j = 0; j < trajectory_size; ++j) { const TrajectoryPoint& trajectory_point = trajectory.at(j); const PathPoint& path_point = trajectory_point.path_point(); const double path_point_x = path_point.x(); const double path_point_y = path_point.y(); const double path_point_theta = path_point.theta(); const Vec2d tracking_vector(path_point_x - ego_x_, path_point_y - ego_y_); const double distance = tracking_vector.Length(); if (distance < distance_search_range_) { // get vehicle box and path point box, compute IOU Box2d path_point_box({path_point_x, path_point_y}, path_point_theta, ego_length_, ego_width_); Vec2d shift_vec{shift_distance_ * std::cos(path_point_theta), shift_distance_ * std::sin(path_point_theta)}; path_point_box.Shift(shift_vec); double iou_ratio = Polygon2d(ego_box_).ComputeIoU(Polygon2d(path_point_box)); failsafe_closest_point.emplace(j, iou_ratio); } } if (!failsafe_closest_point.empty()) { size_t closest_point_index = failsafe_closest_point.top().first; double max_iou_ratio = failsafe_closest_point.top().second; failsafe_closest_point_on_trajs.emplace( std::make_pair(i, closest_point_index), max_iou_ratio); } } if (failsafe_closest_point_on_trajs.empty()) { return false; } else { bool closest_and_not_repeated_traj_found = false; while (!failsafe_closest_point_on_trajs.empty()) { *current_trajectory_index = failsafe_closest_point_on_trajs.top().first.first; *current_trajectory_point_index = failsafe_closest_point_on_trajs.top().first.second; if (CheckTrajTraversed( trajectories_encodings[*current_trajectory_index])) { failsafe_closest_point_on_trajs.pop(); } else { closest_and_not_repeated_traj_found = true; UpdateTrajHistory(trajectories_encodings[*current_trajectory_index]); return true; } } if (!closest_and_not_repeated_traj_found) { return false; } return true; } } bool OpenSpaceTrajectoryPartition::InsertGearShiftTrajectory( const bool flag_change_to_next, const size_t current_trajectory_index, const std::vector<TrajGearPair>& partitioned_trajectories, TrajGearPair* gear_switch_idle_time_trajectory) { const auto* last_frame = injector_->frame_history()->Latest(); const auto& last_gear_status = last_frame->open_space_info().gear_switch_states(); auto* current_gear_status = frame_->mutable_open_space_info()->mutable_gear_switch_states(); *(current_gear_status) = last_gear_status; if (flag_change_to_next || !current_gear_status->gear_shift_period_finished) { current_gear_status->gear_shift_period_finished = false; if (current_gear_status->gear_shift_period_started) { current_gear_status->gear_shift_start_time = Clock::Instance()->NowInSeconds(); current_gear_status->gear_shift_position = partitioned_trajectories.at(current_trajectory_index).second; current_gear_status->gear_shift_period_started = false; } if (current_gear_status->gear_shift_period_time > open_space_trajectory_partition_config_.gear_shift_period_duration()) { current_gear_status->gear_shift_period_finished = true; current_gear_status->gear_shift_period_started = true; } else { GenerateGearShiftTrajectory(current_gear_status->gear_shift_position, gear_switch_idle_time_trajectory); current_gear_status->gear_shift_period_time = Clock::Instance()->NowInSeconds() - current_gear_status->gear_shift_start_time; return true; } } return true; } void OpenSpaceTrajectoryPartition::GenerateGearShiftTrajectory( const canbus::Chassis::GearPosition& gear_position, TrajGearPair* gear_switch_idle_time_trajectory) { gear_switch_idle_time_trajectory->first.clear(); const double gear_shift_max_t = open_space_trajectory_partition_config_.gear_shift_max_t(); const double gear_shift_unit_t = open_space_trajectory_partition_config_.gear_shift_unit_t(); // TrajectoryPoint point; for (double t = 0.0; t < gear_shift_max_t; t += gear_shift_unit_t) { TrajectoryPoint point; point.mutable_path_point()->set_x(frame_->vehicle_state().x()); point.mutable_path_point()->set_y(frame_->vehicle_state().y()); point.mutable_path_point()->set_theta(frame_->vehicle_state().heading()); point.mutable_path_point()->set_s(0.0); point.mutable_path_point()->set_kappa(frame_->vehicle_state().kappa()); point.set_relative_time(t); point.set_v(0.0); point.set_a(0.0); gear_switch_idle_time_trajectory->first.emplace_back(point); } ADEBUG << "gear_switch_idle_time_trajectory" << gear_switch_idle_time_trajectory->first.size(); gear_switch_idle_time_trajectory->second = gear_position; } void OpenSpaceTrajectoryPartition::AdjustRelativeTimeAndS( const std::vector<TrajGearPair>& partitioned_trajectories, const size_t current_trajectory_index, const size_t closest_trajectory_point_index, DiscretizedTrajectory* unpartitioned_trajectory_result, TrajGearPair* current_partitioned_trajectory) { const size_t partitioned_trajectories_size = partitioned_trajectories.size(); CHECK_GT(partitioned_trajectories_size, current_trajectory_index); // Reassign relative time and relative s to have the closest point as origin // point *(current_partitioned_trajectory) = partitioned_trajectories.at(current_trajectory_index); auto trajectory = &(current_partitioned_trajectory->first); double time_shift = trajectory->at(closest_trajectory_point_index).relative_time(); double s_shift = trajectory->at(closest_trajectory_point_index).path_point().s(); const size_t trajectory_size = trajectory->size(); for (size_t i = 0; i < trajectory_size; ++i) { TrajectoryPoint* trajectory_point = &(trajectory->at(i)); trajectory_point->set_relative_time(trajectory_point->relative_time() - time_shift); trajectory_point->mutable_path_point()->set_s( trajectory_point->path_point().s() - s_shift); } // Reassign relative t and s on stitched_trajectory_result for accurate next // frame stitching size_t interpolated_pieces_num = open_space_trajectory_partition_config_.interpolated_pieces_num(); if (FLAGS_use_iterative_anchoring_smoother) { interpolated_pieces_num = 1; } const size_t unpartitioned_trajectory_size = unpartitioned_trajectory_result->size(); size_t index_estimate = 0; for (size_t i = 0; i < current_trajectory_index; ++i) { index_estimate += partitioned_trajectories.at(i).first.size(); } index_estimate += closest_trajectory_point_index; index_estimate /= interpolated_pieces_num; if (index_estimate >= unpartitioned_trajectory_size) { index_estimate = unpartitioned_trajectory_size - 1; } time_shift = unpartitioned_trajectory_result->at(index_estimate).relative_time(); s_shift = unpartitioned_trajectory_result->at(index_estimate).path_point().s(); for (size_t i = 0; i < unpartitioned_trajectory_size; ++i) { TrajectoryPoint* trajectory_point = &(unpartitioned_trajectory_result->at(i)); trajectory_point->set_relative_time(trajectory_point->relative_time() - time_shift); trajectory_point->mutable_path_point()->set_s( trajectory_point->path_point().s() - s_shift); } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/open_space_trajectory_partition/open_space_trajectory_partition_test.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/optimizers/open_space_trajectory_partition/open_space_trajectory_partition.h" #include "gtest/gtest.h" #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { class OpenSpaceTrajectoryPartitionTest : public ::testing::Test { public: virtual void SetUp() { config_.set_task_type(TaskConfig::OPEN_SPACE_TRAJECTORY_PARTITION); injector_ = std::make_shared<DependencyInjector>(); } protected: TaskConfig config_; std::shared_ptr<DependencyInjector> injector_; }; TEST_F(OpenSpaceTrajectoryPartitionTest, Init) { OpenSpaceTrajectoryPartition open_space_trajectory_partition(config_, injector_); EXPECT_EQ(open_space_trajectory_partition.Name(), TaskConfig::TaskType_Name(config_.task_type())); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/open_space_trajectory_partition/open_space_trajectory_partition.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 <utility> #include <vector> #include "modules/common_msgs/chassis_msgs/chassis.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/linear_interpolation.h" #include "modules/common/status/status.h" #include "modules/planning/common/trajectory/discretized_trajectory.h" #include "modules/planning/tasks/optimizers/trajectory_optimizer.h" namespace apollo { namespace planning { class OpenSpaceTrajectoryPartition : public TrajectoryOptimizer { public: OpenSpaceTrajectoryPartition( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); ~OpenSpaceTrajectoryPartition() = default; void Restart(); private: common::Status Process() override; void InterpolateTrajectory( const DiscretizedTrajectory& stitched_trajectory_result, DiscretizedTrajectory* interpolated_trajectory); void UpdateVehicleInfo(); bool EncodeTrajectory(const DiscretizedTrajectory& trajectory, std::string* const encoding); bool CheckTrajTraversed(const std::string& trajectory_encoding_to_check); void UpdateTrajHistory(const std::string& chosen_trajectory_encoding); void PartitionTrajectory(const DiscretizedTrajectory& trajectory, std::vector<TrajGearPair>* partitioned_trajectories); void LoadTrajectoryPoint(const common::TrajectoryPoint& trajectory_point, const bool is_trajectory_last_point, const canbus::Chassis::GearPosition& gear, common::math::Vec2d* last_pos_vec, double* distance_s, DiscretizedTrajectory* current_trajectory); bool CheckReachTrajectoryEnd(const DiscretizedTrajectory& trajectory, const canbus::Chassis::GearPosition& gear, const size_t trajectories_size, const size_t trajectories_index, size_t* current_trajectory_index, size_t* current_trajectory_point_index); bool UseFailSafeSearch( const std::vector<TrajGearPair>& partitioned_trajectories, const std::vector<std::string>& trajectories_encodings, size_t* current_trajectory_index, size_t* current_trajectory_point_index); bool InsertGearShiftTrajectory( const bool flag_change_to_next, const size_t current_trajectory_index, const std::vector<TrajGearPair>& partitioned_trajectories, TrajGearPair* gear_switch_idle_time_trajectory); void GenerateGearShiftTrajectory( const canbus::Chassis::GearPosition& gear_position, TrajGearPair* gear_switch_idle_time_trajectory); void AdjustRelativeTimeAndS( const std::vector<TrajGearPair>& partitioned_trajectories, const size_t current_trajectory_index, const size_t closest_trajectory_point_index, DiscretizedTrajectory* stitched_trajectory_result, TrajGearPair* current_partitioned_trajectory); private: OpenSpaceTrajectoryPartitionConfig open_space_trajectory_partition_config_; double heading_search_range_ = 0.0; double heading_track_range_ = 0.0; double distance_search_range_ = 0.0; double heading_offset_to_midpoint_ = 0.0; double lateral_offset_to_midpoint_ = 0.0; double longitudinal_offset_to_midpoint_ = 0.0; double vehicle_box_iou_threshold_to_midpoint_ = 0.0; double linear_velocity_threshold_on_ego_ = 0.0; common::VehicleParam vehicle_param_; double ego_length_ = 0.0; double ego_width_ = 0.0; double shift_distance_ = 0.0; double wheel_base_ = 0.0; double ego_theta_ = 0.0; double ego_x_ = 0.0; double ego_y_ = 0.0; double ego_v_ = 0.0; common::math::Box2d ego_box_; double vehicle_moving_direction_ = 0.0; int last_index_ = -1; double last_time_ = 0; struct pair_comp_ { bool operator()( const std::pair<std::pair<size_t, size_t>, double>& left, const std::pair<std::pair<size_t, size_t>, double>& right) const { return left.second <= right.second; } }; struct comp_ { bool operator()(const std::pair<size_t, double>& left, const std::pair<size_t, double>& right) { return left.second <= right.second; } }; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/open_space_trajectory_partition/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "open_space_trajectory_partition", srcs = ["open_space_trajectory_partition.cc"], hdrs = ["open_space_trajectory_partition.h"], copts = [ "-DMODULE_NAME=\\\"planning\\\"", ], deps = [ "//modules/common/status", "//modules/planning/proto:planning_config_cc_proto", "//modules/planning/tasks:task", "//modules/planning/tasks/optimizers:trajectory_optimizer", ], ) cc_test( name = "open_space_trajectory_partition_test", size = "small", srcs = ["open_space_trajectory_partition_test.cc"], deps = [ ":open_space_trajectory_partition", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/road_graph/trajectory_cost.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/optimizers/road_graph/trajectory_cost.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/vec2d.h" #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/util/point_factory.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { TrajectoryCost::TrajectoryCost(const DpPolyPathConfig &config, const ReferenceLine &reference_line, const bool is_change_lane_path, const std::vector<const Obstacle *> &obstacles, const common::VehicleParam &vehicle_param, const SpeedData &heuristic_speed_data, const common::SLPoint &init_sl_point, const SLBoundary &adc_sl_boundary) : config_(config), reference_line_(&reference_line), is_change_lane_path_(is_change_lane_path), vehicle_param_(vehicle_param), heuristic_speed_data_(heuristic_speed_data), init_sl_point_(init_sl_point), adc_sl_boundary_(adc_sl_boundary) { const double total_time = std::min(heuristic_speed_data_.TotalTime(), FLAGS_prediction_total_time); num_of_time_stamps_ = static_cast<uint32_t>( std::floor(total_time / config.eval_time_interval())); for (const auto *ptr_obstacle : obstacles) { if (ptr_obstacle->IsIgnore()) { continue; } else if (ptr_obstacle->LongitudinalDecision().has_stop()) { continue; } const auto &sl_boundary = ptr_obstacle->PerceptionSLBoundary(); const double adc_left_l = init_sl_point_.l() + vehicle_param_.left_edge_to_center(); const double adc_right_l = init_sl_point_.l() - vehicle_param_.right_edge_to_center(); if (adc_left_l + FLAGS_lateral_ignore_buffer < sl_boundary.start_l() || adc_right_l - FLAGS_lateral_ignore_buffer > sl_boundary.end_l()) { continue; } bool is_bycycle_or_pedestrian = (ptr_obstacle->Perception().type() == perception::PerceptionObstacle::BICYCLE || ptr_obstacle->Perception().type() == perception::PerceptionObstacle::PEDESTRIAN); if (ptr_obstacle->IsVirtual()) { // Virtual obstacle continue; } else if (ptr_obstacle->IsStatic() || is_bycycle_or_pedestrian) { static_obstacle_sl_boundaries_.push_back(std::move(sl_boundary)); } else { std::vector<Box2d> box_by_time; for (uint32_t t = 0; t <= num_of_time_stamps_; ++t) { TrajectoryPoint trajectory_point = ptr_obstacle->GetPointAtTime(t * config.eval_time_interval()); Box2d obstacle_box = ptr_obstacle->GetBoundingBox(trajectory_point); static constexpr double kBuff = 0.5; Box2d expanded_obstacle_box = Box2d(obstacle_box.center(), obstacle_box.heading(), obstacle_box.length() + kBuff, obstacle_box.width() + kBuff); box_by_time.push_back(expanded_obstacle_box); } dynamic_obstacle_boxes_.push_back(std::move(box_by_time)); } } } ComparableCost TrajectoryCost::CalculatePathCost( const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s, const uint32_t curr_level, const uint32_t total_level) { ComparableCost cost; double path_cost = 0.0; std::function<double(const double)> quasi_softmax = [this](const double x) { const double l0 = this->config_.path_l_cost_param_l0(); const double b = this->config_.path_l_cost_param_b(); const double k = this->config_.path_l_cost_param_k(); return (b + std::exp(-k * (x - l0))) / (1.0 + std::exp(-k * (x - l0))); }; for (double curve_s = 0.0; curve_s < (end_s - start_s); curve_s += config_.path_resolution()) { const double l = curve.Evaluate(0, curve_s); path_cost += l * l * config_.path_l_cost() * quasi_softmax(std::fabs(l)); const double dl = std::fabs(curve.Evaluate(1, curve_s)); if (IsOffRoad(curve_s + start_s, l, dl, is_change_lane_path_)) { cost.cost_items[ComparableCost::OUT_OF_BOUNDARY] = true; } path_cost += dl * dl * config_.path_dl_cost(); const double ddl = std::fabs(curve.Evaluate(2, curve_s)); path_cost += ddl * ddl * config_.path_ddl_cost(); } path_cost *= config_.path_resolution(); if (curr_level == total_level) { const double end_l = curve.Evaluate(0, end_s - start_s); path_cost += std::sqrt(end_l - init_sl_point_.l() / 2.0) * config_.path_end_l_cost(); } cost.smoothness_cost = path_cost; return cost; } bool TrajectoryCost::IsOffRoad(const double ref_s, const double l, const double dl, const bool is_change_lane_path) { static constexpr double kIgnoreDistance = 5.0; if (ref_s - init_sl_point_.s() < kIgnoreDistance) { return false; } Vec2d rear_center(0.0, l); const auto &param = common::VehicleConfigHelper::GetConfig().vehicle_param(); Vec2d vec_to_center( (param.front_edge_to_center() - param.back_edge_to_center()) / 2.0, (param.left_edge_to_center() - param.right_edge_to_center()) / 2.0); Vec2d rear_center_to_center = vec_to_center.rotate(std::atan(dl)); Vec2d center = rear_center + rear_center_to_center; Vec2d front_center = center + rear_center_to_center; const double buffer = 0.1; // in meters const double r_w = (param.left_edge_to_center() + param.right_edge_to_center()) / 2.0; const double r_l = param.back_edge_to_center(); const double r = std::sqrt(r_w * r_w + r_l * r_l); double left_width = 0.0; double right_width = 0.0; reference_line_->GetLaneWidth(ref_s, &left_width, &right_width); double left_bound = std::max(init_sl_point_.l() + r + buffer, left_width); double right_bound = std::min(init_sl_point_.l() - r - buffer, -right_width); if (rear_center.y() + r + buffer / 2.0 > left_bound || rear_center.y() - r - buffer / 2.0 < right_bound) { return true; } if (front_center.y() + r + buffer / 2.0 > left_bound || front_center.y() - r - buffer / 2.0 < right_bound) { return true; } return false; } ComparableCost TrajectoryCost::CalculateStaticObstacleCost( const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s) { ComparableCost obstacle_cost; for (double curr_s = start_s; curr_s <= end_s; curr_s += config_.path_resolution()) { const double curr_l = curve.Evaluate(0, curr_s - start_s); for (const auto &obs_sl_boundary : static_obstacle_sl_boundaries_) { obstacle_cost += GetCostFromObsSL(curr_s, curr_l, obs_sl_boundary); } } obstacle_cost.safety_cost *= config_.path_resolution(); return obstacle_cost; } ComparableCost TrajectoryCost::CalculateDynamicObstacleCost( const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s) const { ComparableCost obstacle_cost; if (dynamic_obstacle_boxes_.empty()) { return obstacle_cost; } double time_stamp = 0.0; for (size_t index = 0; index < num_of_time_stamps_; ++index, time_stamp += config_.eval_time_interval()) { common::SpeedPoint speed_point; heuristic_speed_data_.EvaluateByTime(time_stamp, &speed_point); double ref_s = speed_point.s() + init_sl_point_.s(); if (ref_s < start_s) { continue; } if (ref_s > end_s) { break; } const double s = ref_s - start_s; // s on spline curve const double l = curve.Evaluate(0, s); const double dl = curve.Evaluate(1, s); const common::SLPoint sl = common::util::PointFactory::ToSLPoint(ref_s, l); const Box2d ego_box = GetBoxFromSLPoint(sl, dl); for (const auto &obstacle_trajectory : dynamic_obstacle_boxes_) { obstacle_cost += GetCostBetweenObsBoxes(ego_box, obstacle_trajectory.at(index)); } } static constexpr double kDynamicObsWeight = 1e-6; obstacle_cost.safety_cost *= (config_.eval_time_interval() * kDynamicObsWeight); return obstacle_cost; } ComparableCost TrajectoryCost::GetCostFromObsSL( const double adc_s, const double adc_l, const SLBoundary &obs_sl_boundary) { const auto &vehicle_param = common::VehicleConfigHelper::Instance()->GetConfig().vehicle_param(); ComparableCost obstacle_cost; if (obs_sl_boundary.start_l() * obs_sl_boundary.end_l() <= 0.0) { return obstacle_cost; } const double adc_front_s = adc_s + vehicle_param.front_edge_to_center(); const double adc_end_s = adc_s - vehicle_param.back_edge_to_center(); const double adc_left_l = adc_l + vehicle_param.left_edge_to_center(); const double adc_right_l = adc_l - vehicle_param.right_edge_to_center(); if (adc_left_l + FLAGS_lateral_ignore_buffer < obs_sl_boundary.start_l() || adc_right_l - FLAGS_lateral_ignore_buffer > obs_sl_boundary.end_l()) { return obstacle_cost; } bool no_overlap = ((adc_front_s < obs_sl_boundary.start_s() || adc_end_s > obs_sl_boundary.end_s()) || // longitudinal (adc_left_l + 0.1 < obs_sl_boundary.start_l() || adc_right_l - 0.1 > obs_sl_boundary.end_l())); // lateral if (!no_overlap) { obstacle_cost.cost_items[ComparableCost::HAS_COLLISION] = true; } // if obstacle is behind ADC, ignore its cost contribution. if (adc_front_s > obs_sl_boundary.end_s()) { return obstacle_cost; } const double delta_l = std::fmax(adc_right_l - obs_sl_boundary.end_l(), obs_sl_boundary.start_l() - adc_left_l); /* AWARN << "adc_s: " << adc_s << "; adc_left_l: " << adc_left_l << "; adc_right_l: " << adc_right_l << "; delta_l = " << delta_l; AWARN << obs_sl_boundary.ShortDebugString(); */ static constexpr double kSafeDistance = 0.6; if (delta_l < kSafeDistance) { obstacle_cost.safety_cost += config_.obstacle_collision_cost() * Sigmoid(config_.obstacle_collision_distance() - delta_l); } return obstacle_cost; } // Simple version: calculate obstacle cost by distance ComparableCost TrajectoryCost::GetCostBetweenObsBoxes( const Box2d &ego_box, const Box2d &obstacle_box) const { ComparableCost obstacle_cost; const double distance = obstacle_box.DistanceTo(ego_box); if (distance > config_.obstacle_ignore_distance()) { return obstacle_cost; } obstacle_cost.safety_cost += config_.obstacle_collision_cost() * Sigmoid(config_.obstacle_collision_distance() - distance); obstacle_cost.safety_cost += 20.0 * Sigmoid(config_.obstacle_risk_distance() - distance); return obstacle_cost; } Box2d TrajectoryCost::GetBoxFromSLPoint(const common::SLPoint &sl, const double dl) const { Vec2d xy_point; reference_line_->SLToXY(sl, &xy_point); ReferencePoint reference_point = reference_line_->GetReferencePoint(sl.s()); const double one_minus_kappa_r_d = 1 - reference_point.kappa() * sl.l(); const double delta_theta = std::atan2(dl, one_minus_kappa_r_d); const double theta = common::math::NormalizeAngle(delta_theta + reference_point.heading()); return Box2d(xy_point, theta, vehicle_param_.length(), vehicle_param_.width()); } // TODO(All): optimize obstacle cost calculation time ComparableCost TrajectoryCost::Calculate(const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s, const uint32_t curr_level, const uint32_t total_level) { ComparableCost total_cost; // path cost total_cost += CalculatePathCost(curve, start_s, end_s, curr_level, total_level); // static obstacle cost total_cost += CalculateStaticObstacleCost(curve, start_s, end_s); // dynamic obstacle cost total_cost += CalculateDynamicObstacleCost(curve, start_s, end_s); return total_cost; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/road_graph/trajectory_cost_test.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/tasks/optimizers/road_graph/trajectory_cost.h" #include "gtest/gtest.h" namespace apollo { namespace planning { TEST(AllTrajectoryTests, GetCostFromObsSL) { // left nudge TrajectoryCost tc; SLBoundary obs_sl_boundary; obs_sl_boundary.set_start_s(20.0); obs_sl_boundary.set_end_s(25.0); obs_sl_boundary.set_start_l(-1.5); obs_sl_boundary.set_end_l(-0.2); auto cost = tc.GetCostFromObsSL(5.0, 3.5, obs_sl_boundary); EXPECT_FLOAT_EQ(cost.safety_cost, 0.0); EXPECT_FLOAT_EQ(cost.smoothness_cost, 0.0); EXPECT_FALSE(cost.cost_items.at(0)); EXPECT_FALSE(cost.cost_items.at(1)); EXPECT_FALSE(cost.cost_items.at(2)); // collisioned obstacle TrajectoryCost tc1; SLBoundary obs_sl_boundary1; obs_sl_boundary1.set_start_s(20.0); obs_sl_boundary1.set_end_s(25.0); obs_sl_boundary1.set_start_l(-1.5); obs_sl_boundary1.set_end_l(-0.2); auto cost1 = tc.GetCostFromObsSL(21.0, -0.5, obs_sl_boundary1); EXPECT_FLOAT_EQ(cost1.safety_cost, 825.6347); EXPECT_FLOAT_EQ(cost1.smoothness_cost, 0.0); EXPECT_TRUE(cost1.cost_items.at(0)); EXPECT_FALSE(cost1.cost_items.at(1)); EXPECT_FALSE(cost1.cost_items.at(2)); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/road_graph/trajectory_cost.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 "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/math/box2d.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/path_decision.h" #include "modules/planning/common/speed/speed_data.h" #include "modules/planning/math/curve1d/quintic_polynomial_curve1d.h" #include "modules/planning/proto/dp_poly_path_config.pb.h" #include "modules/planning/reference_line/reference_line.h" #include "modules/planning/tasks/optimizers/road_graph/comparable_cost.h" namespace apollo { namespace planning { class TrajectoryCost { public: TrajectoryCost() = default; TrajectoryCost(const DpPolyPathConfig &config, const ReferenceLine &reference_line, const bool is_change_lane_path, const std::vector<const Obstacle *> &obstacles, const common::VehicleParam &vehicle_param, const SpeedData &heuristic_speed_data, const common::SLPoint &init_sl_point, const SLBoundary &adc_sl_boundary); ComparableCost Calculate(const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s, const uint32_t curr_level, const uint32_t total_level); private: ComparableCost CalculatePathCost(const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s, const uint32_t curr_level, const uint32_t total_level); ComparableCost CalculateStaticObstacleCost( const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s); ComparableCost CalculateDynamicObstacleCost( const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s) const; ComparableCost GetCostBetweenObsBoxes( const common::math::Box2d &ego_box, const common::math::Box2d &obstacle_box) const; FRIEND_TEST(AllTrajectoryTests, GetCostFromObsSL); ComparableCost GetCostFromObsSL(const double adc_s, const double adc_l, const SLBoundary &obs_sl_boundary); common::math::Box2d GetBoxFromSLPoint(const common::SLPoint &sl, const double dl) const; bool IsOffRoad(const double ref_s, const double l, const double dl, const bool is_change_lane_path); const DpPolyPathConfig config_; const ReferenceLine *reference_line_ = nullptr; bool is_change_lane_path_ = false; const common::VehicleParam vehicle_param_; SpeedData heuristic_speed_data_; const common::SLPoint init_sl_point_; const SLBoundary adc_sl_boundary_; uint32_t num_of_time_stamps_ = 0; std::vector<std::vector<common::math::Box2d>> dynamic_obstacle_boxes_; std::vector<double> obstacle_probabilities_; std::vector<SLBoundary> static_obstacle_sl_boundaries_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/road_graph/waypoint_sampler.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_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/status/status.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/path/path_data.h" #include "modules/planning/common/path_decision.h" #include "modules/planning/common/reference_line_info.h" #include "modules/planning/common/trajectory/discretized_trajectory.h" #include "modules/planning/math/curve1d/quintic_polynomial_curve1d.h" #include "modules/planning/proto/dp_poly_path_config.pb.h" #include "modules/planning/reference_line/reference_point.h" #include "modules/planning/tasks/optimizers/road_graph/trajectory_cost.h" namespace apollo { namespace planning { class WaypointSampler { public: explicit WaypointSampler(const WaypointSamplerConfig &config) : config_(config) {} virtual ~WaypointSampler() = default; virtual void Init(const ReferenceLineInfo *reference_line_info, const common::SLPoint &init_sl_point_, const common::FrenetFramePoint &init_frenet_frame_point); virtual void SetDebugLogger(apollo::planning_internal::Debug *debug) { planning_debug_ = debug; } virtual bool SamplePathWaypoints( const common::TrajectoryPoint &init_point, std::vector<std::vector<common::SLPoint>> *const points); protected: const WaypointSamplerConfig &config_; const ReferenceLineInfo *reference_line_info_ = nullptr; common::SLPoint init_sl_point_; common::FrenetFramePoint init_frenet_frame_point_; apollo::planning_internal::Debug *planning_debug_ = nullptr; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/road_graph/waypoint_sampler.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 waypoint_sampler.cc **/ #include "modules/planning/tasks/optimizers/road_graph/waypoint_sampler.h" #include "cyber/common/log.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/cartesian_frenet_conversion.h" #include "modules/common/util/point_factory.h" #include "modules/common/util/util.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/ego_info.h" #include "modules/planning/common/path/frenet_frame_path.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/tasks/deciders/lane_change_decider/lane_change_decider.h" namespace apollo { namespace planning { void WaypointSampler::Init( const ReferenceLineInfo *reference_line_info, const common::SLPoint &init_sl_point, const common::FrenetFramePoint &init_frenet_frame_point) { reference_line_info_ = reference_line_info; init_sl_point_ = init_sl_point; init_frenet_frame_point_ = init_frenet_frame_point; } bool WaypointSampler::SamplePathWaypoints( const common::TrajectoryPoint &init_point, std::vector<std::vector<common::SLPoint>> *const points) { CHECK_NOTNULL(points); points->clear(); points->insert(points->begin(), std::vector<common::SLPoint>{init_sl_point_}); const double kMinSampleDistance = 40.0; const double total_length = std::fmin( init_sl_point_.s() + std::fmax(init_point.v() * 8.0, kMinSampleDistance), reference_line_info_->reference_line().Length()); const auto &vehicle_config = common::VehicleConfigHelper::Instance()->GetConfig(); const double half_adc_width = vehicle_config.vehicle_param().width() / 2.0; const double num_sample_per_level = FLAGS_use_navigation_mode ? config_.navigator_sample_num_each_level() : config_.sample_points_num_each_level(); static constexpr double kSamplePointLookForwardTime = 4.0; const double level_distance = common::math::Clamp(init_point.v() * kSamplePointLookForwardTime, config_.step_length_min(), config_.step_length_max()); double accumulated_s = init_sl_point_.s(); double prev_s = accumulated_s; static constexpr size_t kNumLevel = 3; for (size_t i = 0; i < kNumLevel && accumulated_s < total_length; ++i) { accumulated_s += level_distance; if (accumulated_s + level_distance / 2.0 > total_length) { accumulated_s = total_length; } const double s = std::fmin(accumulated_s, total_length); static constexpr double kMinAllowedSampleStep = 1.0; if (std::fabs(s - prev_s) < kMinAllowedSampleStep) { continue; } prev_s = s; double left_width = 0.0; double right_width = 0.0; reference_line_info_->reference_line().GetLaneWidth(s, &left_width, &right_width); static constexpr double kBoundaryBuff = 0.20; const double eff_right_width = right_width - half_adc_width - kBoundaryBuff; const double eff_left_width = left_width - half_adc_width - kBoundaryBuff; // the heuristic shift of L for lane change scenarios const double delta_dl = 1.2 / 20.0; const double kChangeLaneDeltaL = common::math::Clamp( level_distance * (std::fabs(init_frenet_frame_point_.dl()) + delta_dl), 1.2, 3.5); double kDefaultUnitL = kChangeLaneDeltaL / (num_sample_per_level - 1); if (reference_line_info_->IsChangeLanePath() && LaneChangeDecider::IsClearToChangeLane(reference_line_info_)) { kDefaultUnitL = 1.0; } const double sample_l_range = kDefaultUnitL * (num_sample_per_level - 1); double sample_right_boundary = -eff_right_width; double sample_left_boundary = eff_left_width; static constexpr double kLargeDeviationL = 1.75; static constexpr double kTwentyMilesPerHour = 8.94; if (reference_line_info_->IsChangeLanePath() || std::fabs(init_sl_point_.l()) > kLargeDeviationL) { if (injector_->ego_info()->start_point().v() > kTwentyMilesPerHour) { sample_right_boundary = std::fmin(-eff_right_width, init_sl_point_.l()); sample_left_boundary = std::fmax(eff_left_width, init_sl_point_.l()); if (init_sl_point_.l() > eff_left_width) { sample_right_boundary = std::fmax( sample_right_boundary, init_sl_point_.l() - sample_l_range); } if (init_sl_point_.l() < eff_right_width) { sample_left_boundary = std::fmin(sample_left_boundary, init_sl_point_.l() + sample_l_range); } } } std::vector<double> sample_l; if (reference_line_info_->IsChangeLanePath() && LaneChangeDecider::IsClearToChangeLane(reference_line_info_)) { sample_l.push_back(reference_line_info_->OffsetToOtherReferenceLine()); } else { common::util::uniform_slice( sample_right_boundary, sample_left_boundary, static_cast<uint32_t>(num_sample_per_level - 1), &sample_l); } std::vector<common::SLPoint> level_points; planning_internal::SampleLayerDebug sample_layer_debug; for (size_t j = 0; j < sample_l.size(); ++j) { common::SLPoint sl = common::util::PointFactory::ToSLPoint(s, sample_l[j]); sample_layer_debug.add_sl_point()->CopyFrom(sl); level_points.push_back(std::move(sl)); } if (!level_points.empty()) { planning_debug_->mutable_planning_data() ->mutable_dp_poly_graph() ->add_sample_layer() ->CopyFrom(sample_layer_debug); points->emplace_back(level_points); } } return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/road_graph/dp_road_graph.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 dp_road_graph.cc **/ #include "modules/planning/tasks/optimizers/road_graph/dp_road_graph.h" #include "cyber/common/log.h" #include "cyber/task/task.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/cartesian_frenet_conversion.h" #include "modules/common_msgs/basic_msgs/error_code.pb.h" #include "modules/common/util/util.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/path/frenet_frame_path.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/math/curve1d/quintic_polynomial_curve1d.h" #include "modules/common_msgs/planning_msgs/planning_internal.pb.h" #include "modules/planning/proto/planning_status.pb.h" namespace apollo { namespace planning { DpRoadGraph::DpRoadGraph(const DpPolyPathConfig &config, const ReferenceLineInfo &reference_line_info, const SpeedData &speed_data) : config_(config), reference_line_info_(reference_line_info), reference_line_(reference_line_info.reference_line()), speed_data_(speed_data) {} bool DpRoadGraph::FindPathTunnel(const common::TrajectoryPoint &init_point, const std::vector<const Obstacle *> &obstacles, PathData *const path_data) { CHECK_NOTNULL(path_data); init_point_ = init_point; if (!reference_line_.XYToSL(init_point_.path_point(), &init_sl_point_)) { AERROR << "Fail to create init_sl_point from : " << init_point.DebugString(); return false; } init_frenet_frame_point_ = reference_line_.GetFrenetPoint(init_point_.path_point()); waypoint_sampler_->Init(&reference_line_info_, init_sl_point_, init_frenet_frame_point_); waypoint_sampler_->SetDebugLogger(planning_debug_); std::vector<DpRoadGraphNode> min_cost_path; if (!GenerateMinCostPath(obstacles, &min_cost_path)) { AERROR << "Fail to generate graph!"; return false; } std::vector<common::FrenetFramePoint> frenet_path; double accumulated_s = min_cost_path.front().sl_point.s(); const double path_resolution = config_.path_resolution(); for (size_t i = 1; i < min_cost_path.size(); ++i) { const auto &prev_node = min_cost_path[i - 1]; const auto &cur_node = min_cost_path[i]; const double path_length = cur_node.sl_point.s() - prev_node.sl_point.s(); double current_s = 0.0; const auto &curve = cur_node.min_cost_curve; while (current_s + path_resolution / 2.0 < path_length) { const double l = curve.Evaluate(0, current_s); const double dl = curve.Evaluate(1, current_s); const double ddl = curve.Evaluate(2, current_s); common::FrenetFramePoint frenet_frame_point; frenet_frame_point.set_s(accumulated_s + current_s); frenet_frame_point.set_l(l); frenet_frame_point.set_dl(dl); frenet_frame_point.set_ddl(ddl); frenet_path.push_back(std::move(frenet_frame_point)); current_s += path_resolution; } if (i == min_cost_path.size() - 1) { accumulated_s += current_s; } else { accumulated_s += path_length; } } path_data->SetReferenceLine(&reference_line_); path_data->SetFrenetPath(FrenetFramePath(std::move(frenet_path))); return true; } bool DpRoadGraph::GenerateMinCostPath( const std::vector<const Obstacle *> &obstacles, std::vector<DpRoadGraphNode> *min_cost_path) { ACHECK(min_cost_path != nullptr); std::vector<std::vector<common::SLPoint>> path_waypoints; if (!waypoint_sampler_->SamplePathWaypoints(init_point_, &path_waypoints) || path_waypoints.size() < 1) { AERROR << "Fail to sample path waypoints! reference_line_length = " << reference_line_.Length(); return false; } const auto &vehicle_config = common::VehicleConfigHelper::Instance()->GetConfig(); TrajectoryCost trajectory_cost( config_, reference_line_, reference_line_info_.IsChangeLanePath(), obstacles, vehicle_config.vehicle_param(), speed_data_, init_sl_point_, reference_line_info_.AdcSlBoundary()); std::list<std::list<DpRoadGraphNode>> graph_nodes; // find one point from first row const auto &first_row = path_waypoints.front(); size_t nearest_i = 0; for (size_t i = 1; i < first_row.size(); ++i) { if (std::fabs(first_row[i].l() - init_sl_point_.l()) < std::fabs(first_row[nearest_i].l() - init_sl_point_.l())) { nearest_i = i; } } graph_nodes.emplace_back(); graph_nodes.back().emplace_back(first_row[nearest_i], nullptr, ComparableCost()); auto &front = graph_nodes.front().front(); size_t total_level = path_waypoints.size(); for (size_t level = 1; level < path_waypoints.size(); ++level) { const auto &prev_dp_nodes = graph_nodes.back(); const auto &level_points = path_waypoints[level]; graph_nodes.emplace_back(); std::vector<std::future<void>> results; for (size_t i = 0; i < level_points.size(); ++i) { const auto &cur_point = level_points[i]; graph_nodes.back().emplace_back(cur_point, nullptr); auto msg = std::make_shared<RoadGraphMessage>( prev_dp_nodes, level, total_level, &trajectory_cost, &front, &(graph_nodes.back().back())); if (FLAGS_enable_multi_thread_in_dp_poly_path) { results.emplace_back(cyber::Async(&DpRoadGraph::UpdateNode, this, msg)); } else { UpdateNode(msg); } } if (FLAGS_enable_multi_thread_in_dp_poly_path) { for (auto &result : results) { result.get(); } } } // find best path DpRoadGraphNode fake_head; for (const auto &cur_dp_node : graph_nodes.back()) { fake_head.UpdateCost(&cur_dp_node, cur_dp_node.min_cost_curve, cur_dp_node.min_cost); } const auto *min_cost_node = &fake_head; while (min_cost_node->min_cost_prev_node) { min_cost_node = min_cost_node->min_cost_prev_node; min_cost_path->push_back(*min_cost_node); } if (min_cost_node != &graph_nodes.front().front()) { return false; } std::reverse(min_cost_path->begin(), min_cost_path->end()); for (const auto &node : *min_cost_path) { ADEBUG << "min_cost_path: " << node.sl_point.ShortDebugString(); planning_debug_->mutable_planning_data() ->mutable_dp_poly_graph() ->add_min_cost_point() ->CopyFrom(node.sl_point); } return true; } void DpRoadGraph::UpdateNode(const std::shared_ptr<RoadGraphMessage> &msg) { CHECK_NOTNULL(msg); CHECK_NOTNULL(msg->trajectory_cost); CHECK_NOTNULL(msg->front); CHECK_NOTNULL(msg->cur_node); for (const auto &prev_dp_node : msg->prev_nodes) { const auto &prev_sl_point = prev_dp_node.sl_point; const auto &cur_point = msg->cur_node->sl_point; double init_dl = 0.0; double init_ddl = 0.0; if (msg->level == 1) { init_dl = init_frenet_frame_point_.dl(); init_ddl = init_frenet_frame_point_.ddl(); } QuinticPolynomialCurve1d curve(prev_sl_point.l(), init_dl, init_ddl, cur_point.l(), 0.0, 0.0, cur_point.s() - prev_sl_point.s()); if (!IsValidCurve(curve)) { continue; } const auto cost = msg->trajectory_cost->Calculate(curve, prev_sl_point.s(), cur_point.s(), msg->level, msg->total_level) + prev_dp_node.min_cost; msg->cur_node->UpdateCost(&prev_dp_node, curve, cost); } // try to connect the current point with the first point directly if (reference_line_info_.IsChangeLanePath() && msg->level >= 2) { const double init_dl = init_frenet_frame_point_.dl(); const double init_ddl = init_frenet_frame_point_.ddl(); QuinticPolynomialCurve1d curve( init_sl_point_.l(), init_dl, init_ddl, msg->cur_node->sl_point.l(), 0.0, 0.0, msg->cur_node->sl_point.s() - init_sl_point_.s()); if (!IsValidCurve(curve)) { return; } const auto cost = msg->trajectory_cost->Calculate( curve, init_sl_point_.s(), msg->cur_node->sl_point.s(), msg->level, msg->total_level); msg->cur_node->UpdateCost(msg->front, curve, cost); } } bool DpRoadGraph::IsValidCurve(const QuinticPolynomialCurve1d &curve) const { static constexpr double kMaxLateralDistance = 20.0; for (double s = 0.0; s < curve.ParamLength(); s += 2.0) { const double l = curve.Evaluate(0, s); if (std::fabs(l) > kMaxLateralDistance) { return false; } } return true; } void DpRoadGraph::GetCurveCost(TrajectoryCost trajectory_cost, const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s, const uint32_t curr_level, const uint32_t total_level, ComparableCost *cost) { *cost = trajectory_cost.Calculate(curve, start_s, end_s, curr_level, total_level); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/road_graph/comparable_cost_test.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/tasks/optimizers/road_graph/comparable_cost.h" #include "gtest/gtest.h" namespace apollo { namespace planning { TEST(ComparableCost, simple) { ComparableCost cc; EXPECT_FLOAT_EQ(cc.safety_cost, 0.0); EXPECT_FLOAT_EQ(cc.smoothness_cost, 0.0); EXPECT_FALSE(cc.cost_items[ComparableCost::HAS_COLLISION]); EXPECT_FALSE(cc.cost_items[ComparableCost::OUT_OF_BOUNDARY]); EXPECT_FALSE(cc.cost_items[ComparableCost::OUT_OF_LANE]); } TEST(ComparableCost, add_cost) { ComparableCost cc1(true, false, false, 10.12, 2.51); ComparableCost cc2(false, false, true, 6.1, 3.45); ComparableCost cc = cc1 + cc2; EXPECT_TRUE(cc.cost_items[ComparableCost::HAS_COLLISION]); EXPECT_FALSE(cc.cost_items[ComparableCost::OUT_OF_BOUNDARY]); EXPECT_TRUE(cc.cost_items[ComparableCost::OUT_OF_LANE]); EXPECT_FLOAT_EQ(cc.safety_cost, 16.22); EXPECT_FLOAT_EQ(cc.smoothness_cost, 5.96); EXPECT_GT(cc1, cc2); cc1 += cc2; EXPECT_TRUE(cc1.cost_items[ComparableCost::HAS_COLLISION]); EXPECT_FALSE(cc1.cost_items[ComparableCost::OUT_OF_BOUNDARY]); EXPECT_TRUE(cc1.cost_items[ComparableCost::OUT_OF_LANE]); EXPECT_FLOAT_EQ(cc1.safety_cost, 16.22); EXPECT_FLOAT_EQ(cc1.smoothness_cost, 5.96); ComparableCost cc3(true, false, false, 10.12, 2.51); ComparableCost cc4(false, true, true, 6.1, 3.45); EXPECT_GT(cc3, cc4); ComparableCost cc5(false, false, false, 10.12, 2.51); ComparableCost cc6(false, true, true, 6.1, 3.45); EXPECT_LT(cc5, cc6); ComparableCost cc7 = cc5 + cc6; EXPECT_FALSE(cc7.cost_items[ComparableCost::HAS_COLLISION]); EXPECT_TRUE(cc7.cost_items[ComparableCost::OUT_OF_BOUNDARY]); EXPECT_TRUE(cc7.cost_items[ComparableCost::OUT_OF_LANE]); EXPECT_FLOAT_EQ(cc7.safety_cost, 16.22); EXPECT_FLOAT_EQ(cc7.smoothness_cost, 5.96); EXPECT_LT(cc5, cc6); } TEST(ComparableCost, compare_to) { ComparableCost cc1(true, false, false, 10.12, 2.51); ComparableCost cc2(false, false, true, 6.1, 3.45); EXPECT_GT(cc1, cc2); ComparableCost cc3(false, true, false, 10.12, 2.51); ComparableCost cc4(false, false, false, 6.1, 3.45); EXPECT_GT(cc3, cc4); ComparableCost cc5(false, false, true, 10.12, 2.51); ComparableCost cc6(false, false, false, 6.1, 3.45); EXPECT_GT(cc5, cc6); ComparableCost cc7(false, false, false, 10.12, 2.51); ComparableCost cc8(false, false, false, 6.1, 3.45); EXPECT_GT(cc7, cc8); ComparableCost cc9(false, false, false, 0.12, 2.51); ComparableCost cc10(false, false, false, 6.1, 3.45); EXPECT_LT(cc9, cc10); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/road_graph/dp_road_graph.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 dp_road_graph.h **/ #pragma once #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/status/status.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/path/path_data.h" #include "modules/planning/common/path_decision.h" #include "modules/planning/common/reference_line_info.h" #include "modules/planning/common/speed/speed_data.h" #include "modules/planning/common/trajectory/discretized_trajectory.h" #include "modules/planning/math/curve1d/quintic_polynomial_curve1d.h" #include "modules/planning/proto/dp_poly_path_config.pb.h" #include "modules/planning/reference_line/reference_point.h" #include "modules/planning/tasks/optimizers/road_graph/trajectory_cost.h" #include "modules/planning/tasks/optimizers/road_graph/waypoint_sampler.h" namespace apollo { namespace planning { class DpRoadGraph { public: DpRoadGraph(const DpPolyPathConfig &config, const ReferenceLineInfo &reference_line_info, const SpeedData &speed_data); ~DpRoadGraph() = default; bool FindPathTunnel(const common::TrajectoryPoint &init_point, const std::vector<const Obstacle *> &obstacles, PathData *const path_data); void SetDebugLogger(apollo::planning_internal::Debug *debug) { planning_debug_ = debug; } void SetWaypointSampler(WaypointSampler *waypoint_sampler) { waypoint_sampler_.reset(waypoint_sampler); } private: /** * an private inner struct for the dp algorithm */ struct DpRoadGraphNode { public: DpRoadGraphNode() = default; DpRoadGraphNode(const common::SLPoint point_sl, const DpRoadGraphNode *node_prev) : sl_point(point_sl), min_cost_prev_node(node_prev) {} DpRoadGraphNode(const common::SLPoint point_sl, const DpRoadGraphNode *node_prev, const ComparableCost &cost) : sl_point(point_sl), min_cost_prev_node(node_prev), min_cost(cost) {} void UpdateCost(const DpRoadGraphNode *node_prev, const QuinticPolynomialCurve1d &curve, const ComparableCost &cost) { if (cost <= min_cost) { min_cost = cost; min_cost_prev_node = node_prev; min_cost_curve = curve; } } common::SLPoint sl_point; const DpRoadGraphNode *min_cost_prev_node = nullptr; ComparableCost min_cost = {true, true, true, std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity()}; QuinticPolynomialCurve1d min_cost_curve; }; bool GenerateMinCostPath(const std::vector<const Obstacle *> &obstacles, std::vector<DpRoadGraphNode> *min_cost_path); bool IsValidCurve(const QuinticPolynomialCurve1d &curve) const; void GetCurveCost(TrajectoryCost trajectory_cost, const QuinticPolynomialCurve1d &curve, const double start_s, const double end_s, const uint32_t curr_level, const uint32_t total_level, ComparableCost *cost); struct RoadGraphMessage { RoadGraphMessage(const std::list<DpRoadGraphNode> &_prev_nodes, const uint32_t _level, const uint32_t _total_level, TrajectoryCost *_trajectory_cost, DpRoadGraphNode *_front, DpRoadGraphNode *_cur_node) : prev_nodes(_prev_nodes), level(_level), total_level(_total_level), trajectory_cost(_trajectory_cost), front(_front), cur_node(_cur_node) {} const std::list<DpRoadGraphNode> &prev_nodes; const uint32_t level; const uint32_t total_level; TrajectoryCost *trajectory_cost = nullptr; DpRoadGraphNode *front = nullptr; DpRoadGraphNode *cur_node = nullptr; }; void UpdateNode(const std::shared_ptr<RoadGraphMessage> &msg); private: DpPolyPathConfig config_; common::TrajectoryPoint init_point_; const ReferenceLineInfo &reference_line_info_; const ReferenceLine &reference_line_; SpeedData speed_data_; common::SLPoint init_sl_point_; common::FrenetFramePoint init_frenet_frame_point_; apollo::planning_internal::Debug *planning_debug_ = nullptr; std::unique_ptr<WaypointSampler> waypoint_sampler_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/road_graph/comparable_cost.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 namespace apollo { namespace planning { class ComparableCost { public: ComparableCost() = default; ComparableCost(const bool has_collision, const bool out_of_boundary, const bool out_of_lane, const double safety_cost_, const double smoothness_cost_) : safety_cost(safety_cost_), smoothness_cost(smoothness_cost_) { cost_items[HAS_COLLISION] = has_collision; cost_items[OUT_OF_BOUNDARY] = out_of_boundary; cost_items[OUT_OF_LANE] = out_of_lane; } ComparableCost(const ComparableCost &) = default; int CompareTo(const ComparableCost &other) const { for (size_t i = 0; i < cost_items.size(); ++i) { if (cost_items[i]) { if (other.cost_items[i]) { continue; } else { return 1; } } else { if (other.cost_items[i]) { return -1; } else { continue; } } } static constexpr double kEpsilon = 1e-12; const double diff = safety_cost + smoothness_cost - other.safety_cost - other.smoothness_cost; if (std::fabs(diff) < kEpsilon) { return 0; } else if (diff > 0) { return 1; } else { return -1; } } ComparableCost operator+(const ComparableCost &other) { ComparableCost lhs = *this; lhs += other; return lhs; } ComparableCost &operator+=(const ComparableCost &other) { for (size_t i = 0; i < cost_items.size(); ++i) { cost_items[i] = (cost_items[i] || other.cost_items[i]); } safety_cost += other.safety_cost; smoothness_cost += other.smoothness_cost; return *this; } bool operator>(const ComparableCost &other) const { return this->CompareTo(other) > 0; } bool operator>=(const ComparableCost &other) const { return this->CompareTo(other) >= 0; } bool operator<(const ComparableCost &other) const { return this->CompareTo(other) < 0; } bool operator<=(const ComparableCost &other) const { return this->CompareTo(other) <= 0; } /* * cost_items represents an array of factors that affect the cost, * The level is from most critical to less critical. * It includes: * (0) has_collision or out_of_boundary * (1) out_of_lane * * NOTICE: Items could have same critical levels */ static const size_t HAS_COLLISION = 0; static const size_t OUT_OF_BOUNDARY = 1; static const size_t OUT_OF_LANE = 2; std::array<bool, 3> cost_items = {{false, false, false}}; // cost from distance to obstacles or boundaries double safety_cost = 0.0f; // cost from deviation from lane center, path curvature etc double smoothness_cost = 0.0f; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/piecewise_jerk_path/piecewise_jerk_path_optimizer.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 piecewise_jerk_path_optimizer.h **/ #pragma once #include <memory> #include <utility> #include <vector> #include "modules/planning/tasks/optimizers/path_optimizer.h" namespace apollo { namespace planning { class PiecewiseJerkPathOptimizer : public PathOptimizer { public: PiecewiseJerkPathOptimizer( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); virtual ~PiecewiseJerkPathOptimizer() = default; private: common::Status Process(const SpeedData& speed_data, const ReferenceLine& reference_line, const common::TrajectoryPoint& init_point, const bool path_reusable, PathData* const path_data) override; common::TrajectoryPoint InferFrontAxeCenterFromRearAxeCenter( const common::TrajectoryPoint& traj_point); std::vector<common::PathPoint> ConvertPathPointRefFromFrontAxeToRearAxe( const PathData& path_data); /** * @brief * * @param init_state path start point * @param end_state path end point * @param path_reference_l_ref: a vector with default value 0.0 * @param path_reference_size: length of learning model output * @param delta_s: path point spatial distance * @param is_valid_path_reference: whether using learning model output or not * @param lat_boundaries: path boundaries * @param ddl_bounds: constains * @param w: weighting scales * @param max_iter: optimization max interations * @param ptr_x: optimization result of x * @param ptr_dx: optimization result of dx * @param ptr_ddx: optimization result of ddx * @return true * @return false */ bool OptimizePath( const std::pair<std::array<double, 3>, std::array<double, 3>>& init_state, const std::array<double, 3>& end_state, std::vector<double> path_reference_l_ref, const size_t path_reference_size, const double delta_s, const bool is_valid_path_reference, const std::vector<std::pair<double, double>>& lat_boundaries, const std::vector<std::pair<double, double>>& ddl_bounds, const std::array<double, 5>& w, const int max_iter, std::vector<double>* ptr_x, std::vector<double>* ptr_dx, std::vector<double>* ptr_ddx); FrenetFramePath ToPiecewiseJerkPath(const std::vector<double>& l, const std::vector<double>& dl, const std::vector<double>& ddl, const double delta_s, const double start_s) const; double EstimateJerkBoundary(const double vehicle_speed, const double axis_distance, const double max_steering_rate) const; double GaussianWeighting(const double x, const double peak_weighting, const double peak_weighting_x) const; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/piecewise_jerk_path/piecewise_jerk_path_ipopt_solver.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 piecewise_jerk_path_ipopt_solver.cc **/ #include "modules/planning/tasks/optimizers/piecewise_jerk_path/piecewise_jerk_path_ipopt_solver.h" #include "cyber/common/log.h" namespace apollo { namespace planning { PiecewiseJerkPathIpoptSolver::PiecewiseJerkPathIpoptSolver( const double x_init, const double dx_init, const double ddx_init, const double delta_s, const double dddx_max, std::vector<std::pair<double, double>> d_bounds) { CHECK_GT(d_bounds.size(), 1U); x_init_ = x_init; dx_init_ = dx_init; ddx_init_ = ddx_init; CHECK_GT(delta_s, 0.0); delta_s_ = delta_s; CHECK_GT(dddx_max, 0.0); dddx_max_ = dddx_max; num_of_points_ = static_cast<int>(d_bounds.size()); num_of_variables_ = 3 * num_of_points_; num_of_constraints_ = 3 * (num_of_points_ - 1); d_bounds_ = std::move(d_bounds); } void PiecewiseJerkPathIpoptSolver::set_objective_weights(const double w_x, const double w_dx, const double w_ddx, const double w_dddx, const double w_obs) { w_x_ = w_x; w_dx_ = w_dx; w_ddx_ = w_ddx; w_dddx_ = w_dddx; w_obs_ = w_obs; } bool PiecewiseJerkPathIpoptSolver::get_nlp_info(int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) { // variables n = num_of_variables_; // constraints m = num_of_constraints_; nnz_jac_g = 11 * (num_of_points_ - 1); // none zero hessian and lagrange nnz_h_lag = num_of_variables_ + num_of_points_ - 1; index_style = IndexStyleEnum::C_STYLE; return true; } bool PiecewiseJerkPathIpoptSolver::get_bounds_info(int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) { const double LARGE_VALUE = 1.0; // bounds for variables // x bounds; for (int i = 0; i < num_of_points_; ++i) { x_l[i] = d_bounds_[i].first; x_u[i] = d_bounds_[i].second; } x_l[0] = x_init_; x_u[0] = x_init_; // dx bounds int offset = num_of_points_; for (int i = 0; i < num_of_points_; ++i) { x_l[offset + i] = -LARGE_VALUE; x_u[offset + i] = LARGE_VALUE; } x_l[offset] = dx_init_; x_u[offset] = dx_init_; // ddx bounds; offset = 2 * num_of_points_; for (int i = 0; i < num_of_points_; ++i) { x_l[offset + i] = -LARGE_VALUE; x_u[offset + i] = LARGE_VALUE; } x_l[offset] = ddx_init_; x_u[offset] = ddx_init_; // bounds for constraints // jerk bounds for (int i = 0; i + 1 < num_of_points_; ++i) { g_l[i] = -dddx_max_; g_u[i] = dddx_max_; } // speed increment offset = num_of_points_ - 1; for (int i = 0; i + 1 < num_of_points_; ++i) { g_l[offset + i] = g_u[offset + i] = 0.0; } // position increment offset = 2 * (num_of_points_ - 1); for (int i = 0; i + 1 < num_of_points_; ++i) { g_l[offset + i] = g_u[offset + i] = 0.0; } return true; } bool PiecewiseJerkPathIpoptSolver::get_starting_point(int n, bool init_x, double* x, bool init_z, double* z_L, double* z_U, int m, bool init_lambda, double* lambda) { CHECK_EQ(num_of_variables_, n); auto offset_dx = num_of_points_; auto offset_ddx = num_of_points_ + num_of_points_; for (int i = 0; i < num_of_points_; ++i) { x[i] = 0.0; x[offset_dx + i] = 0.0; x[offset_ddx + i] = 0.0; } x[0] = x_init_; x[offset_dx] = dx_init_; x[offset_ddx] = ddx_init_; return true; } bool PiecewiseJerkPathIpoptSolver::eval_f(int n, const double* x, bool new_x, double& obj_value) { obj_value = 0.0; int offset_dx = num_of_points_; int offset_ddx = 2 * num_of_points_; for (int i = 0; i < num_of_points_; ++i) { // d obj_value += x[i] * x[i] * w_x_; // d_prime obj_value += x[offset_dx + i] * x[offset_dx + i] * w_dx_; // d_pprime obj_value += x[offset_ddx + i] * x[offset_ddx + i] * w_ddx_; // d_ppprime if (i > 0) { // d_pprime1 - d_pprime0 auto dddx = (x[offset_ddx + i] - x[offset_ddx + i - 1]) / delta_s_; obj_value += dddx * dddx * w_dddx_; } // obstacle auto dist = x[i] - (d_bounds_[i].first + d_bounds_[i].second) * 0.5; obj_value += dist * dist * w_obs_; } return true; } bool PiecewiseJerkPathIpoptSolver::eval_grad_f(int n, const double* x, bool new_x, double* grad_f) { std::fill(grad_f, grad_f + n, 0.0); int offset_dx = num_of_points_; int offset_ddx = 2 * num_of_points_; for (int i = 0; i < num_of_points_; ++i) { grad_f[i] = 2.0 * x[i] * w_x_ + 2.0 * (x[i] - (d_bounds_[i].first + d_bounds_[i].second) * 0.5) * w_obs_; grad_f[offset_dx + i] = 2.0 * x[offset_dx + i] * w_dx_; grad_f[offset_ddx + i] = 2.0 * x[offset_ddx + i] * w_ddx_; } for (int i = 1; i < num_of_points_; ++i) { auto delta_ddx = x[offset_ddx + i] - x[offset_ddx + i - 1]; grad_f[offset_ddx + i - 1] += -2.0 * delta_ddx / delta_s_ / delta_s_ * w_dddx_; grad_f[offset_ddx + i] += 2.0 * delta_ddx / delta_s_ / delta_s_ * w_dddx_; } return true; } bool PiecewiseJerkPathIpoptSolver::eval_g(int n, const double* x, bool new_x, int m, double* g) { std::fill(g, g + m, 0.0); int offset_v = num_of_points_; int offset_a = 2 * num_of_points_; for (int i = 0; i + 1 < num_of_points_; ++i) { g[i] = (x[offset_a + i + 1] - x[offset_a + i]) / delta_s_; } for (int i = 0; i + 1 < num_of_points_; ++i) { double p0 = x[i]; double v0 = x[offset_v + i]; double a0 = x[offset_a + i]; double p1 = x[i + 1]; double v1 = x[offset_v + i + 1]; double a1 = x[offset_a + i + 1]; double j = (a1 - a0) / delta_s_; double end_v = v0 + a0 * delta_s_ + 0.5 * j * delta_s_ * delta_s_; double end_p = p0 + v0 * delta_s_ + 0.5 * a0 * delta_s_ * delta_s_ + j * delta_s_ * delta_s_ * delta_s_ / 6.0; auto v_diff = v1 - end_v; g[num_of_points_ - 1 + i] = v_diff; auto p_diff = p1 - end_p; g[2 * (num_of_points_ - 1) + i] = p_diff; } return true; } bool PiecewiseJerkPathIpoptSolver::eval_jac_g(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { CHECK_EQ(n, num_of_variables_); CHECK_EQ(m, num_of_constraints_); auto offset_v = num_of_points_; auto offset_a = 2 * num_of_points_; if (values == nullptr) { int nz_index = 0; int constraint_index = 0; // jerk constraint // d_i+1'' - d_i'' for (int variable_index = 0; variable_index + 1 < num_of_points_; ++variable_index) { // d_i'' iRow[nz_index] = constraint_index; jCol[nz_index] = offset_a + variable_index; ++nz_index; // d_i+1'' iRow[nz_index] = constraint_index; jCol[nz_index] = offset_a + variable_index + 1; ++nz_index; ++constraint_index; } // velocity constraint // d_i+1' - d_i' - 0.5 * ds * (d_i'' + d_i+1'') for (int variable_index = 0; variable_index + 1 < num_of_points_; ++variable_index) { // d_i' iRow[nz_index] = constraint_index; jCol[nz_index] = offset_v + variable_index; ++nz_index; // d_i+1' iRow[nz_index] = constraint_index; jCol[nz_index] = offset_v + variable_index + 1; ++nz_index; // d_i'' iRow[nz_index] = constraint_index; jCol[nz_index] = offset_a + variable_index; ++nz_index; // d_i+1'' iRow[nz_index] = constraint_index; jCol[nz_index] = offset_a + variable_index + 1; ++nz_index; ++constraint_index; } // position constraint // d_i+1 - d_i - d_i' * ds - 1/3 * d_i'' * ds^2 - 1/6 * d_i+1'' * ds^2 for (int variable_index = 0; variable_index + 1 < num_of_points_; ++variable_index) { // d_i iRow[nz_index] = constraint_index; jCol[nz_index] = variable_index; ++nz_index; // d_i+1 iRow[nz_index] = constraint_index; jCol[nz_index] = variable_index + 1; ++nz_index; // d_i' iRow[nz_index] = constraint_index; jCol[nz_index] = offset_v + variable_index; ++nz_index; // d_i'' iRow[nz_index] = constraint_index; jCol[nz_index] = offset_a + variable_index; ++nz_index; // d_i+1'' iRow[nz_index] = constraint_index; jCol[nz_index] = offset_a + variable_index + 1; ++nz_index; ++constraint_index; } CHECK_EQ(nz_index, nele_jac); CHECK_EQ(constraint_index, m); } else { std::fill(values, values + nele_jac, 0.0); int nz_index = 0; // fill jerk constraint // d_i+1'' - d_i'' for (int i = 0; i + 1 < num_of_points_; ++i) { values[nz_index] = -1.0 / delta_s_; ++nz_index; values[nz_index] = 1.0 / delta_s_; ++nz_index; } // fill velocity constraint // d_i+1' - d_i - 0.5 * ds * (d_i'' + d_i+1'') for (int i = 0; i + 1 < num_of_points_; ++i) { // d_i' values[nz_index] = -1.0; ++nz_index; // d_i+1' values[nz_index] = 1.0; ++nz_index; // d_i'' values[nz_index] = -0.5 * delta_s_; ++nz_index; // d_i+1'' values[nz_index] = -0.5 * delta_s_; ++nz_index; } // position constraint // d_i+1 - d_i - d_i' * ds - 1/3 * d_i'' * ds^2 - 1/6 * d_i+1'' * ds^2 for (int i = 0; i + 1 < num_of_points_; ++i) { // d_i values[nz_index] = -1.0; ++nz_index; // d_i+1 values[nz_index] = 1.0; ++nz_index; // d_i' values[nz_index] = -delta_s_; ++nz_index; // d_i'' values[nz_index] = -delta_s_ * delta_s_ / 3.0; ++nz_index; // d_i+1'' values[nz_index] = -delta_s_ * delta_s_ / 6.0; ++nz_index; } CHECK_EQ(nz_index, nele_jac); } return true; } bool PiecewiseJerkPathIpoptSolver::eval_h(int n, const double* x, bool new_x, double obj_factor, int m, const double* lambda, bool new_lambda, int nele_hess, int* iRow, int* jCol, double* values) { CHECK_EQ(num_of_variables_ + num_of_points_ - 1, nele_hess); if (values == nullptr) { for (int i = 0; i < num_of_variables_; ++i) { iRow[i] = i; jCol[i] = i; } auto offset_nnz_index = num_of_variables_; auto offset_ddx = num_of_points_ * 2; for (int i = 0; i + 1 < num_of_points_; ++i) { iRow[offset_nnz_index + i] = offset_ddx + i; jCol[offset_nnz_index + i] = offset_ddx + i + 1; } } else { std::fill(values, values + nele_hess, 0.0); for (int i = 0; i < num_of_points_; ++i) { values[i] = 2.0 * w_x_ + 2.0 * w_obs_; } for (int i = num_of_points_; i < 2 * num_of_points_; ++i) { values[i] = 2.0 * w_dx_; } for (int i = 2 * num_of_points_; i < 3 * num_of_points_; ++i) { values[i] = 2.0 * w_ddx_; } auto delta_s_square = delta_s_ * delta_s_; auto t = 2.0 * w_dddx_ / delta_s_square; auto t2 = t * 2; for (int i = 2 * num_of_points_; i < 3 * num_of_points_; ++i) { if (i == 2 * num_of_points_) { values[i] += t; } else { values[i] += t2; } } auto offset = num_of_variables_; for (int i = 0; i + 1 < num_of_points_; ++i) { values[i + offset] = -t; } } return true; } void PiecewiseJerkPathIpoptSolver::finalize_solution( Ipopt::SolverReturn status, int n, const double* x, const double* z_L, const double* z_U, int m, const double* g, const double* lambda, double obj_value, const Ipopt::IpoptData* ip_data, Ipopt::IpoptCalculatedQuantities* ip_cq) { opt_x_.reserve(num_of_points_); opt_dx_.reserve(num_of_points_); opt_ddx_.reserve(num_of_points_); int offset_prime = num_of_points_; int offset_pprime = offset_prime + num_of_points_; for (int i = 0; i < num_of_points_; ++i) { opt_x_.push_back(x[i]); opt_dx_.push_back(x[offset_prime + i]); opt_ddx_.push_back(x[offset_pprime + i]); } } void PiecewiseJerkPathIpoptSolver::GetOptimizationResult( std::vector<double>* ptr_opt_d, std::vector<double>* ptr_opt_d_prime, std::vector<double>* ptr_opt_d_pprime) const { *ptr_opt_d = opt_x_; *ptr_opt_d_prime = opt_dx_; *ptr_opt_d_pprime = opt_ddx_; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/piecewise_jerk_path/piecewise_jerk_path_optimizer.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 piecewise_jerk_path_optimizer.cc **/ #include "modules/planning/tasks/optimizers/piecewise_jerk_path/piecewise_jerk_path_optimizer.h" #include <memory> #include <string> #include "modules/common/math/math_utils.h" #include "modules/common/util/point_factory.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/speed/speed_data.h" #include "modules/planning/common/trajectory1d/piecewise_jerk_trajectory1d.h" #include "modules/planning/math/piecewise_jerk/piecewise_jerk_path_problem.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::VehicleConfigHelper; using apollo::common::math::Gaussian; PiecewiseJerkPathOptimizer::PiecewiseJerkPathOptimizer( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : PathOptimizer(config, injector) { ACHECK(config_.has_piecewise_jerk_path_optimizer_config()); } common::Status PiecewiseJerkPathOptimizer::Process( const SpeedData& speed_data, const ReferenceLine& reference_line, const common::TrajectoryPoint& init_point, const bool path_reusable, PathData* const final_path_data) { // skip piecewise_jerk_path_optimizer if reused path if (FLAGS_enable_skip_path_tasks && path_reusable) { return Status::OK(); } ADEBUG << "Plan at the starting point: x = " << init_point.path_point().x() << ", y = " << init_point.path_point().y() << ", and angle = " << init_point.path_point().theta(); common::TrajectoryPoint planning_start_point = init_point; if (FLAGS_use_front_axe_center_in_path_planning) { planning_start_point = InferFrontAxeCenterFromRearAxeCenter(planning_start_point); } const auto init_frenet_state = reference_line.ToFrenetFrame(planning_start_point); // Choose lane_change_path_config for lane-change cases // Otherwise, choose default_path_config for normal path planning const auto& config = reference_line_info_->IsChangeLanePath() ? config_.piecewise_jerk_path_optimizer_config() .lane_change_path_config() : config_.piecewise_jerk_path_optimizer_config() .default_path_config(); std::array<double, 5> w = { config.l_weight(), config.dl_weight() * std::fmax(init_frenet_state.first[1] * init_frenet_state.first[1], 5.0), config.ddl_weight(), config.dddl_weight(), 0.0}; const auto& path_boundaries = reference_line_info_->GetCandidatePathBoundaries(); ADEBUG << "There are " << path_boundaries.size() << " path boundaries."; const auto& reference_path_data = reference_line_info_->path_data(); std::vector<PathData> candidate_path_data; for (const auto& path_boundary : path_boundaries) { size_t path_boundary_size = path_boundary.boundary().size(); // if the path_boundary is normal, it is possible to have less than 2 points // skip path boundary of this kind if (path_boundary.label().find("regular") != std::string::npos && path_boundary_size < 2) { continue; } int max_iter = 4000; // lower max_iter for regular/self/ if (path_boundary.label().find("self") != std::string::npos) { max_iter = 4000; } CHECK_GT(path_boundary_size, 1U); std::vector<double> opt_l; std::vector<double> opt_dl; std::vector<double> opt_ddl; std::array<double, 3> end_state = {0.0, 0.0, 0.0}; if (!FLAGS_enable_force_pull_over_open_space_parking_test) { // pull over scenario // set end lateral to be at the desired pull over destination 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() && path_boundary.label().find("pullover") != std::string::npos) { common::SLPoint pull_over_sl; reference_line.XYToSL(pull_over_status.position(), &pull_over_sl); end_state[0] = pull_over_sl.l(); } } // TODO(all): double-check this; // final_path_data might carry info from upper stream PathData path_data = *final_path_data; // updated cost function for path reference std::vector<double> path_reference_l(path_boundary_size, 0.0); bool is_valid_path_reference = false; size_t path_reference_size = reference_path_data.path_reference().size(); if (path_boundary.label().find("regular") != std::string::npos && reference_path_data.is_valid_path_reference()) { ADEBUG << "path label is: " << path_boundary.label(); // when path reference is ready for (size_t i = 0; i < path_reference_size; ++i) { common::SLPoint path_reference_sl; reference_line.XYToSL( common::util::PointFactory::ToPointENU( reference_path_data.path_reference().at(i).x(), reference_path_data.path_reference().at(i).y()), &path_reference_sl); path_reference_l[i] = path_reference_sl.l(); } end_state[0] = path_reference_l.back(); path_data.set_is_optimized_towards_trajectory_reference(true); is_valid_path_reference = true; } const auto& veh_param = common::VehicleConfigHelper::GetConfig().vehicle_param(); const double lat_acc_bound = std::tan(veh_param.max_steer_angle() / veh_param.steer_ratio()) / veh_param.wheel_base(); std::vector<std::pair<double, double>> ddl_bounds; for (size_t i = 0; i < path_boundary_size; ++i) { double s = static_cast<double>(i) * path_boundary.delta_s() + path_boundary.start_s(); double kappa = reference_line.GetNearestReferencePoint(s).kappa(); ddl_bounds.emplace_back(-lat_acc_bound - kappa, lat_acc_bound - kappa); } bool res_opt = OptimizePath( init_frenet_state, end_state, std::move(path_reference_l), path_reference_size, path_boundary.delta_s(), is_valid_path_reference, path_boundary.boundary(), ddl_bounds, w, max_iter, &opt_l, &opt_dl, &opt_ddl); if (res_opt) { for (size_t i = 0; i < path_boundary_size; i += 4) { ADEBUG << "for s[" << static_cast<double>(i) * path_boundary.delta_s() << "], l = " << opt_l[i] << ", dl = " << opt_dl[i]; } auto frenet_frame_path = ToPiecewiseJerkPath(opt_l, opt_dl, opt_ddl, path_boundary.delta_s(), path_boundary.start_s()); path_data.SetReferenceLine(&reference_line); path_data.SetFrenetPath(std::move(frenet_frame_path)); if (FLAGS_use_front_axe_center_in_path_planning) { auto discretized_path = DiscretizedPath( ConvertPathPointRefFromFrontAxeToRearAxe(path_data)); path_data.SetDiscretizedPath(discretized_path); } path_data.set_path_label(path_boundary.label()); path_data.set_blocking_obstacle_id(path_boundary.blocking_obstacle_id()); candidate_path_data.push_back(std::move(path_data)); } } if (candidate_path_data.empty()) { return Status(ErrorCode::PLANNING_ERROR, "Path Optimizer failed to generate path"); } reference_line_info_->SetCandidatePathData(std::move(candidate_path_data)); return Status::OK(); } common::TrajectoryPoint PiecewiseJerkPathOptimizer::InferFrontAxeCenterFromRearAxeCenter( const common::TrajectoryPoint& traj_point) { double front_to_rear_axe_distance = VehicleConfigHelper::GetConfig().vehicle_param().wheel_base(); common::TrajectoryPoint ret = traj_point; ret.mutable_path_point()->set_x( traj_point.path_point().x() + front_to_rear_axe_distance * std::cos(traj_point.path_point().theta())); ret.mutable_path_point()->set_y( traj_point.path_point().y() + front_to_rear_axe_distance * std::sin(traj_point.path_point().theta())); return ret; } std::vector<common::PathPoint> PiecewiseJerkPathOptimizer::ConvertPathPointRefFromFrontAxeToRearAxe( const PathData& path_data) { std::vector<common::PathPoint> ret; double front_to_rear_axe_distance = VehicleConfigHelper::GetConfig().vehicle_param().wheel_base(); for (auto path_point : path_data.discretized_path()) { common::PathPoint new_path_point = path_point; new_path_point.set_x(path_point.x() - front_to_rear_axe_distance * std::cos(path_point.theta())); new_path_point.set_y(path_point.y() - front_to_rear_axe_distance * std::sin(path_point.theta())); ret.push_back(new_path_point); } return ret; } bool PiecewiseJerkPathOptimizer::OptimizePath( const std::pair<std::array<double, 3>, std::array<double, 3>>& init_state, const std::array<double, 3>& end_state, std::vector<double> path_reference_l_ref, const size_t path_reference_size, const double delta_s, const bool is_valid_path_reference, const std::vector<std::pair<double, double>>& lat_boundaries, const std::vector<std::pair<double, double>>& ddl_bounds, const std::array<double, 5>& w, const int max_iter, std::vector<double>* x, std::vector<double>* dx, std::vector<double>* ddx) { // num of knots const size_t kNumKnots = lat_boundaries.size(); PiecewiseJerkPathProblem piecewise_jerk_problem(kNumKnots, delta_s, init_state.second); // TODO(Hongyi): update end_state settings piecewise_jerk_problem.set_end_state_ref({1000.0, 0.0, 0.0}, end_state); // pull over scenarios // Because path reference might also make the end_state != 0 // we have to exclude this condition here if (end_state[0] != 0 && !is_valid_path_reference) { std::vector<double> x_ref(kNumKnots, end_state[0]); const auto& pull_over_type = injector_->planning_context() ->planning_status() .pull_over() .pull_over_type(); const double weight_x_ref = pull_over_type == PullOverStatus::EMERGENCY_PULL_OVER ? 200.0 : 10.0; piecewise_jerk_problem.set_x_ref(weight_x_ref, std::move(x_ref)); } // use path reference as a optimization cost function if (is_valid_path_reference) { // for non-path-reference part // weight_x_ref is set to default value, where // l weight = weight_x_ + weight_x_ref_ = (1.0 + 0.0) std::vector<double> weight_x_ref_vec(kNumKnots, 0.0); // increase l weight for path reference part only const double peak_value = config_.piecewise_jerk_path_optimizer_config() .path_reference_l_weight(); const double peak_value_x = 0.5 * static_cast<double>(path_reference_size) * delta_s; for (size_t i = 0; i < path_reference_size; ++i) { // Gaussian weighting const double x = static_cast<double>(i) * delta_s; weight_x_ref_vec.at(i) = GaussianWeighting(x, peak_value, peak_value_x); ADEBUG << "i: " << i << ", weight: " << weight_x_ref_vec.at(i); } piecewise_jerk_problem.set_x_ref(std::move(weight_x_ref_vec), path_reference_l_ref); } // for debug:here should use std::move piecewise_jerk_problem.set_weight_x(w[0]); piecewise_jerk_problem.set_weight_dx(w[1]); piecewise_jerk_problem.set_weight_ddx(w[2]); piecewise_jerk_problem.set_weight_dddx(w[3]); piecewise_jerk_problem.set_scale_factor({1.0, 10.0, 100.0}); auto start_time = std::chrono::system_clock::now(); piecewise_jerk_problem.set_x_bounds(lat_boundaries); piecewise_jerk_problem.set_dx_bounds(-FLAGS_lateral_derivative_bound_default, FLAGS_lateral_derivative_bound_default); piecewise_jerk_problem.set_ddx_bounds(ddl_bounds); // Estimate lat_acc and jerk boundary from vehicle_params const auto& veh_param = common::VehicleConfigHelper::GetConfig().vehicle_param(); const double axis_distance = veh_param.wheel_base(); const double max_yaw_rate = veh_param.max_steer_angle_rate() / veh_param.steer_ratio() / 2.0; const double jerk_bound = EstimateJerkBoundary( std::fmax(init_state.first[1], 1.0), axis_distance, max_yaw_rate); piecewise_jerk_problem.set_dddx_bound(jerk_bound); bool success = piecewise_jerk_problem.Optimize(max_iter); auto end_time = std::chrono::system_clock::now(); std::chrono::duration<double> diff = end_time - start_time; ADEBUG << "Path Optimizer used time: " << diff.count() * 1000 << " ms."; if (!success) { AERROR << "piecewise jerk path optimizer failed"; std::stringstream ssm; AERROR << "dl bound" << FLAGS_lateral_derivative_bound_default << " jerk bound" << jerk_bound; for (size_t i = 0; i < lat_boundaries.size(); i++) { ssm << lat_boundaries[i].first << " " << lat_boundaries[i].second << "," << ddl_bounds[i].first << " " << ddl_bounds[i].second << "," << path_reference_l_ref[i] << std::endl; } AERROR << "lat boundary, ddl boundary , path reference" << std::endl << ssm.str(); return false; } *x = piecewise_jerk_problem.opt_x(); *dx = piecewise_jerk_problem.opt_dx(); *ddx = piecewise_jerk_problem.opt_ddx(); return true; } FrenetFramePath PiecewiseJerkPathOptimizer::ToPiecewiseJerkPath( const std::vector<double>& x, const std::vector<double>& dx, const std::vector<double>& ddx, const double delta_s, const double start_s) const { ACHECK(!x.empty()); ACHECK(!dx.empty()); ACHECK(!ddx.empty()); PiecewiseJerkTrajectory1d piecewise_jerk_traj(x.front(), dx.front(), ddx.front()); for (std::size_t i = 1; i < x.size(); ++i) { const auto dddl = (ddx[i] - ddx[i - 1]) / delta_s; piecewise_jerk_traj.AppendSegment(dddl, delta_s); } std::vector<common::FrenetFramePoint> frenet_frame_path; double accumulated_s = 0.0; while (accumulated_s < piecewise_jerk_traj.ParamLength()) { double l = piecewise_jerk_traj.Evaluate(0, accumulated_s); double dl = piecewise_jerk_traj.Evaluate(1, accumulated_s); double ddl = piecewise_jerk_traj.Evaluate(2, accumulated_s); common::FrenetFramePoint frenet_frame_point; frenet_frame_point.set_s(accumulated_s + start_s); frenet_frame_point.set_l(l); frenet_frame_point.set_dl(dl); frenet_frame_point.set_ddl(ddl); frenet_frame_path.push_back(std::move(frenet_frame_point)); accumulated_s += FLAGS_trajectory_space_resolution; } return FrenetFramePath(std::move(frenet_frame_path)); } double PiecewiseJerkPathOptimizer::EstimateJerkBoundary( const double vehicle_speed, const double axis_distance, const double max_yaw_rate) const { return max_yaw_rate / axis_distance / vehicle_speed; } double PiecewiseJerkPathOptimizer::GaussianWeighting( const double x, const double peak_weighting, const double peak_weighting_x) const { double std = 1 / (std::sqrt(2 * M_PI) * peak_weighting); double u = peak_weighting_x * std; double x_updated = x * std; ADEBUG << peak_weighting * exp(-0.5 * (x - peak_weighting_x) * (x - peak_weighting_x)); ADEBUG << Gaussian(u, std, x_updated); return Gaussian(u, std, x_updated); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/piecewise_jerk_path/piecewise_jerk_path_ipopt_solver.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 piecewise_jerk_path_ipopt_solver.h **/ #pragma once #include <utility> #include <vector> #include <coin/IpTNLP.hpp> #include <coin/IpTypes.hpp> namespace apollo { namespace planning { class PiecewiseJerkPathIpoptSolver : public Ipopt::TNLP { public: PiecewiseJerkPathIpoptSolver(const double d_init, const double d_prime_init, const double d_pprime_init, const double delta_s, const double d_ppprime_max, std::vector<std::pair<double, double>> d_bounds); virtual ~PiecewiseJerkPathIpoptSolver() = default; void set_objective_weights(const double w_x, const double w_dx, const double w_ddx, const double w_dddx, const double w_d_obs); /** Method to return some info about the nlp */ bool get_nlp_info(int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) override; /** Method to return the bounds for my problem */ bool get_bounds_info(int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) override; /** Method to return the starting point for the algorithm */ bool get_starting_point(int n, bool init_x, double* x, bool init_z, double* z_L, double* z_U, int m, bool init_lambda, double* lambda) override; /** Method to return the objective value */ bool eval_f(int n, const double* x, bool new_x, double& obj_value) override; /** Method to return the gradient of the objective */ bool eval_grad_f(int n, const double* x, bool new_x, double* grad_f) override; /** Method to return the constraint residuals */ bool eval_g(int n, const double* x, bool new_x, int m, double* g) override; /** Method to return: * 1) The structure of the jacobian (if "values" is nullptr) * 2) The values of the jacobian (if "values" is not nullptr) */ bool eval_jac_g(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) override; /** Method to return: * 1) The structure of the hessian of the lagrangian (if "values" is * nullptr) 2) The values of the hessian of the lagrangian (if "values" is not * nullptr) */ bool eval_h(int n, const double* x, bool new_x, double obj_factor, int m, const double* lambda, bool new_lambda, int nele_hess, int* iRow, int* jCol, double* values) override; /** @name Solution Methods */ /** This method is called when the algorithm is complete so the TNLP can * store/write the solution */ void finalize_solution(Ipopt::SolverReturn status, int n, const double* x, const double* z_L, const double* z_U, int m, const double* g, const double* lambda, double obj_value, const Ipopt::IpoptData* ip_data, Ipopt::IpoptCalculatedQuantities* ip_cq) override; void GetOptimizationResult(std::vector<double>* ptr_opt_d, std::vector<double>* ptr_opt_d_prime, std::vector<double>* ptr_opt_d_pprime) const; private: int num_of_points_; int num_of_variables_; int num_of_constraints_; double x_init_ = 0.0; double dx_init_ = 0.0; double ddx_init_ = 0.0; double delta_s_ = 0.0; double dddx_max_ = 0.0; std::vector<std::pair<double, double>> d_bounds_; double w_x_ = 1.0; double w_dx_ = 1.0; double w_ddx_ = 1.0; double w_dddx_ = 1.0; double w_obs_ = 1.0; std::vector<double> opt_x_; std::vector<double> opt_dx_; std::vector<double> opt_ddx_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/piecewise_jerk_path/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 = "piecewise_jerk_path_optimizer", srcs = ["piecewise_jerk_path_optimizer.cc"], hdrs = ["piecewise_jerk_path_optimizer.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/util", "//modules/planning/common:obstacle", "//modules/planning/common:path_boundary", "//modules/planning/common:path_decision", "//modules/planning/common:planning_context", "//modules/planning/common:planning_gflags", "//modules/planning/common/path:discretized_path", "//modules/planning/common/path:frenet_frame_path", "//modules/planning/common/path:path_data", "//modules/planning/common/speed:speed_data", "//modules/planning/lattice/trajectory_generation:trajectory1d_generator", "//modules/planning/math:polynomial_xd", "//modules/planning/math/curve1d:polynomial_curve1d", "//modules/planning/math/curve1d:quintic_polynomial_curve1d", "//modules/planning/math/piecewise_jerk:piecewise_jerk_path_problem", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/reference_line", "//modules/planning/tasks/optimizers:path_optimizer", "@eigen", ], ) cc_library( name = "piecewise_jerk_path_ipopt_solver", srcs = ["piecewise_jerk_path_ipopt_solver.cc"], hdrs = ["piecewise_jerk_path_ipopt_solver.h"], copts = PLANNING_COPTS, deps = [ "//cyber", "@eigen", "@ipopt", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/piecewise_jerk_speed/piecewise_jerk_speed_nonlinear_optimizer.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 piecewise_jerk_fallback_speed.cc **/ #include "modules/planning/tasks/optimizers/piecewise_jerk_speed/piecewise_jerk_speed_nonlinear_optimizer.h" #include <algorithm> #include <string> #include <coin/IpIpoptApplication.hpp> #include <coin/IpSolveStatistics.hpp> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/util/util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/speed_profile_generator.h" #include "modules/planning/common/st_graph_data.h" #include "modules/planning/math/piecewise_jerk/piecewise_jerk_path_problem.h" #include "modules/planning/math/piecewise_jerk/piecewise_jerk_speed_problem.h" #include "modules/planning/proto/ipopt_return_status.pb.h" #include "modules/planning/tasks/optimizers/piecewise_jerk_speed/piecewise_jerk_speed_nonlinear_ipopt_interface.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::SpeedPoint; using apollo::common::Status; using apollo::common::TrajectoryPoint; PiecewiseJerkSpeedNonlinearOptimizer::PiecewiseJerkSpeedNonlinearOptimizer( const TaskConfig& config) : SpeedOptimizer(config), smoothed_speed_limit_(0.0, 0.0, 0.0), smoothed_path_curvature_(0.0, 0.0, 0.0) { ACHECK(config_.has_piecewise_jerk_nonlinear_speed_optimizer_config()); } Status PiecewiseJerkSpeedNonlinearOptimizer::Process( const PathData& path_data, const TrajectoryPoint& init_point, SpeedData* const speed_data) { if (speed_data == nullptr) { const std::string msg = "Null speed_data pointer"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (path_data.discretized_path().empty()) { const std::string msg = "Speed Optimizer receives empty path data"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (reference_line_info_->ReachedDestination()) { return Status::OK(); } const auto problem_setups_status = SetUpStatesAndBounds(path_data, *speed_data); if (!problem_setups_status.ok()) { speed_data->clear(); return problem_setups_status; } std::vector<double> distance; std::vector<double> velocity; std::vector<double> acceleration; const auto qp_start = std::chrono::system_clock::now(); const auto qp_smooth_status = OptimizeByQP(speed_data, &distance, &velocity, &acceleration); const auto qp_end = std::chrono::system_clock::now(); std::chrono::duration<double> qp_diff = qp_end - qp_start; ADEBUG << "speed qp optimization takes " << qp_diff.count() * 1000.0 << " ms"; if (!qp_smooth_status.ok()) { speed_data->clear(); return qp_smooth_status; } const bool speed_limit_check_status = CheckSpeedLimitFeasibility(); if (speed_limit_check_status) { const auto curvature_smooth_start = std::chrono::system_clock::now(); const auto path_curvature_smooth_status = SmoothPathCurvature(path_data); const auto curvature_smooth_end = std::chrono::system_clock::now(); std::chrono::duration<double> curvature_smooth_diff = curvature_smooth_end - curvature_smooth_start; ADEBUG << "path curvature smoothing for nlp optimization takes " << curvature_smooth_diff.count() * 1000.0 << " ms"; if (!path_curvature_smooth_status.ok()) { speed_data->clear(); return path_curvature_smooth_status; } const auto speed_limit_smooth_start = std::chrono::system_clock::now(); const auto speed_limit_smooth_status = SmoothSpeedLimit(); const auto speed_limit_smooth_end = std::chrono::system_clock::now(); std::chrono::duration<double> speed_limit_smooth_diff = speed_limit_smooth_end - speed_limit_smooth_start; ADEBUG << "speed limit smoothing for nlp optimization takes " << speed_limit_smooth_diff.count() * 1000.0 << " ms"; if (!speed_limit_smooth_status.ok()) { speed_data->clear(); return speed_limit_smooth_status; } const auto nlp_start = std::chrono::system_clock::now(); const auto nlp_smooth_status = OptimizeByNLP(&distance, &velocity, &acceleration); const auto nlp_end = std::chrono::system_clock::now(); std::chrono::duration<double> nlp_diff = nlp_end - nlp_start; ADEBUG << "speed nlp optimization takes " << nlp_diff.count() * 1000.0 << " ms"; if (!nlp_smooth_status.ok()) { speed_data->clear(); return nlp_smooth_status; } // Record speed_constraint StGraphData* st_graph_data = reference_line_info_->mutable_st_graph_data(); auto* speed_constraint = st_graph_data->mutable_st_graph_debug()->mutable_speed_constraint(); for (int i = 0; i < num_of_knots_; ++i) { double t = i * delta_t_; speed_constraint->add_t(t); speed_constraint->add_upper_bound( smoothed_speed_limit_.Evaluate(0, distance[i])); } } speed_data->clear(); speed_data->AppendSpeedPoint(distance[0], 0.0, velocity[0], acceleration[0], 0.0); for (int i = 1; i < num_of_knots_; ++i) { // Avoid the very last points when already stopped if (velocity[i] < 0.0) { break; } speed_data->AppendSpeedPoint( distance[i], delta_t_ * i, velocity[i], acceleration[i], (acceleration[i] - acceleration[i - 1]) / delta_t_); } SpeedProfileGenerator::FillEnoughSpeedPoints(speed_data); StGraphData* st_graph_data = reference_line_info_->mutable_st_graph_data(); RecordDebugInfo(*speed_data, st_graph_data->mutable_st_graph_debug()); return Status::OK(); } Status PiecewiseJerkSpeedNonlinearOptimizer::SetUpStatesAndBounds( const PathData& path_data, const SpeedData& speed_data) { // Set st problem dimensions const StGraphData& st_graph_data = *reference_line_info_->mutable_st_graph_data(); // TODO(Jinyun): move to confs delta_t_ = 0.1; total_length_ = st_graph_data.path_length(); total_time_ = st_graph_data.total_time_by_conf(); num_of_knots_ = static_cast<int>(total_time_ / delta_t_) + 1; // Set initial values s_init_ = 0.0; s_dot_init_ = st_graph_data.init_point().v(); s_ddot_init_ = st_graph_data.init_point().a(); // Set s_dot bounary s_dot_max_ = std::fmax(FLAGS_planning_upper_speed_limit, st_graph_data.init_point().v()); // Set s_ddot boundary const auto& veh_param = common::VehicleConfigHelper::GetConfig().vehicle_param(); s_ddot_max_ = veh_param.max_acceleration(); s_ddot_min_ = -1.0 * std::abs(veh_param.max_deceleration()); // Set s_dddot boundary // TODO(Jinyun): allow the setting of jerk_lower_bound and move jerk config to // a better place s_dddot_min_ = -std::abs(FLAGS_longitudinal_jerk_lower_bound); s_dddot_max_ = FLAGS_longitudinal_jerk_upper_bound; // Set s boundary if (FLAGS_use_soft_bound_in_nonlinear_speed_opt) { s_bounds_.clear(); s_soft_bounds_.clear(); // TODO(Jinyun): move to confs for (int i = 0; i < num_of_knots_; ++i) { double curr_t = i * delta_t_; double s_lower_bound = 0.0; double s_upper_bound = total_length_; double s_soft_lower_bound = 0.0; double s_soft_upper_bound = total_length_; for (const STBoundary* boundary : st_graph_data.st_boundaries()) { double s_lower = 0.0; double s_upper = 0.0; if (!boundary->GetUnblockSRange(curr_t, &s_upper, &s_lower)) { continue; } SpeedPoint sp; switch (boundary->boundary_type()) { case STBoundary::BoundaryType::STOP: case STBoundary::BoundaryType::YIELD: s_upper_bound = std::fmin(s_upper_bound, s_upper); s_soft_upper_bound = std::fmin(s_soft_upper_bound, s_upper); break; case STBoundary::BoundaryType::FOLLOW: s_upper_bound = std::fmin(s_upper_bound, s_upper - FLAGS_follow_min_distance); if (!speed_data.EvaluateByTime(curr_t, &sp)) { const std::string msg = "rough speed profile estimation for soft follow fence failed"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } s_soft_upper_bound = std::fmin(s_soft_upper_bound, s_upper - FLAGS_follow_min_distance - std::min(7.0, FLAGS_follow_time_buffer * sp.v())); break; case STBoundary::BoundaryType::OVERTAKE: s_lower_bound = std::fmax(s_lower_bound, s_lower); s_soft_lower_bound = std::fmax(s_soft_lower_bound, s_lower + 10.0); break; default: break; } } if (s_lower_bound > s_upper_bound) { const std::string msg = "s_lower_bound larger than s_upper_bound on STGraph"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } s_soft_bounds_.emplace_back(s_soft_lower_bound, s_soft_upper_bound); s_bounds_.emplace_back(s_lower_bound, s_upper_bound); } } else { s_bounds_.clear(); // TODO(Jinyun): move to confs for (int i = 0; i < num_of_knots_; ++i) { double curr_t = i * delta_t_; double s_lower_bound = 0.0; double s_upper_bound = total_length_; for (const STBoundary* boundary : st_graph_data.st_boundaries()) { double s_lower = 0.0; double s_upper = 0.0; if (!boundary->GetUnblockSRange(curr_t, &s_upper, &s_lower)) { continue; } SpeedPoint sp; switch (boundary->boundary_type()) { case STBoundary::BoundaryType::STOP: case STBoundary::BoundaryType::YIELD: s_upper_bound = std::fmin(s_upper_bound, s_upper); break; case STBoundary::BoundaryType::FOLLOW: s_upper_bound = std::fmin(s_upper_bound, s_upper - 8.0); break; case STBoundary::BoundaryType::OVERTAKE: s_lower_bound = std::fmax(s_lower_bound, s_lower); break; default: break; } } if (s_lower_bound > s_upper_bound) { const std::string msg = "s_lower_bound larger than s_upper_bound on STGraph"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } s_bounds_.emplace_back(s_lower_bound, s_upper_bound); } } speed_limit_ = st_graph_data.speed_limit(); cruise_speed_ = reference_line_info_->GetCruiseSpeed(); return Status::OK(); } bool PiecewiseJerkSpeedNonlinearOptimizer::CheckSpeedLimitFeasibility() { // a naive check on first point of speed limit static constexpr double kEpsilon = 1e-6; const double init_speed_limit = speed_limit_.GetSpeedLimitByS(s_init_); if (init_speed_limit + kEpsilon < s_dot_init_) { AERROR << "speed limit [" << init_speed_limit << "] lower than initial speed[" << s_dot_init_ << "]"; return false; } return true; } Status PiecewiseJerkSpeedNonlinearOptimizer::SmoothSpeedLimit() { // using piecewise_jerk_path to fit a curve of speed_ref // TODO(Hongyi): move smooth configs to gflags double delta_s = 2.0; std::vector<double> speed_ref; for (int i = 0; i < 100; ++i) { double path_s = i * delta_s; double limit = speed_limit_.GetSpeedLimitByS(path_s); speed_ref.emplace_back(limit); } std::array<double, 3> init_state = {speed_ref[0], 0.0, 0.0}; PiecewiseJerkPathProblem piecewise_jerk_problem(speed_ref.size(), delta_s, init_state); piecewise_jerk_problem.set_x_bounds(0.0, 50.0); piecewise_jerk_problem.set_dx_bounds(-10.0, 10.0); piecewise_jerk_problem.set_ddx_bounds(-10.0, 10.0); piecewise_jerk_problem.set_dddx_bound(-10.0, 10.0); piecewise_jerk_problem.set_weight_x(0.0); piecewise_jerk_problem.set_weight_dx(10.0); piecewise_jerk_problem.set_weight_ddx(10.0); piecewise_jerk_problem.set_weight_dddx(10.0); piecewise_jerk_problem.set_x_ref(10.0, std::move(speed_ref)); if (!piecewise_jerk_problem.Optimize(4000)) { const std::string msg = "Smoothing speed limit failed"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } std::vector<double> opt_x; std::vector<double> opt_dx; std::vector<double> opt_ddx; opt_x = piecewise_jerk_problem.opt_x(); opt_dx = piecewise_jerk_problem.opt_dx(); opt_ddx = piecewise_jerk_problem.opt_ddx(); PiecewiseJerkTrajectory1d smoothed_speed_limit(opt_x.front(), opt_dx.front(), opt_ddx.front()); for (size_t i = 1; i < opt_ddx.size(); ++i) { double j = (opt_ddx[i] - opt_ddx[i - 1]) / delta_s; smoothed_speed_limit.AppendSegment(j, delta_s); } smoothed_speed_limit_ = smoothed_speed_limit; return Status::OK(); } Status PiecewiseJerkSpeedNonlinearOptimizer::SmoothPathCurvature( const PathData& path_data) { // using piecewise_jerk_path to fit a curve of path kappa profile // TODO(Jinyun): move smooth configs to gflags const auto& cartesian_path = path_data.discretized_path(); const double delta_s = 0.5; std::vector<double> path_curvature; for (double path_s = cartesian_path.front().s(); path_s < cartesian_path.back().s() + delta_s; path_s += delta_s) { const auto& path_point = cartesian_path.Evaluate(path_s); path_curvature.push_back(path_point.kappa()); } const auto& path_init_point = cartesian_path.front(); std::array<double, 3> init_state = {path_init_point.kappa(), path_init_point.dkappa(), path_init_point.ddkappa()}; PiecewiseJerkPathProblem piecewise_jerk_problem(path_curvature.size(), delta_s, init_state); piecewise_jerk_problem.set_x_bounds(-1.0, 1.0); piecewise_jerk_problem.set_dx_bounds(-10.0, 10.0); piecewise_jerk_problem.set_ddx_bounds(-10.0, 10.0); piecewise_jerk_problem.set_dddx_bound(-10.0, 10.0); piecewise_jerk_problem.set_weight_x(0.0); piecewise_jerk_problem.set_weight_dx(10.0); piecewise_jerk_problem.set_weight_ddx(10.0); piecewise_jerk_problem.set_weight_dddx(10.0); piecewise_jerk_problem.set_x_ref(10.0, std::move(path_curvature)); if (!piecewise_jerk_problem.Optimize(1000)) { const std::string msg = "Smoothing path curvature failed"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } std::vector<double> opt_x; std::vector<double> opt_dx; std::vector<double> opt_ddx; opt_x = piecewise_jerk_problem.opt_x(); opt_dx = piecewise_jerk_problem.opt_dx(); opt_ddx = piecewise_jerk_problem.opt_ddx(); PiecewiseJerkTrajectory1d smoothed_path_curvature( opt_x.front(), opt_dx.front(), opt_ddx.front()); for (size_t i = 1; i < opt_ddx.size(); ++i) { double j = (opt_ddx[i] - opt_ddx[i - 1]) / delta_s; smoothed_path_curvature.AppendSegment(j, delta_s); } smoothed_path_curvature_ = smoothed_path_curvature; return Status::OK(); } Status PiecewiseJerkSpeedNonlinearOptimizer::OptimizeByQP( SpeedData* const speed_data, std::vector<double>* distance, std::vector<double>* velocity, std::vector<double>* acceleration) { std::array<double, 3> init_states = {s_init_, s_dot_init_, s_ddot_init_}; PiecewiseJerkSpeedProblem piecewise_jerk_problem(num_of_knots_, delta_t_, init_states); piecewise_jerk_problem.set_dx_bounds( 0.0, std::fmax(FLAGS_planning_upper_speed_limit, init_states[1])); piecewise_jerk_problem.set_ddx_bounds(s_ddot_min_, s_ddot_max_); piecewise_jerk_problem.set_dddx_bound(s_dddot_min_, s_dddot_max_); piecewise_jerk_problem.set_x_bounds(s_bounds_); // TODO(Jinyun): parameter tunnings const auto& config = config_.piecewise_jerk_nonlinear_speed_optimizer_config(); piecewise_jerk_problem.set_weight_x(0.0); piecewise_jerk_problem.set_weight_dx(0.0); piecewise_jerk_problem.set_weight_ddx(config.acc_weight()); piecewise_jerk_problem.set_weight_dddx(config.jerk_weight()); std::vector<double> x_ref; for (int i = 0; i < num_of_knots_; ++i) { const double curr_t = i * delta_t_; // get path_s SpeedPoint sp; speed_data->EvaluateByTime(curr_t, &sp); x_ref.emplace_back(sp.s()); } piecewise_jerk_problem.set_x_ref(config.ref_s_weight(), std::move(x_ref)); // Solve the problem if (!piecewise_jerk_problem.Optimize()) { const std::string msg = "Speed Optimization by Quadratic Programming failed. " "st boundary is infeasible."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } *distance = piecewise_jerk_problem.opt_x(); *velocity = piecewise_jerk_problem.opt_dx(); *acceleration = piecewise_jerk_problem.opt_ddx(); return Status::OK(); } Status PiecewiseJerkSpeedNonlinearOptimizer::OptimizeByNLP( std::vector<double>* distance, std::vector<double>* velocity, std::vector<double>* acceleration) { static std::mutex mutex_tnlp; UNIQUE_LOCK_MULTITHREAD(mutex_tnlp); // Set optimizer instance auto ptr_interface = new PiecewiseJerkSpeedNonlinearIpoptInterface( s_init_, s_dot_init_, s_ddot_init_, delta_t_, num_of_knots_, total_length_, s_dot_max_, s_ddot_min_, s_ddot_max_, s_dddot_min_, s_dddot_max_); ptr_interface->set_safety_bounds(s_bounds_); // Set weights and reference values const auto& config = config_.piecewise_jerk_nonlinear_speed_optimizer_config(); ptr_interface->set_curvature_curve(smoothed_path_curvature_); // TODO(Hongyi): add debug_info for speed_limit fitting curve ptr_interface->set_speed_limit_curve(smoothed_speed_limit_); // TODO(Jinyun): refactor warms start setting API if (config.use_warm_start()) { const auto& warm_start_distance = *distance; const auto& warm_start_velocity = *velocity; const auto& warm_start_acceleration = *acceleration; if (warm_start_distance.empty() || warm_start_velocity.empty() || warm_start_acceleration.empty() || warm_start_distance.size() != warm_start_velocity.size() || warm_start_velocity.size() != warm_start_acceleration.size()) { const std::string msg = "Piecewise jerk speed nonlinear optimizer warm start invalid!"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } std::vector<std::vector<double>> warm_start; std::size_t size = warm_start_distance.size(); for (std::size_t i = 0; i < size; ++i) { warm_start.emplace_back(std::initializer_list<double>( {warm_start_distance[i], warm_start_velocity[i], warm_start_acceleration[i]})); } ptr_interface->set_warm_start(warm_start); } if (FLAGS_use_smoothed_dp_guide_line) { ptr_interface->set_reference_spatial_distance(*distance); // TODO(Jinyun): move to confs ptr_interface->set_w_reference_spatial_distance(10.0); } else { std::vector<double> spatial_potantial(num_of_knots_, total_length_); ptr_interface->set_reference_spatial_distance(spatial_potantial); ptr_interface->set_w_reference_spatial_distance( config.s_potential_weight()); } if (FLAGS_use_soft_bound_in_nonlinear_speed_opt) { ptr_interface->set_soft_safety_bounds(s_soft_bounds_); ptr_interface->set_w_soft_s_bound(config.soft_s_bound_weight()); } ptr_interface->set_w_overall_a(config.acc_weight()); ptr_interface->set_w_overall_j(config.jerk_weight()); ptr_interface->set_w_overall_centripetal_acc(config.lat_acc_weight()); ptr_interface->set_reference_speed(cruise_speed_); ptr_interface->set_w_reference_speed(config.ref_v_weight()); Ipopt::SmartPtr<Ipopt::TNLP> problem = ptr_interface; Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory(); app->Options()->SetIntegerValue("print_level", 0); app->Options()->SetIntegerValue("max_iter", 1000); Ipopt::ApplicationReturnStatus status = app->Initialize(); if (status != Ipopt::Solve_Succeeded) { const std::string msg = "Piecewise jerk speed nonlinear optimizer failed during initialization"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } const auto start_timestamp = std::chrono::system_clock::now(); status = app->OptimizeTNLP(problem); const auto end_timestamp = std::chrono::system_clock::now(); std::chrono::duration<double> diff = end_timestamp - start_timestamp; ADEBUG << "*** The optimization problem take time: " << diff.count() * 1000.0 << " ms."; if (status == Ipopt::Solve_Succeeded || status == Ipopt::Solved_To_Acceptable_Level) { // Retrieve some statistics about the solve Ipopt::Index iter_count = app->Statistics()->IterationCount(); ADEBUG << "*** The problem solved in " << iter_count << " iterations!"; Ipopt::Number final_obj = app->Statistics()->FinalObjective(); ADEBUG << "*** The final value of the objective function is " << final_obj << '.'; } else { const auto& ipopt_return_status = IpoptReturnStatus_Name(static_cast<IpoptReturnStatus>(status)); if (ipopt_return_status.empty()) { AERROR << "Solver ends with unknown failure code: " << static_cast<int>(status); } else { AERROR << "Solver failure case is : " << ipopt_return_status; } const std::string msg = "Piecewise jerk speed nonlinear optimizer failed"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } ptr_interface->get_optimization_results(distance, velocity, acceleration); return Status::OK(); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/piecewise_jerk_speed/piecewise_jerk_speed_optimizer.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 piecewise_jerk_fallback_speed.cc **/ #include "modules/planning/tasks/optimizers/piecewise_jerk_speed/piecewise_jerk_speed_optimizer.h" #include <string> #include <utility> #include <vector> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/speed_profile_generator.h" #include "modules/planning/common/st_graph_data.h" #include "modules/planning/math/piecewise_jerk/piecewise_jerk_speed_problem.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::PathPoint; using apollo::common::SpeedPoint; using apollo::common::Status; using apollo::common::TrajectoryPoint; PiecewiseJerkSpeedOptimizer::PiecewiseJerkSpeedOptimizer( const TaskConfig& config) : SpeedOptimizer(config) { ACHECK(config_.has_piecewise_jerk_speed_optimizer_config()); } Status PiecewiseJerkSpeedOptimizer::Process(const PathData& path_data, const TrajectoryPoint& init_point, SpeedData* const speed_data) { if (reference_line_info_->ReachedDestination()) { return Status::OK(); } ACHECK(speed_data != nullptr); SpeedData reference_speed_data = *speed_data; if (path_data.discretized_path().empty()) { const std::string msg = "Empty path data"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } StGraphData& st_graph_data = *reference_line_info_->mutable_st_graph_data(); const auto& veh_param = common::VehicleConfigHelper::GetConfig().vehicle_param(); std::array<double, 3> init_s = {0.0, st_graph_data.init_point().v(), st_graph_data.init_point().a()}; double delta_t = 0.1; double total_length = st_graph_data.path_length(); double total_time = st_graph_data.total_time_by_conf(); int num_of_knots = static_cast<int>(total_time / delta_t) + 1; PiecewiseJerkSpeedProblem piecewise_jerk_problem(num_of_knots, delta_t, init_s); const auto& config = config_.piecewise_jerk_speed_optimizer_config(); piecewise_jerk_problem.set_weight_ddx(config.acc_weight()); piecewise_jerk_problem.set_weight_dddx(config.jerk_weight()); piecewise_jerk_problem.set_x_bounds(0.0, total_length); piecewise_jerk_problem.set_dx_bounds( 0.0, std::fmax(FLAGS_planning_upper_speed_limit, st_graph_data.init_point().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); piecewise_jerk_problem.set_dx_ref(config.ref_v_weight(), reference_line_info_->GetCruiseSpeed()); // Update STBoundary std::vector<std::pair<double, double>> s_bounds; for (int i = 0; i < num_of_knots; ++i) { double curr_t = i * delta_t; double s_lower_bound = 0.0; double s_upper_bound = total_length; for (const STBoundary* boundary : st_graph_data.st_boundaries()) { double s_lower = 0.0; double s_upper = 0.0; if (!boundary->GetUnblockSRange(curr_t, &s_upper, &s_lower)) { continue; } switch (boundary->boundary_type()) { case STBoundary::BoundaryType::STOP: case STBoundary::BoundaryType::YIELD: s_upper_bound = std::fmin(s_upper_bound, s_upper); break; case STBoundary::BoundaryType::FOLLOW: // TODO(Hongyi): unify follow buffer on decision side s_upper_bound = std::fmin(s_upper_bound, s_upper - 8.0); break; case STBoundary::BoundaryType::OVERTAKE: s_lower_bound = std::fmax(s_lower_bound, s_lower); break; default: break; } } if (s_lower_bound > s_upper_bound) { const std::string msg = "s_lower_bound larger than s_upper_bound on STGraph"; AERROR << msg; speed_data->clear(); return Status(ErrorCode::PLANNING_ERROR, msg); } s_bounds.emplace_back(s_lower_bound, s_upper_bound); } piecewise_jerk_problem.set_x_bounds(std::move(s_bounds)); // Update SpeedBoundary and ref_s std::vector<double> x_ref; std::vector<double> penalty_dx; std::vector<std::pair<double, double>> s_dot_bounds; const SpeedLimit& speed_limit = st_graph_data.speed_limit(); for (int i = 0; i < num_of_knots; ++i) { double curr_t = i * delta_t; // get path_s SpeedPoint sp; reference_speed_data.EvaluateByTime(curr_t, &sp); const double path_s = sp.s(); x_ref.emplace_back(path_s); // get curvature PathPoint path_point = path_data.GetPathPointWithPathS(path_s); penalty_dx.push_back(std::fabs(path_point.kappa()) * config.kappa_penalty_weight()); // get v_upper_bound const double v_lower_bound = 0.0; double v_upper_bound = FLAGS_planning_upper_speed_limit; v_upper_bound = speed_limit.GetSpeedLimitByS(path_s); s_dot_bounds.emplace_back(v_lower_bound, std::fmax(v_upper_bound, 0.0)); } piecewise_jerk_problem.set_x_ref(config.ref_s_weight(), std::move(x_ref)); piecewise_jerk_problem.set_penalty_dx(penalty_dx); piecewise_jerk_problem.set_dx_bounds(std::move(s_dot_bounds)); // Solve the problem if (!piecewise_jerk_problem.Optimize()) { const std::string msg = "Piecewise jerk speed optimizer failed!"; AERROR << msg; speed_data->clear(); return Status(ErrorCode::PLANNING_ERROR, msg); } // 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 (int i = 0; i < num_of_knots; ++i) { ADEBUG << "For t[" << i * delta_t << "], s = " << s[i] << ", v = " << ds[i] << ", a = " << dds[i]; } speed_data->clear(); speed_data->AppendSpeedPoint(s[0], 0.0, ds[0], dds[0], 0.0); for (int i = 1; i < num_of_knots; ++i) { // Avoid the very last points when already stopped if (ds[i] <= 0.0) { break; } speed_data->AppendSpeedPoint(s[i], delta_t * i, ds[i], dds[i], (dds[i] - dds[i - 1]) / delta_t); } SpeedProfileGenerator::FillEnoughSpeedPoints(speed_data); RecordDebugInfo(*speed_data, st_graph_data.mutable_st_graph_debug()); return Status::OK(); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/piecewise_jerk_speed/piecewise_jerk_speed_nonlinear_ipopt_interface.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 piecewise_jerk_speed_nonlinear_ipopt_interface.h **/ #pragma once #include <unordered_map> #include <utility> #include <vector> #include <coin/IpTNLP.hpp> #include <coin/IpTypes.hpp> #include "modules/planning/common/path/path_data.h" #include "modules/planning/common/trajectory1d/piecewise_jerk_trajectory1d.h" namespace apollo { namespace planning { class PiecewiseJerkSpeedNonlinearIpoptInterface : public Ipopt::TNLP { public: PiecewiseJerkSpeedNonlinearIpoptInterface( const double s_init, const double s_dot_init, const double s_ddot_init, const double delta_t, const int num_of_points, const double s_max_, const double s_dot_max, const double s_ddot_min, const double s_ddot_max, const double s_dddot_min, const double s_dddot_max); virtual ~PiecewiseJerkSpeedNonlinearIpoptInterface() = default; void set_warm_start(const std::vector<std::vector<double>> &speed_profile); void set_curvature_curve(const PiecewiseJerkTrajectory1d &curvature_curve); void get_optimization_results(std::vector<double> *ptr_opt_s, std::vector<double> *ptr_opt_v, std::vector<double> *ptr_opt_a); void set_end_state_target(const double s_target, const double v_target, const double a_target); void set_reference_speed(const double s_dot_ref); void set_reference_spatial_distance(const std::vector<double> &s_ref); void set_speed_limit_curve(const PiecewiseJerkTrajectory1d &v_bound_f); void set_safety_bounds( const std::vector<std::pair<double, double>> &safety_bounds); void set_soft_safety_bounds( const std::vector<std::pair<double, double>> &soft_safety_bounds); void set_w_target_state(const double w_target_s, const double w_target_v, const double w_target_a); void set_w_overall_a(const double w_overall_a); void set_w_overall_j(const double w_overall_j); void set_w_overall_centripetal_acc(const double w_overall_centripetal_acc); void set_w_reference_speed(const double w_reference_speed); void set_w_reference_spatial_distance(const double w_ref_s); void set_w_soft_s_bound(const double w_soft_s_bound); /** Method to return some info about the nlp */ bool get_nlp_info(int &n, int &m, int &nnz_jac_g, int &nnz_h_lag, IndexStyleEnum &index_style) override; /** Method to return the bounds for my problem */ bool get_bounds_info(int n, double *x_l, double *x_u, int m, double *g_l, double *g_u) override; /** Method to return the starting point for the algorithm */ bool get_starting_point(int n, bool init_x, double *x, bool init_z, double *z_L, double *z_U, int m, bool init_lambda, double *lambda) override; /** Method to return the objective value */ bool eval_f(int n, const double *x, bool new_x, double &obj_value) override; /** Method to return the gradient of the objective */ bool eval_grad_f(int n, const double *x, bool new_x, double *grad_f) override; /** Method to return the constraint residuals */ bool eval_g(int n, const double *x, bool new_x, int m, double *g) override; /** Method to return: * 1) The structure of the jacobian (if "values" is nullptr) * 2) The values of the jacobian (if "values" is not nullptr) */ bool eval_jac_g(int n, const double *x, bool new_x, int m, int nele_jac, int *iRow, int *jCol, double *values) override; /** Method to return: * 1) The structure of the hessian of the lagrangian (if "values" is * nullptr) 2) The values of the hessian of the lagrangian (if "values" is not * nullptr) */ bool eval_h(int n, const double *x, bool new_x, double obj_factor, int m, const double *lambda, bool new_lambda, int nele_hess, int *iRow, int *jCol, double *values) override; /** @name Solution Methods */ /** This method is called when the algorithm is complete so the TNLP can * store/write the solution */ void finalize_solution(Ipopt::SolverReturn status, int n, const double *x, const double *z_L, const double *z_U, int m, const double *g, const double *lambda, double obj_value, const Ipopt::IpoptData *ip_data, Ipopt::IpoptCalculatedQuantities *ip_cq) override; private: int to_hash_key(const int i, const int j) const; std::unordered_map<int, int> hessian_mapper_; PiecewiseJerkTrajectory1d curvature_curve_; bool use_v_bound_ = false; bool use_soft_safety_bound_ = false; PiecewiseJerkTrajectory1d v_bound_func_; const double s_init_; const double s_dot_init_; const double s_ddot_init_; const double delta_t_; const int num_of_points_; const double s_max_; const double s_dot_max_; const double s_ddot_min_; const double s_ddot_max_; const double s_dddot_min_; const double s_dddot_max_; const int v_offset_; const int a_offset_; int lower_s_slack_offset_ = 0; int upper_s_slack_offset_ = 0; int num_of_variables_ = 0; int num_of_constraints_ = 0; double w_target_s_ = 10000.0; double w_target_v_ = 10000.0; double w_target_a_ = 10000.0; double w_ref_v_ = 1.0; double w_ref_s_ = 1.0; double w_overall_a_ = 100.0; double w_overall_j_ = 10.0; double w_overall_centripetal_acc_ = 500.0; double w_soft_s_bound_ = 0.0; double v_max_ = 0.0; double s_target_ = 0.0; double v_target_ = 0.0; double a_target_ = 0.0; double v_ref_ = 0.0; std::vector<std::pair<double, double>> safety_bounds_; std::vector<std::pair<double, double>> soft_safety_bounds_; bool has_end_state_target_ = false; std::vector<double> opt_s_; std::vector<double> opt_v_; std::vector<double> opt_a_; std::vector<std::vector<double>> x_warm_start_; std::vector<double> s_ref_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/piecewise_jerk_speed/piecewise_jerk_speed_nonlinear_optimizer.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 piecewise_jerk_speed_nonlinear_optimizer.h **/ #pragma once #include <utility> #include <vector> #include "modules/planning/common/trajectory1d/piecewise_jerk_trajectory1d.h" #include "modules/planning/tasks/optimizers/speed_optimizer.h" namespace apollo { namespace planning { class PiecewiseJerkSpeedNonlinearOptimizer : public SpeedOptimizer { public: explicit PiecewiseJerkSpeedNonlinearOptimizer(const TaskConfig& config); virtual ~PiecewiseJerkSpeedNonlinearOptimizer() = default; private: common::Status Process(const PathData& path_data, const common::TrajectoryPoint& init_point, SpeedData* const speed_data) override; common::Status SetUpStatesAndBounds(const PathData& path_data, const SpeedData& speed_data); bool CheckSpeedLimitFeasibility(); common::Status SmoothSpeedLimit(); common::Status SmoothPathCurvature(const PathData& path_data); common::Status OptimizeByQP(SpeedData* const speed_data, std::vector<double>* distance, std::vector<double>* velocity, std::vector<double>* acceleration); common::Status OptimizeByNLP(std::vector<double>* distance, std::vector<double>* velocity, std::vector<double>* acceleration); // st problem dimensions double delta_t_ = 0.0; double total_length_ = 0.0; double total_time_ = 0.0; int num_of_knots_ = 0; // st initial values double s_init_ = 0.0; double s_dot_init_ = 0.0; double s_ddot_init_ = 0.0; // st states dynamically feasibility bounds double s_dot_max_ = 0.0; double s_ddot_min_ = 0.0; double s_ddot_max_ = 0.0; double s_dddot_min_ = 0.0; double s_dddot_max_ = 0.0; // st safety bounds std::vector<std::pair<double, double>> s_bounds_; std::vector<std::pair<double, double>> s_soft_bounds_; // speed limits SpeedLimit speed_limit_; PiecewiseJerkTrajectory1d smoothed_speed_limit_; // smoothed path curvature profile as a function of traversal distance PiecewiseJerkTrajectory1d smoothed_path_curvature_; // reference speed profile SpeedData reference_speed_data_; // reference cruise speed double cruise_speed_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/piecewise_jerk_speed/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 = "piecewise_jerk_speed_optimizer", srcs = ["piecewise_jerk_speed_optimizer.cc"], hdrs = ["piecewise_jerk_speed_optimizer.h"], copts = PLANNING_COPTS, deps = [ "//modules/common_msgs/basic_msgs:error_code_cc_proto", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/planning/common:speed_profile_generator", "//modules/planning/common:st_graph_data", "//modules/planning/math/piecewise_jerk:piecewise_jerk_speed_problem", "//modules/planning/tasks/optimizers:speed_optimizer", ], ) cc_library( name = "piecewise_jerk_speed_nonlinear_optimizer", srcs = ["piecewise_jerk_speed_nonlinear_optimizer.cc"], hdrs = ["piecewise_jerk_speed_nonlinear_optimizer.h"], copts = PLANNING_COPTS, deps = [ ":piecewise_jerk_speed_nonlinear_ipopt_interface", "//modules/common_msgs/basic_msgs:error_code_cc_proto", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/util", "//modules/planning/common:speed_profile_generator", "//modules/planning/common:st_graph_data", "//modules/planning/common/path:path_data", "//modules/planning/common/trajectory1d:piecewise_jerk_trajectory1d", "//modules/planning/math/piecewise_jerk:piecewise_jerk_path_problem", "//modules/planning/math/piecewise_jerk:piecewise_jerk_speed_problem", "//modules/planning/proto:ipopt_return_status_cc_proto", "//modules/planning/tasks/optimizers:speed_optimizer", ], ) cc_library( name = "piecewise_jerk_speed_nonlinear_ipopt_interface", srcs = ["piecewise_jerk_speed_nonlinear_ipopt_interface.cc"], hdrs = ["piecewise_jerk_speed_nonlinear_ipopt_interface.h"], copts = PLANNING_COPTS, deps = [ "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/planning/common/path:path_data", "//modules/planning/common/trajectory1d:piecewise_jerk_trajectory1d", "@ipopt", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/piecewise_jerk_speed/piecewise_jerk_speed_optimizer.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 piecewise_jerk_speed_optimizer.h **/ #pragma once #include "modules/planning/tasks/optimizers/speed_optimizer.h" namespace apollo { namespace planning { class PiecewiseJerkSpeedOptimizer : public SpeedOptimizer { public: explicit PiecewiseJerkSpeedOptimizer(const TaskConfig& config); virtual ~PiecewiseJerkSpeedOptimizer() = default; private: common::Status Process(const PathData& path_data, const common::TrajectoryPoint& init_point, SpeedData* const speed_data) override; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/piecewise_jerk_speed/piecewise_jerk_speed_nonlinear_ipopt_interface.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 piecewise_jerk_speed_nonlinear_ipopt_interface.cc **/ #include "modules/planning/tasks/optimizers/piecewise_jerk_speed/piecewise_jerk_speed_nonlinear_ipopt_interface.h" #include <algorithm> #include <limits> namespace apollo { namespace planning { PiecewiseJerkSpeedNonlinearIpoptInterface:: PiecewiseJerkSpeedNonlinearIpoptInterface( const double s_init, const double s_dot_init, const double s_ddot_init, const double delta_t, const int num_of_points, const double s_max, const double s_dot_max, const double s_ddot_min, const double s_ddot_max, const double s_dddot_min, const double s_dddot_max) : curvature_curve_(0.0, 0.0, 0.0), v_bound_func_(0.0, 0.0, 0.0), s_init_(s_init), s_dot_init_(s_dot_init), s_ddot_init_(s_ddot_init), delta_t_(delta_t), num_of_points_(num_of_points), s_max_(s_max), s_dot_max_(s_dot_max), s_ddot_min_(-std::abs(s_ddot_min)), s_ddot_max_(s_ddot_max), s_dddot_min_(-std::abs(s_dddot_min)), s_dddot_max_(s_dddot_max), v_offset_(num_of_points), a_offset_(num_of_points * 2) {} bool PiecewiseJerkSpeedNonlinearIpoptInterface::get_nlp_info( int &n, int &m, int &nnz_jac_g, int &nnz_h_lag, IndexStyleEnum &index_style) { num_of_variables_ = num_of_points_ * 3; if (use_soft_safety_bound_) { // complementary slack variable for soft upper and lower s bound num_of_variables_ += num_of_points_ * 2; lower_s_slack_offset_ = num_of_points_ * 3; upper_s_slack_offset_ = num_of_points_ * 4; } n = num_of_variables_; // s monotone constraints s_i+1 - s_i >= 0.0 num_of_constraints_ = num_of_points_ - 1; // jerk bound constraint // |s_ddot_i+1 - s_ddot_i| / delta_t <= s_dddot_max num_of_constraints_ += num_of_points_ - 1; // position equality constraints // s_i+1 - s_i - s_dot_i * delta_t - 1/3 * s_ddot_i * delta_t^2 - 1/6 * // s_ddot_i+1 * delta_t^2 num_of_constraints_ += num_of_points_ - 1; // velocity equality constraints // s_dot_i+1 - s_dot_i - 0.5 * delta_t * s_ddot_i - 0.5 * delta_t * s_ddot_i+1 num_of_constraints_ += num_of_points_ - 1; if (use_v_bound_) { // speed limit constraints // s_dot_i - v_bound_func_(s_i) <= 0.0 num_of_constraints_ += num_of_points_; } if (use_soft_safety_bound_) { // soft safety boundary constraints // s_i - soft_lower_s_i + lower_slack_i >= 0.0 num_of_constraints_ += num_of_points_; // s_i - soft_upper_s_i - upper_slack_i <= 0.0 num_of_constraints_ += num_of_points_; } m = num_of_constraints_; nnz_jac_g = 0; // s_i+1 - s_i nnz_jac_g += (num_of_points_ - 1) * 2; // (s_ddot_i+1 - s_ddot_i) / delta_t nnz_jac_g += (num_of_points_ - 1) * 2; // s_i+1 - s_i - s_dot_i * delta_t - 1/3 * s_ddot_i * delta_t^2 - 1/6 * // s_ddot_i+1 * delta_t^2 nnz_jac_g += (num_of_points_ - 1) * 5; // s_dot_i+1 - s_dot_i - 0.5 * s_ddot_i * delta_t - 0.5 * s_ddot_i+1 * delta_t nnz_jac_g += (num_of_points_ - 1) * 4; if (use_v_bound_) { // speed limit constraints // s_dot_i - v_bound_func_(s_i) <= 0.0 nnz_jac_g += num_of_points_ * 2; } if (use_soft_safety_bound_) { // soft safety boundary constraints // s_i - soft_lower_s_i + lower_slack_i >= 0.0 nnz_jac_g += num_of_points_ * 2; // s_i - soft_upper_s_i - upper_slack_i <= 0.0 nnz_jac_g += num_of_points_ * 2; } nnz_h_lag = num_of_points_ * 5 - 1; index_style = IndexStyleEnum::C_STYLE; return true; } bool PiecewiseJerkSpeedNonlinearIpoptInterface::get_bounds_info( int n, double *x_l, double *x_u, int m, double *g_l, double *g_u) { // default nlp_lower_bound_inf value in Ipopt double INF = 1.0e19; double LARGE_VELOCITY_VALUE = s_dot_max_; // bounds for variables // s x_l[0] = s_init_; x_u[0] = s_init_; for (int i = 1; i < num_of_points_; ++i) { x_l[i] = safety_bounds_[i].first; x_u[i] = safety_bounds_[i].second; } // s_dot x_l[v_offset_] = s_dot_init_; x_u[v_offset_] = s_dot_init_; for (int i = 1; i < num_of_points_; ++i) { x_l[v_offset_ + i] = 0.0; x_u[v_offset_ + i] = LARGE_VELOCITY_VALUE; } // s_ddot x_l[a_offset_] = s_ddot_init_; x_u[a_offset_] = s_ddot_init_; for (int i = 1; i < num_of_points_; ++i) { x_l[a_offset_ + i] = s_ddot_min_; x_u[a_offset_ + i] = s_ddot_max_; } if (use_soft_safety_bound_) { // lower_s_slack for (int i = 0; i < num_of_points_; ++i) { x_l[lower_s_slack_offset_ + i] = 0.0; x_u[lower_s_slack_offset_ + i] = INF; } // upper_s_slack for (int i = 0; i < num_of_points_; ++i) { x_l[upper_s_slack_offset_ + i] = 0.0; x_u[upper_s_slack_offset_ + i] = INF; } } // bounds for constraints // s monotone constraints s_i+1 - s_i for (int i = 0; i + 1 < num_of_points_; ++i) { g_l[i] = 0.0; g_u[i] = LARGE_VELOCITY_VALUE * delta_t_; } // jerk bound constraint // |s_ddot_i+1 - s_ddot_i| / delta_t <= s_dddot_max int offset = num_of_points_ - 1; for (int i = 0; i + 1 < num_of_points_; ++i) { g_l[offset + i] = s_dddot_min_; g_u[offset + i] = s_dddot_max_; } // position equality constraints, // s_i+1 - s_i - s_dot_i * delta_t - 1/3 * s_ddot_i * delta_t^2 - 1/6 * // s_ddot_i+1 * delta_t^2 offset += num_of_points_ - 1; for (int i = 0; i + 1 < num_of_points_; ++i) { g_l[offset + i] = 0.0; g_u[offset + i] = 0.0; } // velocity equality constraints, // s_dot_i+1 - s_dot_i - 0.5 * delta_t * s_ddot_i - 0.5 * delta_t * // s_ddot_i+1 offset += num_of_points_ - 1; for (int i = 0; i + 1 < num_of_points_; ++i) { g_l[offset + i] = 0.0; g_u[offset + i] = 0.0; } if (use_v_bound_) { // speed limit constraints // s_dot_i - v_bound_func_(s_i) <= 0.0 offset += num_of_points_ - 1; for (int i = 0; i < num_of_points_; ++i) { g_l[offset + i] = -INF; g_u[offset + i] = 0.0; } } if (use_soft_safety_bound_) { // soft_s_bound constraints // s_i - soft_lower_s_i + lower_slack_i >= 0.0 offset += num_of_points_; for (int i = 0; i < num_of_points_; ++i) { g_l[offset + i] = 0.0; g_u[offset + i] = INF; } // s_i - soft_upper_s_i - upper_slack_i <= 0.0 offset += num_of_points_; for (int i = 0; i < num_of_points_; ++i) { g_l[offset + i] = -INF; g_u[offset + i] = 0.0; } } return true; } bool PiecewiseJerkSpeedNonlinearIpoptInterface::get_starting_point( int n, bool init_x, double *x, bool init_z, double *z_L, double *z_U, int m, bool init_lambda, double *lambda) { if (!x_warm_start_.empty()) { for (int i = 0; i < num_of_points_; ++i) { x[i] = x_warm_start_[i][0]; x[v_offset_ + i] = x_warm_start_[i][1]; x[a_offset_ + i] = x_warm_start_[i][2]; } } if (use_soft_safety_bound_) { for (int i = 0; i < num_of_points_; ++i) { x[lower_s_slack_offset_ + i] = 0.0; x[upper_s_slack_offset_ + i] = 0.0; } } return true; // TODO(Jinyun): Implement better default warm start based on safety_bounds for (int i = 0; i < num_of_points_; ++i) { x[i] = std::min(5.0 * delta_t_ * i + s_init_, s_max_); } x[0] = s_init_; for (int i = 0; i < num_of_points_; ++i) { x[v_offset_ + i] = 5.0; } x[v_offset_] = s_dot_init_; for (int i = 0; i < num_of_points_; ++i) { x[a_offset_ + i] = 0.0; } x[a_offset_] = s_ddot_init_; if (use_soft_safety_bound_) { for (int i = 0; i < num_of_points_; ++i) { x[lower_s_slack_offset_ + i] = 0.0; x[upper_s_slack_offset_ + i] = 0.0; } } return true; } bool PiecewiseJerkSpeedNonlinearIpoptInterface::eval_f(int n, const double *x, bool new_x, double &obj_value) { obj_value = 0.0; // difference between ref spatial distace for (int i = 0; i < num_of_points_; ++i) { double s_diff = x[i] - s_ref_[i]; obj_value += s_diff * s_diff * w_ref_s_; } // difference between ref speed for (int i = 0; i < num_of_points_; ++i) { double v_diff = x[v_offset_ + i] - v_ref_; obj_value += v_diff * v_diff * w_ref_v_; } // acceleration obj. for (int i = 0; i < num_of_points_; ++i) { double a = x[a_offset_ + i]; obj_value += a * a * w_overall_a_; } // jerk obj. for (int i = 0; i + 1 < num_of_points_; ++i) { double j = (x[a_offset_ + i + 1] - x[a_offset_ + i]) / delta_t_; obj_value += j * j * w_overall_j_; } // centripetal acceleration obj. for (int i = 0; i < num_of_points_; ++i) { double v = x[v_offset_ + i]; double s = x[i]; double kappa = curvature_curve_.Evaluate(0, s); double a_lat = v * v * kappa; obj_value += a_lat * a_lat * w_overall_centripetal_acc_; } if (has_end_state_target_) { double s_diff = x[num_of_points_ - 1] - s_target_; obj_value += s_diff * s_diff * w_target_s_; double v_diff = x[v_offset_ + num_of_points_ - 1] - v_target_; obj_value += v_diff * v_diff * w_target_v_; double a_diff = x[a_offset_ + num_of_points_ - 1] - a_target_; obj_value += a_diff * a_diff * w_target_a_; } if (use_soft_safety_bound_) { for (int i = 0; i < num_of_points_; ++i) { obj_value += x[lower_s_slack_offset_ + i] * w_soft_s_bound_; obj_value += x[upper_s_slack_offset_ + i] * w_soft_s_bound_; } } return true; } bool PiecewiseJerkSpeedNonlinearIpoptInterface::eval_grad_f(int n, const double *x, bool new_x, double *grad_f) { std::fill(grad_f, grad_f + n, 0.0); // ref. spatial distance objective for (int i = 0; i < num_of_points_; ++i) { auto s_diff = x[i] - s_ref_[i]; grad_f[i] += 2.0 * s_diff * w_ref_s_; } // ref. speed objective for (int i = 0; i < num_of_points_; ++i) { auto v_diff = x[v_offset_ + i] - v_ref_; grad_f[v_offset_ + i] += 2.0 * v_diff * w_ref_v_; } // jerk objective double c = 2.0 / (delta_t_ * delta_t_) * w_overall_j_; grad_f[a_offset_] += -c * (x[a_offset_ + 1] - x[a_offset_]); for (int i = 1; i + 1 < num_of_points_; ++i) { grad_f[a_offset_ + i] += c * (2.0 * x[a_offset_ + i] - x[a_offset_ + i + 1] - x[a_offset_ + i - 1]); } grad_f[a_offset_ + num_of_points_ - 1] += c * (x[a_offset_ + num_of_points_ - 1] - x[a_offset_ + num_of_points_ - 2]); // acceleration objective for (int i = 0; i < num_of_points_; ++i) { grad_f[a_offset_ + i] += 2.0 * x[a_offset_ + i] * w_overall_a_; } // centripetal acceleration objective for (int i = 0; i < num_of_points_; ++i) { double v = x[v_offset_ + i]; double v2 = v * v; double v3 = v2 * v; double v4 = v3 * v; double s = x[i]; double kappa = curvature_curve_.Evaluate(0, s); double kappa_dot = curvature_curve_.Evaluate(1, s); grad_f[i] += 2.0 * w_overall_centripetal_acc_ * v4 * kappa * kappa_dot; grad_f[v_offset_ + i] += 4.0 * w_overall_centripetal_acc_ * v3 * kappa * kappa; } if (has_end_state_target_) { double s_diff = x[num_of_points_ - 1] - s_target_; grad_f[num_of_points_ - 1] += 2.0 * s_diff * w_target_s_; double v_diff = x[v_offset_ + num_of_points_ - 1] - v_target_; grad_f[v_offset_ + num_of_points_ - 1] += 2.0 * v_diff * w_target_v_; double a_diff = x[a_offset_ + num_of_points_ - 1] - a_target_; grad_f[a_offset_ + num_of_points_ - 1] += 2.0 * a_diff * w_target_a_; } if (use_soft_safety_bound_) { for (int i = 0; i < num_of_points_; ++i) { grad_f[lower_s_slack_offset_ + i] += w_soft_s_bound_; grad_f[upper_s_slack_offset_ + i] += w_soft_s_bound_; } } return true; } bool PiecewiseJerkSpeedNonlinearIpoptInterface::eval_g(int n, const double *x, bool new_x, int m, double *g) { int offset = 0; // s monotone constraints s_i+1 - s_i for (int i = 0; i + 1 < num_of_points_; ++i) { g[i] = x[offset + i + 1] - x[i]; } offset += num_of_points_ - 1; // jerk bound constraint, |s_ddot_i+1 - s_ddot_i| <= s_dddot_max // position equality constraints, // s_i+1 - s_i - s_dot_i * delta_t - 1/3 * s_ddot_i * delta_t^2 - 1/6 * // s_ddot_i+1 * delta_t^2 // velocity equality constraints // s_dot_i+1 - s_dot_i - 0.5 * delta_t * (s_ddot_i + s_ddot_i+1) int coffset_jerk = offset; int coffset_position = coffset_jerk + num_of_points_ - 1; int coffset_velocity = coffset_position + num_of_points_ - 1; double t = delta_t_; double t2 = t * t; double t3 = t2 * t; for (int i = 0; i + 1 < num_of_points_; ++i) { double s0 = x[i]; double s1 = x[i + 1]; double v0 = x[v_offset_ + i]; double v1 = x[v_offset_ + i + 1]; double a0 = x[a_offset_ + i]; double a1 = x[a_offset_ + i + 1]; double j = (a1 - a0) / t; g[coffset_jerk + i] = j; g[coffset_position + i] = s1 - (s0 + v0 * t + 0.5 * a0 * t2 + 1.0 / 6.0 * j * t3); g[coffset_velocity + i] = v1 - (v0 + a0 * t + 0.5 * j * t2); } offset += 3 * (num_of_points_ - 1); if (use_v_bound_) { // speed limit constraints int coffset_speed_limit = offset; // s_dot_i - v_bound_func_(s_i) <= 0.0 for (int i = 0; i < num_of_points_; ++i) { double s = x[i]; double s_dot = x[v_offset_ + i]; g[coffset_speed_limit + i] = s_dot - v_bound_func_.Evaluate(0, s); } offset += num_of_points_; } if (use_soft_safety_bound_) { // soft safety boundary constraints int coffset_soft_lower_s = offset; // s_i - soft_lower_s_i + lower_slack_i >= 0.0 for (int i = 0; i < num_of_points_; ++i) { double s = x[i]; double lower_s_slack = x[lower_s_slack_offset_ + i]; g[coffset_soft_lower_s + i] = s - soft_safety_bounds_[i].first + lower_s_slack; } offset += num_of_points_; int coffset_soft_upper_s = offset; // s_i - soft_upper_s_i - upper_slack_i <= 0.0 for (int i = 0; i < num_of_points_; ++i) { double s = x[i]; double upper_s_slack = x[upper_s_slack_offset_ + i]; g[coffset_soft_upper_s + i] = s - soft_safety_bounds_[i].second - upper_s_slack; } offset += num_of_points_; } return true; } bool PiecewiseJerkSpeedNonlinearIpoptInterface::eval_jac_g( int n, const double *x, bool new_x, int m, int nele_jac, int *iRow, int *jCol, double *values) { if (values == nullptr) { int non_zero_index = 0; int constraint_index = 0; // s monotone constraints s_i+1 - s_i for (int i = 0; i + 1 < num_of_points_; ++i) { // s_i iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = i; ++non_zero_index; // s_i+1 iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = i + 1; ++non_zero_index; ++constraint_index; } // jerk bound constraint, |s_ddot_i+1 - s_ddot_i| / delta_t <= s_dddot_max for (int i = 0; i + 1 < num_of_points_; ++i) { // a_i iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = a_offset_ + i; ++non_zero_index; // a_i+1 iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = a_offset_ + i + 1; ++non_zero_index; ++constraint_index; } // position equality constraints for (int i = 0; i + 1 < num_of_points_; ++i) { // s_i iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = i; ++non_zero_index; // v_i iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = v_offset_ + i; ++non_zero_index; // a_i iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = a_offset_ + i; ++non_zero_index; // s_i+1 iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = i + 1; ++non_zero_index; // a_i+1 iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = a_offset_ + i + 1; ++non_zero_index; ++constraint_index; } // velocity equality constraints for (int i = 0; i + 1 < num_of_points_; ++i) { // v_i iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = v_offset_ + i; ++non_zero_index; // a_i iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = a_offset_ + i; ++non_zero_index; // v_i+1 iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = v_offset_ + i + 1; ++non_zero_index; // a_i+1 iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = a_offset_ + i + 1; ++non_zero_index; ++constraint_index; } if (use_v_bound_) { // speed limit constraints // s_dot_i - v_bound_func_(s_i) <= 0.0 for (int i = 0; i < num_of_points_; ++i) { // s_i iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = i; ++non_zero_index; // v_i iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = v_offset_ + i; ++non_zero_index; ++constraint_index; } } if (use_soft_safety_bound_) { // soft_s_bound constraints // s_i - soft_lower_s_i + lower_slack_i >= 0.0 for (int i = 0; i < num_of_points_; ++i) { // s_i iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = i; ++non_zero_index; // lower_slack_i iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = lower_s_slack_offset_ + i; ++non_zero_index; ++constraint_index; } // s_i - soft_upper_s_i - upper_slack_i <= 0.0 for (int i = 0; i < num_of_points_; ++i) { // s_i iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = i; ++non_zero_index; // upper_slack_i iRow[non_zero_index] = constraint_index; jCol[non_zero_index] = upper_s_slack_offset_ + i; ++non_zero_index; ++constraint_index; } } } else { int non_zero_index = 0; // s monotone constraints s_i+1 - s_i for (int i = 0; i + 1 < num_of_points_; ++i) { // s_i values[non_zero_index] = -1.0; ++non_zero_index; // s_i+1 values[non_zero_index] = 1.0; ++non_zero_index; } // jerk bound constraint, |s_ddot_i+1 - s_ddot_i| / delta_t <= s_dddot_max for (int i = 0; i + 1 < num_of_points_; ++i) { // a_i values[non_zero_index] = -1.0 / delta_t_; ++non_zero_index; // a_i+1 values[non_zero_index] = 1.0 / delta_t_; ++non_zero_index; } // position equality constraints for (int i = 0; i + 1 < num_of_points_; ++i) { // s_i values[non_zero_index] = -1.0; ++non_zero_index; // v_i values[non_zero_index] = -delta_t_; ++non_zero_index; // a_i values[non_zero_index] = -1.0 / 3.0 * delta_t_ * delta_t_; ++non_zero_index; // s_i+1 values[non_zero_index] = 1.0; ++non_zero_index; // a_i+1 values[non_zero_index] = -1.0 / 6.0 * delta_t_ * delta_t_; ++non_zero_index; } // velocity equality constraints for (int i = 0; i + 1 < num_of_points_; ++i) { // v_i values[non_zero_index] = -1.0; ++non_zero_index; // a_i values[non_zero_index] = -0.5 * delta_t_; ++non_zero_index; // v_i+1 values[non_zero_index] = 1.0; ++non_zero_index; // a_i+1 values[non_zero_index] = -0.5 * delta_t_; ++non_zero_index; } if (use_v_bound_) { // speed limit constraints // s_dot_i - v_bound_func_(s_i) <= 0.0 for (int i = 0; i < num_of_points_; ++i) { // s_i double s = x[i]; values[non_zero_index] = -1.0 * v_bound_func_.Evaluate(1, s); ++non_zero_index; // v_i values[non_zero_index] = 1.0; ++non_zero_index; } } if (use_soft_safety_bound_) { // soft_s_bound constraints // s_i - soft_lower_s_i + lower_slack_i >= 0.0 for (int i = 0; i < num_of_points_; ++i) { // s_i values[non_zero_index] = 1.0; ++non_zero_index; // lower_slack_i values[non_zero_index] = 1.0; ++non_zero_index; } // s_i - soft_upper_s_i - upper_slack_i <= 0.0 for (int i = 0; i < num_of_points_; ++i) { // s_i values[non_zero_index] = 1.0; ++non_zero_index; // upper_slack_i values[non_zero_index] = -1.0; ++non_zero_index; } } } return true; } bool PiecewiseJerkSpeedNonlinearIpoptInterface::eval_h( int n, const double *x, bool new_x, double obj_factor, int m, const double *lambda, bool new_lambda, int nele_hess, int *iRow, int *jCol, double *values) { if (values == nullptr) { int nz_index = 0; for (int i = 0; i < num_of_points_; ++i) { iRow[nz_index] = i; jCol[nz_index] = i; ++nz_index; } for (int i = 0; i < num_of_points_; ++i) { iRow[nz_index] = i; jCol[nz_index] = v_offset_ + i; ++nz_index; } for (int i = 0; i < num_of_points_; ++i) { iRow[nz_index] = v_offset_ + i; jCol[nz_index] = v_offset_ + i; ++nz_index; } for (int i = 0; i < num_of_points_; ++i) { iRow[nz_index] = a_offset_ + i; jCol[nz_index] = a_offset_ + i; ++nz_index; } for (int i = 0; i + 1 < num_of_points_; ++i) { iRow[nz_index] = a_offset_ + i; jCol[nz_index] = a_offset_ + i + 1; ++nz_index; } for (int i = 0; i < nz_index; ++i) { int r = iRow[i]; int c = jCol[i]; hessian_mapper_[to_hash_key(r, c)] = i; } } else { std::fill(values, values + nele_hess, 0.0); // speed by curvature objective for (int i = 0; i < num_of_points_; ++i) { auto s_index = i; auto v_index = v_offset_ + i; auto s = x[s_index]; auto v = x[v_index]; auto kappa = curvature_curve_.Evaluate(0, s); auto kappa_dot = curvature_curve_.Evaluate(1, s); auto kappa_ddot = curvature_curve_.Evaluate(2, s); auto v2 = v * v; auto v3 = v2 * v; auto v4 = v3 * v; auto h_s_s_obj = 2.0 * kappa_dot * kappa_dot * v4 + 2.0 * kappa * kappa_ddot * v4; auto h_s_s_index = hessian_mapper_[to_hash_key(s_index, s_index)]; values[h_s_s_index] += h_s_s_obj * w_overall_centripetal_acc_ * obj_factor; auto h_s_v_obj = 8.0 * kappa * kappa_dot * v3; auto h_s_v_index = hessian_mapper_[to_hash_key(s_index, v_index)]; values[h_s_v_index] += h_s_v_obj * w_overall_centripetal_acc_ * obj_factor; auto h_v_v_obj = 12.0 * kappa * kappa * v2; auto h_v_v_index = hessian_mapper_[to_hash_key(v_index, v_index)]; values[h_v_v_index] += h_v_v_obj * w_overall_centripetal_acc_ * obj_factor; } // spatial distance reference objective for (int i = 0; i < num_of_points_; ++i) { auto h_s_s_index = hessian_mapper_[to_hash_key(i, i)]; values[h_s_s_index] += 2.0 * w_ref_s_ * obj_factor; } // speed limit constraint if (use_v_bound_) { int lambda_offset = 4 * (num_of_points_ - 1); for (int i = 0; i < num_of_points_; ++i) { auto s_index = i; auto s = x[s_index]; auto v_bound_ddot = v_bound_func_.Evaluate(2, s); auto h_s_s_constr = -1.0 * v_bound_ddot; auto h_s_s_index = hessian_mapper_[to_hash_key(s_index, s_index)]; values[h_s_s_index] += h_s_s_constr * lambda[lambda_offset + i]; } } for (int i = 0; i < num_of_points_; ++i) { auto a_index = a_offset_ + i; auto h_index = hessian_mapper_[to_hash_key(a_index, a_index)]; values[h_index] += 2.0 * w_overall_a_ * obj_factor; } auto c = 2.0 / delta_t_ / delta_t_ * w_overall_j_ * obj_factor; for (int i = 0; i + 1 < num_of_points_; ++i) { auto a0_index = a_offset_ + i; auto a1_index = a_offset_ + i + 1; auto h_a0_a0_index = hessian_mapper_[to_hash_key(a0_index, a0_index)]; values[h_a0_a0_index] += c; auto h_a0_a1_index = hessian_mapper_[to_hash_key(a0_index, a1_index)]; values[h_a0_a1_index] += -c; auto h_a1_a1_index = hessian_mapper_[to_hash_key(a1_index, a1_index)]; values[h_a1_a1_index] += c; } for (int i = 0; i < num_of_points_; ++i) { auto v_index = i + v_offset_; auto key = to_hash_key(v_index, v_index); auto index = hessian_mapper_[key]; values[index] += 2.0 * w_ref_v_ * obj_factor; } if (has_end_state_target_) { // target s auto s_end_index = num_of_points_ - 1; auto s_key = to_hash_key(s_end_index, s_end_index); auto s_index = hessian_mapper_[s_key]; values[s_index] += 2.0 * w_target_s_ * obj_factor; // target v auto v_end_index = 2 * num_of_points_ - 1; auto v_key = to_hash_key(v_end_index, v_end_index); auto v_index = hessian_mapper_[v_key]; values[v_index] += 2.0 * w_target_v_ * obj_factor; // target a auto a_end_index = 3 * num_of_points_ - 1; auto a_key = to_hash_key(a_end_index, a_end_index); auto a_index = hessian_mapper_[a_key]; values[a_index] += 2.0 * w_target_a_ * obj_factor; } } return true; } void PiecewiseJerkSpeedNonlinearIpoptInterface::get_optimization_results( std::vector<double> *ptr_opt_s, std::vector<double> *ptr_opt_v, std::vector<double> *ptr_opt_a) { *ptr_opt_s = opt_s_; *ptr_opt_v = opt_v_; *ptr_opt_a = opt_a_; } void PiecewiseJerkSpeedNonlinearIpoptInterface::finalize_solution( Ipopt::SolverReturn status, int n, const double *x, const double *z_L, const double *z_U, int m, const double *g, const double *lambda, double obj_value, const Ipopt::IpoptData *ip_data, Ipopt::IpoptCalculatedQuantities *ip_cq) { opt_s_.clear(); opt_v_.clear(); opt_a_.clear(); for (int i = 0; i < num_of_points_; ++i) { double s = x[i]; double v = x[v_offset_ + i]; double a = x[a_offset_ + i]; opt_s_.push_back(s); opt_v_.push_back(v); opt_a_.push_back(a); } if (use_soft_safety_bound_) { // statistic analysis on soft bound intrusion by inspecting slack variable double lower_s_mean_intrusion = 0.0; double lower_s_highest_intrusion = -std::numeric_limits<double>::infinity(); int lower_s_highest_intrustion_index = 0.0; double upper_s_mean_intrusion = 0.0; double upper_s_highest_intrusion = -std::numeric_limits<double>::infinity(); int upper_s_highest_intrustion_index = 0.0; for (int i = 0; i < num_of_points_; ++i) { double lower_s_slack = x[lower_s_slack_offset_ + i]; double upper_s_slack = x[upper_s_slack_offset_ + i]; lower_s_mean_intrusion += lower_s_slack; upper_s_mean_intrusion += upper_s_slack; if (lower_s_highest_intrusion < lower_s_slack) { lower_s_highest_intrusion = lower_s_slack; lower_s_highest_intrustion_index = i; } if (upper_s_highest_intrusion < upper_s_slack) { upper_s_highest_intrusion = upper_s_slack; upper_s_highest_intrustion_index = i; } } lower_s_mean_intrusion /= static_cast<double>(num_of_points_); upper_s_mean_intrusion /= static_cast<double>(num_of_points_); ADEBUG << "lower soft s boundary average intrustion is [" << lower_s_mean_intrusion << "] with highest value of [" << lower_s_highest_intrusion << "] at time [" << delta_t_ * static_cast<double>(lower_s_highest_intrustion_index) << "]."; ADEBUG << "upper soft s boundary average intrustion is [" << upper_s_mean_intrusion << "] with highest value of [" << upper_s_highest_intrusion << "] at time [" << delta_t_ * static_cast<double>(upper_s_highest_intrustion_index) << "]."; } } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_curvature_curve( const PiecewiseJerkTrajectory1d &curvature_curve) { curvature_curve_ = curvature_curve; } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_speed_limit_curve( const PiecewiseJerkTrajectory1d &v_bound_f) { v_bound_func_ = v_bound_f; use_v_bound_ = true; } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_reference_speed( const double v_ref) { v_ref_ = v_ref; } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_safety_bounds( const std::vector<std::pair<double, double>> &safety_bounds) { safety_bounds_ = safety_bounds; } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_soft_safety_bounds( const std::vector<std::pair<double, double>> &soft_safety_bounds) { soft_safety_bounds_ = soft_safety_bounds; use_soft_safety_bound_ = true; } int PiecewiseJerkSpeedNonlinearIpoptInterface::to_hash_key(const int i, const int j) const { return i * num_of_variables_ + j; } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_end_state_target( const double s_target, const double v_target, const double a_target) { s_target_ = s_target; v_target_ = v_target; a_target_ = a_target; has_end_state_target_ = true; } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_w_target_state( const double w_target_s, const double w_target_v, const double w_target_a) { w_target_s_ = w_target_s; w_target_v_ = w_target_v; w_target_a_ = w_target_a; } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_w_overall_a( const double w_overall_a) { w_overall_a_ = w_overall_a; } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_w_overall_j( const double w_overall_j) { w_overall_j_ = w_overall_j; } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_w_overall_centripetal_acc( const double w_overall_centripetal_acc) { w_overall_centripetal_acc_ = w_overall_centripetal_acc; } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_w_reference_speed( const double w_reference_speed) { w_ref_v_ = w_reference_speed; } void PiecewiseJerkSpeedNonlinearIpoptInterface:: set_w_reference_spatial_distance(const double w_ref_s) { w_ref_s_ = w_ref_s; } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_w_soft_s_bound( const double w_soft_s_bound) { w_soft_s_bound_ = w_soft_s_bound; } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_warm_start( const std::vector<std::vector<double>> &speed_profile) { x_warm_start_ = speed_profile; } void PiecewiseJerkSpeedNonlinearIpoptInterface::set_reference_spatial_distance( const std::vector<double> &s_ref) { s_ref_ = s_ref; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/open_space_trajectory_generation/open_space_trajectory_optimizer_test.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/optimizers/open_space_trajectory_generation/open_space_trajectory_optimizer.h" #include "gtest/gtest.h" #include "modules/planning/proto/open_space_task_config.pb.h" namespace apollo { namespace planning { class OpenSpaceTrajectoryOptimizerTest : public ::testing::Test { public: virtual void SetUp() { OpenSpaceTrajectoryOptimizer open_space_trajectory_optimizer(config); } protected: OpenSpaceTrajectoryOptimizerConfig config; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/open_space_trajectory_generation/open_space_trajectory_provider_test.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/optimizers/open_space_trajectory_generation/open_space_trajectory_provider.h" #include "gtest/gtest.h" #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { class OpenSpaceTrajectoryProviderTest : public ::testing::Test { public: virtual void SetUp() { config_.set_task_type(TaskConfig::OPEN_SPACE_TRAJECTORY_PROVIDER); injector_ = std::make_shared<DependencyInjector>(); } protected: TaskConfig config_; std::shared_ptr<DependencyInjector> injector_; }; // TEST_F(OpenSpaceTrajectoryProviderTest, Init) { // OpenSpaceTrajectoryProvider open_space_trajectory_provider(config_); // EXPECT_EQ(open_space_trajectory_provider.Name(), // TaskConfig::TaskType_Name(config_.task_type())); // } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/open_space_trajectory_generation/open_space_trajectory_optimizer.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 <vector> #include "Eigen/Eigen" #ifdef ALIVE #undef ALIVE #endif #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/math/vec2d.h" #include "modules/common/vehicle_state/proto/vehicle_state.pb.h" #include "modules/planning/common/trajectory/discretized_trajectory.h" #include "modules/planning/open_space/coarse_trajectory_generator/hybrid_a_star.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_problem.h" #include "modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_problem.h" #include "modules/planning/open_space/trajectory_smoother/iterative_anchoring_smoother.h" #include "modules/planning/proto/open_space_task_config.pb.h" namespace apollo { namespace planning { class OpenSpaceTrajectoryOptimizer { public: OpenSpaceTrajectoryOptimizer( const OpenSpaceTrajectoryOptimizerConfig& config); virtual ~OpenSpaceTrajectoryOptimizer() = default; common::Status Plan( const std::vector<common::TrajectoryPoint>& stitching_trajectory, const std::vector<double>& end_pose, const std::vector<double>& XYbounds, double rotate_angle, const common::math::Vec2d& translate_origin, const Eigen::MatrixXi& obstacles_edges_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const std::vector<std::vector<common::math::Vec2d>>& obstacles_vertices_vec, double* time_latency); void GetStitchingTrajectory( std::vector<common::TrajectoryPoint>* stitching_trajectory) { stitching_trajectory->clear(); *stitching_trajectory = stitching_trajectory_; } void GetOptimizedTrajectory(DiscretizedTrajectory* optimized_trajectory) { optimized_trajectory->clear(); *optimized_trajectory = optimized_trajectory_; } void RecordDebugInfo( const common::TrajectoryPoint& trajectory_stitching_point, const common::math::Vec2d& translate_origin, const double rotate_angle, const std::vector<double>& end_pose, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWs, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& dual_l_result_ds, const Eigen::MatrixXd& dual_n_result_ds, const Eigen::MatrixXd& state_result_ds, const Eigen::MatrixXd& control_result_ds, const Eigen::MatrixXd& time_result_ds, const std::vector<double>& XYbounds, const std::vector<std::vector<common::math::Vec2d>>& obstacles_vertices_vec); void UpdateDebugInfo( ::apollo::planning_internal::OpenSpaceDebug* open_space_debug); apollo::planning_internal::OpenSpaceDebug* mutable_open_space_debug() { return &open_space_debug_; } private: bool IsInitPointNearDestination( const common::TrajectoryPoint& planning_init_point, const std::vector<double>& end_pose, double rotate_angle, const common::math::Vec2d& translate_origin); void PathPointNormalizing(double rotate_angle, const common::math::Vec2d& translate_origin, double* x, double* y, double* phi); void PathPointDeNormalizing(double rotate_angle, const common::math::Vec2d& translate_origin, double* x, double* y, double* phi); void LoadTrajectory(const Eigen::MatrixXd& state_result_ds, const Eigen::MatrixXd& control_result_ds, const Eigen::MatrixXd& time_result_ds); void LoadHybridAstarResultInEigen(HybridAStartResult* result, Eigen::MatrixXd* xWS, Eigen::MatrixXd* uWS); void UseWarmStartAsResult( const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, Eigen::MatrixXd* state_result_ds, Eigen::MatrixXd* control_result_ds, Eigen::MatrixXd* time_result_ds, Eigen::MatrixXd* dual_l_result_ds, Eigen::MatrixXd* dual_n_result_ds); bool GenerateDistanceApproachTraj( const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const std::vector<std::vector<common::math::Vec2d>>& obstacles_vertices_vec, const Eigen::MatrixXd& last_time_u, const double init_v, Eigen::MatrixXd* state_result_ds, Eigen::MatrixXd* control_result_ds, Eigen::MatrixXd* time_result_ds, Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up, Eigen::MatrixXd* dual_l_result_ds, Eigen::MatrixXd* dual_n_result_ds); bool GenerateDecoupledTraj( const Eigen::MatrixXd& xWS, const double init_a, const double init_v, const std::vector<std::vector<common::math::Vec2d>>& obstacles_vertices_vec, Eigen::MatrixXd* state_result_dc, Eigen::MatrixXd* control_result_dc, Eigen::MatrixXd* time_result_dc); void LoadResult(const DiscretizedTrajectory& discretized_trajectory, Eigen::MatrixXd* state_result_dc, Eigen::MatrixXd* control_result_dc, Eigen::MatrixXd* time_result_dc); void CombineTrajectories( const std::vector<Eigen::MatrixXd>& xWS_vec, const std::vector<Eigen::MatrixXd>& uWS_vec, const std::vector<Eigen::MatrixXd>& state_result_ds_vec, const std::vector<Eigen::MatrixXd>& control_result_ds_vec, const std::vector<Eigen::MatrixXd>& time_result_ds_vec, const std::vector<Eigen::MatrixXd>& l_warm_up_vec, const std::vector<Eigen::MatrixXd>& n_warm_up_vec, const std::vector<Eigen::MatrixXd>& dual_l_result_ds_vec, const std::vector<Eigen::MatrixXd>& dual_n_result_ds_vec, Eigen::MatrixXd* xWS, Eigen::MatrixXd* uWS, Eigen::MatrixXd* state_result_ds, Eigen::MatrixXd* control_result_ds, Eigen::MatrixXd* time_result_ds, Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up, Eigen::MatrixXd* dual_l_result_ds, Eigen::MatrixXd* dual_n_result_ds); private: OpenSpaceTrajectoryOptimizerConfig config_; std::unique_ptr<HybridAStar> warm_start_; std::unique_ptr<DistanceApproachProblem> distance_approach_; std::unique_ptr<DualVariableWarmStartProblem> dual_variable_warm_start_; std::unique_ptr<IterativeAnchoringSmoother> iterative_anchoring_smoother_; std::vector<common::TrajectoryPoint> stitching_trajectory_; DiscretizedTrajectory optimized_trajectory_; apollo::planning_internal::OpenSpaceDebug open_space_debug_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/open_space_trajectory_generation/open_space_trajectory_optimizer.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/optimizers/open_space_trajectory_generation/open_space_trajectory_optimizer.h" #include <utility> namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::math::Vec2d; OpenSpaceTrajectoryOptimizer::OpenSpaceTrajectoryOptimizer( const OpenSpaceTrajectoryOptimizerConfig& config) : config_(config) { // Load config AINFO << config_.DebugString(); // Initialize hybrid astar class pointer warm_start_.reset(new HybridAStar(config.planner_open_space_config())); // Initialize dual variable warm start class pointer dual_variable_warm_start_.reset( new DualVariableWarmStartProblem(config.planner_open_space_config())); // Initialize distance approach trajectory smootherclass pointer distance_approach_.reset( new DistanceApproachProblem(config.planner_open_space_config())); // Initialize iterative anchoring smoother config class pointer iterative_anchoring_smoother_.reset( new IterativeAnchoringSmoother(config.planner_open_space_config())); } Status OpenSpaceTrajectoryOptimizer::Plan( const std::vector<common::TrajectoryPoint>& stitching_trajectory, const std::vector<double>& end_pose, const std::vector<double>& XYbounds, double rotate_angle, const Vec2d& translate_origin, const Eigen::MatrixXi& obstacles_edges_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const std::vector<std::vector<Vec2d>>& obstacles_vertices_vec, double* time_latency) { if (XYbounds.empty() || end_pose.empty() || obstacles_edges_num.cols() == 0 || obstacles_A.cols() == 0 || obstacles_b.cols() == 0) { ADEBUG << "OpenSpaceTrajectoryOptimizer input data not ready"; return Status(ErrorCode::PLANNING_ERROR, "OpenSpaceTrajectoryOptimizer input data not ready"); } // Generate Stop trajectory if init point close to destination if (IsInitPointNearDestination(stitching_trajectory.back(), end_pose, rotate_angle, translate_origin)) { ADEBUG << "Planning init point is close to destination, skip new " "trajectory generation"; return Status(ErrorCode::OK, "Planning init point is close to destination, skip new " "trajectory generation"); } const auto start_timestamp = std::chrono::system_clock::now(); // Initiate initial states stitching_trajectory_ = stitching_trajectory; // Init trajectory point is the stitching point from last trajectory const common::TrajectoryPoint trajectory_stitching_point = stitching_trajectory.back(); // init x, y, z would be rotated. double init_x = trajectory_stitching_point.path_point().x(); double init_y = trajectory_stitching_point.path_point().y(); double init_phi = trajectory_stitching_point.path_point().theta(); ADEBUG << "origin x: " << std::setprecision(9) << translate_origin.x(); ADEBUG << "origin y: " << std::setprecision(9) << translate_origin.y(); ADEBUG << "init_x: " << std::setprecision(9) << init_x; ADEBUG << "init_y: " << std::setprecision(9) << init_y; // Rotate and scale the state PathPointNormalizing(rotate_angle, translate_origin, &init_x, &init_y, &init_phi); // Result container for warm start (initial velocity is assumed to be 0 for // now) HybridAStartResult result; if (warm_start_->Plan(init_x, init_y, init_phi, end_pose[0], end_pose[1], end_pose[2], XYbounds, obstacles_vertices_vec, &result)) { ADEBUG << "State warm start problem solved successfully!"; } else { AERROR << "State warm start problem failed to solve"; return Status(ErrorCode::PLANNING_ERROR, "State warm start problem failed to solve"); } // Containers for distance approach trajectory smoothing problem Eigen::MatrixXd xWS; Eigen::MatrixXd uWS; Eigen::MatrixXd state_result_ds; Eigen::MatrixXd control_result_ds; Eigen::MatrixXd time_result_ds; Eigen::MatrixXd l_warm_up; Eigen::MatrixXd n_warm_up; Eigen::MatrixXd dual_l_result_ds; Eigen::MatrixXd dual_n_result_ds; if (FLAGS_enable_parallel_trajectory_smoothing) { std::vector<HybridAStartResult> partition_trajectories; if (!warm_start_->TrajectoryPartition(result, &partition_trajectories)) { return Status(ErrorCode::PLANNING_ERROR, "Hybrid Astar partition failed"); } size_t size = partition_trajectories.size(); std::vector<Eigen::MatrixXd> xWS_vec; std::vector<Eigen::MatrixXd> uWS_vec; std::vector<Eigen::MatrixXd> state_result_ds_vec; std::vector<Eigen::MatrixXd> control_result_ds_vec; std::vector<Eigen::MatrixXd> time_result_ds_vec; std::vector<Eigen::MatrixXd> l_warm_up_vec; std::vector<Eigen::MatrixXd> n_warm_up_vec; std::vector<Eigen::MatrixXd> dual_l_result_ds_vec; std::vector<Eigen::MatrixXd> dual_n_result_ds_vec; xWS_vec.resize(size); uWS_vec.resize(size); state_result_ds_vec.resize(size); control_result_ds_vec.resize(size); time_result_ds_vec.resize(size); l_warm_up_vec.resize(size); n_warm_up_vec.resize(size); dual_l_result_ds_vec.resize(size); dual_n_result_ds_vec.resize(size); // In for loop ADEBUG << "Trajectories size in smoother is " << size; for (size_t i = 0; i < size; ++i) { LoadHybridAstarResultInEigen(&partition_trajectories[i], &xWS_vec[i], &uWS_vec[i]); // checking initial and ending points if (config_.planner_open_space_config() .enable_check_parallel_trajectory()) { AINFO << "trajectory id: " << i; AINFO << "trajectory partitioned size: " << xWS_vec[i].cols(); AINFO << "initial point: " << xWS_vec[i].col(0).transpose(); AINFO << "ending point: " << xWS_vec[i].col(xWS_vec[i].cols() - 1).transpose(); } Eigen::MatrixXd last_time_u(2, 1); double init_v = 0.0; // Stitching point control and velocity is set for first piece of // trajectories. In the next ones, control and velocity are assumed to be // zero as the next trajectories always start from vehicle static state if (i == 0) { const double init_steer = trajectory_stitching_point.steer(); const double init_a = trajectory_stitching_point.a(); last_time_u << init_steer, init_a; init_v = trajectory_stitching_point.v(); } else { last_time_u << 0.0, 0.0; init_v = 0.0; } // TODO(Jinyun): Further testing const auto smoother_start_timestamp = std::chrono::system_clock::now(); switch (config_.trajectory_smoother()) { case OpenSpaceTrajectoryOptimizerConfig::ITERATIVE_ANCHORING_SMOOTHER: { if (!GenerateDecoupledTraj( xWS_vec[i], last_time_u(1, 0), init_v, obstacles_vertices_vec, &state_result_ds_vec[i], &control_result_ds_vec[i], &time_result_ds_vec[i])) { AERROR << "Smoother fail at " << i << "th trajectory"; AERROR << i << "th trajectory size is " << xWS_vec[i].cols(); return Status( ErrorCode::PLANNING_ERROR, "iterative anchoring smoothing problem failed to solve"); } break; } case OpenSpaceTrajectoryOptimizerConfig::DISTANCE_APPROACH: { const double start_system_timestamp = std::chrono::duration<double>( std::chrono::system_clock::now().time_since_epoch()) .count(); if (!GenerateDistanceApproachTraj( xWS_vec[i], uWS_vec[i], XYbounds, obstacles_edges_num, obstacles_A, obstacles_b, obstacles_vertices_vec, last_time_u, init_v, &state_result_ds_vec[i], &control_result_ds_vec[i], &time_result_ds_vec[i], &l_warm_up_vec[i], &n_warm_up_vec[i], &dual_l_result_ds_vec[i], &dual_n_result_ds_vec[i])) { AERROR << "Smoother fail at " << i << "th trajectory with index starts from 0"; AERROR << i << "th trajectory size is " << xWS_vec[i].cols(); AERROR << "State matrix: " << xWS_vec[i]; AERROR << "Control matrix: " << uWS_vec[i]; return Status( ErrorCode::PLANNING_ERROR, "distance approach smoothing problem failed to solve"); } const auto end_system_timestamp = std::chrono::duration<double>( std::chrono::system_clock::now().time_since_epoch()) .count(); const auto time_diff_ms = (end_system_timestamp - start_system_timestamp) * 1000; ADEBUG << "total planning time spend: " << time_diff_ms << " ms."; ADEBUG << i << "th trajectory size is " << xWS_vec[i].cols(); ADEBUG << "average time spend: " << time_diff_ms / xWS_vec[i].cols() << " ms per point."; ADEBUG << "average time spend after smooth: " << time_diff_ms / state_result_ds_vec[i].cols() << " ms per point."; ADEBUG << i << "th smoothed trajectory size is " << state_result_ds_vec[i].cols(); break; } case OpenSpaceTrajectoryOptimizerConfig::USE_WARM_START: { UseWarmStartAsResult(xWS_vec[i], uWS_vec[i], l_warm_up_vec[i], n_warm_up_vec[i], &state_result_ds_vec[i], &control_result_ds_vec[i], &time_result_ds_vec[i], &dual_l_result_ds_vec[i], &dual_n_result_ds_vec[i]); break; } } const auto smoother_end_timestamp = std::chrono::system_clock::now(); std::chrono::duration<double> smoother_diff = smoother_end_timestamp - smoother_start_timestamp; ADEBUG << "Open space trajectory smoothing total time: " << smoother_diff.count() * 1000.0 << " ms at the " << i << "th trajectory."; ADEBUG << "The " << i << "th trajectory pre-smoothing size is " << xWS_vec[i].cols() << "; post-smoothing size is " << state_result_ds_vec[i].cols(); } // Retrive the trajectory in one piece CombineTrajectories(xWS_vec, uWS_vec, state_result_ds_vec, control_result_ds_vec, time_result_ds_vec, l_warm_up_vec, n_warm_up_vec, dual_l_result_ds_vec, dual_n_result_ds_vec, &xWS, &uWS, &state_result_ds, &control_result_ds, &time_result_ds, &l_warm_up, &n_warm_up, &dual_l_result_ds, &dual_n_result_ds); } else { LoadHybridAstarResultInEigen(&result, &xWS, &uWS); const double init_steer = trajectory_stitching_point.steer(); const double init_a = trajectory_stitching_point.a(); Eigen::MatrixXd last_time_u(2, 1); last_time_u << init_steer, init_a; const double init_v = trajectory_stitching_point.v(); if (!GenerateDistanceApproachTraj( xWS, uWS, XYbounds, obstacles_edges_num, obstacles_A, obstacles_b, obstacles_vertices_vec, last_time_u, init_v, &state_result_ds, &control_result_ds, &time_result_ds, &l_warm_up, &n_warm_up, &dual_l_result_ds, &dual_n_result_ds)) { return Status(ErrorCode::PLANNING_ERROR, "distance approach smoothing problem failed to solve"); } } // record debug info if (FLAGS_enable_record_debug) { open_space_debug_.Clear(); RecordDebugInfo(trajectory_stitching_point, translate_origin, rotate_angle, end_pose, xWS, uWS, l_warm_up, n_warm_up, dual_l_result_ds, dual_n_result_ds, state_result_ds, control_result_ds, time_result_ds, XYbounds, obstacles_vertices_vec); } // rescale the states to the world frame size_t state_size = state_result_ds.cols(); for (size_t i = 0; i < state_size; ++i) { PathPointDeNormalizing(rotate_angle, translate_origin, &(state_result_ds(0, i)), &(state_result_ds(1, i)), &(state_result_ds(2, i))); } LoadTrajectory(state_result_ds, control_result_ds, time_result_ds); const auto end_timestamp = std::chrono::system_clock::now(); std::chrono::duration<double> diff = end_timestamp - start_timestamp; ADEBUG << "open space trajectory smoother total time: " << diff.count() * 1000.0 << " ms."; *time_latency = diff.count() * 1000.0; return Status::OK(); } void OpenSpaceTrajectoryOptimizer::RecordDebugInfo( const common::TrajectoryPoint& trajectory_stitching_point, const Vec2d& translate_origin, const double rotate_angle, const std::vector<double>& end_pose, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& dual_l_result_ds, const Eigen::MatrixXd& dual_n_result_ds, const Eigen::MatrixXd& state_result_ds, const Eigen::MatrixXd& control_result_ds, const Eigen::MatrixXd& time_result_ds, const std::vector<double>& XYbounds, const std::vector<std::vector<Vec2d>>& obstacles_vertices_vec) { // load information about trajectory stitching point open_space_debug_.mutable_trajectory_stitching_point()->CopyFrom( trajectory_stitching_point); // load translation origin and heading angle auto* roi_shift_point = open_space_debug_.mutable_roi_shift_point(); // pathpoint roi_shift_point->mutable_path_point()->set_x(translate_origin.x()); roi_shift_point->mutable_path_point()->set_y(translate_origin.y()); roi_shift_point->mutable_path_point()->set_theta(rotate_angle); // load end_pose into debug auto* end_point = open_space_debug_.mutable_end_point(); end_point->mutable_path_point()->set_x(end_pose[0]); end_point->mutable_path_point()->set_y(end_pose[1]); end_point->mutable_path_point()->set_theta(end_pose[2]); end_point->set_v(end_pose[3]); // load warm start trajectory size_t horizon = xWS.cols() - 1; auto* warm_start_trajectory = open_space_debug_.mutable_warm_start_trajectory(); for (size_t i = 0; i < horizon; ++i) { auto* warm_start_point = warm_start_trajectory->add_vehicle_motion_point(); warm_start_point->mutable_trajectory_point()->mutable_path_point()->set_x( xWS(0, i)); warm_start_point->mutable_trajectory_point()->mutable_path_point()->set_y( xWS(1, i)); warm_start_point->mutable_trajectory_point() ->mutable_path_point() ->set_theta(xWS(2, i)); warm_start_point->mutable_trajectory_point()->set_v(xWS(3, i)); warm_start_point->set_steer(uWS(0, i)); warm_start_point->mutable_trajectory_point()->set_a(uWS(1, i)); } auto* warm_start_point = warm_start_trajectory->add_vehicle_motion_point(); warm_start_point->mutable_trajectory_point()->mutable_path_point()->set_x( xWS(0, horizon)); warm_start_point->mutable_trajectory_point()->mutable_path_point()->set_y( xWS(1, horizon)); warm_start_point->mutable_trajectory_point()->mutable_path_point()->set_theta( xWS(2, horizon)); warm_start_point->mutable_trajectory_point()->set_v(xWS(3, horizon)); // load warm start dual variables size_t l_warm_up_rows = l_warm_up.rows(); for (size_t i = 0; i < horizon; ++i) { for (size_t j = 0; j < l_warm_up_rows; j++) { open_space_debug_.add_warm_start_dual_lambda(l_warm_up(j, i)); } } size_t n_warm_up_rows = n_warm_up.rows(); for (size_t i = 0; i < horizon; ++i) { for (size_t j = 0; j < n_warm_up_rows; j++) { open_space_debug_.add_warm_start_dual_miu(n_warm_up(j, i)); } } // load optimized dual variables size_t dual_l_result_ds_rows = dual_l_result_ds.rows(); for (size_t i = 0; i < horizon; ++i) { for (size_t j = 0; j < dual_l_result_ds_rows; j++) { open_space_debug_.add_optimized_dual_lambda(dual_l_result_ds(j, i)); } } size_t dual_n_result_ds_rows = dual_n_result_ds.rows(); for (size_t i = 0; i < horizon; ++i) { for (size_t j = 0; j < dual_n_result_ds_rows; j++) { open_space_debug_.add_optimized_dual_miu(dual_n_result_ds(j, i)); } } double relative_time = 0; // load smoothed trajectory horizon = state_result_ds.cols() - 1; auto* smoothed_trajectory = open_space_debug_.mutable_smoothed_trajectory(); for (size_t i = 0; i < horizon; ++i) { auto* smoothed_point = smoothed_trajectory->add_vehicle_motion_point(); smoothed_point->mutable_trajectory_point()->mutable_path_point()->set_x( state_result_ds(0, i)); smoothed_point->mutable_trajectory_point()->mutable_path_point()->set_y( state_result_ds(1, i)); smoothed_point->mutable_trajectory_point()->mutable_path_point()->set_theta( state_result_ds(2, i)); smoothed_point->mutable_trajectory_point()->set_v(state_result_ds(3, i)); smoothed_point->set_steer(control_result_ds(0, i)); smoothed_point->mutable_trajectory_point()->set_a(control_result_ds(1, i)); relative_time += time_result_ds(0, i); smoothed_point->mutable_trajectory_point()->set_relative_time( relative_time); } auto* smoothed_point = smoothed_trajectory->add_vehicle_motion_point(); smoothed_point->mutable_trajectory_point()->mutable_path_point()->set_x( state_result_ds(0, horizon)); smoothed_point->mutable_trajectory_point()->mutable_path_point()->set_y( state_result_ds(1, horizon)); smoothed_point->mutable_trajectory_point()->mutable_path_point()->set_theta( state_result_ds(2, horizon)); smoothed_point->mutable_trajectory_point()->set_v( state_result_ds(3, horizon)); // load xy boundary (xmin, xmax, ymin, ymax) open_space_debug_.add_xy_boundary(XYbounds[0]); open_space_debug_.add_xy_boundary(XYbounds[1]); open_space_debug_.add_xy_boundary(XYbounds[2]); open_space_debug_.add_xy_boundary(XYbounds[3]); // load obstacles for (const auto& obstacle_vertices : obstacles_vertices_vec) { auto* obstacle_ptr = open_space_debug_.add_obstacles(); for (const auto& vertex : obstacle_vertices) { obstacle_ptr->add_vertices_x_coords(vertex.x()); obstacle_ptr->add_vertices_y_coords(vertex.y()); } } } void OpenSpaceTrajectoryOptimizer::UpdateDebugInfo( planning_internal::OpenSpaceDebug* open_space_debug) { open_space_debug->MergeFrom(open_space_debug_); } bool OpenSpaceTrajectoryOptimizer::IsInitPointNearDestination( const common::TrajectoryPoint& planning_init_point, const std::vector<double>& end_pose, double rotate_angle, const Vec2d& translate_origin) { CHECK_EQ(end_pose.size(), 4U); Vec2d end_pose_to_world_frame = Vec2d(end_pose[0], end_pose[1]); end_pose_to_world_frame.SelfRotate(rotate_angle); end_pose_to_world_frame += translate_origin; const common::PathPoint path_point = planning_init_point.path_point(); double distance_to_init_point = std::sqrt((path_point.x() - end_pose_to_world_frame.x()) * (path_point.x() - end_pose_to_world_frame.x()) + (path_point.y() - end_pose_to_world_frame.y()) * (path_point.y() - end_pose_to_world_frame.y())); if (distance_to_init_point < config_.planner_open_space_config().is_near_destination_threshold()) { return true; } return false; } void OpenSpaceTrajectoryOptimizer::PathPointNormalizing( double rotate_angle, const Vec2d& translate_origin, double* x, double* y, double* phi) { *x -= translate_origin.x(); *y -= translate_origin.y(); double tmp_x = *x; *x = (*x) * std::cos(-rotate_angle) - (*y) * std::sin(-rotate_angle); *y = tmp_x * std::sin(-rotate_angle) + (*y) * std::cos(-rotate_angle); *phi = common::math::NormalizeAngle(*phi - rotate_angle); } void OpenSpaceTrajectoryOptimizer::PathPointDeNormalizing( double rotate_angle, const Vec2d& translate_origin, double* x, double* y, double* phi) { double tmp_x = *x; *x = (*x) * std::cos(rotate_angle) - (*y) * std::sin(rotate_angle); *y = tmp_x * std::sin(rotate_angle) + (*y) * std::cos(rotate_angle); *x += translate_origin.x(); *y += translate_origin.y(); *phi = common::math::NormalizeAngle(*phi + rotate_angle); } void OpenSpaceTrajectoryOptimizer::LoadTrajectory( const Eigen::MatrixXd& state_result, const Eigen::MatrixXd& control_result, const Eigen::MatrixXd& time_result) { optimized_trajectory_.clear(); // Optimizer doesn't take end condition control state into consideration for // now size_t states_size = state_result.cols(); size_t times_size = time_result.cols(); size_t controls_size = control_result.cols(); CHECK_EQ(states_size, times_size + 1); CHECK_EQ(states_size, controls_size + 1); double relative_time = 0.0; double relative_s = 0.0; Vec2d last_path_point(state_result(0, 0), state_result(1, 0)); for (size_t i = 0; i < states_size; ++i) { common::TrajectoryPoint point; point.mutable_path_point()->set_x(state_result(0, i)); point.mutable_path_point()->set_y(state_result(1, i)); point.mutable_path_point()->set_theta(state_result(2, i)); point.set_v(state_result(3, i)); Vec2d cur_path_point(state_result(0, i), state_result(1, i)); relative_s += cur_path_point.DistanceTo(last_path_point); point.mutable_path_point()->set_s(relative_s); // TODO(Jinyun): Evaluate how to set end states control input if (i == controls_size) { point.set_steer(0.0); point.set_a(0.0); } else { point.set_steer(control_result(0, i)); point.set_a(control_result(1, i)); } if (i == 0) { point.set_relative_time(relative_time); } else { relative_time += time_result(0, i - 1); point.set_relative_time(relative_time); } optimized_trajectory_.emplace_back(point); last_path_point = cur_path_point; } } void OpenSpaceTrajectoryOptimizer::UseWarmStartAsResult( const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, Eigen::MatrixXd* state_result_ds, Eigen::MatrixXd* control_result_ds, Eigen::MatrixXd* time_result_ds, Eigen::MatrixXd* dual_l_result_ds, Eigen::MatrixXd* dual_n_result_ds) { AERROR << "Use warm start as trajectory output"; *state_result_ds = xWS; *control_result_ds = uWS; *dual_l_result_ds = l_warm_up; *dual_n_result_ds = n_warm_up; size_t time_result_horizon = xWS.cols() - 1; *time_result_ds = Eigen::MatrixXd::Constant( 1, time_result_horizon, config_.planner_open_space_config().delta_t()); } bool OpenSpaceTrajectoryOptimizer::GenerateDistanceApproachTraj( const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const std::vector<std::vector<Vec2d>>& obstacles_vertices_vec, const Eigen::MatrixXd& last_time_u, const double init_v, Eigen::MatrixXd* state_result_ds, Eigen::MatrixXd* control_result_ds, Eigen::MatrixXd* time_result_ds, Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up, Eigen::MatrixXd* dual_l_result_ds, Eigen::MatrixXd* dual_n_result_ds) { size_t horizon = xWS.cols() - 1; Eigen::MatrixXd x0(4, 1); x0 << xWS(0, 0), xWS(1, 0), xWS(2, 0), init_v; Eigen::MatrixXd xF(4, 1); xF << xWS(0, horizon), xWS(1, horizon), xWS(2, horizon), xWS(3, horizon); UseWarmStartAsResult(xWS, uWS, *l_warm_up, *n_warm_up, state_result_ds, control_result_ds, time_result_ds, dual_l_result_ds, dual_n_result_ds); return true; // load vehicle configuration const common::VehicleParam& vehicle_param_ = common::VehicleConfigHelper::GetConfig().vehicle_param(); double front_to_center = vehicle_param_.front_edge_to_center(); double back_to_center = vehicle_param_.back_edge_to_center(); double left_to_center = vehicle_param_.left_edge_to_center(); double right_to_center = vehicle_param_.right_edge_to_center(); Eigen::MatrixXd ego(4, 1); ego << front_to_center, right_to_center, back_to_center, left_to_center; // Get obstacle num size_t obstacles_num = obstacles_vertices_vec.size(); // Get timestep delta t double ts = config_.planner_open_space_config().delta_t(); // slack_warm_up, temp usage Eigen::MatrixXd s_warm_up = Eigen::MatrixXd::Zero(obstacles_num, horizon + 1); // Dual variable warm start for distance approach problem if (FLAGS_use_dual_variable_warm_start) { if (dual_variable_warm_start_->Solve( horizon, ts, ego, obstacles_num, obstacles_edges_num, obstacles_A, obstacles_b, xWS, l_warm_up, n_warm_up, &s_warm_up)) { ADEBUG << "Dual variable problem solved successfully!"; } else { AERROR << "Dual variable problem failed to solve"; return false; } } else { *l_warm_up = 0.5 * Eigen::MatrixXd::Ones(obstacles_edges_num.sum(), horizon + 1); *n_warm_up = 0.5 * Eigen::MatrixXd::Ones(4 * obstacles_num, horizon + 1); } // Distance approach trajectory smoothing if (distance_approach_->Solve( x0, xF, last_time_u, horizon, ts, ego, xWS, uWS, *l_warm_up, *n_warm_up, s_warm_up, XYbounds, obstacles_num, obstacles_edges_num, obstacles_A, obstacles_b, state_result_ds, control_result_ds, time_result_ds, dual_l_result_ds, dual_n_result_ds)) { ADEBUG << "Distance approach problem solved successfully!"; } else { AERROR << "Distance approach problem failed to solve"; if (FLAGS_enable_smoother_failsafe) { UseWarmStartAsResult(xWS, uWS, *l_warm_up, *n_warm_up, state_result_ds, control_result_ds, time_result_ds, dual_l_result_ds, dual_n_result_ds); } else { return false; } } return true; } // TODO(Jinyun): deprecate the use of Eigen in trajectory smoothing void OpenSpaceTrajectoryOptimizer::LoadHybridAstarResultInEigen( HybridAStartResult* result, Eigen::MatrixXd* xWS, Eigen::MatrixXd* uWS) { // load Warm Start result(horizon is timestep number minus one) size_t horizon = result->x.size() - 1; xWS->resize(4, horizon + 1); uWS->resize(2, horizon); Eigen::VectorXd x = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>( result->x.data(), horizon + 1); Eigen::VectorXd y = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>( result->y.data(), horizon + 1); Eigen::VectorXd phi = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>( result->phi.data(), horizon + 1); Eigen::VectorXd v = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>( result->v.data(), horizon + 1); Eigen::VectorXd steer = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>( result->steer.data(), horizon); Eigen::VectorXd a = Eigen::Map<Eigen::VectorXd, Eigen::Unaligned>(result->a.data(), horizon); xWS->row(0) = std::move(x); xWS->row(1) = std::move(y); xWS->row(2) = std::move(phi); xWS->row(3) = std::move(v); uWS->row(0) = std::move(steer); uWS->row(1) = std::move(a); } void OpenSpaceTrajectoryOptimizer::CombineTrajectories( const std::vector<Eigen::MatrixXd>& xWS_vec, const std::vector<Eigen::MatrixXd>& uWS_vec, const std::vector<Eigen::MatrixXd>& state_result_ds_vec, const std::vector<Eigen::MatrixXd>& control_result_ds_vec, const std::vector<Eigen::MatrixXd>& time_result_ds_vec, const std::vector<Eigen::MatrixXd>& l_warm_up_vec, const std::vector<Eigen::MatrixXd>& n_warm_up_vec, const std::vector<Eigen::MatrixXd>& dual_l_result_ds_vec, const std::vector<Eigen::MatrixXd>& dual_n_result_ds_vec, Eigen::MatrixXd* xWS, Eigen::MatrixXd* uWS, Eigen::MatrixXd* state_result_ds, Eigen::MatrixXd* control_result_ds, Eigen::MatrixXd* time_result_ds, Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up, Eigen::MatrixXd* dual_l_result_ds, Eigen::MatrixXd* dual_n_result_ds) { // Repeated midway state point are not added size_t warm_start_state_size = 0; for (const auto& warm_start_state : xWS_vec) { warm_start_state_size += warm_start_state.cols(); } warm_start_state_size -= xWS_vec.size() - 1; size_t warm_start_control_size = 0; for (const auto& warm_start_control : uWS_vec) { warm_start_control_size += warm_start_control.cols(); } // Repeated midway state point are not added size_t smoothed_state_size = 0; for (const auto& smoothed_state : state_result_ds_vec) { smoothed_state_size += smoothed_state.cols(); } smoothed_state_size -= state_result_ds_vec.size() - 1; size_t smoothed_control_size = 0; for (const auto& smoothed_control : control_result_ds_vec) { smoothed_control_size += smoothed_control.cols(); } size_t time_size = 0; for (const auto& smoothed_time : time_result_ds_vec) { time_size += smoothed_time.cols(); } size_t l_warm_start_size = 0; for (const auto& l_warm_start : l_warm_up_vec) { l_warm_start_size += l_warm_start.cols(); } size_t n_warm_start_size = 0; for (const auto& n_warm_start : n_warm_up_vec) { n_warm_start_size += n_warm_start.cols(); } size_t l_smoothed_size = 0; for (const auto& l_smoothed : dual_l_result_ds_vec) { l_smoothed_size += l_smoothed.cols(); } size_t n_smoothed_size = 0; for (const auto& n_smoothed : dual_n_result_ds_vec) { n_smoothed_size += n_smoothed.cols(); } Eigen::MatrixXd xWS_ = Eigen::MatrixXd::Zero(xWS_vec[0].rows(), warm_start_state_size); Eigen::MatrixXd uWS_ = Eigen::MatrixXd::Zero(uWS_vec[0].rows(), warm_start_control_size); Eigen::MatrixXd state_result_ds_ = Eigen::MatrixXd::Zero(state_result_ds_vec[0].rows(), smoothed_state_size); Eigen::MatrixXd control_result_ds_ = Eigen::MatrixXd::Zero( control_result_ds_vec[0].rows(), smoothed_control_size); Eigen::MatrixXd time_result_ds_ = Eigen::MatrixXd::Zero(time_result_ds_vec[0].rows(), time_size); Eigen::MatrixXd l_warm_up_ = Eigen::MatrixXd::Zero(l_warm_up_vec[0].rows(), l_warm_start_size); Eigen::MatrixXd n_warm_up_ = Eigen::MatrixXd::Zero(n_warm_up_vec[0].rows(), n_warm_start_size); Eigen::MatrixXd dual_l_result_ds_ = Eigen::MatrixXd::Zero(dual_l_result_ds_vec[0].rows(), l_smoothed_size); Eigen::MatrixXd dual_n_result_ds_ = Eigen::MatrixXd::Zero(dual_n_result_ds_vec[0].rows(), n_smoothed_size); size_t traj_size = xWS_vec.size(); uint64_t counter = 0; for (size_t i = 0; i < traj_size; ++i) { // leave out the last repeated point so set column minus one uint64_t warm_start_state_cols = xWS_vec[i].cols() - 1; for (size_t j = 0; j < warm_start_state_cols; ++j) { xWS_.col(counter) = xWS_vec[i].col(j); ++counter; } } xWS_.col(counter) = xWS_vec.back().col(xWS_vec.back().cols() - 1); ++counter; CHECK_EQ(counter, warm_start_state_size); counter = 0; for (size_t i = 0; i < traj_size; ++i) { // leave out the last repeated point so set column minus one uint64_t warm_start_control_cols = uWS_vec[i].cols(); for (size_t j = 0; j < warm_start_control_cols; ++j) { uWS_.col(counter) = uWS_vec[i].col(j); ++counter; } } CHECK_EQ(counter, warm_start_control_size); counter = 0; for (size_t i = 0; i < traj_size; ++i) { // leave out the last repeated point so set column minus one uint64_t smoothed_state_cols = state_result_ds_vec[i].cols() - 1; for (size_t j = 0; j < smoothed_state_cols; ++j) { state_result_ds_.col(counter) = state_result_ds_vec[i].col(j); ++counter; } } state_result_ds_.col(counter) = state_result_ds_vec.back().col(state_result_ds_vec.back().cols() - 1); ++counter; CHECK_EQ(counter, smoothed_state_size); counter = 0; for (size_t i = 0; i < traj_size; ++i) { // leave out the last repeated point so set column minus one uint64_t smoothed_control_cols = control_result_ds_vec[i].cols(); for (size_t j = 0; j < smoothed_control_cols; ++j) { control_result_ds_.col(counter) = control_result_ds_vec[i].col(j); ++counter; } } CHECK_EQ(counter, smoothed_control_size); counter = 0; for (size_t i = 0; i < traj_size; ++i) { // leave out the last repeated point so set column minus one uint64_t time_cols = time_result_ds_vec[i].cols(); for (size_t j = 0; j < time_cols; ++j) { time_result_ds_.col(counter) = time_result_ds_vec[i].col(j); ++counter; } } CHECK_EQ(counter, time_size); counter = 0; for (size_t i = 0; i < traj_size; ++i) { // leave out the last repeated point so set column minus one uint64_t l_warm_up_cols = l_warm_up_vec[i].cols(); for (size_t j = 0; j < l_warm_up_cols; ++j) { l_warm_up_.col(counter) = l_warm_up_vec[i].col(j); ++counter; } } CHECK_EQ(counter, l_warm_start_size); counter = 0; for (size_t i = 0; i < traj_size; ++i) { // leave out the last repeated point so set column minus one uint64_t n_warm_up_cols = n_warm_up_vec[i].cols(); for (size_t j = 0; j < n_warm_up_cols; ++j) { n_warm_up_.col(counter) = n_warm_up_vec[i].col(j); ++counter; } } CHECK_EQ(counter, n_warm_start_size); counter = 0; for (size_t i = 0; i < traj_size; ++i) { // leave out the last repeated point so set column minus one uint64_t dual_l_result_ds_cols = dual_l_result_ds_vec[i].cols(); for (size_t j = 0; j < dual_l_result_ds_cols; ++j) { dual_l_result_ds_.col(counter) = dual_l_result_ds_vec[i].col(j); ++counter; } } CHECK_EQ(counter, l_smoothed_size); counter = 0; for (size_t i = 0; i < traj_size; ++i) { // leave out the last repeated point so set column minus one uint64_t dual_n_result_ds_cols = dual_n_result_ds_vec[i].cols(); for (size_t j = 0; j < dual_n_result_ds_cols; ++j) { dual_n_result_ds_.col(counter) = dual_n_result_ds_vec[i].col(j); ++counter; } } CHECK_EQ(counter, n_smoothed_size); *xWS = std::move(xWS_); *uWS = std::move(uWS_); *state_result_ds = std::move(state_result_ds_); *control_result_ds = std::move(control_result_ds_); *time_result_ds = std::move(time_result_ds_); *l_warm_up = std::move(l_warm_up_); *n_warm_up = std::move(n_warm_up_); *dual_l_result_ds = std::move(dual_l_result_ds_); *dual_n_result_ds = std::move(dual_n_result_ds_); } bool OpenSpaceTrajectoryOptimizer::GenerateDecoupledTraj( const Eigen::MatrixXd& xWS, const double init_a, const double init_v, const std::vector<std::vector<Vec2d>>& obstacles_vertices_vec, Eigen::MatrixXd* state_result_dc, Eigen::MatrixXd* control_result_dc, Eigen::MatrixXd* time_result_dc) { DiscretizedTrajectory smoothed_trajectory; if (!iterative_anchoring_smoother_->Smooth( xWS, init_a, init_v, obstacles_vertices_vec, &smoothed_trajectory)) { return false; } LoadResult(smoothed_trajectory, state_result_dc, control_result_dc, time_result_dc); return true; } // TODO(Jinyun): tmp interface, will refactor void OpenSpaceTrajectoryOptimizer::LoadResult( const DiscretizedTrajectory& discretized_trajectory, Eigen::MatrixXd* state_result_dc, Eigen::MatrixXd* control_result_dc, Eigen::MatrixXd* time_result_dc) { const size_t points_size = discretized_trajectory.size(); CHECK_GT(points_size, 1U); *state_result_dc = Eigen::MatrixXd::Zero(4, points_size); *control_result_dc = Eigen::MatrixXd::Zero(2, points_size - 1); *time_result_dc = Eigen::MatrixXd::Zero(1, points_size - 1); auto& state_result = *state_result_dc; for (size_t i = 0; i < points_size; ++i) { state_result(0, i) = discretized_trajectory[i].path_point().x(); state_result(1, i) = discretized_trajectory[i].path_point().y(); state_result(2, i) = discretized_trajectory[i].path_point().theta(); state_result(3, i) = discretized_trajectory[i].v(); } auto& control_result = *control_result_dc; auto& time_result = *time_result_dc; const double wheel_base = common::VehicleConfigHelper::Instance() ->GetConfig() .vehicle_param() .wheel_base(); for (size_t i = 0; i + 1 < points_size; ++i) { control_result(0, i) = std::atan(discretized_trajectory[i].path_point().kappa() * wheel_base); control_result(1, i) = discretized_trajectory[i].a(); time_result(0, i) = discretized_trajectory[i + 1].relative_time() - discretized_trajectory[i].relative_time(); } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/open_space_trajectory_generation/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\\\""] FOPENMP_COPTS = ["-fopenmp"] cc_library( name = "open_space_trajectory_provider", srcs = ["open_space_trajectory_provider.cc"], hdrs = ["open_space_trajectory_provider.h"], copts = [ "-DMODULE_NAME=\\\"planning\\\"", "-fopenmp", ], deps = [ ":open_space_trajectory_optimizer", "//modules/common/status", "//modules/planning/common:planning_common", "//modules/planning/common:planning_gflags", "//modules/planning/common:trajectory_stitcher", "//modules/planning/common/trajectory:discretized_trajectory", "//modules/planning/tasks:task", "//modules/planning/tasks/optimizers:trajectory_optimizer", ] + if_cuda([ "@local_config_cuda//cuda:cudart", ]) + if_rocm([ "@local_config_rocm//rocm:hip", ]), ) cc_library( name = "open_space_trajectory_optimizer", srcs = ["open_space_trajectory_optimizer.cc"], hdrs = ["open_space_trajectory_optimizer.h"], copts = [ "-DMODULE_NAME=\\\"planning\\\"", "-fopenmp", ], deps = [ "//cyber", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/status", "//modules/common/util", "//modules/common/vehicle_state:vehicle_state_provider", "//modules/planning/common:frame", "//modules/planning/open_space/coarse_trajectory_generator:hybrid_a_star", "//modules/planning/open_space/trajectory_smoother:distance_approach_problem", "//modules/planning/open_space/trajectory_smoother:dual_variable_warm_start_problem", "//modules/planning/open_space/trajectory_smoother:iterative_anchoring_smoother", "//modules/planning/proto:planning_config_cc_proto", "@com_github_gflags_gflags//:gflags", "@eigen", ], ) cc_test( name = "open_space_trajectory_provider_test", size = "small", srcs = ["open_space_trajectory_provider_test.cc"], copts = FOPENMP_COPTS, linkopts = ["-lgomp"], deps = [ ":open_space_trajectory_provider", "@com_google_googletest//:gtest_main", ], ) cc_test( name = "open_space_trajectory_optimizer_test", size = "small", srcs = ["open_space_trajectory_optimizer_test.cc"], copts = FOPENMP_COPTS, linkopts = ["-lgomp"], deps = [ ":open_space_trajectory_optimizer", "@com_google_googletest//:gtest_main", ] + if_cuda([ "@local_config_cuda//cuda:cudart", ]) + if_rocm([ "@local_config_rocm//rocm:hip", ]), ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/open_space_trajectory_generation/open_space_trajectory_provider.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 <vector> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/common/status/status.h" #include "modules/planning/common/trajectory/discretized_trajectory.h" #include "modules/planning/tasks/optimizers/open_space_trajectory_generation/open_space_trajectory_optimizer.h" #include "modules/planning/tasks/optimizers/trajectory_optimizer.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { struct OpenSpaceTrajectoryThreadData { std::vector<common::TrajectoryPoint> stitching_trajectory; std::vector<double> end_pose; std::vector<double> XYbounds; double rotate_angle; apollo::common::math::Vec2d translate_origin; Eigen::MatrixXi obstacles_edges_num; Eigen::MatrixXd obstacles_A; Eigen::MatrixXd obstacles_b; std::vector<std::vector<common::math::Vec2d>> obstacles_vertices_vec; }; class OpenSpaceTrajectoryProvider : public TrajectoryOptimizer { public: OpenSpaceTrajectoryProvider( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); ~OpenSpaceTrajectoryProvider(); void Stop(); void Restart(); private: apollo::common::Status Process() override; void GenerateTrajectoryThread(); bool IsVehicleNearDestination(const common::VehicleState& vehicle_state, const std::vector<double>& end_pose, double rotate_angle, const common::math::Vec2d& translate_origin); bool IsVehicleStopDueToFallBack(const bool is_on_fallback, const common::VehicleState& vehicle_state); void GenerateStopTrajectory(DiscretizedTrajectory* const trajectory_data); void LoadResult(DiscretizedTrajectory* const trajectory_data); void ReuseLastFrameResult(const Frame* last_frame, DiscretizedTrajectory* const trajectory_data); void ReuseLastFrameDebug(const Frame* last_frame); private: bool thread_init_flag_ = false; std::unique_ptr<OpenSpaceTrajectoryOptimizer> open_space_trajectory_optimizer_; size_t optimizer_thread_counter = 0; OpenSpaceTrajectoryThreadData thread_data_; std::future<void> task_future_; std::atomic<bool> is_generation_thread_stop_{false}; std::atomic<bool> trajectory_updated_{false}; std::atomic<bool> data_ready_{false}; std::atomic<bool> trajectory_error_{false}; std::atomic<bool> trajectory_skipped_{false}; std::mutex open_space_mutex_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/open_space_trajectory_generation/open_space_trajectory_provider.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/optimizers/open_space_trajectory_generation/open_space_trajectory_provider.h" #include <memory> #include <string> #include "modules/common/vehicle_state/proto/vehicle_state.pb.h" #include "cyber/task/task.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/trajectory/publishable_trajectory.h" #include "modules/planning/common/trajectory_stitcher.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::math::Vec2d; using apollo::cyber::Clock; OpenSpaceTrajectoryProvider::OpenSpaceTrajectoryProvider( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : TrajectoryOptimizer(config, injector) { open_space_trajectory_optimizer_.reset(new OpenSpaceTrajectoryOptimizer( config.open_space_trajectory_provider_config() .open_space_trajectory_optimizer_config())); AINFO << config_.DebugString(); } OpenSpaceTrajectoryProvider::~OpenSpaceTrajectoryProvider() { if (FLAGS_enable_open_space_planner_thread) { Stop(); } } void OpenSpaceTrajectoryProvider::Stop() { if (FLAGS_enable_open_space_planner_thread) { is_generation_thread_stop_.store(true); if (thread_init_flag_) { task_future_.get(); } trajectory_updated_.store(false); trajectory_error_.store(false); trajectory_skipped_.store(false); optimizer_thread_counter = 0; } } void OpenSpaceTrajectoryProvider::Restart() { if (FLAGS_enable_open_space_planner_thread) { is_generation_thread_stop_.store(true); if (thread_init_flag_) { task_future_.get(); } is_generation_thread_stop_.store(false); thread_init_flag_ = false; trajectory_updated_.store(false); trajectory_error_.store(false); trajectory_skipped_.store(false); optimizer_thread_counter = 0; } } Status OpenSpaceTrajectoryProvider::Process() { ADEBUG << "trajectory provider"; auto trajectory_data = frame_->mutable_open_space_info()->mutable_stitched_trajectory_result(); // generate stop trajectory at park_and_go check_stage if (injector_->planning_context() ->mutable_planning_status() ->mutable_park_and_go() ->in_check_stage()) { ADEBUG << "ParkAndGo Stage Check."; GenerateStopTrajectory(trajectory_data); return Status::OK(); } // Start thread when getting in Process() for the first time if (FLAGS_enable_open_space_planner_thread && !thread_init_flag_) { task_future_ = cyber::Async( &OpenSpaceTrajectoryProvider::GenerateTrajectoryThread, this); thread_init_flag_ = true; } // Get stitching trajectory from last frame const common::VehicleState vehicle_state = frame_->vehicle_state(); auto* previous_frame = injector_->frame_history()->Latest(); // Use complete raw trajectory from last frame for stitching purpose std::vector<TrajectoryPoint> stitching_trajectory; if (!IsVehicleStopDueToFallBack( previous_frame->open_space_info().fallback_flag(), vehicle_state)) { const auto& previous_planning = previous_frame->open_space_info().stitched_trajectory_result(); const auto& previous_planning_header = previous_frame->current_frame_planned_trajectory() .header() .timestamp_sec(); const double planning_cycle_time = FLAGS_open_space_planning_period; PublishableTrajectory last_frame_complete_trajectory( previous_planning_header, previous_planning); std::string replan_reason; const double start_timestamp = Clock::NowInSeconds(); stitching_trajectory = TrajectoryStitcher::ComputeStitchingTrajectory( vehicle_state, start_timestamp, planning_cycle_time, FLAGS_open_space_trajectory_stitching_preserved_length, true, &last_frame_complete_trajectory, &replan_reason); } else { AINFO << "Replan due to fallback stop"; const double planning_cycle_time = 1.0 / static_cast<double>(FLAGS_planning_loop_rate); stitching_trajectory = TrajectoryStitcher::ComputeReinitStitchingTrajectory( planning_cycle_time, vehicle_state); auto* open_space_status = injector_->planning_context() ->mutable_planning_status() ->mutable_open_space(); open_space_status->set_position_init(false); } // Get open_space_info from current frame const auto& open_space_info = frame_->open_space_info(); if (FLAGS_enable_open_space_planner_thread) { ADEBUG << "Open space plan in multi-threads mode"; if (is_generation_thread_stop_) { GenerateStopTrajectory(trajectory_data); return Status(ErrorCode::OK, "Parking finished"); } { std::lock_guard<std::mutex> lock(open_space_mutex_); thread_data_.stitching_trajectory = stitching_trajectory; thread_data_.end_pose = open_space_info.open_space_end_pose(); thread_data_.rotate_angle = open_space_info.origin_heading(); thread_data_.translate_origin = open_space_info.origin_point(); thread_data_.obstacles_edges_num = open_space_info.obstacles_edges_num(); thread_data_.obstacles_A = open_space_info.obstacles_A(); thread_data_.obstacles_b = open_space_info.obstacles_b(); thread_data_.obstacles_vertices_vec = open_space_info.obstacles_vertices_vec(); thread_data_.XYbounds = open_space_info.ROI_xy_boundary(); if (stitching_trajectory.size() <= 1 || !injector_->planning_context() ->mutable_planning_status() ->mutable_open_space() ->position_init()) { data_ready_.store(true); } else { data_ready_.store(false); AINFO << "SKIP BECAUSE HAS PLAN"; } } // Check vehicle state if (IsVehicleNearDestination( vehicle_state, open_space_info.open_space_end_pose(), open_space_info.origin_heading(), open_space_info.origin_point())) { GenerateStopTrajectory(trajectory_data); is_generation_thread_stop_.store(true); return Status(ErrorCode::OK, "Vehicle is near to destination"); } // Check if trajectory updated if (trajectory_updated_) { std::lock_guard<std::mutex> lock(open_space_mutex_); LoadResult(trajectory_data); if (FLAGS_enable_record_debug) { // call merge debug ptr, open_space_trajectory_optimizer_ auto* ptr_debug = frame_->mutable_open_space_info()->mutable_debug(); open_space_trajectory_optimizer_->UpdateDebugInfo( ptr_debug->mutable_planning_data()->mutable_open_space()); // sync debug instance frame_->mutable_open_space_info()->sync_debug_instance(); } data_ready_.store(false); trajectory_updated_.store(false); return Status::OK(); } if (trajectory_error_) { ++optimizer_thread_counter; std::lock_guard<std::mutex> lock(open_space_mutex_); trajectory_error_.store(false); // TODO(Jinyun) Use other fallback mechanism when last iteration smoothing // result has out of bound pathpoint which is not allowed for next // iteration hybrid astar algorithm which requires start position to be // strictly in bound if (optimizer_thread_counter > 1000) { return Status(ErrorCode::PLANNING_ERROR, "open_space_optimizer failed too many times"); } } if (previous_frame->open_space_info().open_space_provider_success()) { ReuseLastFrameResult(previous_frame, trajectory_data); if (FLAGS_enable_record_debug) { // copy previous debug to current frame ReuseLastFrameDebug(previous_frame); } // reuse last frame debug when use last frame traj return Status(ErrorCode::OK, "Waiting for open_space_trajectory_optimizer in " "open_space_trajectory_provider"); } else { GenerateStopTrajectory(trajectory_data); return Status(ErrorCode::OK, "Stop due to computation not finished"); } } else { const auto& end_pose = open_space_info.open_space_end_pose(); const auto& rotate_angle = open_space_info.origin_heading(); const auto& translate_origin = open_space_info.origin_point(); const auto& obstacles_edges_num = open_space_info.obstacles_edges_num(); const auto& obstacles_A = open_space_info.obstacles_A(); const auto& obstacles_b = open_space_info.obstacles_b(); const auto& obstacles_vertices_vec = open_space_info.obstacles_vertices_vec(); const auto& XYbounds = open_space_info.ROI_xy_boundary(); // Check vehicle state if (IsVehicleNearDestination(vehicle_state, end_pose, rotate_angle, translate_origin)) { GenerateStopTrajectory(trajectory_data); return Status(ErrorCode::OK, "Vehicle is near to destination"); } // Generate Trajectory; double time_latency; Status status = open_space_trajectory_optimizer_->Plan( stitching_trajectory, end_pose, XYbounds, rotate_angle, translate_origin, obstacles_edges_num, obstacles_A, obstacles_b, obstacles_vertices_vec, &time_latency); frame_->mutable_open_space_info()->set_time_latency(time_latency); // If status is OK, update vehicle trajectory; if (status == Status::OK()) { LoadResult(trajectory_data); return status; } else { return status; } } return Status(ErrorCode::PLANNING_ERROR); } void OpenSpaceTrajectoryProvider::GenerateTrajectoryThread() { while (!is_generation_thread_stop_) { if (!trajectory_updated_ && data_ready_) { OpenSpaceTrajectoryThreadData thread_data; { std::lock_guard<std::mutex> lock(open_space_mutex_); thread_data = thread_data_; } double time_latency; Status status = open_space_trajectory_optimizer_->Plan( thread_data.stitching_trajectory, thread_data.end_pose, thread_data.XYbounds, thread_data.rotate_angle, thread_data.translate_origin, thread_data.obstacles_edges_num, thread_data.obstacles_A, thread_data.obstacles_b, thread_data.obstacles_vertices_vec, &time_latency); frame_->mutable_open_space_info()->set_time_latency(time_latency); if (status == Status::OK()) { std::lock_guard<std::mutex> lock(open_space_mutex_); trajectory_updated_.store(true); } else { if (status.ok()) { std::lock_guard<std::mutex> lock(open_space_mutex_); trajectory_skipped_.store(true); } else { std::lock_guard<std::mutex> lock(open_space_mutex_); trajectory_error_.store(true); } } } } } bool OpenSpaceTrajectoryProvider::IsVehicleNearDestination( const common::VehicleState& vehicle_state, const std::vector<double>& end_pose, double rotate_angle, const Vec2d& translate_origin) { CHECK_EQ(end_pose.size(), 4U); Vec2d end_pose_to_world_frame = Vec2d(end_pose[0], end_pose[1]); end_pose_to_world_frame.SelfRotate(rotate_angle); end_pose_to_world_frame += translate_origin; double end_theta_to_world_frame = end_pose[2]; end_theta_to_world_frame += rotate_angle; double distance_to_vehicle = std::sqrt((vehicle_state.x() - end_pose_to_world_frame.x()) * (vehicle_state.x() - end_pose_to_world_frame.x()) + (vehicle_state.y() - end_pose_to_world_frame.y()) * (vehicle_state.y() - end_pose_to_world_frame.y())); double theta_to_vehicle = std::abs(common::math::AngleDiff( vehicle_state.heading(), end_theta_to_world_frame)); ADEBUG << "theta_to_vehicle" << theta_to_vehicle << "end_theta_to_world_frame" << end_theta_to_world_frame << "rotate_angle" << rotate_angle; ADEBUG << "is_near_destination_threshold" << config_.open_space_trajectory_provider_config() .open_space_trajectory_optimizer_config() .planner_open_space_config() .is_near_destination_threshold(); // which config file ADEBUG << "is_near_destination_theta_threshold" << config_.open_space_trajectory_provider_config() .open_space_trajectory_optimizer_config() .planner_open_space_config() .is_near_destination_theta_threshold(); if (distance_to_vehicle < config_.open_space_trajectory_provider_config() .open_space_trajectory_optimizer_config() .planner_open_space_config() .is_near_destination_threshold() && theta_to_vehicle < config_.open_space_trajectory_provider_config() .open_space_trajectory_optimizer_config() .planner_open_space_config() .is_near_destination_theta_threshold()) { ADEBUG << "vehicle reach end_pose"; frame_->mutable_open_space_info()->set_destination_reached(true); return true; } return false; } bool OpenSpaceTrajectoryProvider::IsVehicleStopDueToFallBack( const bool is_on_fallback, const common::VehicleState& vehicle_state) { if (!is_on_fallback) { return false; } static constexpr double kEpsilon = 1.0e-1; const double adc_speed = vehicle_state.linear_velocity(); const double adc_acceleration = vehicle_state.linear_acceleration(); if (std::abs(adc_speed) < kEpsilon && std::abs(adc_acceleration) < kEpsilon) { ADEBUG << "ADC stops due to fallback trajectory"; return true; } return false; } void OpenSpaceTrajectoryProvider::GenerateStopTrajectory( DiscretizedTrajectory* const trajectory_data) { double relative_time = 0.0; // TODO(Jinyun) Move to conf static constexpr int stop_trajectory_length = 10; static constexpr double relative_stop_time = 0.1; static constexpr double vEpsilon = 0.00001; double standstill_acceleration = frame_->vehicle_state().linear_velocity() >= -vEpsilon ? -FLAGS_open_space_standstill_acceleration : FLAGS_open_space_standstill_acceleration; trajectory_data->clear(); for (size_t i = 0; i < stop_trajectory_length; i++) { TrajectoryPoint point; point.mutable_path_point()->set_x(frame_->vehicle_state().x()); point.mutable_path_point()->set_y(frame_->vehicle_state().y()); point.mutable_path_point()->set_theta(frame_->vehicle_state().heading()); point.mutable_path_point()->set_s(0.0); point.mutable_path_point()->set_kappa(0.0); point.set_relative_time(relative_time); point.set_v(0.0); point.set_a(standstill_acceleration); trajectory_data->emplace_back(point); relative_time += relative_stop_time; } } void OpenSpaceTrajectoryProvider::LoadResult( DiscretizedTrajectory* const trajectory_data) { // Load unstitched two trajectories into frame for debug trajectory_data->clear(); auto optimizer_trajectory_ptr = frame_->mutable_open_space_info()->mutable_optimizer_trajectory_data(); auto stitching_trajectory_ptr = frame_->mutable_open_space_info()->mutable_stitching_trajectory_data(); open_space_trajectory_optimizer_->GetOptimizedTrajectory( optimizer_trajectory_ptr); open_space_trajectory_optimizer_->GetStitchingTrajectory( stitching_trajectory_ptr); // Stitch two trajectories and load back to trajectory_data from frame size_t optimizer_trajectory_size = optimizer_trajectory_ptr->size(); double stitching_point_relative_time = stitching_trajectory_ptr->back().relative_time(); double stitching_point_relative_s = stitching_trajectory_ptr->back().path_point().s(); for (size_t i = 0; i < optimizer_trajectory_size; ++i) { optimizer_trajectory_ptr->at(i).set_relative_time( optimizer_trajectory_ptr->at(i).relative_time() + stitching_point_relative_time); optimizer_trajectory_ptr->at(i).mutable_path_point()->set_s( optimizer_trajectory_ptr->at(i).path_point().s() + stitching_point_relative_s); } *(trajectory_data) = *(optimizer_trajectory_ptr); // Last point in stitching trajectory is already in optimized trajectory, so // it is deleted frame_->mutable_open_space_info() ->mutable_stitching_trajectory_data() ->pop_back(); trajectory_data->PrependTrajectoryPoints( frame_->open_space_info().stitching_trajectory_data()); frame_->mutable_open_space_info()->set_open_space_provider_success(true); } void OpenSpaceTrajectoryProvider::ReuseLastFrameResult( const Frame* last_frame, DiscretizedTrajectory* const trajectory_data) { *(trajectory_data) = last_frame->open_space_info().stitched_trajectory_result(); frame_->mutable_open_space_info()->set_open_space_provider_success(true); } void OpenSpaceTrajectoryProvider::ReuseLastFrameDebug(const Frame* last_frame) { // reuse last frame's instance auto* ptr_debug = frame_->mutable_open_space_info()->mutable_debug_instance(); ptr_debug->mutable_planning_data()->mutable_open_space()->MergeFrom( last_frame->open_space_info() .debug_instance() .planning_data() .open_space()); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/path_time_heuristic/st_graph_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_graph_point.cc **/ #include "modules/planning/tasks/optimizers/path_time_heuristic/st_graph_point.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { std::uint32_t StGraphPoint::index_s() const { return index_s_; } std::uint32_t StGraphPoint::index_t() const { return index_t_; } const STPoint& StGraphPoint::point() const { return point_; } const StGraphPoint* StGraphPoint::pre_point() const { return pre_point_; } double StGraphPoint::reference_cost() const { return reference_cost_; } double StGraphPoint::obstacle_cost() const { return obstacle_cost_; } double StGraphPoint::spatial_potential_cost() const { return spatial_potential_cost_; } double StGraphPoint::total_cost() const { return total_cost_; } void StGraphPoint::Init(const std::uint32_t index_t, const std::uint32_t index_s, const STPoint& st_point) { index_t_ = index_t; index_s_ = index_s; point_ = st_point; } void StGraphPoint::SetReferenceCost(const double reference_cost) { reference_cost_ = reference_cost; } void StGraphPoint::SetObstacleCost(const double obs_cost) { obstacle_cost_ = obs_cost; } void StGraphPoint::SetSpatialPotentialCost( const double spatial_potential_cost) { spatial_potential_cost_ = spatial_potential_cost; } void StGraphPoint::SetTotalCost(const double total_cost) { total_cost_ = total_cost; } void StGraphPoint::SetPrePoint(const StGraphPoint& pre_point) { pre_point_ = &pre_point; } double StGraphPoint::GetOptimalSpeed() const { return optimal_speed_; } void StGraphPoint::SetOptimalSpeed(const double optimal_speed) { optimal_speed_ = optimal_speed; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/path_time_heuristic/dp_st_cost.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 <unordered_map> #include <utility> #include <vector> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/speed/st_boundary.h" #include "modules/planning/common/speed/st_point.h" #include "modules/planning/proto/st_drivable_boundary.pb.h" #include "modules/planning/proto/task_config.pb.h" #include "modules/planning/tasks/optimizers/path_time_heuristic/st_graph_point.h" namespace apollo { namespace planning { class DpStCost { public: DpStCost(const DpStSpeedOptimizerConfig& config, const double total_t, const double total_s, const std::vector<const Obstacle*>& obstacles, const STDrivableBoundary& st_drivable_boundary, const common::TrajectoryPoint& init_point); double GetObstacleCost(const StGraphPoint& point); double GetSpatialPotentialCost(const StGraphPoint& point); double GetReferenceCost(const STPoint& point, const STPoint& reference_point) const; double GetSpeedCost(const STPoint& first, const STPoint& second, const double speed_limit, const double cruise_speed) const; double GetAccelCostByTwoPoints(const double pre_speed, const STPoint& first, const STPoint& second); double GetAccelCostByThreePoints(const STPoint& first, const STPoint& second, const STPoint& third); double GetJerkCostByTwoPoints(const double pre_speed, const double pre_acc, const STPoint& pre_point, const STPoint& curr_point); double GetJerkCostByThreePoints(const double first_speed, const STPoint& first_point, const STPoint& second_point, const STPoint& third_point); double GetJerkCostByFourPoints(const STPoint& first, const STPoint& second, const STPoint& third, const STPoint& fourth); private: double GetAccelCost(const double accel); double JerkCost(const double jerk); void AddToKeepClearRange(const std::vector<const Obstacle*>& obstacles); static void SortAndMergeRange( std::vector<std::pair<double, double>>* keep_clear_range_); bool InKeepClearRange(double s) const; const DpStSpeedOptimizerConfig& config_; const std::vector<const Obstacle*>& obstacles_; STDrivableBoundary st_drivable_boundary_; const common::TrajectoryPoint& init_point_; double unit_t_ = 0.0; double total_s_ = 0.0; std::unordered_map<std::string, int> boundary_map_; std::vector<std::vector<std::pair<double, double>>> boundary_cost_; std::vector<std::pair<double, double>> keep_clear_range_; std::array<double, 200> accel_cost_; std::array<double, 400> jerk_cost_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/path_time_heuristic/path_time_heuristic_optimizer.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_time_heuristic_optimizer.h **/ #pragma once #include <string> #include "modules/common_msgs/planning_msgs/planning_internal.pb.h" #include "modules/planning/proto/task_config.pb.h" #include "modules/planning/tasks/optimizers/speed_optimizer.h" namespace apollo { namespace planning { /** * @class PathTimeHeuristicOptimizer * @brief PathTimeHeuristicOptimizer does ST graph speed planning with dynamic * programming algorithm. */ class PathTimeHeuristicOptimizer : public SpeedOptimizer { public: explicit PathTimeHeuristicOptimizer(const TaskConfig& config); private: common::Status Process(const PathData& path_data, const common::TrajectoryPoint& init_point, SpeedData* const speed_data) override; bool SearchPathTimeGraph(SpeedData* speed_data) const; private: common::TrajectoryPoint init_point_; SLBoundary adc_sl_boundary_; SpeedHeuristicOptimizerConfig speed_heuristic_optimizer_config_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/path_time_heuristic/st_graph_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_graph_point.h */ #pragma once #include <limits> #include "modules/planning/common/speed/st_point.h" namespace apollo { namespace planning { class StGraphPoint { public: std::uint32_t index_s() const; std::uint32_t index_t() const; const STPoint& point() const; const StGraphPoint* pre_point() const; double reference_cost() const; double obstacle_cost() const; double spatial_potential_cost() const; double total_cost() const; void Init(const std::uint32_t index_t, const std::uint32_t index_s, const STPoint& st_point); // given reference speed profile, reach the cost, including position void SetReferenceCost(const double reference_cost); // given obstacle info, get the cost; void SetObstacleCost(const double obs_cost); // given potential cost for minimal time traversal void SetSpatialPotentialCost(const double spatial_potential_cost); // total cost void SetTotalCost(const double total_cost); void SetPrePoint(const StGraphPoint& pre_point); double GetOptimalSpeed() const; void SetOptimalSpeed(const double optimal_speed); private: STPoint point_; const StGraphPoint* pre_point_ = nullptr; std::uint32_t index_s_ = 0; std::uint32_t index_t_ = 0; double optimal_speed_ = 0.0; double reference_cost_ = 0.0; double obstacle_cost_ = 0.0; double spatial_potential_cost_ = 0.0; double total_cost_ = std::numeric_limits<double>::infinity(); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/path_time_heuristic/dp_st_cost.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/optimizers/path_time_heuristic/dp_st_cost.h" #include <algorithm> #include <limits> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/speed/st_point.h" #include "modules/planning/tasks/utils/st_gap_estimator.h" namespace apollo { namespace planning { namespace { constexpr double kInf = std::numeric_limits<double>::infinity(); } DpStCost::DpStCost(const DpStSpeedOptimizerConfig& config, const double total_t, const double total_s, const std::vector<const Obstacle*>& obstacles, const STDrivableBoundary& st_drivable_boundary, const common::TrajectoryPoint& init_point) : config_(config), obstacles_(obstacles), st_drivable_boundary_(st_drivable_boundary), init_point_(init_point), unit_t_(config.unit_t()), total_s_(total_s) { int index = 0; for (const auto& obstacle : obstacles) { boundary_map_[obstacle->path_st_boundary().id()] = index++; } AddToKeepClearRange(obstacles); const auto dimension_t = static_cast<uint32_t>(std::ceil(total_t / static_cast<double>(unit_t_))) + 1; boundary_cost_.resize(obstacles_.size()); for (auto& vec : boundary_cost_) { vec.resize(dimension_t, std::make_pair(-1.0, -1.0)); } accel_cost_.fill(-1.0); jerk_cost_.fill(-1.0); } void DpStCost::AddToKeepClearRange( const std::vector<const Obstacle*>& obstacles) { for (const auto& obstacle : obstacles) { if (obstacle->path_st_boundary().IsEmpty()) { continue; } if (obstacle->path_st_boundary().boundary_type() != STBoundary::BoundaryType::KEEP_CLEAR) { continue; } double start_s = obstacle->path_st_boundary().min_s(); double end_s = obstacle->path_st_boundary().max_s(); keep_clear_range_.emplace_back(start_s, end_s); } SortAndMergeRange(&keep_clear_range_); } void DpStCost::SortAndMergeRange( std::vector<std::pair<double, double>>* keep_clear_range) { if (!keep_clear_range || keep_clear_range->empty()) { return; } std::sort(keep_clear_range->begin(), keep_clear_range->end()); size_t i = 0; size_t j = i + 1; while (j < keep_clear_range->size()) { if (keep_clear_range->at(i).second < keep_clear_range->at(j).first) { ++i; ++j; } else { keep_clear_range->at(i).second = std::max(keep_clear_range->at(i).second, keep_clear_range->at(j).second); ++j; } } keep_clear_range->resize(i + 1); } bool DpStCost::InKeepClearRange(double s) const { for (const auto& p : keep_clear_range_) { if (p.first <= s && p.second >= s) { return true; } } return false; } double DpStCost::GetObstacleCost(const StGraphPoint& st_graph_point) { const double s = st_graph_point.point().s(); const double t = st_graph_point.point().t(); double cost = 0.0; if (FLAGS_use_st_drivable_boundary) { // TODO(Jiancheng): move to configs static constexpr double boundary_resolution = 0.1; int index = static_cast<int>(t / boundary_resolution); const double lower_bound = st_drivable_boundary_.st_boundary(index).s_lower(); const double upper_bound = st_drivable_boundary_.st_boundary(index).s_upper(); if (s > upper_bound || s < lower_bound) { return kInf; } } for (const auto* obstacle : obstacles_) { // Not applying obstacle approaching cost to virtual obstacle like created // stop fences if (obstacle->IsVirtual()) { continue; } // Stop obstacles are assumed to have a safety margin when mapping them out, // so repelling force in dp st is not needed as it is designed to have adc // stop right at the stop distance we design in prior mapping process if (obstacle->LongitudinalDecision().has_stop()) { continue; } auto boundary = obstacle->path_st_boundary(); if (boundary.min_s() > FLAGS_speed_lon_decision_horizon) { continue; } if (t < boundary.min_t() || t > boundary.max_t()) { continue; } if (boundary.IsPointInBoundary(st_graph_point.point())) { return kInf; } double s_upper = 0.0; double s_lower = 0.0; int boundary_index = boundary_map_[boundary.id()]; if (boundary_cost_[boundary_index][st_graph_point.index_t()].first < 0.0) { boundary.GetBoundarySRange(t, &s_upper, &s_lower); boundary_cost_[boundary_index][st_graph_point.index_t()] = std::make_pair(s_upper, s_lower); } else { s_upper = boundary_cost_[boundary_index][st_graph_point.index_t()].first; s_lower = boundary_cost_[boundary_index][st_graph_point.index_t()].second; } if (s < s_lower) { const double follow_distance_s = config_.safe_distance(); if (s + follow_distance_s < s_lower) { continue; } else { auto s_diff = follow_distance_s - s_lower + s; cost += config_.obstacle_weight() * config_.default_obstacle_cost() * s_diff * s_diff; } } else if (s > s_upper) { const double overtake_distance_s = StGapEstimator::EstimateSafeOvertakingGap(); if (s > s_upper + overtake_distance_s) { // or calculated from velocity continue; } else { auto s_diff = overtake_distance_s + s_upper - s; cost += config_.obstacle_weight() * config_.default_obstacle_cost() * s_diff * s_diff; } } } return cost * unit_t_; } double DpStCost::GetSpatialPotentialCost(const StGraphPoint& point) { return (total_s_ - point.point().s()) * config_.spatial_potential_penalty(); } double DpStCost::GetReferenceCost(const STPoint& point, const STPoint& reference_point) const { return config_.reference_weight() * (point.s() - reference_point.s()) * (point.s() - reference_point.s()) * unit_t_; } double DpStCost::GetSpeedCost(const STPoint& first, const STPoint& second, const double speed_limit, const double cruise_speed) const { double cost = 0.0; const double speed = (second.s() - first.s()) / unit_t_; if (speed < 0) { return kInf; } const double max_adc_stop_speed = common::VehicleConfigHelper::Instance() ->GetConfig() .vehicle_param() .max_abs_speed_when_stopped(); if (speed < max_adc_stop_speed && InKeepClearRange(second.s())) { // first.s in range cost += config_.keep_clear_low_speed_penalty() * unit_t_ * config_.default_speed_cost(); } double det_speed = (speed - speed_limit) / speed_limit; if (det_speed > 0) { cost += config_.exceed_speed_penalty() * config_.default_speed_cost() * (det_speed * det_speed) * unit_t_; } else if (det_speed < 0) { cost += config_.low_speed_penalty() * config_.default_speed_cost() * -det_speed * unit_t_; } if (FLAGS_enable_dp_reference_speed) { double diff_speed = speed - cruise_speed; cost += config_.reference_speed_penalty() * config_.default_speed_cost() * fabs(diff_speed) * unit_t_; } return cost; } double DpStCost::GetAccelCost(const double accel) { double cost = 0.0; static constexpr double kEpsilon = 0.1; static constexpr size_t kShift = 100; const size_t accel_key = static_cast<size_t>(accel / kEpsilon + 0.5 + kShift); DCHECK_LT(accel_key, accel_cost_.size()); if (accel_key >= accel_cost_.size()) { return kInf; } if (accel_cost_.at(accel_key) < 0.0) { const double accel_sq = accel * accel; double max_acc = config_.max_acceleration(); double max_dec = config_.max_deceleration(); double accel_penalty = config_.accel_penalty(); double decel_penalty = config_.decel_penalty(); if (accel > 0.0) { cost = accel_penalty * accel_sq; } else { cost = decel_penalty * accel_sq; } cost += accel_sq * decel_penalty * decel_penalty / (1 + std::exp(1.0 * (accel - max_dec))) + accel_sq * accel_penalty * accel_penalty / (1 + std::exp(-1.0 * (accel - max_acc))); accel_cost_.at(accel_key) = cost; } else { cost = accel_cost_.at(accel_key); } return cost * unit_t_; } double DpStCost::GetAccelCostByThreePoints(const STPoint& first, const STPoint& second, const STPoint& third) { double accel = (first.s() + third.s() - 2 * second.s()) / (unit_t_ * unit_t_); return GetAccelCost(accel); } double DpStCost::GetAccelCostByTwoPoints(const double pre_speed, const STPoint& pre_point, const STPoint& curr_point) { double current_speed = (curr_point.s() - pre_point.s()) / unit_t_; double accel = (current_speed - pre_speed) / unit_t_; return GetAccelCost(accel); } double DpStCost::JerkCost(const double jerk) { double cost = 0.0; static constexpr double kEpsilon = 0.1; static constexpr size_t kShift = 200; const size_t jerk_key = static_cast<size_t>(jerk / kEpsilon + 0.5 + kShift); if (jerk_key >= jerk_cost_.size()) { return kInf; } if (jerk_cost_.at(jerk_key) < 0.0) { double jerk_sq = jerk * jerk; if (jerk > 0) { cost = config_.positive_jerk_coeff() * jerk_sq * unit_t_; } else { cost = config_.negative_jerk_coeff() * jerk_sq * unit_t_; } jerk_cost_.at(jerk_key) = cost; } else { cost = jerk_cost_.at(jerk_key); } // TODO(All): normalize to unit_t_ return cost; } double DpStCost::GetJerkCostByFourPoints(const STPoint& first, const STPoint& second, const STPoint& third, const STPoint& fourth) { double jerk = (fourth.s() - 3 * third.s() + 3 * second.s() - first.s()) / (unit_t_ * unit_t_ * unit_t_); return JerkCost(jerk); } double DpStCost::GetJerkCostByTwoPoints(const double pre_speed, const double pre_acc, const STPoint& pre_point, const STPoint& curr_point) { const double curr_speed = (curr_point.s() - pre_point.s()) / unit_t_; const double curr_accel = (curr_speed - pre_speed) / unit_t_; const double jerk = (curr_accel - pre_acc) / unit_t_; return JerkCost(jerk); } double DpStCost::GetJerkCostByThreePoints(const double first_speed, const STPoint& first, const STPoint& second, const STPoint& third) { const double pre_speed = (second.s() - first.s()) / unit_t_; const double pre_acc = (pre_speed - first_speed) / unit_t_; const double curr_speed = (third.s() - second.s()) / unit_t_; const double curr_acc = (curr_speed - pre_speed) / unit_t_; const double jerk = (curr_acc - pre_acc) / unit_t_; return JerkCost(jerk); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/path_time_heuristic/gridded_path_time_graph.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 gridded_path_time_graph.h **/ #pragma once #include <memory> #include <vector> #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/status/status.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/path_decision.h" #include "modules/planning/common/speed/speed_data.h" #include "modules/planning/common/speed/st_point.h" #include "modules/planning/common/st_graph_data.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/proto/task_config.pb.h" #include "modules/planning/tasks/optimizers/path_time_heuristic/dp_st_cost.h" #include "modules/planning/tasks/optimizers/path_time_heuristic/st_graph_point.h" namespace apollo { namespace planning { class GriddedPathTimeGraph { public: GriddedPathTimeGraph(const StGraphData& st_graph_data, const DpStSpeedOptimizerConfig& dp_config, const std::vector<const Obstacle*>& obstacles, const common::TrajectoryPoint& init_point); common::Status Search(SpeedData* const speed_data); private: common::Status InitCostTable(); common::Status InitSpeedLimitLookUp(); common::Status RetrieveSpeedProfile(SpeedData* const speed_data); common::Status CalculateTotalCost(); // defined for cyber task struct StGraphMessage { StGraphMessage(const uint32_t c_, const int32_t r_) : c(c_), r(r_) {} uint32_t c; uint32_t r; }; void CalculateCostAt(const std::shared_ptr<StGraphMessage>& msg); double CalculateEdgeCost(const STPoint& first, const STPoint& second, const STPoint& third, const STPoint& forth, const double speed_limit, const double cruise_speed); double CalculateEdgeCostForSecondCol(const uint32_t row, const double speed_limit, const double cruise_speed); double CalculateEdgeCostForThirdCol(const uint32_t curr_row, const uint32_t pre_row, const double speed_limit, const double cruise_speed); // get the row-range of next time step void GetRowRange(const StGraphPoint& point, size_t* next_highest_row, size_t* next_lowest_row); private: const StGraphData& st_graph_data_; std::vector<double> speed_limit_by_index_; std::vector<double> spatial_distance_by_index_; // dp st configuration DpStSpeedOptimizerConfig gridded_path_time_graph_config_; // obstacles based on the current reference line const std::vector<const Obstacle*>& obstacles_; // vehicle configuration parameter const common::VehicleParam& vehicle_param_ = common::VehicleConfigHelper::GetConfig().vehicle_param(); // initial status common::TrajectoryPoint init_point_; // cost utility with configuration; DpStCost dp_st_cost_; double total_length_t_ = 0.0; double unit_t_ = 0.0; uint32_t dimension_t_ = 0; double total_length_s_ = 0.0; double dense_unit_s_ = 0.0; double sparse_unit_s_ = 0.0; uint32_t dense_dimension_s_ = 0; uint32_t sparse_dimension_s_ = 0; uint32_t dimension_s_ = 0; double max_acceleration_ = 0.0; double max_deceleration_ = 0.0; // cost_table_[t][s] // row: s, col: t --- NOTICE: Please do NOT change. std::vector<std::vector<StGraphPoint>> cost_table_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/path_time_heuristic/path_time_heuristic_optimizer.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_time_heuristic_optimizer.cc **/ #include "modules/planning/tasks/optimizers/path_time_heuristic/path_time_heuristic_optimizer.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/st_graph_data.h" #include "modules/planning/tasks/optimizers/path_time_heuristic/gridded_path_time_graph.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; PathTimeHeuristicOptimizer::PathTimeHeuristicOptimizer(const TaskConfig& config) : SpeedOptimizer(config) { ACHECK(config.has_speed_heuristic_optimizer_config()); speed_heuristic_optimizer_config_ = config.speed_heuristic_optimizer_config(); } bool PathTimeHeuristicOptimizer::SearchPathTimeGraph( SpeedData* speed_data) const { const auto& dp_st_speed_optimizer_config = reference_line_info_->IsChangeLanePath() ? speed_heuristic_optimizer_config_.lane_change_speed_config() : speed_heuristic_optimizer_config_.default_speed_config(); GriddedPathTimeGraph st_graph( reference_line_info_->st_graph_data(), dp_st_speed_optimizer_config, reference_line_info_->path_decision()->obstacles().Items(), init_point_); if (!st_graph.Search(speed_data).ok()) { AERROR << "failed to search graph with dynamic programming."; return false; } return true; } Status PathTimeHeuristicOptimizer::Process( const PathData& path_data, const common::TrajectoryPoint& init_point, SpeedData* const speed_data) { init_point_ = init_point; if (path_data.discretized_path().empty()) { const std::string msg = "Empty path data"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (!SearchPathTimeGraph(speed_data)) { const std::string msg = absl::StrCat( Name(), ": Failed to search graph with dynamic programming."); AERROR << msg; RecordDebugInfo(*speed_data, reference_line_info_->mutable_st_graph_data() ->mutable_st_graph_debug()); return Status(ErrorCode::PLANNING_ERROR, msg); } RecordDebugInfo( *speed_data, reference_line_info_->mutable_st_graph_data()->mutable_st_graph_debug()); return Status::OK(); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/path_time_heuristic/gridded_path_time_graph_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. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/optimizers/path_time_heuristic/gridded_path_time_graph.h" #include "cyber/common/file.h" #include "cyber/common/log.h" #include "gtest/gtest.h" #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common_msgs/perception_msgs/perception_obstacle.pb.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { using apollo::cyber::common::GetProtoFromFile; class DpStGraphTest : public ::testing::Test { public: virtual void SetUp() { FLAGS_enable_multi_thread_in_dp_st_graph = false; FLAGS_scenario_lane_follow_config_file = "/apollo/modules/planning/conf/scenario/lane_follow_config.pb.txt"; ScenarioConfig config; ACHECK(GetProtoFromFile(FLAGS_scenario_lane_follow_config_file, &config)); PlanningConfig planning_config; const std::string planning_config_file = "/apollo/modules/planning/conf/planning_config.pb.txt"; ACHECK(GetProtoFromFile(planning_config_file, &planning_config)) << "failed to load planning config file " << planning_config_file; DpStSpeedOptimizerConfig default_dp_config; for (const auto& cfg : planning_config.default_task_config()) { if (cfg.task_type() == TaskConfig::SPEED_HEURISTIC_OPTIMIZER) { default_dp_config = cfg.speed_heuristic_optimizer_config().default_speed_config(); break; } } dp_config_ = default_dp_config; for (const auto& stage : config.stage_config()) { for (const auto& cfg : stage.task_config()) { if (cfg.task_type() == TaskConfig::SPEED_HEURISTIC_OPTIMIZER) { dp_config_.MergeFrom( cfg.speed_heuristic_optimizer_config().default_speed_config()); break; } } } AERROR << dp_config_.ShortDebugString(); // speed_limit: for (double s = 0; s < 200.0; s += 1.0) { speed_limit_.AppendSpeedLimit(s, 25.0); } } virtual void TearDown() {} protected: std::list<Obstacle> obstacle_list_; StGraphData st_graph_data_; SpeedLimit speed_limit_; DpStSpeedOptimizerConfig dp_config_; common::TrajectoryPoint init_point_; }; TEST_F(DpStGraphTest, simple) { Obstacle o1; o1.SetId("o1"); obstacle_list_.push_back(o1); std::vector<const Obstacle*> obstacles_; obstacles_.emplace_back(&(obstacle_list_.back())); std::vector<STPoint> upper_points; std::vector<STPoint> lower_points; std::vector<std::pair<STPoint, STPoint>> point_pairs; lower_points.emplace_back(30.0, 4.0); lower_points.emplace_back(30.0, 6.0); upper_points.emplace_back(45.0, 4.0); upper_points.emplace_back(45.0, 6.0); point_pairs.emplace_back(lower_points[0], upper_points[0]); point_pairs.emplace_back(lower_points[1], upper_points[1]); obstacle_list_.back().set_path_st_boundary(STBoundary(point_pairs)); std::vector<const STBoundary*> boundaries; boundaries.push_back(&(obstacles_.back()->path_st_boundary())); init_point_.mutable_path_point()->set_x(0.0); init_point_.mutable_path_point()->set_y(0.0); init_point_.mutable_path_point()->set_z(0.0); init_point_.mutable_path_point()->set_kappa(0.0); init_point_.set_v(10.0); init_point_.set_a(0.0); planning_internal::STGraphDebug st_graph_debug; st_graph_data_ = StGraphData(); st_graph_data_.LoadData(boundaries, 30.0, init_point_, speed_limit_, 5.0, 120.0, 7.0, &st_graph_debug); GriddedPathTimeGraph dp_st_graph(st_graph_data_, dp_config_, obstacles_, init_point_); SpeedData speed_data; auto ret = dp_st_graph.Search(&speed_data); EXPECT_TRUE(ret.ok()); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/path_time_heuristic/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_graph_point", srcs = ["st_graph_point.cc"], hdrs = ["st_graph_point.h"], copts = PLANNING_COPTS, deps = [ "//modules/planning/common:planning_gflags", "//modules/planning/common/speed:st_point", ], ) cc_library( name = "dp_st_cost", srcs = ["dp_st_cost.cc"], hdrs = ["dp_st_cost.h"], copts = PLANNING_COPTS, deps = [ ":st_graph_point", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/planning/common:frame", "//modules/planning/common:obstacle", "//modules/planning/common/speed:st_boundary", "//modules/planning/tasks/utils:st_gap_estimator", ], ) cc_library( name = "gridded_path_time_graph", srcs = ["gridded_path_time_graph.cc"], hdrs = ["gridded_path_time_graph.h"], copts = PLANNING_COPTS, deps = [ ":dp_st_cost", ":st_graph_point", "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common_msgs/config_msgs:vehicle_config_cc_proto", "//modules/common_msgs/basic_msgs:geometry_cc_proto", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/status", "//modules/planning/common:obstacle", "//modules/planning/common:path_decision", "//modules/planning/common:st_graph_data", "//modules/planning/common/speed:speed_data", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/proto:planning_config_cc_proto", ], ) cc_library( name = "path_time_heuristic_optimizer", srcs = ["path_time_heuristic_optimizer.cc"], hdrs = ["path_time_heuristic_optimizer.h"], copts = PLANNING_COPTS, deps = [ ":dp_st_cost", ":gridded_path_time_graph", "//modules/common/configs:vehicle_config_helper", "//modules/common/vehicle_state:vehicle_state_provider", "//modules/planning/common:st_graph_data", "//modules/common_msgs/planning_msgs:planning_internal_cc_proto", "//modules/planning/tasks/deciders/speed_bounds_decider:st_boundary_mapper", "//modules/planning/tasks/optimizers:speed_optimizer", ], ) cc_test( name = "gridded_path_time_graph_test", size = "small", srcs = ["gridded_path_time_graph_test.cc"], data = [ "//modules/planning:planning_conf", ], deps = [ ":gridded_path_time_graph", "//modules/planning/proto:planning_config_cc_proto", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/optimizers
apollo_public_repos/apollo/modules/planning/tasks/optimizers/path_time_heuristic/gridded_path_time_graph.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 gridded_path_time_graph.cc **/ #include "modules/planning/tasks/optimizers/path_time_heuristic/gridded_path_time_graph.h" #include <algorithm> #include <limits> #include <string> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "cyber/common/log.h" #include "cyber/task/task.h" #include "modules/common/math/vec2d.h" #include "modules/common/util/point_factory.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::SpeedPoint; using apollo::common::Status; using apollo::common::util::PointFactory; namespace { static constexpr double kDoubleEpsilon = 1.0e-6; // Continuous-time collision check using linear interpolation as closed-loop // dynamics bool CheckOverlapOnDpStGraph(const std::vector<const STBoundary*>& boundaries, const StGraphPoint& p1, const StGraphPoint& p2) { if (FLAGS_use_st_drivable_boundary) { return false; } for (const auto* boundary : boundaries) { if (boundary->boundary_type() == STBoundary::BoundaryType::KEEP_CLEAR) { continue; } // Check collision between a polygon and a line segment if (boundary->HasOverlap({p1.point(), p2.point()})) { return true; } } return false; } } // namespace GriddedPathTimeGraph::GriddedPathTimeGraph( const StGraphData& st_graph_data, const DpStSpeedOptimizerConfig& dp_config, const std::vector<const Obstacle*>& obstacles, const common::TrajectoryPoint& init_point) : st_graph_data_(st_graph_data), gridded_path_time_graph_config_(dp_config), obstacles_(obstacles), init_point_(init_point), dp_st_cost_(dp_config, st_graph_data_.total_time_by_conf(), st_graph_data_.path_length(), obstacles, st_graph_data_.st_drivable_boundary(), init_point_) { total_length_t_ = st_graph_data_.total_time_by_conf(); unit_t_ = gridded_path_time_graph_config_.unit_t(); total_length_s_ = st_graph_data_.path_length(); dense_unit_s_ = gridded_path_time_graph_config_.dense_unit_s(); sparse_unit_s_ = gridded_path_time_graph_config_.sparse_unit_s(); dense_dimension_s_ = gridded_path_time_graph_config_.dense_dimension_s(); // Safety approach preventing unreachable acceleration/deceleration max_acceleration_ = std::min(std::abs(vehicle_param_.max_acceleration()), std::abs(gridded_path_time_graph_config_.max_acceleration())); max_deceleration_ = -1.0 * std::min(std::abs(vehicle_param_.max_deceleration()), std::abs(gridded_path_time_graph_config_.max_deceleration())); } Status GriddedPathTimeGraph::Search(SpeedData* const speed_data) { static constexpr double kBounadryEpsilon = 1e-2; for (const auto& boundary : st_graph_data_.st_boundaries()) { // KeepClear obstacles not considered in Dp St decision if (boundary->boundary_type() == STBoundary::BoundaryType::KEEP_CLEAR) { continue; } // If init point in collision with obstacle, return speed fallback if (boundary->IsPointInBoundary({0.0, 0.0}) || (std::fabs(boundary->min_t()) < kBounadryEpsilon && std::fabs(boundary->min_s()) < kBounadryEpsilon)) { dimension_t_ = static_cast<uint32_t>(std::ceil( total_length_t_ / static_cast<double>(unit_t_))) + 1; std::vector<SpeedPoint> speed_profile; double t = 0.0; for (uint32_t i = 0; i < dimension_t_; ++i, t += unit_t_) { speed_profile.push_back(PointFactory::ToSpeedPoint(0, t)); } *speed_data = SpeedData(speed_profile); return Status::OK(); } } if (!InitCostTable().ok()) { const std::string msg = "Initialize cost table failed."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (!InitSpeedLimitLookUp().ok()) { const std::string msg = "Initialize speed limit lookup table failed."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (!CalculateTotalCost().ok()) { const std::string msg = "Calculate total cost failed."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (!RetrieveSpeedProfile(speed_data).ok()) { const std::string msg = "Retrieve best speed profile failed."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } return Status::OK(); } Status GriddedPathTimeGraph::InitCostTable() { // Time dimension is homogeneous while Spatial dimension has two resolutions, // dense and sparse with dense resolution coming first in the spatial horizon // Sanity check for numerical stability if (unit_t_ < kDoubleEpsilon) { const std::string msg = "unit_t is smaller than the kDoubleEpsilon."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // Sanity check on s dimension setting if (dense_dimension_s_ < 1) { const std::string msg = "dense_dimension_s is at least 1."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } dimension_t_ = static_cast<uint32_t>(std::ceil( total_length_t_ / static_cast<double>(unit_t_))) + 1; double sparse_length_s = total_length_s_ - static_cast<double>(dense_dimension_s_ - 1) * dense_unit_s_; sparse_dimension_s_ = sparse_length_s > std::numeric_limits<double>::epsilon() ? static_cast<uint32_t>(std::ceil(sparse_length_s / sparse_unit_s_)) : 0; dense_dimension_s_ = sparse_length_s > std::numeric_limits<double>::epsilon() ? dense_dimension_s_ : static_cast<uint32_t>(std::ceil(total_length_s_ / dense_unit_s_)) + 1; dimension_s_ = dense_dimension_s_ + sparse_dimension_s_; // Sanity Check if (dimension_t_ < 1 || dimension_s_ < 1) { const std::string msg = "Dp st cost table size incorrect."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } cost_table_ = std::vector<std::vector<StGraphPoint>>( dimension_t_, std::vector<StGraphPoint>(dimension_s_, StGraphPoint())); double curr_t = 0.0; for (uint32_t i = 0; i < cost_table_.size(); ++i, curr_t += unit_t_) { auto& cost_table_i = cost_table_[i]; double curr_s = 0.0; for (uint32_t j = 0; j < dense_dimension_s_; ++j, curr_s += dense_unit_s_) { cost_table_i[j].Init(i, j, STPoint(curr_s, curr_t)); } curr_s = static_cast<double>(dense_dimension_s_ - 1) * dense_unit_s_ + sparse_unit_s_; for (uint32_t j = dense_dimension_s_; j < cost_table_i.size(); ++j, curr_s += sparse_unit_s_) { cost_table_i[j].Init(i, j, STPoint(curr_s, curr_t)); } } const auto& cost_table_0 = cost_table_[0]; spatial_distance_by_index_ = std::vector<double>(cost_table_0.size(), 0.0); for (uint32_t i = 0; i < cost_table_0.size(); ++i) { spatial_distance_by_index_[i] = cost_table_0[i].point().s(); } return Status::OK(); } Status GriddedPathTimeGraph::InitSpeedLimitLookUp() { speed_limit_by_index_.clear(); speed_limit_by_index_.resize(dimension_s_); const auto& speed_limit = st_graph_data_.speed_limit(); for (uint32_t i = 0; i < dimension_s_; ++i) { speed_limit_by_index_[i] = speed_limit.GetSpeedLimitByS(cost_table_[0][i].point().s()); } return Status::OK(); } Status GriddedPathTimeGraph::CalculateTotalCost() { // col and row are for STGraph // t corresponding to col // s corresponding to row size_t next_highest_row = 0; size_t next_lowest_row = 0; for (size_t c = 0; c < cost_table_.size(); ++c) { size_t highest_row = 0; size_t lowest_row = cost_table_.back().size() - 1; int count = static_cast<int>(next_highest_row) - static_cast<int>(next_lowest_row) + 1; if (count > 0) { std::vector<std::future<void>> results; for (size_t r = next_lowest_row; r <= next_highest_row; ++r) { auto msg = std::make_shared<StGraphMessage>(c, r); if (FLAGS_enable_multi_thread_in_dp_st_graph) { results.push_back( cyber::Async(&GriddedPathTimeGraph::CalculateCostAt, this, msg)); } else { CalculateCostAt(msg); } } if (FLAGS_enable_multi_thread_in_dp_st_graph) { for (auto& result : results) { result.get(); } } } for (size_t r = next_lowest_row; r <= next_highest_row; ++r) { const auto& cost_cr = cost_table_[c][r]; if (cost_cr.total_cost() < std::numeric_limits<double>::infinity()) { size_t h_r = 0; size_t l_r = 0; GetRowRange(cost_cr, &h_r, &l_r); highest_row = std::max(highest_row, h_r); lowest_row = std::min(lowest_row, l_r); } } next_highest_row = highest_row; next_lowest_row = lowest_row; } return Status::OK(); } void GriddedPathTimeGraph::GetRowRange(const StGraphPoint& point, size_t* next_highest_row, size_t* next_lowest_row) { double v0 = 0.0; // TODO(all): Record speed information in StGraphPoint and deprecate this. // A scaling parameter for DP range search due to the lack of accurate // information of the current velocity (set to 1 by default since we use // past 1 second's average v as approximation) double acc_coeff = 0.5; if (!point.pre_point()) { v0 = init_point_.v(); } else { v0 = point.GetOptimalSpeed(); } const auto max_s_size = dimension_s_ - 1; const double t_squared = unit_t_ * unit_t_; const double s_upper_bound = v0 * unit_t_ + acc_coeff * max_acceleration_ * t_squared + point.point().s(); const auto next_highest_itr = std::lower_bound(spatial_distance_by_index_.begin(), spatial_distance_by_index_.end(), s_upper_bound); if (next_highest_itr == spatial_distance_by_index_.end()) { *next_highest_row = max_s_size; } else { *next_highest_row = std::distance(spatial_distance_by_index_.begin(), next_highest_itr); } const double s_lower_bound = std::fmax(0.0, v0 * unit_t_ + acc_coeff * max_deceleration_ * t_squared) + point.point().s(); const auto next_lowest_itr = std::lower_bound(spatial_distance_by_index_.begin(), spatial_distance_by_index_.end(), s_lower_bound); if (next_lowest_itr == spatial_distance_by_index_.end()) { *next_lowest_row = max_s_size; } else { *next_lowest_row = std::distance(spatial_distance_by_index_.begin(), next_lowest_itr); } } void GriddedPathTimeGraph::CalculateCostAt( const std::shared_ptr<StGraphMessage>& msg) { const uint32_t c = msg->c; const uint32_t r = msg->r; auto& cost_cr = cost_table_[c][r]; cost_cr.SetObstacleCost(dp_st_cost_.GetObstacleCost(cost_cr)); if (cost_cr.obstacle_cost() > std::numeric_limits<double>::max()) { return; } cost_cr.SetSpatialPotentialCost(dp_st_cost_.GetSpatialPotentialCost(cost_cr)); const auto& cost_init = cost_table_[0][0]; if (c == 0) { DCHECK_EQ(r, 0U) << "Incorrect. Row should be 0 with col = 0. row: " << r; cost_cr.SetTotalCost(0.0); cost_cr.SetOptimalSpeed(init_point_.v()); return; } const double speed_limit = speed_limit_by_index_[r]; const double cruise_speed = st_graph_data_.cruise_speed(); // The mininal s to model as constant acceleration formula // default: 0.25 * 7 = 1.75 m const double min_s_consider_speed = dense_unit_s_ * dimension_t_; if (c == 1) { const double acc = 2 * (cost_cr.point().s() / unit_t_ - init_point_.v()) / unit_t_; if (acc < max_deceleration_ || acc > max_acceleration_) { return; } if (init_point_.v() + acc * unit_t_ < -kDoubleEpsilon && cost_cr.point().s() > min_s_consider_speed) { return; } if (CheckOverlapOnDpStGraph(st_graph_data_.st_boundaries(), cost_cr, cost_init)) { return; } cost_cr.SetTotalCost( cost_cr.obstacle_cost() + cost_cr.spatial_potential_cost() + cost_init.total_cost() + CalculateEdgeCostForSecondCol(r, speed_limit, cruise_speed)); cost_cr.SetPrePoint(cost_init); cost_cr.SetOptimalSpeed(init_point_.v() + acc * unit_t_); return; } static constexpr double kSpeedRangeBuffer = 0.20; const double pre_lowest_s = cost_cr.point().s() - FLAGS_planning_upper_speed_limit * (1 + kSpeedRangeBuffer) * unit_t_; const auto pre_lowest_itr = std::lower_bound(spatial_distance_by_index_.begin(), spatial_distance_by_index_.end(), pre_lowest_s); uint32_t r_low = 0; if (pre_lowest_itr == spatial_distance_by_index_.end()) { r_low = dimension_s_ - 1; } else { r_low = static_cast<uint32_t>( std::distance(spatial_distance_by_index_.begin(), pre_lowest_itr)); } const uint32_t r_pre_size = r - r_low + 1; const auto& pre_col = cost_table_[c - 1]; double curr_speed_limit = speed_limit; if (c == 2) { for (uint32_t i = 0; i < r_pre_size; ++i) { uint32_t r_pre = r - i; if (std::isinf(pre_col[r_pre].total_cost()) || pre_col[r_pre].pre_point() == nullptr) { continue; } // TODO(Jiaxuan): Calculate accurate acceleration by recording speed // data in ST point. // Use curr_v = (point.s - pre_point.s) / unit_t as current v // Use pre_v = (pre_point.s - prepre_point.s) / unit_t as previous v // Current acc estimate: curr_a = (curr_v - pre_v) / unit_t // = (point.s + prepre_point.s - 2 * pre_point.s) / (unit_t * unit_t) const double curr_a = 2 * ((cost_cr.point().s() - pre_col[r_pre].point().s()) / unit_t_ - pre_col[r_pre].GetOptimalSpeed()) / unit_t_; if (curr_a < max_deceleration_ || curr_a > max_acceleration_) { continue; } if (pre_col[r_pre].GetOptimalSpeed() + curr_a * unit_t_ < -kDoubleEpsilon && cost_cr.point().s() > min_s_consider_speed) { continue; } // Filter out continuous-time node connection which is in collision with // obstacle if (CheckOverlapOnDpStGraph(st_graph_data_.st_boundaries(), cost_cr, pre_col[r_pre])) { continue; } curr_speed_limit = std::fmin(curr_speed_limit, speed_limit_by_index_[r_pre]); const double cost = cost_cr.obstacle_cost() + cost_cr.spatial_potential_cost() + pre_col[r_pre].total_cost() + CalculateEdgeCostForThirdCol( r, r_pre, curr_speed_limit, cruise_speed); if (cost < cost_cr.total_cost()) { cost_cr.SetTotalCost(cost); cost_cr.SetPrePoint(pre_col[r_pre]); cost_cr.SetOptimalSpeed(pre_col[r_pre].GetOptimalSpeed() + curr_a * unit_t_); } } return; } for (uint32_t i = 0; i < r_pre_size; ++i) { uint32_t r_pre = r - i; if (std::isinf(pre_col[r_pre].total_cost()) || pre_col[r_pre].pre_point() == nullptr) { continue; } // Use curr_v = (point.s - pre_point.s) / unit_t as current v // Use pre_v = (pre_point.s - prepre_point.s) / unit_t as previous v // Current acc estimate: curr_a = (curr_v - pre_v) / unit_t // = (point.s + prepre_point.s - 2 * pre_point.s) / (unit_t * unit_t) const double curr_a = 2 * ((cost_cr.point().s() - pre_col[r_pre].point().s()) / unit_t_ - pre_col[r_pre].GetOptimalSpeed()) / unit_t_; if (curr_a > max_acceleration_ || curr_a < max_deceleration_) { continue; } if (pre_col[r_pre].GetOptimalSpeed() + curr_a * unit_t_ < -kDoubleEpsilon && cost_cr.point().s() > min_s_consider_speed) { continue; } if (CheckOverlapOnDpStGraph(st_graph_data_.st_boundaries(), cost_cr, pre_col[r_pre])) { continue; } uint32_t r_prepre = pre_col[r_pre].pre_point()->index_s(); const StGraphPoint& prepre_graph_point = cost_table_[c - 2][r_prepre]; if (std::isinf(prepre_graph_point.total_cost())) { continue; } if (!prepre_graph_point.pre_point()) { continue; } const STPoint& triple_pre_point = prepre_graph_point.pre_point()->point(); const STPoint& prepre_point = prepre_graph_point.point(); const STPoint& pre_point = pre_col[r_pre].point(); const STPoint& curr_point = cost_cr.point(); curr_speed_limit = std::fmin(curr_speed_limit, speed_limit_by_index_[r_pre]); double cost = cost_cr.obstacle_cost() + cost_cr.spatial_potential_cost() + pre_col[r_pre].total_cost() + CalculateEdgeCost(triple_pre_point, prepre_point, pre_point, curr_point, curr_speed_limit, cruise_speed); if (cost < cost_cr.total_cost()) { cost_cr.SetTotalCost(cost); cost_cr.SetPrePoint(pre_col[r_pre]); cost_cr.SetOptimalSpeed(pre_col[r_pre].GetOptimalSpeed() + curr_a * unit_t_); } } } Status GriddedPathTimeGraph::RetrieveSpeedProfile(SpeedData* const speed_data) { double min_cost = std::numeric_limits<double>::infinity(); const StGraphPoint* best_end_point = nullptr; for (const StGraphPoint& cur_point : cost_table_.back()) { if (!std::isinf(cur_point.total_cost()) && cur_point.total_cost() < min_cost) { best_end_point = &cur_point; min_cost = cur_point.total_cost(); } } for (const auto& row : cost_table_) { const StGraphPoint& cur_point = row.back(); if (!std::isinf(cur_point.total_cost()) && cur_point.total_cost() < min_cost) { best_end_point = &cur_point; min_cost = cur_point.total_cost(); } } if (best_end_point == nullptr) { const std::string msg = "Fail to find the best feasible trajectory."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } std::vector<SpeedPoint> speed_profile; const StGraphPoint* cur_point = best_end_point; while (cur_point != nullptr) { ADEBUG << "Time: " << cur_point->point().t(); ADEBUG << "S: " << cur_point->point().s(); ADEBUG << "V: " << cur_point->GetOptimalSpeed(); SpeedPoint speed_point; speed_point.set_s(cur_point->point().s()); speed_point.set_t(cur_point->point().t()); speed_profile.push_back(speed_point); cur_point = cur_point->pre_point(); } std::reverse(speed_profile.begin(), speed_profile.end()); static constexpr double kEpsilon = std::numeric_limits<double>::epsilon(); if (speed_profile.front().t() > kEpsilon || speed_profile.front().s() > kEpsilon) { const std::string msg = "Fail to retrieve speed profile."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } for (size_t i = 0; i + 1 < speed_profile.size(); ++i) { const double v = (speed_profile[i + 1].s() - speed_profile[i].s()) / (speed_profile[i + 1].t() - speed_profile[i].t() + 1e-3); speed_profile[i].set_v(v); } *speed_data = SpeedData(speed_profile); return Status::OK(); } double GriddedPathTimeGraph::CalculateEdgeCost( const STPoint& first, const STPoint& second, const STPoint& third, const STPoint& forth, const double speed_limit, const double cruise_speed) { return dp_st_cost_.GetSpeedCost(third, forth, speed_limit, cruise_speed) + dp_st_cost_.GetAccelCostByThreePoints(second, third, forth) + dp_st_cost_.GetJerkCostByFourPoints(first, second, third, forth); } double GriddedPathTimeGraph::CalculateEdgeCostForSecondCol( const uint32_t row, const double speed_limit, const double cruise_speed) { double init_speed = init_point_.v(); double init_acc = init_point_.a(); const STPoint& pre_point = cost_table_[0][0].point(); const STPoint& curr_point = cost_table_[1][row].point(); return dp_st_cost_.GetSpeedCost(pre_point, curr_point, speed_limit, cruise_speed) + dp_st_cost_.GetAccelCostByTwoPoints(init_speed, pre_point, curr_point) + dp_st_cost_.GetJerkCostByTwoPoints(init_speed, init_acc, pre_point, curr_point); } double GriddedPathTimeGraph::CalculateEdgeCostForThirdCol( const uint32_t curr_row, const uint32_t pre_row, const double speed_limit, const double cruise_speed) { double init_speed = init_point_.v(); const STPoint& first = cost_table_[0][0].point(); const STPoint& second = cost_table_[1][pre_row].point(); const STPoint& third = cost_table_[2][curr_row].point(); return dp_st_cost_.GetSpeedCost(second, third, speed_limit, cruise_speed) + dp_st_cost_.GetAccelCostByThreePoints(first, second, third) + dp_st_cost_.GetJerkCostByThreePoints(init_speed, first, second, third); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/deciders/decider.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <memory> #include "modules/common/status/status.h" #include "modules/planning/common/frame.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { class Decider : public Task { public: explicit Decider(const TaskConfig& config); Decider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); virtual ~Decider() = default; apollo::common::Status Execute( Frame* frame, ReferenceLineInfo* reference_line_info) override; apollo::common::Status Execute(Frame* frame) override; protected: virtual apollo::common::Status Process( Frame* frame, ReferenceLineInfo* reference_line_info) { return apollo::common::Status::OK(); } virtual apollo::common::Status Process(Frame* frame) { return apollo::common::Status::OK(); } }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/deciders/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "decider_base", srcs = ["decider.cc"], hdrs = ["decider.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/common/status", "//modules/planning/common:frame", "//modules/planning/tasks:task", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks
apollo_public_repos/apollo/modules/planning/tasks/deciders/decider.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/decider.h" #include <memory> namespace apollo { namespace planning { Decider::Decider(const TaskConfig& config) : Task(config) {} Decider::Decider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Task(config, injector) {} apollo::common::Status Decider::Execute( Frame* frame, ReferenceLineInfo* reference_line_info) { Task::Execute(frame, reference_line_info); return Process(frame, reference_line_info); } apollo::common::Status Decider::Execute(Frame* frame) { Task::Execute(frame); return Process(frame); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_bounds_decider/path_bounds_decider.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/tasks/deciders/path_bounds_decider/path_bounds_decider.h" #include <algorithm> #include <functional> #include <limits> #include <memory> #include <set> #include "absl/strings/str_cat.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/util/point_factory.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/path_boundary.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/tasks/deciders/utils/path_decider_obstacle_utils.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::VehicleConfigHelper; using apollo::hdmap::HDMapUtil; using apollo::hdmap::JunctionInfo; namespace { // PathBoundPoint contains: (s, l_min, l_max). using PathBoundPoint = std::tuple<double, double, double>; // PathBound contains a vector of PathBoundPoints. using PathBound = std::vector<PathBoundPoint>; // ObstacleEdge contains: (is_start_s, s, l_min, l_max, obstacle_id). using ObstacleEdge = std::tuple<int, double, double, double, std::string>; } // namespace PathBoundsDecider::PathBoundsDecider( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Decider(config, injector) {} Status PathBoundsDecider::Process( Frame* const frame, ReferenceLineInfo* const reference_line_info) { // Sanity checks. CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); // Skip the path boundary decision if reusing the path. if (FLAGS_enable_skip_path_tasks && reference_line_info->path_reusable()) { return Status::OK(); } std::vector<PathBoundary> candidate_path_boundaries; // const TaskConfig& config = Decider::config_; // Initialization. InitPathBoundsDecider(*frame, *reference_line_info); // Generate the fallback path boundary. PathBound fallback_path_bound; Status ret = GenerateFallbackPathBound(*reference_line_info, &fallback_path_bound); if (!ret.ok()) { ADEBUG << "Cannot generate a fallback path bound."; return Status(ErrorCode::PLANNING_ERROR, ret.error_message()); } if (fallback_path_bound.empty()) { const std::string msg = "Failed to get a valid fallback path boundary"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (!fallback_path_bound.empty()) { CHECK_LE(adc_frenet_l_, std::get<2>(fallback_path_bound[0])); CHECK_GE(adc_frenet_l_, std::get<1>(fallback_path_bound[0])); } // Update the fallback path boundary into the reference_line_info. std::vector<std::pair<double, double>> fallback_path_bound_pair; for (size_t i = 0; i < fallback_path_bound.size(); ++i) { fallback_path_bound_pair.emplace_back(std::get<1>(fallback_path_bound[i]), std::get<2>(fallback_path_bound[i])); } candidate_path_boundaries.emplace_back(std::get<0>(fallback_path_bound[0]), kPathBoundsDeciderResolution, fallback_path_bound_pair); candidate_path_boundaries.back().set_label("fallback"); // If pull-over is requested, generate pull-over path boundary. auto* pull_over_status = injector_->planning_context() ->mutable_planning_status() ->mutable_pull_over(); const bool plan_pull_over_path = pull_over_status->plan_pull_over_path(); if (plan_pull_over_path) { PathBound pull_over_path_bound; Status ret = GeneratePullOverPathBound(*frame, *reference_line_info, &pull_over_path_bound); if (!ret.ok()) { AWARN << "Cannot generate a pullover path bound, do regular planning."; } else { ACHECK(!pull_over_path_bound.empty()); CHECK_LE(adc_frenet_l_, std::get<2>(pull_over_path_bound[0])); CHECK_GE(adc_frenet_l_, std::get<1>(pull_over_path_bound[0])); // Update the fallback path boundary into the reference_line_info. std::vector<std::pair<double, double>> pull_over_path_bound_pair; for (size_t i = 0; i < pull_over_path_bound.size(); ++i) { pull_over_path_bound_pair.emplace_back( std::get<1>(pull_over_path_bound[i]), std::get<2>(pull_over_path_bound[i])); } candidate_path_boundaries.emplace_back( std::get<0>(pull_over_path_bound[0]), kPathBoundsDeciderResolution, pull_over_path_bound_pair); candidate_path_boundaries.back().set_label("regular/pullover"); reference_line_info->SetCandidatePathBoundaries( std::move(candidate_path_boundaries)); ADEBUG << "Completed pullover and fallback path boundaries generation."; // set debug info in planning_data auto* pull_over_debug = reference_line_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()); return Status::OK(); } } // If it's a lane-change reference-line, generate lane-change path boundary. if (FLAGS_enable_smarter_lane_change && reference_line_info->IsChangeLanePath()) { PathBound lanechange_path_bound; Status ret = GenerateLaneChangePathBound(*reference_line_info, &lanechange_path_bound); if (!ret.ok()) { ADEBUG << "Cannot generate a lane-change path bound."; return Status(ErrorCode::PLANNING_ERROR, ret.error_message()); } if (lanechange_path_bound.empty()) { const std::string msg = "Failed to get a valid fallback path boundary"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // disable this change when not extending lane bounds to include adc if (config_.path_bounds_decider_config() .is_extend_lane_bounds_to_include_adc()) { CHECK_LE(adc_frenet_l_, std::get<2>(lanechange_path_bound[0])); CHECK_GE(adc_frenet_l_, std::get<1>(lanechange_path_bound[0])); } // Update the fallback path boundary into the reference_line_info. std::vector<std::pair<double, double>> lanechange_path_bound_pair; for (size_t i = 0; i < lanechange_path_bound.size(); ++i) { lanechange_path_bound_pair.emplace_back( std::get<1>(lanechange_path_bound[i]), std::get<2>(lanechange_path_bound[i])); } candidate_path_boundaries.emplace_back( std::get<0>(lanechange_path_bound[0]), kPathBoundsDeciderResolution, lanechange_path_bound_pair); candidate_path_boundaries.back().set_label("regular/lanechange"); RecordDebugInfo(lanechange_path_bound, "", reference_line_info); reference_line_info->SetCandidatePathBoundaries( std::move(candidate_path_boundaries)); ADEBUG << "Completed lanechange and fallback path boundaries generation."; return Status::OK(); } // Generate regular path boundaries. std::vector<LaneBorrowInfo> lane_borrow_info_list; lane_borrow_info_list.push_back(LaneBorrowInfo::NO_BORROW); if (reference_line_info->is_path_lane_borrow()) { const auto& path_decider_status = injector_->planning_context()->planning_status().path_decider(); for (const auto& lane_borrow_direction : path_decider_status.decided_side_pass_direction()) { if (lane_borrow_direction == PathDeciderStatus::LEFT_BORROW) { lane_borrow_info_list.push_back(LaneBorrowInfo::LEFT_BORROW); } else if (lane_borrow_direction == PathDeciderStatus::RIGHT_BORROW) { lane_borrow_info_list.push_back(LaneBorrowInfo::RIGHT_BORROW); } } } // Try every possible lane-borrow option: // PathBound regular_self_path_bound; // bool exist_self_path_bound = false; for (const auto& lane_borrow_info : lane_borrow_info_list) { PathBound regular_path_bound; std::string blocking_obstacle_id = ""; std::string borrow_lane_type = ""; Status ret = GenerateRegularPathBound( *reference_line_info, lane_borrow_info, &regular_path_bound, &blocking_obstacle_id, &borrow_lane_type); if (!ret.ok()) { continue; } if (regular_path_bound.empty()) { continue; } // disable this change when not extending lane bounds to include adc if (config_.path_bounds_decider_config() .is_extend_lane_bounds_to_include_adc()) { CHECK_LE(adc_frenet_l_, std::get<2>(regular_path_bound[0])); CHECK_GE(adc_frenet_l_, std::get<1>(regular_path_bound[0])); } // Update the path boundary into the reference_line_info. std::vector<std::pair<double, double>> regular_path_bound_pair; for (size_t i = 0; i < regular_path_bound.size(); ++i) { regular_path_bound_pair.emplace_back(std::get<1>(regular_path_bound[i]), std::get<2>(regular_path_bound[i])); } candidate_path_boundaries.emplace_back(std::get<0>(regular_path_bound[0]), kPathBoundsDeciderResolution, regular_path_bound_pair); std::string path_label = ""; switch (lane_borrow_info) { case LaneBorrowInfo::LEFT_BORROW: path_label = "left"; break; case LaneBorrowInfo::RIGHT_BORROW: path_label = "right"; break; default: path_label = "self"; // exist_self_path_bound = true; // regular_self_path_bound = regular_path_bound; break; } // RecordDebugInfo(regular_path_bound, "", reference_line_info); candidate_path_boundaries.back().set_label( absl::StrCat("regular/", path_label, "/", borrow_lane_type)); candidate_path_boundaries.back().set_blocking_obstacle_id( blocking_obstacle_id); } // Remove redundant boundaries. // RemoveRedundantPathBoundaries(&candidate_path_boundaries); // Success reference_line_info->SetCandidatePathBoundaries( std::move(candidate_path_boundaries)); ADEBUG << "Completed regular and fallback path boundaries generation."; return Status::OK(); } void PathBoundsDecider::InitPathBoundsDecider( const Frame& frame, const ReferenceLineInfo& reference_line_info) { const ReferenceLine& reference_line = reference_line_info.reference_line(); common::TrajectoryPoint planning_start_point = frame.PlanningStartPoint(); if (FLAGS_use_front_axe_center_in_path_planning) { planning_start_point = InferFrontAxeCenterFromRearAxeCenter(planning_start_point); } ADEBUG << "Plan at the starting point: x = " << planning_start_point.path_point().x() << ", y = " << planning_start_point.path_point().y() << ", and angle = " << planning_start_point.path_point().theta(); // Initialize some private variables. // ADC s/l info. auto adc_sl_info = reference_line.ToFrenetFrame(planning_start_point); adc_frenet_s_ = adc_sl_info.first[0]; adc_frenet_l_ = adc_sl_info.second[0]; adc_frenet_sd_ = adc_sl_info.first[1]; adc_frenet_ld_ = adc_sl_info.second[1] * adc_frenet_sd_; double offset_to_map = 0.0; reference_line.GetOffsetToMap(adc_frenet_s_, &offset_to_map); adc_l_to_lane_center_ = adc_frenet_l_ + offset_to_map; // ADC's lane width. double lane_left_width = 0.0; double lane_right_width = 0.0; if (!reference_line.GetLaneWidth(adc_frenet_s_, &lane_left_width, &lane_right_width)) { AWARN << "Failed to get lane width at planning start point."; adc_lane_width_ = kDefaultLaneWidth; } else { adc_lane_width_ = lane_left_width + lane_right_width; } } common::TrajectoryPoint PathBoundsDecider::InferFrontAxeCenterFromRearAxeCenter( const common::TrajectoryPoint& traj_point) { double front_to_rear_axe_distance = VehicleConfigHelper::GetConfig().vehicle_param().wheel_base(); common::TrajectoryPoint ret = traj_point; ret.mutable_path_point()->set_x( traj_point.path_point().x() + front_to_rear_axe_distance * std::cos(traj_point.path_point().theta())); ret.mutable_path_point()->set_y( traj_point.path_point().y() + front_to_rear_axe_distance * std::sin(traj_point.path_point().theta())); return ret; } Status PathBoundsDecider::GenerateRegularPathBound( const ReferenceLineInfo& reference_line_info, const LaneBorrowInfo& lane_borrow_info, PathBound* const path_bound, std::string* const blocking_obstacle_id, std::string* const borrow_lane_type) { // 1. Initialize the path boundaries to be an indefinitely large area. if (!InitPathBoundary(reference_line_info, path_bound)) { const std::string msg = "Failed to initialize path boundaries."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // PathBoundsDebugString(*path_bound); // 2. Decide a rough boundary based on lane info and ADC's position if (!GetBoundaryFromLanesAndADC(reference_line_info, lane_borrow_info, 0.1, path_bound, borrow_lane_type)) { const std::string msg = "Failed to decide a rough boundary based on " "road information."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // PathBoundsDebugString(*path_bound); // TODO(jiacheng): once ready, limit the path boundary based on the // actual road boundary to avoid getting off-road. // 3. Fine-tune the boundary based on static obstacles PathBound temp_path_bound = *path_bound; if (!GetBoundaryFromStaticObstacles(reference_line_info.path_decision(), path_bound, blocking_obstacle_id)) { const std::string msg = "Failed to decide fine tune the boundaries after " "taking into consideration all static obstacles."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // Append some extra path bound points to avoid zero-length path data. int counter = 0; while (!blocking_obstacle_id->empty() && path_bound->size() < temp_path_bound.size() && counter < kNumExtraTailBoundPoint) { path_bound->push_back(temp_path_bound[path_bound->size()]); counter++; } // PathBoundsDebugString(*path_bound); // 4. Adjust the boundary considering dynamic obstacles // TODO(all): may need to implement this in the future. ADEBUG << "Completed generating path boundaries."; return Status::OK(); } Status PathBoundsDecider::GenerateLaneChangePathBound( const ReferenceLineInfo& reference_line_info, std::vector<std::tuple<double, double, double>>* const path_bound) { // 1. Initialize the path boundaries to be an indefinitely large area. if (!InitPathBoundary(reference_line_info, path_bound)) { const std::string msg = "Failed to initialize path boundaries."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // PathBoundsDebugString(*path_bound); // 2. Decide a rough boundary based on lane info and ADC's position std::string dummy_borrow_lane_type; if (!GetBoundaryFromLanesAndADC(reference_line_info, LaneBorrowInfo::NO_BORROW, 0.1, path_bound, &dummy_borrow_lane_type, true)) { const std::string msg = "Failed to decide a rough boundary based on " "road information."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // PathBoundsDebugString(*path_bound); // 3. Remove the S-length of target lane out of the path-bound. GetBoundaryFromLaneChangeForbiddenZone(reference_line_info, path_bound); PathBound temp_path_bound = *path_bound; std::string blocking_obstacle_id; if (!GetBoundaryFromStaticObstacles(reference_line_info.path_decision(), path_bound, &blocking_obstacle_id)) { const std::string msg = "Failed to decide fine tune the boundaries after " "taking into consideration all static obstacles."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // Append some extra path bound points to avoid zero-length path data. int counter = 0; while (!blocking_obstacle_id.empty() && path_bound->size() < temp_path_bound.size() && counter < kNumExtraTailBoundPoint) { path_bound->push_back(temp_path_bound[path_bound->size()]); counter++; } ADEBUG << "Completed generating path boundaries."; return Status::OK(); } Status PathBoundsDecider::GeneratePullOverPathBound( const Frame& frame, const ReferenceLineInfo& reference_line_info, PathBound* const path_bound) { // 1. Initialize the path boundaries to be an indefinitely large area. if (!InitPathBoundary(reference_line_info, path_bound)) { const std::string msg = "Failed to initialize path boundaries."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // PathBoundsDebugString(*path_bound); // 2. Decide a rough boundary based on road boundary if (!GetBoundaryFromRoads(reference_line_info, path_bound)) { const std::string msg = "Failed to decide a rough boundary based on road boundary."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // PathBoundsDebugString(*path_bound); ConvertBoundarySAxisFromLaneCenterToRefLine(reference_line_info, path_bound); if (adc_frenet_l_ < std::get<1>(path_bound->front()) || adc_frenet_l_ > std::get<2>(path_bound->front())) { const std::string msg = "ADC is outside road boundary already. Cannot generate pull-over path"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // 2. Update boundary by lane boundary for pull_over UpdatePullOverBoundaryByLaneBoundary(reference_line_info, path_bound); // PathBoundsDebugString(*path_bound); // 3. Fine-tune the boundary based on static obstacles PathBound temp_path_bound = *path_bound; std::string blocking_obstacle_id; if (!GetBoundaryFromStaticObstacles(reference_line_info.path_decision(), path_bound, &blocking_obstacle_id)) { const std::string msg = "Failed to decide fine tune the boundaries after " "taking into consideration all static obstacles."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // PathBoundsDebugString(*path_bound); auto* pull_over_status = injector_->planning_context() ->mutable_planning_status() ->mutable_pull_over(); // If already found a pull-over position, simply check if it's valid. int curr_idx = -1; if (pull_over_status->has_position()) { curr_idx = IsPointWithinPathBound( reference_line_info, pull_over_status->position().x(), pull_over_status->position().y(), *path_bound); } // If haven't found a pull-over position, search for one. if (curr_idx < 0) { auto pull_over_type = pull_over_status->pull_over_type(); pull_over_status->Clear(); pull_over_status->set_pull_over_type(pull_over_type); pull_over_status->set_plan_pull_over_path(true); std::tuple<double, double, double, int> pull_over_configuration; if (!SearchPullOverPosition(frame, reference_line_info, *path_bound, &pull_over_configuration)) { const std::string msg = "Failed to find a proper pull-over position."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } curr_idx = std::get<3>(pull_over_configuration); // If have found a pull-over position, update planning-context pull_over_status->mutable_position()->set_x( std::get<0>(pull_over_configuration)); pull_over_status->mutable_position()->set_y( std::get<1>(pull_over_configuration)); pull_over_status->mutable_position()->set_z(0.0); pull_over_status->set_theta(std::get<2>(pull_over_configuration)); pull_over_status->set_length_front(FLAGS_obstacle_lon_start_buffer); pull_over_status->set_length_back(FLAGS_obstacle_lon_end_buffer); pull_over_status->set_width_left( VehicleConfigHelper::GetConfig().vehicle_param().width() / 2.0); pull_over_status->set_width_right( VehicleConfigHelper::GetConfig().vehicle_param().width() / 2.0); ADEBUG << "Pull Over: x[" << pull_over_status->position().x() << "] y[" << pull_over_status->position().y() << "] theta[" << pull_over_status->theta() << "]"; } // Trim path-bound properly while (static_cast<int>(path_bound->size()) - 1 > curr_idx + kNumExtraTailBoundPoint) { path_bound->pop_back(); } for (size_t idx = curr_idx + 1; idx < path_bound->size(); ++idx) { std::get<1>((*path_bound)[idx]) = std::get<1>((*path_bound)[curr_idx]); std::get<2>((*path_bound)[idx]) = std::get<2>((*path_bound)[curr_idx]); } return Status::OK(); } Status PathBoundsDecider::GenerateFallbackPathBound( const ReferenceLineInfo& reference_line_info, PathBound* const path_bound) { // 1. Initialize the path boundaries to be an indefinitely large area. if (!InitPathBoundary(reference_line_info, path_bound)) { const std::string msg = "Failed to initialize fallback path boundaries."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // PathBoundsDebugString(*path_bound); // 2. Decide a rough boundary based on lane info and ADC's position std::string dummy_borrow_lane_type; if (!GetBoundaryFromLanesAndADC(reference_line_info, LaneBorrowInfo::NO_BORROW, 0.5, path_bound, &dummy_borrow_lane_type, true)) { const std::string msg = "Failed to decide a rough fallback boundary based on " "road information."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // PathBoundsDebugString(*path_bound); ADEBUG << "Completed generating fallback path boundaries."; return Status::OK(); } int PathBoundsDecider::IsPointWithinPathBound( const ReferenceLineInfo& reference_line_info, const double x, const double y, const std::vector<std::tuple<double, double, double>>& path_bound) { common::SLPoint point_sl; reference_line_info.reference_line().XYToSL({x, y}, &point_sl); if (point_sl.s() > std::get<0>(path_bound.back()) || point_sl.s() < std::get<0>(path_bound.front()) - kPathBoundsDeciderResolution * 2) { ADEBUG << "Longitudinally outside the boundary."; return -1; } int idx_after = 0; while (idx_after < static_cast<int>(path_bound.size()) && std::get<0>(path_bound[idx_after]) < point_sl.s()) { ++idx_after; } ADEBUG << "The idx_after = " << idx_after; ADEBUG << "The boundary is: " << "[" << std::get<1>(path_bound[idx_after]) << ", " << std::get<2>(path_bound[idx_after]) << "]."; ADEBUG << "The point is at: " << point_sl.l(); int idx_before = idx_after - 1; if (std::get<1>(path_bound[idx_before]) <= point_sl.l() && std::get<2>(path_bound[idx_before]) >= point_sl.l() && std::get<1>(path_bound[idx_after]) <= point_sl.l() && std::get<2>(path_bound[idx_after]) >= point_sl.l()) { return idx_after; } ADEBUG << "Laterally outside the boundary."; return -1; } bool PathBoundsDecider::FindDestinationPullOverS( const Frame& frame, const ReferenceLineInfo& reference_line_info, const std::vector<std::tuple<double, double, double>>& path_bound, double* pull_over_s) { // destination_s based on routing_end const auto& reference_line = reference_line_info_->reference_line(); common::SLPoint destination_sl; const auto& routing = frame.local_view().routing; const auto& routing_end = *(routing->routing_request().waypoint().rbegin()); reference_line.XYToSL(routing_end.pose(), &destination_sl); const double destination_s = destination_sl.s(); const double adc_end_s = reference_line_info.AdcSlBoundary().end_s(); // Check if destination is some distance away from ADC. ADEBUG << "Destination s[" << destination_s << "] adc_end_s[" << adc_end_s << "]"; if (destination_s - adc_end_s < config_.path_bounds_decider_config() .pull_over_destination_to_adc_buffer()) { AERROR << "Destination is too close to ADC. distance[" << destination_s - adc_end_s << "]"; return false; } // Check if destination is within path-bounds searching scope. const double destination_to_pathend_buffer = config_.path_bounds_decider_config() .pull_over_destination_to_pathend_buffer(); if (destination_s + destination_to_pathend_buffer >= std::get<0>(path_bound.back())) { AERROR << "Destination is not within path_bounds search scope"; return false; } *pull_over_s = destination_s; return true; } bool PathBoundsDecider::FindEmergencyPullOverS( const ReferenceLineInfo& reference_line_info, double* pull_over_s) { const double adc_end_s = reference_line_info.AdcSlBoundary().end_s(); const double min_turn_radius = common::VehicleConfigHelper::Instance() ->GetConfig() .vehicle_param() .min_turn_radius(); const double adjust_factor = config_.path_bounds_decider_config() .pull_over_approach_lon_distance_adjust_factor(); const double pull_over_distance = min_turn_radius * 2 * adjust_factor; *pull_over_s = adc_end_s + pull_over_distance; return true; } bool PathBoundsDecider::SearchPullOverPosition( const Frame& frame, const ReferenceLineInfo& reference_line_info, const std::vector<std::tuple<double, double, double>>& path_bound, std::tuple<double, double, double, int>* const pull_over_configuration) { const auto& pull_over_status = injector_->planning_context()->planning_status().pull_over(); // search direction bool search_backward = false; // search FORWARD by default double pull_over_s = 0.0; if (pull_over_status.pull_over_type() == PullOverStatus::EMERGENCY_PULL_OVER) { if (!FindEmergencyPullOverS(reference_line_info, &pull_over_s)) { AERROR << "Failed to find emergency_pull_over s"; return false; } search_backward = false; // search FORWARD from target position } else if (pull_over_status.pull_over_type() == PullOverStatus::PULL_OVER) { if (!FindDestinationPullOverS(frame, reference_line_info, path_bound, &pull_over_s)) { AERROR << "Failed to find pull_over s upon destination arrival"; return false; } search_backward = true; // search BACKWARD from target position } else { return false; } int idx = 0; if (search_backward) { // 1. Locate the first point before destination. idx = static_cast<int>(path_bound.size()) - 1; while (idx >= 0 && std::get<0>(path_bound[idx]) > pull_over_s) { --idx; } } else { // 1. Locate the first point after emergency_pull_over s. while (idx < static_cast<int>(path_bound.size()) && std::get<0>(path_bound[idx]) < pull_over_s) { ++idx; } } if (idx < 0 || idx >= static_cast<int>(path_bound.size())) { AERROR << "Failed to find path_bound index for pull over s"; return false; } // Search for a feasible location for pull-over. const double pull_over_space_length = kPulloverLonSearchCoeff * VehicleConfigHelper::GetConfig().vehicle_param().length() - FLAGS_obstacle_lon_start_buffer - FLAGS_obstacle_lon_end_buffer; const double pull_over_space_width = (kPulloverLatSearchCoeff - 1.0) * VehicleConfigHelper::GetConfig().vehicle_param().width(); const double adc_half_width = VehicleConfigHelper::GetConfig().vehicle_param().width() / 2.0; // 2. Find a window that is close to road-edge. // (not in any intersection) bool has_a_feasible_window = false; while ((search_backward && idx >= 0 && std::get<0>(path_bound[idx]) - std::get<0>(path_bound.front()) > pull_over_space_length) || (!search_backward && idx < static_cast<int>(path_bound.size()) && std::get<0>(path_bound.back()) - std::get<0>(path_bound[idx]) > pull_over_space_length)) { int j = idx; bool is_feasible_window = true; // Check if the point of idx is within intersection. double pt_ref_line_s = std::get<0>(path_bound[idx]); double pt_ref_line_l = 0.0; common::SLPoint pt_sl; pt_sl.set_s(pt_ref_line_s); pt_sl.set_l(pt_ref_line_l); common::math::Vec2d pt_xy; reference_line_info.reference_line().SLToXY(pt_sl, &pt_xy); common::PointENU hdmap_point; hdmap_point.set_x(pt_xy.x()); hdmap_point.set_y(pt_xy.y()); ADEBUG << "Pull-over position might be around (" << pt_xy.x() << ", " << pt_xy.y() << ")"; std::vector<std::shared_ptr<const JunctionInfo>> junctions; HDMapUtil::BaseMap().GetJunctions(hdmap_point, 1.0, &junctions); if (!junctions.empty()) { AWARN << "Point is in PNC-junction."; idx = search_backward ? idx - 1 : idx + 1; continue; } while ((search_backward && j >= 0 && std::get<0>(path_bound[idx]) - std::get<0>(path_bound[j]) < pull_over_space_length) || (!search_backward && j < static_cast<int>(path_bound.size()) && std::get<0>(path_bound[j]) - std::get<0>(path_bound[idx]) < pull_over_space_length)) { double curr_s = std::get<0>(path_bound[j]); double curr_right_bound = std::fabs(std::get<1>(path_bound[j])); double curr_road_left_width = 0; double curr_road_right_width = 0; reference_line_info.reference_line().GetRoadWidth( curr_s, &curr_road_left_width, &curr_road_right_width); ADEBUG << "s[" << curr_s << "] curr_road_left_width[" << curr_road_left_width << "] curr_road_right_width[" << curr_road_right_width << "]"; if (curr_road_right_width - (curr_right_bound + adc_half_width) > config_.path_bounds_decider_config().pull_over_road_edge_buffer()) { AERROR << "Not close enough to road-edge. Not feasible for pull-over."; is_feasible_window = false; break; } const double right_bound = std::get<1>(path_bound[j]); const double left_bound = std::get<2>(path_bound[j]); ADEBUG << "left_bound[" << left_bound << "] right_bound[" << right_bound << "]"; if (left_bound - right_bound < pull_over_space_width) { AERROR << "Not wide enough to fit ADC. Not feasible for pull-over."; is_feasible_window = false; break; } j = search_backward ? j - 1 : j + 1; } if (j < 0) { return false; } if (is_feasible_window) { has_a_feasible_window = true; const auto& reference_line = reference_line_info.reference_line(); // estimate pull over point to have the vehicle keep same safety distance // to front and back const auto& vehicle_param = VehicleConfigHelper::GetConfig().vehicle_param(); const double back_clear_to_total_length_ratio = (0.5 * (kPulloverLonSearchCoeff - 1.0) * vehicle_param.length() + vehicle_param.back_edge_to_center()) / vehicle_param.length() / kPulloverLonSearchCoeff; int start_idx = j; int end_idx = idx; if (!search_backward) { start_idx = idx; end_idx = j; } auto pull_over_idx = static_cast<size_t>( back_clear_to_total_length_ratio * static_cast<double>(end_idx) + (1.0 - back_clear_to_total_length_ratio) * static_cast<double>(start_idx)); const auto& pull_over_point = path_bound[pull_over_idx]; const double pull_over_s = std::get<0>(pull_over_point); const double pull_over_l = std::get<1>(pull_over_point) + pull_over_space_width / 2.0; common::SLPoint pull_over_sl_point; pull_over_sl_point.set_s(pull_over_s); pull_over_sl_point.set_l(pull_over_l); common::math::Vec2d pull_over_xy_point; reference_line.SLToXY(pull_over_sl_point, &pull_over_xy_point); const double pull_over_x = pull_over_xy_point.x(); const double pull_over_y = pull_over_xy_point.y(); // set the pull over theta to be the nearest lane theta rather than // reference line theta in case of reference line theta not aligned with // the lane const auto& reference_point = reference_line.GetReferencePoint(pull_over_s); double pull_over_theta = reference_point.heading(); hdmap::LaneInfoConstPtr lane; double s = 0.0; double l = 0.0; auto point = common::util::PointFactory::ToPointENU(pull_over_x, pull_over_y); if (HDMapUtil::BaseMap().GetNearestLaneWithHeading( point, 5.0, pull_over_theta, M_PI_2, &lane, &s, &l) == 0) { pull_over_theta = lane->Heading(s); } *pull_over_configuration = std::make_tuple(pull_over_x, pull_over_y, pull_over_theta, static_cast<int>(pull_over_idx)); break; } idx = search_backward ? idx - 1 : idx + 1; } return has_a_feasible_window; } void PathBoundsDecider::RemoveRedundantPathBoundaries( std::vector<PathBoundary>* const candidate_path_boundaries) { // 1. Check to see if both "left" and "right" exist. bool is_left_exist = false; std::vector<std::pair<double, double>> left_boundary; bool is_right_exist = false; std::vector<std::pair<double, double>> right_boundary; for (const auto& path_boundary : *candidate_path_boundaries) { if (path_boundary.label().find("left") != std::string::npos) { is_left_exist = true; left_boundary = path_boundary.boundary(); } if (path_boundary.label().find("right") != std::string::npos) { is_right_exist = true; right_boundary = path_boundary.boundary(); } } // 2. Check if "left" is contained by "right", and vice versa. if (!is_left_exist || !is_right_exist) { return; } bool is_left_redundant = false; bool is_right_redundant = false; if (IsContained(left_boundary, right_boundary)) { is_left_redundant = true; } if (IsContained(right_boundary, left_boundary)) { is_right_redundant = true; } // 3. If one contains the other, then remove the redundant one. for (size_t i = 0; i < candidate_path_boundaries->size(); ++i) { const auto& path_boundary = (*candidate_path_boundaries)[i]; if (path_boundary.label().find("right") != std::string::npos && is_right_redundant) { (*candidate_path_boundaries)[i] = candidate_path_boundaries->back(); candidate_path_boundaries->pop_back(); break; } if (path_boundary.label().find("left") != std::string::npos && is_left_redundant) { (*candidate_path_boundaries)[i] = candidate_path_boundaries->back(); candidate_path_boundaries->pop_back(); break; } } } bool PathBoundsDecider::IsContained( const std::vector<std::pair<double, double>>& lhs, const std::vector<std::pair<double, double>>& rhs) { if (lhs.size() > rhs.size()) { return false; } for (size_t i = 0; i < lhs.size(); ++i) { if (lhs[i].first < rhs[i].first) { return false; } if (lhs[i].second > rhs[i].second) { return false; } } return true; } bool PathBoundsDecider::InitPathBoundary( const ReferenceLineInfo& reference_line_info, PathBound* const path_bound) { // Sanity checks. CHECK_NOTNULL(path_bound); path_bound->clear(); const auto& reference_line = reference_line_info.reference_line(); // Starting from ADC's current position, increment until the horizon, and // set lateral bounds to be infinite at every spot. for (double curr_s = adc_frenet_s_; curr_s < std::fmin(adc_frenet_s_ + std::fmax(kPathBoundsDeciderHorizon, reference_line_info.GetCruiseSpeed() * FLAGS_trajectory_time_length), reference_line.Length()); curr_s += kPathBoundsDeciderResolution) { path_bound->emplace_back(curr_s, std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max()); } // Return. if (path_bound->empty()) { ADEBUG << "Empty path boundary in InitPathBoundary"; return false; } return true; } bool PathBoundsDecider::GetBoundaryFromRoads( const ReferenceLineInfo& reference_line_info, PathBound* const path_bound) { // Sanity checks. CHECK_NOTNULL(path_bound); ACHECK(!path_bound->empty()); const ReferenceLine& reference_line = reference_line_info.reference_line(); // Go through every point, update the boudnary based on the road boundary. double past_road_left_width = adc_lane_width_ / 2.0; double past_road_right_width = adc_lane_width_ / 2.0; int path_blocked_idx = -1; for (size_t i = 0; i < path_bound->size(); ++i) { // 1. Get road boundary. double curr_s = std::get<0>((*path_bound)[i]); double curr_road_left_width = 0.0; double curr_road_right_width = 0.0; double refline_offset_to_lane_center = 0.0; reference_line.GetOffsetToMap(curr_s, &refline_offset_to_lane_center); if (!reference_line.GetRoadWidth(curr_s, &curr_road_left_width, &curr_road_right_width)) { AWARN << "Failed to get lane width at s = " << curr_s; curr_road_left_width = past_road_left_width; curr_road_right_width = past_road_right_width; } else { curr_road_left_width += refline_offset_to_lane_center; curr_road_right_width -= refline_offset_to_lane_center; past_road_left_width = curr_road_left_width; past_road_right_width = curr_road_right_width; } double curr_left_bound = curr_road_left_width; double curr_right_bound = -curr_road_right_width; ADEBUG << "At s = " << curr_s << ", left road bound = " << curr_road_left_width << ", right road bound = " << curr_road_right_width << ", offset from refline to lane-center = " << refline_offset_to_lane_center; // 2. Update into path_bound. if (!UpdatePathBoundaryWithBuffer(i, curr_left_bound, curr_right_bound, path_bound)) { path_blocked_idx = static_cast<int>(i); } if (path_blocked_idx != -1) { break; } } TrimPathBounds(path_blocked_idx, path_bound); return true; } bool PathBoundsDecider::GetBoundaryFromLanes( const ReferenceLineInfo& reference_line_info, const LaneBorrowInfo& lane_borrow_info, PathBound* const path_bound, std::string* const borrow_lane_type) { // Sanity checks. CHECK_NOTNULL(path_bound); ACHECK(!path_bound->empty()); const ReferenceLine& reference_line = reference_line_info.reference_line(); // Go through every point, update the boundary based on lane-info. double past_lane_left_width = adc_lane_width_ / 2.0; double past_lane_right_width = adc_lane_width_ / 2.0; int path_blocked_idx = -1; bool borrowing_reverse_lane = false; for (size_t i = 0; i < path_bound->size(); ++i) { double curr_s = std::get<0>((*path_bound)[i]); // 1. Get the current lane width at current point. double curr_lane_left_width = 0.0; double curr_lane_right_width = 0.0; if (!reference_line.GetLaneWidth(curr_s, &curr_lane_left_width, &curr_lane_right_width)) { AWARN << "Failed to get lane width at s = " << curr_s; curr_lane_left_width = past_lane_left_width; curr_lane_right_width = past_lane_right_width; } else { double offset_to_lane_center = 0.0; reference_line.GetOffsetToMap(curr_s, &offset_to_lane_center); // The left-width and right-width are w.r.t. lane-center, not ref-line. curr_lane_left_width += offset_to_lane_center; curr_lane_right_width -= offset_to_lane_center; past_lane_left_width = curr_lane_left_width; past_lane_right_width = curr_lane_right_width; } // 2. Get the neighbor lane widths at the current point. double curr_neighbor_lane_width = 0.0; if (CheckLaneBoundaryType(reference_line_info, curr_s, lane_borrow_info)) { hdmap::Id neighbor_lane_id; if (lane_borrow_info == LaneBorrowInfo::LEFT_BORROW) { // Borrowing left neighbor lane. if (reference_line_info.GetNeighborLaneInfo( ReferenceLineInfo::LaneType::LeftForward, curr_s, &neighbor_lane_id, &curr_neighbor_lane_width)) { ADEBUG << "Borrow left forward neighbor lane."; } else if (reference_line_info.GetNeighborLaneInfo( ReferenceLineInfo::LaneType::LeftReverse, curr_s, &neighbor_lane_id, &curr_neighbor_lane_width)) { borrowing_reverse_lane = true; ADEBUG << "Borrow left reverse neighbor lane."; } else { ADEBUG << "There is no left neighbor lane."; } } else if (lane_borrow_info == LaneBorrowInfo::RIGHT_BORROW) { // Borrowing right neighbor lane. if (reference_line_info.GetNeighborLaneInfo( ReferenceLineInfo::LaneType::RightForward, curr_s, &neighbor_lane_id, &curr_neighbor_lane_width)) { ADEBUG << "Borrow right forward neighbor lane."; } else if (reference_line_info.GetNeighborLaneInfo( ReferenceLineInfo::LaneType::RightReverse, curr_s, &neighbor_lane_id, &curr_neighbor_lane_width)) { borrowing_reverse_lane = true; ADEBUG << "Borrow right reverse neighbor lane."; } else { ADEBUG << "There is no right neighbor lane."; } } } // 3. Get the proper boundary double curr_left_bound = curr_lane_left_width + (lane_borrow_info == LaneBorrowInfo::LEFT_BORROW ? curr_neighbor_lane_width : 0.0); double curr_right_bound = -curr_lane_right_width - (lane_borrow_info == LaneBorrowInfo::RIGHT_BORROW ? curr_neighbor_lane_width : 0.0); ADEBUG << "At s = " << curr_s << ", left_lane_bound = " << curr_left_bound << ", right_lane_bound = " << curr_right_bound; // 4. Update the boundary. if (!UpdatePathBoundary(i, curr_left_bound, curr_right_bound, path_bound)) { path_blocked_idx = static_cast<int>(i); } if (path_blocked_idx != -1) { break; } } TrimPathBounds(path_blocked_idx, path_bound); if (lane_borrow_info == LaneBorrowInfo::NO_BORROW) { *borrow_lane_type = ""; } else { *borrow_lane_type = borrowing_reverse_lane ? "reverse" : "forward"; } return true; } bool PathBoundsDecider::GetBoundaryFromADC( const ReferenceLineInfo& reference_line_info, double ADC_extra_buffer, PathBound* const path_bound) { // Sanity checks. CHECK_NOTNULL(path_bound); ACHECK(!path_bound->empty()); // Calculate the ADC's lateral boundary. static constexpr double kMaxLateralAccelerations = 1.5; double ADC_lat_decel_buffer = (adc_frenet_ld_ > 0 ? 1.0 : -1.0) * adc_frenet_ld_ * adc_frenet_ld_ / kMaxLateralAccelerations / 2.0; double curr_left_bound_adc = GetBufferBetweenADCCenterAndEdge() + ADC_extra_buffer + std::fmax(adc_l_to_lane_center_, adc_l_to_lane_center_ + ADC_lat_decel_buffer); double curr_right_bound_adc = -GetBufferBetweenADCCenterAndEdge() - ADC_extra_buffer + std::fmin(adc_l_to_lane_center_, adc_l_to_lane_center_ + ADC_lat_decel_buffer); // Expand the boundary in case ADC falls outside. for (size_t i = 0; i < path_bound->size(); ++i) { double curr_left_bound = std::get<2>((*path_bound)[i]); curr_left_bound = std::fmax(curr_left_bound_adc, curr_left_bound); double curr_right_bound = std::get<1>((*path_bound)[i]); curr_right_bound = std::fmin(curr_right_bound_adc, curr_right_bound); UpdatePathBoundary(i, curr_left_bound, curr_right_bound, path_bound); } return true; } // TODO(jiacheng): this function is to be retired soon. bool PathBoundsDecider::GetBoundaryFromLanesAndADC( const ReferenceLineInfo& reference_line_info, const LaneBorrowInfo& lane_borrow_info, double ADC_buffer, PathBound* const path_bound, std::string* const borrow_lane_type, bool is_fallback_lanechange) { // Sanity checks. CHECK_NOTNULL(path_bound); ACHECK(!path_bound->empty()); const ReferenceLine& reference_line = reference_line_info.reference_line(); bool is_left_lane_boundary = true; bool is_right_lane_boundary = true; const double boundary_buffer = 0.05; // meter // Go through every point, update the boundary based on lane info and // ADC's position. double past_lane_left_width = adc_lane_width_ / 2.0; double past_lane_right_width = adc_lane_width_ / 2.0; int path_blocked_idx = -1; bool borrowing_reverse_lane = false; for (size_t i = 0; i < path_bound->size(); ++i) { double curr_s = std::get<0>((*path_bound)[i]); // 1. Get the current lane width at current point. double curr_lane_left_width = 0.0; double curr_lane_right_width = 0.0; double offset_to_lane_center = 0.0; if (!reference_line.GetLaneWidth(curr_s, &curr_lane_left_width, &curr_lane_right_width)) { AWARN << "Failed to get lane width at s = " << curr_s; curr_lane_left_width = past_lane_left_width; curr_lane_right_width = past_lane_right_width; } else { // check if lane boundary is also road boundary double curr_road_left_width = 0.0; double curr_road_right_width = 0.0; if (reference_line.GetRoadWidth(curr_s, &curr_road_left_width, &curr_road_right_width)) { is_left_lane_boundary = (std::abs(curr_road_left_width - curr_lane_left_width) > boundary_buffer); is_right_lane_boundary = (std::abs(curr_road_right_width - curr_lane_right_width) > boundary_buffer); } reference_line.GetOffsetToMap(curr_s, &offset_to_lane_center); curr_lane_left_width += offset_to_lane_center; curr_lane_right_width -= offset_to_lane_center; past_lane_left_width = curr_lane_left_width; past_lane_right_width = curr_lane_right_width; } // 2. Get the neighbor lane widths at the current point. double curr_neighbor_lane_width = 0.0; if (CheckLaneBoundaryType(reference_line_info, curr_s, lane_borrow_info)) { hdmap::Id neighbor_lane_id; if (lane_borrow_info == LaneBorrowInfo::LEFT_BORROW) { // Borrowing left neighbor lane. if (reference_line_info.GetNeighborLaneInfo( ReferenceLineInfo::LaneType::LeftForward, curr_s, &neighbor_lane_id, &curr_neighbor_lane_width)) { ADEBUG << "Borrow left forward neighbor lane."; } else if (reference_line_info.GetNeighborLaneInfo( ReferenceLineInfo::LaneType::LeftReverse, curr_s, &neighbor_lane_id, &curr_neighbor_lane_width)) { borrowing_reverse_lane = true; ADEBUG << "Borrow left reverse neighbor lane."; } else { ADEBUG << "There is no left neighbor lane."; } } else if (lane_borrow_info == LaneBorrowInfo::RIGHT_BORROW) { // Borrowing right neighbor lane. if (reference_line_info.GetNeighborLaneInfo( ReferenceLineInfo::LaneType::RightForward, curr_s, &neighbor_lane_id, &curr_neighbor_lane_width)) { ADEBUG << "Borrow right forward neighbor lane."; } else if (reference_line_info.GetNeighborLaneInfo( ReferenceLineInfo::LaneType::RightReverse, curr_s, &neighbor_lane_id, &curr_neighbor_lane_width)) { borrowing_reverse_lane = true; ADEBUG << "Borrow right reverse neighbor lane."; } else { ADEBUG << "There is no right neighbor lane."; } } } // 3. Calculate the proper boundary based on lane-width, ADC's position, // and ADC's velocity. static constexpr double kMaxLateralAccelerations = 1.5; double offset_to_map = 0.0; reference_line.GetOffsetToMap(curr_s, &offset_to_map); double ADC_speed_buffer = (adc_frenet_ld_ > 0 ? 1.0 : -1.0) * adc_frenet_ld_ * adc_frenet_ld_ / kMaxLateralAccelerations / 2.0; double curr_left_bound_lane = curr_lane_left_width + (lane_borrow_info == LaneBorrowInfo::LEFT_BORROW ? curr_neighbor_lane_width : 0.0); double curr_right_bound_lane = -curr_lane_right_width - (lane_borrow_info == LaneBorrowInfo::RIGHT_BORROW ? curr_neighbor_lane_width : 0.0); double curr_left_bound = 0.0; double curr_right_bound = 0.0; if (config_.path_bounds_decider_config() .is_extend_lane_bounds_to_include_adc() || is_fallback_lanechange) { // extend path bounds to include ADC in fallback or change lane path // bounds. double curr_left_bound_adc = std::fmax(adc_l_to_lane_center_, adc_l_to_lane_center_ + ADC_speed_buffer) + GetBufferBetweenADCCenterAndEdge() + ADC_buffer; curr_left_bound = std::fmax(curr_left_bound_lane, curr_left_bound_adc) - offset_to_map; double curr_right_bound_adc = std::fmin(adc_l_to_lane_center_, adc_l_to_lane_center_ + ADC_speed_buffer) - GetBufferBetweenADCCenterAndEdge() - ADC_buffer; curr_right_bound = std::fmin(curr_right_bound_lane, curr_right_bound_adc) - offset_to_map; } else { curr_left_bound = curr_left_bound_lane - offset_to_map; curr_right_bound = curr_right_bound_lane - offset_to_map; } ADEBUG << "At s = " << curr_s << ", left_lane_bound = " << curr_lane_left_width << ", right_lane_bound = " << curr_lane_right_width << ", offset = " << offset_to_map; // 4. Update the boundary. if (!UpdatePathBoundaryWithBuffer(i, curr_left_bound, curr_right_bound, path_bound, is_left_lane_boundary, is_right_lane_boundary)) { path_blocked_idx = static_cast<int>(i); } if (path_blocked_idx != -1) { break; } } TrimPathBounds(path_blocked_idx, path_bound); if (lane_borrow_info == LaneBorrowInfo::NO_BORROW) { *borrow_lane_type = ""; } else { *borrow_lane_type = borrowing_reverse_lane ? "reverse" : "forward"; } return true; } // update boundaries with corresponding one-side lane boundary for pull over // (1) use left lane boundary for normal PULL_OVER type // (2) use left/right(which is opposite to pull over direction // (pull over at closer road side) lane boundary for EMERGENCY_PULL_OVER void PathBoundsDecider::UpdatePullOverBoundaryByLaneBoundary( const ReferenceLineInfo& reference_line_info, PathBound* const path_bound) { const ReferenceLine& reference_line = reference_line_info.reference_line(); const auto& pull_over_status = injector_->planning_context()->planning_status().pull_over(); const auto pull_over_type = pull_over_status.pull_over_type(); if (pull_over_type != PullOverStatus::PULL_OVER && pull_over_type != PullOverStatus::EMERGENCY_PULL_OVER) { return; } for (size_t i = 0; i < path_bound->size(); ++i) { const double curr_s = std::get<0>((*path_bound)[i]); double left_bound = 3.0; double right_bound = 3.0; double curr_lane_left_width = 0.0; double curr_lane_right_width = 0.0; if (reference_line.GetLaneWidth(curr_s, &curr_lane_left_width, &curr_lane_right_width)) { double offset_to_lane_center = 0.0; reference_line.GetOffsetToMap(curr_s, &offset_to_lane_center); left_bound = curr_lane_left_width + offset_to_lane_center; right_bound = curr_lane_right_width + offset_to_lane_center; } ADEBUG << "left_bound[" << left_bound << "] right_bound[" << right_bound << "]"; if (pull_over_type == PullOverStatus::PULL_OVER) { std::get<2>((*path_bound)[i]) = left_bound; } else if (pull_over_type == PullOverStatus::EMERGENCY_PULL_OVER) { // TODO(all): use left/right lane boundary accordingly std::get<2>((*path_bound)[i]) = left_bound; } } } void PathBoundsDecider::ConvertBoundarySAxisFromLaneCenterToRefLine( const ReferenceLineInfo& reference_line_info, PathBound* const path_bound) { const ReferenceLine& reference_line = reference_line_info.reference_line(); for (size_t i = 0; i < path_bound->size(); ++i) { // 1. Get road boundary. double curr_s = std::get<0>((*path_bound)[i]); double refline_offset_to_lane_center = 0.0; reference_line.GetOffsetToMap(curr_s, &refline_offset_to_lane_center); std::get<1>((*path_bound)[i]) -= refline_offset_to_lane_center; std::get<2>((*path_bound)[i]) -= refline_offset_to_lane_center; } } void PathBoundsDecider::GetBoundaryFromLaneChangeForbiddenZone( const ReferenceLineInfo& reference_line_info, PathBound* const path_bound) { // Sanity checks. CHECK_NOTNULL(path_bound); const ReferenceLine& reference_line = reference_line_info.reference_line(); // If there is a pre-determined lane-change starting position, then use it; // otherwise, decide one. auto* lane_change_status = injector_->planning_context() ->mutable_planning_status() ->mutable_change_lane(); if (lane_change_status->is_clear_to_change_lane()) { ADEBUG << "Current position is clear to change lane. No need prep s."; lane_change_status->set_exist_lane_change_start_position(false); return; } double lane_change_start_s = 0.0; if (lane_change_status->exist_lane_change_start_position()) { common::SLPoint point_sl; reference_line.XYToSL(lane_change_status->lane_change_start_position(), &point_sl); lane_change_start_s = point_sl.s(); } else { // TODO(jiacheng): train ML model to learn this. lane_change_start_s = FLAGS_lane_change_prepare_length + adc_frenet_s_; // Update the decided lane_change_start_s into planning-context. common::SLPoint lane_change_start_sl; lane_change_start_sl.set_s(lane_change_start_s); lane_change_start_sl.set_l(0.0); common::math::Vec2d lane_change_start_xy; reference_line.SLToXY(lane_change_start_sl, &lane_change_start_xy); lane_change_status->set_exist_lane_change_start_position(true); lane_change_status->mutable_lane_change_start_position()->set_x( lane_change_start_xy.x()); lane_change_status->mutable_lane_change_start_position()->set_y( lane_change_start_xy.y()); } // Remove the target lane out of the path-boundary, up to the decided S. if (lane_change_start_s < adc_frenet_s_) { // If already passed the decided S, then return. // lane_change_status->set_exist_lane_change_start_position(false); return; } for (size_t i = 0; i < path_bound->size(); ++i) { double curr_s = std::get<0>((*path_bound)[i]); if (curr_s > lane_change_start_s) { break; } double curr_lane_left_width = 0.0; double curr_lane_right_width = 0.0; double offset_to_map = 0.0; reference_line.GetOffsetToMap(curr_s, &offset_to_map); if (reference_line.GetLaneWidth(curr_s, &curr_lane_left_width, &curr_lane_right_width)) { double offset_to_lane_center = 0.0; reference_line.GetOffsetToMap(curr_s, &offset_to_lane_center); curr_lane_left_width += offset_to_lane_center; curr_lane_right_width -= offset_to_lane_center; } curr_lane_left_width -= offset_to_map; curr_lane_right_width += offset_to_map; std::get<1>((*path_bound)[i]) = adc_frenet_l_ > curr_lane_left_width ? curr_lane_left_width + GetBufferBetweenADCCenterAndEdge() : std::get<1>((*path_bound)[i]); std::get<1>((*path_bound)[i]) = std::fmin(std::get<1>((*path_bound)[i]), adc_frenet_l_ - 0.1); std::get<2>((*path_bound)[i]) = adc_frenet_l_ < -curr_lane_right_width ? -curr_lane_right_width - GetBufferBetweenADCCenterAndEdge() : std::get<2>((*path_bound)[i]); std::get<2>((*path_bound)[i]) = std::fmax(std::get<2>((*path_bound)[i]), adc_frenet_l_ + 0.1); } } // Currently, it processes each obstacle based on its frenet-frame // projection. Therefore, it might be overly conservative when processing // obstacles whose headings differ from road-headings a lot. // TODO(all): (future work) this can be improved in the future. bool PathBoundsDecider::GetBoundaryFromStaticObstacles( const PathDecision& path_decision, PathBound* const path_boundaries, std::string* const blocking_obstacle_id) { // Preprocessing. auto indexed_obstacles = path_decision.obstacles(); auto sorted_obstacles = SortObstaclesForSweepLine(indexed_obstacles); ADEBUG << "There are " << sorted_obstacles.size() << " obstacles."; double center_line = adc_frenet_l_; size_t obs_idx = 0; int path_blocked_idx = -1; std::multiset<double, std::greater<double>> right_bounds; right_bounds.insert(std::numeric_limits<double>::lowest()); std::multiset<double> left_bounds; left_bounds.insert(std::numeric_limits<double>::max()); // Maps obstacle ID's to the decided ADC pass direction, if ADC should // pass from left, then true; otherwise, false. std::unordered_map<std::string, bool> obs_id_to_direction; // Maps obstacle ID's to the decision of whether side-pass on this obstacle // is allowed. If allowed, then true; otherwise, false. std::unordered_map<std::string, bool> obs_id_to_sidepass_decision; // Step through every path point. for (size_t i = 1; i < path_boundaries->size(); ++i) { double curr_s = std::get<0>((*path_boundaries)[i]); // Check and see if there is any obstacle change: if (obs_idx < sorted_obstacles.size() && std::get<1>(sorted_obstacles[obs_idx]) < curr_s) { while (obs_idx < sorted_obstacles.size() && std::get<1>(sorted_obstacles[obs_idx]) < curr_s) { const auto& curr_obstacle = sorted_obstacles[obs_idx]; const double curr_obstacle_s = std::get<1>(curr_obstacle); const double curr_obstacle_l_min = std::get<2>(curr_obstacle); const double curr_obstacle_l_max = std::get<3>(curr_obstacle); const std::string curr_obstacle_id = std::get<4>(curr_obstacle); ADEBUG << "id[" << curr_obstacle_id << "] s[" << curr_obstacle_s << "] curr_obstacle_l_min[" << curr_obstacle_l_min << "] curr_obstacle_l_max[" << curr_obstacle_l_max << "] center_line[" << center_line << "]"; if (std::get<0>(curr_obstacle) == 1) { // A new obstacle enters into our scope: // - Decide which direction for the ADC to pass. // - Update the left/right bound accordingly. // - If boundaries blocked, then decide whether can side-pass. // - If yes, then borrow neighbor lane to side-pass. if (curr_obstacle_l_min + curr_obstacle_l_max < center_line * 2) { // Obstacle is to the right of center-line, should pass from left. obs_id_to_direction[curr_obstacle_id] = true; right_bounds.insert(curr_obstacle_l_max); } else { // Obstacle is to the left of center-line, should pass from right. obs_id_to_direction[curr_obstacle_id] = false; left_bounds.insert(curr_obstacle_l_min); } if (!UpdatePathBoundaryAndCenterLineWithBuffer( i, *left_bounds.begin(), *right_bounds.begin(), path_boundaries, &center_line)) { path_blocked_idx = static_cast<int>(i); *blocking_obstacle_id = curr_obstacle_id; break; } } else { // An existing obstacle exits our scope. if (obs_id_to_direction[curr_obstacle_id]) { right_bounds.erase(right_bounds.find(curr_obstacle_l_max)); } else { left_bounds.erase(left_bounds.find(curr_obstacle_l_min)); } obs_id_to_direction.erase(curr_obstacle_id); } // Update the bounds and center_line. std::get<1>((*path_boundaries)[i]) = std::fmax( std::get<1>((*path_boundaries)[i]), *right_bounds.begin() + GetBufferBetweenADCCenterAndEdge()); std::get<2>((*path_boundaries)[i]) = std::fmin( std::get<2>((*path_boundaries)[i]), *left_bounds.begin() - GetBufferBetweenADCCenterAndEdge()); if (std::get<1>((*path_boundaries)[i]) > std::get<2>((*path_boundaries)[i])) { ADEBUG << "Path is blocked at s = " << curr_s; path_blocked_idx = static_cast<int>(i); if (!obs_id_to_direction.empty()) { *blocking_obstacle_id = obs_id_to_direction.begin()->first; } break; } else { center_line = (std::get<1>((*path_boundaries)[i]) + std::get<2>((*path_boundaries)[i])) / 2.0; } ++obs_idx; } } else { // If no obstacle change, update the bounds and center_line. std::get<1>((*path_boundaries)[i]) = std::fmax(std::get<1>((*path_boundaries)[i]), *right_bounds.begin() + GetBufferBetweenADCCenterAndEdge()); std::get<2>((*path_boundaries)[i]) = std::fmin(std::get<2>((*path_boundaries)[i]), *left_bounds.begin() - GetBufferBetweenADCCenterAndEdge()); if (std::get<1>((*path_boundaries)[i]) > std::get<2>((*path_boundaries)[i])) { ADEBUG << "Path is blocked at s = " << curr_s; path_blocked_idx = static_cast<int>(i); if (!obs_id_to_direction.empty()) { *blocking_obstacle_id = obs_id_to_direction.begin()->first; } } else { center_line = (std::get<1>((*path_boundaries)[i]) + std::get<2>((*path_boundaries)[i])) / 2.0; } } // Early exit if path is blocked. if (path_blocked_idx != -1) { break; } } TrimPathBounds(path_blocked_idx, path_boundaries); return true; } // The tuple contains (is_start_s, s, l_min, l_max, obstacle_id) std::vector<ObstacleEdge> PathBoundsDecider::SortObstaclesForSweepLine( const IndexedList<std::string, Obstacle>& indexed_obstacles) { std::vector<ObstacleEdge> sorted_obstacles; // Go through every obstacle and preprocess it. for (const auto* obstacle : indexed_obstacles.Items()) { // Only focus on those within-scope obstacles. if (!IsWithinPathDeciderScopeObstacle(*obstacle)) { continue; } // Only focus on obstacles that are ahead of ADC. if (obstacle->PerceptionSLBoundary().end_s() < adc_frenet_s_) { continue; } // Decompose each obstacle's rectangle into two edges: one at // start_s; the other at end_s. const auto obstacle_sl = obstacle->PerceptionSLBoundary(); sorted_obstacles.emplace_back( 1, obstacle_sl.start_s() - FLAGS_obstacle_lon_start_buffer, obstacle_sl.start_l() - FLAGS_obstacle_lat_buffer, obstacle_sl.end_l() + FLAGS_obstacle_lat_buffer, obstacle->Id()); sorted_obstacles.emplace_back( 0, obstacle_sl.end_s() + FLAGS_obstacle_lon_end_buffer, obstacle_sl.start_l() - FLAGS_obstacle_lat_buffer, obstacle_sl.end_l() + FLAGS_obstacle_lat_buffer, obstacle->Id()); } // Sort. std::sort(sorted_obstacles.begin(), sorted_obstacles.end(), [](const ObstacleEdge& lhs, const ObstacleEdge& rhs) { if (std::get<1>(lhs) != std::get<1>(rhs)) { return std::get<1>(lhs) < std::get<1>(rhs); } else { return std::get<0>(lhs) > std::get<0>(rhs); } }); return sorted_obstacles; } std::vector<PathBound> PathBoundsDecider::ConstructSubsequentPathBounds( const std::vector<ObstacleEdge>& sorted_obstacles, size_t path_idx, size_t obs_idx, std::unordered_map<std::string, std::tuple<bool, double>>* const obs_id_to_details, PathBound* const curr_path_bounds) { double left_bounds_from_obstacles = std::numeric_limits<double>::max(); double right_bounds_from_obstacles = std::numeric_limits<double>::lowest(); double curr_s = std::get<0>((*curr_path_bounds)[path_idx]); //============================================================== // If searched through all available s and found a path, return. if (path_idx >= curr_path_bounds->size()) { ADEBUG << "Completed path bounds search ending at path_idx = " << path_idx; return {*curr_path_bounds}; } //============================================================== // If there is no obstacle updates at this path_idx. if (obs_idx >= sorted_obstacles.size() || std::get<1>(sorted_obstacles[obs_idx]) > curr_s) { // 0. Backup the old memory. auto old_path_boundary = *curr_path_bounds; // 1. Get the boundary from obstacles. for (auto it = obs_id_to_details->begin(); it != obs_id_to_details->end(); ++it) { if (std::get<0>(it->second)) { // Pass from left. right_bounds_from_obstacles = std::max(right_bounds_from_obstacles, std::get<1>(it->second)); } else { // Pass from right. left_bounds_from_obstacles = std::min(left_bounds_from_obstacles, std::get<1>(it->second)); } } // 2. Update the path boundary bool is_able_to_update = UpdatePathBoundaryWithBuffer( path_idx, left_bounds_from_obstacles, right_bounds_from_obstacles, curr_path_bounds); // 3. Return proper values. std::vector<PathBound> ret; if (is_able_to_update) { ret = ConstructSubsequentPathBounds(sorted_obstacles, path_idx + 1, obs_idx, obs_id_to_details, curr_path_bounds); } else { TrimPathBounds(static_cast<int>(path_idx), curr_path_bounds); ret.push_back(*curr_path_bounds); } *curr_path_bounds = old_path_boundary; return ret; } //============================================================== // If there are obstacle changes // 0. Backup the old memory. std::unordered_map<std::string, std::tuple<bool, double>> old_obs_id_to_details = *obs_id_to_details; auto old_path_boundary = *curr_path_bounds; // 1. Go through all obstacle changes. // - For exiting obstacle, remove from our memory. // - For entering obstacle, save it to a vector. std::vector<ObstacleEdge> new_entering_obstacles; size_t new_obs_idx = obs_idx; while (new_obs_idx < sorted_obstacles.size() && std::get<1>(sorted_obstacles[new_obs_idx]) <= curr_s) { if (!std::get<0>(sorted_obstacles[new_obs_idx])) { // For exiting obstacle. obs_id_to_details->erase(std::get<4>(sorted_obstacles[new_obs_idx])); } else { // For entering obstacle. new_entering_obstacles.push_back(sorted_obstacles[new_obs_idx]); } ++new_obs_idx; } // 2. For new entering obstacles, decide possible pass directions. // (ranked in terms of optimality) auto pass_direction_decisions = DecidePassDirections(0.0, 0.0, new_entering_obstacles); // 3. Try constructing subsequent path-bounds for all possible directions. std::vector<PathBound> ret; for (size_t i = 0; i < pass_direction_decisions.size(); ++i) { // For each possible direction: // a. Update the obs_id_to_details for (size_t j = 0; j < pass_direction_decisions[i].size(); ++j) { if (pass_direction_decisions[i][j]) { // Pass from left. (*obs_id_to_details)[std::get<4>(new_entering_obstacles[j])] = std::make_tuple(true, std::get<3>(new_entering_obstacles[j])); } else { // Pass from right. (*obs_id_to_details)[std::get<4>(new_entering_obstacles[j])] = std::make_tuple(false, std::get<2>(new_entering_obstacles[j])); } } // b. Figure out left/right bounds after the updates. for (auto it = obs_id_to_details->begin(); it != obs_id_to_details->end(); ++it) { if (std::get<0>(it->second)) { // Pass from left. right_bounds_from_obstacles = std::max(right_bounds_from_obstacles, std::get<1>(it->second)); } else { // Pass from right. left_bounds_from_obstacles = std::min(left_bounds_from_obstacles, std::get<1>(it->second)); } } // c. Update for this path_idx, and construct the subsequent path bounds. std::vector<PathBound> curr_dir_path_boundaries; bool is_able_to_update = UpdatePathBoundaryWithBuffer( path_idx, left_bounds_from_obstacles, right_bounds_from_obstacles, curr_path_bounds); if (is_able_to_update) { curr_dir_path_boundaries = ConstructSubsequentPathBounds( sorted_obstacles, path_idx + 1, new_obs_idx, obs_id_to_details, curr_path_bounds); } else { TrimPathBounds(static_cast<int>(path_idx), curr_path_bounds); curr_dir_path_boundaries.push_back(*curr_path_bounds); } // d. Update the path_bounds into the vector, and revert changes // to curr_path_bounds for next cycle. ret.insert(ret.end(), curr_dir_path_boundaries.begin(), curr_dir_path_boundaries.end()); *curr_path_bounds = old_path_boundary; } // 4. Select the best path_bounds in ret. *obs_id_to_details = old_obs_id_to_details; *curr_path_bounds = old_path_boundary; std::sort(ret.begin(), ret.end(), [](const PathBound& lhs, const PathBound& rhs) { return lhs.size() > rhs.size(); }); while (ret.size() > 3) { ret.pop_back(); } return ret; } std::vector<std::vector<bool>> PathBoundsDecider::DecidePassDirections( double l_min, double l_max, const std::vector<ObstacleEdge>& new_entering_obstacles) { std::vector<std::vector<bool>> decisions; // Convert into lateral edges. std::vector<ObstacleEdge> lateral_edges; lateral_edges.emplace_back(1, std::numeric_limits<double>::lowest(), 0.0, 0.0, "l_min"); lateral_edges.emplace_back(0, l_min, 0.0, 0.0, "l_min"); lateral_edges.emplace_back(1, l_max, 0.0, 0.0, "l_max"); lateral_edges.emplace_back(0, std::numeric_limits<double>::max(), 0.0, 0.0, "l_max"); for (size_t i = 0; i < new_entering_obstacles.size(); ++i) { if (std::get<3>(new_entering_obstacles[i]) < l_min || std::get<2>(new_entering_obstacles[i]) > l_max) { continue; } lateral_edges.emplace_back(1, std::get<2>(new_entering_obstacles[i]), 0.0, 0.0, std::get<4>(new_entering_obstacles[i])); lateral_edges.emplace_back(0, std::get<3>(new_entering_obstacles[i]), 0.0, 0.0, std::get<4>(new_entering_obstacles[i])); } // Sort the lateral edges for lateral sweep-line algorithm. std::sort(lateral_edges.begin(), lateral_edges.end(), [](const ObstacleEdge& lhs, const ObstacleEdge& rhs) { if (std::get<1>(lhs) != std::get<1>(rhs)) { return std::get<1>(lhs) < std::get<1>(rhs); } else { return std::get<0>(lhs) > std::get<0>(rhs); } }); // Go through the lateral edges and find any possible slot. std::vector<double> empty_slot; int num_obs = 0; for (size_t i = 0; i < lateral_edges.size(); ++i) { // Update obstacle overlapping info. if (std::get<0>(lateral_edges[i])) { ++num_obs; } else { --num_obs; } // If there is an empty slot within lane boundary. if (num_obs == 0 && i != lateral_edges.size() - 1) { empty_slot.push_back( (std::get<1>(lateral_edges[i]) + std::get<1>(lateral_edges[i + 1])) / 2.0); } } // For each empty slot, update a corresponding pass direction for (size_t i = 0; i < empty_slot.size(); ++i) { double pass_position = empty_slot[i]; std::vector<bool> pass_direction; for (size_t j = 0; j < new_entering_obstacles.size(); ++j) { if (std::get<2>(new_entering_obstacles[j]) > pass_position) { pass_direction.push_back(false); } else { pass_direction.push_back(true); } } decisions.push_back(pass_direction); } // TODO(jiacheng): sort the decisions based on the feasibility. return decisions; } double PathBoundsDecider::GetBufferBetweenADCCenterAndEdge() { double adc_half_width = VehicleConfigHelper::GetConfig().vehicle_param().width() / 2.0; // TODO(all): currently it's a fixed number. But it can take into account many // factors such as: ADC length, possible turning angle, speed, etc. static constexpr double kAdcEdgeBuffer = 0.0; return (adc_half_width + kAdcEdgeBuffer); } bool PathBoundsDecider::UpdatePathBoundaryWithBuffer( size_t idx, double left_bound, double right_bound, PathBound* const path_boundaries, bool is_left_lane_bound, bool is_right_lane_bound) { // substract vehicle width when bound does not come from the lane boundary const double default_adc_buffer_coeff = 1.0; double left_adc_buffer_coeff = (is_left_lane_bound ? config_.path_bounds_decider_config().adc_buffer_coeff() : default_adc_buffer_coeff); double right_adc_buffer_coeff = (is_right_lane_bound ? config_.path_bounds_decider_config().adc_buffer_coeff() : default_adc_buffer_coeff); // Update the right bound (l_min): double new_l_min = std::fmax(std::get<1>((*path_boundaries)[idx]), right_bound + right_adc_buffer_coeff * GetBufferBetweenADCCenterAndEdge()); // Update the left bound (l_max): double new_l_max = std::fmin( std::get<2>((*path_boundaries)[idx]), left_bound - left_adc_buffer_coeff * GetBufferBetweenADCCenterAndEdge()); // Check if ADC is blocked. // If blocked, don't update anything, return false. if (new_l_min > new_l_max) { ADEBUG << "Path is blocked at idx = " << idx; return false; } // Otherwise, update path_boundaries and center_line; then return true. std::get<1>((*path_boundaries)[idx]) = new_l_min; std::get<2>((*path_boundaries)[idx]) = new_l_max; return true; } bool PathBoundsDecider::UpdatePathBoundaryAndCenterLineWithBuffer( size_t idx, double left_bound, double right_bound, PathBound* const path_boundaries, double* const center_line) { UpdatePathBoundaryWithBuffer(idx, left_bound, right_bound, path_boundaries); *center_line = (std::get<1>((*path_boundaries)[idx]) + std::get<2>((*path_boundaries)[idx])) / 2.0; return true; } bool PathBoundsDecider::UpdatePathBoundary(size_t idx, double left_bound, double right_bound, PathBound* const path_boundaries) { // Update the right bound (l_min): double new_l_min = std::fmax(std::get<1>((*path_boundaries)[idx]), right_bound); // Update the left bound (l_max): double new_l_max = std::fmin(std::get<2>((*path_boundaries)[idx]), left_bound); // Check if ADC is blocked. // If blocked, don't update anything, return false. if (new_l_min > new_l_max) { ADEBUG << "Path is blocked at idx = " << idx; return false; } // Otherwise, update path_boundaries and center_line; then return true. std::get<1>((*path_boundaries)[idx]) = new_l_min; std::get<2>((*path_boundaries)[idx]) = new_l_max; return true; } void PathBoundsDecider::TrimPathBounds(const int path_blocked_idx, PathBound* const path_boundaries) { if (path_blocked_idx != -1) { if (path_blocked_idx == 0) { ADEBUG << "Completely blocked. Cannot move at all."; } int range = static_cast<int>(path_boundaries->size()) - path_blocked_idx; for (int i = 0; i < range; ++i) { path_boundaries->pop_back(); } } } void PathBoundsDecider::PathBoundsDebugString( const PathBound& path_boundaries) { for (size_t i = 0; i < path_boundaries.size(); ++i) { AWARN << "idx " << i << "; s = " << std::get<0>(path_boundaries[i]) << "; l_min = " << std::get<1>(path_boundaries[i]) << "; l_max = " << std::get<2>(path_boundaries[i]); } } bool PathBoundsDecider::CheckLaneBoundaryType( const ReferenceLineInfo& reference_line_info, const double check_s, const LaneBorrowInfo& lane_borrow_info) { if (lane_borrow_info == LaneBorrowInfo::NO_BORROW) { return false; } const ReferenceLine& reference_line = reference_line_info.reference_line(); auto ref_point = reference_line.GetNearestReferencePoint(check_s); if (ref_point.lane_waypoints().empty()) { return false; } const auto waypoint = ref_point.lane_waypoints().front(); hdmap::LaneBoundaryType::Type lane_boundary_type = hdmap::LaneBoundaryType::UNKNOWN; if (lane_borrow_info == LaneBorrowInfo::LEFT_BORROW) { lane_boundary_type = hdmap::LeftBoundaryType(waypoint); } else if (lane_borrow_info == LaneBorrowInfo::RIGHT_BORROW) { lane_boundary_type = hdmap::RightBoundaryType(waypoint); } if (lane_boundary_type == hdmap::LaneBoundaryType::SOLID_YELLOW || lane_boundary_type == hdmap::LaneBoundaryType::SOLID_WHITE) { return false; } return true; } void PathBoundsDecider::RecordDebugInfo( const PathBound& path_boundaries, const std::string& debug_name, ReferenceLineInfo* const reference_line_info) { // Sanity checks. ACHECK(!path_boundaries.empty()); CHECK_NOTNULL(reference_line_info); // Take the left and right path boundaries, and transform them into two // PathData so that they can be displayed in simulator. std::vector<common::FrenetFramePoint> frenet_frame_left_boundaries; std::vector<common::FrenetFramePoint> frenet_frame_right_boundaries; for (const PathBoundPoint& path_bound_point : path_boundaries) { common::FrenetFramePoint frenet_frame_point; frenet_frame_point.set_s(std::get<0>(path_bound_point)); frenet_frame_point.set_dl(0.0); frenet_frame_point.set_ddl(0.0); frenet_frame_point.set_l(std::get<1>(path_bound_point)); frenet_frame_right_boundaries.push_back(frenet_frame_point); frenet_frame_point.set_l(std::get<2>(path_bound_point)); frenet_frame_left_boundaries.push_back(frenet_frame_point); } auto frenet_frame_left_path = FrenetFramePath(std::move(frenet_frame_left_boundaries)); auto frenet_frame_right_path = FrenetFramePath(std::move(frenet_frame_right_boundaries)); PathData left_path_data; left_path_data.SetReferenceLine(&(reference_line_info->reference_line())); left_path_data.SetFrenetPath(std::move(frenet_frame_left_path)); PathData right_path_data; right_path_data.SetReferenceLine(&(reference_line_info->reference_line())); right_path_data.SetFrenetPath(std::move(frenet_frame_right_path)); // Insert the transformed PathData into the simulator display. auto* ptr_display_path_1 = reference_line_info->mutable_debug()->mutable_planning_data()->add_path(); ptr_display_path_1->set_name("planning_path_boundary_1"); ptr_display_path_1->mutable_path_point()->CopyFrom( {left_path_data.discretized_path().begin(), left_path_data.discretized_path().end()}); auto* ptr_display_path_2 = reference_line_info->mutable_debug()->mutable_planning_data()->add_path(); ptr_display_path_2->set_name("planning_path_boundary_2"); ptr_display_path_2->mutable_path_point()->CopyFrom( {right_path_data.discretized_path().begin(), right_path_data.discretized_path().end()}); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_bounds_decider/path_bounds_decider_test.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/path_bounds_decider/path_bounds_decider.h" #include "gtest/gtest.h" #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { class PathBoundsDeciderTest : public ::testing::Test { public: virtual void SetUp() { config_.set_task_type(TaskConfig::PATH_BOUNDS_DECIDER); config_.mutable_path_bounds_decider_config(); config_.mutable_path_bounds_decider_config()->set_is_lane_borrowing(false); injector_ = std::make_shared<DependencyInjector>(); } virtual void TearDown() {} protected: TaskConfig config_; std::shared_ptr<DependencyInjector> injector_; }; TEST_F(PathBoundsDeciderTest, Init) { PathBoundsDecider path_bounds_decider(config_, injector_); EXPECT_EQ(path_bounds_decider.Name(), TaskConfig::TaskType_Name(config_.task_type())); } TEST_F(PathBoundsDeciderTest, InitPathBoundary) { PathBoundsDecider path_bounds_decider(config_, injector_); path_bounds_decider.adc_frenet_s_ = 10.0; // TODO(all): implement this unit test. // ReferenceLine reference_line; // reference_line.map_path_.length_ = 200.0; // std::vector<std::tuple<double, double, double>> path_boundary; } TEST_F(PathBoundsDeciderTest, GetBoundaryFromLanesAndADC) { PathBoundsDecider path_bounds_decider(config_, injector_); path_bounds_decider.adc_frenet_s_ = 10.0; // TODO(all): implement this unit test. } TEST_F(PathBoundsDeciderTest, GetBoundaryFromStaticObstacles) { PathBoundsDecider path_bounds_decider(config_, injector_); std::vector<std::tuple<double, double, double>> path_bound; PathDecision path_decision; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_bounds_decider/path_bounds_decider.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <memory> #include <string> #include <tuple> #include <unordered_map> #include <utility> #include <vector> #include "gtest/gtest.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/tasks/deciders/decider.h" namespace apollo { namespace planning { constexpr double kPathBoundsDeciderHorizon = 100.0; constexpr double kPathBoundsDeciderResolution = 0.5; constexpr double kDefaultLaneWidth = 5.0; constexpr double kDefaultRoadWidth = 20.0; // TODO(all): Update extra tail point base on vehicle speed. constexpr int kNumExtraTailBoundPoint = 20; constexpr double kPulloverLonSearchCoeff = 1.5; constexpr double kPulloverLatSearchCoeff = 1.25; class PathBoundsDecider : public Decider { public: enum class LaneBorrowInfo { LEFT_BORROW, NO_BORROW, RIGHT_BORROW, }; PathBoundsDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); private: /** @brief Every time when Process function is called, it will: * 1. Initialize. * 2. Generate Fallback Path Bound. * 3. Generate Regular Path Bound(s). */ common::Status Process(Frame* frame, ReferenceLineInfo* reference_line_info) override; ///////////////////////////////////////////////////////////////////////////// // Below are functions called every frame when executing PathBoundsDecider. /** @brief The initialization function. */ void InitPathBoundsDecider(const Frame& frame, const ReferenceLineInfo& reference_line_info); common::TrajectoryPoint InferFrontAxeCenterFromRearAxeCenter( const common::TrajectoryPoint& traj_point); /** @brief The regular path boundary generation considers the ADC itself * and other static environments: * - ADC's position (lane-changing considerations) * - lane info * - static obstacles * The philosophy is: static environment must be and can only be taken * care of by the path planning. * @param reference_line_info * @param lane_borrow_info: which lane to borrow. * @param The generated regular path_boundary, if there is one. * @param The blocking obstacle's id. If none, then it's not modified. * @return common::Status */ common::Status GenerateRegularPathBound( const ReferenceLineInfo& reference_line_info, const LaneBorrowInfo& lane_borrow_info, std::vector<std::tuple<double, double, double>>* const path_bound, std::string* const blocking_obstacle_id, std::string* const borrow_lane_type); /** @brief The fallback path only considers: * - ADC's position (so that boundary must contain ADC's position) * - lane info * It is supposed to be the last resort in case regular path generation * fails so that speed decider can at least have some path and won't * fail drastically. * Therefore, it be reliable so that optimizer will not likely to * fail with this boundary, and therefore doesn't consider any static * obstacle. When the fallback path is used, stopping before static * obstacles should be taken care of by the speed decider. Also, it * doesn't consider any lane-borrowing. * @param reference_line_info * @param The generated fallback path_boundary, if there is one. * @return common::Status */ common::Status GenerateFallbackPathBound( const ReferenceLineInfo& reference_line_info, std::vector<std::tuple<double, double, double>>* const path_bound); common::Status GenerateLaneChangePathBound( const ReferenceLineInfo& reference_line_info, std::vector<std::tuple<double, double, double>>* const path_bound); common::Status GeneratePullOverPathBound( const Frame& frame, const ReferenceLineInfo& reference_line_info, std::vector<std::tuple<double, double, double>>* const path_bound); int IsPointWithinPathBound( const ReferenceLineInfo& reference_line_info, const double x, const double y, const std::vector<std::tuple<double, double, double>>& path_bound); bool FindDestinationPullOverS( const Frame& frame, const ReferenceLineInfo& reference_line_info, const std::vector<std::tuple<double, double, double>>& path_bound, double* pull_over_s); bool FindEmergencyPullOverS(const ReferenceLineInfo& reference_line_info, double* pull_over_s); bool SearchPullOverPosition( const Frame& frame, const ReferenceLineInfo& reference_line_info, const std::vector<std::tuple<double, double, double>>& path_bound, std::tuple<double, double, double, int>* const pull_over_configuration); /** @brief Remove redundant path bounds in the following manner: * - if "left" is contained by "right", remove "left"; vice versa. */ void RemoveRedundantPathBoundaries( std::vector<PathBoundary>* const candidate_path_boundaries); bool IsContained(const std::vector<std::pair<double, double>>& lhs, const std::vector<std::pair<double, double>>& rhs); ///////////////////////////////////////////////////////////////////////////// // Below are functions called when generating path bounds. /** @brief Initializes an empty path boundary. */ bool InitPathBoundary( const ReferenceLineInfo& reference_line_info, std::vector<std::tuple<double, double, double>>* const path_bound); /** @brief Refine the boundary based on the road-info. * The returned boundary is with respect to the lane-center (NOT the * reference_line), though for most of the times reference_line's * deviation from lane-center is negligible. */ bool GetBoundaryFromRoads( const ReferenceLineInfo& reference_line_info, std::vector<std::tuple<double, double, double>>* const path_bound); /** @brief Refine the boundary based on the lane-info. * The returned boundary is with respect to the lane-center (NOT the * reference_line), though for most of the times reference_line's * deviation from lane-center is negligible. */ bool GetBoundaryFromLanes( const ReferenceLineInfo& reference_line_info, const LaneBorrowInfo& lane_borrow_info, std::vector<std::tuple<double, double, double>>* const path_bound, std::string* const borrow_lane_type); /** @brief Refine the boundary based on the ADC position and velocity. * The returned boundary is with respect to the lane-center (NOT the * reference_line), though for most of the times reference_line's * deviation from lane-center is negligible. */ bool GetBoundaryFromADC( const ReferenceLineInfo& reference_line_info, double ADC_extra_buffer, std::vector<std::tuple<double, double, double>>* const path_bound); /** @brief Refine the boundary based on lane-info and ADC's location. * It will comply to the lane-boundary. However, if the ADC itself * is out of the given lane(s), it will adjust the boundary * accordingly to include ADC's current position. */ bool GetBoundaryFromLanesAndADC( const ReferenceLineInfo& reference_line_info, const LaneBorrowInfo& lane_borrow_info, double ADC_buffer, std::vector<std::tuple<double, double, double>>* const path_bound, std::string* const borrow_lane_type, bool is_fallback_lanechange = false); /** @brief Update left boundary by lane_left_width * This is for normal pull-over, which uses lane boundary as left boundary * and road_boundary for right boundary */ void UpdatePullOverBoundaryByLaneBoundary( const ReferenceLineInfo& reference_line_info, std::vector<std::tuple<double, double, double>>* const path_bound); void ConvertBoundarySAxisFromLaneCenterToRefLine( const ReferenceLineInfo& reference_line_info, std::vector<std::tuple<double, double, double>>* const path_bound); void GetBoundaryFromLaneChangeForbiddenZone( const ReferenceLineInfo& reference_line_info, std::vector<std::tuple<double, double, double>>* const path_bound); /** @brief Refine the boundary based on static obstacles. It will make sure * the boundary doesn't contain any static obstacle so that the path * generated by optimizer won't collide with any static obstacle. */ bool GetBoundaryFromStaticObstacles( const PathDecision& path_decision, std::vector<std::tuple<double, double, double>>* const path_boundaries, std::string* const blocking_obstacle_id); std::vector<std::tuple<int, double, double, double, std::string>> SortObstaclesForSweepLine( const IndexedList<std::string, Obstacle>& indexed_obstacles); std::vector<std::vector<std::tuple<double, double, double>>> ConstructSubsequentPathBounds( const std::vector<std::tuple<int, double, double, double, std::string>>& sorted_obstacles, size_t path_idx, size_t obs_idx, std::unordered_map<std::string, std::tuple<bool, double>>* const obs_id_to_details, std::vector<std::tuple<double, double, double>>* const curr_path_bounds); std::vector<std::vector<bool>> DecidePassDirections( double l_min, double l_max, const std::vector<std::tuple<int, double, double, double, std::string>>& new_entering_obstacles); ///////////////////////////////////////////////////////////////////////////// // Below are several helper functions: /** @brief Get the distance between ADC's center and its edge. * @return The distance. */ double GetBufferBetweenADCCenterAndEdge(); /** @brief Update the path_boundary at "idx" * It also checks if ADC is blocked (lmax < lmin). * @param The current index of the path_bounds * @param The minimum left boundary (l_max) * @param The maximum right boundary (l_min) * @param The path_boundaries (its content at idx will be updated) * @param Is the left bound comes from lane boundary * @param Is the right bound comes from lane boundary * @return If path is good, true; if path is blocked, false. */ bool UpdatePathBoundaryWithBuffer( size_t idx, double left_bound, double right_bound, std::vector<std::tuple<double, double, double>>* const path_boundaries, bool is_left_lane_bound = false, bool is_right_lane_bound = false); /** @brief Update the path_boundary at "idx", as well as the new center-line. * It also checks if ADC is blocked (lmax < lmin). * @param The current index of the path_bounds * @param The minimum left boundary (l_max) * @param The maximum right boundary (l_min) * @param The path_boundaries (its content at idx will be updated) * @param The center_line (to be updated) * @return If path is good, true; if path is blocked, false. */ bool UpdatePathBoundaryAndCenterLineWithBuffer( size_t idx, double left_bound, double right_bound, std::vector<std::tuple<double, double, double>>* const path_boundaries, double* const center_line); /** @brief Update the path_boundary at "idx", It also checks if ADC is blocked (lmax < lmin). * @param The current index of the path_bounds * @param The minimum left boundary (l_max) * @param The maximum right boundary (l_min) * @param The path_boundaries (its content at idx will be updated) * @return If path is good, true; if path is blocked, false. */ bool UpdatePathBoundary( size_t idx, double left_bound, double right_bound, std::vector<std::tuple<double, double, double>>* const path_boundaries); /** @brief Trim the path bounds starting at the idx where path is blocked. */ void TrimPathBounds( const int path_blocked_idx, std::vector<std::tuple<double, double, double>>* const path_boundaries); /** @brief Print out the path bounds for debugging purpose. */ void PathBoundsDebugString( const std::vector<std::tuple<double, double, double>>& path_boundaries); bool CheckLaneBoundaryType(const ReferenceLineInfo& reference_line_info, const double check_s, const LaneBorrowInfo& lane_borrow_info); void RecordDebugInfo( const std::vector<std::tuple<double, double, double>>& path_boundaries, const std::string& debug_name, ReferenceLineInfo* const reference_line_info); private: double adc_frenet_s_ = 0.0; double adc_frenet_sd_ = 0.0; double adc_frenet_l_ = 0.0; double adc_frenet_ld_ = 0.0; double adc_l_to_lane_center_ = 0.0; double adc_lane_width_ = 0.0; FRIEND_TEST(PathBoundsDeciderTest, InitPathBoundary); FRIEND_TEST(PathBoundsDeciderTest, GetBoundaryFromLanesAndADC); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_bounds_decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "path_bounds_decider", srcs = ["path_bounds_decider.cc"], hdrs = ["path_bounds_decider.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/planning/common:planning_context", "//modules/planning/common:planning_gflags", "//modules/planning/common:reference_line_info", "//modules/planning/tasks/deciders:decider_base", "//modules/planning/tasks/deciders/utils:path_decider_obstacle_utils", ], ) cc_test( name = "path_bounds_decider_test", size = "small", srcs = ["path_bounds_decider_test.cc"], deps = [ "path_bounds_decider", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/st_bounds_decider/st_bounds_decider.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/tasks/deciders/st_bounds_decider/st_bounds_decider.h" #include <limits> #include <memory> #include "modules/planning/common/st_graph_data.h" #include "modules/planning/tasks/deciders/st_bounds_decider/st_obstacles_processor.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::planning_internal::StGraphBoundaryDebug; using apollo::planning_internal::STGraphDebug; namespace { // STBoundPoint contains (t, s_min, s_max) using STBoundPoint = std::tuple<double, double, double>; // STBound is a vector of STBoundPoints using STBound = std::vector<STBoundPoint>; // ObsDecSet is a set of decision for new obstacles. using ObsDecSet = std::vector<std::pair<std::string, ObjectDecisionType>>; } // namespace STBoundsDecider::STBoundsDecider( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Decider(config, injector) { ACHECK(config.has_st_bounds_decider_config()); st_bounds_config_ = config.st_bounds_decider_config(); } Status STBoundsDecider::Process(Frame* const frame, ReferenceLineInfo* const reference_line_info) { // Initialize the related helper classes. InitSTBoundsDecider(*frame, reference_line_info); // Sweep the t-axis, and determine the s-boundaries step by step. STBound regular_st_bound; STBound regular_vt_bound; std::vector<std::pair<double, double>> st_guide_line; Status ret = GenerateRegularSTBound(&regular_st_bound, &regular_vt_bound, &st_guide_line); if (!ret.ok()) { ADEBUG << "Cannot generate a regular ST-boundary."; return Status(ErrorCode::PLANNING_ERROR, ret.error_message()); } if (regular_st_bound.empty()) { const std::string msg = "Generated regular ST-boundary is empty."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } StGraphData* st_graph_data = reference_line_info_->mutable_st_graph_data(); st_graph_data->SetSTDrivableBoundary(regular_st_bound, regular_vt_bound); // Record the ST-Graph for good visualization and easy debugging. auto all_st_boundaries = st_obstacles_processor_.GetAllSTBoundaries(); std::vector<STBoundary> st_boundaries; for (const auto& st_boundary : all_st_boundaries) { st_boundaries.push_back(st_boundary.second); } ADEBUG << "Total ST boundaries = " << st_boundaries.size(); STGraphDebug* st_graph_debug = reference_line_info->mutable_debug() ->mutable_planning_data() ->add_st_graph(); RecordSTGraphDebug(st_boundaries, regular_st_bound, st_guide_line, st_graph_debug); return Status::OK(); } void STBoundsDecider::InitSTBoundsDecider( const Frame& frame, ReferenceLineInfo* const reference_line_info) { const PathData& path_data = reference_line_info->path_data(); PathDecision* path_decision = reference_line_info->path_decision(); // Map all related obstacles onto ST-Graph. auto time1 = std::chrono::system_clock::now(); st_obstacles_processor_.Init(path_data.discretized_path().Length(), st_bounds_config_.total_time(), path_data, path_decision, injector_->history()); st_obstacles_processor_.MapObstaclesToSTBoundaries(path_decision); auto time2 = std::chrono::system_clock::now(); std::chrono::duration<double> diff = time2 - time1; ADEBUG << "Time for ST Obstacles Processing = " << diff.count() * 1000 << " msec."; // Initialize Guide-Line and Driving-Limits. static constexpr double desired_speed = 15.0; // If the path_data optimization is guided from a reference path of a // reference trajectory, use its reference speed profile to select the st // bounds in LaneFollow Hybrid Mode if (path_data.is_optimized_towards_trajectory_reference()) { st_guide_line_.Init(desired_speed, injector_->learning_based_data() ->learning_data_adc_future_trajectory_points()); } else { st_guide_line_.Init(desired_speed); } static constexpr double max_acc = 2.5; static constexpr double max_dec = 5.0; static constexpr double max_v = desired_speed * 1.5; st_driving_limits_.Init(max_acc, max_dec, max_v, frame.PlanningStartPoint().v()); } Status STBoundsDecider::GenerateFallbackSTBound(STBound* const st_bound, STBound* const vt_bound) { // Initialize st-boundary. for (double curr_t = 0.0; curr_t <= st_bounds_config_.total_time(); curr_t += kSTBoundsDeciderResolution) { st_bound->emplace_back(curr_t, std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max()); vt_bound->emplace_back(curr_t, std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max()); } // Sweep-line to get detailed ST-boundary. for (size_t i = 0; i < st_bound->size(); ++i) { double t, s_lower, s_upper, lower_obs_v, upper_obs_v; std::tie(t, s_lower, s_upper) = st_bound->at(i); std::tie(t, lower_obs_v, upper_obs_v) = vt_bound->at(i); ADEBUG << "Processing st-boundary at t = " << t; // Get Boundary due to driving limits auto driving_limits_bound = st_driving_limits_.GetVehicleDynamicsLimits(t); s_lower = std::fmax(s_lower, driving_limits_bound.first); s_upper = std::fmin(s_upper, driving_limits_bound.second); ADEBUG << "Bounds for s due to driving limits are " << "s_upper = " << s_upper << ", s_lower = " << s_lower; // Get Boundary due to obstacles std::vector<std::pair<double, double>> available_s_bounds; std::vector<ObsDecSet> available_obs_decisions; if (!st_obstacles_processor_.GetSBoundsFromDecisions( t, &available_s_bounds, &available_obs_decisions)) { const std::string msg = "Failed to find a proper boundary due to obstacles."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } std::vector<std::pair<STBoundPoint, ObsDecSet>> available_choices; ADEBUG << "Available choices are:"; for (int j = 0; j < static_cast<int>(available_s_bounds.size()); ++j) { ADEBUG << " (" << available_s_bounds[j].first << ", " << available_s_bounds[j].second << ")"; available_choices.emplace_back( std::make_tuple(0.0, available_s_bounds[j].first, available_s_bounds[j].second), available_obs_decisions[j]); } RemoveInvalidDecisions(driving_limits_bound, &available_choices); // Always go for the most conservative option. if (!available_choices.empty()) { // Select the most conservative decision. auto top_choice_s_range = available_choices.front().first; auto top_choice_decision = available_choices.front().second; for (size_t j = 1; j < available_choices.size(); ++j) { if (std::get<1>(available_choices[j].first) < std::get<1>(top_choice_s_range)) { top_choice_s_range = available_choices[j].first; top_choice_decision = available_choices[j].second; } } // Set decision for obstacles without decisions. bool is_limited_by_upper_obs = false; bool is_limited_by_lower_obs = false; if (s_lower < std::get<1>(top_choice_s_range)) { s_lower = std::get<1>(top_choice_s_range); is_limited_by_lower_obs = true; } if (s_upper > std::get<2>(top_choice_s_range)) { s_upper = std::get<2>(top_choice_s_range); is_limited_by_upper_obs = true; } st_obstacles_processor_.SetObstacleDecision(top_choice_decision); // Update st-guide-line, st-driving-limit info, and v-limits. std::pair<double, double> limiting_speed_info; if (st_obstacles_processor_.GetLimitingSpeedInfo(t, &limiting_speed_info)) { st_driving_limits_.UpdateBlockingInfo( t, s_lower, limiting_speed_info.first, s_upper, limiting_speed_info.second); st_guide_line_.UpdateBlockingInfo(t, s_lower, true); st_guide_line_.UpdateBlockingInfo(t, s_upper, false); if (is_limited_by_lower_obs) { lower_obs_v = limiting_speed_info.first; } if (is_limited_by_upper_obs) { upper_obs_v = limiting_speed_info.second; } } } else { const std::string msg = "No valid st-boundary exists."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // Update into st_bound st_bound->at(i) = std::make_tuple(t, s_lower, s_upper); vt_bound->at(i) = std::make_tuple(t, lower_obs_v, upper_obs_v); } return Status::OK(); } Status STBoundsDecider::GenerateRegularSTBound( STBound* const st_bound, STBound* const vt_bound, std::vector<std::pair<double, double>>* const st_guide_line) { // Initialize st-boundary. for (double curr_t = 0.0; curr_t <= st_bounds_config_.total_time(); curr_t += kSTBoundsDeciderResolution) { st_bound->emplace_back(curr_t, std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max()); vt_bound->emplace_back(curr_t, std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max()); } // Sweep-line to get detailed ST-boundary. for (size_t i = 0; i < st_bound->size(); ++i) { double t, s_lower, s_upper, lower_obs_v, upper_obs_v; std::tie(t, s_lower, s_upper) = st_bound->at(i); std::tie(t, lower_obs_v, upper_obs_v) = vt_bound->at(i); ADEBUG << "Processing st-boundary at t = " << t; // Get Boundary due to driving limits auto driving_limits_bound = st_driving_limits_.GetVehicleDynamicsLimits(t); s_lower = std::fmax(s_lower, driving_limits_bound.first); s_upper = std::fmin(s_upper, driving_limits_bound.second); ADEBUG << "Bounds for s due to driving limits are " << "s_upper = " << s_upper << ", s_lower = " << s_lower; // Get Boundary due to obstacles std::vector<std::pair<double, double>> available_s_bounds; std::vector<ObsDecSet> available_obs_decisions; if (!st_obstacles_processor_.GetSBoundsFromDecisions( t, &available_s_bounds, &available_obs_decisions)) { const std::string msg = "Failed to find a proper boundary due to obstacles."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } std::vector<std::pair<STBoundPoint, ObsDecSet>> available_choices; ADEBUG << "Available choices are:"; for (int j = 0; j < static_cast<int>(available_s_bounds.size()); ++j) { ADEBUG << " (" << available_s_bounds[j].first << ", " << available_s_bounds[j].second << ")"; available_choices.emplace_back( std::make_tuple(0.0, available_s_bounds[j].first, available_s_bounds[j].second), available_obs_decisions[j]); } RemoveInvalidDecisions(driving_limits_bound, &available_choices); if (!available_choices.empty()) { ADEBUG << "One decision needs to be made among " << available_choices.size() << " choices."; double guide_line_s = st_guide_line_.GetGuideSFromT(t); st_guide_line->emplace_back(t, guide_line_s); RankDecisions(guide_line_s, driving_limits_bound, &available_choices); // Select the top decision. auto top_choice_s_range = available_choices.front().first; bool is_limited_by_upper_obs = false; bool is_limited_by_lower_obs = false; if (s_lower < std::get<1>(top_choice_s_range)) { s_lower = std::get<1>(top_choice_s_range); is_limited_by_lower_obs = true; } if (s_upper > std::get<2>(top_choice_s_range)) { s_upper = std::get<2>(top_choice_s_range); is_limited_by_upper_obs = true; } // Set decision for obstacles without decisions. auto top_choice_decision = available_choices.front().second; st_obstacles_processor_.SetObstacleDecision(top_choice_decision); // Update st-guide-line, st-driving-limit info, and v-limits. std::pair<double, double> limiting_speed_info; if (st_obstacles_processor_.GetLimitingSpeedInfo(t, &limiting_speed_info)) { st_driving_limits_.UpdateBlockingInfo( t, s_lower, limiting_speed_info.first, s_upper, limiting_speed_info.second); st_guide_line_.UpdateBlockingInfo(t, s_lower, true); st_guide_line_.UpdateBlockingInfo(t, s_upper, false); if (is_limited_by_lower_obs) { lower_obs_v = limiting_speed_info.first; } if (is_limited_by_upper_obs) { upper_obs_v = limiting_speed_info.second; } } } else { const std::string msg = "No valid st-boundary exists."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // Update into st_bound st_bound->at(i) = std::make_tuple(t, s_lower, s_upper); vt_bound->at(i) = std::make_tuple(t, lower_obs_v, upper_obs_v); } return Status::OK(); } void STBoundsDecider::RemoveInvalidDecisions( std::pair<double, double> driving_limit, std::vector<std::pair<STBoundPoint, ObsDecSet>>* available_choices) { // Remove those choices that don't even fall within driving-limits. size_t i = 0; while (i < available_choices->size()) { double s_lower = 0.0; double s_upper = 0.0; std::tie(std::ignore, s_lower, s_upper) = available_choices->at(i).first; if (s_lower > driving_limit.second || s_upper < driving_limit.first) { // Invalid bound, should be removed. if (i != available_choices->size() - 1) { swap(available_choices->at(i), available_choices->at(available_choices->size() - 1)); } available_choices->pop_back(); } else { // Valid bound, proceed to the next one. ++i; } } } void STBoundsDecider::RankDecisions( double s_guide_line, std::pair<double, double> driving_limit, std::vector<std::pair<STBoundPoint, ObsDecSet>>* available_choices) { // Perform sorting of the existing decisions. bool has_swaps = true; while (has_swaps) { has_swaps = false; for (int i = 0; i < static_cast<int>(available_choices->size()) - 1; ++i) { double A_s_lower = 0.0; double A_s_upper = 0.0; std::tie(std::ignore, A_s_lower, A_s_upper) = available_choices->at(i).first; double B_s_lower = 0.0; double B_s_upper = 0.0; std::tie(std::ignore, B_s_lower, B_s_upper) = available_choices->at(i + 1).first; ADEBUG << " Range ranking: A has s_upper = " << A_s_upper << ", s_lower = " << A_s_lower; ADEBUG << " Range ranking: B has s_upper = " << B_s_upper << ", s_lower = " << B_s_lower; // If not both are larger than passable-threshold, should select // the one with larger room. double A_room = std::fmin(driving_limit.second, A_s_upper) - std::fmax(driving_limit.first, A_s_lower); double B_room = std::fmin(driving_limit.second, B_s_upper) - std::fmax(driving_limit.first, B_s_lower); if (A_room < kSTPassableThreshold || B_room < kSTPassableThreshold) { if (A_room < B_room) { swap(available_choices->at(i + 1), available_choices->at(i)); has_swaps = true; ADEBUG << "Swapping to favor larger room."; } continue; } // Should select the one with overlap to guide-line bool A_contains_guideline = A_s_upper >= s_guide_line && A_s_lower <= s_guide_line; bool B_contains_guideline = B_s_upper >= s_guide_line && B_s_lower <= s_guide_line; if (A_contains_guideline != B_contains_guideline) { if (!A_contains_guideline) { swap(available_choices->at(i + 1), available_choices->at(i)); has_swaps = true; ADEBUG << "Swapping to favor overlapping with guide-line."; } continue; } } } } void STBoundsDecider::RecordSTGraphDebug( const std::vector<STBoundary>& st_graph_data, const STBound& st_bound, const std::vector<std::pair<double, double>>& st_guide_line, planning_internal::STGraphDebug* const st_graph_debug) { if (!FLAGS_enable_record_debug || !st_graph_debug) { ADEBUG << "Skip record debug info"; return; } // Plot ST-obstacle boundaries. for (const auto& boundary : st_graph_data) { auto boundary_debug = st_graph_debug->add_boundary(); boundary_debug->set_name(boundary.id()); if (boundary.boundary_type() == STBoundary::BoundaryType::YIELD) { boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_YIELD); ADEBUG << "Obstacle ID = " << boundary.id() << ", decision = YIELD"; } else if (boundary.boundary_type() == STBoundary::BoundaryType::OVERTAKE) { boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_OVERTAKE); ADEBUG << "Obstacle ID = " << boundary.id() << ", decision = OVERTAKE"; } else { boundary_debug->set_type(StGraphBoundaryDebug::ST_BOUNDARY_TYPE_UNKNOWN); ADEBUG << "Obstacle ID = " << boundary.id() << ", decision = UNKNOWN"; } for (const auto& point : boundary.points()) { auto point_debug = boundary_debug->add_point(); point_debug->set_t(point.x()); point_debug->set_s(point.y()); } } // Plot the chosen ST boundary. auto boundary_debug = st_graph_debug->add_boundary(); boundary_debug->set_name("Generated ST-Boundary"); boundary_debug->set_type( StGraphBoundaryDebug::ST_BOUNDARY_TYPE_DRIVABLE_REGION); for (const auto& st_bound_pt : st_bound) { auto point_debug = boundary_debug->add_point(); double t = 0.0; double s_lower = 0.0; std::tie(t, s_lower, std::ignore) = st_bound_pt; point_debug->set_t(t); point_debug->set_s(s_lower); ADEBUG << "(" << t << ", " << s_lower << ")"; } for (int i = static_cast<int>(st_bound.size()) - 1; i >= 0; --i) { auto point_debug = boundary_debug->add_point(); double t = 0.0; double s_upper = 0.0; std::tie(t, std::ignore, s_upper) = st_bound[i]; point_debug->set_t(t); point_debug->set_s(s_upper); ADEBUG << "(" << t << ", " << s_upper << ")"; } // Plot the used st_guide_line when generating the st_bounds for (const auto& st_points : st_guide_line) { auto* speed_point = st_graph_debug->add_speed_profile(); speed_point->set_t(st_points.first); speed_point->set_s(st_points.second); } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/st_bounds_decider/st_guide_line.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 <vector> #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/status/status.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/path/path_data.h" #include "modules/planning/common/path_decision.h" #include "modules/planning/common/speed/speed_data.h" #include "modules/planning/common/speed/st_boundary.h" #include "modules/planning/common/speed_limit.h" #include "modules/planning/common/trajectory/discretized_trajectory.h" #include "modules/planning/reference_line/reference_line.h" namespace apollo { namespace planning { // TODO(jiacheng): currently implemented a constant velocity model for // guide-line. Upgrade it to a constant acceleration model. class STGuideLine { public: STGuideLine() {} void Init(double desired_v); void Init(double desired_v, const std::vector<common::TrajectoryPoint> &speed_reference); virtual ~STGuideLine() = default; double GetGuideSFromT(double t); void UpdateBlockingInfo(const double t, const double s_block, const bool is_lower_block); private: // Variables for simple guide-line calculation. double t0_; double s0_; double v0_; // St guideline from upstream modules SpeedData guideline_speed_data_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/st_bounds_decider/st_bounds_decider.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "modules/planning/common/frame.h" #include "modules/planning/common/st_graph_data.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/proto/task_config.pb.h" #include "modules/planning/tasks/deciders/decider.h" #include "modules/planning/tasks/deciders/st_bounds_decider/st_driving_limits.h" #include "modules/planning/tasks/deciders/st_bounds_decider/st_guide_line.h" #include "modules/planning/tasks/deciders/st_bounds_decider/st_obstacles_processor.h" namespace apollo { namespace planning { constexpr double kSTBoundsDeciderResolution = 0.1; constexpr double kSTPassableThreshold = 3.0; class STBoundsDecider : public Decider { public: STBoundsDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); private: common::Status Process(Frame* const frame, ReferenceLineInfo* const reference_line_info) override; void InitSTBoundsDecider(const Frame& frame, ReferenceLineInfo* const reference_line_info); common::Status GenerateFallbackSTBound( std::vector<std::tuple<double, double, double>>* const st_bound, std::vector<std::tuple<double, double, double>>* const vt_bound); common::Status GenerateRegularSTBound( std::vector<std::tuple<double, double, double>>* const st_bound, std::vector<std::tuple<double, double, double>>* const vt_bound, std::vector<std::pair<double, double>>* const st_guide_line); void RemoveInvalidDecisions( std::pair<double, double> driving_limit, std::vector< std::pair<std::tuple<double, double, double>, std::vector<std::pair<std::string, ObjectDecisionType>>>>* available_choices); void RankDecisions( double s_guide_line, std::pair<double, double> driving_limit, std::vector< std::pair<std::tuple<double, double, double>, std::vector<std::pair<std::string, ObjectDecisionType>>>>* available_choices); bool BackwardFlatten( std::vector<std::tuple<double, double, double>>* const st_bound); void RecordSTGraphDebug( const std::vector<STBoundary>& st_graph_data, const std::vector<std::tuple<double, double, double>>& st_bound, const std::vector<std::pair<double, double>>& st_guide_line, planning_internal::STGraphDebug* const st_graph_debug); private: STBoundsDeciderConfig st_bounds_config_; STGuideLine st_guide_line_; STDrivingLimits st_driving_limits_; STObstaclesProcessor st_obstacles_processor_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/st_bounds_decider/st_driving_limits.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 <tuple> #include <utility> #include <vector> #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/status/status.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/path/path_data.h" #include "modules/planning/common/path_decision.h" #include "modules/planning/common/speed/st_boundary.h" #include "modules/planning/common/speed_limit.h" #include "modules/planning/reference_line/reference_line.h" namespace apollo { namespace planning { class STDrivingLimits { public: STDrivingLimits() {} void Init(const double max_acc, const double max_dec, const double max_v, double curr_v); virtual ~STDrivingLimits() = default; /** @brief Given time t, calculate the driving limits in s due to * vehicle's dynamics. * @param Timestamp t. * @return The lower and upper bounds. */ std::pair<double, double> GetVehicleDynamicsLimits(const double t) const; /** @brief Update the anchoring of the vehicle dynamics limits. * For example, when ADC is blocked by some obstacle, its max. * drivable area, max. speed, etc. are also limited subsequently. * @param Time t * @param lower bound in s * @param lower bound's corresponding speed. * @param upper bound in s * @param upper bound's corresponding speed. */ void UpdateBlockingInfo(const double t, const double lower_s, const double lower_v, const double upper_s, const double upper_v); private: // Private variables for calculating vehicle dynamic limits: double max_acc_; double max_dec_; double max_v_; double upper_t0_; double upper_v0_; double upper_s0_; double lower_t0_; double lower_v0_; double lower_s0_; // The limits expressed as v vs. s, which contains the following parts: // 1. speed limits at path segments with big curvatures. std::vector<std::tuple<double, double, double>> curvature_speed_limits_s_v_; // 2. speed limits from traffic limits (speed bumps, etc.). std::vector<std::tuple<double, double, double>> traffic_speed_limits_s_v_; // 3. speed limits for safety considerations when other obstacles are nearby std::vector<std::tuple<double, double, double>> obstacles_speed_limits_s_v_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/st_bounds_decider/st_driving_limits.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/st_bounds_decider/st_driving_limits.h" namespace apollo { namespace planning { void STDrivingLimits::Init(const double max_acc, const double max_dec, const double max_v, double curr_v) { max_acc_ = max_acc; max_dec_ = max_dec; max_v_ = max_v; upper_t0_ = 0.0; upper_v0_ = curr_v; upper_s0_ = 0.0; lower_t0_ = 0.0; lower_v0_ = curr_v; lower_s0_ = 0.0; } std::pair<double, double> STDrivingLimits::GetVehicleDynamicsLimits( const double t) const { std::pair<double, double> dynamic_limits; // Process lower bound: (constant deceleration) double dec_time = lower_v0_ / max_dec_; if (t - lower_t0_ < dec_time) { dynamic_limits.first = lower_s0_ + (lower_v0_ - max_dec_ * (t - lower_t0_) + lower_v0_) * (t - lower_t0_) * 0.5; } else { dynamic_limits.first = lower_s0_ + (lower_v0_ * dec_time) * 0.5; } // Process upper bound: (constant acceleration) double acc_time = (max_v_ - upper_v0_) / max_acc_; if (t - upper_t0_ < acc_time) { dynamic_limits.second = upper_s0_ + (upper_v0_ + max_acc_ * (t - upper_t0_) + upper_v0_) * (t - upper_t0_) * 0.5; } else { dynamic_limits.second = upper_s0_ + (upper_v0_ + max_v_) * acc_time * 0.5 + (t - upper_t0_ - acc_time) * max_v_; } return dynamic_limits; } void STDrivingLimits::UpdateBlockingInfo(const double t, const double lower_s, const double lower_v, const double upper_s, const double upper_v) { auto curr_bounds = GetVehicleDynamicsLimits(t); if (curr_bounds.first < lower_s) { // lower_v0_ = std::fmax(lower_v, 0.0); lower_v0_ = std::fmax(0.0, lower_v0_ - max_dec_ * (t - lower_t0_)); lower_t0_ = t; lower_s0_ = lower_s; } if (curr_bounds.second > upper_s) { // upper_v0_ = std::fmax(upper_v, 0.0); upper_v0_ = std::fmin(max_v_, upper_v0_ + max_acc_ * (t - upper_t0_)); upper_t0_ = t; upper_s0_ = upper_s; } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/st_bounds_decider/st_obstacles_processor.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/st_bounds_decider/st_obstacles_processor.h" #include <algorithm> #include <unordered_set> #include "cyber/common/log.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/line_segment2d.h" #include "modules/common/math/vec2d.h" #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/common_msgs/planning_msgs/decision.pb.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::PathPoint; using apollo::common::Status; using apollo::common::math::Box2d; using apollo::common::math::LineSegment2d; using apollo::common::math::Vec2d; namespace { // ObsTEdge contains: (is_starting_t, t, s_min, s_max, obs_id). using ObsTEdge = std::tuple<int, double, double, double, std::string>; } // namespace void STObstaclesProcessor::Init(const double planning_distance, const double planning_time, const PathData& path_data, PathDecision* const path_decision, History* const history) { planning_time_ = planning_time; planning_distance_ = planning_distance; path_data_ = path_data; vehicle_param_ = common::VehicleConfigHelper::GetConfig().vehicle_param(); adc_path_init_s_ = path_data_.discretized_path().front().s(); path_decision_ = path_decision; history_ = history; obs_t_edges_.clear(); obs_t_edges_idx_ = 0; obs_id_to_st_boundary_.clear(); obs_id_to_decision_.clear(); candidate_clear_zones_.clear(); obs_id_to_alternative_st_boundary_.clear(); } Status STObstaclesProcessor::MapObstaclesToSTBoundaries( PathDecision* const path_decision) { // Sanity checks. if (path_decision == nullptr) { const std::string msg = "path_decision is nullptr"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (planning_time_ < 0.0) { const std::string msg = "Negative planning time."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (planning_distance_ < 0.0) { const std::string msg = "Negative planning distance."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (path_data_.discretized_path().size() <= 1) { const std::string msg = "Number of path points is too few."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } obs_id_to_st_boundary_.clear(); // Some preprocessing to save the adc_low_road_right segments. bool is_adc_low_road_right_beginning = true; for (const auto& path_pt_info : path_data_.path_point_decision_guide()) { double path_pt_s = 0.0; PathData::PathPointType path_pt_type; std::tie(path_pt_s, path_pt_type, std::ignore) = path_pt_info; if (path_pt_type == PathData::PathPointType::OUT_ON_FORWARD_LANE || path_pt_type == PathData::PathPointType::OUT_ON_REVERSE_LANE) { if (is_adc_low_road_right_beginning) { adc_low_road_right_segments_.emplace_back(path_pt_s, path_pt_s); is_adc_low_road_right_beginning = false; } else { adc_low_road_right_segments_.back().second = path_pt_s; } } else if (path_pt_type == PathData::PathPointType::IN_LANE) { if (!is_adc_low_road_right_beginning) { is_adc_low_road_right_beginning = true; } } } // Map obstacles into ST-graph. // Go through every obstacle and plot them in ST-graph. std::unordered_set<std::string> non_ignore_obstacles; std::tuple<std::string, STBoundary, Obstacle*> closest_stop_obstacle; std::get<0>(closest_stop_obstacle) = "NULL"; for (const auto* obs_item_ptr : path_decision->obstacles().Items()) { // Sanity checks. Obstacle* obs_ptr = path_decision->Find(obs_item_ptr->Id()); if (obs_ptr == nullptr) { const std::string msg = "Null obstacle pointer."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } // Draw the obstacle's st-boundary. std::vector<STPoint> lower_points; std::vector<STPoint> upper_points; bool is_caution_obstacle = false; double obs_caution_end_t = 0.0; if (!ComputeObstacleSTBoundary(*obs_ptr, &lower_points, &upper_points, &is_caution_obstacle, &obs_caution_end_t)) { // Obstacle doesn't appear on ST-Graph. continue; } auto boundary = STBoundary::CreateInstanceAccurate(lower_points, upper_points); boundary.set_id(obs_ptr->Id()); if (is_caution_obstacle) { boundary.set_obstacle_road_right_ending_t(obs_caution_end_t); } // Update the trimmed obstacle into alternative st-bound storage // for later uses. while (lower_points.size() > 2 && lower_points.back().t() > obs_caution_end_t) { lower_points.pop_back(); } while (upper_points.size() > 2 && upper_points.back().t() > obs_caution_end_t) { upper_points.pop_back(); } auto alternative_boundary = STBoundary::CreateInstanceAccurate(lower_points, upper_points); alternative_boundary.set_id(obs_ptr->Id()); obs_id_to_alternative_st_boundary_[obs_ptr->Id()] = alternative_boundary; ADEBUG << "Obstacle " << obs_ptr->Id() << " has an alternative st-boundary with " << lower_points.size() + upper_points.size() << " points."; // Store all Keep-Clear zone together. if (obs_item_ptr->Id().find("KC") != std::string::npos) { candidate_clear_zones_.push_back( make_tuple(obs_ptr->Id(), boundary, obs_ptr)); continue; } // Process all other obstacles than Keep-Clear zone. if (obs_ptr->Trajectory().trajectory_point().empty()) { // Obstacle is static. if (std::get<0>(closest_stop_obstacle) == "NULL" || std::get<1>(closest_stop_obstacle).bottom_left_point().s() > boundary.bottom_left_point().s()) { // If this static obstacle is closer for ADC to stop, record it. closest_stop_obstacle = std::make_tuple(obs_ptr->Id(), boundary, obs_ptr); } } else { // Obstacle is dynamic. if (boundary.bottom_left_point().s() - adc_path_init_s_ < kSIgnoreThreshold && boundary.bottom_left_point().t() > kTIgnoreThreshold) { // Ignore obstacles that are behind. // TODO(jiacheng): don't ignore if ADC is in dangerous segments. continue; } obs_id_to_st_boundary_[obs_ptr->Id()] = boundary; obs_ptr->set_path_st_boundary(boundary); non_ignore_obstacles.insert(obs_ptr->Id()); ADEBUG << "Adding " << obs_ptr->Id() << " into the ST-graph."; } } // For static obstacles, only retain the closest one (also considers // Keep-Clear zone here). // Note: We only need to check the overlapping between the closest obstacle // and all the Keep-Clear zones. Because if there is another obstacle // overlapping with a Keep-Clear zone, which results in an even closer // stop fence, then that very Keep-Clear zone must also overlap with // the closest obstacle. (Proof omitted here) if (std::get<0>(closest_stop_obstacle) != "NULL") { std::string closest_stop_obs_id; STBoundary closest_stop_obs_boundary; Obstacle* closest_stop_obs_ptr; std::tie(closest_stop_obs_id, closest_stop_obs_boundary, closest_stop_obs_ptr) = closest_stop_obstacle; ADEBUG << "Closest obstacle ID = " << closest_stop_obs_id; // Go through all Keep-Clear zones, and see if there is an even closer // stop fence due to them. if (!closest_stop_obs_ptr->IsVirtual()) { for (const auto& clear_zone : candidate_clear_zones_) { const auto& clear_zone_boundary = std::get<1>(clear_zone); if (closest_stop_obs_boundary.min_s() >= clear_zone_boundary.min_s() && closest_stop_obs_boundary.min_s() <= clear_zone_boundary.max_s()) { std::tie(closest_stop_obs_id, closest_stop_obs_boundary, closest_stop_obs_ptr) = clear_zone; ADEBUG << "Clear zone " << closest_stop_obs_id << " is closer."; break; } } } obs_id_to_st_boundary_[closest_stop_obs_id] = closest_stop_obs_boundary; closest_stop_obs_ptr->set_path_st_boundary(closest_stop_obs_boundary); non_ignore_obstacles.insert(closest_stop_obs_id); ADEBUG << "Adding " << closest_stop_obs_ptr->Id() << " into the ST-graph."; ADEBUG << "min_s = " << closest_stop_obs_boundary.min_s(); } // Set IGNORE decision for those that are not in ST-graph: for (const auto* obs_item_ptr : path_decision->obstacles().Items()) { Obstacle* obs_ptr = path_decision->Find(obs_item_ptr->Id()); if (non_ignore_obstacles.count(obs_ptr->Id()) == 0) { ObjectDecisionType ignore_decision; ignore_decision.mutable_ignore(); if (!obs_ptr->HasLongitudinalDecision()) { obs_ptr->AddLongitudinalDecision("st_obstacle_processor", ignore_decision); } if (!obs_ptr->HasLateralDecision()) { obs_ptr->AddLateralDecision("st_obstacle_processor", ignore_decision); } } } // Preprocess the obstacles for sweep-line algorithms. // Fetch every obstacle's beginning end ending t-edges only. for (const auto& it : obs_id_to_st_boundary_) { obs_t_edges_.emplace_back(true, it.second.min_t(), it.second.bottom_left_point().s(), it.second.upper_left_point().s(), it.first); obs_t_edges_.emplace_back(false, it.second.max_t(), it.second.bottom_right_point().s(), it.second.upper_right_point().s(), it.first); } // Sort the edges. std::sort(obs_t_edges_.begin(), obs_t_edges_.end(), [](const ObsTEdge& lhs, const ObsTEdge& rhs) { if (std::get<1>(lhs) != std::get<1>(rhs)) { return std::get<1>(lhs) < std::get<1>(rhs); } else { return std::get<0>(lhs) > std::get<0>(rhs); } }); return Status::OK(); } std::unordered_map<std::string, STBoundary> STObstaclesProcessor::GetAllSTBoundaries() { return obs_id_to_st_boundary_; } bool STObstaclesProcessor::GetLimitingSpeedInfo( double t, std::pair<double, double>* const limiting_speed_info) { if (obs_id_to_decision_.empty()) { // If no obstacle, then no speed limits. return false; } double s_min = 0.0; double s_max = planning_distance_; for (auto it : obs_id_to_decision_) { auto obs_id = it.first; auto obs_decision = it.second; auto obs_st_boundary = obs_id_to_st_boundary_[obs_id]; double obs_s_min = 0.0; double obs_s_max = 0.0; obs_st_boundary.GetBoundarySRange(t, &obs_s_max, &obs_s_min); double obs_ds_lower = 0.0; double obs_ds_upper = 0.0; obs_st_boundary.GetBoundarySlopes(t, &obs_ds_upper, &obs_ds_lower); if (obs_decision.has_yield() || obs_decision.has_stop()) { if (obs_s_min <= s_max) { s_max = obs_s_min; limiting_speed_info->second = obs_ds_lower; } } else if (it.second.has_overtake()) { if (obs_s_max >= s_min) { s_min = obs_s_max; limiting_speed_info->first = obs_ds_upper; } } } return s_min <= s_max; } bool STObstaclesProcessor::GetSBoundsFromDecisions( double t, std::vector<std::pair<double, double>>* const available_s_bounds, std::vector<std::vector<std::pair<std::string, ObjectDecisionType>>>* const available_obs_decisions) { // Sanity checks. available_s_bounds->clear(); available_obs_decisions->clear(); // Gather any possible change in st-boundary situations. ADEBUG << "There are " << obs_t_edges_.size() << " t-edges."; std::vector<ObsTEdge> new_t_edges; while (obs_t_edges_idx_ < static_cast<int>(obs_t_edges_.size()) && std::get<1>(obs_t_edges_[obs_t_edges_idx_]) <= t) { if (std::get<0>(obs_t_edges_[obs_t_edges_idx_]) == 0 && std::get<1>(obs_t_edges_[obs_t_edges_idx_]) == t) { break; } ADEBUG << "Seeing a new t-edge at t = " << std::get<1>(obs_t_edges_[obs_t_edges_idx_]); new_t_edges.push_back(obs_t_edges_[obs_t_edges_idx_]); ++obs_t_edges_idx_; } // For st-boundaries that disappeared before t, remove them. for (const auto& obs_t_edge : new_t_edges) { if (std::get<0>(obs_t_edge) == 0) { ADEBUG << "Obstacle id: " << std::get<4>(obs_t_edge) << " is leaving st-graph."; if (obs_id_to_decision_.count(std::get<4>(obs_t_edge)) != 0) { obs_id_to_decision_.erase(std::get<4>(obs_t_edge)); } } } // For overtaken obstacles, remove them if we are after // their high right-of-road ending time (with a margin). std::vector<std::string> obs_id_to_remove; for (const auto& obs_id_to_decision_pair : obs_id_to_decision_) { auto obs_id = obs_id_to_decision_pair.first; auto obs_decision = obs_id_to_decision_pair.second; auto obs_st_boundary = obs_id_to_st_boundary_[obs_id]; if (obs_decision.has_overtake() && obs_st_boundary.min_t() <= t - kOvertakenObsCautionTime && obs_st_boundary.obstacle_road_right_ending_t() <= t - kOvertakenObsCautionTime) { obs_id_to_remove.push_back(obs_id_to_decision_pair.first); } } for (const auto& obs_id : obs_id_to_remove) { obs_id_to_decision_.erase(obs_id); // Change the displayed st-boundary to the alternative one: if (obs_id_to_alternative_st_boundary_.count(obs_id) > 0) { Obstacle* obs_ptr = path_decision_->Find(obs_id); obs_id_to_st_boundary_[obs_id] = obs_id_to_alternative_st_boundary_[obs_id]; obs_id_to_st_boundary_[obs_id].SetBoundaryType( STBoundary::BoundaryType::OVERTAKE); obs_ptr->set_path_st_boundary(obs_id_to_alternative_st_boundary_[obs_id]); } } // Based on existing decisions, get the s-boundary. double s_min = 0.0; double s_max = planning_distance_; for (auto it : obs_id_to_decision_) { auto obs_id = it.first; auto obs_decision = it.second; auto obs_st_boundary = obs_id_to_st_boundary_[obs_id]; double obs_s_min = 0.0; double obs_s_max = 0.0; obs_st_boundary.GetBoundarySRange(t, &obs_s_max, &obs_s_min); if (obs_decision.has_yield() || obs_decision.has_stop()) { s_max = std::fmin(s_max, obs_s_min); } else if (it.second.has_overtake()) { s_min = std::fmax(s_min, obs_s_max); } } if (s_min > s_max) { return false; } ADEBUG << "S-boundary based on existing decisions = (" << s_min << ", " << s_max << ")"; // For newly entering st_boundaries, determine possible new-boundaries. // For apparent ones, make decisions directly. std::vector<ObsTEdge> ambiguous_t_edges; for (auto obs_t_edge : new_t_edges) { ADEBUG << "For obstacle id: " << std::get<4>(obs_t_edge) << ", its s-range = [" << std::get<2>(obs_t_edge) << ", " << std::get<3>(obs_t_edge) << "]"; if (std::get<0>(obs_t_edge) == 1) { if (std::get<2>(obs_t_edge) >= s_max) { ADEBUG << " Apparently, it should be yielded."; obs_id_to_decision_[std::get<4>(obs_t_edge)] = DetermineObstacleDecision(std::get<2>(obs_t_edge), std::get<3>(obs_t_edge), s_max); obs_id_to_st_boundary_[std::get<4>(obs_t_edge)].SetBoundaryType( STBoundary::BoundaryType::YIELD); } else if (std::get<3>(obs_t_edge) <= s_min) { ADEBUG << " Apparently, it should be overtaken."; obs_id_to_decision_[std::get<4>(obs_t_edge)] = DetermineObstacleDecision(std::get<2>(obs_t_edge), std::get<3>(obs_t_edge), s_min); obs_id_to_st_boundary_[std::get<4>(obs_t_edge)].SetBoundaryType( STBoundary::BoundaryType::OVERTAKE); } else { ADEBUG << " It should be further analyzed."; ambiguous_t_edges.push_back(obs_t_edge); } } } // For ambiguous ones, enumerate all decisions and corresponding bounds. auto s_gaps = FindSGaps(ambiguous_t_edges, s_min, s_max); if (s_gaps.empty()) { return false; } for (auto s_gap : s_gaps) { available_s_bounds->push_back(s_gap); std::vector<std::pair<std::string, ObjectDecisionType>> obs_decisions; for (auto obs_t_edge : ambiguous_t_edges) { std::string obs_id = std::get<4>(obs_t_edge); double obs_s_min = std::get<2>(obs_t_edge); double obs_s_max = std::get<3>(obs_t_edge); obs_decisions.emplace_back( obs_id, DetermineObstacleDecision(obs_s_min, obs_s_max, (s_gap.first + s_gap.second) / 2.0)); } available_obs_decisions->push_back(obs_decisions); } return true; } void STObstaclesProcessor::SetObstacleDecision( const std::string& obs_id, const ObjectDecisionType& obs_decision) { obs_id_to_decision_[obs_id] = obs_decision; ObjectStatus object_status; object_status.mutable_motion_type()->mutable_dynamic(); if (obs_decision.has_yield() || obs_decision.has_stop()) { obs_id_to_st_boundary_[obs_id].SetBoundaryType( STBoundary::BoundaryType::YIELD); object_status.mutable_decision_type()->mutable_yield(); } else if (obs_decision.has_overtake()) { obs_id_to_st_boundary_[obs_id].SetBoundaryType( STBoundary::BoundaryType::OVERTAKE); object_status.mutable_decision_type()->mutable_overtake(); } history_->mutable_history_status()->SetObjectStatus(obs_id, object_status); } void STObstaclesProcessor::SetObstacleDecision( const std::vector<std::pair<std::string, ObjectDecisionType>>& obstacle_decisions) { for (auto obs_decision : obstacle_decisions) { SetObstacleDecision(obs_decision.first, obs_decision.second); } } /////////////////////////////////////////////////////////////////////////////// // Private helper functions. bool STObstaclesProcessor::ComputeObstacleSTBoundary( const Obstacle& obstacle, std::vector<STPoint>* const lower_points, std::vector<STPoint>* const upper_points, bool* const is_caution_obstacle, double* const obs_caution_end_t) { lower_points->clear(); upper_points->clear(); *is_caution_obstacle = false; const auto& adc_path_points = path_data_.discretized_path(); const auto& obs_trajectory = obstacle.Trajectory(); if (obs_trajectory.trajectory_point().empty()) { // Processing a static obstacle. // Sanity checks. if (!obstacle.IsStatic()) { AWARN << "Non-static obstacle[" << obstacle.Id() << "] has NO prediction trajectory." << obstacle.Perception().ShortDebugString(); } // Get the overlapping s between ADC path and obstacle's perception box. const Box2d& obs_box = obstacle.PerceptionBoundingBox(); std::pair<double, double> overlapping_s; if (GetOverlappingS(adc_path_points, obs_box, kADCSafetyLBuffer, &overlapping_s)) { lower_points->emplace_back(overlapping_s.first, 0.0); lower_points->emplace_back(overlapping_s.first, planning_time_); upper_points->emplace_back(overlapping_s.second, 0.0); upper_points->emplace_back(overlapping_s.second, planning_time_); } *is_caution_obstacle = true; *obs_caution_end_t = planning_time_; } else { // Processing a dynamic obstacle. // Go through every occurrence of the obstacle at all timesteps, and // figure out the overlapping s-max and s-min one by one. bool is_obs_first_traj_pt = true; for (const auto& obs_traj_pt : obs_trajectory.trajectory_point()) { // TODO(jiacheng): Currently, if the obstacle overlaps with ADC at // disjoint segments (happens very rarely), we merge them into one. // In the future, this could be considered in greater details rather // than being approximated. const Box2d& obs_box = obstacle.GetBoundingBox(obs_traj_pt); ADEBUG << obs_box.DebugString(); std::pair<double, double> overlapping_s; if (GetOverlappingS(adc_path_points, obs_box, kADCSafetyLBuffer, &overlapping_s)) { ADEBUG << "Obstacle instance is overlapping with ADC path."; lower_points->emplace_back(overlapping_s.first, obs_traj_pt.relative_time()); upper_points->emplace_back(overlapping_s.second, obs_traj_pt.relative_time()); if (is_obs_first_traj_pt) { if (IsSWithinADCLowRoadRightSegment(overlapping_s.first) || IsSWithinADCLowRoadRightSegment(overlapping_s.second)) { *is_caution_obstacle = true; } } if ((*is_caution_obstacle)) { if (IsSWithinADCLowRoadRightSegment(overlapping_s.first) || IsSWithinADCLowRoadRightSegment(overlapping_s.second)) { *obs_caution_end_t = obs_traj_pt.relative_time(); } } } is_obs_first_traj_pt = false; } if (lower_points->size() == 1) { lower_points->emplace_back(lower_points->front().s(), lower_points->front().t() + 0.1); upper_points->emplace_back(upper_points->front().s(), upper_points->front().t() + 0.1); } } return (!lower_points->empty() && !upper_points->empty()); } bool STObstaclesProcessor::GetOverlappingS( const std::vector<PathPoint>& adc_path_points, const Box2d& obstacle_instance, const double adc_l_buffer, std::pair<double, double>* const overlapping_s) { // Locate the possible range to search in details. int pt_before_idx = GetSBoundingPathPointIndex( adc_path_points, obstacle_instance, vehicle_param_.front_edge_to_center(), true, 0, static_cast<int>(adc_path_points.size()) - 2); ADEBUG << "The index before is " << pt_before_idx; int pt_after_idx = GetSBoundingPathPointIndex( adc_path_points, obstacle_instance, vehicle_param_.back_edge_to_center(), false, 0, static_cast<int>(adc_path_points.size()) - 2); ADEBUG << "The index after is " << pt_after_idx; if (pt_before_idx == static_cast<int>(adc_path_points.size()) - 2) { return false; } if (pt_after_idx == 0) { return false; } if (pt_before_idx == -1) { pt_before_idx = 0; } if (pt_after_idx == -1) { pt_after_idx = static_cast<int>(adc_path_points.size()) - 2; } if (pt_before_idx >= pt_after_idx) { return false; } // Detailed searching. bool has_overlapping = false; for (int i = pt_before_idx; i <= pt_after_idx; ++i) { ADEBUG << "At ADC path index = " << i << " :"; if (IsADCOverlappingWithObstacle(adc_path_points[i], obstacle_instance, adc_l_buffer)) { overlapping_s->first = adc_path_points[std::max(i - 1, 0)].s(); has_overlapping = true; ADEBUG << "There is overlapping."; break; } } if (!has_overlapping) { return false; } for (int i = pt_after_idx; i >= pt_before_idx; --i) { ADEBUG << "At ADC path index = " << i << " :"; if (IsADCOverlappingWithObstacle(adc_path_points[i], obstacle_instance, adc_l_buffer)) { overlapping_s->second = adc_path_points[i + 1].s(); ADEBUG << "There is overlapping."; break; } } return true; } int STObstaclesProcessor::GetSBoundingPathPointIndex( const std::vector<PathPoint>& adc_path_points, const Box2d& obstacle_instance, const double s_thresh, const bool is_before, const int start_idx, const int end_idx) { if (start_idx == end_idx) { if (IsPathPointAwayFromObstacle(adc_path_points[start_idx], adc_path_points[start_idx + 1], obstacle_instance, s_thresh, is_before)) { return start_idx; } else { return -1; } } if (is_before) { int mid_idx = (start_idx + end_idx - 1) / 2 + 1; if (IsPathPointAwayFromObstacle(adc_path_points[mid_idx], adc_path_points[mid_idx + 1], obstacle_instance, s_thresh, is_before)) { return GetSBoundingPathPointIndex(adc_path_points, obstacle_instance, s_thresh, is_before, mid_idx, end_idx); } else { return GetSBoundingPathPointIndex(adc_path_points, obstacle_instance, s_thresh, is_before, start_idx, mid_idx - 1); } } else { int mid_idx = (start_idx + end_idx) / 2; if (IsPathPointAwayFromObstacle(adc_path_points[mid_idx], adc_path_points[mid_idx + 1], obstacle_instance, s_thresh, is_before)) { return GetSBoundingPathPointIndex(adc_path_points, obstacle_instance, s_thresh, is_before, start_idx, mid_idx); } else { return GetSBoundingPathPointIndex(adc_path_points, obstacle_instance, s_thresh, is_before, mid_idx + 1, end_idx); } } } bool STObstaclesProcessor::IsPathPointAwayFromObstacle( const PathPoint& path_point, const PathPoint& direction_point, const Box2d& obs_box, const double s_thresh, const bool is_before) { Vec2d path_pt(path_point.x(), path_point.y()); Vec2d dir_pt(direction_point.x(), direction_point.y()); LineSegment2d path_dir_lineseg(path_pt, dir_pt); LineSegment2d normal_line_seg(path_pt, path_dir_lineseg.rotate(M_PI_2)); auto corner_points = obs_box.GetAllCorners(); for (const auto& corner_pt : corner_points) { Vec2d normal_line_ft_pt; normal_line_seg.GetPerpendicularFoot(corner_pt, &normal_line_ft_pt); Vec2d path_dir_unit_vec = path_dir_lineseg.unit_direction(); Vec2d perpendicular_vec = corner_pt - normal_line_ft_pt; double corner_pt_s_dist = path_dir_unit_vec.InnerProd(perpendicular_vec); if (is_before && corner_pt_s_dist < s_thresh) { return false; } if (!is_before && corner_pt_s_dist > -s_thresh) { return false; } } return true; } bool STObstaclesProcessor::IsADCOverlappingWithObstacle( const PathPoint& adc_path_point, const Box2d& obs_box, const double l_buffer) const { // Convert reference point from center of rear axis to center of ADC. Vec2d ego_center_map_frame((vehicle_param_.front_edge_to_center() - vehicle_param_.back_edge_to_center()) * 0.5, (vehicle_param_.left_edge_to_center() - vehicle_param_.right_edge_to_center()) * 0.5); ego_center_map_frame.SelfRotate(adc_path_point.theta()); ego_center_map_frame.set_x(ego_center_map_frame.x() + adc_path_point.x()); ego_center_map_frame.set_y(ego_center_map_frame.y() + adc_path_point.y()); // Compute the ADC bounding box. Box2d adc_box(ego_center_map_frame, adc_path_point.theta(), vehicle_param_.length(), vehicle_param_.width() + l_buffer * 2); ADEBUG << " ADC box is: " << adc_box.DebugString(); ADEBUG << " Obs box is: " << obs_box.DebugString(); // Check whether ADC bounding box overlaps with obstacle bounding box. return obs_box.HasOverlap(adc_box); } std::vector<std::pair<double, double>> STObstaclesProcessor::FindSGaps( const std::vector<ObsTEdge>& obstacle_t_edges, double s_min, double s_max) { std::vector<std::pair<double, int>> obs_s_edges; for (auto obs_t_edge : obstacle_t_edges) { obs_s_edges.emplace_back(std::get<2>(obs_t_edge), 1); obs_s_edges.emplace_back(std::get<3>(obs_t_edge), 0); } // obs_s_edges.emplace_back(std::numeric_limits<double>::lowest(), 1); obs_s_edges.emplace_back(s_min, 0); obs_s_edges.emplace_back(s_max, 1); // obs_s_edges.emplace_back(std::numeric_limits<double>::max(), 0); std::sort( obs_s_edges.begin(), obs_s_edges.end(), [](const std::pair<double, int>& lhs, const std::pair<double, int>& rhs) { if (lhs.first != rhs.first) { return lhs.first < rhs.first; } else { return lhs.second > rhs.second; } }); std::vector<std::pair<double, double>> s_gaps; int num_st_obs = 1; double prev_open_s = 0.0; for (auto obs_s_edge : obs_s_edges) { if (obs_s_edge.second == 1) { num_st_obs++; if (num_st_obs == 1) { s_gaps.emplace_back(prev_open_s, obs_s_edge.first); } } else { num_st_obs--; if (num_st_obs == 0) { prev_open_s = obs_s_edge.first; } } } return s_gaps; } ObjectDecisionType STObstaclesProcessor::DetermineObstacleDecision( const double obs_s_min, const double obs_s_max, const double s) const { ObjectDecisionType decision; if (s <= obs_s_min) { decision.mutable_yield()->set_distance_s(0.0); } else if (s >= obs_s_max) { decision.mutable_overtake()->set_distance_s(0.0); } return decision; } bool STObstaclesProcessor::IsSWithinADCLowRoadRightSegment( const double s) const { for (const auto& seg : adc_low_road_right_segments_) { if (s >= seg.first && s <= seg.second) { return true; } } return false; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/st_bounds_decider/st_guide_line.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/st_bounds_decider/st_guide_line.h" namespace apollo { namespace planning { constexpr double kSpeedGuideLineResolution = 0.1; void STGuideLine::Init(double desired_v) { s0_ = 0.0; t0_ = 0.0; v0_ = desired_v; } void STGuideLine::Init( double desired_v, const std::vector<common::TrajectoryPoint> &speed_reference) { s0_ = 0.0; t0_ = 0.0; v0_ = desired_v; DiscretizedTrajectory discrete_speed_reference(speed_reference); double total_time = discrete_speed_reference.GetTemporalLength(); guideline_speed_data_.clear(); for (double t = 0; t <= total_time; t += kSpeedGuideLineResolution) { const common::TrajectoryPoint trajectory_point = discrete_speed_reference.Evaluate(t); guideline_speed_data_.AppendSpeedPoint( trajectory_point.path_point().s(), trajectory_point.relative_time(), trajectory_point.v(), trajectory_point.a(), trajectory_point.da()); } } double STGuideLine::GetGuideSFromT(double t) { common::SpeedPoint speed_point; if (t < guideline_speed_data_.TotalTime() && guideline_speed_data_.EvaluateByTime(t, &speed_point)) { s0_ = speed_point.s(); t0_ = t; return speed_point.s(); } return s0_ + (t - t0_) * v0_; } void STGuideLine::UpdateBlockingInfo(const double t, const double s_block, const bool is_lower_block) { if (is_lower_block) { if (GetGuideSFromT(t) < s_block) { s0_ = s_block; t0_ = t; } } else { if (GetGuideSFromT(t) > s_block) { s0_ = s_block; t0_ = t; } } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/st_bounds_decider/st_obstacles_processor.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 <tuple> #include <unordered_map> #include <utility> #include <vector> #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/status/status.h" #include "modules/planning/common/history.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/path/path_data.h" #include "modules/planning/common/path_decision.h" #include "modules/planning/common/speed/st_boundary.h" #include "modules/planning/common/speed_limit.h" #include "modules/common_msgs/planning_msgs/decision.pb.h" #include "modules/planning/reference_line/reference_line.h" namespace apollo { namespace planning { constexpr double kADCSafetyLBuffer = 0.1; constexpr double kSIgnoreThreshold = 0.01; constexpr double kTIgnoreThreshold = 0.1; constexpr double kOvertakenObsCautionTime = 0.5; class STObstaclesProcessor { public: STObstaclesProcessor() {} void Init(const double planning_distance, const double planning_time, const PathData& path_data, PathDecision* const path_decision, History* const history); virtual ~STObstaclesProcessor() = default; common::Status MapObstaclesToSTBoundaries(PathDecision* const path_decision); std::unordered_map<std::string, STBoundary> GetAllSTBoundaries(); /** @brief Given a time t, get the lower and upper s-boundaries. * If the boundary is well-defined based on decision made previously, * fill "available_s_bounds" with only one boundary. * Otherwise, fill "available_s_bounds with all candidates and * "available_obs_decisions" with corresponding possible obstacle decisions. * @param Time t * @param The available s-boundaries to be filled up. * @param The corresponding possible obstacle decisions. * @return Whether we can get valid s-bounds. */ bool GetSBoundsFromDecisions( double t, std::vector<std::pair<double, double>>* const available_s_bounds, std::vector< std::vector<std::pair<std::string, ObjectDecisionType>>>* const available_obs_decisions); /** @brief Provided that decisions for all existing obstacles are made, get * the speed limiting info from limiting st-obstacles. * @param Time t. * @param The actual limiting speed-info: (lower, upper) * @return True if there is speed limiting info; otherwise, false. */ bool GetLimitingSpeedInfo( double t, std::pair<double, double>* const limiting_speed_info); /** @brief Set the decision for a given obstacle. */ void SetObstacleDecision(const std::string& obs_id, const ObjectDecisionType& obs_decision); /** @brief Set the decision for a list of obstacles. */ void SetObstacleDecision( const std::vector<std::pair<std::string, ObjectDecisionType>>& obstacle_decisions); private: /** @brief Given a single obstacle, compute its ST-boundary. * @param An obstacle (if moving, should contain predicted trajectory). * @param A vector to be filled with lower edge of ST-polygon. * @param A vector to be filled with upper edge of ST-polygon. * @return If appears on ST-graph, return true; otherwise, false. */ bool ComputeObstacleSTBoundary(const Obstacle& obstacle, std::vector<STPoint>* const lower_points, std::vector<STPoint>* const upper_points, bool* const is_caution_obstacle, double* const obs_caution_end_t); /** @brief Given ADC's path and an obstacle instance at a certain timestep, * get the upper and lower s that ADC might overlap with the obs instance. * @param A vector of ADC planned path points. * @param A obstacle at a certain timestep. * @param ADC lateral buffer for safety consideration. * @param The overlapping upper and lower s to be updated. * @return Whether there is an overlap or not. */ bool GetOverlappingS(const std::vector<common::PathPoint>& adc_path_points, const common::math::Box2d& obstacle_instance, const double adc_l_buffer, std::pair<double, double>* const overlapping_s); /** @brief Over the s-dimension, find the last point that is before the * obstacle instance of the first point that is after the obstacle. * If there exists no such point within the given range, return -1. * @param ADC path points * @param The obstacle box * @param The s threshold, must be non-negative. * @param The direction * @param The start-idx * @param The end-idx * @return Whether there is overlapping or not. */ int GetSBoundingPathPointIndex( const std::vector<common::PathPoint>& adc_path_points, const common::math::Box2d& obstacle_instance, const double s_thresh, const bool is_before, const int start_idx, const int end_idx); /** @brief Over the s-dimension, check if the path-point is away * from the projected obstacle in the given direction. * @param A certain path-point. * @param The next path-point indicating path direction. * @param The obstacle bounding box. * @param The threshold s to tell if path point is far away. * @param Direction indicator. True if we want the path-point to be * before the obstacle. * @return whether the path-point is away in the indicated direction. */ bool IsPathPointAwayFromObstacle(const common::PathPoint& path_point, const common::PathPoint& direction_point, const common::math::Box2d& obs_box, const double s_thresh, const bool is_before); /** @brief Check if ADC is overlapping with the given obstacle box. * @param ADC's position. * @param Obstacle's box. * @param ADC's lateral buffer. * @return Whether ADC at that position is overlapping with the given * obstacle box. */ bool IsADCOverlappingWithObstacle(const common::PathPoint& adc_path_point, const common::math::Box2d& obs_box, const double l_buffer) const; /** @brief Find the vertical (s) gaps of the st-graph. * @param Vector of obstacle-t-edges * @param The existing minimum s edge. * @param The existing maximum s edge. * @return A list of available s gaps for ADC to go. */ std::vector<std::pair<double, double>> FindSGaps( const std::vector<std::tuple<int, double, double, double, std::string>>& obstacle_t_edges, double s_min, double s_max); /** @brief Based on obstacle position and prospective ADC position, * determine the obstacle decision. * @param Obstacle's minimum s. * @param Obstacle's maximum s. * @param ADC's prospective position. * @return The decision for the given obstacle. */ ObjectDecisionType DetermineObstacleDecision(const double obs_s_min, const double obs_s_max, const double s) const; /** @brief Check if a given s falls within adc's low road right segment. * @param A certain S. * @return True if within; false otherwise. */ bool IsSWithinADCLowRoadRightSegment(const double s) const; private: double planning_time_; double planning_distance_; PathData path_data_; common::VehicleParam vehicle_param_; double adc_path_init_s_; PathDecision* path_decision_; // A vector of sorted obstacle's t-edges: // (is_starting_t, t, s_min, s_max, obs_id). std::vector<std::tuple<int, double, double, double, std::string>> obs_t_edges_; int obs_t_edges_idx_; std::unordered_map<std::string, STBoundary> obs_id_to_st_boundary_; std::unordered_map<std::string, ObjectDecisionType> obs_id_to_decision_; std::vector<std::tuple<std::string, STBoundary, Obstacle*>> candidate_clear_zones_; std::unordered_map<std::string, STBoundary> obs_id_to_alternative_st_boundary_; std::vector<std::pair<double, double>> adc_low_road_right_segments_; History* history_ = nullptr; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/st_bounds_decider/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 = "st_bounds_decider", srcs = ["st_bounds_decider.cc"], hdrs = ["st_bounds_decider.h"], copts = PLANNING_COPTS, deps = [ ":st_driving_limits", ":st_guide_line", ":st_obstacles_processor", "//modules/common/status", "//modules/planning/common:frame", "//modules/planning/common:planning_gflags", "//modules/planning/common:st_graph_data", "//modules/planning/common/util:common_lib", "//modules/planning/tasks:task", "//modules/planning/tasks/deciders:decider_base", ], ) cc_library( name = "st_guide_line", srcs = ["st_guide_line.cc"], hdrs = ["st_guide_line.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/common_msgs/config_msgs:vehicle_config_cc_proto", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/status", "//modules/map/pnc_map", "//modules/common_msgs/map_msgs:map_cc_proto", "//modules/planning/common:frame", "//modules/planning/common:obstacle", "//modules/planning/common:path_decision", "//modules/planning/common:planning_gflags", "//modules/planning/common:speed_limit", "//modules/planning/common/path:discretized_path", "//modules/planning/common/path:frenet_frame_path", "//modules/planning/common/path:path_data", "//modules/planning/common/speed:speed_data", "//modules/planning/common/speed:st_boundary", "//modules/planning/common/trajectory:discretized_trajectory", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/proto:planning_config_cc_proto", "//modules/planning/reference_line", ], ) cc_library( name = "st_driving_limits", srcs = ["st_driving_limits.cc"], hdrs = ["st_driving_limits.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/common_msgs/config_msgs:vehicle_config_cc_proto", "//modules/common/status", "//modules/map/pnc_map", "//modules/planning/common:frame", "//modules/planning/common:obstacle", "//modules/planning/common:path_decision", "//modules/planning/common:planning_gflags", "//modules/planning/common:speed_limit", "//modules/planning/common/path:discretized_path", "//modules/planning/common/path:frenet_frame_path", "//modules/planning/common/path:path_data", "//modules/planning/common/speed:st_boundary", "//modules/planning/common/trajectory:discretized_trajectory", "//modules/planning/proto:planning_config_cc_proto", "//modules/planning/reference_line", ], ) cc_library( name = "st_obstacles_processor", srcs = ["st_obstacles_processor.cc"], hdrs = ["st_obstacles_processor.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/common_msgs/config_msgs:vehicle_config_cc_proto", "//modules/common_msgs/basic_msgs:pnc_point_cc_proto", "//modules/common/status", "//modules/map/pnc_map", "//modules/planning/common:frame", "//modules/planning/common:history", "//modules/planning/common:obstacle", "//modules/planning/common:path_decision", "//modules/planning/common:planning_gflags", "//modules/planning/common:speed_limit", "//modules/planning/common/path:discretized_path", "//modules/planning/common/path:frenet_frame_path", "//modules/planning/common/path:path_data", "//modules/planning/common/speed:st_boundary", "//modules/planning/common/trajectory:discretized_trajectory", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/proto:planning_config_cc_proto", "//modules/planning/reference_line", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/rss_decider/rss_decider.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/rss_decider/rss_decider.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/planning/common/planning_gflags.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using ad_rss::physics::Distance; using ad_rss::physics::ParametricValue; using ad_rss::physics::Speed; using ad_rss::situation::VehicleState; using ad_rss::world::Object; using ad_rss::world::RoadArea; using ad_rss::world::Scene; RssDecider::RssDecider(const TaskConfig &config) : Task(config) {} apollo::common::Status RssDecider::Execute( Frame *frame, ReferenceLineInfo *reference_line_info) { return Process(frame, reference_line_info); } Status RssDecider::Process(Frame *frame, ReferenceLineInfo *reference_line_info) { CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); if (reference_line_info->path_data().Empty() || reference_line_info->speed_data().empty()) { const std::string msg = "Empty path or speed data"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } double adc_velocity = frame->vehicle_state().linear_velocity(); const PathDecision *path_decision = reference_line_info->path_decision(); const double ego_v_s_start = reference_line_info->AdcSlBoundary().start_s(); const double ego_v_s_end = reference_line_info->AdcSlBoundary().end_s(); const double ego_v_l_start = reference_line_info->AdcSlBoundary().start_l(); const double ego_v_l_end = reference_line_info->AdcSlBoundary().end_l(); double nearest_obs_s_start = 0.0; double nearest_obs_s_end = 0.0; double nearest_obs_l_start = 0.0; double nearest_obs_l_end = 0.0; double nearest_obs_speed = 0.0; double front_obstacle_distance = FLAGS_rss_max_front_obstacle_distance; for (const auto *obstacle : path_decision->obstacles().Items()) { if (obstacle->IsVirtual()) { continue; } bool is_on_road = reference_line_info->reference_line().HasOverlap( obstacle->PerceptionBoundingBox()); if (!is_on_road) { continue; } const auto &obstacle_sl = obstacle->PerceptionSLBoundary(); if (obstacle_sl.end_s() <= ego_v_s_start) { continue; } double distance = obstacle_sl.start_s() - ego_v_s_end; if (distance > 0 && distance < front_obstacle_distance) { front_obstacle_distance = distance; nearest_obs_s_start = obstacle_sl.start_s(); nearest_obs_s_end = obstacle_sl.end_s(); nearest_obs_l_start = obstacle_sl.start_l(); nearest_obs_l_end = obstacle_sl.end_l(); nearest_obs_speed = obstacle->speed(); } } // there is no obstacle in front of adc if (front_obstacle_distance >= FLAGS_rss_max_front_obstacle_distance) { ::ad_rss::world::Dynamics dynamics; rss_config_default_dynamics(&dynamics); reference_line_info->mutable_rss_info()->set_is_rss_safe(true); reference_line_info->mutable_rss_info()->set_cur_dist_lon( front_obstacle_distance); reference_line_info->mutable_rss_info()->set_rss_safe_dist_lon( front_obstacle_distance); reference_line_info->mutable_rss_info()->set_acc_lon_range_minimum( -1 * static_cast<double>(dynamics.alphaLon.brakeMax)); reference_line_info->mutable_rss_info()->set_acc_lon_range_maximum( static_cast<double>(dynamics.alphaLon.accelMax)); reference_line_info->mutable_rss_info()->set_acc_lat_left_range_minimum( -1 * static_cast<double>(dynamics.alphaLat.brakeMin)); reference_line_info->mutable_rss_info()->set_acc_lat_left_range_maximum( static_cast<double>(dynamics.alphaLat.accelMax)); reference_line_info->mutable_rss_info()->set_acc_lat_right_range_minimum( -1 * static_cast<double>(dynamics.alphaLat.brakeMin)); reference_line_info->mutable_rss_info()->set_acc_lat_right_range_maximum( static_cast<double>(dynamics.alphaLat.accelMax)); return Status::OK(); } #if RSS_FAKE_INPUT nearest_obs_l_start = -4.2608; nearest_obs_l_end = -1.42591; ego_v_l_start = -1.05554; ego_v_l_end = 1.08416; #endif double lane_leftmost = std::max(ego_v_l_end, nearest_obs_l_end); double lane_rightmost = std::min(ego_v_l_start, nearest_obs_l_start); double lane_width = std::abs(lane_leftmost - lane_rightmost); double lane_length = std::max(nearest_obs_s_end, ego_v_s_end); rss_world_info.front_obs_dist = front_obstacle_distance; rss_world_info.obs_s_start = nearest_obs_s_start; rss_world_info.obs_s_end = nearest_obs_s_end; rss_world_info.obs_l_start = nearest_obs_l_start; rss_world_info.obs_l_end = nearest_obs_l_end; rss_world_info.obs_speed = nearest_obs_speed; rss_world_info.ego_v_s_start = ego_v_s_start; rss_world_info.ego_v_s_end = ego_v_s_end; rss_world_info.ego_v_l_start = ego_v_l_start; rss_world_info.ego_v_l_end = ego_v_l_end; rss_world_info.lane_leftmost = lane_leftmost; rss_world_info.lane_rightmost = lane_rightmost; rss_world_info.lane_width = lane_width; rss_world_info.lane_length = lane_length; Object followingObject; Object leadingObject; RoadArea roadArea; Scene scene; scene.situationType = ad_rss::situation::SituationType::SameDirection; rss_create_other_object(&leadingObject, nearest_obs_speed, 0); ad_rss::world::OccupiedRegion occupiedRegion_leading; occupiedRegion_leading.segmentId = 0; occupiedRegion_leading.lonRange.minimum = ParametricValue(nearest_obs_s_start / lane_length); occupiedRegion_leading.lonRange.maximum = ParametricValue(nearest_obs_s_end / lane_length); occupiedRegion_leading.latRange.minimum = ParametricValue(std::abs(ego_v_l_end - lane_leftmost) / lane_width); occupiedRegion_leading.latRange.maximum = ParametricValue(std::abs(ego_v_l_start - lane_leftmost) / lane_width); leadingObject.occupiedRegions.push_back(occupiedRegion_leading); rss_world_info.OR_front_lon_min = static_cast<double>(occupiedRegion_leading.lonRange.minimum); rss_world_info.OR_front_lon_max = static_cast<double>(occupiedRegion_leading.lonRange.maximum); rss_world_info.OR_front_lat_min = static_cast<double>(occupiedRegion_leading.latRange.minimum); rss_world_info.OR_front_lat_max = static_cast<double>(occupiedRegion_leading.latRange.maximum); RssDecider::rss_create_ego_object(&followingObject, adc_velocity, 0.0); ad_rss::world::OccupiedRegion occupiedRegion_following; occupiedRegion_following.segmentId = 0; occupiedRegion_following.lonRange.minimum = ParametricValue(ego_v_s_start / lane_length); occupiedRegion_following.lonRange.maximum = ParametricValue(ego_v_s_end / lane_length); occupiedRegion_following.latRange.minimum = ParametricValue(std::abs(nearest_obs_l_end - lane_leftmost) / lane_width); occupiedRegion_following.latRange.maximum = ParametricValue( std::abs(nearest_obs_l_start - lane_leftmost) / lane_width); followingObject.occupiedRegions.push_back(occupiedRegion_following); rss_world_info.adc_vel = adc_velocity; rss_world_info.OR_rear_lon_min = static_cast<double>(occupiedRegion_following.lonRange.minimum); rss_world_info.OR_rear_lon_max = static_cast<double>(occupiedRegion_following.lonRange.maximum); rss_world_info.OR_rear_lat_min = static_cast<double>(occupiedRegion_following.latRange.minimum); rss_world_info.OR_rear_lat_max = static_cast<double>(occupiedRegion_following.latRange.maximum); ad_rss::world::RoadSegment roadSegment; ad_rss::world::LaneSegment laneSegment; laneSegment.id = 0; laneSegment.length.minimum = Distance(lane_length); laneSegment.length.maximum = Distance(lane_length); laneSegment.width.minimum = Distance(lane_width); laneSegment.width.maximum = Distance(lane_width); roadSegment.push_back(laneSegment); roadArea.push_back(roadSegment); rss_world_info.laneSeg_len_min = static_cast<double>(laneSegment.length.minimum); rss_world_info.laneSeg_len_max = static_cast<double>(laneSegment.length.maximum); rss_world_info.laneSeg_width_min = static_cast<double>(laneSegment.width.minimum); rss_world_info.laneSeg_width_max = static_cast<double>(laneSegment.width.maximum); ad_rss::world::WorldModel worldModel; worldModel.egoVehicle = followingObject; scene.object = leadingObject; scene.egoVehicleRoad = roadArea; worldModel.scenes.push_back(scene); worldModel.timeIndex = frame->SequenceNum(); ad_rss::situation::SituationVector situationVector; bool rss_result = ::ad_rss::core::RssSituationExtraction::extractSituations( worldModel, situationVector); if (!rss_result) { rss_world_info.err_code = "ad_rss::extractSituation failed"; rss_dump_world_info(rss_world_info); return Status(ErrorCode::PLANNING_ERROR, rss_world_info.err_code); } if (situationVector.empty()) { rss_world_info.err_code = "situationVector unexpected empty"; rss_dump_world_info(rss_world_info); return Status(ErrorCode::PLANNING_ERROR, rss_world_info.err_code); } ::ad_rss::state::ResponseStateVector responseStateVector; ::ad_rss::core::RssSituationChecking RssCheck; rss_result = RssCheck.checkSituations(situationVector, responseStateVector); if (!rss_result) { rss_world_info.err_code = "ad_rss::checkSituation failed"; rss_dump_world_info(rss_world_info); return Status(ErrorCode::PLANNING_ERROR, rss_world_info.err_code); } if (responseStateVector.empty()) { rss_world_info.err_code = "responseStateVector unexpected empty"; rss_dump_world_info(rss_world_info); return Status(ErrorCode::PLANNING_ERROR, rss_world_info.err_code); } ::ad_rss::state::ResponseState properResponse; ::ad_rss::core::RssResponseResolving RssResponse; rss_result = RssResponse.provideProperResponse(responseStateVector, properResponse); if (!rss_result) { rss_world_info.err_code = "ad_rss::provideProperResponse failed"; rss_dump_world_info(rss_world_info); return Status(ErrorCode::PLANNING_ERROR, rss_world_info.err_code); } ::ad_rss::world::AccelerationRestriction accelerationRestriction; rss_result = ad_rss::core::RssResponseTransformation::transformProperResponse( worldModel, properResponse, accelerationRestriction); if (!rss_result) { rss_world_info.err_code = "ad_rss::transformProperResponse failed"; rss_dump_world_info(rss_world_info); return Status(ErrorCode::PLANNING_ERROR, rss_world_info.err_code); } Distance const currentLonDistance = situationVector[0].relativePosition.longitudinalDistance; Distance safeLonDistance; VehicleState const &leadingVehicleState = situationVector[0].otherVehicleState; VehicleState const &followingVehicleState = situationVector[0].egoVehicleState; rss_result = ::ad_rss::situation::calculateSafeLongitudinalDistanceSameDirection( leadingVehicleState, followingVehicleState, safeLonDistance); if (!rss_result) { rss_world_info.err_code = ("ad_rss::calculateSafeLongitudinalDistanceSameDirection failed"); rss_dump_world_info(rss_world_info); return Status(ErrorCode::PLANNING_ERROR, rss_world_info.err_code); } if (responseStateVector[0].longitudinalState.isSafe) { ADEBUG << "Task " << Name() << " Distance is RSS-Safe"; reference_line_info->mutable_rss_info()->set_is_rss_safe(true); } else { ADEBUG << "Task " << Name() << " Distance is not RSS-Safe"; reference_line_info->mutable_rss_info()->set_is_rss_safe(false); if (FLAGS_enable_rss_fallback) { reference_line_info->mutable_speed_data()->clear(); } } reference_line_info->mutable_rss_info()->set_cur_dist_lon( static_cast<double>(currentLonDistance)); reference_line_info->mutable_rss_info()->set_rss_safe_dist_lon( static_cast<double>(safeLonDistance)); reference_line_info->mutable_rss_info()->set_acc_lon_range_minimum( static_cast<double>(accelerationRestriction.longitudinalRange.minimum)); reference_line_info->mutable_rss_info()->set_acc_lon_range_maximum( static_cast<double>(accelerationRestriction.longitudinalRange.maximum)); reference_line_info->mutable_rss_info()->set_acc_lat_left_range_minimum( static_cast<double>(accelerationRestriction.lateralLeftRange.minimum)); reference_line_info->mutable_rss_info()->set_acc_lat_left_range_maximum( static_cast<double>(accelerationRestriction.lateralLeftRange.maximum)); reference_line_info->mutable_rss_info()->set_acc_lat_right_range_minimum( static_cast<double>(accelerationRestriction.lateralRightRange.minimum)); reference_line_info->mutable_rss_info()->set_acc_lat_right_range_maximum( static_cast<double>(accelerationRestriction.lateralRightRange.maximum)); ADEBUG << " longitudinalState.isSafe: " << responseStateVector[0].longitudinalState.isSafe; ADEBUG << " lateralStateLeft.isSafe: " << responseStateVector[0].lateralStateLeft.isSafe; ADEBUG << " lateralStateRight.isSafe: " << responseStateVector[0].lateralStateRight.isSafe; ADEBUG << " is_rss_safe : " << reference_line_info->rss_info().is_rss_safe(); ADEBUG << " cur_dist_lon: " << reference_line_info->rss_info().cur_dist_lon(); ADEBUG << " is_rss_safe : " << reference_line_info->rss_info().is_rss_safe(); ADEBUG << " cur_dist_lon: " << reference_line_info->rss_info().cur_dist_lon(); ADEBUG << " rss_safe_dist_lon: " << reference_line_info->rss_info().rss_safe_dist_lon(); ADEBUG << " acc_longitudianlRange_minimum: " << reference_line_info->rss_info().acc_lon_range_minimum(); ADEBUG << " acc_longitudinalRange_maximum: " << reference_line_info->rss_info().acc_lon_range_maximum(); ADEBUG << " acc_lateralLeftRange_minimum: " << reference_line_info->rss_info().acc_lat_left_range_minimum(); ADEBUG << " acc_lateralLeftRange_maximum: " << reference_line_info->rss_info().acc_lat_left_range_maximum(); ADEBUG << " acc_lateralRightRange: " << reference_line_info->rss_info().acc_lat_right_range_minimum(); ADEBUG << " acc_lateralRightRange_maximum: " << reference_line_info->rss_info().acc_lat_right_range_maximum(); return Status::OK(); } void RssDecider::rss_config_default_dynamics( ::ad_rss::world::Dynamics *dynamics) { dynamics->alphaLon.accelMax = ::ad_rss::physics::Acceleration(3.5); dynamics->alphaLon.brakeMax = ::ad_rss::physics::Acceleration(8); dynamics->alphaLon.brakeMin = ::ad_rss::physics::Acceleration(4.); dynamics->alphaLon.brakeMinCorrect = ::ad_rss::physics::Acceleration(3.); dynamics->alphaLat.accelMax = ::ad_rss::physics::Acceleration(0.2); dynamics->alphaLat.brakeMin = ::ad_rss::physics::Acceleration(0.8); } void RssDecider::rss_create_ego_object(::ad_rss::world::Object *ego, double vel_lon, double vel_lat) { ego->objectId = 1; ego->objectType = ::ad_rss::world::ObjectType::EgoVehicle; ego->velocity.speedLon = Speed(vel_lon); ego->velocity.speedLat = Speed(vel_lat); rss_config_default_dynamics(&(ego->dynamics)); ego->responseTime = ::ad_rss::physics::Duration(1.); } void RssDecider::rss_create_other_object(::ad_rss::world::Object *other, double vel_lon, double vel_lat) { other->objectId = 0; other->objectType = ::ad_rss::world::ObjectType::OtherVehicle; other->velocity.speedLon = Speed(vel_lon); other->velocity.speedLat = Speed(vel_lat); rss_config_default_dynamics(&(other->dynamics)); other->responseTime = ::ad_rss::physics::Duration(2.); } void RssDecider::rss_dump_world_info( const struct rss_world_model_struct &rss_info) { AERROR << " RSS_INFO :" << " front_obs_dist: " << rss_info.front_obs_dist << " obs_s_start: " << rss_info.obs_s_start << " obs_s_end: " << rss_info.obs_s_end << " obs_l_start: " << rss_info.obs_l_start << " obs_l_end: " << rss_info.obs_l_end << " obs_speed: " << rss_info.obs_speed << " ego_v_s_start: " << rss_info.ego_v_s_start << " ego_v_s_end: " << rss_info.ego_v_s_end << " ego_v_l_start: " << rss_info.ego_v_l_start << " ego_v_l_end: " << rss_info.ego_v_l_end << " lane_leftmost: " << rss_info.lane_leftmost << " lane_rightmost: " << rss_info.lane_rightmost << " lane_width: " << rss_info.lane_width << " lane_length: " << rss_info.lane_length << " OR_front_lon_min: " << rss_info.OR_front_lon_min << " OR_front_lon_max: " << rss_info.OR_front_lon_max << " OR_front_lat_min: " << rss_info.OR_front_lat_min << " OR_front_lat_max: " << rss_info.OR_front_lat_max << " OR_rear_lon_min: " << rss_info.OR_rear_lon_min << " OR_rear_lon_max: " << rss_info.OR_rear_lon_max << " OR_rear_lat_min: " << rss_info.OR_rear_lat_min << " OR_rear_lat_max: " << rss_info.OR_rear_lat_max << " adc_vel: " << rss_info.adc_vel << " laneSeg_len_min: " << rss_info.laneSeg_len_min << " laneSeg_len_max: " << rss_info.laneSeg_len_max << " laneSeg_width_min: " << rss_info.laneSeg_width_min << " laneSeg_width_max: " << rss_info.laneSeg_width_max; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/rss_decider/rss_decider_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "TestSupport.hpp" #include "ad_rss/core/RssCheck.hpp" namespace ad_rss { namespace core { using ad_rss::world::OccupiedRegion; class RssCheckSameDirectionTests : public testing::Test { protected: virtual void SetUp() { scene.situationType = ad_rss::situation::SituationType::SameDirection; // leadingObject = createObject(0., 0.); // lateral speed 0 leadingObject = createObject(0., 0.5); // lateral speed toward right leadingObject.objectId = 0; { OccupiedRegion occupiedRegion; occupiedRegion.lonRange.minimum = ParametricValue(0.94); occupiedRegion.lonRange.maximum = ParametricValue(1.0); occupiedRegion.segmentId = 0; occupiedRegion.latRange.minimum = ParametricValue(0.); occupiedRegion.latRange.maximum = ParametricValue(0.089); // rss safe // occupiedRegion.latRange.maximum = ParametricValue(0.15); // rss unsafe // occupiedRegion.latRange.maximum = ParametricValue(0.3); // rss unsafe leadingObject.occupiedRegions.push_back(occupiedRegion); } // followingObject = createObject(11.0, 0.); // lateral speed 0 followingObject = createObject(11.0, -0.5); // lateral speed toward left followingObject.objectId = 1; { OccupiedRegion occupiedRegion; occupiedRegion.lonRange.minimum = ParametricValue(0.7); occupiedRegion.lonRange.maximum = ParametricValue(0.82); occupiedRegion.segmentId = 0; occupiedRegion.latRange.minimum = ParametricValue(0.3); occupiedRegion.latRange.maximum = ParametricValue(0.66); followingObject.occupiedRegions.push_back(occupiedRegion); } { world::RoadSegment roadSegment; world::LaneSegment laneSegment; laneSegment.id = 0; laneSegment.length.minimum = Distance(41.4); laneSegment.length.maximum = Distance(41.4); laneSegment.width.minimum = Distance(5.98); laneSegment.width.maximum = Distance(5.98); roadSegment.push_back(laneSegment); roadArea.push_back(roadSegment); } } virtual void TearDown() { followingObject.occupiedRegions.clear(); leadingObject.occupiedRegions.clear(); scene.egoVehicleRoad.clear(); } ::ad_rss::world::Object followingObject; ::ad_rss::world::Object leadingObject; ::ad_rss::world::RoadArea roadArea; ::ad_rss::world::Scene scene; }; TEST_F(RssCheckSameDirectionTests, OtherLeading_FixDistance) { ::ad_rss::world::WorldModel worldModel; worldModel.egoVehicle = ad_rss::objectAsEgo(followingObject); scene.object = leadingObject; scene.egoVehicleRoad = roadArea; worldModel.scenes.push_back(scene); worldModel.timeIndex = 1; ::ad_rss::world::AccelerationRestriction accelerationRestriction; ::ad_rss::core::RssCheck rssCheck; ASSERT_TRUE(rssCheck.calculateAccelerationRestriction( worldModel, accelerationRestriction)); if (accelerationRestriction.longitudinalRange.maximum == -1. * worldModel.egoVehicle.dynamics.alphaLon.brakeMin) { printf("[----------] RSS unsafe!!!\n"); EXPECT_EQ(accelerationRestriction.longitudinalRange.maximum, -1. * worldModel.egoVehicle.dynamics.alphaLon.brakeMin); } else { printf("[----------] RSS safe!!!\n"); EXPECT_EQ(accelerationRestriction.longitudinalRange.maximum, worldModel.egoVehicle.dynamics.alphaLon.accelMax); } // following judgement only true for leading-v v(0,0.5) and ego-v v(11,-0.5) EXPECT_EQ(accelerationRestriction.lateralLeftRange.maximum, -1 * worldModel.egoVehicle.dynamics.alphaLat.brakeMin); EXPECT_EQ(accelerationRestriction.lateralRightRange.maximum, worldModel.egoVehicle.dynamics.alphaLat.accelMax); } } // namespace core } // namespace ad_rss
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/rss_decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "rss_decider", srcs = ["rss_decider.cc"], hdrs = ["rss_decider.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/common/status", "//modules/planning/common:planning_context", "//modules/planning/common:planning_gflags", "//modules/planning/common:reference_line_info", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/tasks:task", "@ad_rss_lib//:ad_rss", ], ) cc_test( name = "rss_decider_test", size = "small", srcs = ["rss_decider_test.cc"], tags = ["exclude"], deps = [ ":rss_decider", "@ad_rss_lib//:ad_rss", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/rss_decider/rss_decider.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <algorithm> #include <string> #include "ad_rss/core/RssResponseResolving.hpp" #include "ad_rss/core/RssResponseTransformation.hpp" #include "ad_rss/core/RssSituationChecking.hpp" #include "ad_rss/core/RssSituationExtraction.hpp" #include "ad_rss/situation/SituationVector.hpp" #include "ad_rss/state/ResponseState.hpp" #include "ad_rss/state/ResponseStateVector.hpp" #include "modules/planning/tasks/task.h" #include "situation/RSSFormulas.hpp" namespace apollo { namespace planning { struct rss_world_model_struct { std::string err_code; double front_obs_dist; double obs_s_start; double obs_s_end; double obs_l_start; double obs_l_end; double obs_speed; double ego_v_s_start; double ego_v_s_end; double ego_v_l_start; double ego_v_l_end; double lane_leftmost; double lane_rightmost; double lane_length; double lane_width; double OR_front_lon_min; double OR_front_lon_max; double OR_front_lat_min; double OR_front_lat_max; double OR_rear_lon_min; double OR_rear_lon_max; double OR_rear_lat_min; double OR_rear_lat_max; double adc_vel; double laneSeg_len_min; double laneSeg_len_max; double laneSeg_width_min; double laneSeg_width_max; }; class RssDecider : public Task { public: explicit RssDecider(const TaskConfig &config); apollo::common::Status Execute( Frame *frame, ReferenceLineInfo *reference_line_info) override; private: apollo::common::Status Process(Frame *frame, ReferenceLineInfo *reference_line_info); struct rss_world_model_struct rss_world_info; void rss_config_default_dynamics(::ad_rss::world::Dynamics *dynamics); void rss_create_ego_object(::ad_rss::world::Object *ego, double vel_lon, double vel_lat); void rss_create_other_object(::ad_rss::world::Object *other, double vel_lon, double vel_lat); void rss_dump_world_info(const struct rss_world_model_struct &rss_info); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_lane_borrow_decider/path_lane_borrow_decider.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <memory> #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/tasks/deciders/decider.h" namespace apollo { namespace planning { class PathLaneBorrowDecider : public Decider { public: PathLaneBorrowDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); private: common::Status Process(Frame* frame, ReferenceLineInfo* reference_line_info) override; bool IsNecessaryToBorrowLane(const Frame& frame, const ReferenceLineInfo& reference_line_info); bool HasSingleReferenceLine(const Frame& frame); bool IsWithinSidePassingSpeedADC(const Frame& frame); bool IsLongTermBlockingObstacle(); bool IsBlockingObstacleWithinDestination( const ReferenceLineInfo& reference_line_info); bool IsBlockingObstacleFarFromIntersection( const ReferenceLineInfo& reference_line_info); bool IsSidePassableObstacle(const ReferenceLineInfo& reference_line_info); void CheckLaneBorrow(const ReferenceLineInfo& reference_line_info, bool* left_neighbor_lane_borrowable, bool* right_neighbor_lane_borrowable); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_lane_borrow_decider/path_lane_borrow_decider.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/tasks/deciders/path_lane_borrow_decider/path_lane_borrow_decider.h" #include <algorithm> #include <memory> #include <string> #include "modules/planning/common/obstacle_blocking_analyzer.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::Status; constexpr double kIntersectionClearanceDist = 20.0; constexpr double kJunctionClearanceDist = 15.0; PathLaneBorrowDecider::PathLaneBorrowDecider( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Decider(config, injector) {} Status PathLaneBorrowDecider::Process( Frame* const frame, ReferenceLineInfo* const reference_line_info) { // Sanity checks. CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); // skip path_lane_borrow_decider if reused path if (FLAGS_enable_skip_path_tasks && reference_line_info->path_reusable()) { // for debug AINFO << "skip due to reusing path"; return Status::OK(); } // By default, don't borrow any lane. reference_line_info->set_is_path_lane_borrow(false); // Check if lane-borrowing is needed, if so, borrow lane. if (Decider::config_.path_lane_borrow_decider_config() .allow_lane_borrowing() && IsNecessaryToBorrowLane(*frame, *reference_line_info)) { reference_line_info->set_is_path_lane_borrow(true); } return Status::OK(); } bool PathLaneBorrowDecider::IsNecessaryToBorrowLane( const Frame& frame, const ReferenceLineInfo& reference_line_info) { auto* mutable_path_decider_status = injector_->planning_context() ->mutable_planning_status() ->mutable_path_decider(); if (mutable_path_decider_status->is_in_path_lane_borrow_scenario()) { // If originally borrowing neighbor lane: if (mutable_path_decider_status->able_to_use_self_lane_counter() >= 6) { // If have been able to use self-lane for some time, then switch to // non-lane-borrowing. mutable_path_decider_status->set_is_in_path_lane_borrow_scenario(false); mutable_path_decider_status->clear_decided_side_pass_direction(); AINFO << "Switch from LANE-BORROW path to SELF-LANE path."; } } else { // If originally not borrowing neighbor lane: ADEBUG << "Blocking obstacle ID[" << mutable_path_decider_status->front_static_obstacle_id() << "]"; // ADC requirements check for lane-borrowing: if (!HasSingleReferenceLine(frame)) { return false; } if (!IsWithinSidePassingSpeedADC(frame)) { return false; } // Obstacle condition check for lane-borrowing: if (!IsBlockingObstacleFarFromIntersection(reference_line_info)) { return false; } if (!IsLongTermBlockingObstacle()) { return false; } if (!IsBlockingObstacleWithinDestination(reference_line_info)) { return false; } if (!IsSidePassableObstacle(reference_line_info)) { return false; } // switch to lane-borrowing // set side-pass direction const auto& path_decider_status = injector_->planning_context()->planning_status().path_decider(); if (path_decider_status.decided_side_pass_direction().empty()) { // first time init decided_side_pass_direction bool left_borrowable; bool right_borrowable; CheckLaneBorrow(reference_line_info, &left_borrowable, &right_borrowable); if (!left_borrowable && !right_borrowable) { mutable_path_decider_status->set_is_in_path_lane_borrow_scenario(false); return false; } else { mutable_path_decider_status->set_is_in_path_lane_borrow_scenario(true); if (left_borrowable) { mutable_path_decider_status->add_decided_side_pass_direction( PathDeciderStatus::LEFT_BORROW); } if (right_borrowable) { mutable_path_decider_status->add_decided_side_pass_direction( PathDeciderStatus::RIGHT_BORROW); } } } AINFO << "Switch from SELF-LANE path to LANE-BORROW path."; } return mutable_path_decider_status->is_in_path_lane_borrow_scenario(); } // This function is to prevent lane-borrowing during lane-changing. // TODO(jiacheng): depending on our needs, may allow lane-borrowing during // lane-change. bool PathLaneBorrowDecider::HasSingleReferenceLine(const Frame& frame) { return frame.reference_line_info().size() == 1; } bool PathLaneBorrowDecider::IsWithinSidePassingSpeedADC(const Frame& frame) { return frame.PlanningStartPoint().v() < FLAGS_lane_borrow_max_speed; } bool PathLaneBorrowDecider::IsLongTermBlockingObstacle() { if (injector_->planning_context() ->planning_status() .path_decider() .front_static_obstacle_cycle_counter() >= FLAGS_long_term_blocking_obstacle_cycle_threshold) { ADEBUG << "The blocking obstacle is long-term existing."; return true; } else { ADEBUG << "The blocking obstacle is not long-term existing."; return false; } } bool PathLaneBorrowDecider::IsBlockingObstacleWithinDestination( const ReferenceLineInfo& reference_line_info) { const auto& path_decider_status = injector_->planning_context()->planning_status().path_decider(); const std::string blocking_obstacle_id = path_decider_status.front_static_obstacle_id(); if (blocking_obstacle_id.empty()) { ADEBUG << "There is no blocking obstacle."; return true; } const Obstacle* blocking_obstacle = reference_line_info.path_decision().obstacles().Find( blocking_obstacle_id); if (blocking_obstacle == nullptr) { ADEBUG << "Blocking obstacle is no longer there."; return true; } double blocking_obstacle_s = blocking_obstacle->PerceptionSLBoundary().start_s(); double adc_end_s = reference_line_info.AdcSlBoundary().end_s(); ADEBUG << "Blocking obstacle is at s = " << blocking_obstacle_s; ADEBUG << "ADC is at s = " << adc_end_s; ADEBUG << "Destination is at s = " << reference_line_info.SDistanceToDestination() + adc_end_s; if (blocking_obstacle_s - adc_end_s > reference_line_info.SDistanceToDestination()) { return false; } return true; } bool PathLaneBorrowDecider::IsBlockingObstacleFarFromIntersection( const ReferenceLineInfo& reference_line_info) { const auto& path_decider_status = injector_->planning_context()->planning_status().path_decider(); const std::string blocking_obstacle_id = path_decider_status.front_static_obstacle_id(); if (blocking_obstacle_id.empty()) { ADEBUG << "There is no blocking obstacle."; return true; } const Obstacle* blocking_obstacle = reference_line_info.path_decision().obstacles().Find( blocking_obstacle_id); if (blocking_obstacle == nullptr) { ADEBUG << "Blocking obstacle is no longer there."; return true; } // Get blocking obstacle's s. double blocking_obstacle_s = blocking_obstacle->PerceptionSLBoundary().end_s(); ADEBUG << "Blocking obstacle is at s = " << blocking_obstacle_s; // Get intersection's s and compare with threshold. const auto& first_encountered_overlaps = reference_line_info.FirstEncounteredOverlaps(); for (const auto& overlap : first_encountered_overlaps) { ADEBUG << overlap.first << ", " << overlap.second.DebugString(); // if (// overlap.first != ReferenceLineInfo::CLEAR_AREA && // overlap.first != ReferenceLineInfo::CROSSWALK && // overlap.first != ReferenceLineInfo::PNC_JUNCTION && if (overlap.first != ReferenceLineInfo::SIGNAL && overlap.first != ReferenceLineInfo::STOP_SIGN) { continue; } auto distance = overlap.second.start_s - blocking_obstacle_s; if (overlap.first == ReferenceLineInfo::SIGNAL || overlap.first == ReferenceLineInfo::STOP_SIGN) { if (distance < kIntersectionClearanceDist) { ADEBUG << "Too close to signal intersection (" << distance << "m); don't SIDE_PASS."; return false; } } else { if (distance < kJunctionClearanceDist) { ADEBUG << "Too close to overlap_type[" << overlap.first << "] (" << distance << "m); don't SIDE_PASS"; return false; } } } return true; } bool PathLaneBorrowDecider::IsSidePassableObstacle( const ReferenceLineInfo& reference_line_info) { const auto& path_decider_status = injector_->planning_context()->planning_status().path_decider(); const std::string blocking_obstacle_id = path_decider_status.front_static_obstacle_id(); if (blocking_obstacle_id.empty()) { ADEBUG << "There is no blocking obstacle."; return false; } const Obstacle* blocking_obstacle = reference_line_info.path_decision().obstacles().Find( blocking_obstacle_id); if (blocking_obstacle == nullptr) { ADEBUG << "Blocking obstacle is no longer there."; return false; } return IsNonmovableObstacle(reference_line_info, *blocking_obstacle); } void PathLaneBorrowDecider::CheckLaneBorrow( const ReferenceLineInfo& reference_line_info, bool* left_neighbor_lane_borrowable, bool* right_neighbor_lane_borrowable) { const ReferenceLine& reference_line = reference_line_info.reference_line(); *left_neighbor_lane_borrowable = true; *right_neighbor_lane_borrowable = true; static constexpr double kLookforwardDistance = 100.0; double check_s = reference_line_info.AdcSlBoundary().end_s(); const double lookforward_distance = std::min(check_s + kLookforwardDistance, reference_line.Length()); while (check_s < lookforward_distance) { auto ref_point = reference_line.GetNearestReferencePoint(check_s); if (ref_point.lane_waypoints().empty()) { *left_neighbor_lane_borrowable = false; *right_neighbor_lane_borrowable = false; return; } const auto waypoint = ref_point.lane_waypoints().front(); hdmap::LaneBoundaryType::Type lane_boundary_type = hdmap::LaneBoundaryType::UNKNOWN; if (*left_neighbor_lane_borrowable) { lane_boundary_type = hdmap::LeftBoundaryType(waypoint); if (lane_boundary_type == hdmap::LaneBoundaryType::SOLID_YELLOW || lane_boundary_type == hdmap::LaneBoundaryType::DOUBLE_YELLOW || lane_boundary_type == hdmap::LaneBoundaryType::SOLID_WHITE) { *left_neighbor_lane_borrowable = false; } ADEBUG << "s[" << check_s << "] left_lane_boundary_type[" << LaneBoundaryType_Type_Name(lane_boundary_type) << "]"; } if (*right_neighbor_lane_borrowable) { lane_boundary_type = hdmap::RightBoundaryType(waypoint); if (lane_boundary_type == hdmap::LaneBoundaryType::SOLID_YELLOW || lane_boundary_type == hdmap::LaneBoundaryType::SOLID_WHITE) { *right_neighbor_lane_borrowable = false; } ADEBUG << "s[" << check_s << "] right_neighbor_lane_borrowable[" << LaneBoundaryType_Type_Name(lane_boundary_type) << "]"; } check_s += 2.0; } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_lane_borrow_decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "path_lane_borrow_decider", srcs = ["path_lane_borrow_decider.cc"], hdrs = ["path_lane_borrow_decider.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/planning/common:obstacle_blocking_analyzer", "//modules/planning/common:planning_context", "//modules/planning/common:planning_gflags", "//modules/planning/common:reference_line_info", "//modules/planning/tasks/deciders:decider_base", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/rule_based_stop_decider/rule_based_stop_decider.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include "modules/planning/common/dependency_injector.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/tasks/deciders/decider.h" namespace apollo { namespace planning { class RuleBasedStopDecider : public Decider { public: RuleBasedStopDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); private: apollo::common::Status Process( Frame* const frame, ReferenceLineInfo* const reference_line_info) override; // @brief Rule-based stop at path end void AddPathEndStop(Frame* const frame, ReferenceLineInfo* const reference_line_info); // @brief Rule-based stop for urgent lane change void CheckLaneChangeUrgency(Frame* const frame); // @brief Rule-based stop for side pass on reverse lane void StopOnSidePass(Frame* const frame, ReferenceLineInfo* const reference_line_info); // @brief Check if necessary to set stop fence used for nonscenario side pass bool CheckSidePassStop(const PathData& path_data, const ReferenceLineInfo& reference_line_info, double* stop_s_on_pathdata); // @brief Set stop fence for side pass bool BuildSidePassStopFence(const PathData& path_data, const double stop_s_on_pathdata, common::PathPoint* stop_point, Frame* const frame, ReferenceLineInfo* const reference_line_info); // @brief Check if ADV stop at a stop fence bool CheckADCStop(const PathData& path_data, const ReferenceLineInfo& reference_line_info, const double stop_s_on_pathdata); // @brief Check if needed to check clear again for side pass bool CheckClearDone(const ReferenceLineInfo& reference_line_info, const common::PathPoint& stop_point); private: static constexpr char const* PATH_END_VO_ID_PREFIX = "PATH_END_"; RuleBasedStopDeciderConfig rule_based_stop_decider_config_; bool is_clear_to_change_lane_ = false; bool is_change_lane_planning_succeed_ = false; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/rule_based_stop_decider/rule_based_stop_decider.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/tasks/deciders/rule_based_stop_decider/rule_based_stop_decider.h" #include <string> #include <tuple> #include <vector> #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/util/common.h" #include "modules/planning/tasks/deciders/lane_change_decider/lane_change_decider.h" namespace apollo { namespace planning { using apollo::common::SLPoint; using apollo::common::Status; using apollo::common::math::Vec2d; namespace { // TODO(ALL): temporarily copy the value from lane_follow_stage.cc, will extract // as a common value for planning later constexpr double kStraightForwardLineCost = 10.0; } // namespace RuleBasedStopDecider::RuleBasedStopDecider( const TaskConfig &config, const std::shared_ptr<DependencyInjector> &injector) : Decider(config, injector) { ACHECK(config.has_rule_based_stop_decider_config()); rule_based_stop_decider_config_ = config.rule_based_stop_decider_config(); } apollo::common::Status RuleBasedStopDecider::Process( Frame *const frame, ReferenceLineInfo *const reference_line_info) { // 1. Rule_based stop for side pass onto reverse lane StopOnSidePass(frame, reference_line_info); // 2. Rule_based stop for urgent lane change if (FLAGS_enable_lane_change_urgency_checking) { CheckLaneChangeUrgency(frame); } // 3. Rule_based stop at path end position AddPathEndStop(frame, reference_line_info); return Status::OK(); } void RuleBasedStopDecider::CheckLaneChangeUrgency(Frame *const frame) { for (auto &reference_line_info : *frame->mutable_reference_line_info()) { // Check if the target lane is blocked or not if (reference_line_info.IsChangeLanePath()) { is_clear_to_change_lane_ = LaneChangeDecider::IsClearToChangeLane(&reference_line_info); is_change_lane_planning_succeed_ = reference_line_info.Cost() < kStraightForwardLineCost; continue; } // If it's not in lane-change scenario || (target lane is not blocked && // change lane planning succeed), skip if (frame->reference_line_info().size() <= 1 || (is_clear_to_change_lane_ && is_change_lane_planning_succeed_)) { continue; } // When the target lane is blocked in change-lane case, check the urgency // Get the end point of current routing const auto &route_end_waypoint = reference_line_info.Lanes().RouteEndWaypoint(); // If can't get lane from the route's end waypoint, then skip if (!route_end_waypoint.lane) { continue; } auto point = route_end_waypoint.lane->GetSmoothPoint(route_end_waypoint.s); auto *reference_line = reference_line_info.mutable_reference_line(); common::SLPoint sl_point; // Project the end point to sl_point on current reference lane if (reference_line->XYToSL(point, &sl_point) && reference_line->IsOnLane(sl_point)) { // Check the distance from ADC to the end point of current routing double distance_to_passage_end = sl_point.s() - reference_line_info.AdcSlBoundary().end_s(); // If ADC is still far from the end of routing, no need to stop, skip if (distance_to_passage_end > rule_based_stop_decider_config_.approach_distance_for_lane_change()) { continue; } // In urgent case, set a temporary stop fence and wait to change lane // TODO(Jiaxuan Xu): replace the stop fence to more intelligent actions const std::string stop_wall_id = "lane_change_stop"; std::vector<std::string> wait_for_obstacles; util::BuildStopDecision( stop_wall_id, sl_point.s(), rule_based_stop_decider_config_.urgent_distance_for_lane_change(), StopReasonCode::STOP_REASON_LANE_CHANGE_URGENCY, wait_for_obstacles, "RuleBasedStopDecider", frame, &reference_line_info); } } } void RuleBasedStopDecider::AddPathEndStop( Frame *const frame, ReferenceLineInfo *const reference_line_info) { if (!reference_line_info->path_data().path_label().empty() && reference_line_info->path_data().frenet_frame_path().back().s() - reference_line_info->path_data().frenet_frame_path().front().s() < FLAGS_short_path_length_threshold) { const std::string stop_wall_id = PATH_END_VO_ID_PREFIX + reference_line_info->path_data().path_label(); std::vector<std::string> wait_for_obstacles; util::BuildStopDecision( stop_wall_id, reference_line_info->path_data().frenet_frame_path().back().s() - 5.0, 0.0, StopReasonCode::STOP_REASON_REFERENCE_END, wait_for_obstacles, "RuleBasedStopDecider", frame, reference_line_info); } } void RuleBasedStopDecider::StopOnSidePass( Frame *const frame, ReferenceLineInfo *const reference_line_info) { static bool check_clear; static common::PathPoint change_lane_stop_path_point; const PathData &path_data = reference_line_info->path_data(); double stop_s_on_pathdata = 0.0; if (path_data.path_label().find("self") != std::string::npos) { check_clear = false; change_lane_stop_path_point.Clear(); return; } if (check_clear && CheckClearDone(*reference_line_info, change_lane_stop_path_point)) { check_clear = false; } if (!check_clear && CheckSidePassStop(path_data, *reference_line_info, &stop_s_on_pathdata)) { if (!LaneChangeDecider::IsPerceptionBlocked( *reference_line_info, rule_based_stop_decider_config_.search_beam_length(), rule_based_stop_decider_config_.search_beam_radius_intensity(), rule_based_stop_decider_config_.search_range(), rule_based_stop_decider_config_.is_block_angle_threshold()) && LaneChangeDecider::IsClearToChangeLane(reference_line_info)) { return; } if (!CheckADCStop(path_data, *reference_line_info, stop_s_on_pathdata)) { if (!BuildSidePassStopFence(path_data, stop_s_on_pathdata, &change_lane_stop_path_point, frame, reference_line_info)) { AERROR << "Set side pass stop fail"; } } else { if (LaneChangeDecider::IsClearToChangeLane(reference_line_info)) { check_clear = true; } } } } // @brief Check if necessary to set stop fence used for nonscenario side pass bool RuleBasedStopDecider::CheckSidePassStop( const PathData &path_data, const ReferenceLineInfo &reference_line_info, double *stop_s_on_pathdata) { const std::vector<std::tuple<double, PathData::PathPointType, double>> &path_point_decision_guide = path_data.path_point_decision_guide(); PathData::PathPointType last_path_point_type = PathData::PathPointType::UNKNOWN; for (const auto &point_guide : path_point_decision_guide) { if (last_path_point_type == PathData::PathPointType::IN_LANE && std::get<1>(point_guide) == PathData::PathPointType::OUT_ON_REVERSE_LANE) { *stop_s_on_pathdata = std::get<0>(point_guide); // Approximate the stop fence s based on the vehicle position const auto &vehicle_config = common::VehicleConfigHelper::Instance()->GetConfig(); const double ego_front_to_center = vehicle_config.vehicle_param().front_edge_to_center(); common::PathPoint stop_pathpoint; if (!path_data.GetPathPointWithRefS(*stop_s_on_pathdata, &stop_pathpoint)) { AERROR << "Can't get stop point on path data"; return false; } const double ego_theta = stop_pathpoint.theta(); Vec2d shift_vec{ego_front_to_center * std::cos(ego_theta), ego_front_to_center * std::sin(ego_theta)}; const Vec2d stop_fence_pose = shift_vec + Vec2d(stop_pathpoint.x(), stop_pathpoint.y()); double stop_l_on_pathdata = 0.0; const auto &nearby_path = reference_line_info.reference_line().map_path(); nearby_path.GetNearestPoint(stop_fence_pose, stop_s_on_pathdata, &stop_l_on_pathdata); return true; } last_path_point_type = std::get<1>(point_guide); } return false; } // @brief Set stop fence for side pass bool RuleBasedStopDecider::BuildSidePassStopFence( const PathData &path_data, const double stop_s_on_pathdata, common::PathPoint *stop_point, Frame *const frame, ReferenceLineInfo *const reference_line_info) { CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); if (!path_data.GetPathPointWithRefS(stop_s_on_pathdata, stop_point)) { AERROR << "Can't get stop point on path data"; return false; } const std::string stop_wall_id = "Side_Pass_Stop"; std::vector<std::string> wait_for_obstacles; const auto &nearby_path = reference_line_info->reference_line().map_path(); double stop_point_s = 0.0; double stop_point_l = 0.0; nearby_path.GetNearestPoint({stop_point->x(), stop_point->y()}, &stop_point_s, &stop_point_l); util::BuildStopDecision(stop_wall_id, stop_point_s, 0.0, StopReasonCode::STOP_REASON_SIDEPASS_SAFETY, wait_for_obstacles, "RuleBasedStopDecider", frame, reference_line_info); return true; } // @brief Check if ADV stop at a stop fence bool RuleBasedStopDecider::CheckADCStop( const PathData &path_data, const ReferenceLineInfo &reference_line_info, const double stop_s_on_pathdata) { common::PathPoint stop_point; if (!path_data.GetPathPointWithRefS(stop_s_on_pathdata, &stop_point)) { AERROR << "Can't get stop point on path data"; return false; } const double adc_speed = injector_->vehicle_state()->linear_velocity(); if (adc_speed > rule_based_stop_decider_config_.max_adc_stop_speed()) { ADEBUG << "ADC not stopped: speed[" << adc_speed << "]"; return false; } // check stop close enough to stop line of the stop_sign const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const auto &nearby_path = reference_line_info.reference_line().map_path(); double stop_point_s = 0.0; double stop_point_l = 0.0; nearby_path.GetNearestPoint({stop_point.x(), stop_point.y()}, &stop_point_s, &stop_point_l); const double distance_stop_line_to_adc_front_edge = stop_point_s - adc_front_edge_s; if (distance_stop_line_to_adc_front_edge > rule_based_stop_decider_config_.max_valid_stop_distance()) { ADEBUG << "not a valid stop. too far from stop line."; return false; } return true; } bool RuleBasedStopDecider::CheckClearDone( const ReferenceLineInfo &reference_line_info, const common::PathPoint &stop_point) { const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const double adc_back_edge_s = reference_line_info.AdcSlBoundary().start_s(); const double adc_start_l = reference_line_info.AdcSlBoundary().start_l(); const double adc_end_l = reference_line_info.AdcSlBoundary().end_l(); double lane_left_width = 0.0; double lane_right_width = 0.0; reference_line_info.reference_line().GetLaneWidth( (adc_front_edge_s + adc_back_edge_s) / 2.0, &lane_left_width, &lane_right_width); SLPoint stop_sl_point; reference_line_info.reference_line().XYToSL(stop_point, &stop_sl_point); // use distance to last stop point to determine if needed to check clear // again if (adc_back_edge_s > stop_sl_point.s()) { if (adc_start_l > -lane_right_width || adc_end_l < lane_left_width) { return true; } } return false; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/rule_based_stop_decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "rule_based_stop_decider", srcs = ["rule_based_stop_decider.cc"], hdrs = ["rule_based_stop_decider.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/common/status", "//modules/planning/common:frame", "//modules/planning/common:planning_gflags", "//modules/planning/common/util:common_lib", "//modules/planning/tasks:task", "//modules/planning/tasks/deciders:decider_base", "//modules/planning/tasks/deciders/lane_change_decider", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/utils/path_decider_obstacle_utils.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/tasks/deciders/utils/path_decider_obstacle_utils.h" #include <limits> #include "modules/common/math/linear_interpolation.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { bool IsWithinPathDeciderScopeObstacle(const Obstacle& obstacle) { // Obstacle should be non-virtual. if (obstacle.IsVirtual()) { return false; } // Obstacle should not have ignore decision. if (obstacle.HasLongitudinalDecision() && obstacle.HasLateralDecision() && obstacle.IsIgnore()) { return false; } // Obstacle should not be moving obstacle. if (!obstacle.IsStatic() || obstacle.speed() > FLAGS_static_obstacle_speed_threshold) { return false; } // TODO(jiacheng): // Some obstacles are not moving, but only because they are waiting for // red light (traffic rule) or because they are blocked by others (social). // These obstacles will almost certainly move in the near future and we // should not side-pass such obstacles. return true; } bool ComputeSLBoundaryIntersection(const SLBoundary& sl_boundary, const double s, double* ptr_l_min, double* ptr_l_max) { *ptr_l_min = std::numeric_limits<double>::max(); *ptr_l_max = -std::numeric_limits<double>::max(); // invalid polygon if (sl_boundary.boundary_point_size() < 3) { return false; } bool has_intersection = false; for (auto i = 0; i < sl_boundary.boundary_point_size(); ++i) { auto j = (i + 1) % sl_boundary.boundary_point_size(); const auto& p0 = sl_boundary.boundary_point(i); const auto& p1 = sl_boundary.boundary_point(j); if (common::util::WithinBound<double>(std::fmin(p0.s(), p1.s()), std::fmax(p0.s(), p1.s()), s)) { has_intersection = true; auto l = common::math::lerp<double>(p0.l(), p0.s(), p1.l(), p1.s(), s); if (l < *ptr_l_min) { *ptr_l_min = l; } if (l > *ptr_l_max) { *ptr_l_max = l; } } } return has_intersection; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/utils/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "path_decider_obstacle_utils", srcs = ["path_decider_obstacle_utils.cc"], hdrs = ["path_decider_obstacle_utils.h"], deps = [ "//modules/planning/common:frame", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/utils/path_decider_obstacle_utils.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. *****************************************************************************/ #include "modules/planning/common/frame.h" namespace apollo { namespace planning { bool IsWithinPathDeciderScopeObstacle(const Obstacle& obstacle); } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/lane_change_decider/lane_change_decider.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <list> #include <memory> #include <string> #include "modules/map/pnc_map/route_segments.h" #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/proto/planning_status.pb.h" #include "modules/planning/tasks/deciders/decider.h" namespace apollo { namespace planning { class LaneChangeDecider : public Decider { public: LaneChangeDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); /** * @brief A static function to check if the ChangeLanePath type of reference * line is safe or if current reference line is safe to deviate away and come * back */ static bool IsClearToChangeLane(ReferenceLineInfo* reference_line_info); /** * @brief A static function to estimate if an obstacle in certain range in * front of ADV blocks too much space perception behind itself by beam * scanning * @param search_beam_length is the length of scanning beam * @param search_beam_radius_intensity is the resolution of scanning * @param search_range is the scanning range centering at ADV heading * @param is_block_angle_threshold is the threshold to tell how big a block * angle range is perception blocking */ static bool IsPerceptionBlocked(const ReferenceLineInfo& reference_line_info, const double search_beam_length, const double search_beam_radius_intensity, const double search_range, const double is_block_angle_threshold); static void UpdatePreparationDistance( const bool is_opt_succeed, const Frame* frame, const ReferenceLineInfo* const reference_line_info, PlanningContext* planning_context); private: common::Status Process( Frame* frame, ReferenceLineInfo* const current_reference_line_info) override; static bool HysteresisFilter(const double obstacle_distance, const double safe_distance, const double distance_buffer, const bool is_obstacle_blocking); void UpdateStatus(ChangeLaneStatus::Status status_code, const std::string& path_id); void UpdateStatus(double timestamp, ChangeLaneStatus::Status status_code, const std::string& path_id); void PrioritizeChangeLane( const bool is_prioritize_change_lane, std::list<ReferenceLineInfo>* reference_line_info) const; void RemoveChangeLane( std::list<ReferenceLineInfo>* reference_line_info) const; std::string GetCurrentPathId( const std::list<ReferenceLineInfo>& reference_line_info) const; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/lane_change_decider/lane_change_decider.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/tasks/deciders/lane_change_decider/lane_change_decider.h" #include <limits> #include <memory> #include "cyber/time/clock.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::SLPoint; using apollo::common::Status; using apollo::cyber::Clock; LaneChangeDecider::LaneChangeDecider( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Decider(config, injector) { ACHECK(config_.has_lane_change_decider_config()); } // added a dummy parameter to enable this task in ExecuteTaskOnReferenceLine Status LaneChangeDecider::Process( Frame* frame, ReferenceLineInfo* const current_reference_line_info) { // Sanity checks. CHECK_NOTNULL(frame); const auto& lane_change_decider_config = config_.lane_change_decider_config(); std::list<ReferenceLineInfo>* reference_line_info = frame->mutable_reference_line_info(); if (reference_line_info->empty()) { const std::string msg = "Reference lines empty."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (lane_change_decider_config.reckless_change_lane()) { PrioritizeChangeLane(true, reference_line_info); return Status::OK(); } auto* prev_status = injector_->planning_context() ->mutable_planning_status() ->mutable_change_lane(); double now = Clock::NowInSeconds(); prev_status->set_is_clear_to_change_lane(false); if (current_reference_line_info->IsChangeLanePath()) { prev_status->set_is_clear_to_change_lane( IsClearToChangeLane(current_reference_line_info)); } if (!prev_status->has_status()) { UpdateStatus(now, ChangeLaneStatus::CHANGE_LANE_FINISHED, GetCurrentPathId(*reference_line_info)); prev_status->set_last_succeed_timestamp(now); return Status::OK(); } bool has_change_lane = reference_line_info->size() > 1; ADEBUG << "has_change_lane: " << has_change_lane; if (!has_change_lane) { const auto& path_id = reference_line_info->front().Lanes().Id(); if (prev_status->status() == ChangeLaneStatus::CHANGE_LANE_FINISHED) { } else if (prev_status->status() == ChangeLaneStatus::IN_CHANGE_LANE) { UpdateStatus(now, ChangeLaneStatus::CHANGE_LANE_FINISHED, path_id); } else if (prev_status->status() == ChangeLaneStatus::CHANGE_LANE_FAILED) { } else { const std::string msg = absl::StrCat("Unknown state: ", prev_status->ShortDebugString()); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } return Status::OK(); } else { // has change lane in reference lines. auto current_path_id = GetCurrentPathId(*reference_line_info); if (current_path_id.empty()) { const std::string msg = "The vehicle is not on any reference line"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } if (prev_status->status() == ChangeLaneStatus::IN_CHANGE_LANE) { if (prev_status->path_id() == current_path_id) { PrioritizeChangeLane(true, reference_line_info); } else { // RemoveChangeLane(reference_line_info); PrioritizeChangeLane(false, reference_line_info); ADEBUG << "removed change lane."; UpdateStatus(now, ChangeLaneStatus::CHANGE_LANE_FINISHED, current_path_id); } return Status::OK(); } else if (prev_status->status() == ChangeLaneStatus::CHANGE_LANE_FAILED) { // TODO(SHU): add an optimization_failure counter to enter // change_lane_failed status if (now - prev_status->timestamp() < lane_change_decider_config.change_lane_fail_freeze_time()) { // RemoveChangeLane(reference_line_info); PrioritizeChangeLane(false, reference_line_info); ADEBUG << "freezed after failed"; } else { UpdateStatus(now, ChangeLaneStatus::IN_CHANGE_LANE, current_path_id); ADEBUG << "change lane again after failed"; } return Status::OK(); } else if (prev_status->status() == ChangeLaneStatus::CHANGE_LANE_FINISHED) { if (now - prev_status->timestamp() < lane_change_decider_config.change_lane_success_freeze_time()) { // RemoveChangeLane(reference_line_info); PrioritizeChangeLane(false, reference_line_info); ADEBUG << "freezed after completed lane change"; } else { PrioritizeChangeLane(true, reference_line_info); UpdateStatus(now, ChangeLaneStatus::IN_CHANGE_LANE, current_path_id); ADEBUG << "change lane again after success"; } } else { const std::string msg = absl::StrCat("Unknown state: ", prev_status->ShortDebugString()); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } } return Status::OK(); } void LaneChangeDecider::UpdatePreparationDistance( const bool is_opt_succeed, const Frame* frame, const ReferenceLineInfo* const reference_line_info, PlanningContext* planning_context) { auto* lane_change_status = planning_context->mutable_planning_status()->mutable_change_lane(); ADEBUG << "Current time: " << lane_change_status->timestamp(); ADEBUG << "Lane Change Status: " << lane_change_status->status(); // If lane change planning succeeded, update and return if (is_opt_succeed) { lane_change_status->set_last_succeed_timestamp(Clock::NowInSeconds()); lane_change_status->set_is_current_opt_succeed(true); return; } // If path optimizer or speed optimizer failed, report the status lane_change_status->set_is_current_opt_succeed(false); // If the planner just succeed recently, let's be more patient and try again if (Clock::NowInSeconds() - lane_change_status->last_succeed_timestamp() < FLAGS_allowed_lane_change_failure_time) { return; } // Get ADC's current s and the lane-change start distance s const ReferenceLine& reference_line = reference_line_info->reference_line(); const common::TrajectoryPoint& planning_start_point = frame->PlanningStartPoint(); auto adc_sl_info = reference_line.ToFrenetFrame(planning_start_point); if (!lane_change_status->exist_lane_change_start_position()) { return; } common::SLPoint point_sl; reference_line.XYToSL(lane_change_status->lane_change_start_position(), &point_sl); ADEBUG << "Current ADC s: " << adc_sl_info.first[0]; ADEBUG << "Change lane point s: " << point_sl.s(); // If the remaining lane-change preparation distance is too small, // refresh the preparation distance if (adc_sl_info.first[0] + FLAGS_min_lane_change_prepare_length > point_sl.s()) { lane_change_status->set_exist_lane_change_start_position(false); ADEBUG << "Refresh the lane-change preparation distance"; } } void LaneChangeDecider::UpdateStatus(ChangeLaneStatus::Status status_code, const std::string& path_id) { UpdateStatus(Clock::NowInSeconds(), status_code, path_id); } void LaneChangeDecider::UpdateStatus(double timestamp, ChangeLaneStatus::Status status_code, const std::string& path_id) { auto* lane_change_status = injector_->planning_context() ->mutable_planning_status() ->mutable_change_lane(); lane_change_status->set_timestamp(timestamp); lane_change_status->set_path_id(path_id); lane_change_status->set_status(status_code); } void LaneChangeDecider::PrioritizeChangeLane( const bool is_prioritize_change_lane, std::list<ReferenceLineInfo>* reference_line_info) const { if (reference_line_info->empty()) { AERROR << "Reference line info empty"; return; } const auto& lane_change_decider_config = config_.lane_change_decider_config(); // TODO(SHU): disable the reference line order change for now if (!lane_change_decider_config.enable_prioritize_change_lane()) { return; } auto iter = reference_line_info->begin(); while (iter != reference_line_info->end()) { ADEBUG << "iter->IsChangeLanePath(): " << iter->IsChangeLanePath(); /* is_prioritize_change_lane == true: prioritize change_lane_reference_line is_prioritize_change_lane == false: prioritize non_change_lane_reference_line */ if ((is_prioritize_change_lane && iter->IsChangeLanePath()) || (!is_prioritize_change_lane && !iter->IsChangeLanePath())) { ADEBUG << "is_prioritize_change_lane: " << is_prioritize_change_lane; ADEBUG << "iter->IsChangeLanePath(): " << iter->IsChangeLanePath(); break; } ++iter; } reference_line_info->splice(reference_line_info->begin(), *reference_line_info, iter); ADEBUG << "reference_line_info->IsChangeLanePath(): " << reference_line_info->begin()->IsChangeLanePath(); } // disabled for now void LaneChangeDecider::RemoveChangeLane( std::list<ReferenceLineInfo>* reference_line_info) const { const auto& lane_change_decider_config = config_.lane_change_decider_config(); // TODO(SHU): fix core dump when removing change lane if (!lane_change_decider_config.enable_remove_change_lane()) { return; } ADEBUG << "removed change lane"; auto iter = reference_line_info->begin(); while (iter != reference_line_info->end()) { if (iter->IsChangeLanePath()) { iter = reference_line_info->erase(iter); } else { ++iter; } } } std::string LaneChangeDecider::GetCurrentPathId( const std::list<ReferenceLineInfo>& reference_line_info) const { for (const auto& info : reference_line_info) { if (!info.IsChangeLanePath()) { return info.Lanes().Id(); } } return ""; } bool LaneChangeDecider::IsClearToChangeLane( ReferenceLineInfo* reference_line_info) { double ego_start_s = reference_line_info->AdcSlBoundary().start_s(); double ego_end_s = reference_line_info->AdcSlBoundary().end_s(); double ego_v = std::abs(reference_line_info->vehicle_state().linear_velocity()); for (const auto* obstacle : reference_line_info->path_decision()->obstacles().Items()) { if (obstacle->IsVirtual() || obstacle->IsStatic()) { ADEBUG << "skip one virtual or static obstacle"; continue; } double start_s = std::numeric_limits<double>::max(); double end_s = -std::numeric_limits<double>::max(); double start_l = std::numeric_limits<double>::max(); double end_l = -std::numeric_limits<double>::max(); for (const auto& p : obstacle->PerceptionPolygon().points()) { SLPoint sl_point; reference_line_info->reference_line().XYToSL(p, &sl_point); start_s = std::fmin(start_s, sl_point.s()); end_s = std::fmax(end_s, sl_point.s()); start_l = std::fmin(start_l, sl_point.l()); end_l = std::fmax(end_l, sl_point.l()); } if (reference_line_info->IsChangeLanePath()) { double left_width(0), right_width(0); reference_line_info->mutable_reference_line()->GetLaneWidth( (start_s + end_s) * 0.5, &left_width, &right_width); if (end_l < -right_width || start_l > left_width) { continue; } } // Raw estimation on whether same direction with ADC or not based on // prediction trajectory bool same_direction = true; if (obstacle->HasTrajectory()) { double obstacle_moving_direction = obstacle->Trajectory().trajectory_point(0).path_point().theta(); const auto& vehicle_state = reference_line_info->vehicle_state(); double vehicle_moving_direction = vehicle_state.heading(); if (vehicle_state.gear() == canbus::Chassis::GEAR_REVERSE) { vehicle_moving_direction = common::math::NormalizeAngle(vehicle_moving_direction + M_PI); } double heading_difference = std::abs(common::math::NormalizeAngle( obstacle_moving_direction - vehicle_moving_direction)); same_direction = heading_difference < (M_PI / 2.0); } // TODO(All) move to confs static constexpr double kSafeTimeOnSameDirection = 3.0; static constexpr double kSafeTimeOnOppositeDirection = 5.0; static constexpr double kForwardMinSafeDistanceOnSameDirection = 10.0; static constexpr double kBackwardMinSafeDistanceOnSameDirection = 10.0; static constexpr double kForwardMinSafeDistanceOnOppositeDirection = 50.0; static constexpr double kBackwardMinSafeDistanceOnOppositeDirection = 1.0; static constexpr double kDistanceBuffer = 0.5; double kForwardSafeDistance = 0.0; double kBackwardSafeDistance = 0.0; if (same_direction) { kForwardSafeDistance = std::fmax(kForwardMinSafeDistanceOnSameDirection, (ego_v - obstacle->speed()) * kSafeTimeOnSameDirection); kBackwardSafeDistance = std::fmax(kBackwardMinSafeDistanceOnSameDirection, (obstacle->speed() - ego_v) * kSafeTimeOnSameDirection); } else { kForwardSafeDistance = std::fmax(kForwardMinSafeDistanceOnOppositeDirection, (ego_v + obstacle->speed()) * kSafeTimeOnOppositeDirection); kBackwardSafeDistance = kBackwardMinSafeDistanceOnOppositeDirection; } if (HysteresisFilter(ego_start_s - end_s, kBackwardSafeDistance, kDistanceBuffer, obstacle->IsLaneChangeBlocking()) && HysteresisFilter(start_s - ego_end_s, kForwardSafeDistance, kDistanceBuffer, obstacle->IsLaneChangeBlocking())) { reference_line_info->path_decision() ->Find(obstacle->Id()) ->SetLaneChangeBlocking(true); ADEBUG << "Lane Change is blocked by obstacle" << obstacle->Id(); return false; } else { reference_line_info->path_decision() ->Find(obstacle->Id()) ->SetLaneChangeBlocking(false); } } return true; } bool LaneChangeDecider::IsPerceptionBlocked( const ReferenceLineInfo& reference_line_info, const double search_beam_length, const double search_beam_radius_intensity, const double search_range, const double is_block_angle_threshold) { const auto& vehicle_state = reference_line_info.vehicle_state(); const common::math::Vec2d adv_pos(vehicle_state.x(), vehicle_state.y()); const double adv_heading = vehicle_state.heading(); for (auto* obstacle : reference_line_info.path_decision().obstacles().Items()) { double left_most_angle = common::math::NormalizeAngle(adv_heading + 0.5 * search_range); double right_most_angle = common::math::NormalizeAngle(adv_heading - 0.5 * search_range); bool right_most_found = false; if (obstacle->IsVirtual()) { ADEBUG << "skip one virtual obstacle"; continue; } const auto& obstacle_polygon = obstacle->PerceptionPolygon(); for (double search_angle = 0.0; search_angle < search_range; search_angle += search_beam_radius_intensity) { common::math::Vec2d search_beam_end(search_beam_length, 0.0); const double beam_heading = common::math::NormalizeAngle( adv_heading - 0.5 * search_range + search_angle); search_beam_end.SelfRotate(beam_heading); search_beam_end += adv_pos; common::math::LineSegment2d search_beam(adv_pos, search_beam_end); if (!right_most_found && obstacle_polygon.HasOverlap(search_beam)) { right_most_found = true; right_most_angle = beam_heading; } if (right_most_found && !obstacle_polygon.HasOverlap(search_beam)) { left_most_angle = beam_heading; break; } } if (!right_most_found) { // obstacle is not in search range continue; } if (std::fabs(common::math::NormalizeAngle( left_most_angle - right_most_angle)) > is_block_angle_threshold) { return true; } } return false; } bool LaneChangeDecider::HysteresisFilter(const double obstacle_distance, const double safe_distance, const double distance_buffer, const bool is_obstacle_blocking) { if (is_obstacle_blocking) { return obstacle_distance < safe_distance + distance_buffer; } else { return obstacle_distance < safe_distance - distance_buffer; } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/lane_change_decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "lane_change_decider", srcs = ["lane_change_decider.cc"], hdrs = ["lane_change_decider.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/map/pnc_map", "//modules/planning/common:planning_context", "//modules/planning/common:planning_gflags", "//modules/planning/common:reference_line_info", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/tasks/deciders:decider_base", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_assessment_decider/path_assessment_decider.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/tasks/deciders/path_assessment_decider/path_assessment_decider.h" #include <algorithm> #include <limits> #include <memory> #include <utility> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common_msgs/basic_msgs/pnc_point.pb.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/tasks/deciders/path_bounds_decider/path_bounds_decider.h" #include "modules/planning/tasks/deciders/utils/path_decider_obstacle_utils.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::math::Box2d; using apollo::common::math::Polygon2d; using apollo::common::math::Vec2d; namespace { // PointDecision contains (s, PathPointType, distance to closest obstacle). using PathPointDecision = std::tuple<double, PathData::PathPointType, double>; constexpr double kMinObstacleArea = 1e-4; } // namespace PathAssessmentDecider::PathAssessmentDecider( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Decider(config, injector) {} Status PathAssessmentDecider::Process( Frame* const frame, ReferenceLineInfo* const reference_line_info) { // Sanity checks. CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); // skip path_assessment_decider if reused path if (FLAGS_enable_skip_path_tasks && reference_line_info->path_reusable()) { return Status::OK(); } const auto& candidate_path_data = reference_line_info->GetCandidatePathData(); if (candidate_path_data.empty()) { ADEBUG << "Candidate path data is empty."; } else { ADEBUG << "There are " << candidate_path_data.size() << " candidate paths"; } const auto& end_time0 = std::chrono::system_clock::now(); // 1. Remove invalid path. std::vector<PathData> valid_path_data; for (const auto& curr_path_data : candidate_path_data) { // RecordDebugInfo(curr_path_data, curr_path_data.path_label(), // reference_line_info); if (curr_path_data.path_label().find("fallback") != std::string::npos) { if (IsValidFallbackPath(*reference_line_info, curr_path_data)) { valid_path_data.push_back(curr_path_data); } } else { if (IsValidRegularPath(*reference_line_info, curr_path_data)) { valid_path_data.push_back(curr_path_data); } } } const auto& end_time1 = std::chrono::system_clock::now(); std::chrono::duration<double> diff = end_time1 - end_time0; ADEBUG << "Time for path validity checking: " << diff.count() * 1000 << " msec."; // 2. Analyze and add important info for speed decider to use size_t cnt = 0; const Obstacle* blocking_obstacle_on_selflane = nullptr; for (size_t i = 0; i != valid_path_data.size(); ++i) { auto& curr_path_data = valid_path_data[i]; if (curr_path_data.path_label().find("fallback") != std::string::npos) { // remove empty path_data. if (!curr_path_data.Empty()) { if (cnt != i) { valid_path_data[cnt] = curr_path_data; } ++cnt; } continue; } SetPathInfo(*reference_line_info, &curr_path_data); // Trim all the lane-borrowing paths so that it ends with an in-lane // position. if (curr_path_data.path_label().find("pullover") == std::string::npos) { TrimTailingOutLanePoints(&curr_path_data); } // find blocking_obstacle_on_selflane, to be used for lane selection later if (curr_path_data.path_label().find("self") != std::string::npos) { const auto blocking_obstacle_id = curr_path_data.blocking_obstacle_id(); blocking_obstacle_on_selflane = reference_line_info->path_decision()->Find(blocking_obstacle_id); } // remove empty path_data. if (!curr_path_data.Empty()) { if (cnt != i) { valid_path_data[cnt] = curr_path_data; } ++cnt; } // RecordDebugInfo(curr_path_data, curr_path_data.path_label(), // reference_line_info); ADEBUG << "For " << curr_path_data.path_label() << ", " << "path length = " << curr_path_data.frenet_frame_path().size(); } valid_path_data.resize(cnt); // If there is no valid path_data, exit. if (valid_path_data.empty()) { const std::string msg = "Neither regular nor fallback path is valid."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } ADEBUG << "There are " << valid_path_data.size() << " valid path data."; const auto& end_time2 = std::chrono::system_clock::now(); diff = end_time2 - end_time1; ADEBUG << "Time for path info labeling: " << diff.count() * 1000 << " msec."; // 3. Pick the optimal path. std::sort(valid_path_data.begin(), valid_path_data.end(), std::bind(ComparePathData, std::placeholders::_1, std::placeholders::_2, blocking_obstacle_on_selflane)); ADEBUG << "Using '" << valid_path_data.front().path_label() << "' path out of " << valid_path_data.size() << " path(s)"; if (valid_path_data.front().path_label().find("fallback") != std::string::npos) { FLAGS_static_obstacle_nudge_l_buffer = 0.8; } *(reference_line_info->mutable_path_data()) = valid_path_data.front(); reference_line_info->SetBlockingObstacle( valid_path_data.front().blocking_obstacle_id()); const auto& end_time3 = std::chrono::system_clock::now(); diff = end_time3 - end_time2; ADEBUG << "Time for optimal path selection: " << diff.count() * 1000 << " msec."; reference_line_info->SetCandidatePathData(std::move(valid_path_data)); // 4. Update necessary info for lane-borrow decider's future uses. // Update front static obstacle's info. auto* mutable_path_decider_status = injector_->planning_context() ->mutable_planning_status() ->mutable_path_decider(); if (reference_line_info->GetBlockingObstacle() != nullptr) { int front_static_obstacle_cycle_counter = mutable_path_decider_status->front_static_obstacle_cycle_counter(); mutable_path_decider_status->set_front_static_obstacle_cycle_counter( std::max(front_static_obstacle_cycle_counter, 0)); mutable_path_decider_status->set_front_static_obstacle_cycle_counter( std::min(front_static_obstacle_cycle_counter + 1, 10)); mutable_path_decider_status->set_front_static_obstacle_id( reference_line_info->GetBlockingObstacle()->Id()); } else { int front_static_obstacle_cycle_counter = mutable_path_decider_status->front_static_obstacle_cycle_counter(); mutable_path_decider_status->set_front_static_obstacle_cycle_counter( std::min(front_static_obstacle_cycle_counter, 0)); mutable_path_decider_status->set_front_static_obstacle_cycle_counter( std::max(front_static_obstacle_cycle_counter - 1, -10)); } // Update self-lane usage info. if (reference_line_info->path_data().path_label().find("self") != std::string::npos) { // && std::get<1>(reference_line_info->path_data() // .path_point_decision_guide() // .front()) == PathData::PathPointType::IN_LANE) int able_to_use_self_lane_counter = mutable_path_decider_status->able_to_use_self_lane_counter(); if (able_to_use_self_lane_counter < 0) { able_to_use_self_lane_counter = 0; } mutable_path_decider_status->set_able_to_use_self_lane_counter( std::min(able_to_use_self_lane_counter + 1, 10)); } else { mutable_path_decider_status->set_able_to_use_self_lane_counter(0); } // Update side-pass direction. if (mutable_path_decider_status->is_in_path_lane_borrow_scenario()) { bool left_borrow = false; bool right_borrow = false; const auto& path_decider_status = injector_->planning_context()->planning_status().path_decider(); for (const auto& lane_borrow_direction : path_decider_status.decided_side_pass_direction()) { if (lane_borrow_direction == PathDeciderStatus::LEFT_BORROW && reference_line_info->path_data().path_label().find("left") != std::string::npos) { left_borrow = true; } if (lane_borrow_direction == PathDeciderStatus::RIGHT_BORROW && reference_line_info->path_data().path_label().find("right") != std::string::npos) { right_borrow = true; } } mutable_path_decider_status->clear_decided_side_pass_direction(); if (right_borrow) { mutable_path_decider_status->add_decided_side_pass_direction( PathDeciderStatus::RIGHT_BORROW); } if (left_borrow) { mutable_path_decider_status->add_decided_side_pass_direction( PathDeciderStatus::LEFT_BORROW); } } const auto& end_time4 = std::chrono::system_clock::now(); diff = end_time4 - end_time3; ADEBUG << "Time for FSM state updating: " << diff.count() * 1000 << " msec."; // Plot the path in simulator for debug purpose. RecordDebugInfo(reference_line_info->path_data(), "Planning PathData", reference_line_info); return Status::OK(); } bool ComparePathData(const PathData& lhs, const PathData& rhs, const Obstacle* blocking_obstacle) { ADEBUG << "Comparing " << lhs.path_label() << " and " << rhs.path_label(); // Empty path_data is never the larger one. if (lhs.Empty()) { ADEBUG << "LHS is empty."; return false; } if (rhs.Empty()) { ADEBUG << "RHS is empty."; return true; } // Regular path goes before fallback path. bool lhs_is_regular = lhs.path_label().find("regular") != std::string::npos; bool rhs_is_regular = rhs.path_label().find("regular") != std::string::npos; if (lhs_is_regular != rhs_is_regular) { return lhs_is_regular; } // Select longer path. // If roughly same length, then select self-lane path. bool lhs_on_selflane = lhs.path_label().find("self") != std::string::npos; bool rhs_on_selflane = rhs.path_label().find("self") != std::string::npos; static constexpr double kSelfPathLengthComparisonTolerance = 15.0; static constexpr double kNeighborPathLengthComparisonTolerance = 25.0; double lhs_path_length = lhs.frenet_frame_path().back().s(); double rhs_path_length = rhs.frenet_frame_path().back().s(); if (lhs_on_selflane || rhs_on_selflane) { if (std::fabs(lhs_path_length - rhs_path_length) > kSelfPathLengthComparisonTolerance) { return lhs_path_length > rhs_path_length; } else { return lhs_on_selflane; } } else { if (std::fabs(lhs_path_length - rhs_path_length) > kNeighborPathLengthComparisonTolerance) { return lhs_path_length > rhs_path_length; } } // If roughly same length, and must borrow neighbor lane, // then prefer to borrow forward lane rather than reverse lane. int lhs_on_reverse = ContainsOutOnReverseLane(lhs.path_point_decision_guide()); int rhs_on_reverse = ContainsOutOnReverseLane(rhs.path_point_decision_guide()); // TODO(jiacheng): make this a flag. if (std::abs(lhs_on_reverse - rhs_on_reverse) > 6) { return lhs_on_reverse < rhs_on_reverse; } // For two lane-borrow directions, based on ADC's position, // select the more convenient one. if ((lhs.path_label().find("left") != std::string::npos && rhs.path_label().find("right") != std::string::npos) || (lhs.path_label().find("right") != std::string::npos && rhs.path_label().find("left") != std::string::npos)) { if (blocking_obstacle) { // select left/right path based on blocking_obstacle's position const double obstacle_l = (blocking_obstacle->PerceptionSLBoundary().start_l() + blocking_obstacle->PerceptionSLBoundary().end_l()) / 2; ADEBUG << "obstacle[" << blocking_obstacle->Id() << "] l[" << obstacle_l << "]"; return (obstacle_l > 0.0 ? (lhs.path_label().find("right") != std::string::npos) : (lhs.path_label().find("left") != std::string::npos)); } else { // select left/right path based on ADC's position double adc_l = lhs.frenet_frame_path().front().l(); if (adc_l < -1.0) { return lhs.path_label().find("right") != std::string::npos; } else if (adc_l > 1.0) { return lhs.path_label().find("left") != std::string::npos; } } } // If same length, both neighbor lane are forward, // then select the one that returns to in-lane earlier. static constexpr double kBackToSelfLaneComparisonTolerance = 20.0; int lhs_back_idx = GetBackToInLaneIndex(lhs.path_point_decision_guide()); int rhs_back_idx = GetBackToInLaneIndex(rhs.path_point_decision_guide()); double lhs_back_s = lhs.frenet_frame_path()[lhs_back_idx].s(); double rhs_back_s = rhs.frenet_frame_path()[rhs_back_idx].s(); if (std::fabs(lhs_back_s - rhs_back_s) > kBackToSelfLaneComparisonTolerance) { return lhs_back_idx < rhs_back_idx; } // If same length, both forward, back to inlane at same time, // select the left one to side-pass. bool lhs_on_leftlane = lhs.path_label().find("left") != std::string::npos; bool rhs_on_leftlane = rhs.path_label().find("left") != std::string::npos; if (lhs_on_leftlane != rhs_on_leftlane) { ADEBUG << "Select " << (lhs_on_leftlane ? "left" : "right") << " lane over " << (!lhs_on_leftlane ? "left" : "right") << " lane."; return lhs_on_leftlane; } // Otherwise, they are the same path, lhs is not < rhs. return false; } bool PathAssessmentDecider::IsValidRegularPath( const ReferenceLineInfo& reference_line_info, const PathData& path_data) { // Basic sanity checks. if (path_data.Empty()) { ADEBUG << path_data.path_label() << ": path data is empty."; return false; } // Check if the path is greatly off the reference line. if (IsGreatlyOffReferenceLine(path_data)) { ADEBUG << path_data.path_label() << ": ADC is greatly off reference line."; return false; } // Check if the path is greatly off the road. if (IsGreatlyOffRoad(reference_line_info, path_data)) { ADEBUG << path_data.path_label() << ": ADC is greatly off road."; return false; } // Check if there is any collision. if (IsCollidingWithStaticObstacles(reference_line_info, path_data)) { ADEBUG << path_data.path_label() << ": ADC has collision."; return false; } if (IsStopOnReverseNeighborLane(reference_line_info, path_data)) { ADEBUG << path_data.path_label() << ": stop at reverse neighbor lane"; return false; } return true; } bool PathAssessmentDecider::IsValidFallbackPath( const ReferenceLineInfo& reference_line_info, const PathData& path_data) { // Basic sanity checks. if (path_data.Empty()) { ADEBUG << "Fallback Path: path data is empty."; return false; } // Check if the path is greatly off the reference line. if (IsGreatlyOffReferenceLine(path_data)) { ADEBUG << "Fallback Path: ADC is greatly off reference line."; return false; } // Check if the path is greatly off the road. if (IsGreatlyOffRoad(reference_line_info, path_data)) { ADEBUG << "Fallback Path: ADC is greatly off road."; return false; } return true; } void PathAssessmentDecider::SetPathInfo( const ReferenceLineInfo& reference_line_info, PathData* const path_data) { // Go through every path_point, and label its: // - in-lane/out-of-lane info (side-pass or lane-change) // - distance to the closest obstacle. std::vector<PathPointDecision> path_decision; // 0. Initialize the path info. InitPathPointDecision(*path_data, &path_decision); // 1. Label caution types, differently for side-pass or lane-change. if (reference_line_info.IsChangeLanePath()) { // If lane-change, then label the lane-changing part to // be out-on-forward lane. SetPathPointType(reference_line_info, *path_data, true, &path_decision); } else { // Otherwise, only do the label for borrow-lane generated paths. if (path_data->path_label().find("fallback") == std::string::npos && path_data->path_label().find("self") == std::string::npos) { SetPathPointType(reference_line_info, *path_data, false, &path_decision); } } // SetObstacleDistance(reference_line_info, *path_data, &path_decision); path_data->SetPathPointDecisionGuide(std::move(path_decision)); } void PathAssessmentDecider::TrimTailingOutLanePoints( PathData* const path_data) { // Don't trim self-lane path or fallback path. if (path_data->path_label().find("fallback") != std::string::npos || path_data->path_label().find("self") != std::string::npos) { return; } // Trim. ADEBUG << "Trimming " << path_data->path_label(); auto frenet_path = path_data->frenet_frame_path(); auto path_point_decision = path_data->path_point_decision_guide(); CHECK_EQ(frenet_path.size(), path_point_decision.size()); while (!path_point_decision.empty() && std::get<1>(path_point_decision.back()) != PathData::PathPointType::IN_LANE) { if (std::get<1>(path_point_decision.back()) == PathData::PathPointType::OUT_ON_FORWARD_LANE) { ADEBUG << "Trimming out forward lane point"; } else if (std::get<1>(path_point_decision.back()) == PathData::PathPointType::OUT_ON_REVERSE_LANE) { ADEBUG << "Trimming out reverse lane point"; } else { ADEBUG << "Trimming unknown lane point"; } frenet_path.pop_back(); path_point_decision.pop_back(); } path_data->SetFrenetPath(std::move(frenet_path)); path_data->SetPathPointDecisionGuide(std::move(path_point_decision)); } bool PathAssessmentDecider::IsGreatlyOffReferenceLine( const PathData& path_data) { static constexpr double kOffReferenceLineThreshold = 20.0; const auto& frenet_path = path_data.frenet_frame_path(); for (const auto& frenet_path_point : frenet_path) { if (std::fabs(frenet_path_point.l()) > kOffReferenceLineThreshold) { ADEBUG << "Greatly off reference line at s = " << frenet_path_point.s() << ", with l = " << frenet_path_point.l(); return true; } } return false; } bool PathAssessmentDecider::IsGreatlyOffRoad( const ReferenceLineInfo& reference_line_info, const PathData& path_data) { static constexpr double kOffRoadThreshold = 10.0; const auto& frenet_path = path_data.frenet_frame_path(); for (const auto& frenet_path_point : frenet_path) { double road_left_width = 0.0; double road_right_width = 0.0; if (reference_line_info.reference_line().GetRoadWidth( frenet_path_point.s(), &road_left_width, &road_right_width)) { if (frenet_path_point.l() > road_left_width + kOffRoadThreshold || frenet_path_point.l() < -road_right_width - kOffRoadThreshold) { ADEBUG << "Greatly off-road at s = " << frenet_path_point.s() << ", with l = " << frenet_path_point.l(); return true; } } } return false; } bool PathAssessmentDecider::IsCollidingWithStaticObstacles( const ReferenceLineInfo& reference_line_info, const PathData& path_data) { // Get all obstacles and convert them into frenet-frame polygons. std::vector<Polygon2d> obstacle_polygons; const auto& indexed_obstacles = reference_line_info.path_decision().obstacles(); for (const auto* obstacle : indexed_obstacles.Items()) { // Filter out unrelated obstacles. if (!IsWithinPathDeciderScopeObstacle(*obstacle)) { continue; } // Ignore too small obstacles. const auto& obstacle_sl = obstacle->PerceptionSLBoundary(); if ((obstacle_sl.end_s() - obstacle_sl.start_s()) * (obstacle_sl.end_l() - obstacle_sl.start_l()) < kMinObstacleArea) { continue; } // Convert into polygon and save it. obstacle_polygons.push_back( Polygon2d({Vec2d(obstacle_sl.start_s(), obstacle_sl.start_l()), Vec2d(obstacle_sl.start_s(), obstacle_sl.end_l()), Vec2d(obstacle_sl.end_s(), obstacle_sl.end_l()), Vec2d(obstacle_sl.end_s(), obstacle_sl.start_l())})); } // Go through all the four corner points at every path pt, check collision. for (size_t i = 0; i < path_data.discretized_path().size(); ++i) { if (path_data.frenet_frame_path().back().s() - path_data.frenet_frame_path()[i].s() < (kNumExtraTailBoundPoint + 1) * kPathBoundsDeciderResolution) { break; } const auto& path_point = path_data.discretized_path()[i]; // Get the four corner points ABCD of ADC at every path point. const auto& vehicle_box = common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point); std::vector<Vec2d> ABCDpoints = vehicle_box.GetAllCorners(); for (const auto& corner_point : ABCDpoints) { // For each corner point, project it onto reference_line common::SLPoint curr_point_sl; if (!reference_line_info.reference_line().XYToSL(corner_point, &curr_point_sl)) { AERROR << "Failed to get the projection from point onto " "reference_line"; return true; } auto curr_point = Vec2d(curr_point_sl.s(), curr_point_sl.l()); // Check if it's in any polygon of other static obstacles. for (const auto& obstacle_polygon : obstacle_polygons) { if (obstacle_polygon.IsPointIn(curr_point)) { ADEBUG << "ADC is colliding with obstacle at path s = " << path_point.s(); return true; } } } } return false; } bool PathAssessmentDecider::IsStopOnReverseNeighborLane( const ReferenceLineInfo& reference_line_info, const PathData& path_data) { if (path_data.path_label().find("left") == std::string::npos && path_data.path_label().find("right") == std::string::npos) { return false; } std::vector<common::SLPoint> all_stop_point_sl = reference_line_info.GetAllStopDecisionSLPoint(); if (all_stop_point_sl.empty()) { return false; } double check_s = 0.0; static constexpr double kLookForwardBuffer = 5.0; // filter out sidepass stop fence const double adc_end_s = reference_line_info.AdcSlBoundary().end_s(); for (const auto& stop_point_sl : all_stop_point_sl) { if (stop_point_sl.s() - adc_end_s < kLookForwardBuffer) { continue; } check_s = stop_point_sl.s(); break; } if (check_s <= 0.0) { return false; } double lane_left_width = 0.0; double lane_right_width = 0.0; if (!reference_line_info.reference_line().GetLaneWidth( check_s, &lane_left_width, &lane_right_width)) { return false; } static constexpr double kSDelta = 0.3; common::SLPoint path_point_sl; for (const auto& frenet_path_point : path_data.frenet_frame_path()) { if (std::fabs(frenet_path_point.s() - check_s) < kSDelta) { path_point_sl.set_s(frenet_path_point.s()); path_point_sl.set_l(frenet_path_point.l()); } } ADEBUG << "path_point_sl[" << path_point_sl.s() << ", " << path_point_sl.l() << "] lane_left_width[" << lane_left_width << "] lane_right_width[" << lane_right_width << "]"; hdmap::Id neighbor_lane_id; double neighbor_lane_width = 0.0; if (path_data.path_label().find("left") != std::string::npos && path_point_sl.l() > lane_left_width) { if (reference_line_info.GetNeighborLaneInfo( ReferenceLineInfo::LaneType::LeftReverse, path_point_sl.s(), &neighbor_lane_id, &neighbor_lane_width)) { ADEBUG << "stop path point at LeftReverse neighbor lane[" << neighbor_lane_id.id() << "]"; return true; } } else if (path_data.path_label().find("right") != std::string::npos && path_point_sl.l() < -lane_right_width) { if (reference_line_info.GetNeighborLaneInfo( ReferenceLineInfo::LaneType::RightReverse, path_point_sl.s(), &neighbor_lane_id, &neighbor_lane_width)) { ADEBUG << "stop path point at RightReverse neighbor lane[" << neighbor_lane_id.id() << "]"; return true; } } return false; } void PathAssessmentDecider::InitPathPointDecision( const PathData& path_data, std::vector<PathPointDecision>* const path_point_decision) { // Sanity checks. CHECK_NOTNULL(path_point_decision); path_point_decision->clear(); // Go through every path point in path data, and initialize a // corresponding path point decision. for (const auto& frenet_path_point : path_data.frenet_frame_path()) { path_point_decision->emplace_back(frenet_path_point.s(), PathData::PathPointType::UNKNOWN, std::numeric_limits<double>::max()); } } void PathAssessmentDecider::SetPathPointType( const ReferenceLineInfo& reference_line_info, const PathData& path_data, const bool is_lane_change_path, std::vector<PathPointDecision>* const path_point_decision) { // Sanity checks. CHECK_NOTNULL(path_point_decision); // Go through every path_point, and add in-lane/out-of-lane info. const auto& discrete_path = path_data.discretized_path(); const auto& vehicle_config = common::VehicleConfigHelper::Instance()->GetConfig(); const double ego_length = vehicle_config.vehicle_param().length(); const double ego_width = vehicle_config.vehicle_param().width(); const double ego_back_to_center = vehicle_config.vehicle_param().back_edge_to_center(); const double ego_center_shift_distance = ego_length / 2.0 - ego_back_to_center; bool is_prev_point_out_lane = false; for (size_t i = 0; i < discrete_path.size(); ++i) { const auto& rear_center_path_point = discrete_path[i]; const double ego_theta = rear_center_path_point.theta(); Box2d ego_box({rear_center_path_point.x(), rear_center_path_point.y()}, ego_theta, ego_length, ego_width); Vec2d shift_vec{ego_center_shift_distance * std::cos(ego_theta), ego_center_shift_distance * std::sin(ego_theta)}; ego_box.Shift(shift_vec); SLBoundary ego_sl_boundary; if (!reference_line_info.reference_line().GetSLBoundary(ego_box, &ego_sl_boundary)) { ADEBUG << "Unable to get SL-boundary of ego-vehicle."; continue; } double lane_left_width = 0.0; double lane_right_width = 0.0; double middle_s = (ego_sl_boundary.start_s() + ego_sl_boundary.end_s()) / 2.0; if (reference_line_info.reference_line().GetLaneWidth( middle_s, &lane_left_width, &lane_right_width)) { // Rough sl boundary estimate using single point lane width double back_to_inlane_extra_buffer = 0.2; double in_and_out_lane_hysteresis_buffer = is_prev_point_out_lane ? back_to_inlane_extra_buffer : 0.0; // Check for lane-change and lane-borrow differently: if (is_lane_change_path) { // For lane-change path, only transitioning part is labeled as // out-of-lane. if (ego_sl_boundary.start_l() > lane_left_width || ego_sl_boundary.end_l() < -lane_right_width) { // This means that ADC hasn't started lane-change yet. std::get<1>((*path_point_decision)[i]) = PathData::PathPointType::IN_LANE; } else if (ego_sl_boundary.start_l() > -lane_right_width + back_to_inlane_extra_buffer && ego_sl_boundary.end_l() < lane_left_width - back_to_inlane_extra_buffer) { // This means that ADC has safely completed lane-change with margin. std::get<1>((*path_point_decision)[i]) = PathData::PathPointType::IN_LANE; } else { // ADC is right across two lanes. std::get<1>((*path_point_decision)[i]) = PathData::PathPointType::OUT_ON_FORWARD_LANE; } } else { // For lane-borrow path, as long as ADC is not on the lane of // reference-line, it is out on other lanes. It might even be // on reverse lane! if (ego_sl_boundary.end_l() > lane_left_width + in_and_out_lane_hysteresis_buffer || ego_sl_boundary.start_l() < -lane_right_width - in_and_out_lane_hysteresis_buffer) { if (path_data.path_label().find("reverse") != std::string::npos) { std::get<1>((*path_point_decision)[i]) = PathData::PathPointType::OUT_ON_REVERSE_LANE; } else if (path_data.path_label().find("forward") != std::string::npos) { std::get<1>((*path_point_decision)[i]) = PathData::PathPointType::OUT_ON_FORWARD_LANE; } else { std::get<1>((*path_point_decision)[i]) = PathData::PathPointType::UNKNOWN; } if (!is_prev_point_out_lane) { if (ego_sl_boundary.end_l() > lane_left_width + back_to_inlane_extra_buffer || ego_sl_boundary.start_l() < -lane_right_width - back_to_inlane_extra_buffer) { is_prev_point_out_lane = true; } } } else { // The path point is within the reference_line's lane. std::get<1>((*path_point_decision)[i]) = PathData::PathPointType::IN_LANE; if (is_prev_point_out_lane) { is_prev_point_out_lane = false; } } } } else { AERROR << "reference line not ready when setting path point guide"; return; } } } void PathAssessmentDecider::SetObstacleDistance( const ReferenceLineInfo& reference_line_info, const PathData& path_data, std::vector<PathPointDecision>* const path_point_decision) { // Sanity checks CHECK_NOTNULL(path_point_decision); // Get all obstacles and convert them into frenet-frame polygons. std::vector<Polygon2d> obstacle_polygons; const auto& indexed_obstacles = reference_line_info.path_decision().obstacles(); for (const auto* obstacle : indexed_obstacles.Items()) { // Filter out unrelated obstacles. if (!IsWithinPathDeciderScopeObstacle(*obstacle)) { continue; } // Convert into polygon and save it. const auto& obstacle_box = obstacle->PerceptionBoundingBox(); if (obstacle_box.area() < kMinObstacleArea) { continue; } obstacle_polygons.emplace_back(obstacle_box); } // Go through every path point, update closest obstacle info. const auto& discrete_path = path_data.discretized_path(); for (size_t i = 0; i < discrete_path.size(); ++i) { const auto& path_point = discrete_path[i]; // Get the bounding box of the vehicle at that point. const auto& vehicle_box = common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point); // Go through all the obstacle polygons, and update the min distance. double min_distance_to_obstacles = std::numeric_limits<double>::max(); for (const auto& obstacle_polygon : obstacle_polygons) { double distance_to_vehicle = obstacle_polygon.DistanceTo(vehicle_box); min_distance_to_obstacles = std::min(min_distance_to_obstacles, distance_to_vehicle); } std::get<2>((*path_point_decision)[i]) = min_distance_to_obstacles; } } void PathAssessmentDecider::RecordDebugInfo( const PathData& path_data, const std::string& debug_name, ReferenceLineInfo* const reference_line_info) { const auto& path_points = path_data.discretized_path(); auto* ptr_optimized_path = reference_line_info->mutable_debug()->mutable_planning_data()->add_path(); ptr_optimized_path->set_name(debug_name); ptr_optimized_path->mutable_path_point()->CopyFrom( {path_points.begin(), path_points.end()}); } int ContainsOutOnReverseLane( const std::vector<PathPointDecision>& path_point_decision) { int ret = 0; for (const auto& curr_decision : path_point_decision) { if (std::get<1>(curr_decision) == PathData::PathPointType::OUT_ON_REVERSE_LANE) { ++ret; } } return ret; } int GetBackToInLaneIndex( const std::vector<PathPointDecision>& path_point_decision) { // ACHECK(!path_point_decision.empty()); // ACHECK(std::get<1>(path_point_decision.back()) == // PathData::PathPointType::IN_LANE); for (int i = static_cast<int>(path_point_decision.size()) - 1; i >= 0; --i) { if (std::get<1>(path_point_decision[i]) != PathData::PathPointType::IN_LANE) { return i; } } return 0; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_assessment_decider/path_assessment_decider.h
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include <string> #include <tuple> #include <vector> #include "modules/planning/proto/planning_config.pb.h" #include "modules/planning/tasks/deciders/decider.h" namespace apollo { namespace planning { class PathAssessmentDecider : public Decider { public: PathAssessmentDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); private: /** @brief Every time when Process function is called, it will: * 1. Check the validity of regular/fallback paths, and remove if invalid. * 2. Analyze the paths and label necessary info for speed planning use. * 3. Pick the best one and update it into the reference_line. */ common::Status Process(Frame* const frame, ReferenceLineInfo* const reference_line_info) override; ///////////////////////////////////////////////////////////////////////////// // Below are functions called when executing PathAssessmentDecider. bool IsValidRegularPath(const ReferenceLineInfo& reference_line_info, const PathData& path_data); bool IsValidFallbackPath(const ReferenceLineInfo& reference_line_info, const PathData& path_data); void SetPathInfo(const ReferenceLineInfo& reference_line_info, PathData* const path_data); void TrimTailingOutLanePoints(PathData* const path_data); ///////////////////////////////////////////////////////////////////////////// // Below are functions used when checking validity of path. bool IsGreatlyOffReferenceLine(const PathData& path_data); bool IsGreatlyOffRoad(const ReferenceLineInfo& reference_line_info, const PathData& path_data); bool IsCollidingWithStaticObstacles( const ReferenceLineInfo& reference_line_info, const PathData& path_data); bool IsStopOnReverseNeighborLane(const ReferenceLineInfo& reference_line_info, const PathData& path_data); // * @brief Check if the path ever returns to the self-lane. // * @param reference_line_info // * @param path_data // * @return It returns the last index that the path returns to self-lane. // * If the path always stays within self-lane, it returns the size()-1. // * If the path never returns to self-lane, returns -1. // int IsReturningToSelfLane( // const ReferenceLineInfo& reference_line_info, const PathData& path_data); ///////////////////////////////////////////////////////////////////////////// // Below are functions used for setting path point type info. void InitPathPointDecision( const PathData& path_data, std::vector<std::tuple<double, PathData::PathPointType, double>>* const path_point_decision); void SetPathPointType( const ReferenceLineInfo& reference_line_info, const PathData& path_data, const bool is_lane_change_path, std::vector<std::tuple<double, PathData::PathPointType, double>>* const path_point_decision); void SetObstacleDistance( const ReferenceLineInfo& reference_line_info, const PathData& path_data, std::vector<std::tuple<double, PathData::PathPointType, double>>* const path_point_decision); void RecordDebugInfo(const PathData& path_data, const std::string& debug_name, ReferenceLineInfo* const reference_line_info); }; ///////////////////////////////////////////////////////////////////////////// // Below are helper functions. int ContainsOutOnReverseLane( const std::vector<std::tuple<double, PathData::PathPointType, double>>& path_point_decision); int GetBackToInLaneIndex( const std::vector<std::tuple<double, PathData::PathPointType, double>>& path_point_decision); bool ComparePathData(const PathData& lhs, const PathData& rhs, const Obstacle* blocking_obstacle); } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/path_assessment_decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "path_assessment_decider", srcs = ["path_assessment_decider.cc"], hdrs = ["path_assessment_decider.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/planning/common:planning_context", "//modules/planning/common:planning_gflags", "//modules/planning/common:reference_line_info", "//modules/planning/tasks/deciders:decider_base", "//modules/planning/tasks/deciders/path_bounds_decider", "//modules/planning/tasks/deciders/utils:path_decider_obstacle_utils", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/creep_decider/creep_decider_test.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/creep_decider/creep_decider.h" #include "gtest/gtest.h" #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { class CreepDeciderTest : public ::testing::Test { public: virtual void SetUp() { config_.set_task_type(TaskConfig::CREEP_DECIDER); config_.mutable_creep_decider_config(); injector_ = std::make_shared<DependencyInjector>(); } virtual void TearDown() {} protected: TaskConfig config_; std::shared_ptr<DependencyInjector> injector_; }; TEST_F(CreepDeciderTest, Init) { CreepDecider creep_decider(config_, injector_); EXPECT_EQ(creep_decider.Name(), TaskConfig::TaskType_Name(config_.task_type())); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/creep_decider/creep_decider.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/creep_decider/creep_decider.h" #include <memory> #include <string> #include <vector> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/util/common.h" #include "modules/planning/scenarios/util/util.h" namespace apollo { namespace planning { using apollo::common::Status; using apollo::hdmap::PathOverlap; CreepDecider::CreepDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Decider(config, injector) { ACHECK(config_.has_creep_decider_config()); } Status CreepDecider::Process(Frame* frame, ReferenceLineInfo* reference_line_info) { CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); double stop_line_s = 0.0; std::string current_overlap_id; // stop sign const std::string stop_sign_overlap_id = injector_->planning_context() ->planning_status() .stop_sign() .current_stop_sign_overlap_id(); // traffic light std::string current_traffic_light_overlap_id; if (injector_->planning_context() ->planning_status() .traffic_light() .current_traffic_light_overlap_id_size() > 0) { current_traffic_light_overlap_id = injector_->planning_context() ->planning_status() .traffic_light() .current_traffic_light_overlap_id(0); } // yield sign std::string yield_sign_overlap_id; if (injector_->planning_context() ->planning_status() .yield_sign() .current_yield_sign_overlap_id_size() > 0) { yield_sign_overlap_id = injector_->planning_context() ->planning_status() .yield_sign() .current_yield_sign_overlap_id(0); } if (!stop_sign_overlap_id.empty()) { // get overlap along reference line PathOverlap* current_stop_sign_overlap = scenario::util::GetOverlapOnReferenceLine(*reference_line_info, stop_sign_overlap_id, ReferenceLineInfo::STOP_SIGN); if (current_stop_sign_overlap) { stop_line_s = current_stop_sign_overlap->end_s + FindCreepDistance(*frame, *reference_line_info); current_overlap_id = current_stop_sign_overlap->object_id; } } else if (!current_traffic_light_overlap_id.empty()) { // get overlap along reference line PathOverlap* current_traffic_light_overlap = scenario::util::GetOverlapOnReferenceLine( *reference_line_info, current_traffic_light_overlap_id, ReferenceLineInfo::SIGNAL); if (current_traffic_light_overlap) { stop_line_s = current_traffic_light_overlap->end_s + FindCreepDistance(*frame, *reference_line_info); current_overlap_id = current_traffic_light_overlap_id; } } else if (!yield_sign_overlap_id.empty()) { // 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) { stop_line_s = current_yield_sign_overlap->end_s + FindCreepDistance(*frame, *reference_line_info); current_overlap_id = yield_sign_overlap_id; } } if (stop_line_s > 0.0) { std::string virtual_obstacle_id = CREEP_VO_ID_PREFIX + current_overlap_id; const double creep_stop_s = stop_line_s + FindCreepDistance(*frame, *reference_line_info); const std::vector<std::string> wait_for_obstacles; util::BuildStopDecision(virtual_obstacle_id, creep_stop_s, config_.creep_decider_config().stop_distance(), StopReasonCode::STOP_REASON_CREEPER, wait_for_obstacles, "CreepDecider", frame, reference_line_info); } return Status::OK(); } double CreepDecider::FindCreepDistance( const Frame& frame, const ReferenceLineInfo& reference_line_info) { // more delicate design of creep distance return 2.0; } bool CreepDecider::CheckCreepDone(const Frame& frame, const ReferenceLineInfo& reference_line_info, const double traffic_sign_overlap_end_s, const double wait_time_sec, const double timeout_sec) { const auto& creep_config = config_.creep_decider_config(); bool creep_done = false; double creep_stop_s = traffic_sign_overlap_end_s + FindCreepDistance(frame, reference_line_info); const double distance = creep_stop_s - reference_line_info.AdcSlBoundary().end_s(); if (distance < creep_config.max_valid_stop_distance() || wait_time_sec >= timeout_sec) { bool all_far_away = true; for (auto* obstacle : reference_line_info.path_decision().obstacles().Items()) { if (obstacle->IsVirtual() || obstacle->IsStatic()) { continue; } if (obstacle->reference_line_st_boundary().min_t() < creep_config.min_boundary_t()) { 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 if (obstacle_traveled_s < kepsilon && obstacle->reference_line_st_boundary().min_t() < creep_config.ignore_max_st_min_t() && obstacle->reference_line_st_boundary().min_s() > creep_config.ignore_min_st_min_s()) { continue; } all_far_away = false; break; } } auto* creep_decider_status = injector_->planning_context() ->mutable_planning_status() ->mutable_creep_decider(); int creep_clear_counter = creep_decider_status->creep_clear_counter(); creep_clear_counter = all_far_away ? creep_clear_counter + 1 : 0; if (creep_clear_counter >= 5) { creep_clear_counter = 0; // reset creep_done = true; } // use PlanningContext instead of static counter for multi-ADC creep_decider_status->set_creep_clear_counter(creep_clear_counter); } return creep_done; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/creep_decider/creep_decider.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <memory> #include "cyber/common/macros.h" #include "modules/map/pnc_map/path.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/reference_line_info.h" #include "modules/planning/tasks/deciders/decider.h" namespace apollo { namespace planning { class CreepDecider : public Decider { public: CreepDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); apollo::common::Status Process( Frame* frame, ReferenceLineInfo* reference_line_info) override; bool CheckCreepDone(const Frame& frame, const ReferenceLineInfo& reference_line_info, const double stop_sign_overlap_end_s, const double wait_time_sec, const double timeout_sec); double FindCreepDistance(const Frame& frame, const ReferenceLineInfo& reference_line_info); private: static constexpr const char* CREEP_VO_ID_PREFIX = "CREEP_"; common::TrajectoryPoint adc_planning_start_point_; hdmap::Lane curr_lane_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/creep_decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "creep_decider", srcs = ["creep_decider.cc"], hdrs = ["creep_decider.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/planning/common:planning_context", "//modules/planning/common:reference_line_info", "//modules/planning/common/util:common_lib", "//modules/planning/common/util:util_lib", "//modules/planning/scenarios/util:scenario_util_lib", "//modules/planning/tasks/deciders:decider_base", ], ) cc_test( name = "creep_decider_test", size = "small", srcs = ["creep_decider_test.cc"], deps = [ "creep_decider", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/speed_decider/speed_decider.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/speed_decider/speed_decider.h" #include <algorithm> #include <memory> #include "cyber/common/log.h" #include "cyber/time/clock.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" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/common_msgs/planning_msgs/decision.pb.h" #include "modules/planning/tasks/utils/st_gap_estimator.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::VehicleConfigHelper; using apollo::common::math::Vec2d; using apollo::cyber::Clock; using apollo::perception::PerceptionObstacle; SpeedDecider::SpeedDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Task(config, injector) {} common::Status SpeedDecider::Execute(Frame* frame, ReferenceLineInfo* reference_line_info) { Task::Execute(frame, reference_line_info); init_point_ = frame_->PlanningStartPoint(); adc_sl_boundary_ = reference_line_info_->AdcSlBoundary(); reference_line_ = &reference_line_info_->reference_line(); if (!MakeObjectDecision(reference_line_info->speed_data(), reference_line_info->path_decision()) .ok()) { const std::string msg = "Get object decision by speed profile failed."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } return Status::OK(); } SpeedDecider::STLocation SpeedDecider::GetSTLocation( const PathDecision* const path_decision, const SpeedData& speed_profile, const STBoundary& st_boundary) const { if (st_boundary.IsEmpty()) { return BELOW; } STLocation st_location = BELOW; bool st_position_set = false; const double start_t = st_boundary.min_t(); const double end_t = st_boundary.max_t(); for (size_t i = 0; i + 1 < speed_profile.size(); ++i) { const STPoint curr_st(speed_profile[i].s(), speed_profile[i].t()); const STPoint next_st(speed_profile[i + 1].s(), speed_profile[i + 1].t()); if (curr_st.t() < start_t && next_st.t() < start_t) { continue; } if (curr_st.t() > end_t) { break; } if (!FLAGS_use_st_drivable_boundary) { common::math::LineSegment2d speed_line(curr_st, next_st); if (st_boundary.HasOverlap(speed_line)) { ADEBUG << "speed profile cross st_boundaries."; st_location = CROSS; if (!FLAGS_use_st_drivable_boundary) { if (st_boundary.boundary_type() == STBoundary::BoundaryType::KEEP_CLEAR) { if (!CheckKeepClearCrossable(path_decision, speed_profile, st_boundary)) { st_location = BELOW; } } } break; } } // note: st_position can be calculated by checking two st points once // but we need iterate all st points to make sure there is no CROSS if (!st_position_set) { if (start_t < next_st.t() && curr_st.t() < end_t) { STPoint bd_point_front = st_boundary.upper_points().front(); double side = common::math::CrossProd(bd_point_front, curr_st, next_st); st_location = side < 0.0 ? ABOVE : BELOW; st_position_set = true; } } } return st_location; } bool SpeedDecider::CheckKeepClearCrossable( const PathDecision* const path_decision, const SpeedData& speed_profile, const STBoundary& keep_clear_st_boundary) const { bool keep_clear_crossable = true; const auto& last_speed_point = speed_profile.back(); double last_speed_point_v = 0.0; if (last_speed_point.has_v()) { last_speed_point_v = last_speed_point.v(); } else { const size_t len = speed_profile.size(); if (len > 1) { const auto& last_2nd_speed_point = speed_profile[len - 2]; last_speed_point_v = (last_speed_point.s() - last_2nd_speed_point.s()) / (last_speed_point.t() - last_2nd_speed_point.t()); } } static constexpr double kKeepClearSlowSpeed = 2.5; // m/s ADEBUG << "last_speed_point_s[" << last_speed_point.s() << "] st_boundary.max_s[" << keep_clear_st_boundary.max_s() << "] last_speed_point_v[" << last_speed_point_v << "]"; if (last_speed_point.s() <= keep_clear_st_boundary.max_s() && last_speed_point_v < kKeepClearSlowSpeed) { keep_clear_crossable = false; } return keep_clear_crossable; } bool SpeedDecider::CheckKeepClearBlocked( const PathDecision* const path_decision, const Obstacle& keep_clear_obstacle) const { bool keep_clear_blocked = false; // check if overlap with other stop wall for (const auto* obstacle : path_decision->obstacles().Items()) { if (obstacle->Id() == keep_clear_obstacle.Id()) { continue; } const double obstacle_start_s = obstacle->PerceptionSLBoundary().start_s(); const double adc_length = VehicleConfigHelper::GetConfig().vehicle_param().length(); const double distance = obstacle_start_s - keep_clear_obstacle.PerceptionSLBoundary().end_s(); if (obstacle->IsBlockingObstacle() && distance > 0 && distance < (adc_length / 2)) { keep_clear_blocked = true; break; } } return keep_clear_blocked; } bool SpeedDecider::IsFollowTooClose(const Obstacle& obstacle) const { if (!obstacle.IsBlockingObstacle()) { return false; } if (obstacle.path_st_boundary().min_t() > 0.0) { return false; } const double obs_speed = obstacle.speed(); const double ego_speed = init_point_.v(); if (obs_speed > ego_speed) { return false; } const double distance = obstacle.path_st_boundary().min_s() - FLAGS_min_stop_distance_obstacle; static constexpr double lane_follow_max_decel = 3.0; static constexpr double lane_change_max_decel = 3.0; auto* planning_status = injector_->planning_context() ->mutable_planning_status() ->mutable_change_lane(); double distance_numerator = std::pow((ego_speed - obs_speed), 2) * 0.5; double distance_denominator = lane_follow_max_decel; if (planning_status->has_status() && planning_status->status() == ChangeLaneStatus::IN_CHANGE_LANE) { distance_denominator = lane_change_max_decel; } return distance < distance_numerator / distance_denominator; } Status SpeedDecider::MakeObjectDecision( const SpeedData& speed_profile, PathDecision* const path_decision) const { if (speed_profile.size() < 2) { const std::string msg = "dp_st_graph failed to get speed profile."; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } for (const auto* obstacle : path_decision->obstacles().Items()) { auto* mutable_obstacle = path_decision->Find(obstacle->Id()); const auto& boundary = mutable_obstacle->path_st_boundary(); if (boundary.IsEmpty() || boundary.max_s() < 0.0 || boundary.max_t() < 0.0 || boundary.min_t() >= speed_profile.back().t()) { AppendIgnoreDecision(mutable_obstacle); continue; } if (obstacle->HasLongitudinalDecision()) { AppendIgnoreDecision(mutable_obstacle); continue; } // for Virtual obstacle, skip if center point NOT "on lane" if (obstacle->IsVirtual()) { const auto& obstacle_box = obstacle->PerceptionBoundingBox(); if (!reference_line_->IsOnLane(obstacle_box.center())) { continue; } } // always STOP for pedestrian if (CheckStopForPedestrian(*mutable_obstacle)) { ObjectDecisionType stop_decision; if (CreateStopDecision(*mutable_obstacle, &stop_decision, -FLAGS_min_stop_distance_obstacle)) { mutable_obstacle->AddLongitudinalDecision("dp_st_graph/pedestrian", stop_decision); } continue; } auto location = GetSTLocation(path_decision, speed_profile, boundary); if (!FLAGS_use_st_drivable_boundary) { if (boundary.boundary_type() == STBoundary::BoundaryType::KEEP_CLEAR) { if (CheckKeepClearBlocked(path_decision, *obstacle)) { location = BELOW; } } } switch (location) { case BELOW: if (boundary.boundary_type() == STBoundary::BoundaryType::KEEP_CLEAR) { ObjectDecisionType stop_decision; if (CreateStopDecision(*mutable_obstacle, &stop_decision, 0.0)) { mutable_obstacle->AddLongitudinalDecision("dp_st_graph/keep_clear", stop_decision); } } else if (CheckIsFollow(*obstacle, boundary)) { // stop for low_speed decelerating if (IsFollowTooClose(*mutable_obstacle)) { ObjectDecisionType stop_decision; if (CreateStopDecision(*mutable_obstacle, &stop_decision, -FLAGS_min_stop_distance_obstacle)) { mutable_obstacle->AddLongitudinalDecision("dp_st_graph/too_close", stop_decision); } } else { // high speed or low speed accelerating // FOLLOW decision ObjectDecisionType follow_decision; if (CreateFollowDecision(*mutable_obstacle, &follow_decision)) { mutable_obstacle->AddLongitudinalDecision("dp_st_graph", follow_decision); } } } else { // YIELD decision ObjectDecisionType yield_decision; if (CreateYieldDecision(*mutable_obstacle, &yield_decision)) { mutable_obstacle->AddLongitudinalDecision("dp_st_graph", yield_decision); } } break; case ABOVE: if (boundary.boundary_type() == STBoundary::BoundaryType::KEEP_CLEAR) { ObjectDecisionType ignore; ignore.mutable_ignore(); mutable_obstacle->AddLongitudinalDecision("dp_st_graph", ignore); } else { // OVERTAKE decision ObjectDecisionType overtake_decision; if (CreateOvertakeDecision(*mutable_obstacle, &overtake_decision)) { mutable_obstacle->AddLongitudinalDecision("dp_st_graph/overtake", overtake_decision); } } break; case CROSS: if (mutable_obstacle->IsBlockingObstacle()) { ObjectDecisionType stop_decision; if (CreateStopDecision(*mutable_obstacle, &stop_decision, -FLAGS_min_stop_distance_obstacle)) { mutable_obstacle->AddLongitudinalDecision("dp_st_graph/cross", stop_decision); } const std::string msg = absl::StrCat( "Failed to find a solution for crossing obstacle: ", mutable_obstacle->Id()); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } break; default: AERROR << "Unknown position:" << location; } AppendIgnoreDecision(mutable_obstacle); } return Status::OK(); } void SpeedDecider::AppendIgnoreDecision(Obstacle* obstacle) const { ObjectDecisionType ignore_decision; ignore_decision.mutable_ignore(); if (!obstacle->HasLongitudinalDecision()) { obstacle->AddLongitudinalDecision("dp_st_graph", ignore_decision); } if (!obstacle->HasLateralDecision()) { obstacle->AddLateralDecision("dp_st_graph", ignore_decision); } } bool SpeedDecider::CreateStopDecision(const Obstacle& obstacle, ObjectDecisionType* const stop_decision, double stop_distance) const { const auto& boundary = obstacle.path_st_boundary(); // TODO(all): this is a bug! Cannot mix reference s and path s! // Replace boundary.min_s() with computed reference line s // fence is set according to reference line s. double fence_s = adc_sl_boundary_.end_s() + boundary.min_s() + stop_distance; if (boundary.boundary_type() == STBoundary::BoundaryType::KEEP_CLEAR) { fence_s = obstacle.PerceptionSLBoundary().start_s(); } const double main_stop_s = reference_line_info_->path_decision()->stop_reference_line_s(); if (main_stop_s < fence_s) { ADEBUG << "Stop fence is further away, ignore."; return false; } const auto fence_point = reference_line_->GetReferencePoint(fence_s); // set STOP decision auto* stop = stop_decision->mutable_stop(); stop->set_distance_s(stop_distance); auto* stop_point = stop->mutable_stop_point(); stop_point->set_x(fence_point.x()); stop_point->set_y(fence_point.y()); stop_point->set_z(0.0); stop->set_stop_heading(fence_point.heading()); if (boundary.boundary_type() == STBoundary::BoundaryType::KEEP_CLEAR) { stop->set_reason_code(StopReasonCode::STOP_REASON_CLEAR_ZONE); } PerceptionObstacle::Type obstacle_type = obstacle.Perception().type(); ADEBUG << "STOP: obstacle_id[" << obstacle.Id() << "] obstacle_type[" << PerceptionObstacle_Type_Name(obstacle_type) << "]"; return true; } bool SpeedDecider::CreateFollowDecision( const Obstacle& obstacle, ObjectDecisionType* const follow_decision) const { const double follow_speed = init_point_.v(); const double follow_distance_s = -StGapEstimator::EstimateProperFollowingGap(follow_speed); const auto& boundary = obstacle.path_st_boundary(); const double reference_s = adc_sl_boundary_.end_s() + boundary.min_s() + follow_distance_s; const double main_stop_s = reference_line_info_->path_decision()->stop_reference_line_s(); if (main_stop_s < reference_s) { ADEBUG << "Follow reference_s is further away, ignore."; return false; } auto ref_point = reference_line_->GetReferencePoint(reference_s); // set FOLLOW decision auto* follow = follow_decision->mutable_follow(); follow->set_distance_s(follow_distance_s); auto* fence_point = follow->mutable_fence_point(); fence_point->set_x(ref_point.x()); fence_point->set_y(ref_point.y()); fence_point->set_z(0.0); follow->set_fence_heading(ref_point.heading()); PerceptionObstacle::Type obstacle_type = obstacle.Perception().type(); ADEBUG << "FOLLOW: obstacle_id[" << obstacle.Id() << "] obstacle_type[" << PerceptionObstacle_Type_Name(obstacle_type) << "]"; return true; } bool SpeedDecider::CreateYieldDecision( const Obstacle& obstacle, ObjectDecisionType* const yield_decision) const { PerceptionObstacle::Type obstacle_type = obstacle.Perception().type(); double yield_distance = StGapEstimator::EstimateProperYieldingGap(); const auto& obstacle_boundary = obstacle.path_st_boundary(); const double yield_distance_s = std::max(-obstacle_boundary.min_s(), -yield_distance); const double reference_line_fence_s = adc_sl_boundary_.end_s() + obstacle_boundary.min_s() + yield_distance_s; const double main_stop_s = reference_line_info_->path_decision()->stop_reference_line_s(); if (main_stop_s < reference_line_fence_s) { ADEBUG << "Yield reference_s is further away, ignore."; return false; } auto ref_point = reference_line_->GetReferencePoint(reference_line_fence_s); // set YIELD decision auto* yield = yield_decision->mutable_yield(); yield->set_distance_s(yield_distance_s); yield->mutable_fence_point()->set_x(ref_point.x()); yield->mutable_fence_point()->set_y(ref_point.y()); yield->mutable_fence_point()->set_z(0.0); yield->set_fence_heading(ref_point.heading()); ADEBUG << "YIELD: obstacle_id[" << obstacle.Id() << "] obstacle_type[" << PerceptionObstacle_Type_Name(obstacle_type) << "]"; return true; } bool SpeedDecider::CreateOvertakeDecision( const Obstacle& obstacle, ObjectDecisionType* const overtake_decision) const { const auto& velocity = obstacle.Perception().velocity(); const double obstacle_speed = common::math::Vec2d::CreateUnitVec2d(init_point_.path_point().theta()) .InnerProd(Vec2d(velocity.x(), velocity.y())); const double overtake_distance_s = StGapEstimator::EstimateProperOvertakingGap(obstacle_speed, init_point_.v()); const auto& boundary = obstacle.path_st_boundary(); const double reference_line_fence_s = adc_sl_boundary_.end_s() + boundary.min_s() + overtake_distance_s; const double main_stop_s = reference_line_info_->path_decision()->stop_reference_line_s(); if (main_stop_s < reference_line_fence_s) { ADEBUG << "Overtake reference_s is further away, ignore."; return false; } auto ref_point = reference_line_->GetReferencePoint(reference_line_fence_s); // set OVERTAKE decision auto* overtake = overtake_decision->mutable_overtake(); overtake->set_distance_s(overtake_distance_s); overtake->mutable_fence_point()->set_x(ref_point.x()); overtake->mutable_fence_point()->set_y(ref_point.y()); overtake->mutable_fence_point()->set_z(0.0); overtake->set_fence_heading(ref_point.heading()); PerceptionObstacle::Type obstacle_type = obstacle.Perception().type(); ADEBUG << "OVERTAKE: obstacle_id[" << obstacle.Id() << "] obstacle_type[" << PerceptionObstacle_Type_Name(obstacle_type) << "]"; return true; } bool SpeedDecider::CheckIsFollow(const Obstacle& obstacle, const STBoundary& boundary) const { const double obstacle_l_distance = std::min(std::fabs(obstacle.PerceptionSLBoundary().start_l()), std::fabs(obstacle.PerceptionSLBoundary().end_l())); if (obstacle_l_distance > FLAGS_follow_min_obs_lateral_distance) { return false; } // move towards adc if (boundary.bottom_left_point().s() > boundary.bottom_right_point().s()) { return false; } static constexpr double kFollowTimeEpsilon = 1e-3; static constexpr double kFollowCutOffTime = 0.5; if (boundary.min_t() > kFollowCutOffTime || boundary.max_t() < kFollowTimeEpsilon) { return false; } // cross lane but be moving to different direction if (boundary.max_t() - boundary.min_t() < FLAGS_follow_min_time_sec) { return false; } return true; } bool SpeedDecider::CheckStopForPedestrian(const Obstacle& obstacle) const { const auto& perception_obstacle = obstacle.Perception(); if (perception_obstacle.type() != PerceptionObstacle::PEDESTRIAN) { return false; } const auto& obstacle_sl_boundary = obstacle.PerceptionSLBoundary(); if (obstacle_sl_boundary.end_s() < adc_sl_boundary_.start_s()) { return false; } // read pedestrian stop time from PlanningContext auto* mutable_speed_decider_status = injector_->planning_context() ->mutable_planning_status() ->mutable_speed_decider(); std::unordered_map<std::string, double> stop_time_map; for (const auto& pedestrian_stop_time : mutable_speed_decider_status->pedestrian_stop_time()) { stop_time_map[pedestrian_stop_time.obstacle_id()] = pedestrian_stop_time.stop_timestamp_sec(); } const std::string& obstacle_id = obstacle.Id(); // update stop timestamp on static pedestrian for watch timer // check on stop timer for static pedestrians static constexpr double kSDistanceStartTimer = 10.0; static constexpr double kMaxStopSpeed = 0.3; static constexpr double kPedestrianStopTimeout = 4.0; bool result = true; if (obstacle.path_st_boundary().min_s() < kSDistanceStartTimer) { const auto obstacle_speed = std::hypot(perception_obstacle.velocity().x(), perception_obstacle.velocity().y()); if (obstacle_speed > kMaxStopSpeed) { stop_time_map.erase(obstacle_id); } else { if (stop_time_map.count(obstacle_id) == 0) { // add timestamp stop_time_map[obstacle_id] = Clock::NowInSeconds(); ADEBUG << "add timestamp: obstacle_id[" << obstacle_id << "] timestamp[" << Clock::NowInSeconds() << "]"; } else { // check timeout double stop_timer = Clock::NowInSeconds() - stop_time_map[obstacle_id]; ADEBUG << "stop_timer: obstacle_id[" << obstacle_id << "] stop_timer[" << stop_timer << "]"; if (stop_timer >= kPedestrianStopTimeout) { result = false; } } } } // write pedestrian stop time to PlanningContext mutable_speed_decider_status->mutable_pedestrian_stop_time()->Clear(); for (const auto& stop_time : stop_time_map) { auto pedestrian_stop_time = mutable_speed_decider_status->add_pedestrian_stop_time(); pedestrian_stop_time->set_obstacle_id(stop_time.first); pedestrian_stop_time->set_stop_timestamp_sec(stop_time.second); } return result; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/speed_decider/speed_decider.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <memory> #include <string> #include <unordered_map> #include "modules/planning/common/frame.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/tasks/task.h" namespace apollo { namespace planning { class SpeedDecider : public Task { public: SpeedDecider(const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector); common::Status Execute(Frame* frame, ReferenceLineInfo* reference_line_info) override; private: enum STLocation { ABOVE = 1, BELOW = 2, CROSS = 3, }; STLocation GetSTLocation(const PathDecision* const path_decision, const SpeedData& speed_profile, const STBoundary& st_boundary) const; bool CheckKeepClearCrossable(const PathDecision* const path_decision, const SpeedData& speed_profile, const STBoundary& keep_clear_st_boundary) const; bool CheckKeepClearBlocked(const PathDecision* const path_decision, const Obstacle& keep_clear_obstacle) const; /** * @brief check if the ADC should follow an obstacle by examing the *StBoundary of the obstacle. * @param boundary The boundary of the obstacle. * @return true if the ADC believe it should follow the obstacle, and * false otherwise. **/ bool CheckIsFollow(const Obstacle& obstacle, const STBoundary& boundary) const; bool CheckStopForPedestrian(const Obstacle& obstacle) const; bool CreateStopDecision(const Obstacle& obstacle, ObjectDecisionType* const stop_decision, double stop_distance) const; /** * @brief create follow decision based on the boundary **/ bool CreateFollowDecision(const Obstacle& obstacle, ObjectDecisionType* const follow_decision) const; /** * @brief create yield decision based on the boundary **/ bool CreateYieldDecision(const Obstacle& obstacle, ObjectDecisionType* const yield_decision) const; /** * @brief create overtake decision based on the boundary **/ bool CreateOvertakeDecision( const Obstacle& obstacle, ObjectDecisionType* const overtake_decision) const; common::Status MakeObjectDecision(const SpeedData& speed_profile, PathDecision* const path_decision) const; void AppendIgnoreDecision(Obstacle* obstacle) const; /** * @brief "too close" is determined by whether ego vehicle will hit the front * obstacle if the obstacle drive at current speed and ego vehicle use some * reasonable deceleration **/ bool IsFollowTooClose(const Obstacle& obstacle) const; private: SLBoundary adc_sl_boundary_; common::TrajectoryPoint init_point_; const ReferenceLine* reference_line_ = nullptr; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/speed_decider/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "speed_decider", srcs = ["speed_decider.cc"], hdrs = ["speed_decider.h"], copts = ["-DMODULE_NAME=\\\"planning\\\""], deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/status", "//modules/planning/common:frame", "//modules/planning/common:path_decision", "//modules/planning/common:planning_gflags", "//modules/planning/common:reference_line_info", "//modules/common_msgs/planning_msgs:planning_cc_proto", "//modules/planning/tasks:task", "//modules/planning/tasks/utils:st_gap_estimator", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/open_space_decider/open_space_fallback_decider_test.cc
/****************************************************************************** * Copyright 2019 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/deciders/open_space_decider/open_space_fallback_decider.h" #include "gtest/gtest.h" #include "modules/planning/proto/planning_config.pb.h" namespace apollo { namespace planning { class OpenSpaceFallbackDeciderTest : public ::testing::Test { public: virtual void SetUp() { config_.set_task_type(TaskConfig::OPEN_SPACE_FALLBACK_DECIDER); } protected: TaskConfig config_; }; TEST_F(OpenSpaceFallbackDeciderTest, Init) { auto injector = std::make_shared<DependencyInjector>(); OpenSpaceFallbackDecider open_space_fallback_decider(config_, injector); EXPECT_EQ(open_space_fallback_decider.Name(), TaskConfig::TaskType_Name(config_.task_type())); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/tasks/deciders
apollo_public_repos/apollo/modules/planning/tasks/deciders/open_space_decider/open_space_pre_stop_decider.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/tasks/deciders/open_space_decider/open_space_pre_stop_decider.h" #include <memory> #include <string> #include <vector> #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/util/common.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::VehicleState; using apollo::common::math::Vec2d; using apollo::hdmap::ParkingSpaceInfoConstPtr; OpenSpacePreStopDecider::OpenSpacePreStopDecider( const TaskConfig& config, const std::shared_ptr<DependencyInjector>& injector) : Decider(config, injector) { ACHECK(config.has_open_space_pre_stop_decider_config()); } Status OpenSpacePreStopDecider::Process( Frame* frame, ReferenceLineInfo* reference_line_info) { CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); open_space_pre_stop_decider_config_ = config_.open_space_pre_stop_decider_config(); double target_s = 0.0; const auto& stop_type = open_space_pre_stop_decider_config_.stop_type(); switch (stop_type) { case OpenSpacePreStopDeciderConfig::PARKING: if (!CheckParkingSpotPreStop(frame, reference_line_info, &target_s)) { const std::string msg = "Checking parking spot pre stop fails"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } SetParkingSpotStopFence(target_s, frame, reference_line_info); break; case OpenSpacePreStopDeciderConfig::PULL_OVER: if (!CheckPullOverPreStop(frame, reference_line_info, &target_s)) { const std::string msg = "Checking pull over pre stop fails"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } SetPullOverStopFence(target_s, frame, reference_line_info); break; default: const std::string msg = "This stop type not implemented"; AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } return Status::OK(); } bool OpenSpacePreStopDecider::CheckPullOverPreStop( Frame* const frame, ReferenceLineInfo* const reference_line_info, double* target_s) { *target_s = 0.0; 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()) { common::SLPoint pull_over_sl; const auto& reference_line = reference_line_info->reference_line(); reference_line.XYToSL(pull_over_status.position(), &pull_over_sl); *target_s = pull_over_sl.s(); } return true; } bool OpenSpacePreStopDecider::CheckParkingSpotPreStop( Frame* const frame, ReferenceLineInfo* const reference_line_info, double* target_s) { const auto& routing_request = frame->local_view().routing->routing_request(); auto corner_point = routing_request.parking_info().corner_point(); const auto& target_parking_spot_id = frame->open_space_info().target_parking_spot_id(); const auto& nearby_path = reference_line_info->reference_line().map_path(); if (target_parking_spot_id.empty()) { AERROR << "no target parking spot id found when setting pre stop fence"; return false; } double target_area_center_s = 0.0; bool target_area_found = false; const auto& parking_space_overlaps = nearby_path.parking_space_overlaps(); ParkingSpaceInfoConstPtr target_parking_spot_ptr; const hdmap::HDMap* hdmap = hdmap::HDMapUtil::BaseMapPtr(); for (const auto& parking_overlap : parking_space_overlaps) { if (parking_overlap.object_id == target_parking_spot_id) { // TODO(Jinyun) parking overlap s are wrong on map, not usable // target_area_center_s = // (parking_overlap.start_s + parking_overlap.end_s) / 2.0; hdmap::Id id; id.set_id(parking_overlap.object_id); target_parking_spot_ptr = hdmap->GetParkingSpaceById(id); Vec2d left_bottom_point = target_parking_spot_ptr->polygon().points().at(0); Vec2d right_bottom_point = target_parking_spot_ptr->polygon().points().at(1); left_bottom_point.set_x(corner_point.point().at(0).x()); left_bottom_point.set_y(corner_point.point().at(0).y()); right_bottom_point.set_x(corner_point.point().at(1).x()); right_bottom_point.set_y(corner_point.point().at(1).y()); double left_bottom_point_s = 0.0; double left_bottom_point_l = 0.0; double right_bottom_point_s = 0.0; double right_bottom_point_l = 0.0; nearby_path.GetNearestPoint(left_bottom_point, &left_bottom_point_s, &left_bottom_point_l); nearby_path.GetNearestPoint(right_bottom_point, &right_bottom_point_s, &right_bottom_point_l); target_area_center_s = (left_bottom_point_s + right_bottom_point_s) / 2.0; target_area_found = true; } } if (!target_area_found) { AERROR << "no target parking spot found on reference line"; return false; } *target_s = target_area_center_s; return true; } void OpenSpacePreStopDecider::SetParkingSpotStopFence( const double target_s, Frame* const frame, ReferenceLineInfo* const reference_line_info) { const auto& nearby_path = reference_line_info->reference_line().map_path(); const double adc_front_edge_s = reference_line_info->AdcSlBoundary().end_s(); const VehicleState& vehicle_state = frame->vehicle_state(); double stop_line_s = 0.0; double stop_distance_to_target = open_space_pre_stop_decider_config_.stop_distance_to_target(); double static_linear_velocity_epsilon = 1.0e-2; CHECK_GE(stop_distance_to_target, 1.0e-8); double target_vehicle_offset = target_s - adc_front_edge_s; if (target_vehicle_offset > stop_distance_to_target) { stop_line_s = target_s - stop_distance_to_target; } else if (std::abs(target_vehicle_offset) < stop_distance_to_target) { stop_line_s = target_s + stop_distance_to_target; } else if (target_vehicle_offset < -stop_distance_to_target) { if (!frame->open_space_info().pre_stop_rightaway_flag()) { // TODO(Jinyun) Use constant comfortable deacceleration rather than // distance by config to set stop fence stop_line_s = adc_front_edge_s + open_space_pre_stop_decider_config_.rightaway_stop_distance(); if (std::abs(vehicle_state.linear_velocity()) < static_linear_velocity_epsilon) { stop_line_s = adc_front_edge_s; } *(frame->mutable_open_space_info()->mutable_pre_stop_rightaway_point()) = nearby_path.GetSmoothPoint(stop_line_s); frame->mutable_open_space_info()->set_pre_stop_rightaway_flag(true); } else { double stop_point_s = 0.0; double stop_point_l = 0.0; nearby_path.GetNearestPoint( frame->open_space_info().pre_stop_rightaway_point(), &stop_point_s, &stop_point_l); stop_line_s = stop_point_s; } } const std::string stop_wall_id = OPEN_SPACE_STOP_ID; std::vector<std::string> wait_for_obstacles; frame->mutable_open_space_info()->set_open_space_pre_stop_fence_s( stop_line_s); util::BuildStopDecision(stop_wall_id, stop_line_s, 0.0, StopReasonCode::STOP_REASON_PRE_OPEN_SPACE_STOP, wait_for_obstacles, "OpenSpacePreStopDecider", frame, reference_line_info); } void OpenSpacePreStopDecider::SetPullOverStopFence( const double target_s, Frame* const frame, ReferenceLineInfo* const reference_line_info) { const auto& nearby_path = reference_line_info->reference_line().map_path(); const double adc_front_edge_s = reference_line_info->AdcSlBoundary().end_s(); const VehicleState& vehicle_state = frame->vehicle_state(); double stop_line_s = 0.0; double stop_distance_to_target = open_space_pre_stop_decider_config_.stop_distance_to_target(); double static_linear_velocity_epsilon = 1.0e-2; CHECK_GE(stop_distance_to_target, 1.0e-8); double target_vehicle_offset = target_s - adc_front_edge_s; if (target_vehicle_offset > stop_distance_to_target) { stop_line_s = target_s - stop_distance_to_target; } else { if (!frame->open_space_info().pre_stop_rightaway_flag()) { // TODO(Jinyun) Use constant comfortable deacceleration rather than // distance by config to set stop fence stop_line_s = adc_front_edge_s + open_space_pre_stop_decider_config_.rightaway_stop_distance(); if (std::abs(vehicle_state.linear_velocity()) < static_linear_velocity_epsilon) { stop_line_s = adc_front_edge_s; } *(frame->mutable_open_space_info()->mutable_pre_stop_rightaway_point()) = nearby_path.GetSmoothPoint(stop_line_s); frame->mutable_open_space_info()->set_pre_stop_rightaway_flag(true); } else { double stop_point_s = 0.0; double stop_point_l = 0.0; nearby_path.GetNearestPoint( frame->open_space_info().pre_stop_rightaway_point(), &stop_point_s, &stop_point_l); stop_line_s = stop_point_s; } } const std::string stop_wall_id = OPEN_SPACE_STOP_ID; std::vector<std::string> wait_for_obstacles; frame->mutable_open_space_info()->set_open_space_pre_stop_fence_s( stop_line_s); util::BuildStopDecision(stop_wall_id, stop_line_s, 0.0, StopReasonCode::STOP_REASON_PRE_OPEN_SPACE_STOP, wait_for_obstacles, "OpenSpacePreStopDecider", frame, reference_line_info); } } // namespace planning } // namespace apollo
0