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/open_space
apollo_public_repos/apollo/modules/planning/open_space/tools/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_binary( name = "hybrid_a_star_wrapper_lib.so", srcs = ["hybrid_a_star_wrapper.cc"], linkshared = True, linkstatic = False, deps = [ "//modules/planning/open_space/coarse_trajectory_generator:hybrid_a_star", ], ) cc_binary( name = "distance_approach_problem_wrapper_lib.so", srcs = ["distance_approach_problem_wrapper.cc"], copts = ["-fopenmp"], linkshared = True, linkstatic = False, deps = [ "//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", ], ) cc_binary( name = "open_space_roi_wrapper_lib.so", srcs = ["open_space_roi_wrapper.cc"], copts = [ "-DMODULE_NAME=\\\"planning\\\"", ], linkshared = True, linkstatic = False, deps = [ "//cyber", "//modules/common/math", "//modules/map/pnc_map", "//modules/planning/common:planning_gflags", "//modules/planning/proto:planner_open_space_config_cc_proto", "@eigen", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/tools/hybrid_a_star_wrapper.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* * @file */ #include "cyber/common/file.h" #include "modules/planning/open_space/coarse_trajectory_generator/hybrid_a_star.h" namespace apollo { namespace planning { class HybridAObstacleContainer { public: HybridAObstacleContainer() = default; void AddVirtualObstacle(double* obstacle_x, double* obstacle_y, int vertice_num) { std::vector<common::math::Vec2d> obstacle_vertices; for (int i = 0; i < vertice_num; i++) { common::math::Vec2d vertice(obstacle_x[i], obstacle_y[i]); obstacle_vertices.emplace_back(vertice); } obstacles_list.emplace_back(obstacle_vertices); } const std::vector<std::vector<common::math::Vec2d>>& GetObstaclesVerticesVec() { return obstacles_list; } private: std::vector<std::vector<common::math::Vec2d>> obstacles_list; }; class HybridAResultContainer { public: HybridAResultContainer() = default; void LoadResult() { x_ = std::move(result_.x); y_ = std::move(result_.y); phi_ = std::move(result_.phi); v_ = std::move(result_.v); a_ = std::move(result_.a); steer_ = std::move(result_.steer); } std::vector<double>* GetX() { return &x_; } std::vector<double>* GetY() { return &y_; } std::vector<double>* GetPhi() { return &phi_; } std::vector<double>* GetV() { return &v_; } std::vector<double>* GetA() { return &a_; } std::vector<double>* GetSteer() { return &steer_; } HybridAStartResult* PrepareResult() { return &result_; } private: HybridAStartResult result_; std::vector<double> x_; std::vector<double> y_; std::vector<double> phi_; std::vector<double> v_; std::vector<double> a_; std::vector<double> steer_; }; extern "C" { HybridAStar* CreatePlannerPtr() { apollo::planning::PlannerOpenSpaceConfig planner_open_space_config_; ACHECK(apollo::cyber::common::GetProtoFromFile( FLAGS_planner_open_space_config_filename, &planner_open_space_config_)) << "Failed to load open space config file " << FLAGS_planner_open_space_config_filename; return new HybridAStar(planner_open_space_config_); } HybridAObstacleContainer* CreateObstaclesPtr() { return new HybridAObstacleContainer(); } HybridAResultContainer* CreateResultPtr() { return new HybridAResultContainer(); } void AddVirtualObstacle(HybridAObstacleContainer* obstacles_ptr, double* obstacle_x, double* obstacle_y, int vertice_num) { obstacles_ptr->AddVirtualObstacle(obstacle_x, obstacle_y, vertice_num); } bool Plan(HybridAStar* planner_ptr, HybridAObstacleContainer* obstacles_ptr, HybridAResultContainer* result_ptr, double sx, double sy, double sphi, double ex, double ey, double ephi, double* XYbounds) { std::vector<double> XYbounds_(XYbounds, XYbounds + 4); return planner_ptr->Plan(sx, sy, sphi, ex, ey, ephi, XYbounds_, obstacles_ptr->GetObstaclesVerticesVec(), result_ptr->PrepareResult()); } void GetResult(HybridAResultContainer* result_ptr, double* x, double* y, double* phi, double* v, double* a, double* steer, size_t* output_size) { result_ptr->LoadResult(); size_t size = result_ptr->GetX()->size(); std::cout << "return size is " << size << std::endl; for (size_t i = 0; i < size; i++) { x[i] = result_ptr->GetX()->at(i); y[i] = result_ptr->GetY()->at(i); phi[i] = result_ptr->GetPhi()->at(i); v[i] = result_ptr->GetV()->at(i); } for (size_t i = 0; i < size - 1; i++) { a[i] = result_ptr->GetA()->at(i); steer[i] = result_ptr->GetSteer()->at(i); } *output_size = size; } }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_ipopt_qp_interface.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 <limits> #include <vector> #include <adolc/adolc.h> #include <adolc/adolc_sparse.h> #include <coin/IpTNLP.hpp> #include <coin/IpTypes.hpp> #include "Eigen/Dense" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/planning/proto/planner_open_space_config.pb.h" // #define tag_f 1 // #define tag_g 2 #define tag_L 3 // #define HPOFF namespace apollo { namespace planning { class DualVariableWarmStartIPOPTQPInterface : public Ipopt::TNLP { public: DualVariableWarmStartIPOPTQPInterface( size_t horizon, double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const Eigen::MatrixXd& xWS, const PlannerOpenSpaceConfig& planner_open_space_config); virtual ~DualVariableWarmStartIPOPTQPInterface() = default; void get_optimization_results(Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up) const; void check_solution(const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up); /** 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; //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> bool eval_obj(int n, const T* x, T* obj_value); /** Template to compute constraints */ template <class T> bool eval_constraints(int n, const T* x, int m, T* g); /** Method to generate the required tapes */ void generate_tapes(int n, int m, int* nnz_h_lag); //*************** end ADOL-C part *********************************** private: int num_of_variables_; int num_of_constraints_; int horizon_; double ts_; Eigen::MatrixXd ego_; int lambda_horizon_ = 0; int miu_horizon_ = 0; int dual_formulation_horizon_ = 0; Eigen::MatrixXd l_warm_up_; Eigen::MatrixXd n_warm_up_; double wheelbase_; double w_ev_; double l_ev_; std::vector<double> g_; double offset_; Eigen::MatrixXi obstacles_edges_num_; int obstacles_num_; int obstacles_edges_sum_; // lagrangian l start index int l_start_index_ = 0; // lagrangian n start index int n_start_index_ = 0; // lagrangian d start index int d_start_index_ = 0; // obstacles_A Eigen::MatrixXd obstacles_A_; // obstacles_b Eigen::MatrixXd obstacles_b_; // states of warm up stage Eigen::MatrixXd xWS_; double min_safety_distance_; //*************** start ADOL-C part *********************************** double* obj_lam; unsigned int* rind_L; /* row indices */ unsigned int* cind_L; /* column indices */ double* hessval; /* values */ int nnz_L; int options_L[4]; //*************** end ADOL-C part *********************************** }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_ipopt_interface_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_ipopt_interface.h" #include "cyber/common/file.h" #include "gtest/gtest.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { class DualVariableWarmStartIPOPTInterfaceTest : public ::testing::Test { public: virtual void SetUp() { FLAGS_planner_open_space_config_filename = "/apollo/modules/planning/testdata/conf/" "open_space_standard_parking_lot.pb.txt"; ACHECK(apollo::cyber::common::GetProtoFromFile( FLAGS_planner_open_space_config_filename, &planner_open_space_config_)) << "Failed to load open space config file " << FLAGS_planner_open_space_config_filename; ProblemSetup(); } protected: void ProblemSetup(); protected: size_t horizon_ = 5; size_t obstacles_num_ = 10; double ts_ = 0.01; Eigen::MatrixXd ego_ = Eigen::MatrixXd::Ones(4, 1); Eigen::MatrixXd last_time_u_ = Eigen::MatrixXd::Zero(2, 1); Eigen::MatrixXi obstacles_edges_num_; Eigen::MatrixXd obstacles_A_ = Eigen::MatrixXd::Ones(10, 2); Eigen::MatrixXd obstacles_b_ = Eigen::MatrixXd::Ones(10, 1); int num_of_variables_ = 0; double rx_ = 0.0; double ry_ = 0.0; double r_yaw_ = 0.0; int num_of_constraints_ = 0; std::unique_ptr<DualVariableWarmStartIPOPTInterface> ptop_ = nullptr; PlannerOpenSpaceConfig planner_open_space_config_; }; void DualVariableWarmStartIPOPTInterfaceTest::ProblemSetup() { obstacles_edges_num_ = 4 * Eigen::MatrixXi::Ones(obstacles_num_, 1); Eigen::MatrixXd xWS = Eigen::MatrixXd::Ones(4, horizon_ + 1); ptop_.reset(new DualVariableWarmStartIPOPTInterface( horizon_, ts_, ego_, obstacles_edges_num_, obstacles_num_, obstacles_A_, obstacles_b_, xWS, planner_open_space_config_)); } TEST_F(DualVariableWarmStartIPOPTInterfaceTest, initilization) { EXPECT_NE(ptop_, nullptr); } TEST_F(DualVariableWarmStartIPOPTInterfaceTest, get_bounds_info) { int kNumOfVariables = 540; int kNumOfConstraints = 240; double x_l[kNumOfVariables]; double x_u[kNumOfVariables]; double g_l[kNumOfConstraints]; double g_u[kNumOfConstraints]; bool res = ptop_->get_bounds_info(kNumOfVariables, x_l, x_u, kNumOfConstraints, g_l, g_u); EXPECT_TRUE(res); } TEST_F(DualVariableWarmStartIPOPTInterfaceTest, get_starting_point) { int kNumOfVariables = 540; int kNumOfConstraints = 240; bool init_x = true; bool init_z = false; bool init_lambda = false; double x[kNumOfVariables]; double z_L[kNumOfVariables]; double z_U[kNumOfVariables]; double lambda[kNumOfVariables]; bool res = ptop_->get_starting_point(kNumOfVariables, init_x, x, init_z, z_L, z_U, kNumOfConstraints, init_lambda, lambda); EXPECT_TRUE(res); } TEST_F(DualVariableWarmStartIPOPTInterfaceTest, eval_f) { int kNumOfVariables = 540; double obj_value; double x[kNumOfVariables]; std::fill_n(x, kNumOfVariables, 1.2); bool res = ptop_->eval_f(kNumOfVariables, x, true, obj_value); EXPECT_DOUBLE_EQ(obj_value, 72.000000000000085); EXPECT_TRUE(res); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_ipopt_interface.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 <limits> #include <vector> #include <adolc/adolc.h> #include <adolc/adolc_sparse.h> #include <coin/IpTNLP.hpp> #include <coin/IpTypes.hpp> #include "Eigen/Dense" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/planning/proto/planner_open_space_config.pb.h" // #define tag_f 1 // #define tag_g 2 #define tag_L 3 // #define HPOFF 30 namespace apollo { namespace planning { class DualVariableWarmStartIPOPTInterface : public Ipopt::TNLP { public: DualVariableWarmStartIPOPTInterface( size_t horizon, double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const Eigen::MatrixXd& xWS, const PlannerOpenSpaceConfig& planner_open_space_config); virtual ~DualVariableWarmStartIPOPTInterface() = default; void get_optimization_results(Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up) const; /** 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; //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> bool eval_obj(int n, const T* x, T* obj_value); /** Template to compute constraints */ template <class T> bool eval_constraints(int n, const T* x, int m, T* g); /** Method to generate the required tapes */ void generate_tapes(int n, int m, int* nnz_h_lag); //*************** end ADOL-C part *********************************** private: int num_of_variables_; int num_of_constraints_; int horizon_; double ts_; Eigen::MatrixXd ego_; int lambda_horizon_ = 0; int miu_horizon_ = 0; int dual_formulation_horizon_ = 0; Eigen::MatrixXd l_warm_up_; Eigen::MatrixXd n_warm_up_; double wheelbase_; double w_ev_; double l_ev_; std::vector<double> g_; double offset_; Eigen::MatrixXi obstacles_edges_num_; int obstacles_num_; int obstacles_edges_sum_; // lagrangian l start index int l_start_index_ = 0; // lagrangian n start index int n_start_index_ = 0; // lagrangian d start index int d_start_index_ = 0; // obstacles_A Eigen::MatrixXd obstacles_A_; // obstacles_b Eigen::MatrixXd obstacles_b_; // states of warm up stage Eigen::MatrixXd xWS_; double weight_d_; //*************** start ADOL-C part *********************************** double* obj_lam; unsigned int* rind_L; /* row indices */ unsigned int* cind_L; /* column indices */ double* hessval; /* values */ int nnz_L; int options_L[4]; //*************** end ADOL-C part *********************************** }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_problem_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_problem.h" #include "gtest/gtest.h" namespace apollo { namespace planning { TEST(DualVariableWarmStartProblem, SetUp) {} } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_relax_end_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 */ #include "modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_relax_end_interface.h" // #define ADEBUG AERROR namespace apollo { namespace planning { DistanceApproachIPOPTRelaxEndInterface::DistanceApproachIPOPTRelaxEndInterface( const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xf, const Eigen::MatrixXd& last_time_u, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const PlannerOpenSpaceConfig& planner_open_space_config) : ts_(ts), ego_(ego), xWS_(xWS), uWS_(uWS), l_warm_up_(l_warm_up), n_warm_up_(n_warm_up), x0_(x0), xf_(xf), last_time_u_(last_time_u), XYbounds_(XYbounds), obstacles_edges_num_(obstacles_edges_num), obstacles_A_(obstacles_A), obstacles_b_(obstacles_b) { ACHECK(horizon < std::numeric_limits<int>::max()) << "Invalid cast on horizon in open space planner"; horizon_ = static_cast<int>(horizon); ACHECK(obstacles_num < std::numeric_limits<int>::max()) << "Invalid cast on obstacles_num in open space planner"; obstacles_num_ = static_cast<int>(obstacles_num); w_ev_ = ego_(1, 0) + ego_(3, 0); l_ev_ = ego_(0, 0) + ego_(2, 0); g_ = {l_ev_ / 2, w_ev_ / 2, l_ev_ / 2, w_ev_ / 2}; offset_ = (ego_(0, 0) + ego_(2, 0)) / 2 - ego_(2, 0); obstacles_edges_sum_ = obstacles_edges_num_.sum(); state_result_ = Eigen::MatrixXd::Zero(4, horizon_ + 1); dual_l_result_ = Eigen::MatrixXd::Zero(obstacles_edges_sum_, horizon_ + 1); dual_n_result_ = Eigen::MatrixXd::Zero(4 * obstacles_num_, horizon_ + 1); control_result_ = Eigen::MatrixXd::Zero(2, horizon_); time_result_ = Eigen::MatrixXd::Zero(1, horizon_); state_start_index_ = 0; control_start_index_ = 4 * (horizon_ + 1); time_start_index_ = control_start_index_ + 2 * horizon_; l_start_index_ = time_start_index_ + (horizon_ + 1); n_start_index_ = l_start_index_ + obstacles_edges_sum_ * (horizon_ + 1); distance_approach_config_ = planner_open_space_config.distance_approach_config(); weight_state_x_ = distance_approach_config_.weight_x(); weight_state_y_ = distance_approach_config_.weight_y(); weight_state_phi_ = distance_approach_config_.weight_phi(); weight_state_v_ = distance_approach_config_.weight_v(); weight_input_steer_ = distance_approach_config_.weight_steer(); weight_input_a_ = distance_approach_config_.weight_a(); weight_rate_steer_ = distance_approach_config_.weight_steer_rate(); weight_rate_a_ = distance_approach_config_.weight_a_rate(); weight_stitching_steer_ = distance_approach_config_.weight_steer_stitching(); weight_stitching_a_ = distance_approach_config_.weight_a_stitching(); weight_first_order_time_ = distance_approach_config_.weight_first_order_time(); weight_second_order_time_ = distance_approach_config_.weight_second_order_time(); weight_end_state_ = distance_approach_config_.weight_end_state(); min_safety_distance_ = distance_approach_config_.min_safety_distance(); max_steer_angle_ = vehicle_param_.max_steer_angle() / vehicle_param_.steer_ratio(); max_speed_forward_ = distance_approach_config_.max_speed_forward(); max_speed_reverse_ = distance_approach_config_.max_speed_reverse(); max_acceleration_forward_ = distance_approach_config_.max_acceleration_forward(); max_acceleration_reverse_ = distance_approach_config_.max_acceleration_reverse(); min_time_sample_scaling_ = distance_approach_config_.min_time_sample_scaling(); max_time_sample_scaling_ = distance_approach_config_.max_time_sample_scaling(); max_steer_rate_ = vehicle_param_.max_steer_angle_rate() / vehicle_param_.steer_ratio(); use_fix_time_ = distance_approach_config_.use_fix_time(); wheelbase_ = vehicle_param_.wheel_base(); enable_constraint_check_ = distance_approach_config_.enable_constraint_check(); enable_jacobian_ad_ = true; } bool DistanceApproachIPOPTRelaxEndInterface::get_nlp_info( int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) { ADEBUG << "get_nlp_info"; // n1 : states variables, 4 * (N+1) int n1 = 4 * (horizon_ + 1); ADEBUG << "n1: " << n1; // n2 : control inputs variables int n2 = 2 * horizon_; ADEBUG << "n2: " << n2; // n3 : sampling time variables int n3 = horizon_ + 1; ADEBUG << "n3: " << n3; // n4 : dual multiplier associated with obstacle shape lambda_horizon_ = obstacles_edges_num_.sum() * (horizon_ + 1); ADEBUG << "lambda_horizon_: " << lambda_horizon_; // n5 : dual multipier associated with car shape, obstacles_num*4 * (N+1) miu_horizon_ = obstacles_num_ * 4 * (horizon_ + 1); ADEBUG << "miu_horizon_: " << miu_horizon_; // m1 : dynamics constatins int m1 = 4 * horizon_; // m2 : control rate constraints (only steering) int m2 = horizon_; // m3 : sampling time equality constraints int m3 = horizon_; // m4 : obstacle constraints int m4 = 4 * obstacles_num_ * (horizon_ + 1); num_of_variables_ = n1 + n2 + n3 + lambda_horizon_ + miu_horizon_; num_of_constraints_ = m1 + m2 + m3 + m4 + (num_of_variables_ - (horizon_ + 1) + 2); // number of variables n = num_of_variables_; ADEBUG << "num_of_variables_ " << num_of_variables_; // number of constraints m = num_of_constraints_; ADEBUG << "num_of_constraints_ " << num_of_constraints_; generate_tapes(n, m, &nnz_jac_g, &nnz_h_lag); // number of nonzero in Jacobian. if (!enable_jacobian_ad_) { int tmp = 0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); tmp += current_edges_num * 4 + 9 + 4; } } nnz_jac_g = 24 * horizon_ + 3 * horizon_ + 2 * horizon_ + tmp - 1 + (num_of_variables_ - (horizon_ + 1) + 2); } index_style = IndexStyleEnum::C_STYLE; return true; } bool DistanceApproachIPOPTRelaxEndInterface::get_bounds_info(int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) { ADEBUG << "get_bounds_info"; ACHECK(XYbounds_.size() == 4) << "XYbounds_ size is not 4, but" << XYbounds_.size(); // Variables: includes state, u, sample time and lagrange multipliers // 1. state variables, 4 * [0, horizon] // start point pose int variable_index = 0; for (int i = 0; i < 4; ++i) { x_l[i] = -2e19; x_u[i] = 2e19; } variable_index += 4; // During horizons, 2 ~ N-1 for (int i = 1; i < horizon_; ++i) { // x x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // y x_l[variable_index + 1] = -2e19; x_u[variable_index + 1] = 2e19; // phi x_l[variable_index + 2] = -2e19; x_u[variable_index + 2] = 2e19; // v x_l[variable_index + 3] = -2e19; x_u[variable_index + 3] = 2e19; variable_index += 4; } // end point pose for (int i = 0; i < 4; ++i) { x_l[variable_index + i] = -2e19; x_u[variable_index + i] = 2e19; } variable_index += 4; ADEBUG << "variable_index after adding state variables : " << variable_index; // 2. control variables, 2 * [0, horizon_-1] for (int i = 0; i < horizon_; ++i) { // steer x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // a x_l[variable_index + 1] = -2e19; x_u[variable_index + 1] = 2e19; variable_index += 2; } ADEBUG << "variable_index after adding control variables : " << variable_index; // 3. sampling time variables, 1 * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; ++variable_index; } ADEBUG << "variable_index after adding sample time : " << variable_index; ADEBUG << "sample time fix time status is : " << use_fix_time_; // 4. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0, // horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { x_l[variable_index] = 0.0; x_u[variable_index] = 2e19; // nlp_upper_bound_limit ++variable_index; } } ADEBUG << "variable_index after adding lagrange l : " << variable_index; // 5. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { x_l[variable_index] = 0.0; x_u[variable_index] = 2e19; // nlp_upper_bound_limit ++variable_index; } } ADEBUG << "variable_index after adding lagrange n : " << variable_index; // Constraints: includes four state Euler forward constraints, three // Obstacle related constraints // 1. dynamics constraints 4 * [0, horizons-1] int constraint_index = 0; for (int i = 0; i < 4 * horizon_; ++i) { g_l[i] = 0.0; g_u[i] = 0.0; } constraint_index += 4 * horizon_; ADEBUG << "constraint_index after adding Euler forward dynamics constraints: " << constraint_index; // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply // steering rate as of now for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = -max_steer_rate_; g_u[constraint_index] = max_steer_rate_; ++constraint_index; } ADEBUG << "constraint_index after adding steering rate constraints: " << constraint_index; // 3. Time constraints 1 * [0, horizons-1] for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 0.0; ++constraint_index; } ADEBUG << "constraint_index after adding time constraints: " << constraint_index; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { // a. norm(A'*lambda) <= 1 g_l[constraint_index] = -2e19; g_u[constraint_index] = 1.0; // b. G'*mu + R'*A*lambda = 0 g_l[constraint_index + 1] = 0.0; g_u[constraint_index + 1] = 0.0; g_l[constraint_index + 2] = 0.0; g_u[constraint_index + 2] = 0.0; // c. -g'*mu + (A*t - b)*lambda > min_safety_distance_ g_l[constraint_index + 3] = min_safety_distance_; g_u[constraint_index + 3] = 2e19; // nlp_upper_bound_limit constraint_index += 4; } } // 5. load variable bounds as constraints // start configuration g_l[constraint_index] = x0_(0, 0); g_u[constraint_index] = x0_(0, 0); g_l[constraint_index + 1] = x0_(1, 0); g_u[constraint_index + 1] = x0_(1, 0); g_l[constraint_index + 2] = x0_(2, 0); g_u[constraint_index + 2] = x0_(2, 0); g_l[constraint_index + 3] = x0_(3, 0); g_u[constraint_index + 3] = x0_(3, 0); constraint_index += 4; for (int i = 1; i < horizon_; ++i) { g_l[constraint_index] = XYbounds_[0]; g_u[constraint_index] = XYbounds_[1]; g_l[constraint_index + 1] = XYbounds_[2]; g_u[constraint_index + 1] = XYbounds_[3]; g_l[constraint_index + 2] = -max_speed_reverse_; g_u[constraint_index + 2] = max_speed_forward_; constraint_index += 3; } // end configuration g_l[constraint_index] = -2e19; g_u[constraint_index] = 2e19; g_l[constraint_index + 1] = -2e19; g_u[constraint_index + 1] = 2e19; g_l[constraint_index + 2] = -2e19; g_u[constraint_index + 2] = 2e19; g_l[constraint_index + 3] = -2e19; g_u[constraint_index + 3] = 2e19; constraint_index += 4; for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = -max_steer_angle_; g_u[constraint_index] = max_steer_angle_; g_l[constraint_index + 1] = -max_acceleration_reverse_; g_u[constraint_index + 1] = max_acceleration_forward_; constraint_index += 2; } for (int i = 0; i < horizon_ + 1; ++i) { if (!use_fix_time_) { g_l[constraint_index] = min_time_sample_scaling_; g_u[constraint_index] = max_time_sample_scaling_; } else { g_l[constraint_index] = 1.0; g_u[constraint_index] = 1.0; } constraint_index++; } for (int i = 0; i < lambda_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; } for (int i = 0; i < miu_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; } ADEBUG << "constraint_index after adding obstacles constraints: " << constraint_index; ADEBUG << "get_bounds_info_ out"; return true; } bool DistanceApproachIPOPTRelaxEndInterface::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) { ADEBUG << "get_starting_point"; ACHECK(init_x) << "Warm start init_x setting failed"; CHECK_EQ(horizon_, uWS_.cols()); CHECK_EQ(horizon_ + 1, xWS_.cols()); // 1. state variables 4 * (horizon_ + 1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * 4; for (int j = 0; j < 4; ++j) { x[index + j] = xWS_(j, i); } } // 2. control variable initialization, 2 * horizon_ for (int i = 0; i < horizon_; ++i) { int index = i * 2; x[control_start_index_ + index] = uWS_(0, i); x[control_start_index_ + index + 1] = uWS_(1, i); } // 2. time scale variable initialization, horizon_ + 1 for (int i = 0; i < horizon_ + 1; ++i) { x[time_start_index_ + i] = 0.5 * (min_time_sample_scaling_ + max_time_sample_scaling_); } // 3. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * obstacles_edges_sum_; for (int j = 0; j < obstacles_edges_sum_; ++j) { x[l_start_index_ + index + j] = l_warm_up_(j, i); } } // 4. lagrange constraint m, 4*obstacles_num * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * 4 * obstacles_num_; for (int j = 0; j < 4 * obstacles_num_; ++j) { x[n_start_index_ + index + j] = n_warm_up_(j, i); } } ADEBUG << "get_starting_point out"; return true; } bool DistanceApproachIPOPTRelaxEndInterface::eval_f(int n, const double* x, bool new_x, double& obj_value) { eval_obj(n, x, &obj_value); return true; } bool DistanceApproachIPOPTRelaxEndInterface::eval_grad_f(int n, const double* x, bool new_x, double* grad_f) { gradient(tag_f, n, x, grad_f); return true; } bool DistanceApproachIPOPTRelaxEndInterface::eval_g(int n, const double* x, bool new_x, int m, double* g) { eval_constraints(n, x, m, g); // if (enable_constraint_check_) check_g(n, x, m, g); return true; } bool DistanceApproachIPOPTRelaxEndInterface::eval_jac_g(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { if (enable_jacobian_ad_) { if (values == nullptr) { // return the structure of the jacobian for (int idx = 0; idx < nnz_jac; idx++) { iRow[idx] = rind_g[idx]; jCol[idx] = cind_g[idx]; } } else { // return the values of the jacobian of the constraints sparse_jac(tag_g, m, n, 1, x, &nnz_jac, &rind_g, &cind_g, &jacval, options_g); for (int idx = 0; idx < nnz_jac; idx++) { values[idx] = jacval[idx]; } } return true; } else { return eval_jac_g_ser(n, x, new_x, m, nele_jac, iRow, jCol, values); } } bool DistanceApproachIPOPTRelaxEndInterface::eval_jac_g_ser( int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { AERROR << "NOT READY"; return false; } bool DistanceApproachIPOPTRelaxEndInterface::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) { // return the structure. This is a symmetric matrix, fill the lower left // triangle only. for (int idx = 0; idx < nnz_L; idx++) { iRow[idx] = rind_L[idx]; jCol[idx] = cind_L[idx]; } } else { // return the values. This is a symmetric matrix, fill the lower left // triangle only obj_lam[0] = obj_factor; for (int idx = 0; idx < m; idx++) { obj_lam[1 + idx] = lambda[idx]; } set_param_vec(tag_L, m + 1, obj_lam); sparse_hess(tag_L, n, 1, const_cast<double*>(x), &nnz_L, &rind_L, &cind_L, &hessval, options_L); for (int idx = 0; idx < nnz_L; idx++) { values[idx] = hessval[idx]; } } return true; } void DistanceApproachIPOPTRelaxEndInterface::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) { int state_index = state_start_index_; int control_index = control_start_index_; int time_index = time_start_index_; int dual_l_index = l_start_index_; int dual_n_index = n_start_index_; // enable_constraint_check_: for debug only if (enable_constraint_check_) { ADEBUG << "final resolution constraint checking"; check_g(n, x, m, g); } // 1. state variables, 4 * [0, horizon] // 2. control variables, 2 * [0, horizon_-1] // 3. sampling time variables, 1 * [0, horizon_] // 4. dual_l obstacles_edges_sum_ * [0, horizon] // 5. dual_n obstacles_num * [0, horizon] for (int i = 0; i < horizon_; ++i) { state_result_(0, i) = x[state_index]; state_result_(1, i) = x[state_index + 1]; state_result_(2, i) = x[state_index + 2]; state_result_(3, i) = x[state_index + 3]; control_result_(0, i) = x[control_index]; control_result_(1, i) = x[control_index + 1]; time_result_(0, i) = ts_ * x[time_index]; for (int j = 0; j < obstacles_edges_sum_; ++j) { dual_l_result_(j, i) = x[dual_l_index + j]; } for (int k = 0; k < 4 * obstacles_num_; k++) { dual_n_result_(k, i) = x[dual_n_index + k]; } state_index += 4; control_index += 2; time_index++; dual_l_index += obstacles_edges_sum_; dual_n_index += 4 * obstacles_num_; } state_result_(0, 0) = x0_(0, 0); state_result_(1, 0) = x0_(1, 0); state_result_(2, 0) = x0_(2, 0); state_result_(3, 0) = x0_(3, 0); // push back last horizon for states state_result_(0, horizon_) = xf_(0, 0); state_result_(1, horizon_) = xf_(1, 0); state_result_(2, horizon_) = xf_(2, 0); state_result_(3, horizon_) = xf_(3, 0); for (int j = 0; j < obstacles_edges_sum_; ++j) { dual_l_result_(j, horizon_) = x[dual_l_index + j]; } for (int k = 0; k < 4 * obstacles_num_; k++) { dual_n_result_(k, horizon_) = x[dual_n_index + k]; } // memory deallocation of ADOL-C variables delete[] obj_lam; if (enable_jacobian_ad_) { free(rind_g); free(cind_g); free(jacval); } free(rind_L); free(cind_L); free(hessval); } void DistanceApproachIPOPTRelaxEndInterface::get_optimization_results( Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) const { ADEBUG << "get_optimization_results"; *state_result = state_result_; *control_result = control_result_; *time_result = time_result_; *dual_l_result = dual_l_result_; *dual_n_result = dual_n_result_; if (!distance_approach_config_.enable_initial_final_check()) { return; } CHECK_EQ(state_result_.cols(), xWS_.cols()); CHECK_EQ(state_result_.rows(), xWS_.rows()); double state_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4; ++j) { state_diff_max = std::max(std::abs(xWS_(j, i) - state_result_(j, i)), state_diff_max); } } // 2. control variable initialization, 2 * horizon_ CHECK_EQ(control_result_.cols(), uWS_.cols()); CHECK_EQ(control_result_.rows(), uWS_.rows()); double control_diff_max = 0.0; for (int i = 0; i < horizon_; ++i) { control_diff_max = std::max(std::abs(uWS_(0, i) - control_result_(0, i)), control_diff_max); control_diff_max = std::max(std::abs(uWS_(1, i) - control_result_(1, i)), control_diff_max); } // 2. time scale variable initialization, horizon_ + 1 // 3. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1) CHECK_EQ(dual_l_result_.cols(), l_warm_up_.cols()); CHECK_EQ(dual_l_result_.rows(), l_warm_up_.rows()); double l_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { l_diff_max = std::max(std::abs(l_warm_up_(j, i) - dual_l_result_(j, i)), l_diff_max); } } // 4. lagrange constraint m, 4*obstacles_num * (horizon_+1) CHECK_EQ(n_warm_up_.cols(), dual_n_result_.cols()); CHECK_EQ(n_warm_up_.rows(), dual_n_result_.rows()); double n_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { n_diff_max = std::max(std::abs(n_warm_up_(j, i) - dual_n_result_(j, i)), n_diff_max); } } ADEBUG << "state_diff_max: " << state_diff_max; ADEBUG << "control_diff_max: " << control_diff_max; ADEBUG << "dual_l_diff_max: " << l_diff_max; ADEBUG << "dual_n_diff_max: " << n_diff_max; } //*************** start ADOL-C part *********************************** template <class T> void DistanceApproachIPOPTRelaxEndInterface::eval_obj(int n, const T* x, T* obj_value) { // Objective is : // min control inputs // min input rate // min time (if the time step is not fixed) // regularization wrt warm start trajectory DCHECK(ts_ != 0) << "ts in distance_approach_ is 0"; int control_index = control_start_index_; int time_index = time_start_index_; int state_index = state_start_index_; // TODO(QiL): Initial implementation towards earlier understanding and debug // purpose, later code refine towards improving efficiency *obj_value = 0.0; // 1. objective to minimize state diff to warm up for (int i = 0; i < horizon_ + 1; ++i) { T x1_diff = x[state_index] - xWS_(0, i); T x2_diff = x[state_index + 1] - xWS_(1, i); T x3_diff = x[state_index + 2] - xWS_(2, i); T x4_abs = x[state_index + 3]; *obj_value += weight_state_x_ * x1_diff * x1_diff + weight_state_y_ * x2_diff * x2_diff + weight_state_phi_ * x3_diff * x3_diff + weight_state_v_ * x4_abs * x4_abs; state_index += 4; } // 2. objective to minimize u square for (int i = 0; i < horizon_; ++i) { *obj_value += weight_input_steer_ * x[control_index] * x[control_index] + weight_input_a_ * x[control_index + 1] * x[control_index + 1]; control_index += 2; } // 3. objective to minimize input change rate for first horizon control_index = control_start_index_; T last_time_steer_rate = (x[control_index] - last_time_u_(0, 0)) / x[time_index] / ts_; T last_time_a_rate = (x[control_index + 1] - last_time_u_(1, 0)) / x[time_index] / ts_; *obj_value += weight_stitching_steer_ * last_time_steer_rate * last_time_steer_rate + weight_stitching_a_ * last_time_a_rate * last_time_a_rate; // 4. objective to minimize input change rates, [0- horizon_ -2] time_index++; for (int i = 0; i < horizon_ - 1; ++i) { T steering_rate = (x[control_index + 2] - x[control_index]) / x[time_index] / ts_; T a_rate = (x[control_index + 3] - x[control_index + 1]) / x[time_index] / ts_; *obj_value += weight_rate_steer_ * steering_rate * steering_rate + weight_rate_a_ * a_rate * a_rate; control_index += 2; time_index++; } // 5. objective to minimize total time [0, horizon_] time_index = time_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { T first_order_penalty = weight_first_order_time_ * x[time_index]; T second_order_penalty = weight_second_order_time_ * x[time_index] * x[time_index]; *obj_value += first_order_penalty + second_order_penalty; time_index++; } // 6. end state constraints for (int i = 0; i < 4; ++i) { *obj_value += weight_end_state_ * (x[state_start_index_ + 4 * horizon_ + i] - xf_(i, 0)) * (x[state_start_index_ + 4 * horizon_ + i] - xf_(i, 0)); } } template <class T> void DistanceApproachIPOPTRelaxEndInterface::eval_constraints(int n, const T* x, int m, T* g) { // state start index int state_index = state_start_index_; // control start index. int control_index = control_start_index_; // time start index int time_index = time_start_index_; int constraint_index = 0; // // 1. state constraints 4 * [0, horizons-1] for (int i = 0; i < horizon_; ++i) { // x1 g[constraint_index] = x[state_index + 4] - (x[state_index] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * cos(x[state_index + 2] + ts_ * x[time_index] * 0.5 * x[state_index + 3] * tan(x[control_index]) / wheelbase_)); // x2 g[constraint_index + 1] = x[state_index + 5] - (x[state_index + 1] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * sin(x[state_index + 2] + ts_ * x[time_index] * 0.5 * x[state_index + 3] * tan(x[control_index]) / wheelbase_)); // x3 g[constraint_index + 2] = x[state_index + 6] - (x[state_index + 2] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * tan(x[control_index]) / wheelbase_); // x4 g[constraint_index + 3] = x[state_index + 7] - (x[state_index + 3] + ts_ * x[time_index] * x[control_index + 1]); control_index += 2; constraint_index += 4; time_index++; state_index += 4; } ADEBUG << "constraint_index after adding Euler forward dynamics constraints " "updated: " << constraint_index; // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply // steering rate as of now control_index = control_start_index_; time_index = time_start_index_; // First rate is compare first with stitch point g[constraint_index] = (x[control_index] - last_time_u_(0, 0)) / x[time_index] / ts_; control_index += 2; constraint_index++; time_index++; for (int i = 1; i < horizon_; ++i) { g[constraint_index] = (x[control_index] - x[control_index - 2]) / x[time_index] / ts_; constraint_index++; control_index += 2; time_index++; } // 3. Time constraints 1 * [0, horizons-1] time_index = time_start_index_; for (int i = 0; i < horizon_; ++i) { g[constraint_index] = x[time_index + 1] - x[time_index]; constraint_index++; time_index++; } ADEBUG << "constraint_index after adding time constraints " "updated: " << constraint_index; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 state_index = state_start_index_; int l_index = l_start_index_; int n_index = n_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); // norm(A* lambda) <= 1 T tmp1 = 0.0; T tmp2 = 0.0; for (int k = 0; k < current_edges_num; ++k) { // TODO(QiL) : replace this one directly with x tmp1 += Aj(k, 0) * x[l_index + k]; tmp2 += Aj(k, 1) * x[l_index + k]; } g[constraint_index] = tmp1 * tmp1 + tmp2 * tmp2; // G' * mu + R' * lambda == 0 g[constraint_index + 1] = x[n_index] - x[n_index + 2] + cos(x[state_index + 2]) * tmp1 + sin(x[state_index + 2]) * tmp2; g[constraint_index + 2] = x[n_index + 1] - x[n_index + 3] - sin(x[state_index + 2]) * tmp1 + cos(x[state_index + 2]) * tmp2; // -g'*mu + (A*t - b)*lambda > 0 T tmp3 = 0.0; for (int k = 0; k < 4; ++k) { tmp3 += -g_[k] * x[n_index + k]; } T tmp4 = 0.0; for (int k = 0; k < current_edges_num; ++k) { tmp4 += bj(k, 0) * x[l_index + k]; } g[constraint_index + 3] = tmp3 + (x[state_index] + cos(x[state_index + 2]) * offset_) * tmp1 + (x[state_index + 1] + sin(x[state_index + 2]) * offset_) * tmp2 - tmp4; // Update index edges_counter += current_edges_num; l_index += current_edges_num; n_index += 4; constraint_index += 4; } state_index += 4; } ADEBUG << "constraint_index after obstacles avoidance constraints " "updated: " << constraint_index; // 5. load variable bounds as constraints state_index = state_start_index_; control_index = control_start_index_; time_index = time_start_index_; l_index = l_start_index_; n_index = n_start_index_; // start configuration g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 2]; g[constraint_index + 3] = x[state_index + 3]; constraint_index += 4; state_index += 4; // constraints on x,y,v for (int i = 1; i < horizon_; ++i) { g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 3]; constraint_index += 3; state_index += 4; } // end configuration g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 2]; g[constraint_index + 3] = x[state_index + 3]; constraint_index += 4; state_index += 4; for (int i = 0; i < horizon_; ++i) { g[constraint_index] = x[control_index]; g[constraint_index + 1] = x[control_index + 1]; constraint_index += 2; control_index += 2; } for (int i = 0; i < horizon_ + 1; ++i) { g[constraint_index] = x[time_index]; constraint_index++; time_index++; } for (int i = 0; i < lambda_horizon_; ++i) { g[constraint_index] = x[l_index]; constraint_index++; l_index++; } for (int i = 0; i < miu_horizon_; ++i) { g[constraint_index] = x[n_index]; constraint_index++; n_index++; } } bool DistanceApproachIPOPTRelaxEndInterface::check_g(int n, const double* x, int m, const double* g) { int kN = n; int kM = m; double x_u_tmp[kN]; double x_l_tmp[kN]; double g_u_tmp[kM]; double g_l_tmp[kM]; get_bounds_info(n, x_l_tmp, x_u_tmp, m, g_l_tmp, g_u_tmp); const double delta_v = 1e-4; for (int idx = 0; idx < n; ++idx) { x_u_tmp[idx] = x_u_tmp[idx] + delta_v; x_l_tmp[idx] = x_l_tmp[idx] - delta_v; if (x[idx] > x_u_tmp[idx] || x[idx] < x_l_tmp[idx]) { AINFO << "x idx unfeasible: " << idx << ", x: " << x[idx] << ", lower: " << x_l_tmp[idx] << ", upper: " << x_u_tmp[idx]; } } // m1 : dynamics constatins int m1 = 4 * horizon_; // m2 : control rate constraints (only steering) int m2 = m1 + horizon_; // m3 : sampling time equality constraints int m3 = m2 + horizon_; // m4 : obstacle constraints int m4 = m3 + 4 * obstacles_num_ * (horizon_ + 1); // 5. load variable bounds as constraints // start configuration int m5 = m4 + 3 + 1; // constraints on x,y,v int m6 = m5 + 3 * (horizon_ - 1); // end configuration int m7 = m6 + 3 + 1; // control variable bnd int m8 = m7 + 2 * horizon_; // time interval variable bnd int m9 = m8 + (horizon_ + 1); // lambda_horizon_ int m10 = m9 + lambda_horizon_; // miu_horizon_ int m11 = m10 + miu_horizon_; CHECK_EQ(m11, num_of_constraints_); AINFO << "dynamics constatins to: " << m1; AINFO << "control rate constraints (only steering) to: " << m2; AINFO << "sampling time equality constraints to: " << m3; AINFO << "obstacle constraints to: " << m4; AINFO << "start conf constraints to: " << m5; AINFO << "constraints on x,y,v to: " << m6; AINFO << "end constraints to: " << m7; AINFO << "control bnd to: " << m8; AINFO << "time interval constraints to: " << m9; AINFO << "lambda constraints to: " << m10; AINFO << "miu constraints to: " << m11; AINFO << "total constraints: " << num_of_constraints_; for (int idx = 0; idx < m; ++idx) { if (g[idx] > g_u_tmp[idx] + delta_v || g[idx] < g_l_tmp[idx] - delta_v) { AINFO << "constratins idx unfeasible: " << idx << ", g: " << g[idx] << ", lower: " << g_l_tmp[idx] << ", upper: " << g_u_tmp[idx]; } } return true; } void DistanceApproachIPOPTRelaxEndInterface::generate_tapes(int n, int m, int* nnz_jac_g, int* nnz_h_lag) { std::vector<double> xp(n); std::vector<double> lamp(m); std::vector<double> zl(m); std::vector<double> zu(m); std::vector<adouble> xa(n); std::vector<adouble> g(m); std::vector<double> lam(m); double sig; adouble obj_value; double dummy = 0.0; obj_lam = new double[m + 1]; get_starting_point(n, 1, &xp[0], 0, &zl[0], &zu[0], m, 0, &lamp[0]); trace_on(tag_f); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_obj(n, &xa[0], &obj_value); obj_value >>= dummy; trace_off(); trace_on(tag_g); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { g[idx] >>= dummy; } trace_off(); trace_on(tag_L); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } for (int idx = 0; idx < m; idx++) { lam[idx] = 1.0; } sig = 1.0; eval_obj(n, &xa[0], &obj_value); obj_value *= mkparam(sig); eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { obj_value += g[idx] * mkparam(lam[idx]); } obj_value >>= dummy; trace_off(); if (enable_jacobian_ad_) { rind_g = nullptr; cind_g = nullptr; jacval = nullptr; options_g[0] = 0; /* sparsity pattern by index domains (default) */ options_g[1] = 0; /* safe mode (default) */ options_g[2] = 0; options_g[3] = 0; /* column compression (default) */ sparse_jac(tag_g, m, n, 0, &xp[0], &nnz_jac, &rind_g, &cind_g, &jacval, options_g); *nnz_jac_g = nnz_jac; } rind_L = nullptr; cind_L = nullptr; hessval = nullptr; options_L[0] = 0; options_L[1] = 1; sparse_hess(tag_L, n, 0, &xp[0], &nnz_L, &rind_L, &cind_L, &hessval, options_L); *nnz_h_lag = nnz_L; } //*************** end ADOL-C part *********************************** } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_problem.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/open_space/trajectory_smoother/distance_approach_problem.h" #include <string> #include <unordered_map> #include "modules/common/util/perf_util.h" namespace apollo { namespace planning { DistanceApproachProblem::DistanceApproachProblem( const PlannerOpenSpaceConfig& planner_open_space_config) { planner_open_space_config_ = planner_open_space_config; } bool DistanceApproachProblem::Solve( const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xF, const Eigen::MatrixXd& last_time_u, const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& s_warm_up, const std::vector<double>& XYbounds, const size_t obstacles_num, const Eigen::MatrixXi& obstacles_edges_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) { // TODO(QiL) : evaluate whether need to new it everytime PERF_BLOCK_START(); DistanceApproachInterface* ptop = nullptr; if (planner_open_space_config_.distance_approach_config() .distance_approach_mode() == DISTANCE_APPROACH_IPOPT) { ptop = new DistanceApproachIPOPTInterface( horizon, ts, ego, xWS, uWS, l_warm_up, n_warm_up, x0, xF, last_time_u, XYbounds, obstacles_edges_num, obstacles_num, obstacles_A, obstacles_b, planner_open_space_config_); } else if (planner_open_space_config_.distance_approach_config() .distance_approach_mode() == DISTANCE_APPROACH_IPOPT_FIXED_TS) { ptop = new DistanceApproachIPOPTFixedTsInterface( horizon, ts, ego, xWS, uWS, l_warm_up, n_warm_up, x0, xF, last_time_u, XYbounds, obstacles_edges_num, obstacles_num, obstacles_A, obstacles_b, planner_open_space_config_); } else if (planner_open_space_config_.distance_approach_config() .distance_approach_mode() == DISTANCE_APPROACH_IPOPT_CUDA) { ptop = new DistanceApproachIPOPTCUDAInterface( horizon, ts, ego, xWS, uWS, l_warm_up, n_warm_up, x0, xF, last_time_u, XYbounds, obstacles_edges_num, obstacles_num, obstacles_A, obstacles_b, planner_open_space_config_); } else if (planner_open_space_config_.distance_approach_config() .distance_approach_mode() == DISTANCE_APPROACH_IPOPT_FIXED_DUAL) { ptop = new DistanceApproachIPOPTFixedDualInterface( horizon, ts, ego, xWS, uWS, l_warm_up, n_warm_up, x0, xF, last_time_u, XYbounds, obstacles_edges_num, obstacles_num, obstacles_A, obstacles_b, planner_open_space_config_); } else if (planner_open_space_config_.distance_approach_config() .distance_approach_mode() == DISTANCE_APPROACH_IPOPT_RELAX_END) { ptop = new DistanceApproachIPOPTRelaxEndInterface( horizon, ts, ego, xWS, uWS, l_warm_up, n_warm_up, x0, xF, last_time_u, XYbounds, obstacles_edges_num, obstacles_num, obstacles_A, obstacles_b, planner_open_space_config_); } else if (planner_open_space_config_.distance_approach_config() .distance_approach_mode() == DISTANCE_APPROACH_IPOPT_RELAX_END_SLACK) { ptop = new DistanceApproachIPOPTRelaxEndSlackInterface( horizon, ts, ego, xWS, uWS, l_warm_up, n_warm_up, s_warm_up, x0, xF, last_time_u, XYbounds, obstacles_edges_num, obstacles_num, obstacles_A, obstacles_b, planner_open_space_config_); } Ipopt::SmartPtr<Ipopt::TNLP> problem = ptop; // Create an instance of the IpoptApplication Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory(); app->Options()->SetIntegerValue( "print_level", planner_open_space_config_.distance_approach_config() .ipopt_config() .ipopt_print_level()); app->Options()->SetIntegerValue( "mumps_mem_percent", planner_open_space_config_.distance_approach_config() .ipopt_config() .mumps_mem_percent()); app->Options()->SetNumericValue( "mumps_pivtol", planner_open_space_config_.distance_approach_config() .ipopt_config() .mumps_pivtol()); app->Options()->SetIntegerValue( "max_iter", planner_open_space_config_.distance_approach_config() .ipopt_config() .ipopt_max_iter()); app->Options()->SetNumericValue( "tol", planner_open_space_config_.distance_approach_config() .ipopt_config() .ipopt_tol()); app->Options()->SetNumericValue( "acceptable_constr_viol_tol", planner_open_space_config_.distance_approach_config() .ipopt_config() .ipopt_acceptable_constr_viol_tol()); app->Options()->SetNumericValue( "min_hessian_perturbation", planner_open_space_config_.distance_approach_config() .ipopt_config() .ipopt_min_hessian_perturbation()); app->Options()->SetNumericValue( "jacobian_regularization_value", planner_open_space_config_.distance_approach_config() .ipopt_config() .ipopt_jacobian_regularization_value()); app->Options()->SetStringValue( "print_timing_statistics", planner_open_space_config_.distance_approach_config() .ipopt_config() .ipopt_print_timing_statistics()); app->Options()->SetStringValue( "alpha_for_y", planner_open_space_config_.distance_approach_config() .ipopt_config() .ipopt_alpha_for_y()); app->Options()->SetStringValue( "recalc_y", planner_open_space_config_.distance_approach_config() .ipopt_config() .ipopt_recalc_y()); app->Options()->SetNumericValue( "mu_init", planner_open_space_config_.distance_approach_config() .ipopt_config() .ipopt_mu_init()); Ipopt::ApplicationReturnStatus status = app->Initialize(); if (status != Ipopt::Solve_Succeeded) { AERROR << "*** Distance Approach problem error during initialization!"; return false; } status = app->OptimizeTNLP(problem); 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 << '.'; PERF_BLOCK_END("DistanceApproachProblemSolving"); } else { /* return detailed failure information, reference resource: Ipopt::ApplicationReturnStatus, https:// www.coin-or.org/Doxygen/CoinAll/_ip_return_codes__inc_8h-source.html */ std::unordered_map<int, std::string> failure_status = { {0, "Solve_Succeeded"}, {1, "Solved_To_Acceptable_Level"}, {2, "Infeasible_Problem_Detected"}, {3, "Search_Direction_Becomes_Too_Small"}, {4, "Diverging_Iterates"}, {5, "User_Requested_Stop"}, {6, "Feasible_Point_Found"}, {-1, "Maximum_Iterations_Exceeded"}, {-2, "Restoration_Failed"}, {-3, "Error_In_Step_Computation"}, {-10, "Not_Enough_Degrees_Of_Freedom"}, {-11, "Invalid_Problem_Definition"}, {-12, "Invalid_Option"}, {-13, "Invalid_Number_Detected"}, {-100, "Unrecoverable_Exception"}, {-101, "NonIpopt_Exception_Thrown"}, {-102, "Insufficient_Memory"}, {-199, "Internal_Error"}}; if (!failure_status.count(static_cast<size_t>(status))) { AINFO << "Solver ends with unknown failure code: " << static_cast<int>(status); } else { AINFO << "Solver failure case: " << failure_status[static_cast<size_t>(status)]; } } ptop->get_optimization_results(state_result, control_result, time_result, dual_l_result, dual_n_result); return status == Ipopt::Solve_Succeeded || status == Ipopt::Solved_To_Acceptable_Level; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_ipopt_qp_interface.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/open_space/trajectory_smoother/dual_variable_warm_start_ipopt_qp_interface.h" #include "cyber/common/log.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { DualVariableWarmStartIPOPTQPInterface::DualVariableWarmStartIPOPTQPInterface( size_t horizon, double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const Eigen::MatrixXd& xWS, const PlannerOpenSpaceConfig& planner_open_space_config) : ts_(ts), ego_(ego), obstacles_edges_num_(obstacles_edges_num), obstacles_A_(obstacles_A), obstacles_b_(obstacles_b), xWS_(xWS) { ACHECK(horizon < std::numeric_limits<int>::max()) << "Invalid cast on horizon in open space planner"; horizon_ = static_cast<int>(horizon); ACHECK(obstacles_num < std::numeric_limits<int>::max()) << "Invalid cast on obstacles_num in open space planner"; obstacles_num_ = static_cast<int>(obstacles_num); w_ev_ = ego_(1, 0) + ego_(3, 0); l_ev_ = ego_(0, 0) + ego_(2, 0); g_ = {l_ev_ / 2, w_ev_ / 2, l_ev_ / 2, w_ev_ / 2}; offset_ = (ego_(0, 0) + ego_(2, 0)) / 2 - ego_(2, 0); obstacles_edges_sum_ = obstacles_edges_num_.sum(); l_start_index_ = 0; n_start_index_ = l_start_index_ + obstacles_edges_sum_ * (horizon_ + 1); l_warm_up_ = Eigen::MatrixXd::Zero(obstacles_edges_sum_, horizon_ + 1); n_warm_up_ = Eigen::MatrixXd::Zero(4 * obstacles_num_, horizon_ + 1); min_safety_distance_ = planner_open_space_config.dual_variable_warm_start_config() .min_safety_distance(); } bool DualVariableWarmStartIPOPTQPInterface::get_nlp_info( int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) { lambda_horizon_ = obstacles_edges_sum_ * (horizon_ + 1); miu_horizon_ = obstacles_num_ * 4 * (horizon_ + 1); dual_formulation_horizon_ = obstacles_num_ * (horizon_ + 1); num_of_variables_ = lambda_horizon_ + miu_horizon_; num_of_constraints_ = 3 * obstacles_num_ * (horizon_ + 1) + num_of_variables_; // number of variables n = num_of_variables_; // number of constraints m = num_of_constraints_; // number of nonzero Jacobian and Lagrangian. generate_tapes(n, m, &nnz_h_lag); int tmp = 0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); tmp += current_edges_num * 3 + 2 + 2 + 4; } } nnz_jac_g = tmp + num_of_variables_; ADEBUG << "nnz_jac_g : " << nnz_jac_g; index_style = IndexStyleEnum::C_STYLE; return true; } bool DualVariableWarmStartIPOPTQPInterface::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) { ADEBUG << "get_starting_point"; ACHECK(init_x) << "Warm start init_x setting failed"; ACHECK(!init_z) << "Warm start init_z setting failed"; ACHECK(!init_lambda) << "Warm start init_lambda setting failed"; int l_index = l_start_index_; int n_index = n_start_index_; ADEBUG << "l_start_index_ : " << l_start_index_; ADEBUG << "n_start_index_ : " << n_start_index_; // 1. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { x[l_index] = 0.5; ++l_index; } } // 2. lagrange constraint n, 4*obstacles_num * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { x[n_index] = 1.0; ++n_index; } } ADEBUG << "get_starting_point out"; return true; } bool DualVariableWarmStartIPOPTQPInterface::get_bounds_info(int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) { int variable_index = 0; // 1. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0, // horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; ++variable_index; } } ADEBUG << "variable_index after adding lagrange l : " << variable_index; // 2. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // nlp_upper_bound_limit ++variable_index; } } ADEBUG << "variable_index after adding lagrange n : " << variable_index; int constraint_index = 0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { // a. G'*mu + R'*A*lambda = 0 g_l[constraint_index] = 0.0; g_u[constraint_index] = 0.0; g_l[constraint_index + 1] = 0.0; g_u[constraint_index + 1] = 0.0; // b. (-g'*mu + (A*t - b)*lambda) >= 0 g_l[constraint_index + 2] = min_safety_distance_; g_u[constraint_index + 2] = 2e19; constraint_index += 3; } } int l_index = l_start_index_; int n_index = n_start_index_; for (int i = 0; i < lambda_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; l_index++; } for (int i = 0; i < miu_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; n_index++; } ADEBUG << "constraint_index after adding obstacles constraints: " << constraint_index; return true; } bool DualVariableWarmStartIPOPTQPInterface::eval_f(int n, const double* x, bool new_x, double& obj_value) { eval_obj(n, x, &obj_value); return true; } bool DualVariableWarmStartIPOPTQPInterface::eval_grad_f(int n, const double* x, bool new_x, double* grad_f) { std::fill(grad_f, grad_f + n, 0.0); int l_index = l_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; // assume: stationary obstacles for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); // norm(A* lambda) double tmp1 = 0.0; double tmp2 = 0.0; for (int k = 0; k < current_edges_num; ++k) { tmp1 += Aj(k, 0) * x[l_index + k]; tmp2 += Aj(k, 1) * x[l_index + k]; } for (int k = 0; k < current_edges_num; ++k) { grad_f[l_index + k] += 2.0 * tmp1 * Aj(k, 0) + 2.0 * tmp2 * Aj(k, 1); } // Update index edges_counter += current_edges_num; l_index += current_edges_num; } } return true; } bool DualVariableWarmStartIPOPTQPInterface::eval_g(int n, const double* x, bool new_x, int m, double* g) { eval_constraints(n, x, m, g); return true; } bool DualVariableWarmStartIPOPTQPInterface::eval_jac_g(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { ADEBUG << "eval_jac_g"; if (values == nullptr) { int nz_index = 0; int constraint_index = 0; // 1. Three obstacles related equal constraints, one equality // constraints, // [0, horizon_] * [0, obstacles_num_-1] * 3 int l_index = l_start_index_; int n_index = n_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); // 1. G' * mu + R' * lambda == 0, part 1 // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index] = constraint_index; jCol[nz_index] = l_index + k; ++nz_index; } // With respect to n iRow[nz_index] = constraint_index; jCol[nz_index] = n_index; ++nz_index; iRow[nz_index] = constraint_index; jCol[nz_index] = n_index + 2; ++nz_index; // 2. G' * mu + R' * lambda == 0, part 2 // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index] = constraint_index + 1; jCol[nz_index] = l_index + k; ++nz_index; } // With respect to n iRow[nz_index] = constraint_index + 1; jCol[nz_index] = n_index + 1; ++nz_index; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = n_index + 3; ++nz_index; // 3. -g'*mu + (A*t - b)*lambda > 0 // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index] = constraint_index + 2; jCol[nz_index] = l_index + k; ++nz_index; } // with respect to n for (int k = 0; k < 4; ++k) { iRow[nz_index] = constraint_index + 2; jCol[nz_index] = n_index + k; ++nz_index; } // Update index l_index += current_edges_num; n_index += 4; constraint_index += 3; } } l_index = l_start_index_; n_index = n_start_index_; for (int i = 0; i < lambda_horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = l_index; ++nz_index; ++constraint_index; ++l_index; } for (int i = 0; i < miu_horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = n_index; ++nz_index; ++constraint_index; ++n_index; } CHECK_EQ(constraint_index, m) << "No. of constraints wrong in eval_jac_g."; ADEBUG << "nz_index here : " << nz_index << " nele_jac is : " << nele_jac; } else { std::fill(values, values + nele_jac, 0.0); int nz_index = 0; // 1. Three obstacles related equal constraints, one equality // constraints, // [0, horizon_] * [0, obstacles_num_-1] * 3 int l_index = l_start_index_; int n_index = n_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); double tmp1 = 0; double tmp2 = 0; for (int k = 0; k < current_edges_num; ++k) { // TODO(QiL) : replace this one directly with x tmp1 += Aj(k, 0) * x[l_index + k]; tmp2 += Aj(k, 1) * x[l_index + k]; } // 1. G' * mu + R' * lambda == 0, part 1 // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index] = std::cos(xWS_(2, i)) * Aj(k, 0) + std::sin(xWS_(2, i)) * Aj(k, 1); // v0~vn ++nz_index; } // With respect to n values[nz_index] = 1.0; // w0 ++nz_index; values[nz_index] = -1.0; // w2 ++nz_index; ADEBUG << "eval_jac_g, after adding part 2"; // 1. G' * mu + R' * lambda == 0, part 2 // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index] = -std::sin(xWS_(2, i)) * Aj(k, 0) + std::cos(xWS_(2, i)) * Aj(k, 1); // y0~yn ++nz_index; } // With respect to n values[nz_index] = 1.0; // z1 ++nz_index; values[nz_index] = -1.0; // z3 ++nz_index; // 2. -g'*mu + (A*t - b)*lambda > 0 // TODO(QiL): Revise dual variables modeling here. double tmp3 = 0.0; double tmp4 = 0.0; for (int k = 0; k < 4; ++k) { tmp3 += -g_[k] * x[n_index + k]; } for (int k = 0; k < current_edges_num; ++k) { tmp4 += bj(k, 0) * x[l_index + k]; } // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index] = (xWS_(0, i) + std::cos(xWS_(2, i)) * offset_) * Aj(k, 0) + (xWS_(1, i) + std::sin(xWS_(2, i)) * offset_) * Aj(k, 1) - bj(k, 0); // ddk ++nz_index; } // with respect to n for (int k = 0; k < 4; ++k) { values[nz_index] = -g_[k]; // eek ++nz_index; } // Update index edges_counter += current_edges_num; l_index += current_edges_num; n_index += 4; } } for (int i = 0; i < lambda_horizon_; ++i) { values[nz_index] = 1.0; ++nz_index; } for (int i = 0; i < miu_horizon_; ++i) { values[nz_index] = 1.0; ++nz_index; } ADEBUG << "eval_jac_g, fulfilled obstacle constraint values"; CHECK_EQ(nz_index, nele_jac); } ADEBUG << "eval_jac_g done"; return true; } bool DualVariableWarmStartIPOPTQPInterface::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) { // return the structure. This is a symmetric matrix, fill the lower left // triangle only. for (int idx = 0; idx < nnz_L; idx++) { iRow[idx] = rind_L[idx]; jCol[idx] = cind_L[idx]; } } else { // return the values. This is a symmetric matrix, fill the lower left // triangle only obj_lam[0] = obj_factor; for (int idx = 0; idx < m; idx++) { obj_lam[1 + idx] = lambda[idx]; } set_param_vec(tag_L, m + 1, obj_lam); sparse_hess(tag_L, n, 1, const_cast<double*>(x), &nnz_L, &rind_L, &cind_L, &hessval, options_L); for (int idx = 0; idx < nnz_L; idx++) { values[idx] = hessval[idx]; } } return true; } void DualVariableWarmStartIPOPTQPInterface::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) { int variable_index = 0; // 1. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0, // horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { l_warm_up_(j, i) = x[variable_index]; ++variable_index; } } ADEBUG << "variable_index after adding lagrange l : " << variable_index; // 2. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { n_warm_up_(j, i) = x[variable_index]; ++variable_index; } } ADEBUG << "variable_index after adding lagrange n : " << variable_index; // memory deallocation of ADOL-C variables delete[] obj_lam; free(rind_L); free(cind_L); free(hessval); } void DualVariableWarmStartIPOPTQPInterface::get_optimization_results( Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up) const { *l_warm_up = l_warm_up_; *n_warm_up = n_warm_up_; } void DualVariableWarmStartIPOPTQPInterface::check_solution( const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up) { // wrap input solution int kNumVariables = num_of_variables_; double x[kNumVariables]; int variable_index = 0; // 1. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0, // horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { x[variable_index] = l_warm_up(j, i); ++variable_index; } } // 2. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { x[variable_index] = n_warm_up(j, i); ++variable_index; } } // evaluate constraints int kNumConstraint = num_of_constraints_; double g[kNumConstraint]; eval_g(num_of_variables_, x, true, num_of_constraints_, g); // get the boundaries double x_l[kNumVariables]; double x_u[kNumVariables]; double g_l[kNumConstraint]; double g_u[kNumConstraint]; get_bounds_info(num_of_variables_, x_l, x_u, num_of_constraints_, g_l, g_u); // compare g with g_l & g_u int constraint_index = 0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { // G' * mu + R' * A * lambda == 0 if (g_l[constraint_index + 0] > g[constraint_index + 0] || g_u[constraint_index + 0] < g[constraint_index + 0]) { AERROR << "G' * mu + R' * A * lambda == 0 constraint fails, " << "constraint_index: " << constraint_index + 0 << ", g: " << g[constraint_index + 0]; } if (g_l[constraint_index + 1] > g[constraint_index + 1] || g_u[constraint_index + 1] < g[constraint_index + 1]) { AERROR << "G' * mu + R' * A * lambda == 0 constraint fails, " << "constraint_index: " << constraint_index + 1 << ", g: " << g[constraint_index + 1]; } // -g' * mu + (A * t - b) * lambda) >= d_min if (g_l[constraint_index + 2] > g[constraint_index + 2] || g_u[constraint_index + 2] < g[constraint_index + 2]) { AERROR << "-g' * mu + (A * t - b) * lambda) >= d_min constraint fails, " << "constraint_index: " << constraint_index + 2 << ", g: " << g[constraint_index + 2]; } // Update index constraint_index += 3; } } for (int i = 0; i < lambda_horizon_; ++i) { if (g_l[constraint_index] > g[constraint_index] || g_u[constraint_index] < g[constraint_index]) { AERROR << "lambda box constraint fails, " << "constraint_index: " << constraint_index << ", g: " << g[constraint_index]; } constraint_index++; } for (int i = 0; i < miu_horizon_; ++i) { if (g_l[constraint_index] > g[constraint_index] || g_u[constraint_index] < g[constraint_index]) { AERROR << "miu box constraint fails, " << "constraint_index: " << constraint_index << ", g: " << g[constraint_index]; } constraint_index++; } } //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> bool DualVariableWarmStartIPOPTQPInterface::eval_obj(int n, const T* x, T* obj_value) { ADEBUG << "eval_obj"; *obj_value = 0.0; int l_index = l_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; // assume: stationary obstacles for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); // norm(A* lambda) <= 1 T tmp1 = 0.0; T tmp2 = 0.0; for (int k = 0; k < current_edges_num; ++k) { tmp1 += Aj(k, 0) * x[l_index + k]; tmp2 += Aj(k, 1) * x[l_index + k]; } *obj_value += tmp1 * tmp1 + tmp2 * tmp2; // Update index edges_counter += current_edges_num; l_index += current_edges_num; } } return true; } /** Template to compute constraints */ template <class T> bool DualVariableWarmStartIPOPTQPInterface::eval_constraints(int n, const T* x, int m, T* g) { ADEBUG << "eval_constraints"; // state start index // 1. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 int l_index = l_start_index_; int n_index = n_start_index_; int constraint_index = 0; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; // assume: stationary obstacles for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); // A * lambda T tmp1 = 0.0; T tmp2 = 0.0; for (int k = 0; k < current_edges_num; ++k) { tmp1 += Aj(k, 0) * x[l_index + k]; tmp2 += Aj(k, 1) * x[l_index + k]; } // G' * mu + R' * A * lambda == 0 g[constraint_index + 0] = x[n_index] - x[n_index + 2] + cos(xWS_(2, i)) * tmp1 + sin(xWS_(2, i)) * tmp2; g[constraint_index + 1] = x[n_index + 1] - x[n_index + 3] - sin(xWS_(2, i)) * tmp1 + cos(xWS_(2, i)) * tmp2; // (-g' * mu + (A * t - b) * lambda) >= d_min T tmp3 = 0.0; for (int k = 0; k < 4; ++k) { tmp3 += g_[k] * x[n_index + k]; } T tmp4 = 0.0; for (int k = 0; k < current_edges_num; ++k) { tmp4 += bj(k, 0) * x[l_index + k]; } g[constraint_index + 2] = -tmp3 + (xWS_(0, i) + cos(xWS_(2, i)) * offset_) * tmp1 + (xWS_(1, i) + sin(xWS_(2, i)) * offset_) * tmp2 - tmp4; // Update index edges_counter += current_edges_num; l_index += current_edges_num; n_index += 4; constraint_index += 3; } } l_index = l_start_index_; n_index = n_start_index_; for (int i = 0; i < lambda_horizon_; ++i) { g[constraint_index] = x[l_index]; constraint_index++; l_index++; } for (int i = 0; i < miu_horizon_; ++i) { g[constraint_index] = x[n_index]; constraint_index++; n_index++; } CHECK_EQ(constraint_index, m) << "No. of constraints wrong in eval_g. n : " << n; return true; } /** Method to generate the required tapes */ void DualVariableWarmStartIPOPTQPInterface::generate_tapes(int n, int m, int* nnz_h_lag) { std::vector<double> xp(n); std::vector<double> lamp(m); std::vector<double> zl(m); std::vector<double> zu(m); std::vector<adouble> xa(n); std::vector<adouble> g(m); std::vector<double> lam(m); double sig; adouble obj_value; double dummy = 0.0; obj_lam = new double[m + 1]; get_starting_point(n, 1, &xp[0], 0, &zl[0], &zu[0], m, 0, &lamp[0]); // trace_on(tag_f); // for (int idx = 0; idx < n; idx++) xa[idx] <<= xp[idx]; // eval_obj(n, xa, &obj_value); // obj_value >>= dummy; // trace_off(); // trace_on(tag_g); // for (int idx = 0; idx < n; idx++) xa[idx] <<= xp[idx]; // eval_constraints(n, xa, m, g); // for (int idx = 0; idx < m; idx++) g[idx] >>= dummy; // trace_off(); trace_on(tag_L); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } for (int idx = 0; idx < m; idx++) { lam[idx] = 1.0; } sig = 1.0; eval_obj(n, &xa[0], &obj_value); obj_value *= mkparam(sig); eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { obj_value += g[idx] * mkparam(lam[idx]); } obj_value >>= dummy; trace_off(); rind_L = nullptr; cind_L = nullptr; hessval = nullptr; options_L[0] = 0; options_L[1] = 1; sparse_hess(tag_L, n, 0, &xp[0], &nnz_L, &rind_L, &cind_L, &hessval, options_L); *nnz_h_lag = nnz_L; } //*************** end ADOL-C part *********************************** } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/planning_block.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 #if GPU_PLATFORM == NVIDIA #include <cuda_runtime.h> #elif GPU_PLATFORM == AMD #include <hip/hip_runtime.h> #define cudaDeviceProp hipDeviceProp_t #define cudaDeviceReset hipDeviceReset #define cudaDeviceSynchronize hipDeviceSynchronize #define cudaError_t hipError_t #define cudaFree hipFree #define cudaGetDeviceProperties hipGetDeviceProperties #define cudaGetErrorString hipGetErrorString #define cudaMalloc hipMalloc #define cudaMemcpy hipMemcpy #define cudaMemcpyDeviceToHost hipMemcpyDeviceToHost #define cudaMemcpyHostToDevice hipMemcpyHostToDevice #define cudaSetDevice hipSetDevice #define cudaSuccess hipSuccess #endif namespace apollo { namespace planning { #define BLOCK_WIDTH 16 #define BLOCK_HEIGHT 16 #define BLOCK_1 256 #define TEMPLATE_ROUTINE_INSTANCE(ret, routine) template ret routine #define DATA_TRANSFER_INST(type) \ TEMPLATE_ROUTINE_INSTANCE( \ bool, data_transfer(type *dst, const type *src, const int size)) #define CUDA_CHECK(call) \ { \ const cudaError_t error = call; \ if (error != cudaSuccess) { \ printf("Error: %s:%d, ", __FILE__, __LINE__); \ printf("code: %d, reasone: %s\n", error, cudaGetErrorString(error)); \ return false; \ } \ } bool InitialCuda(); __global__ void fill_lower_left_gpu(int *iRow, int *jCol, unsigned int *rind_L, unsigned int *cind_L, const int nnz_L); template <typename T> __global__ void data_transfer_gpu(T *dst, const T *src, const int size); bool fill_lower_left(int *iRow, int *jCol, unsigned int *rind_L, unsigned int *cind_L, const int nnz_L); template <typename T> bool data_transfer(T *dst, const T *src, const int size); } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_relax_end_slack_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 */ #pragma once #include <algorithm> #include <limits> #include <vector> #include <omp.h> #include <adolc/adolc.h> #include <adolc/adolc_openmp.h> #include <adolc/adolc_sparse.h> #include <adolc/adouble.h> #include <coin/IpTNLP.hpp> #include <coin/IpTypes.hpp> #include "Eigen/Dense" #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_interface.h" #include "modules/planning/proto/planner_open_space_config.pb.h" #define tag_f 1 #define tag_g 2 #define tag_L 3 #define HPOFF 30 namespace apollo { namespace planning { class DistanceApproachIPOPTRelaxEndSlackInterface : public DistanceApproachInterface { public: DistanceApproachIPOPTRelaxEndSlackInterface( const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& s_warm_up, const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xf, const Eigen::MatrixXd& last_time_u, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const PlannerOpenSpaceConfig& planner_open_space_config); virtual ~DistanceApproachIPOPTRelaxEndSlackInterface() = default; /** Method to return some info about the nlp */ bool get_nlp_info(int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, // NOLINT IndexStyleEnum& index_style) override; // NOLINT /** 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; /** Check unfeasible constraints for further study**/ bool check_g(int n, const double* x, int m, const double* g); /** 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; // sequential implementation to jac_g bool eval_jac_g_ser(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 get_optimization_results(Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) const override; //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> void eval_obj(int n, const T* x, T* obj_value); /** Template to compute constraints */ template <class T> void eval_constraints(int n, const T* x, int m, T* g); /** Method to generate the required tapes by ADOL-C*/ void generate_tapes(int n, int m, int* nnz_jac_g, int* nnz_h_lag); //*************** end ADOL-C part *********************************** private: int num_of_variables_ = 0; int num_of_constraints_ = 0; int horizon_ = 0; int lambda_horizon_ = 0; int miu_horizon_ = 0; int slack_horizon_ = 0; double ts_ = 0.0; Eigen::MatrixXd ego_; Eigen::MatrixXd xWS_; Eigen::MatrixXd uWS_; Eigen::MatrixXd l_warm_up_; Eigen::MatrixXd n_warm_up_; Eigen::MatrixXd slack_warm_up_; Eigen::MatrixXd x0_; Eigen::MatrixXd xf_; Eigen::MatrixXd last_time_u_; std::vector<double> XYbounds_; // debug flag bool enable_constraint_check_; // penalty double weight_state_x_ = 0.0; double weight_state_y_ = 0.0; double weight_state_phi_ = 0.0; double weight_state_v_ = 0.0; double weight_input_steer_ = 0.0; double weight_input_a_ = 0.0; double weight_rate_steer_ = 0.0; double weight_rate_a_ = 0.0; double weight_stitching_steer_ = 0.0; double weight_stitching_a_ = 0.0; double weight_first_order_time_ = 0.0; double weight_second_order_time_ = 0.0; double weight_end_state_ = 0.0; double weight_slack_ = 0.0; double w_ev_ = 0.0; double l_ev_ = 0.0; std::vector<double> g_; double offset_ = 0.0; Eigen::MatrixXi obstacles_edges_num_; int obstacles_num_ = 0; int obstacles_edges_sum_ = 0; double wheelbase_ = 0.0; Eigen::MatrixXd state_result_; Eigen::MatrixXd dual_l_result_; Eigen::MatrixXd dual_n_result_; Eigen::MatrixXd control_result_; Eigen::MatrixXd time_result_; Eigen::MatrixXd slack_result_; // obstacles_A Eigen::MatrixXd obstacles_A_; // obstacles_b Eigen::MatrixXd obstacles_b_; // whether to use fix time bool use_fix_time_ = false; // state start index int state_start_index_ = 0; // control start index. int control_start_index_ = 0; // time start index int time_start_index_ = 0; // lagrangian l start index int l_start_index_ = 0; // lagrangian n start index int n_start_index_ = 0; // slack s start index int slack_index_ = 0; double min_safety_distance_ = 0.0; double max_safety_distance_ = 0.0; double max_steer_angle_ = 0.0; double max_speed_forward_ = 0.0; double max_speed_reverse_ = 0.0; double max_acceleration_forward_ = 0.0; double max_acceleration_reverse_ = 0.0; double min_time_sample_scaling_ = 0.0; double max_time_sample_scaling_ = 0.0; double max_steer_rate_ = 0.0; double max_lambda_ = 0.0; double max_miu_ = 0.0; bool enable_jacobian_ad_ = false; private: DistanceApproachConfig distance_approach_config_; const common::VehicleParam vehicle_param_ = common::VehicleConfigHelper::GetConfig().vehicle_param(); private: //*************** start ADOL-C part *********************************** double* obj_lam; //** variables for sparsity exploitation unsigned int* rind_g; /* row indices */ unsigned int* cind_g; /* column indices */ double* jacval; /* values */ unsigned int* rind_L; /* row indices */ unsigned int* cind_L; /* column indices */ double* hessval; /* values */ int nnz_jac; int nnz_L; int options_g[4]; int options_L[4]; //*************** end ADOL-C part *********************************** }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_problem.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/open_space/trajectory_smoother/dual_variable_warm_start_problem.h" #include <coin/IpIpoptApplication.hpp> #include <coin/IpSolveStatistics.hpp> #include "cyber/common/log.h" #include "modules/common/util/perf_util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { DualVariableWarmStartProblem::DualVariableWarmStartProblem( const PlannerOpenSpaceConfig& planner_open_space_config) { planner_open_space_config_ = planner_open_space_config; } bool DualVariableWarmStartProblem::Solve( const size_t horizon, const double ts, const Eigen::MatrixXd& ego, size_t obstacles_num, const Eigen::MatrixXi& obstacles_edges_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const Eigen::MatrixXd& xWS, Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up, Eigen::MatrixXd* s_warm_up) { PERF_BLOCK_START() bool solver_flag = false; if (planner_open_space_config_.dual_variable_warm_start_config() .qp_format() == OSQP) { DualVariableWarmStartOSQPInterface ptop = DualVariableWarmStartOSQPInterface( horizon, ts, ego, obstacles_edges_num, obstacles_num, obstacles_A, obstacles_b, xWS, planner_open_space_config_); if (ptop.optimize()) { ADEBUG << "dual warm up done."; ptop.get_optimization_results(l_warm_up, n_warm_up); PERF_BLOCK_END("DualVariableWarmStartSolving"); solver_flag = true; } else { AWARN << "dual warm up fail."; ptop.get_optimization_results(l_warm_up, n_warm_up); solver_flag = false; } } else if (planner_open_space_config_.dual_variable_warm_start_config() .qp_format() == SLACKQP) { DualVariableWarmStartSlackOSQPInterface ptop = DualVariableWarmStartSlackOSQPInterface( horizon, ts, ego, obstacles_edges_num, obstacles_num, obstacles_A, obstacles_b, xWS, planner_open_space_config_); if (ptop.optimize()) { ADEBUG << "dual warm up done."; ptop.get_optimization_results(l_warm_up, n_warm_up, s_warm_up); PERF_BLOCK_END("DualVariableWarmStartSolving"); solver_flag = true; } else { AWARN << "dual warm up fail."; ptop.get_optimization_results(l_warm_up, n_warm_up, s_warm_up); solver_flag = false; } } else if (planner_open_space_config_.dual_variable_warm_start_config() .qp_format() == IPOPTQP) { DualVariableWarmStartIPOPTQPInterface* ptop = new DualVariableWarmStartIPOPTQPInterface( horizon, ts, ego, obstacles_edges_num, obstacles_num, obstacles_A, obstacles_b, xWS, planner_open_space_config_); Ipopt::SmartPtr<Ipopt::TNLP> problem = ptop; // Create an instance of the IpoptApplication Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory(); app->Options()->SetIntegerValue( "print_level", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_print_level()); app->Options()->SetIntegerValue( "mumps_mem_percent", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .mumps_mem_percent()); app->Options()->SetNumericValue( "mumps_pivtol", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .mumps_pivtol()); app->Options()->SetIntegerValue( "max_iter", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_max_iter()); app->Options()->SetNumericValue( "tol", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_tol()); app->Options()->SetNumericValue( "acceptable_constr_viol_tol", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_acceptable_constr_viol_tol()); app->Options()->SetNumericValue( "min_hessian_perturbation", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_min_hessian_perturbation()); app->Options()->SetNumericValue( "jacobian_regularization_value", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_jacobian_regularization_value()); app->Options()->SetStringValue( "print_timing_statistics", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_print_timing_statistics()); app->Options()->SetStringValue( "alpha_for_y", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_alpha_for_y()); app->Options()->SetStringValue( "recalc_y", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_recalc_y()); // for qp problem speed up app->Options()->SetStringValue("mehrotra_algorithm", "yes"); Ipopt::ApplicationReturnStatus status = app->Initialize(); if (status != Ipopt::Solve_Succeeded) { AERROR << "*** Dual variable wart start problem error during " "initialization!"; return false; } status = app->OptimizeTNLP(problem); 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 << '.'; PERF_BLOCK_END("DualVariableWarmStartSolving"); } else { ADEBUG << "Solve not succeeding, return status: " << int(status); } ptop->get_optimization_results(l_warm_up, n_warm_up); solver_flag = (status == Ipopt::Solve_Succeeded || status == Ipopt::Solved_To_Acceptable_Level); } else if (planner_open_space_config_.dual_variable_warm_start_config() .qp_format() == IPOPT) { DualVariableWarmStartIPOPTInterface* ptop = new DualVariableWarmStartIPOPTInterface( horizon, ts, ego, obstacles_edges_num, obstacles_num, obstacles_A, obstacles_b, xWS, planner_open_space_config_); Ipopt::SmartPtr<Ipopt::TNLP> problem = ptop; // Create an instance of the IpoptApplication Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory(); app->Options()->SetIntegerValue( "print_level", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_print_level()); app->Options()->SetIntegerValue( "mumps_mem_percent", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .mumps_mem_percent()); app->Options()->SetNumericValue( "mumps_pivtol", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .mumps_pivtol()); app->Options()->SetIntegerValue( "max_iter", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_max_iter()); app->Options()->SetNumericValue( "tol", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_tol()); app->Options()->SetNumericValue( "acceptable_constr_viol_tol", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_acceptable_constr_viol_tol()); app->Options()->SetNumericValue( "min_hessian_perturbation", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_min_hessian_perturbation()); app->Options()->SetNumericValue( "jacobian_regularization_value", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_jacobian_regularization_value()); app->Options()->SetStringValue( "print_timing_statistics", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_print_timing_statistics()); app->Options()->SetStringValue( "alpha_for_y", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_alpha_for_y()); app->Options()->SetStringValue( "recalc_y", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_recalc_y()); Ipopt::ApplicationReturnStatus status = app->Initialize(); if (status != Ipopt::Solve_Succeeded) { AERROR << "*** Dual variable wart start problem error during " "initialization!"; return false; } status = app->OptimizeTNLP(problem); 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 << '.'; PERF_BLOCK_END("DualVariableWarmStartSolving"); } else { ADEBUG << "Solve not succeeding, return status: " << int(status); } ptop->get_optimization_results(l_warm_up, n_warm_up); solver_flag = (status == Ipopt::Solve_Succeeded || status == Ipopt::Solved_To_Acceptable_Level); } else { // debug mode DualVariableWarmStartOSQPInterface* ptop_osqp = new DualVariableWarmStartOSQPInterface( horizon, ts, ego, obstacles_edges_num, obstacles_num, obstacles_A, obstacles_b, xWS, planner_open_space_config_); bool succ = ptop_osqp->optimize(); if (!succ) { AERROR << "dual warm up fail."; ptop_osqp->get_optimization_results(l_warm_up, n_warm_up); } ADEBUG << "dual warm up done."; ptop_osqp->get_optimization_results(l_warm_up, n_warm_up); PERF_BLOCK_END("DualVariableWarmStartSolving"); // ipoptqp result Eigen::MatrixXd l_warm_up_ipoptqp(l_warm_up->rows(), l_warm_up->cols()); Eigen::MatrixXd n_warm_up_ipoptqp(n_warm_up->rows(), n_warm_up->cols()); DualVariableWarmStartIPOPTQPInterface* ptop_ipoptqp = new DualVariableWarmStartIPOPTQPInterface( horizon, ts, ego, obstacles_edges_num, obstacles_num, obstacles_A, obstacles_b, xWS, planner_open_space_config_); Ipopt::SmartPtr<Ipopt::TNLP> problem = ptop_ipoptqp; // Create an instance of the IpoptApplication Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory(); app->Options()->SetIntegerValue( "print_level", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_print_level()); app->Options()->SetIntegerValue( "mumps_mem_percent", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .mumps_mem_percent()); app->Options()->SetNumericValue( "mumps_pivtol", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .mumps_pivtol()); app->Options()->SetIntegerValue( "max_iter", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_max_iter()); app->Options()->SetNumericValue( "tol", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_tol()); app->Options()->SetNumericValue( "acceptable_constr_viol_tol", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_acceptable_constr_viol_tol()); app->Options()->SetNumericValue( "min_hessian_perturbation", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_min_hessian_perturbation()); app->Options()->SetNumericValue( "jacobian_regularization_value", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_jacobian_regularization_value()); app->Options()->SetStringValue( "print_timing_statistics", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_print_timing_statistics()); app->Options()->SetStringValue( "alpha_for_y", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_alpha_for_y()); app->Options()->SetStringValue( "recalc_y", planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config() .ipopt_recalc_y()); // for qp problem speed up app->Options()->SetStringValue("mehrotra_algorithm", "yes"); Ipopt::ApplicationReturnStatus status = app->Initialize(); if (status != Ipopt::Solve_Succeeded) { AERROR << "*** Dual variable wart start problem error during " "initialization!"; return false; } status = app->OptimizeTNLP(problem); 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 << "*** IPOPTQP: The problem solved in " << iter_count << " iterations!"; Ipopt::Number final_obj = app->Statistics()->FinalObjective(); ADEBUG << "*** IPOPTQP: The final value of the objective function is " << final_obj << '.'; } else { ADEBUG << "Solve not succeeding, return status: " << int(status); } ptop_ipoptqp->get_optimization_results(&l_warm_up_ipoptqp, &n_warm_up_ipoptqp); // ipopt result Eigen::MatrixXd l_warm_up_ipopt(l_warm_up->rows(), l_warm_up->cols()); Eigen::MatrixXd n_warm_up_ipopt(n_warm_up->rows(), n_warm_up->cols()); DualVariableWarmStartIPOPTInterface* ptop_ipopt = new DualVariableWarmStartIPOPTInterface( horizon, ts, ego, obstacles_edges_num, obstacles_num, obstacles_A, obstacles_b, xWS, planner_open_space_config_); problem = ptop_ipopt; // Create an instance of the IpoptApplication status = app->Initialize(); if (status != Ipopt::Solve_Succeeded) { AERROR << "*** Dual variable wart start problem error during " "initialization!"; return false; } status = app->OptimizeTNLP(problem); 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 << "*** IPOPT: The problem solved in " << iter_count << " iterations!"; Ipopt::Number final_obj = app->Statistics()->FinalObjective(); ADEBUG << "*** IPOPT: The final value of the objective function is " << final_obj << '.'; } else { ADEBUG << "Solve not succeeding, return status: " << int(status); } ptop_ipopt->get_optimization_results(&l_warm_up_ipopt, &n_warm_up_ipopt); // compare three results double l_max_diff1 = 0.0; double l_max_diff2 = 0.0; double l_max_diff3 = 0.0; for (int c = 0; c < l_warm_up->cols(); ++c) { for (int r = 0; r < l_warm_up->rows(); ++r) { l_max_diff1 = std::max(l_max_diff1, std::abs(l_warm_up->coeff(r, c) - l_warm_up_ipopt(r, c))); l_max_diff2 = std::max(l_max_diff2, std::abs(l_warm_up->coeff(r, c) - l_warm_up_ipoptqp(r, c))); l_max_diff3 = std::max(l_max_diff3, std::abs(l_warm_up_ipoptqp(r, c) - l_warm_up_ipopt(r, c))); } } ADEBUG << "max l warm up diff between osqp & ipopt: " << l_max_diff1; ADEBUG << "max l warm up diff between osqp & ipoptqp: " << l_max_diff2; ADEBUG << "max l warm up diff between ipopt & ipoptqp: " << l_max_diff3; double n_max_diff1 = 0.0; double n_max_diff2 = 0.0; double n_max_diff3 = 0.0; for (int c = 0; c < n_warm_up->cols(); ++c) { for (int r = 0; r < n_warm_up->rows(); ++r) { n_max_diff1 = std::max(n_max_diff1, std::abs(n_warm_up->coeff(r, c) - n_warm_up_ipopt(r, c))); n_max_diff2 = std::max(n_max_diff2, std::abs(n_warm_up->coeff(r, c) - n_warm_up_ipoptqp(r, c))); n_max_diff3 = std::max(n_max_diff3, std::abs(n_warm_up_ipoptqp(r, c) - n_warm_up_ipopt(r, c))); } } ADEBUG << "max n warm up diff between osqp & ipopt: " << n_max_diff1; ADEBUG << "max n warm up diff between osqp & ipoptqp: " << n_max_diff2; ADEBUG << "max n warm up diff between ipopt & ipoptqp: " << n_max_diff3; return true; } if (solver_flag == false) { // if solver fails during dual warm up, insert zeros instead for (int r = 0; r < l_warm_up->rows(); ++r) { for (int c = 0; c < l_warm_up->cols(); ++c) { (*l_warm_up)(r, c) = 0.0; } } for (int r = 0; r < n_warm_up->rows(); ++r) { for (int c = 0; c < n_warm_up->cols(); ++c) { (*n_warm_up)(r, c) = 0.0; } } } return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_fixed_ts_interface.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/open_space/trajectory_smoother/distance_approach_ipopt_fixed_ts_interface.h" namespace apollo { namespace planning { DistanceApproachIPOPTFixedTsInterface::DistanceApproachIPOPTFixedTsInterface( const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xf, const Eigen::MatrixXd& last_time_u, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const PlannerOpenSpaceConfig& planner_open_space_config) : ts_(ts), ego_(ego), xWS_(xWS), uWS_(uWS), l_warm_up_(l_warm_up), n_warm_up_(n_warm_up), x0_(x0), xf_(xf), last_time_u_(last_time_u), XYbounds_(XYbounds), obstacles_edges_num_(obstacles_edges_num), obstacles_A_(obstacles_A), obstacles_b_(obstacles_b) { ACHECK(horizon < std::numeric_limits<int>::max()) << "Invalid cast on horizon in open space planner"; horizon_ = static_cast<int>(horizon); ACHECK(obstacles_num < std::numeric_limits<int>::max()) << "Invalid cast on obstacles_num in open space planner"; obstacles_num_ = static_cast<int>(obstacles_num); w_ev_ = ego_(1, 0) + ego_(3, 0); l_ev_ = ego_(0, 0) + ego_(2, 0); g_ = {l_ev_ / 2, w_ev_ / 2, l_ev_ / 2, w_ev_ / 2}; offset_ = (ego_(0, 0) + ego_(2, 0)) / 2 - ego_(2, 0); obstacles_edges_sum_ = obstacles_edges_num_.sum(); state_result_ = Eigen::MatrixXd::Zero(4, horizon_ + 1); dual_l_result_ = Eigen::MatrixXd::Zero(obstacles_edges_sum_, horizon_ + 1); dual_n_result_ = Eigen::MatrixXd::Zero(4 * obstacles_num_, horizon_ + 1); control_result_ = Eigen::MatrixXd::Zero(2, horizon_ + 1); time_result_ = Eigen::MatrixXd::Zero(1, horizon_ + 1); state_start_index_ = 0; control_start_index_ = 4 * (horizon_ + 1); time_start_index_ = control_start_index_ + 2 * horizon_; l_start_index_ = time_start_index_; n_start_index_ = l_start_index_ + obstacles_edges_sum_ * (horizon_ + 1); planner_open_space_config_ = planner_open_space_config; distance_approach_config_ = planner_open_space_config_.distance_approach_config(); weight_state_x_ = distance_approach_config_.weight_x(); weight_state_y_ = distance_approach_config_.weight_y(); weight_state_phi_ = distance_approach_config_.weight_phi(); weight_state_v_ = distance_approach_config_.weight_v(); weight_input_steer_ = distance_approach_config_.weight_steer(); weight_input_a_ = distance_approach_config_.weight_a(); weight_rate_steer_ = distance_approach_config_.weight_steer_rate(); weight_rate_a_ = distance_approach_config_.weight_a_rate(); weight_stitching_steer_ = distance_approach_config_.weight_steer_stitching(); weight_stitching_a_ = distance_approach_config_.weight_a_stitching(); weight_first_order_time_ = distance_approach_config_.weight_first_order_time(); weight_second_order_time_ = distance_approach_config_.weight_second_order_time(); min_safety_distance_ = distance_approach_config_.min_safety_distance(); max_steer_angle_ = vehicle_param_.max_steer_angle() / vehicle_param_.steer_ratio(); max_speed_forward_ = distance_approach_config_.max_speed_forward(); max_speed_reverse_ = distance_approach_config_.max_speed_reverse(); max_acceleration_forward_ = distance_approach_config_.max_acceleration_forward(); max_acceleration_reverse_ = distance_approach_config_.max_acceleration_reverse(); min_time_sample_scaling_ = distance_approach_config_.min_time_sample_scaling(); max_time_sample_scaling_ = distance_approach_config_.max_time_sample_scaling(); max_steer_rate_ = vehicle_param_.max_steer_angle_rate() / vehicle_param_.steer_ratio(); use_fix_time_ = distance_approach_config_.use_fix_time(); wheelbase_ = vehicle_param_.wheel_base(); enable_constraint_check_ = distance_approach_config_.enable_constraint_check(); } bool DistanceApproachIPOPTFixedTsInterface::get_nlp_info( int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) { ADEBUG << "get_nlp_info"; // n1 : states variables, 4 * (N+1) int n1 = 4 * (horizon_ + 1); ADEBUG << "n1: " << n1; // n2 : control inputs variables int n2 = 2 * horizon_; ADEBUG << "n2: " << n2; // n4 : dual multiplier associated with obstacle shape lambda_horizon_ = obstacles_edges_num_.sum() * (horizon_ + 1); ADEBUG << "lambda_horizon_: " << lambda_horizon_; // n5 : dual multipier associated with car shape, obstacles_num*4 * (N+1) miu_horizon_ = obstacles_num_ * 4 * (horizon_ + 1); ADEBUG << "miu_horizon_: " << miu_horizon_; // m1 : dynamics constatins int m1 = 4 * horizon_; ADEBUG << "m1: " << m1; // m2 : control rate constraints (only steering) int m2 = horizon_; ADEBUG << "m2: " << m2; // m4 : obstacle constraints int m4 = 4 * obstacles_num_ * (horizon_ + 1); ADEBUG << "m4: " << m4; num_of_variables_ = n1 + n2 + lambda_horizon_ + miu_horizon_; num_of_constraints_ = m1 + m2 + m4 + (num_of_variables_ - (horizon_ + 1) + 2); // number of variables n = num_of_variables_; ADEBUG << "num_of_variables_ " << num_of_variables_; // number of constraints m = num_of_constraints_; ADEBUG << "num_of_constraints_ " << num_of_constraints_; generate_tapes(n, m, &nnz_jac_g, &nnz_h_lag); index_style = IndexStyleEnum::C_STYLE; return true; } bool DistanceApproachIPOPTFixedTsInterface::get_bounds_info(int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) { ADEBUG << "get_bounds_info"; ACHECK(XYbounds_.size() == 4) << "XYbounds_ size is not 4, but" << XYbounds_.size(); // Variables: includes state, u, sample time and lagrange multipliers // 1. state variables, 4 * [0, horizon] // start point pose int variable_index = 0; for (int i = 0; i < 4; ++i) { x_l[i] = -2e19; x_u[i] = 2e19; } variable_index += 4; // During horizons, 2 ~ N-1 for (int i = 1; i < horizon_; ++i) { // x x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // y x_l[variable_index + 1] = -2e19; x_u[variable_index + 1] = 2e19; // phi x_l[variable_index + 2] = -2e19; x_u[variable_index + 2] = 2e19; // v x_l[variable_index + 3] = -2e19; x_u[variable_index + 3] = 2e19; variable_index += 4; } // end point pose for (int i = 0; i < 4; ++i) { x_l[variable_index + i] = -2e19; x_u[variable_index + i] = 2e19; } variable_index += 4; ADEBUG << "variable_index after adding state variables : " << variable_index; // 2. control variables, 2 * [0, horizon_-1] for (int i = 0; i < horizon_; ++i) { // u1 x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // u2 x_l[variable_index + 1] = -2e19; x_u[variable_index + 1] = 2e19; variable_index += 2; } ADEBUG << "variable_index after adding control variables : " << variable_index; // 4. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0, // horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { x_l[variable_index] = 0.0; x_u[variable_index] = 2e19; // nlp_upper_bound_limit ++variable_index; } } ADEBUG << "variable_index after adding lagrange l : " << variable_index; // 5. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { x_l[variable_index] = 0.0; x_u[variable_index] = 2e19; // nlp_upper_bound_limit ++variable_index; } } ADEBUG << "variable_index after adding lagrange n : " << variable_index; // Constraints: includes four state Euler forward constraints, three // Obstacle related constraints // 1. dynamics constraints 4 * [0, horizons-1] int constraint_index = 0; for (int i = 0; i < 4 * horizon_; ++i) { g_l[i] = 0.0; g_u[i] = 0.0; } constraint_index += 4 * horizon_; ADEBUG << "constraint_index after adding Euler forward dynamics constraints: " << constraint_index; // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply // steering rate as of now for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = -max_steer_rate_; g_u[constraint_index] = max_steer_rate_; ++constraint_index; } ADEBUG << "constraint_index after adding steering rate constraints: " << constraint_index; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { // a. norm(A'*lambda) <= 1 g_l[constraint_index] = -2e19; g_u[constraint_index] = 1.0; // b. G'*mu + R'*A*lambda = 0 g_l[constraint_index + 1] = 0.0; g_u[constraint_index + 1] = 0.0; g_l[constraint_index + 2] = 0.0; g_u[constraint_index + 2] = 0.0; // c. -g'*mu + (A*t - b)*lambda > min_safety_distance_ g_l[constraint_index + 3] = min_safety_distance_; g_u[constraint_index + 3] = 2e19; // nlp_upper_bound_limit constraint_index += 4; } } ADEBUG << "constraints_index after adding obstacles related constraints: " << constraint_index; // 5. load variable bounds as constraints // start configuration g_l[constraint_index] = x0_(0, 0); g_u[constraint_index] = x0_(0, 0); g_l[constraint_index + 1] = x0_(1, 0); g_u[constraint_index + 1] = x0_(1, 0); g_l[constraint_index + 2] = x0_(2, 0); g_u[constraint_index + 2] = x0_(2, 0); g_l[constraint_index + 3] = x0_(3, 0); g_u[constraint_index + 3] = x0_(3, 0); constraint_index += 4; for (int i = 1; i < horizon_; ++i) { g_l[constraint_index] = XYbounds_[0]; g_u[constraint_index] = XYbounds_[1]; g_l[constraint_index + 1] = XYbounds_[2]; g_u[constraint_index + 1] = XYbounds_[3]; g_l[constraint_index + 2] = -max_speed_reverse_; g_u[constraint_index + 2] = max_speed_forward_; constraint_index += 3; } // end configuration g_l[constraint_index] = xf_(0, 0); g_u[constraint_index] = xf_(0, 0); g_l[constraint_index + 1] = xf_(1, 0); g_u[constraint_index + 1] = xf_(1, 0); g_l[constraint_index + 2] = xf_(2, 0); g_u[constraint_index + 2] = xf_(2, 0); g_l[constraint_index + 3] = xf_(3, 0); g_u[constraint_index + 3] = xf_(3, 0); constraint_index += 4; for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = -max_steer_angle_; g_u[constraint_index] = max_steer_angle_; g_l[constraint_index + 1] = -max_acceleration_reverse_; g_u[constraint_index + 1] = max_acceleration_forward_; constraint_index += 2; } for (int i = 0; i < lambda_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; } for (int i = 0; i < miu_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; } ADEBUG << "constraint_index after adding obstacles constraints: " << constraint_index; ADEBUG << "get_bounds_info_ out"; return true; } bool DistanceApproachIPOPTFixedTsInterface::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) { ADEBUG << "get_starting_point"; ACHECK(init_x) << "Warm start init_x setting failed"; CHECK_EQ(horizon_, uWS_.cols()); CHECK_EQ(horizon_ + 1, xWS_.cols()); // 1. state variables 4 * (horizon_ + 1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * 4; for (int j = 0; j < 4; ++j) { x[index + j] = xWS_(j, i); } } // 2. control variable initialization, 2 * horizon_ for (int i = 0; i < horizon_; ++i) { int index = i * 2; x[control_start_index_ + index] = uWS_(0, i); x[control_start_index_ + index + 1] = uWS_(1, i); } // 3. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * obstacles_edges_sum_; for (int j = 0; j < obstacles_edges_sum_; ++j) { x[l_start_index_ + index + j] = l_warm_up_(j, i); } } // 4. lagrange constraint m, 4*obstacles_num * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * 4 * obstacles_num_; for (int j = 0; j < 4 * obstacles_num_; ++j) { x[n_start_index_ + index + j] = n_warm_up_(j, i); } } if (enable_constraint_check_) { int kM = m; double g[kM]; ADEBUG << "initial points constraint checking"; eval_constraints(n, x, m, g); check_g(n, x, m, g); } ADEBUG << "get_starting_point out"; return true; } bool DistanceApproachIPOPTFixedTsInterface::eval_f(int n, const double* x, bool new_x, double& obj_value) { eval_obj(n, x, &obj_value); return true; } bool DistanceApproachIPOPTFixedTsInterface::eval_grad_f(int n, const double* x, bool new_x, double* grad_f) { gradient(tag_f, n, x, grad_f); return true; } bool DistanceApproachIPOPTFixedTsInterface::eval_g(int n, const double* x, bool new_x, int m, double* g) { eval_constraints(n, x, m, g); if (enable_constraint_check_) { check_g(n, x, m, g); } return true; } bool DistanceApproachIPOPTFixedTsInterface::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) { // return the structure of the jacobian for (int idx = 0; idx < nnz_jac; idx++) { iRow[idx] = rind_g[idx]; jCol[idx] = cind_g[idx]; } } else { // return the values of the jacobian of the constraints sparse_jac(tag_g, m, n, 1, x, &nnz_jac, &rind_g, &cind_g, &jacval, options_g); for (int idx = 0; idx < nnz_jac; idx++) { values[idx] = jacval[idx]; } } return true; // return eval_jac_g_ser(n, x, new_x, m, nele_jac, iRow, jCol, values); } bool DistanceApproachIPOPTFixedTsInterface::eval_jac_g_ser( int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { AERROR << "NOT VALID NOW"; return false; } // NOLINT bool DistanceApproachIPOPTFixedTsInterface::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) { // return the structure. This is a symmetric matrix, fill the lower left // triangle only. for (int idx = 0; idx < nnz_L; idx++) { iRow[idx] = rind_L[idx]; jCol[idx] = cind_L[idx]; } } else { // return the values. This is a symmetric matrix, fill the lower left // triangle only obj_lam[0] = obj_factor; for (int idx = 0; idx < m; idx++) { obj_lam[1 + idx] = lambda[idx]; } set_param_vec(tag_L, m + 1, obj_lam); sparse_hess(tag_L, n, 1, const_cast<double*>(x), &nnz_L, &rind_L, &cind_L, &hessval, options_L); for (int idx = 0; idx < nnz_L; idx++) { values[idx] = hessval[idx]; } } return true; } void DistanceApproachIPOPTFixedTsInterface::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) { int state_index = state_start_index_; int control_index = control_start_index_; // int time_index = time_start_index_; int dual_l_index = l_start_index_; int dual_n_index = n_start_index_; // enable_constraint_check_: for debug only if (enable_constraint_check_) { ADEBUG << "final resolution constraint checking"; check_g(n, x, m, g); } // 1. state variables, 4 * [0, horizon] // 2. control variables, 2 * [0, horizon_-1] // 3. sampling time variables, 1 * [0, horizon_] // 4. dual_l obstacles_edges_sum_ * [0, horizon] // 5. dual_n obstacles_num * [0, horizon] for (int i = 0; i < horizon_; ++i) { state_result_(0, i) = x[state_index]; state_result_(1, i) = x[state_index + 1]; state_result_(2, i) = x[state_index + 2]; state_result_(3, i) = x[state_index + 3]; control_result_(0, i) = x[control_index]; control_result_(1, i) = x[control_index + 1]; time_result_(0, i) = ts_; for (int j = 0; j < obstacles_edges_sum_; ++j) { dual_l_result_(j, i) = x[dual_l_index + j]; } for (int k = 0; k < 4 * obstacles_num_; k++) { dual_n_result_(k, i) = x[dual_n_index + k]; } state_index += 4; control_index += 2; // time_index++; dual_l_index += obstacles_edges_sum_; dual_n_index += 4 * obstacles_num_; } state_result_(0, 0) = x0_(0, 0); state_result_(1, 0) = x0_(1, 0); state_result_(2, 0) = x0_(2, 0); state_result_(3, 0) = x0_(3, 0); // push back last horizon for state and time variables state_result_(0, horizon_) = xf_(0, 0); state_result_(1, horizon_) = xf_(1, 0); state_result_(2, horizon_) = xf_(2, 0); state_result_(3, horizon_) = xf_(3, 0); time_result_(0, horizon_) = ts_; // time_result_ = ts_ * time_result_; for (int j = 0; j < obstacles_edges_sum_; ++j) { dual_l_result_(j, horizon_) = x[dual_l_index + j]; } for (int k = 0; k < 4 * obstacles_num_; k++) { dual_n_result_(k, horizon_) = x[dual_n_index + k]; } // memory deallocation of ADOL-C variables delete[] obj_lam; free(rind_g); free(cind_g); free(rind_L); free(cind_L); free(jacval); free(hessval); } void DistanceApproachIPOPTFixedTsInterface::get_optimization_results( Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) const { ADEBUG << "get_optimization_results"; *state_result = state_result_; *control_result = control_result_; *time_result = time_result_; *dual_l_result = dual_l_result_; *dual_n_result = dual_n_result_; if (!distance_approach_config_.enable_initial_final_check()) { return; } CHECK_EQ(state_result_.cols(), xWS_.cols()); CHECK_EQ(state_result_.rows(), xWS_.rows()); double state_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4; ++j) { state_diff_max = std::max(std::abs(xWS_(j, i) - state_result_(j, i)), state_diff_max); } } // 2. control variable initialization, 2 * horizon_ CHECK_EQ(control_result_.rows(), uWS_.rows()); double control_diff_max = 0.0; for (int i = 0; i < horizon_; ++i) { control_diff_max = std::max(std::abs(uWS_(0, i) - control_result_(0, i)), control_diff_max); control_diff_max = std::max(std::abs(uWS_(1, i) - control_result_(1, i)), control_diff_max); } // 3. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1) CHECK_EQ(dual_l_result_.cols(), l_warm_up_.cols()); CHECK_EQ(dual_l_result_.rows(), l_warm_up_.rows()); double l_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { l_diff_max = std::max(std::abs(l_warm_up_(j, i) - dual_l_result_(j, i)), l_diff_max); } } // 4. lagrange constraint m, 4*obstacles_num * (horizon_+1) CHECK_EQ(n_warm_up_.cols(), dual_n_result_.cols()); CHECK_EQ(n_warm_up_.rows(), dual_n_result_.rows()); double n_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { n_diff_max = std::max(std::abs(n_warm_up_(j, i) - dual_n_result_(j, i)), n_diff_max); } } ADEBUG << "state_diff_max: " << state_diff_max; ADEBUG << "control_diff_max: " << control_diff_max; ADEBUG << "dual_l_diff_max: " << l_diff_max; ADEBUG << "dual_n_diff_max: " << n_diff_max; } //*************** start ADOL-C part *********************************** template <class T> void DistanceApproachIPOPTFixedTsInterface::eval_obj(int n, const T* x, T* obj_value) { // Objective is : // min control inputs // min input rate // min time (if the time step is not fixed) // regularization wrt warm start trajectory DCHECK(ts_ != 0) << "ts in distance_approach_ is 0"; int control_index = control_start_index_; // int time_index = time_start_index_; int state_index = state_start_index_; // TODO(QiL): Initial implementation towards earlier understanding and debug // purpose, later code refine towards improving efficiency *obj_value = 0.0; // 1. objective to minimize state diff to warm up for (int i = 0; i < horizon_ + 1; ++i) { T x1_diff = x[state_index] - xWS_(0, i); T x2_diff = x[state_index + 1] - xWS_(1, i); T x3_diff = x[state_index + 2] - xWS_(2, i); T x4_abs = x[state_index + 3]; *obj_value += weight_state_x_ * x1_diff * x1_diff + weight_state_y_ * x2_diff * x2_diff + weight_state_phi_ * x3_diff * x3_diff + weight_state_v_ * x4_abs * x4_abs; state_index += 4; } // 2. objective to minimize u square for (int i = 0; i < horizon_; ++i) { *obj_value += weight_input_steer_ * x[control_index] * x[control_index] + weight_input_a_ * x[control_index + 1] * x[control_index + 1]; control_index += 2; } // 3. objective to minimize input change rate for first horizon control_index = control_start_index_; T last_time_steer_rate = (x[control_index] - last_time_u_(0, 0)) / ts_; T last_time_a_rate = (x[control_index + 1] - last_time_u_(1, 0)) / ts_; *obj_value += weight_stitching_steer_ * last_time_steer_rate * last_time_steer_rate + weight_stitching_a_ * last_time_a_rate * last_time_a_rate; // 4. objective to minimize input change rates, [0- horizon_ -2] for (int i = 0; i < horizon_ - 1; ++i) { T steering_rate = (x[control_index + 2] - x[control_index]) / ts_; T a_rate = (x[control_index + 3] - x[control_index + 1]) / ts_; *obj_value += weight_rate_steer_ * steering_rate * steering_rate + weight_rate_a_ * a_rate * a_rate; control_index += 2; } } template <class T> void DistanceApproachIPOPTFixedTsInterface::eval_constraints(int n, const T* x, int m, T* g) { // state start index int state_index = state_start_index_; // control start index. int control_index = control_start_index_; // time start index // int time_index = time_start_index_; int constraint_index = 0; // 1. state constraints 4 * [0, horizons-1] // commented implementation is linearized model with fixed ts for (int i = 0; i < horizon_; ++i) { // x1 /* g[constraint_index] = x[state_index + 4] - ((xWS_(0, i) + ts_ * xWS_(3, i) * cos(xWS_(2, i))) + (x[state_index] - xWS_(0, i)) + (ts_ * cos(xWS_(2, i))) * (x[state_index + 3] - xWS_(3, i)) + (-ts_ * xWS_(3, i) * sin(xWS_(2, i))) * (x[state_index + 2] - xWS_(2, i))); */ g[constraint_index] = x[state_index + 4] - (x[state_index] + ts_ * x[state_index + 3] * cos(x[state_index + 2])); // x2 /* g[constraint_index + 1] = x[state_index + 5] - ((xWS_(1, i) + ts_ * xWS_(3, i) * sin(xWS_(2, i))) + (x[state_index + 1] - xWS_(1, i)) + (ts_ * sin(xWS_(2, i))) * (x[state_index + 3] - xWS_(3, i)) + (ts_ * xWS_(3, i) * cos(xWS_(2, i))) * (x[state_index + 2] - xWS_(2, i))); */ g[constraint_index + 1] = x[state_index + 5] - (x[state_index + 1] + ts_ * x[state_index + 3] * sin(x[state_index + 2])); // x3 /* g[constraint_index + 2] = x[state_index + 6] - ((xWS_(2, i) + ts_ * xWS_(3, i) * tan(uWS_(0, i)) / wheelbase_) + (x[state_index + 2] - xWS_(2, i)) + (ts_ * tan(uWS_(0, i)) / wheelbase_) * (x[state_index + 3] - xWS_(3, i)) + (ts_ * xWS_(3, i) / cos(uWS_(0, i)) / cos(uWS_(0, i)) / wheelbase_) * (x[control_index] - uWS_(0, i))); */ g[constraint_index + 2] = x[state_index + 6] - (x[state_index + 2] + ts_ * x[state_index + 3] * tan(x[control_index]) / wheelbase_); // x4 /* g[constraint_index + 3] = x[state_index + 7] - ((x[state_index + 3] + ts_ * uWS_(1, i)) + (ts_ * (x[control_index + 1] - uWS_(1, i)))); */ g[constraint_index + 3] = x[state_index + 7] - (x[state_index + 3] + ts_ * x[control_index + 1]); control_index += 2; constraint_index += 4; state_index += 4; } ADEBUG << "constraint_index after adding Euler forward dynamics constraints " "updated: " << constraint_index; // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply // steering rate as of now control_index = control_start_index_; // First rate is compare first with stitch point g[constraint_index] = (x[control_index] - last_time_u_(0, 0)) / ts_; control_index += 2; constraint_index++; for (int i = 1; i < horizon_; ++i) { g[constraint_index] = (x[control_index] - x[control_index - 2]) / ts_; constraint_index++; control_index += 2; } // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 state_index = state_start_index_; int l_index = l_start_index_; int n_index = n_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); // norm(A* lambda) <= 1 T tmp1 = 0.0; T tmp2 = 0.0; for (int k = 0; k < current_edges_num; ++k) { // TODO(QiL) : replace this one directly with x tmp1 += Aj(k, 0) * x[l_index + k]; tmp2 += Aj(k, 1) * x[l_index + k]; } g[constraint_index] = tmp1 * tmp1 + tmp2 * tmp2; // G' * mu + R' * lambda == 0 g[constraint_index + 1] = x[n_index] - x[n_index + 2] + cos(x[state_index + 2]) * tmp1 + sin(x[state_index + 2]) * tmp2; g[constraint_index + 2] = x[n_index + 1] - x[n_index + 3] - sin(x[state_index + 2]) * tmp1 + cos(x[state_index + 2]) * tmp2; // -g'*mu + (A*t - b)*lambda > 0 T tmp3 = 0.0; for (int k = 0; k < 4; ++k) { tmp3 += -g_[k] * x[n_index + k]; } T tmp4 = 0.0; for (int k = 0; k < current_edges_num; ++k) { tmp4 += bj(k, 0) * x[l_index + k]; } g[constraint_index + 3] = tmp3 + (x[state_index] + cos(x[state_index + 2]) * offset_) * tmp1 + (x[state_index + 1] + sin(x[state_index + 2]) * offset_) * tmp2 - tmp4; // Update index edges_counter += current_edges_num; l_index += current_edges_num; n_index += 4; constraint_index += 4; } state_index += 4; } ADEBUG << "constraint_index after obstacles avoidance constraints " "updated: " << constraint_index; // 5. load variable bounds as constraints state_index = state_start_index_; control_index = control_start_index_; // time_index = time_start_index_; l_index = l_start_index_; n_index = n_start_index_; // start configuration g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 2]; g[constraint_index + 3] = x[state_index + 3]; constraint_index += 4; state_index += 4; // constraints on x,y,v for (int i = 1; i < horizon_; ++i) { g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 3]; constraint_index += 3; state_index += 4; } // end configuration g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 2]; g[constraint_index + 3] = x[state_index + 3]; constraint_index += 4; state_index += 4; for (int i = 0; i < horizon_; ++i) { g[constraint_index] = x[control_index]; g[constraint_index + 1] = x[control_index + 1]; constraint_index += 2; control_index += 2; } for (int i = 0; i < lambda_horizon_; ++i) { g[constraint_index] = x[l_index]; constraint_index++; l_index++; } for (int i = 0; i < miu_horizon_; ++i) { g[constraint_index] = x[n_index]; constraint_index++; n_index++; } } bool DistanceApproachIPOPTFixedTsInterface::check_g(int n, const double* x, int m, const double* g) { int kN = n; int kM = m; double x_u_tmp[kN]; double x_l_tmp[kN]; double g_u_tmp[kM]; double g_l_tmp[kM]; get_bounds_info(n, x_l_tmp, x_u_tmp, m, g_l_tmp, g_u_tmp); const double delta_v = 1e-4; for (int idx = 0; idx < n; ++idx) { x_u_tmp[idx] = x_u_tmp[idx] + delta_v; x_l_tmp[idx] = x_l_tmp[idx] - delta_v; if (x[idx] > x_u_tmp[idx] || x[idx] < x_l_tmp[idx]) { AINFO << "x idx unfeasible: " << idx << ", x: " << x[idx] << ", lower: " << x_l_tmp[idx] << ", upper: " << x_u_tmp[idx]; } } // m1 : dynamics constatins int m1 = 4 * horizon_; // m2 : control rate constraints (only steering) int m2 = m1 + horizon_; // m3 : sampling time equality constraints int m3 = m2; // m4 : obstacle constraints int m4 = m3 + 4 * obstacles_num_ * (horizon_ + 1); // 5. load variable bounds as constraints // start configuration int m5 = m4 + 3 + 1; // constraints on x,y,v int m6 = m5 + 3 * (horizon_ - 1); // end configuration int m7 = m6 + 3 + 1; // control variable bnd int m8 = m7 + 2 * horizon_; // time interval variable bnd int m9 = m8; // lambda_horizon_ int m10 = m9 + lambda_horizon_; // miu_horizon_ int m11 = m10 + miu_horizon_; CHECK_EQ(m11, num_of_constraints_); AINFO << "dynamics constatins to: " << m1; AINFO << "control rate constraints (only steering) to: " << m2; AINFO << "sampling time equality constraints to: " << m3; AINFO << "obstacle constraints to: " << m4; AINFO << "start conf constraints to: " << m5; AINFO << "constraints on x,y,v to: " << m6; AINFO << "end constraints to: " << m7; AINFO << "control bnd to: " << m8; AINFO << "time interval constraints to: " << m9; AINFO << "lambda constraints to: " << m10; AINFO << "miu constraints to: " << m11; AINFO << "total constraints: " << num_of_constraints_; for (int idx = 0; idx < m; ++idx) { if (g[idx] > g_u_tmp[idx] + delta_v || g[idx] < g_l_tmp[idx] - delta_v) { AINFO << "constratins idx unfeasible: " << idx << ", g: " << g[idx] << ", lower: " << g_l_tmp[idx] << ", upper: " << g_u_tmp[idx]; } } return true; } void DistanceApproachIPOPTFixedTsInterface::generate_tapes(int n, int m, int* nnz_jac_g, int* nnz_h_lag) { std::vector<double> xp(n); std::vector<double> lamp(m); std::vector<double> zl(m); std::vector<double> zu(m); std::vector<adouble> xa(n); std::vector<adouble> g(m); std::vector<double> lam(m); double sig; adouble obj_value; double dummy = 0.0; obj_lam = new double[m + 1]; get_starting_point(n, 1, &xp[0], 0, &zl[0], &zu[0], m, 0, &lamp[0]); trace_on(tag_f); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_obj(n, &xa[0], &obj_value); obj_value >>= dummy; trace_off(); trace_on(tag_g); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { g[idx] >>= dummy; } trace_off(); trace_on(tag_L); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } for (int idx = 0; idx < m; idx++) { lam[idx] = 1.0; } sig = 1.0; eval_obj(n, &xa[0], &obj_value); obj_value *= mkparam(sig); eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { obj_value += g[idx] * mkparam(lam[idx]); } obj_value >>= dummy; trace_off(); rind_g = nullptr; cind_g = nullptr; rind_L = nullptr; cind_L = nullptr; jacval = nullptr; hessval = nullptr; options_g[0] = 0; /* sparsity pattern by index domains (default) */ options_g[1] = 0; /* safe mode (default) */ options_g[2] = 0; options_g[3] = 0; /* column compression (default) */ sparse_jac(tag_g, m, n, 0, &xp[0], &nnz_jac, &rind_g, &cind_g, &jacval, options_g); *nnz_jac_g = nnz_jac; options_L[0] = 0; options_L[1] = 1; sparse_hess(tag_L, n, 0, &xp[0], &nnz_L, &rind_L, &cind_L, &hessval, options_L); *nnz_h_lag = nnz_L; } //*************** end ADOL-C part *********************************** } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_fixed_ts_interface.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 <algorithm> #include <limits> #include <vector> #include <omp.h> #include <adolc/adolc.h> #include <adolc/adolc_openmp.h> #include <adolc/adolc_sparse.h> #include <adolc/adouble.h> #include <coin/IpTNLP.hpp> #include <coin/IpTypes.hpp> #include "Eigen/Dense" #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_interface.h" #include "modules/planning/proto/planner_open_space_config.pb.h" #define tag_f 1 #define tag_g 2 #define tag_L 3 #define HPOFF 30 namespace apollo { namespace planning { class DistanceApproachIPOPTFixedTsInterface : public DistanceApproachInterface { public: DistanceApproachIPOPTFixedTsInterface( const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xf, const Eigen::MatrixXd& last_time_u, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const PlannerOpenSpaceConfig& planner_open_space_config); virtual ~DistanceApproachIPOPTFixedTsInterface() = default; /** Method to return some info about the nlp */ bool get_nlp_info(int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, // NOLINT IndexStyleEnum& index_style) override; // NOLINT /** 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; /** Check unfeasible constraints for further study**/ bool check_g(int n, const double* x, int m, const double* g); /** 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; // sequential implementation to jac_g bool eval_jac_g_ser(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 get_optimization_results(Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) const override; //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> void eval_obj(int n, const T* x, T* obj_value); /** Template to compute constraints */ template <class T> void eval_constraints(int n, const T* x, int m, T* g); /** Method to generate the required tapes by ADOL-C*/ void generate_tapes(int n, int m, int* nnz_jac_g, int* nnz_h_lag); //*************** end ADOL-C part *********************************** private: int num_of_variables_ = 0; int num_of_constraints_ = 0; int horizon_ = 0; int lambda_horizon_ = 0; int miu_horizon_ = 0; double ts_ = 0.0; Eigen::MatrixXd ego_; Eigen::MatrixXd xWS_; Eigen::MatrixXd uWS_; Eigen::MatrixXd l_warm_up_; Eigen::MatrixXd n_warm_up_; Eigen::MatrixXd x0_; Eigen::MatrixXd xf_; Eigen::MatrixXd last_time_u_; std::vector<double> XYbounds_; // debug flag bool enable_constraint_check_; // penalty double weight_state_x_ = 0.0; double weight_state_y_ = 0.0; double weight_state_phi_ = 0.0; double weight_state_v_ = 0.0; double weight_input_steer_ = 0.0; double weight_input_a_ = 0.0; double weight_rate_steer_ = 0.0; double weight_rate_a_ = 0.0; double weight_stitching_steer_ = 0.0; double weight_stitching_a_ = 0.0; double weight_first_order_time_ = 0.0; double weight_second_order_time_ = 0.0; double w_ev_ = 0.0; double l_ev_ = 0.0; std::vector<double> g_; double offset_ = 0.0; Eigen::MatrixXi obstacles_edges_num_; int obstacles_num_ = 0; int obstacles_edges_sum_ = 0; double wheelbase_ = 0.0; Eigen::MatrixXd state_result_; Eigen::MatrixXd dual_l_result_; Eigen::MatrixXd dual_n_result_; Eigen::MatrixXd control_result_; Eigen::MatrixXd time_result_; // obstacles_A Eigen::MatrixXd obstacles_A_; // obstacles_b Eigen::MatrixXd obstacles_b_; // whether to use fix time bool use_fix_time_ = false; // state start index int state_start_index_ = 0; // control start index. int control_start_index_ = 0; // time start index int time_start_index_ = 0; // lagrangian l start index int l_start_index_ = 0; // lagrangian n start index int n_start_index_ = 0; double min_safety_distance_ = 0.0; double max_safety_distance_ = 0.0; double max_steer_angle_ = 0.0; double max_speed_forward_ = 0.0; double max_speed_reverse_ = 0.0; double max_acceleration_forward_ = 0.0; double max_acceleration_reverse_ = 0.0; double min_time_sample_scaling_ = 0.0; double max_time_sample_scaling_ = 0.0; double max_steer_rate_ = 0.0; double max_lambda_ = 0.0; double max_miu_ = 0.0; private: DistanceApproachConfig distance_approach_config_; PlannerOpenSpaceConfig planner_open_space_config_; const common::VehicleParam vehicle_param_ = common::VehicleConfigHelper::GetConfig().vehicle_param(); private: //*************** start ADOL-C part *********************************** double* obj_lam; //** variables for sparsity exploitation unsigned int* rind_g; /* row indices */ unsigned int* cind_g; /* column indices */ double* jacval; /* values */ unsigned int* rind_L; /* row indices */ unsigned int* cind_L; /* column indices */ double* hessval; /* values */ int nnz_jac; int nnz_L; int options_g[4]; int options_L[4]; //*************** end ADOL-C part *********************************** }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_cuda_interface_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/open_space/trajectory_smoother/distance_approach_ipopt_cuda_interface.h" #include "cyber/common/file.h" #include "gtest/gtest.h" namespace apollo { namespace planning { class DistanceApproachIPOPTCUDAInterfaceTest : public ::testing::Test { public: virtual void SetUp() { FLAGS_planner_open_space_config_filename = "/apollo/modules/planning/testdata/conf/" "open_space_standard_parking_lot.pb.txt"; ACHECK(apollo::cyber::common::GetProtoFromFile( FLAGS_planner_open_space_config_filename, &planner_open_space_config_)) << "Failed to load open space config file " << FLAGS_planner_open_space_config_filename; distance_approach_config_ = planner_open_space_config_.distance_approach_config(); ProblemSetup(); } protected: void ProblemSetup(); protected: size_t horizon_ = 43; size_t obstacles_num_ = 4; double ts_ = 0.5; Eigen::MatrixXd ego_ = Eigen::MatrixXd::Ones(4, 1); Eigen::MatrixXd x0_ = Eigen::MatrixXd::Ones(4, 1); Eigen::MatrixXd xf_ = 10 * Eigen::MatrixXd::Ones(4, 1); Eigen::MatrixXd last_time_u_ = Eigen::MatrixXd::Zero(2, 1); std::vector<double> XYbounds_ = {1.0, 1.0, 1.0, 1.0}; Eigen::MatrixXd xWS_ = Eigen::MatrixXd::Ones(4, 44); Eigen::MatrixXd uWS_ = Eigen::MatrixXd::Ones(2, 43); Eigen::MatrixXi obstacles_edges_num_; // {2, 1, 2, 1} size_t obstacles_edges_sum_; Eigen::MatrixXd obstacles_A_ = Eigen::MatrixXd::Ones(6, 2); Eigen::MatrixXd obstacles_b_ = Eigen::MatrixXd::Ones(6, 1); bool use_fix_time_ = false; std::unique_ptr<DistanceApproachIPOPTCUDAInterface> ptop_ = nullptr; PlannerOpenSpaceConfig planner_open_space_config_; DistanceApproachConfig distance_approach_config_; }; void DistanceApproachIPOPTCUDAInterfaceTest::ProblemSetup() { // obstacles_edges_num_ = 4 * Eigen::MatrixXi::Ones(obstacles_num_, 1); obstacles_edges_num_ = Eigen::MatrixXi(obstacles_num_, 1); obstacles_edges_num_ << 2, 1, 2, 1; obstacles_edges_sum_ = obstacles_edges_num_.sum(); Eigen::MatrixXd l_warm_up_ = Eigen::MatrixXd::Ones(obstacles_edges_sum_, horizon_ + 1); Eigen::MatrixXd n_warm_up_ = Eigen::MatrixXd::Ones(4 * obstacles_num_, horizon_ + 1); ptop_.reset(new DistanceApproachIPOPTCUDAInterface( horizon_, ts_, ego_, xWS_, uWS_, l_warm_up_, n_warm_up_, x0_, xf_, last_time_u_, XYbounds_, obstacles_edges_num_, obstacles_num_, obstacles_A_, obstacles_b_, planner_open_space_config_)); } TEST_F(DistanceApproachIPOPTCUDAInterfaceTest, initilization) { EXPECT_NE(ptop_, nullptr); } TEST_F(DistanceApproachIPOPTCUDAInterfaceTest, get_bounds_info) { int n = 1274; int m = 2194; double x_l[1274]; double x_u[1274]; double g_l[2194]; double g_u[2194]; bool res = ptop_->get_bounds_info(n, x_l, x_u, m, g_l, g_u); EXPECT_TRUE(res); } TEST_F(DistanceApproachIPOPTCUDAInterfaceTest, get_starting_point) { int n = 1274; int m = 2194; bool init_x = true; bool init_z = false; bool init_lambda = false; double x[1274]; double z_L[2194]; double z_U[2194]; double lambda[2194]; bool res = ptop_->get_starting_point(n, init_x, x, init_z, z_L, z_U, m, init_lambda, lambda); EXPECT_TRUE(res); } TEST_F(DistanceApproachIPOPTCUDAInterfaceTest, eval_f) { int n = 1274; double obj_value = 0.0; double x[1274]; std::fill_n(x, n, 1.2); bool res = ptop_->eval_f(n, x, true, obj_value); EXPECT_DOUBLE_EQ(obj_value, 1443.3600000000008) << "eval_f: " << obj_value; EXPECT_TRUE(res); } TEST_F(DistanceApproachIPOPTCUDAInterfaceTest, eval_jac_g_par) { int n = 1274; int m = 2194; int kNnzJac = 0; int kNnzhss = 0; Ipopt::TNLP::IndexStyleEnum index_style; // to-do: check get_nlp_info bool res = ptop_->get_nlp_info(n, m, kNnzJac, kNnzhss, index_style); EXPECT_TRUE(res); double x[1274]; std::fill_n(x, n, 1.2); int new_x = 0; // to-do: check eval_jac_g_ser int i_row_ser[kNnzJac]; int j_col_ser[kNnzJac]; double values_ser[kNnzJac]; std::fill_n(values_ser, n, 0.0); bool res2 = ptop_->eval_jac_g_ser(n, x, new_x, m, kNnzJac, i_row_ser, j_col_ser, nullptr); EXPECT_TRUE(res2); bool res3 = ptop_->eval_jac_g_ser(n, x, new_x, m, kNnzJac, i_row_ser, j_col_ser, values_ser); EXPECT_TRUE(res3); int i_row_par[kNnzJac]; int j_col_par[kNnzJac]; double values_par[kNnzJac]; std::fill_n(values_par, n, 0.0); bool res4 = ptop_->eval_jac_g_par(n, x, new_x, m, kNnzJac, i_row_par, j_col_par, nullptr); EXPECT_TRUE(res4); for (int i = 0; i < kNnzJac; ++i) { EXPECT_EQ(i_row_ser[i], i_row_par[i]) << "iRow differ at index " << i; EXPECT_EQ(j_col_ser[i], j_col_par[i]) << "iCol differ at index " << i; } bool res5 = ptop_->eval_jac_g_par(n, x, new_x, m, kNnzJac, i_row_par, j_col_par, values_par); EXPECT_TRUE(res5); for (int i = 0; i < kNnzJac; ++i) { EXPECT_EQ(values_ser[i], values_par[i]) << "values differ at index " << i; } } TEST_F(DistanceApproachIPOPTCUDAInterfaceTest, eval_grad_f_hand) { int n = 1274; double x[1274]; std::fill_n(x, n, 1.2); bool new_x = false; double grad_f_adolc[1274]; double grad_f_hand[1274]; std::fill_n(grad_f_adolc, n, 0.0); std::fill_n(grad_f_hand, n, 0.0); bool res = ptop_->eval_grad_f(n, x, new_x, grad_f_adolc); EXPECT_TRUE(res); bool res2 = ptop_->eval_grad_f_hand(n, x, new_x, grad_f_hand); EXPECT_TRUE(res2); for (int i = 0; i < n; ++i) { EXPECT_EQ(grad_f_adolc[i], grad_f_hand[i]) << "grad_f differ at index " << i; } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_problem.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* * @file */ #pragma once #include <vector> #include <coin/IpIpoptApplication.hpp> #include <coin/IpSolveStatistics.hpp> #include "Eigen/Dense" #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_cuda_interface.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_fixed_dual_interface.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_fixed_ts_interface.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_interface.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_relax_end_interface.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_relax_end_slack_interface.h" namespace apollo { namespace planning { class DistanceApproachProblem { public: explicit DistanceApproachProblem( const PlannerOpenSpaceConfig& planner_open_space_config); virtual ~DistanceApproachProblem() = default; bool Solve(const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xF, const Eigen::MatrixXd& last_time_u, const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& s_warm_up, const std::vector<double>& XYbounds, const size_t obstacles_num, const Eigen::MatrixXi& obstacles_edges_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result); private: PlannerOpenSpaceConfig planner_open_space_config_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_problem_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/open_space/trajectory_smoother/distance_approach_problem.h" #include "cyber/common/file.h" #include "gtest/gtest.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { class DistanceApproachProblemTest : public ::testing::Test { public: virtual void SetUp() { FLAGS_planner_open_space_config_filename = "/apollo/modules/planning/testdata/conf/" "open_space_standard_parking_lot.pb.txt"; ACHECK(apollo::cyber::common::GetProtoFromFile( FLAGS_planner_open_space_config_filename, &planner_open_space_config_)) << "Failed to load open space config file " << FLAGS_planner_open_space_config_filename; } protected: std::unique_ptr<DistanceApproachProblem> distance_approach_ = nullptr; int num_of_variables_ = 160; int num_of_constraints_ = 200; size_t horizon_ = 20; double ts_ = 0.01; Eigen::MatrixXd ego_ = Eigen::MatrixXd::Ones(4, 1); Eigen::MatrixXd x0_ = Eigen::MatrixXd::Ones(4, 1); Eigen::MatrixXd xf_ = Eigen::MatrixXd::Ones(4, 1); std::vector<double> XYbounds_ = {1.0, 1.0, 1.0, 1.0}; Eigen::MatrixXd last_time_u_ = Eigen::MatrixXd::Zero(2, 1); Eigen::MatrixXi obstacles_edges_num_ = Eigen::MatrixXi::Ones(12, 4); Eigen::MatrixXd xWS_ = Eigen::MatrixXd::Zero(4, horizon_ + 1); Eigen::MatrixXd uWS_ = Eigen::MatrixXd::Zero(2, horizon_); Eigen::MatrixXi obstacles_edges_num = Eigen::MatrixXi::Zero(1, horizon_ + 1); Eigen::MatrixXd obstacles_A = Eigen::MatrixXd::Ones(4, 1); Eigen::MatrixXd obstacles_b = Eigen::MatrixXd::Ones(4, 1); PlannerOpenSpaceConfig planner_open_space_config_; }; TEST_F(DistanceApproachProblemTest, initilization) { distance_approach_.reset( new DistanceApproachProblem(planner_open_space_config_)); EXPECT_NE(distance_approach_, nullptr); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_interface.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/open_space/trajectory_smoother/distance_approach_ipopt_interface.h" namespace apollo { namespace planning { DistanceApproachIPOPTInterface::DistanceApproachIPOPTInterface( const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xf, const Eigen::MatrixXd& last_time_u, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const PlannerOpenSpaceConfig& planner_open_space_config) : ts_(ts), ego_(ego), xWS_(xWS), uWS_(uWS), l_warm_up_(l_warm_up), n_warm_up_(n_warm_up), x0_(x0), xf_(xf), last_time_u_(last_time_u), XYbounds_(XYbounds), obstacles_edges_num_(obstacles_edges_num), obstacles_A_(obstacles_A), obstacles_b_(obstacles_b) { ACHECK(horizon < std::numeric_limits<int>::max()) << "Invalid cast on horizon in open space planner"; horizon_ = static_cast<int>(horizon); ACHECK(obstacles_num < std::numeric_limits<int>::max()) << "Invalid cast on obstacles_num in open space planner"; obstacles_num_ = static_cast<int>(obstacles_num); w_ev_ = ego_(1, 0) + ego_(3, 0); l_ev_ = ego_(0, 0) + ego_(2, 0); g_ = {l_ev_ / 2, w_ev_ / 2, l_ev_ / 2, w_ev_ / 2}; offset_ = (ego_(0, 0) + ego_(2, 0)) / 2 - ego_(2, 0); obstacles_edges_sum_ = obstacles_edges_num_.sum(); state_result_ = Eigen::MatrixXd::Zero(4, horizon_ + 1); dual_l_result_ = Eigen::MatrixXd::Zero(obstacles_edges_sum_, horizon_ + 1); dual_n_result_ = Eigen::MatrixXd::Zero(4 * obstacles_num_, horizon_ + 1); control_result_ = Eigen::MatrixXd::Zero(2, horizon_); time_result_ = Eigen::MatrixXd::Zero(1, horizon_); state_start_index_ = 0; control_start_index_ = 4 * (horizon_ + 1); time_start_index_ = control_start_index_ + 2 * horizon_; l_start_index_ = time_start_index_ + (horizon_ + 1); n_start_index_ = l_start_index_ + obstacles_edges_sum_ * (horizon_ + 1); distance_approach_config_ = planner_open_space_config.distance_approach_config(); weight_state_x_ = distance_approach_config_.weight_x(); weight_state_y_ = distance_approach_config_.weight_y(); weight_state_phi_ = distance_approach_config_.weight_phi(); weight_state_v_ = distance_approach_config_.weight_v(); weight_input_steer_ = distance_approach_config_.weight_steer(); weight_input_a_ = distance_approach_config_.weight_a(); weight_rate_steer_ = distance_approach_config_.weight_steer_rate(); weight_rate_a_ = distance_approach_config_.weight_a_rate(); weight_stitching_steer_ = distance_approach_config_.weight_steer_stitching(); weight_stitching_a_ = distance_approach_config_.weight_a_stitching(); weight_first_order_time_ = distance_approach_config_.weight_first_order_time(); weight_second_order_time_ = distance_approach_config_.weight_second_order_time(); min_safety_distance_ = distance_approach_config_.min_safety_distance(); max_steer_angle_ = vehicle_param_.max_steer_angle() / vehicle_param_.steer_ratio(); max_speed_forward_ = distance_approach_config_.max_speed_forward(); max_speed_reverse_ = distance_approach_config_.max_speed_reverse(); max_acceleration_forward_ = distance_approach_config_.max_acceleration_forward(); max_acceleration_reverse_ = distance_approach_config_.max_acceleration_reverse(); min_time_sample_scaling_ = distance_approach_config_.min_time_sample_scaling(); max_time_sample_scaling_ = distance_approach_config_.max_time_sample_scaling(); max_steer_rate_ = vehicle_param_.max_steer_angle_rate() / vehicle_param_.steer_ratio(); use_fix_time_ = distance_approach_config_.use_fix_time(); wheelbase_ = vehicle_param_.wheel_base(); enable_constraint_check_ = distance_approach_config_.enable_constraint_check(); enable_jacobian_ad_ = distance_approach_config_.enable_jacobian_ad(); } bool DistanceApproachIPOPTInterface::get_nlp_info(int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) { ADEBUG << "get_nlp_info"; // n1 : states variables, 4 * (N+1) int n1 = 4 * (horizon_ + 1); ADEBUG << "n1: " << n1; // n2 : control inputs variables int n2 = 2 * horizon_; ADEBUG << "n2: " << n2; // n3 : sampling time variables int n3 = horizon_ + 1; ADEBUG << "n3: " << n3; // n4 : dual multiplier associated with obstacle shape lambda_horizon_ = obstacles_edges_num_.sum() * (horizon_ + 1); ADEBUG << "lambda_horizon_: " << lambda_horizon_; // n5 : dual multipier associated with car shape, obstacles_num*4 * (N+1) miu_horizon_ = obstacles_num_ * 4 * (horizon_ + 1); ADEBUG << "miu_horizon_: " << miu_horizon_; // m1 : dynamics constatins int m1 = 4 * horizon_; // m2 : control rate constraints (only steering) int m2 = horizon_; // m3 : sampling time equality constraints int m3 = horizon_; // m4 : obstacle constraints int m4 = 4 * obstacles_num_ * (horizon_ + 1); num_of_variables_ = n1 + n2 + n3 + lambda_horizon_ + miu_horizon_; num_of_constraints_ = m1 + m2 + m3 + m4 + (num_of_variables_ - (horizon_ + 1) + 2); // number of variables n = num_of_variables_; ADEBUG << "num_of_variables_ " << num_of_variables_; // number of constraints m = num_of_constraints_; ADEBUG << "num_of_constraints_ " << num_of_constraints_; generate_tapes(n, m, &nnz_jac_g, &nnz_h_lag); // number of nonzero in Jacobian. if (!enable_jacobian_ad_) { int tmp = 0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); tmp += current_edges_num * 4 + 9 + 4; } } nnz_jac_g = 24 * horizon_ + 3 * horizon_ + 2 * horizon_ + tmp - 1 + (num_of_variables_ - (horizon_ + 1) + 2); } index_style = IndexStyleEnum::C_STYLE; return true; } bool DistanceApproachIPOPTInterface::get_bounds_info(int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) { ADEBUG << "get_bounds_info"; ACHECK(XYbounds_.size() == 4) << "XYbounds_ size is not 4, but" << XYbounds_.size(); // Variables: includes state, u, sample time and lagrange multipliers // 1. state variables, 4 * [0, horizon] // start point pose int variable_index = 0; for (int i = 0; i < 4; ++i) { x_l[i] = -2e19; x_u[i] = 2e19; } variable_index += 4; // During horizons, 2 ~ N-1 for (int i = 1; i < horizon_; ++i) { // x x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // y x_l[variable_index + 1] = -2e19; x_u[variable_index + 1] = 2e19; // phi x_l[variable_index + 2] = -2e19; x_u[variable_index + 2] = 2e19; // v x_l[variable_index + 3] = -2e19; x_u[variable_index + 3] = 2e19; variable_index += 4; } // end point pose for (int i = 0; i < 4; ++i) { x_l[variable_index + i] = -2e19; x_u[variable_index + i] = 2e19; } variable_index += 4; ADEBUG << "variable_index after adding state variables : " << variable_index; // 2. control variables, 2 * [0, horizon_-1] for (int i = 0; i < horizon_; ++i) { // steer x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // a x_l[variable_index + 1] = -2e19; x_u[variable_index + 1] = 2e19; variable_index += 2; } ADEBUG << "variable_index after adding control variables : " << variable_index; // 3. sampling time variables, 1 * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; ++variable_index; } ADEBUG << "variable_index after adding sample time : " << variable_index; ADEBUG << "sample time fix time status is : " << use_fix_time_; // 4. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0, // horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { x_l[variable_index] = 0.0; x_u[variable_index] = 2e19; // nlp_upper_bound_limit ++variable_index; } } ADEBUG << "variable_index after adding lagrange l : " << variable_index; // 5. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { x_l[variable_index] = 0.0; x_u[variable_index] = 2e19; // nlp_upper_bound_limit ++variable_index; } } ADEBUG << "variable_index after adding lagrange n : " << variable_index; // Constraints: includes four state Euler forward constraints, three // Obstacle related constraints // 1. dynamics constraints 4 * [0, horizons-1] int constraint_index = 0; for (int i = 0; i < 4 * horizon_; ++i) { g_l[i] = 0.0; g_u[i] = 0.0; } constraint_index += 4 * horizon_; ADEBUG << "constraint_index after adding Euler forward dynamics constraints: " << constraint_index; // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply // steering rate as of now for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = -max_steer_rate_; g_u[constraint_index] = max_steer_rate_; ++constraint_index; } ADEBUG << "constraint_index after adding steering rate constraints: " << constraint_index; // 3. Time constraints 1 * [0, horizons-1] for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 0.0; ++constraint_index; } ADEBUG << "constraint_index after adding time constraints: " << constraint_index; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { // a. norm(A'*lambda) <= 1 g_l[constraint_index] = -2e19; g_u[constraint_index] = 1.0; // b. G'*mu + R'*A*lambda = 0 g_l[constraint_index + 1] = 0.0; g_u[constraint_index + 1] = 0.0; g_l[constraint_index + 2] = 0.0; g_u[constraint_index + 2] = 0.0; // c. -g'*mu + (A*t - b)*lambda > min_safety_distance_ g_l[constraint_index + 3] = min_safety_distance_; g_u[constraint_index + 3] = 2e19; // nlp_upper_bound_limit constraint_index += 4; } } // 5. load variable bounds as constraints // start configuration g_l[constraint_index] = x0_(0, 0); g_u[constraint_index] = x0_(0, 0); g_l[constraint_index + 1] = x0_(1, 0); g_u[constraint_index + 1] = x0_(1, 0); g_l[constraint_index + 2] = x0_(2, 0); g_u[constraint_index + 2] = x0_(2, 0); g_l[constraint_index + 3] = x0_(3, 0); g_u[constraint_index + 3] = x0_(3, 0); constraint_index += 4; for (int i = 1; i < horizon_; ++i) { g_l[constraint_index] = XYbounds_[0]; g_u[constraint_index] = XYbounds_[1]; g_l[constraint_index + 1] = XYbounds_[2]; g_u[constraint_index + 1] = XYbounds_[3]; g_l[constraint_index + 2] = -max_speed_reverse_; g_u[constraint_index + 2] = max_speed_forward_; constraint_index += 3; } // end configuration g_l[constraint_index] = xf_(0, 0); g_u[constraint_index] = xf_(0, 0); g_l[constraint_index + 1] = xf_(1, 0); g_u[constraint_index + 1] = xf_(1, 0); g_l[constraint_index + 2] = xf_(2, 0); g_u[constraint_index + 2] = xf_(2, 0); g_l[constraint_index + 3] = xf_(3, 0); g_u[constraint_index + 3] = xf_(3, 0); constraint_index += 4; for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = -max_steer_angle_; g_u[constraint_index] = max_steer_angle_; g_l[constraint_index + 1] = -max_acceleration_reverse_; g_u[constraint_index + 1] = max_acceleration_forward_; constraint_index += 2; } for (int i = 0; i < horizon_ + 1; ++i) { if (!use_fix_time_) { g_l[constraint_index] = min_time_sample_scaling_; g_u[constraint_index] = max_time_sample_scaling_; } else { g_l[constraint_index] = 1.0; g_u[constraint_index] = 1.0; } constraint_index++; } for (int i = 0; i < lambda_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; } for (int i = 0; i < miu_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; } ADEBUG << "constraint_index after adding obstacles constraints: " << constraint_index; ADEBUG << "get_bounds_info_ out"; return true; } bool DistanceApproachIPOPTInterface::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) { ADEBUG << "get_starting_point"; ACHECK(init_x) << "Warm start init_x setting failed"; CHECK_EQ(horizon_, uWS_.cols()); CHECK_EQ(horizon_ + 1, xWS_.cols()); // 1. state variables 4 * (horizon_ + 1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * 4; for (int j = 0; j < 4; ++j) { x[index + j] = xWS_(j, i); } } // 2. control variable initialization, 2 * horizon_ for (int i = 0; i < horizon_; ++i) { int index = i * 2; x[control_start_index_ + index] = uWS_(0, i); x[control_start_index_ + index + 1] = uWS_(1, i); } // 2. time scale variable initialization, horizon_ + 1 for (int i = 0; i < horizon_ + 1; ++i) { x[time_start_index_ + i] = 0.5 * (min_time_sample_scaling_ + max_time_sample_scaling_); } // 3. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * obstacles_edges_sum_; for (int j = 0; j < obstacles_edges_sum_; ++j) { x[l_start_index_ + index + j] = l_warm_up_(j, i); } } // 4. lagrange constraint m, 4*obstacles_num * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * 4 * obstacles_num_; for (int j = 0; j < 4 * obstacles_num_; ++j) { x[n_start_index_ + index + j] = n_warm_up_(j, i); } } ADEBUG << "get_starting_point out"; return true; } bool DistanceApproachIPOPTInterface::eval_f(int n, const double* x, bool new_x, double& obj_value) { eval_obj(n, x, &obj_value); return true; } bool DistanceApproachIPOPTInterface::eval_grad_f(int n, const double* x, bool new_x, double* grad_f) { gradient(tag_f, n, x, grad_f); return true; } bool DistanceApproachIPOPTInterface::eval_g(int n, const double* x, bool new_x, int m, double* g) { eval_constraints(n, x, m, g); // if (enable_constraint_check_) check_g(n, x, m, g); return true; } bool DistanceApproachIPOPTInterface::eval_jac_g(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { if (enable_jacobian_ad_) { if (values == nullptr) { // return the structure of the jacobian for (int idx = 0; idx < nnz_jac; idx++) { iRow[idx] = rind_g[idx]; jCol[idx] = cind_g[idx]; } } else { // return the values of the jacobian of the constraints sparse_jac(tag_g, m, n, 1, x, &nnz_jac, &rind_g, &cind_g, &jacval, options_g); for (int idx = 0; idx < nnz_jac; idx++) { values[idx] = jacval[idx]; } } return true; } else { return eval_jac_g_ser(n, x, new_x, m, nele_jac, iRow, jCol, values); } } bool DistanceApproachIPOPTInterface::eval_jac_g_ser(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { ADEBUG << "eval_jac_g"; CHECK_EQ(n, num_of_variables_) << "No. of variables wrong in eval_jac_g. n : " << n; CHECK_EQ(m, num_of_constraints_) << "No. of constraints wrong in eval_jac_g. n : " << m; if (values == nullptr) { int nz_index = 0; int constraint_index = 0; int state_index = state_start_index_; int control_index = control_start_index_; int time_index = time_start_index_; // 1. State Constraint with respect to variables for (int i = 0; i < horizon_; ++i) { // g(0)' with respect to x0 ~ x7 iRow[nz_index] = state_index; jCol[nz_index] = state_index; ++nz_index; iRow[nz_index] = state_index; jCol[nz_index] = state_index + 2; ++nz_index; iRow[nz_index] = state_index; jCol[nz_index] = state_index + 3; ++nz_index; iRow[nz_index] = state_index; jCol[nz_index] = state_index + 4; ++nz_index; // g(0)' with respect to u0 ~ u1' iRow[nz_index] = state_index; jCol[nz_index] = control_index; ++nz_index; iRow[nz_index] = state_index; jCol[nz_index] = control_index + 1; ++nz_index; // g(0)' with respect to time iRow[nz_index] = state_index; jCol[nz_index] = time_index; ++nz_index; // g(1)' with respect to x0 ~ x7 iRow[nz_index] = state_index + 1; jCol[nz_index] = state_index + 1; ++nz_index; iRow[nz_index] = state_index + 1; jCol[nz_index] = state_index + 2; ++nz_index; iRow[nz_index] = state_index + 1; jCol[nz_index] = state_index + 3; ++nz_index; iRow[nz_index] = state_index + 1; jCol[nz_index] = state_index + 5; ++nz_index; // g(1)' with respect to u0 ~ u1' iRow[nz_index] = state_index + 1; jCol[nz_index] = control_index; ++nz_index; iRow[nz_index] = state_index + 1; jCol[nz_index] = control_index + 1; ++nz_index; // g(1)' with respect to time iRow[nz_index] = state_index + 1; jCol[nz_index] = time_index; ++nz_index; // g(2)' with respect to x0 ~ x7 iRow[nz_index] = state_index + 2; jCol[nz_index] = state_index + 2; ++nz_index; iRow[nz_index] = state_index + 2; jCol[nz_index] = state_index + 3; ++nz_index; iRow[nz_index] = state_index + 2; jCol[nz_index] = state_index + 6; ++nz_index; // g(2)' with respect to u0 ~ u1' iRow[nz_index] = state_index + 2; jCol[nz_index] = control_index; ++nz_index; iRow[nz_index] = state_index + 2; jCol[nz_index] = control_index + 1; ++nz_index; // g(2)' with respect to time iRow[nz_index] = state_index + 2; jCol[nz_index] = time_index; ++nz_index; // g(3)' with x0 ~ x7 iRow[nz_index] = state_index + 3; jCol[nz_index] = state_index + 3; ++nz_index; iRow[nz_index] = state_index + 3; jCol[nz_index] = state_index + 7; ++nz_index; // g(3)' with respect to u0 ~ u1' iRow[nz_index] = state_index + 3; jCol[nz_index] = control_index + 1; ++nz_index; // g(3)' with respect to time iRow[nz_index] = state_index + 3; jCol[nz_index] = time_index; ++nz_index; state_index += 4; control_index += 2; time_index++; constraint_index += 4; } // 2. only have control rate constraints on u0 , range [0, horizon_-1] control_index = control_start_index_; state_index = state_start_index_; time_index = time_start_index_; // First one, with respect to u(0, 0) iRow[nz_index] = constraint_index; jCol[nz_index] = control_index; ++nz_index; // First element, with respect to time iRow[nz_index] = constraint_index; jCol[nz_index] = time_index; ++nz_index; control_index += 2; time_index++; constraint_index++; for (int i = 1; i < horizon_; ++i) { // with respect to u(0, i-1) iRow[nz_index] = constraint_index; jCol[nz_index] = control_index - 2; ++nz_index; // with respect to u(0, i) iRow[nz_index] = constraint_index; jCol[nz_index] = control_index; ++nz_index; // with respect to time iRow[nz_index] = constraint_index; jCol[nz_index] = time_index; ++nz_index; // only consider rate limits on u0 control_index += 2; constraint_index++; time_index++; } // 3. Time constraints [0, horizon_ -1] time_index = time_start_index_; for (int i = 0; i < horizon_; ++i) { // with respect to timescale(0, i-1) iRow[nz_index] = constraint_index; jCol[nz_index] = time_index; ++nz_index; // with respect to timescale(0, i) iRow[nz_index] = constraint_index; jCol[nz_index] = time_index + 1; ++nz_index; time_index++; constraint_index++; } // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 state_index = state_start_index_; int l_index = l_start_index_; int n_index = n_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); // 1. norm(A* lambda == 1) for (int k = 0; k < current_edges_num; ++k) { // with respect to l iRow[nz_index] = constraint_index; jCol[nz_index] = l_index + k; ++nz_index; } // 2. G' * mu + R' * lambda == 0, part 1 // With respect to x iRow[nz_index] = constraint_index + 1; jCol[nz_index] = state_index + 2; ++nz_index; // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index] = constraint_index + 1; jCol[nz_index] = l_index + k; ++nz_index; } // With respect to n iRow[nz_index] = constraint_index + 1; jCol[nz_index] = n_index; ++nz_index; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = n_index + 2; ++nz_index; // 2. G' * mu + R' * lambda == 0, part 2 // With respect to x iRow[nz_index] = constraint_index + 2; jCol[nz_index] = state_index + 2; ++nz_index; // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index] = constraint_index + 2; jCol[nz_index] = l_index + k; ++nz_index; } // With respect to n iRow[nz_index] = constraint_index + 2; jCol[nz_index] = n_index + 1; ++nz_index; iRow[nz_index] = constraint_index + 2; jCol[nz_index] = n_index + 3; ++nz_index; // -g'*mu + (A*t - b)*lambda > 0 // With respect to x iRow[nz_index] = constraint_index + 3; jCol[nz_index] = state_index; ++nz_index; iRow[nz_index] = constraint_index + 3; jCol[nz_index] = state_index + 1; ++nz_index; iRow[nz_index] = constraint_index + 3; jCol[nz_index] = state_index + 2; ++nz_index; // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index] = constraint_index + 3; jCol[nz_index] = l_index + k; ++nz_index; } // with respect to n for (int k = 0; k < 4; ++k) { iRow[nz_index] = constraint_index + 3; jCol[nz_index] = n_index + k; ++nz_index; } // Update index l_index += current_edges_num; n_index += 4; constraint_index += 4; } state_index += 4; } // 5. load variable bounds as constraints state_index = state_start_index_; control_index = control_start_index_; time_index = time_start_index_; l_index = l_start_index_; n_index = n_start_index_; // start configuration iRow[nz_index] = constraint_index; jCol[nz_index] = state_index; nz_index++; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = state_index + 1; nz_index++; iRow[nz_index] = constraint_index + 2; jCol[nz_index] = state_index + 2; nz_index++; iRow[nz_index] = constraint_index + 3; jCol[nz_index] = state_index + 3; nz_index++; constraint_index += 4; state_index += 4; for (int i = 1; i < horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = state_index; nz_index++; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = state_index + 1; nz_index++; iRow[nz_index] = constraint_index + 2; jCol[nz_index] = state_index + 3; nz_index++; constraint_index += 3; state_index += 4; } // end configuration iRow[nz_index] = constraint_index; jCol[nz_index] = state_index; nz_index++; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = state_index + 1; nz_index++; iRow[nz_index] = constraint_index + 2; jCol[nz_index] = state_index + 2; nz_index++; iRow[nz_index] = constraint_index + 3; jCol[nz_index] = state_index + 3; nz_index++; constraint_index += 4; state_index += 4; for (int i = 0; i < horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = control_index; nz_index++; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = control_index + 1; nz_index++; constraint_index += 2; control_index += 2; } for (int i = 0; i < horizon_ + 1; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = time_index; nz_index++; constraint_index++; time_index++; } for (int i = 0; i < lambda_horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = l_index; nz_index++; constraint_index++; l_index++; } for (int i = 0; i < miu_horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = n_index; nz_index++; constraint_index++; n_index++; } CHECK_EQ(nz_index, static_cast<int>(nele_jac)); CHECK_EQ(constraint_index, static_cast<int>(m)); } else { std::fill(values, values + nele_jac, 0.0); int nz_index = 0; int time_index = time_start_index_; int state_index = state_start_index_; int control_index = control_start_index_; // TODO(QiL) : initially implemented to be debug friendly, later iterate // towards better efficiency // 1. state constraints 4 * [0, horizons-1] for (int i = 0; i < horizon_; ++i) { values[nz_index] = -1.0; ++nz_index; values[nz_index] = x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_); // a. ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * (-1) * x[time_index] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_ * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // b ++nz_index; values[nz_index] = 1.0; ++nz_index; values[nz_index] = x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) * x[time_index] * ts_ * 0.5 * x[state_index + 3] / (std::cos(x[control_index]) * std::cos(x[control_index])) / wheelbase_; // c ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * x[time_index] * ts_ * 0.5 * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // d ++nz_index; values[nz_index] = -1.0 * (ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * ts_ * 0.5 * x[control_index + 1] * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) - x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * x[state_index + 3] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_ * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // e ++nz_index; values[nz_index] = -1.0; ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // f. ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * x[time_index] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_ * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // g ++nz_index; values[nz_index] = 1.0; ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) * x[time_index] * ts_ * 0.5 * x[state_index + 3] / (std::cos(x[control_index]) * std::cos(x[control_index])) / wheelbase_); // h ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * x[time_index] * ts_ * 0.5 * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // i ++nz_index; values[nz_index] = -1.0 * (ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * ts_ * 0.5 * x[control_index + 1] * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * x[state_index + 3] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_ * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // j ++nz_index; values[nz_index] = -1.0; ++nz_index; values[nz_index] = -1.0 * x[time_index] * ts_ * std::tan(x[control_index]) / wheelbase_; // k. ++nz_index; values[nz_index] = 1.0; ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) / (std::cos(x[control_index]) * std::cos(x[control_index])) / wheelbase_); // l. ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * x[time_index] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_); // m. ++nz_index; values[nz_index] = -1.0 * (ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::tan(x[control_index]) / wheelbase_ + x[time_index] * ts_ * ts_ * 0.5 * x[control_index + 1] * std::tan(x[control_index]) / wheelbase_); // n. ++nz_index; values[nz_index] = -1.0; ++nz_index; values[nz_index] = 1.0; ++nz_index; values[nz_index] = -1.0 * ts_ * x[time_index]; // o. ++nz_index; values[nz_index] = -1.0 * ts_ * x[control_index + 1]; // p. ++nz_index; state_index += 4; control_index += 2; time_index++; } // 2. control rate constraints 1 * [0, horizons-1] control_index = control_start_index_; state_index = state_start_index_; time_index = time_start_index_; // First horizon // with respect to u(0, 0) values[nz_index] = 1.0 / x[time_index] / ts_; // q ++nz_index; // with respect to time values[nz_index] = -1.0 * (x[control_index] - last_time_u_(0, 0)) / x[time_index] / x[time_index] / ts_; ++nz_index; time_index++; control_index += 2; for (int i = 1; i < horizon_; ++i) { // with respect to u(0, i-1) values[nz_index] = -1.0 / x[time_index] / ts_; ++nz_index; // with respect to u(0, i) values[nz_index] = 1.0 / x[time_index] / ts_; ++nz_index; // with respect to time values[nz_index] = -1.0 * (x[control_index] - x[control_index - 2]) / x[time_index] / x[time_index] / ts_; ++nz_index; control_index += 2; time_index++; } ADEBUG << "After fulfilled control rate constraints derivative, nz_index : " << nz_index << " nele_jac : " << nele_jac; // 3. Time constraints [0, horizon_ -1] time_index = time_start_index_; for (int i = 0; i < horizon_; ++i) { // with respect to timescale(0, i-1) values[nz_index] = -1.0; ++nz_index; // with respect to timescale(0, i) values[nz_index] = 1.0; ++nz_index; time_index++; } ADEBUG << "After fulfilled time constraints derivative, nz_index : " << nz_index << " nele_jac : " << nele_jac; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 state_index = state_start_index_; int l_index = l_start_index_; int n_index = n_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); // TODO(QiL) : Remove redundant calculation double tmp1 = 0; double tmp2 = 0; for (int k = 0; k < current_edges_num; ++k) { // TODO(QiL) : replace this one directly with x tmp1 += Aj(k, 0) * x[l_index + k]; tmp2 += Aj(k, 1) * x[l_index + k]; } // 1. norm(A* lambda == 1) for (int k = 0; k < current_edges_num; ++k) { // with respect to l values[nz_index] = 2 * tmp1 * Aj(k, 0) + 2 * tmp2 * Aj(k, 1); // t0~tk ++nz_index; } // 2. G' * mu + R' * lambda == 0, part 1 // With respect to x values[nz_index] = -std::sin(x[state_index + 2]) * tmp1 + std::cos(x[state_index + 2]) * tmp2; // u ++nz_index; // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index] = std::cos(x[state_index + 2]) * Aj(k, 0) + std::sin(x[state_index + 2]) * Aj(k, 1); // v0~vn ++nz_index; } // With respect to n values[nz_index] = 1.0; // w0 ++nz_index; values[nz_index] = -1.0; // w2 ++nz_index; // 3. G' * mu + R' * lambda == 0, part 2 // With respect to x values[nz_index] = -std::cos(x[state_index + 2]) * tmp1 - std::sin(x[state_index + 2]) * tmp2; // x ++nz_index; // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index] = -std::sin(x[state_index + 2]) * Aj(k, 0) + std::cos(x[state_index + 2]) * Aj(k, 1); // y0~yn ++nz_index; } // With respect to n values[nz_index] = 1.0; // z1 ++nz_index; values[nz_index] = -1.0; // z3 ++nz_index; // 3. -g'*mu + (A*t - b)*lambda > 0 double tmp3 = 0.0; double tmp4 = 0.0; for (int k = 0; k < 4; ++k) { tmp3 += -g_[k] * x[n_index + k]; } for (int k = 0; k < current_edges_num; ++k) { tmp4 += bj(k, 0) * x[l_index + k]; } // With respect to x values[nz_index] = tmp1; // aa1 ++nz_index; values[nz_index] = tmp2; // bb1 ++nz_index; values[nz_index] = -std::sin(x[state_index + 2]) * offset_ * tmp1 + std::cos(x[state_index + 2]) * offset_ * tmp2; // cc1 ++nz_index; // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index] = (x[state_index] + std::cos(x[state_index + 2]) * offset_) * Aj(k, 0) + (x[state_index + 1] + std::sin(x[state_index + 2]) * offset_) * Aj(k, 1) - bj(k, 0); // ddk ++nz_index; } // with respect to n for (int k = 0; k < 4; ++k) { values[nz_index] = -g_[k]; // eek ++nz_index; } // Update index edges_counter += current_edges_num; l_index += current_edges_num; n_index += 4; } state_index += 4; } // 5. load variable bounds as constraints state_index = state_start_index_; control_index = control_start_index_; time_index = time_start_index_; l_index = l_start_index_; n_index = n_start_index_; // start configuration values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; for (int i = 1; i < horizon_; ++i) { values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; } // end configuration values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; for (int i = 0; i < horizon_; ++i) { values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; } for (int i = 0; i < horizon_ + 1; ++i) { values[nz_index] = 1.0; nz_index++; } for (int i = 0; i < lambda_horizon_; ++i) { values[nz_index] = 1.0; nz_index++; } for (int i = 0; i < miu_horizon_; ++i) { values[nz_index] = 1.0; nz_index++; } ADEBUG << "eval_jac_g, fulfilled obstacle constraint values"; CHECK_EQ(nz_index, static_cast<int>(nele_jac)); } ADEBUG << "eval_jac_g done"; return true; } // NOLINT bool DistanceApproachIPOPTInterface::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) { // return the structure. This is a symmetric matrix, fill the lower left // triangle only. for (int idx = 0; idx < nnz_L; idx++) { iRow[idx] = rind_L[idx]; jCol[idx] = cind_L[idx]; } } else { // return the values. This is a symmetric matrix, fill the lower left // triangle only obj_lam[0] = obj_factor; for (int idx = 0; idx < m; idx++) { obj_lam[1 + idx] = lambda[idx]; } set_param_vec(tag_L, m + 1, obj_lam); sparse_hess(tag_L, n, 1, const_cast<double*>(x), &nnz_L, &rind_L, &cind_L, &hessval, options_L); for (int idx = 0; idx < nnz_L; idx++) { values[idx] = hessval[idx]; } } return true; } void DistanceApproachIPOPTInterface::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) { int state_index = state_start_index_; int control_index = control_start_index_; int time_index = time_start_index_; int dual_l_index = l_start_index_; int dual_n_index = n_start_index_; // enable_constraint_check_: for debug only if (enable_constraint_check_) { ADEBUG << "final resolution constraint checking"; check_g(n, x, m, g); } // 1. state variables, 4 * [0, horizon] // 2. control variables, 2 * [0, horizon_-1] // 3. sampling time variables, 1 * [0, horizon_] // 4. dual_l obstacles_edges_sum_ * [0, horizon] // 5. dual_n obstacles_num * [0, horizon] for (int i = 0; i < horizon_; ++i) { state_result_(0, i) = x[state_index]; state_result_(1, i) = x[state_index + 1]; state_result_(2, i) = x[state_index + 2]; state_result_(3, i) = x[state_index + 3]; control_result_(0, i) = x[control_index]; control_result_(1, i) = x[control_index + 1]; time_result_(0, i) = ts_ * x[time_index]; for (int j = 0; j < obstacles_edges_sum_; ++j) { dual_l_result_(j, i) = x[dual_l_index + j]; } for (int k = 0; k < 4 * obstacles_num_; k++) { dual_n_result_(k, i) = x[dual_n_index + k]; } state_index += 4; control_index += 2; time_index++; dual_l_index += obstacles_edges_sum_; dual_n_index += 4 * obstacles_num_; } state_result_(0, 0) = x0_(0, 0); state_result_(1, 0) = x0_(1, 0); state_result_(2, 0) = x0_(2, 0); state_result_(3, 0) = x0_(3, 0); // push back last horizon for states state_result_(0, horizon_) = xf_(0, 0); state_result_(1, horizon_) = xf_(1, 0); state_result_(2, horizon_) = xf_(2, 0); state_result_(3, horizon_) = xf_(3, 0); for (int j = 0; j < obstacles_edges_sum_; ++j) { dual_l_result_(j, horizon_) = x[dual_l_index + j]; } for (int k = 0; k < 4 * obstacles_num_; k++) { dual_n_result_(k, horizon_) = x[dual_n_index + k]; } // memory deallocation of ADOL-C variables delete[] obj_lam; if (enable_jacobian_ad_) { free(rind_g); free(cind_g); free(jacval); } free(rind_L); free(cind_L); free(hessval); } void DistanceApproachIPOPTInterface::get_optimization_results( Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) const { ADEBUG << "get_optimization_results"; *state_result = state_result_; *control_result = control_result_; *time_result = time_result_; *dual_l_result = dual_l_result_; *dual_n_result = dual_n_result_; if (!distance_approach_config_.enable_initial_final_check()) { return; } CHECK_EQ(state_result_.cols(), xWS_.cols()); CHECK_EQ(state_result_.rows(), xWS_.rows()); double state_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4; ++j) { state_diff_max = std::max(std::abs(xWS_(j, i) - state_result_(j, i)), state_diff_max); } } // 2. control variable initialization, 2 * horizon_ CHECK_EQ(control_result_.cols(), uWS_.cols()); CHECK_EQ(control_result_.rows(), uWS_.rows()); double control_diff_max = 0.0; for (int i = 0; i < horizon_; ++i) { control_diff_max = std::max(std::abs(uWS_(0, i) - control_result_(0, i)), control_diff_max); control_diff_max = std::max(std::abs(uWS_(1, i) - control_result_(1, i)), control_diff_max); } // 2. time scale variable initialization, horizon_ + 1 // 3. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1) CHECK_EQ(dual_l_result_.cols(), l_warm_up_.cols()); CHECK_EQ(dual_l_result_.rows(), l_warm_up_.rows()); double l_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { l_diff_max = std::max(std::abs(l_warm_up_(j, i) - dual_l_result_(j, i)), l_diff_max); } } // 4. lagrange constraint m, 4*obstacles_num * (horizon_+1) CHECK_EQ(n_warm_up_.cols(), dual_n_result_.cols()); CHECK_EQ(n_warm_up_.rows(), dual_n_result_.rows()); double n_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { n_diff_max = std::max(std::abs(n_warm_up_(j, i) - dual_n_result_(j, i)), n_diff_max); } } ADEBUG << "state_diff_max: " << state_diff_max; ADEBUG << "control_diff_max: " << control_diff_max; ADEBUG << "dual_l_diff_max: " << l_diff_max; ADEBUG << "dual_n_diff_max: " << n_diff_max; } //*************** start ADOL-C part *********************************** template <class T> void DistanceApproachIPOPTInterface::eval_obj(int n, const T* x, T* obj_value) { // Objective is : // min control inputs // min input rate // min time (if the time step is not fixed) // regularization wrt warm start trajectory DCHECK(ts_ != 0) << "ts in distance_approach_ is 0"; int control_index = control_start_index_; int time_index = time_start_index_; int state_index = state_start_index_; // TODO(QiL): Initial implementation towards earlier understanding and debug // purpose, later code refine towards improving efficiency *obj_value = 0.0; // 1. objective to minimize state diff to warm up for (int i = 0; i < horizon_ + 1; ++i) { T x1_diff = x[state_index] - xWS_(0, i); T x2_diff = x[state_index + 1] - xWS_(1, i); T x3_diff = x[state_index + 2] - xWS_(2, i); T x4_abs = x[state_index + 3]; *obj_value += weight_state_x_ * x1_diff * x1_diff + weight_state_y_ * x2_diff * x2_diff + weight_state_phi_ * x3_diff * x3_diff + weight_state_v_ * x4_abs * x4_abs; state_index += 4; } // 2. objective to minimize u square for (int i = 0; i < horizon_; ++i) { *obj_value += weight_input_steer_ * x[control_index] * x[control_index] + weight_input_a_ * x[control_index + 1] * x[control_index + 1]; control_index += 2; } // 3. objective to minimize input change rate for first horizon control_index = control_start_index_; T last_time_steer_rate = (x[control_index] - last_time_u_(0, 0)) / x[time_index] / ts_; T last_time_a_rate = (x[control_index + 1] - last_time_u_(1, 0)) / x[time_index] / ts_; *obj_value += weight_stitching_steer_ * last_time_steer_rate * last_time_steer_rate + weight_stitching_a_ * last_time_a_rate * last_time_a_rate; // 4. objective to minimize input change rates, [0- horizon_ -2] time_index++; for (int i = 0; i < horizon_ - 1; ++i) { T steering_rate = (x[control_index + 2] - x[control_index]) / x[time_index] / ts_; T a_rate = (x[control_index + 3] - x[control_index + 1]) / x[time_index] / ts_; *obj_value += weight_rate_steer_ * steering_rate * steering_rate + weight_rate_a_ * a_rate * a_rate; control_index += 2; time_index++; } // 5. objective to minimize total time [0, horizon_] time_index = time_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { T first_order_penalty = weight_first_order_time_ * x[time_index]; T second_order_penalty = weight_second_order_time_ * x[time_index] * x[time_index]; *obj_value += first_order_penalty + second_order_penalty; time_index++; } } template <class T> void DistanceApproachIPOPTInterface::eval_constraints(int n, const T* x, int m, T* g) { // state start index int state_index = state_start_index_; // control start index. int control_index = control_start_index_; // time start index int time_index = time_start_index_; int constraint_index = 0; // // 1. state constraints 4 * [0, horizons-1] for (int i = 0; i < horizon_; ++i) { // x1 g[constraint_index] = x[state_index + 4] - (x[state_index] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * cos(x[state_index + 2] + ts_ * x[time_index] * 0.5 * x[state_index + 3] * tan(x[control_index]) / wheelbase_)); // TODO(Jinyun): evaluate performance of different models // g[constraint_index] = // x[state_index + 4] - // (x[state_index] + // ts_ * x[time_index] * x[state_index + 3] * cos(x[state_index + 2])); // g[constraint_index] = // x[state_index + 4] - // ((xWS_(0, i) + ts_ * xWS_(3, i) * cos(xWS_(2, i))) + // (x[state_index] - xWS_(0, i)) + // (xWS_(3, i) * cos(xWS_(2, i))) * (ts_ * x[time_index] - ts_) + // (ts_ * cos(xWS_(2, i))) * (x[state_index + 3] - xWS_(3, i)) + // (-ts_ * xWS_(3, i) * sin(xWS_(2, i))) * // (x[state_index + 2] - xWS_(2, i))); // x2 g[constraint_index + 1] = x[state_index + 5] - (x[state_index + 1] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * sin(x[state_index + 2] + ts_ * x[time_index] * 0.5 * x[state_index + 3] * tan(x[control_index]) / wheelbase_)); // g[constraint_index + 1] = // x[state_index + 5] - // (x[state_index + 1] + // ts_ * x[time_index] * x[state_index + 3] * sin(x[state_index + 2])); // g[constraint_index + 1] = // x[state_index + 5] - // ((xWS_(1, i) + ts_ * xWS_(3, i) * sin(xWS_(2, i))) + // (x[state_index + 1] - xWS_(1, i)) + // (xWS_(3, i) * sin(xWS_(2, i))) * (ts_ * x[time_index] - ts_) + // (ts_ * sin(xWS_(2, i))) * (x[state_index + 3] - xWS_(3, i)) + // (ts_ * xWS_(3, i) * cos(xWS_(2, i))) * // (x[state_index + 2] - xWS_(2, i))); // x3 g[constraint_index + 2] = x[state_index + 6] - (x[state_index + 2] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * tan(x[control_index]) / wheelbase_); // g[constraint_index + 2] = // x[state_index + 6] - // (x[state_index + 2] + ts_ * x[time_index] * x[state_index + 3] * // tan(x[control_index]) / wheelbase_); // g[constraint_index + 2] = // x[state_index + 6] - // ((xWS_(2, i) + ts_ * xWS_(3, i) * tan(uWS_(0, i)) / wheelbase_) + // (x[state_index + 2] - xWS_(2, i)) + // (xWS_(3, i) * tan(uWS_(0, i)) / wheelbase_) * // (ts_ * x[time_index] - ts_) + // (ts_ * tan(uWS_(0, i)) / wheelbase_) * // (x[state_index + 3] - xWS_(3, i)) + // (ts_ * xWS_(3, i) / cos(uWS_(0, i)) / cos(uWS_(0, i)) / wheelbase_) // * // (x[control_index] - uWS_(0, i))); // x4 g[constraint_index + 3] = x[state_index + 7] - (x[state_index + 3] + ts_ * x[time_index] * x[control_index + 1]); // g[constraint_index + 3] = // x[state_index + 7] - // ((xWS_(3, i) + ts_ * uWS_(1, i)) + (x[state_index + 3] - xWS_(3, i)) // + // uWS_(1, i) * (ts_ * x[time_index] - ts_) + // ts_ * (x[control_index + 1] - uWS_(1, i))); control_index += 2; constraint_index += 4; time_index++; state_index += 4; } ADEBUG << "constraint_index after adding Euler forward dynamics constraints " "updated: " << constraint_index; // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply // steering rate as of now control_index = control_start_index_; time_index = time_start_index_; // First rate is compare first with stitch point g[constraint_index] = (x[control_index] - last_time_u_(0, 0)) / x[time_index] / ts_; control_index += 2; constraint_index++; time_index++; for (int i = 1; i < horizon_; ++i) { g[constraint_index] = (x[control_index] - x[control_index - 2]) / x[time_index] / ts_; constraint_index++; control_index += 2; time_index++; } // 3. Time constraints 1 * [0, horizons-1] time_index = time_start_index_; for (int i = 0; i < horizon_; ++i) { g[constraint_index] = x[time_index + 1] - x[time_index]; constraint_index++; time_index++; } ADEBUG << "constraint_index after adding time constraints " "updated: " << constraint_index; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 state_index = state_start_index_; int l_index = l_start_index_; int n_index = n_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); // norm(A* lambda) <= 1 T tmp1 = 0.0; T tmp2 = 0.0; for (int k = 0; k < current_edges_num; ++k) { // TODO(QiL) : replace this one directly with x tmp1 += Aj(k, 0) * x[l_index + k]; tmp2 += Aj(k, 1) * x[l_index + k]; } g[constraint_index] = tmp1 * tmp1 + tmp2 * tmp2; // G' * mu + R' * lambda == 0 g[constraint_index + 1] = x[n_index] - x[n_index + 2] + cos(x[state_index + 2]) * tmp1 + sin(x[state_index + 2]) * tmp2; g[constraint_index + 2] = x[n_index + 1] - x[n_index + 3] - sin(x[state_index + 2]) * tmp1 + cos(x[state_index + 2]) * tmp2; // -g'*mu + (A*t - b)*lambda > 0 T tmp3 = 0.0; for (int k = 0; k < 4; ++k) { tmp3 += -g_[k] * x[n_index + k]; } T tmp4 = 0.0; for (int k = 0; k < current_edges_num; ++k) { tmp4 += bj(k, 0) * x[l_index + k]; } g[constraint_index + 3] = tmp3 + (x[state_index] + cos(x[state_index + 2]) * offset_) * tmp1 + (x[state_index + 1] + sin(x[state_index + 2]) * offset_) * tmp2 - tmp4; // Update index edges_counter += current_edges_num; l_index += current_edges_num; n_index += 4; constraint_index += 4; } state_index += 4; } ADEBUG << "constraint_index after obstacles avoidance constraints " "updated: " << constraint_index; // 5. load variable bounds as constraints state_index = state_start_index_; control_index = control_start_index_; time_index = time_start_index_; l_index = l_start_index_; n_index = n_start_index_; // start configuration g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 2]; g[constraint_index + 3] = x[state_index + 3]; constraint_index += 4; state_index += 4; // constraints on x,y,v for (int i = 1; i < horizon_; ++i) { g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 3]; constraint_index += 3; state_index += 4; } // end configuration g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 2]; g[constraint_index + 3] = x[state_index + 3]; constraint_index += 4; state_index += 4; for (int i = 0; i < horizon_; ++i) { g[constraint_index] = x[control_index]; g[constraint_index + 1] = x[control_index + 1]; constraint_index += 2; control_index += 2; } for (int i = 0; i < horizon_ + 1; ++i) { g[constraint_index] = x[time_index]; constraint_index++; time_index++; } for (int i = 0; i < lambda_horizon_; ++i) { g[constraint_index] = x[l_index]; constraint_index++; l_index++; } for (int i = 0; i < miu_horizon_; ++i) { g[constraint_index] = x[n_index]; constraint_index++; n_index++; } } bool DistanceApproachIPOPTInterface::check_g(int n, const double* x, int m, const double* g) { int kN = n; int kM = m; double x_u_tmp[kN]; double x_l_tmp[kN]; double g_u_tmp[kM]; double g_l_tmp[kM]; get_bounds_info(n, x_l_tmp, x_u_tmp, m, g_l_tmp, g_u_tmp); const double delta_v = 1e-4; for (int idx = 0; idx < n; ++idx) { x_u_tmp[idx] = x_u_tmp[idx] + delta_v; x_l_tmp[idx] = x_l_tmp[idx] - delta_v; if (x[idx] > x_u_tmp[idx] || x[idx] < x_l_tmp[idx]) { AINFO << "x idx unfeasible: " << idx << ", x: " << x[idx] << ", lower: " << x_l_tmp[idx] << ", upper: " << x_u_tmp[idx]; } } // m1 : dynamics constatins int m1 = 4 * horizon_; // m2 : control rate constraints (only steering) int m2 = m1 + horizon_; // m3 : sampling time equality constraints int m3 = m2 + horizon_; // m4 : obstacle constraints int m4 = m3 + 4 * obstacles_num_ * (horizon_ + 1); // 5. load variable bounds as constraints // start configuration int m5 = m4 + 3 + 1; // constraints on x,y,v int m6 = m5 + 3 * (horizon_ - 1); // end configuration int m7 = m6 + 3 + 1; // control variable bnd int m8 = m7 + 2 * horizon_; // time interval variable bnd int m9 = m8 + (horizon_ + 1); // lambda_horizon_ int m10 = m9 + lambda_horizon_; // miu_horizon_ int m11 = m10 + miu_horizon_; CHECK_EQ(m11, num_of_constraints_); AINFO << "dynamics constatins to: " << m1; AINFO << "control rate constraints (only steering) to: " << m2; AINFO << "sampling time equality constraints to: " << m3; AINFO << "obstacle constraints to: " << m4; AINFO << "start conf constraints to: " << m5; AINFO << "constraints on x,y,v to: " << m6; AINFO << "end constraints to: " << m7; AINFO << "control bnd to: " << m8; AINFO << "time interval constraints to: " << m9; AINFO << "lambda constraints to: " << m10; AINFO << "miu constraints to: " << m11; AINFO << "total constraints: " << num_of_constraints_; for (int idx = 0; idx < m; ++idx) { if (g[idx] > g_u_tmp[idx] + delta_v || g[idx] < g_l_tmp[idx] - delta_v) { AINFO << "constrains idx unfeasible: " << idx << ", g: " << g[idx] << ", lower: " << g_l_tmp[idx] << ", upper: " << g_u_tmp[idx]; } } return true; } void DistanceApproachIPOPTInterface::generate_tapes(int n, int m, int* nnz_jac_g, int* nnz_h_lag) { std::vector<double> xp(n); std::vector<double> lamp(m); std::vector<double> zl(m); std::vector<double> zu(m); std::vector<adouble> xa(n); std::vector<adouble> g(m); std::vector<double> lam(m); double sig; adouble obj_value; double dummy = 0.0; obj_lam = new double[m + 1]; get_starting_point(n, 1, &xp[0], 0, &zl[0], &zu[0], m, 0, &lamp[0]); trace_on(tag_f); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_obj(n, &xa[0], &obj_value); obj_value >>= dummy; trace_off(); trace_on(tag_g); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { g[idx] >>= dummy; } trace_off(); trace_on(tag_L); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } for (int idx = 0; idx < m; idx++) { lam[idx] = 1.0; } sig = 1.0; eval_obj(n, &xa[0], &obj_value); obj_value *= mkparam(sig); eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { obj_value += g[idx] * mkparam(lam[idx]); } obj_value >>= dummy; trace_off(); if (enable_jacobian_ad_) { rind_g = nullptr; cind_g = nullptr; jacval = nullptr; options_g[0] = 0; /* sparsity pattern by index domains (default) */ options_g[1] = 0; /* safe mode (default) */ options_g[2] = 0; options_g[3] = 0; /* column compression (default) */ sparse_jac(tag_g, m, n, 0, &xp[0], &nnz_jac, &rind_g, &cind_g, &jacval, options_g); *nnz_jac_g = nnz_jac; } rind_L = nullptr; cind_L = nullptr; hessval = nullptr; options_L[0] = 0; options_L[1] = 1; sparse_hess(tag_L, n, 0, &xp[0], &nnz_L, &rind_L, &cind_L, &hessval, options_L); *nnz_h_lag = nnz_L; } //*************** end ADOL-C part *********************************** } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_fixed_dual_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 */ #pragma once #include <algorithm> #include <limits> #include <vector> #include <omp.h> #include <adolc/adolc.h> #include <adolc/adolc_openmp.h> #include <adolc/adolc_sparse.h> #include <adolc/adouble.h> #include <coin/IpTNLP.hpp> #include <coin/IpTypes.hpp> #include "Eigen/Dense" #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_interface.h" #include "modules/planning/proto/planner_open_space_config.pb.h" #define tag_f 1 #define tag_g 2 #define tag_L 3 #define HPOFF 30 namespace apollo { namespace planning { class DistanceApproachIPOPTFixedDualInterface : public DistanceApproachInterface { public: DistanceApproachIPOPTFixedDualInterface( const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xf, const Eigen::MatrixXd& last_time_u, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const PlannerOpenSpaceConfig& planner_open_space_config); virtual ~DistanceApproachIPOPTFixedDualInterface() = default; /** Method to return some info about the nlp */ bool get_nlp_info(int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, // NOLINT IndexStyleEnum& index_style) override; // NOLINT /** 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; /** Check unfeasible constraints for further study**/ bool check_g(int n, const double* x, int m, const double* g); /** 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; // sequential implementation to jac_g bool eval_jac_g_ser(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 get_optimization_results(Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) const override; //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> void eval_obj(int n, const T* x, T* obj_value); /** Template to compute constraints */ template <class T> void eval_constraints(int n, const T* x, int m, T* g); /** Method to generate the required tapes by ADOL-C*/ void generate_tapes(int n, int m, int* nnz_jac_g, int* nnz_h_lag); //*************** end ADOL-C part *********************************** private: int num_of_variables_ = 0; int num_of_constraints_ = 0; int horizon_ = 0; int lambda_horizon_ = 0; int miu_horizon_ = 0; double ts_ = 0.0; Eigen::MatrixXd ego_; Eigen::MatrixXd xWS_; Eigen::MatrixXd uWS_; Eigen::MatrixXd l_warm_up_; Eigen::MatrixXd n_warm_up_; Eigen::MatrixXd x0_; Eigen::MatrixXd xf_; Eigen::MatrixXd last_time_u_; std::vector<double> XYbounds_; // debug flag bool enable_constraint_check_; // penalty double weight_state_x_ = 0.0; double weight_state_y_ = 0.0; double weight_state_phi_ = 0.0; double weight_state_v_ = 0.0; double weight_input_steer_ = 0.0; double weight_input_a_ = 0.0; double weight_rate_steer_ = 0.0; double weight_rate_a_ = 0.0; double weight_stitching_steer_ = 0.0; double weight_stitching_a_ = 0.0; double weight_first_order_time_ = 0.0; double weight_second_order_time_ = 0.0; double w_ev_ = 0.0; double l_ev_ = 0.0; std::vector<double> g_; double offset_ = 0.0; Eigen::MatrixXi obstacles_edges_num_; int obstacles_num_ = 0; int obstacles_edges_sum_ = 0; double wheelbase_ = 0.0; Eigen::MatrixXd state_result_; Eigen::MatrixXd dual_l_result_; Eigen::MatrixXd dual_n_result_; Eigen::MatrixXd control_result_; Eigen::MatrixXd time_result_; // obstacles_A Eigen::MatrixXd obstacles_A_; // obstacles_b Eigen::MatrixXd obstacles_b_; // whether to use fix time bool use_fix_time_ = false; // state start index int state_start_index_ = 0; // control start index. int control_start_index_ = 0; // time start index int time_start_index_ = 0; // lagrangian l start index int l_start_index_ = 0; // lagrangian n start index int n_start_index_ = 0; double min_safety_distance_ = 0.0; double max_safety_distance_ = 0.0; double max_steer_angle_ = 0.0; double max_speed_forward_ = 0.0; double max_speed_reverse_ = 0.0; double max_acceleration_forward_ = 0.0; double max_acceleration_reverse_ = 0.0; double min_time_sample_scaling_ = 0.0; double max_time_sample_scaling_ = 0.0; double max_steer_rate_ = 0.0; double max_lambda_ = 0.0; double max_miu_ = 0.0; bool enable_jacobian_ad_ = false; private: DistanceApproachConfig distance_approach_config_; const common::VehicleParam vehicle_param_ = common::VehicleConfigHelper::GetConfig().vehicle_param(); private: //*************** start ADOL-C part *********************************** double* obj_lam; //** variables for sparsity exploitation unsigned int* rind_g; /* row indices */ unsigned int* cind_g; /* column indices */ double* jacval; /* values */ unsigned int* rind_L; /* row indices */ unsigned int* cind_L; /* column indices */ double* hessval; /* values */ int nnz_jac; int nnz_L; int options_g[4]; int options_L[4]; //*************** end ADOL-C part *********************************** }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_relax_end_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 */ #pragma once #include <algorithm> #include <limits> #include <vector> #include <omp.h> #include <adolc/adolc.h> #include <adolc/adolc_openmp.h> #include <adolc/adolc_sparse.h> #include <adolc/adouble.h> #include <coin/IpTNLP.hpp> #include <coin/IpTypes.hpp> #include "Eigen/Dense" #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_interface.h" #include "modules/planning/proto/planner_open_space_config.pb.h" #define tag_f 1 #define tag_g 2 #define tag_L 3 #define HPOFF 30 namespace apollo { namespace planning { class DistanceApproachIPOPTRelaxEndInterface : public DistanceApproachInterface { public: DistanceApproachIPOPTRelaxEndInterface( const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xf, const Eigen::MatrixXd& last_time_u, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const PlannerOpenSpaceConfig& planner_open_space_config); virtual ~DistanceApproachIPOPTRelaxEndInterface() = default; /** Method to return some info about the nlp */ bool get_nlp_info(int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, // NOLINT IndexStyleEnum& index_style) override; // NOLINT /** 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; /** Check unfeasible constraints for further study**/ bool check_g(int n, const double* x, int m, const double* g); /** 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; // sequential implementation to jac_g bool eval_jac_g_ser(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 get_optimization_results(Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) const override; //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> void eval_obj(int n, const T* x, T* obj_value); /** Template to compute constraints */ template <class T> void eval_constraints(int n, const T* x, int m, T* g); /** Method to generate the required tapes by ADOL-C*/ void generate_tapes(int n, int m, int* nnz_jac_g, int* nnz_h_lag); //*************** end ADOL-C part *********************************** private: int num_of_variables_ = 0; int num_of_constraints_ = 0; int horizon_ = 0; int lambda_horizon_ = 0; int miu_horizon_ = 0; double ts_ = 0.0; Eigen::MatrixXd ego_; Eigen::MatrixXd xWS_; Eigen::MatrixXd uWS_; Eigen::MatrixXd l_warm_up_; Eigen::MatrixXd n_warm_up_; Eigen::MatrixXd x0_; Eigen::MatrixXd xf_; Eigen::MatrixXd last_time_u_; std::vector<double> XYbounds_; // debug flag bool enable_constraint_check_; // penalty double weight_state_x_ = 0.0; double weight_state_y_ = 0.0; double weight_state_phi_ = 0.0; double weight_state_v_ = 0.0; double weight_input_steer_ = 0.0; double weight_input_a_ = 0.0; double weight_rate_steer_ = 0.0; double weight_rate_a_ = 0.0; double weight_stitching_steer_ = 0.0; double weight_stitching_a_ = 0.0; double weight_first_order_time_ = 0.0; double weight_second_order_time_ = 0.0; double weight_end_state_ = 0.0; double w_ev_ = 0.0; double l_ev_ = 0.0; std::vector<double> g_; double offset_ = 0.0; Eigen::MatrixXi obstacles_edges_num_; int obstacles_num_ = 0; int obstacles_edges_sum_ = 0; double wheelbase_ = 0.0; Eigen::MatrixXd state_result_; Eigen::MatrixXd dual_l_result_; Eigen::MatrixXd dual_n_result_; Eigen::MatrixXd control_result_; Eigen::MatrixXd time_result_; // obstacles_A Eigen::MatrixXd obstacles_A_; // obstacles_b Eigen::MatrixXd obstacles_b_; // whether to use fix time bool use_fix_time_ = false; // state start index int state_start_index_ = 0; // control start index. int control_start_index_ = 0; // time start index int time_start_index_ = 0; // lagrangian l start index int l_start_index_ = 0; // lagrangian n start index int n_start_index_ = 0; double min_safety_distance_ = 0.0; double max_safety_distance_ = 0.0; double max_steer_angle_ = 0.0; double max_speed_forward_ = 0.0; double max_speed_reverse_ = 0.0; double max_acceleration_forward_ = 0.0; double max_acceleration_reverse_ = 0.0; double min_time_sample_scaling_ = 0.0; double max_time_sample_scaling_ = 0.0; double max_steer_rate_ = 0.0; double max_lambda_ = 0.0; double max_miu_ = 0.0; bool enable_jacobian_ad_ = false; private: DistanceApproachConfig distance_approach_config_; const common::VehicleParam vehicle_param_ = common::VehicleConfigHelper::GetConfig().vehicle_param(); private: //*************** start ADOL-C part *********************************** double* obj_lam; //** variables for sparsity exploitation unsigned int* rind_g; /* row indices */ unsigned int* cind_g; /* column indices */ double* jacval; /* values */ unsigned int* rind_L; /* row indices */ unsigned int* cind_L; /* column indices */ double* hessval; /* values */ int nnz_jac; int nnz_L; int options_g[4]; int options_L[4]; //*************** end ADOL-C part *********************************** }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_cuda_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 */ #pragma once #include <vector> #include <omp.h> #include <adolc/adolc.h> #include <adolc/adolc_openmp.h> #include <adolc/adolc_sparse.h> #include <adolc/adouble.h> #include <coin/IpTNLP.hpp> #include <coin/IpTypes.hpp> #include "Eigen/Dense" #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_interface.h" #include "modules/planning/proto/planner_open_space_config.pb.h" #define tag_f 1 #define tag_g 2 #define tag_L 3 #define HPOFF 30 namespace apollo { namespace planning { class DistanceApproachIPOPTCUDAInterface : public DistanceApproachInterface { public: DistanceApproachIPOPTCUDAInterface( const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xf, const Eigen::MatrixXd& last_time_u, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const PlannerOpenSpaceConfig& planner_open_space_config); virtual ~DistanceApproachIPOPTCUDAInterface() = default; /** Method to return some info about the nlp */ bool get_nlp_info(int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, // NOLINT IndexStyleEnum& index_style) override; // NOLINT /** 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; // eval_grad_f by hand. bool eval_grad_f_hand(int n, const double* x, bool new_x, double* grad_f); /** Method to return the constraint residuals */ bool eval_g(int n, const double* x, bool new_x, int m, double* g) override; /** Check unfeasible constraints for further study**/ bool check_g(int n, const double* x, int m, const double* g); /** 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; // sequential implementation to jac_g bool eval_jac_g_ser(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values); // parallel implementation to jac_g bool eval_jac_g_par(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values); /** 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 get_optimization_results(Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) const; //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> bool eval_obj(int n, const T* x, T* obj_value); /** Template to compute constraints */ template <class T> bool eval_constraints(int n, const T* x, int m, T* g); /** Method to generate the required tapes by ADOL-C*/ void generate_tapes(int n, int m, int* nnz_h_lag); //*************** end ADOL-C part *********************************** private: int num_of_variables_ = 0; int num_of_constraints_ = 0; int horizon_ = 0; int lambda_horizon_ = 0; int miu_horizon_ = 0; double ts_ = 0.0; Eigen::MatrixXd ego_; Eigen::MatrixXd xWS_; Eigen::MatrixXd uWS_; Eigen::MatrixXd l_warm_up_; Eigen::MatrixXd n_warm_up_; Eigen::MatrixXd x0_; Eigen::MatrixXd xf_; Eigen::MatrixXd last_time_u_; std::vector<double> XYbounds_; // debug flag bool enable_constraint_check_; // penalty double weight_state_x_ = 0.0; double weight_state_y_ = 0.0; double weight_state_phi_ = 0.0; double weight_state_v_ = 0.0; double weight_input_steer_ = 0.0; double weight_input_a_ = 0.0; double weight_rate_steer_ = 0.0; double weight_rate_a_ = 0.0; double weight_stitching_steer_ = 0.0; double weight_stitching_a_ = 0.0; double weight_first_order_time_ = 0.0; double weight_second_order_time_ = 0.0; double w_ev_ = 0.0; double l_ev_ = 0.0; std::vector<double> g_; double offset_ = 0.0; Eigen::MatrixXi obstacles_edges_num_; int obstacles_num_ = 0; int obstacles_edges_sum_ = 0; double wheelbase_ = 0.0; Eigen::MatrixXd state_result_; Eigen::MatrixXd dual_l_result_; Eigen::MatrixXd dual_n_result_; Eigen::MatrixXd control_result_; Eigen::MatrixXd time_result_; // obstacles_A Eigen::MatrixXd obstacles_A_; // obstacles_b Eigen::MatrixXd obstacles_b_; // whether to use fix time bool use_fix_time_ = false; // state start index int state_start_index_ = 0; // control start index. int control_start_index_ = 0; // time start index int time_start_index_ = 0; // lagrangian l start index int l_start_index_ = 0; // lagrangian n start index int n_start_index_ = 0; double min_safety_distance_ = 0.0; double max_safety_distance_ = 0.0; double max_steer_angle_ = 0.0; double max_speed_forward_ = 0.0; double max_speed_reverse_ = 0.0; double max_acceleration_forward_ = 0.0; double max_acceleration_reverse_ = 0.0; double min_time_sample_scaling_ = 0.0; double max_time_sample_scaling_ = 0.0; double max_steer_rate_ = 0.0; double max_lambda_ = 0.0; double max_miu_ = 0.0; private: DistanceApproachConfig distance_approach_config_; PlannerOpenSpaceConfig planner_open_space_config_; const common::VehicleParam vehicle_param_ = common::VehicleConfigHelper::GetConfig().vehicle_param(); private: //*************** start ADOL-C part *********************************** double* obj_lam; unsigned int* rind_L; /* row indices */ unsigned int* cind_L; /* column indices */ double* hessval; /* values */ int nnz_L = 0; int options_L[4]; //*************** end ADOL-C part *********************************** }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/planning_block.cu
/****************************************************************************** * 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 <iostream> #include "planning_block.h" namespace apollo { namespace planning { bool InitialCuda() { int dev = 0; cudaDeviceProp deviceProp; CUDA_CHECK(cudaGetDeviceProperties(&deviceProp, dev)); CUDA_CHECK(cudaSetDevice(dev)); return true; } __global__ void fill_lower_left_gpu(int *iRow, int *jCol, unsigned int *rind_L, unsigned int *cind_L, const int nnz_L) { int i = threadIdx.x; if (i < nnz_L) { iRow[i] = rind_L[i]; jCol[i] = cind_L[i]; } } template <typename T> __global__ void data_transfer_gpu(T *dst, const T *src, const int size) { int i = threadIdx.x; if (i < size) { dst[i] = src[i]; } } bool fill_lower_left(int *iRow, int *jCol, unsigned int *rind_L, unsigned int *cind_L, const int nnz_L) { if (!InitialCuda()) return false; int *d_iRow, *d_jCol; unsigned int *d_rind_L, *d_cind_L; unsigned int nBytes = nnz_L * sizeof(int); unsigned int nUBytes = nnz_L * sizeof(unsigned int); cudaMalloc((void **)&d_iRow, nBytes); cudaMalloc((void **)&d_jCol, nBytes); cudaMalloc((void **)&d_rind_L, nUBytes); cudaMalloc((void **)&d_cind_L, nUBytes); cudaMemcpy(d_iRow, iRow, nBytes, cudaMemcpyHostToDevice); cudaMemcpy(d_jCol, jCol, nBytes, cudaMemcpyHostToDevice); dim3 block(BLOCK_1); dim3 grid((nnz_L + block.x - 1) / block.x); fill_lower_left_gpu<<<grid, block>>>(d_iRow, d_jCol, d_rind_L, d_cind_L, nnz_L); cudaDeviceSynchronize(); cudaMemcpy(rind_L, d_rind_L, nUBytes, cudaMemcpyDeviceToHost); cudaMemcpy(cind_L, d_cind_L, nUBytes, cudaMemcpyDeviceToHost); cudaFree(d_iRow); cudaFree(d_jCol); cudaFree(d_rind_L); cudaFree(d_cind_L); cudaDeviceReset(); return true; } template <typename T> bool data_transfer(T *dst, const T *src, const int size) { if (!InitialCuda()) return false; T *d_dst, *d_src; size_t nBytes = size * sizeof(T); cudaMalloc((void **)&d_dst, nBytes); cudaMalloc((void **)&d_src, nBytes); cudaMemcpy(d_src, src, nBytes, cudaMemcpyHostToDevice); cudaMemcpy(d_dst, dst, nBytes, cudaMemcpyHostToDevice); dim3 block(BLOCK_1); dim3 grid((size + block.x - 1) / block.x); data_transfer_gpu<<<grid, block>>>(dst, src, size); cudaDeviceSynchronize(); cudaMemcpy(dst, d_dst, nBytes, cudaMemcpyDeviceToHost); cudaFree(d_dst); cudaFree(d_src); cudaDeviceReset(); return true; } DATA_TRANSFER_INST(int); DATA_TRANSFER_INST(double); DATA_TRANSFER_INST(float); } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_ipopt_interface.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/open_space/trajectory_smoother/dual_variable_warm_start_ipopt_interface.h" #include "cyber/common/log.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { DualVariableWarmStartIPOPTInterface::DualVariableWarmStartIPOPTInterface( size_t horizon, double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const Eigen::MatrixXd& xWS, const PlannerOpenSpaceConfig& planner_open_space_config) : ts_(ts), ego_(ego), obstacles_edges_num_(obstacles_edges_num), obstacles_A_(obstacles_A), obstacles_b_(obstacles_b), xWS_(xWS) { ACHECK(horizon < std::numeric_limits<int>::max()) << "Invalid cast on horizon in open space planner"; horizon_ = static_cast<int>(horizon); ACHECK(obstacles_num < std::numeric_limits<int>::max()) << "Invalid cast on obstacles_num in open space planner"; obstacles_num_ = static_cast<int>(obstacles_num); w_ev_ = ego_(1, 0) + ego_(3, 0); l_ev_ = ego_(0, 0) + ego_(2, 0); g_ = {l_ev_ / 2, w_ev_ / 2, l_ev_ / 2, w_ev_ / 2}; offset_ = (ego_(0, 0) + ego_(2, 0)) / 2 - ego_(2, 0); obstacles_edges_sum_ = obstacles_edges_num_.sum(); l_start_index_ = 0; n_start_index_ = l_start_index_ + obstacles_edges_sum_ * (horizon_ + 1); d_start_index_ = n_start_index_ + 4 * obstacles_num_ * (horizon_ + 1); l_warm_up_ = Eigen::MatrixXd::Zero(obstacles_edges_sum_, horizon_ + 1); n_warm_up_ = Eigen::MatrixXd::Zero(4 * obstacles_num_, horizon_ + 1); weight_d_ = planner_open_space_config.dual_variable_warm_start_config().weight_d(); } bool DualVariableWarmStartIPOPTInterface::get_nlp_info( int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) { lambda_horizon_ = obstacles_edges_sum_ * (horizon_ + 1); miu_horizon_ = obstacles_num_ * 4 * (horizon_ + 1); dual_formulation_horizon_ = obstacles_num_ * (horizon_ + 1); num_of_variables_ = lambda_horizon_ + miu_horizon_ + dual_formulation_horizon_; num_of_constraints_ = 4 * obstacles_num_ * (horizon_ + 1) + num_of_variables_; // number of variables n = num_of_variables_; // number of constraints m = num_of_constraints_; // number of nonzero Jacobian and Lagrangian. generate_tapes(n, m, &nnz_h_lag); int tmp = 0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); tmp += current_edges_num * 4 + 2 + 2 + 4 + 1; } } nnz_jac_g = tmp + num_of_variables_; ADEBUG << "nnz_jac_g : " << nnz_jac_g; index_style = IndexStyleEnum::C_STYLE; return true; } bool DualVariableWarmStartIPOPTInterface::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) { ADEBUG << "get_starting_point"; ACHECK(init_x) << "Warm start init_x setting failed"; ACHECK(!init_z) << "Warm start init_z setting failed"; ACHECK(!init_lambda) << "Warm start init_lambda setting failed"; int l_index = l_start_index_; int n_index = n_start_index_; int d_index = d_start_index_; ADEBUG << "l_start_index_ : " << l_start_index_; ADEBUG << "n_start_index_ : " << n_start_index_; ADEBUG << "d_start_index_ : " << d_start_index_; // 1. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { x[l_index] = 0.0; ++l_index; } } // 2. lagrange constraint n, 4*obstacles_num * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { x[n_index] = 0.0; ++n_index; } } // 3. d, [0, obstacles_num] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { x[d_index] = 0.0; ++d_index; } } ADEBUG << "get_starting_point out"; return true; } bool DualVariableWarmStartIPOPTInterface::get_bounds_info(int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) { int variable_index = 0; // 1. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0, // horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; ++variable_index; } } ADEBUG << "variable_index after adding lagrange l : " << variable_index; // 2. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // nlp_upper_bound_limit ++variable_index; } } ADEBUG << "variable_index after adding lagrange n : " << variable_index; // 3. d, [0, obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { // TODO(QiL): Load this from configuration x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // nlp_upper_bound_limit ++variable_index; } } ADEBUG << "variable_index after adding d : " << variable_index; int constraint_index = 0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { // a. norm(A'*lambda) <= 1 g_l[constraint_index] = -2e19; g_u[constraint_index] = 1.0; // b. G'*mu + R'*A*lambda = 0 g_l[constraint_index + 1] = 0.0; g_u[constraint_index + 1] = 0.0; g_l[constraint_index + 2] = 0.0; g_u[constraint_index + 2] = 0.0; // c. d - (-g'*mu + (A*t - b)*lambda) = 0 g_l[constraint_index + 3] = 0.0; g_u[constraint_index + 3] = 0.0; constraint_index += 4; } } int l_index = l_start_index_; int n_index = n_start_index_; int d_index = d_start_index_; for (int i = 0; i < lambda_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; l_index++; } for (int i = 0; i < miu_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; n_index++; } for (int i = 0; i < dual_formulation_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; d_index++; } ADEBUG << "constraint_index after adding obstacles constraints: " << constraint_index; return true; } bool DualVariableWarmStartIPOPTInterface::eval_f(int n, const double* x, bool new_x, double& obj_value) { eval_obj(n, x, &obj_value); return true; } bool DualVariableWarmStartIPOPTInterface::eval_grad_f(int n, const double* x, bool new_x, double* grad_f) { // gradient(tag_f, n, x, grad_f); // return true; std::fill(grad_f, grad_f + n, 0.0); int d_index = d_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { grad_f[d_index] = weight_d_; ++d_index; } } return true; } bool DualVariableWarmStartIPOPTInterface::eval_g(int n, const double* x, bool new_x, int m, double* g) { eval_constraints(n, x, m, g); return true; } bool DualVariableWarmStartIPOPTInterface::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) { // // return the structure of the jacobian // for (int idx = 0; idx < nnz_jac; idx++) { // iRow[idx] = rind_g[idx]; // jCol[idx] = cind_g[idx]; // } // } else { // // return the values of the jacobian of the constraints // sparse_jac(tag_g, m, n, 1, x, &nnz_jac, &rind_g, &cind_g, &jacval, // options_g); // for (int idx = 0; idx < nnz_jac; idx++) { // values[idx] = jacval[idx]; // } // } // return true; ADEBUG << "eval_jac_g"; if (values == nullptr) { int nz_index = 0; int constraint_index = 0; // 1. Three obstacles related equal constraints, one equality // constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 int l_index = l_start_index_; int n_index = n_start_index_; int d_index = d_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); // 1. norm(A* lambda <= 1) for (int k = 0; k < current_edges_num; ++k) { // with respect to l iRow[nz_index] = constraint_index; jCol[nz_index] = l_index + k; ++nz_index; } // 2. G' * mu + R' * lambda == 0, part 1 // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index] = constraint_index + 1; jCol[nz_index] = l_index + k; ++nz_index; } // With respect to n iRow[nz_index] = constraint_index + 1; jCol[nz_index] = n_index; ++nz_index; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = n_index + 2; ++nz_index; // 2. G' * mu + R' * lambda == 0, part 2 // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index] = constraint_index + 2; jCol[nz_index] = l_index + k; ++nz_index; } // With respect to n iRow[nz_index] = constraint_index + 2; jCol[nz_index] = n_index + 1; ++nz_index; iRow[nz_index] = constraint_index + 2; jCol[nz_index] = n_index + 3; ++nz_index; // -g'*mu + (A*t - b)*lambda > 0 // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index] = constraint_index + 3; jCol[nz_index] = l_index + k; ++nz_index; } // with respect to n for (int k = 0; k < 4; ++k) { iRow[nz_index] = constraint_index + 3; jCol[nz_index] = n_index + k; ++nz_index; } // with resepct to d iRow[nz_index] = constraint_index + 3; jCol[nz_index] = d_index; ++nz_index; // Update index l_index += current_edges_num; n_index += 4; d_index += 1; constraint_index += 4; } } l_index = l_start_index_; n_index = n_start_index_; d_index = d_start_index_; for (int i = 0; i < lambda_horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = l_index; ++nz_index; ++constraint_index; ++l_index; } for (int i = 0; i < miu_horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = n_index; ++nz_index; ++constraint_index; ++n_index; } for (int i = 0; i < dual_formulation_horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = d_index; ++nz_index; ++constraint_index; ++d_index; } CHECK_EQ(constraint_index, m) << "No. of constraints wrong in eval_jac_g."; ADEBUG << "nz_index here : " << nz_index << " nele_jac is : " << nele_jac; } else { std::fill(values, values + nele_jac, 0.0); int nz_index = 0; // 1. Three obstacles related equal constraints, one equality // constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 int l_index = l_start_index_; int n_index = n_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); // TODO(QiL) : Remove redundant calculation double tmp1 = 0; double tmp2 = 0; for (int k = 0; k < current_edges_num; ++k) { // TODO(QiL) : replace this one directly with x tmp1 += Aj(k, 0) * x[l_index + k]; tmp2 += Aj(k, 1) * x[l_index + k]; } // 1. norm(A* lambda == 1) for (int k = 0; k < current_edges_num; ++k) { // with respect to l values[nz_index] = 2 * tmp1 * Aj(k, 0) + 2 * tmp2 * Aj(k, 1); // t0~tk ++nz_index; } // 2. G' * mu + R' * lambda == 0, part 1 // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index] = std::cos(xWS_(2, i)) * Aj(k, 0) + std::sin(xWS_(2, i)) * Aj(k, 1); // v0~vn ++nz_index; } // With respect to n values[nz_index] = 1.0; // w0 ++nz_index; values[nz_index] = -1.0; // w2 ++nz_index; ADEBUG << "eval_jac_g, after adding part 2"; // 3. G' * mu + R' * lambda == 0, part 2 // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index] = -std::sin(xWS_(2, i)) * Aj(k, 0) + std::cos(xWS_(2, i)) * Aj(k, 1); // y0~yn ++nz_index; } // With respect to n values[nz_index] = 1.0; // z1 ++nz_index; values[nz_index] = -1.0; // z3 ++nz_index; // 3. -g'*mu + (A*t - b)*lambda > 0 // TODO(QiL): Revise dual variables modeling here. double tmp3 = 0.0; double tmp4 = 0.0; for (int k = 0; k < 4; ++k) { tmp3 += -g_[k] * x[n_index + k]; } for (int k = 0; k < current_edges_num; ++k) { tmp4 += bj(k, 0) * x[l_index + k]; } // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index] = -(xWS_(0, i) + std::cos(xWS_(2, i)) * offset_) * Aj(k, 0) - (xWS_(1, i) + std::sin(xWS_(2, i)) * offset_) * Aj(k, 1) + bj(k, 0); // ddk ++nz_index; } // with respect to n for (int k = 0; k < 4; ++k) { values[nz_index] = g_[k]; // eek ++nz_index; } // with respect to d values[nz_index] = 1.0; // ffk ++nz_index; // Update index edges_counter += current_edges_num; l_index += current_edges_num; n_index += 4; } } for (int i = 0; i < lambda_horizon_; ++i) { values[nz_index] = 1.0; ++nz_index; } for (int i = 0; i < miu_horizon_; ++i) { values[nz_index] = 1.0; ++nz_index; } for (int i = 0; i < dual_formulation_horizon_; ++i) { values[nz_index] = 1.0; ++nz_index; } ADEBUG << "eval_jac_g, fulfilled obstacle constraint values"; CHECK_EQ(nz_index, nele_jac); } ADEBUG << "eval_jac_g done"; return true; } bool DualVariableWarmStartIPOPTInterface::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) { // return the structure. This is a symmetric matrix, fill the lower left // triangle only. for (int idx = 0; idx < nnz_L; idx++) { iRow[idx] = rind_L[idx]; jCol[idx] = cind_L[idx]; } } else { // return the values. This is a symmetric matrix, fill the lower left // triangle only obj_lam[0] = obj_factor; for (int idx = 0; idx < m; idx++) { obj_lam[1 + idx] = lambda[idx]; } set_param_vec(tag_L, m + 1, obj_lam); sparse_hess(tag_L, n, 1, const_cast<double*>(x), &nnz_L, &rind_L, &cind_L, &hessval, options_L); for (int idx = 0; idx < nnz_L; idx++) { values[idx] = hessval[idx]; } } return true; } void DualVariableWarmStartIPOPTInterface::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) { int variable_index = 0; // 1. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0, // horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { l_warm_up_(j, i) = x[variable_index]; ++variable_index; } } ADEBUG << "variable_index after adding lagrange l : " << variable_index; // 2. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { n_warm_up_(j, i) = x[variable_index]; ++variable_index; } } ADEBUG << "variable_index after adding lagrange n : " << variable_index; // memory deallocation of ADOL-C variables delete[] obj_lam; free(rind_L); free(cind_L); free(hessval); } void DualVariableWarmStartIPOPTInterface::get_optimization_results( Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up) const { *l_warm_up = l_warm_up_; *n_warm_up = n_warm_up_; } //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> bool DualVariableWarmStartIPOPTInterface::eval_obj(int n, const T* x, T* obj_value) { ADEBUG << "eval_obj"; *obj_value = 0.0; int d_index = d_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { *obj_value += weight_d_ * x[d_index]; ++d_index; } } return true; } /** Template to compute constraints */ template <class T> bool DualVariableWarmStartIPOPTInterface::eval_constraints(int n, const T* x, int m, T* g) { ADEBUG << "eval_constraints"; // state start index // 1. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 int l_index = l_start_index_; int n_index = n_start_index_; int d_index = d_start_index_; int constraint_index = 0; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; // assume: stationary obstacles for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); // norm(A* lambda) <= 1 T tmp1 = 0.0; T tmp2 = 0.0; for (int k = 0; k < current_edges_num; ++k) { tmp1 += Aj(k, 0) * x[l_index + k]; tmp2 += Aj(k, 1) * x[l_index + k]; } g[constraint_index] = tmp1 * tmp1 + tmp2 * tmp2; // G' * mu + R' * A' * lambda == 0 g[constraint_index + 1] = x[n_index] - x[n_index + 2] + cos(xWS_(2, i)) * tmp1 + sin(xWS_(2, i)) * tmp2; g[constraint_index + 2] = x[n_index + 1] - x[n_index + 3] - sin(xWS_(2, i)) * tmp1 + cos(xWS_(2, i)) * tmp2; // d - (-g'*mu + (A*t - b)*lambda) = 0 // TODO(QiL): Need to revise according to dual modeling T tmp3 = 0.0; for (int k = 0; k < 4; ++k) { tmp3 += g_[k] * x[n_index + k]; } T tmp4 = 0.0; for (int k = 0; k < current_edges_num; ++k) { tmp4 += bj(k, 0) * x[l_index + k]; } g[constraint_index + 3] = x[d_index] + tmp3 - (xWS_(0, i) + cos(xWS_(2, i)) * offset_) * tmp1 - (xWS_(1, i) + sin(xWS_(2, i)) * offset_) * tmp2 + tmp4; // Update index edges_counter += current_edges_num; l_index += current_edges_num; n_index += 4; d_index += 1; constraint_index += 4; } } l_index = l_start_index_; n_index = n_start_index_; d_index = d_start_index_; for (int i = 0; i < lambda_horizon_; ++i) { g[constraint_index] = x[l_index]; constraint_index++; l_index++; } for (int i = 0; i < miu_horizon_; ++i) { g[constraint_index] = x[n_index]; constraint_index++; n_index++; } for (int i = 0; i < dual_formulation_horizon_; ++i) { g[constraint_index] = x[d_index]; constraint_index++; d_index++; } CHECK_EQ(constraint_index, m) << "No. of constraints wrong in eval_g. n : " << n; return true; } /** Method to generate the required tapes */ void DualVariableWarmStartIPOPTInterface::generate_tapes(int n, int m, int* nnz_h_lag) { std::vector<double> xp(n); std::vector<double> lamp(m); std::vector<double> zl(m); std::vector<double> zu(m); std::vector<adouble> xa(n); std::vector<adouble> g(m); std::vector<double> lam(m); double sig; adouble obj_value; double dummy = 0.0; obj_lam = new double[m + 1]; get_starting_point(n, 1, &xp[0], 0, &zl[0], &zu[0], m, 0, &lamp[0]); // trace_on(tag_f); // for (int idx = 0; idx < n; idx++) xa[idx] <<= xp[idx]; // eval_obj(n, xa, &obj_value); // obj_value >>= dummy; // trace_off(); // trace_on(tag_g); // for (int idx = 0; idx < n; idx++) xa[idx] <<= xp[idx]; // eval_constraints(n, xa, m, g); // for (int idx = 0; idx < m; idx++) g[idx] >>= dummy; // trace_off(); trace_on(tag_L); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } for (int idx = 0; idx < m; idx++) { lam[idx] = 1.0; } sig = 1.0; eval_obj(n, &xa[0], &obj_value); obj_value *= mkparam(sig); eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { obj_value += g[idx] * mkparam(lam[idx]); } obj_value >>= dummy; trace_off(); rind_L = nullptr; cind_L = nullptr; hessval = nullptr; options_L[0] = 0; options_L[1] = 1; sparse_hess(tag_L, n, 0, &xp[0], &nnz_L, &rind_L, &cind_L, &hessval, options_L); *nnz_h_lag = nnz_L; } //*************** end ADOL-C part *********************************** } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_relax_end_slack_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 */ #include "modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_relax_end_slack_interface.h" // #define ADEBUG AERROR namespace apollo { namespace planning { DistanceApproachIPOPTRelaxEndSlackInterface:: DistanceApproachIPOPTRelaxEndSlackInterface( const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& s_warm_up, const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xf, const Eigen::MatrixXd& last_time_u, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const PlannerOpenSpaceConfig& planner_open_space_config) : ts_(ts), ego_(ego), xWS_(xWS), uWS_(uWS), l_warm_up_(l_warm_up), n_warm_up_(n_warm_up), slack_warm_up_(s_warm_up), x0_(x0), xf_(xf), last_time_u_(last_time_u), XYbounds_(XYbounds), obstacles_edges_num_(obstacles_edges_num), obstacles_A_(obstacles_A), obstacles_b_(obstacles_b) { ACHECK(horizon < std::numeric_limits<int>::max()) << "Invalid cast on horizon in open space planner"; horizon_ = static_cast<int>(horizon); ACHECK(obstacles_num < std::numeric_limits<int>::max()) << "Invalid cast on obstacles_num in open space planner"; // TODO(RHe): use relax slacks from dual warm up // slack_warm_up_ = Eigen::MatrixXd::Zero(obstacles_num, horizon_ + 1); obstacles_num_ = static_cast<int>(obstacles_num); w_ev_ = ego_(1, 0) + ego_(3, 0); l_ev_ = ego_(0, 0) + ego_(2, 0); g_ = {l_ev_ / 2, w_ev_ / 2, l_ev_ / 2, w_ev_ / 2}; offset_ = (ego_(0, 0) + ego_(2, 0)) / 2 - ego_(2, 0); obstacles_edges_sum_ = obstacles_edges_num_.sum(); state_result_ = Eigen::MatrixXd::Zero(4, horizon_ + 1); dual_l_result_ = Eigen::MatrixXd::Zero(obstacles_edges_sum_, horizon_ + 1); dual_n_result_ = Eigen::MatrixXd::Zero(4 * obstacles_num_, horizon_ + 1); slack_result_ = Eigen::MatrixXd::Zero(obstacles_num_, horizon_ + 1); control_result_ = Eigen::MatrixXd::Zero(2, horizon_); time_result_ = Eigen::MatrixXd::Zero(1, horizon_); state_start_index_ = 0; control_start_index_ = 4 * (horizon_ + 1); time_start_index_ = control_start_index_ + 2 * horizon_; l_start_index_ = time_start_index_ + (horizon_ + 1); n_start_index_ = l_start_index_ + obstacles_edges_sum_ * (horizon_ + 1); slack_index_ = n_start_index_ + 4 * obstacles_num_ * (horizon_ + 1); distance_approach_config_ = planner_open_space_config.distance_approach_config(); weight_state_x_ = distance_approach_config_.weight_x(); weight_state_y_ = distance_approach_config_.weight_y(); weight_state_phi_ = distance_approach_config_.weight_phi(); weight_state_v_ = distance_approach_config_.weight_v(); weight_input_steer_ = distance_approach_config_.weight_steer(); weight_input_a_ = distance_approach_config_.weight_a(); weight_rate_steer_ = distance_approach_config_.weight_steer_rate(); weight_rate_a_ = distance_approach_config_.weight_a_rate(); weight_stitching_steer_ = distance_approach_config_.weight_steer_stitching(); weight_stitching_a_ = distance_approach_config_.weight_a_stitching(); weight_first_order_time_ = distance_approach_config_.weight_first_order_time(); weight_second_order_time_ = distance_approach_config_.weight_second_order_time(); weight_end_state_ = distance_approach_config_.weight_end_state(); weight_slack_ = distance_approach_config_.weight_slack(); min_safety_distance_ = distance_approach_config_.min_safety_distance(); max_steer_angle_ = vehicle_param_.max_steer_angle() / vehicle_param_.steer_ratio(); max_speed_forward_ = distance_approach_config_.max_speed_forward(); max_speed_reverse_ = distance_approach_config_.max_speed_reverse(); max_acceleration_forward_ = distance_approach_config_.max_acceleration_forward(); max_acceleration_reverse_ = distance_approach_config_.max_acceleration_reverse(); min_time_sample_scaling_ = distance_approach_config_.min_time_sample_scaling(); max_time_sample_scaling_ = distance_approach_config_.max_time_sample_scaling(); max_steer_rate_ = vehicle_param_.max_steer_angle_rate() / vehicle_param_.steer_ratio(); use_fix_time_ = distance_approach_config_.use_fix_time(); wheelbase_ = vehicle_param_.wheel_base(); enable_constraint_check_ = distance_approach_config_.enable_constraint_check(); enable_jacobian_ad_ = true; } bool DistanceApproachIPOPTRelaxEndSlackInterface::get_nlp_info( int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) { ADEBUG << "get_nlp_info"; // n1 : states variables, 4 * (N+1) int n1 = 4 * (horizon_ + 1); ADEBUG << "n1: " << n1; // n2 : control inputs variables int n2 = 2 * horizon_; ADEBUG << "n2: " << n2; // n3 : sampling time variables int n3 = horizon_ + 1; ADEBUG << "n3: " << n3; // n4 : dual multiplier associated with obstacle shape lambda_horizon_ = obstacles_edges_num_.sum() * (horizon_ + 1); ADEBUG << "lambda_horizon_: " << lambda_horizon_; // n5 : dual multipier associated with car shape, obstacles_num*4 * (N+1) miu_horizon_ = obstacles_num_ * 4 * (horizon_ + 1); ADEBUG << "miu_horizon_: " << miu_horizon_; // n6 : slack variables related to safety min distance slack_horizon_ = obstacles_num_ * (horizon_ + 1); // m1 : dynamics constatins int m1 = 4 * horizon_; // m2 : control rate constraints (only steering) int m2 = horizon_; // m3 : sampling time equality constraints int m3 = horizon_; // m4 : obstacle constraints int m4 = 4 * obstacles_num_ * (horizon_ + 1); num_of_variables_ = n1 + n2 + n3 + lambda_horizon_ + miu_horizon_ + slack_horizon_; num_of_constraints_ = m1 + m2 + m3 + m4 + (num_of_variables_ - (horizon_ + 1) + 2); // number of variables n = num_of_variables_; ADEBUG << "num_of_variables_ " << num_of_variables_; // number of constraints m = num_of_constraints_; ADEBUG << "num_of_constraints_ " << num_of_constraints_; generate_tapes(n, m, &nnz_jac_g, &nnz_h_lag); index_style = IndexStyleEnum::C_STYLE; return true; } bool DistanceApproachIPOPTRelaxEndSlackInterface::get_bounds_info( int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) { ADEBUG << "get_bounds_info"; ACHECK(XYbounds_.size() == 4) << "XYbounds_ size is not 4, but" << XYbounds_.size(); // Variables: includes state, u, sample time and lagrange multipliers // 1. state variables, 4 * [0, horizon] // start point pose int variable_index = 0; for (int i = 0; i < 4; ++i) { x_l[i] = -2e19; x_u[i] = 2e19; } variable_index += 4; // During horizons, 2 ~ N-1 for (int i = 1; i < horizon_; ++i) { // x x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // y x_l[variable_index + 1] = -2e19; x_u[variable_index + 1] = 2e19; // phi x_l[variable_index + 2] = -2e19; x_u[variable_index + 2] = 2e19; // v x_l[variable_index + 3] = -2e19; x_u[variable_index + 3] = 2e19; variable_index += 4; } // end point pose for (int i = 0; i < 4; ++i) { x_l[variable_index + i] = -2e19; x_u[variable_index + i] = 2e19; } variable_index += 4; ADEBUG << "variable_index after adding state variables : " << variable_index; // 2. control variables, 2 * [0, horizon_-1] for (int i = 0; i < horizon_; ++i) { // steer x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // a x_l[variable_index + 1] = -2e19; x_u[variable_index + 1] = 2e19; variable_index += 2; } ADEBUG << "variable_index after adding control variables : " << variable_index; // 3. sampling time variables, 1 * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; ++variable_index; } ADEBUG << "variable_index after adding sample time : " << variable_index; ADEBUG << "sample time fix time status is : " << use_fix_time_; // 4. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0, // horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { x_l[variable_index] = 0.0; x_u[variable_index] = 2e19; // nlp_upper_bound_limit ++variable_index; } } ADEBUG << "variable_index after adding lagrange l : " << variable_index; // 5. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { x_l[variable_index] = 0.0; x_u[variable_index] = 2e19; // nlp_upper_bound_limit ++variable_index; } } ADEBUG << "variable_index after adding lagrange n : " << variable_index; // 6. slack variable constraint s, obstacles_num * (horizon_ + 1) for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { x_l[variable_index] = 0.0; x_u[variable_index] = 2e19; ++variable_index; } } ADEBUG << "variable_index after adding slack s: " << variable_index; // Constraints: includes four state Euler forward constraints, three // Obstacle related constraints // 1. dynamics constraints 4 * [0, horizons-1] int constraint_index = 0; for (int i = 0; i < 4 * horizon_; ++i) { g_l[i] = 0.0; g_u[i] = 0.0; } constraint_index += 4 * horizon_; ADEBUG << "constraint_index after adding Euler forward dynamics constraints: " << constraint_index; // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply // steering rate as of now for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = -max_steer_rate_; g_u[constraint_index] = max_steer_rate_; ++constraint_index; } ADEBUG << "constraint_index after adding steering rate constraints: " << constraint_index; // 3. Time constraints 1 * [0, horizons-1] for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 0.0; ++constraint_index; } ADEBUG << "constraint_index after adding time constraints: " << constraint_index; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { // a. norm(A'*lambda) <= 1 g_l[constraint_index] = -2e19; g_u[constraint_index] = 1.0; // b. G'*mu + R'*A*lambda = 0 g_l[constraint_index + 1] = 0.0; g_u[constraint_index + 1] = 0.0; g_l[constraint_index + 2] = 0.0; g_u[constraint_index + 2] = 0.0; // c. -g'*mu + (A*t - b)*lambda + s > 0 g_l[constraint_index + 3] = 0.0; g_u[constraint_index + 3] = 2e19; // nlp_upper_bound_limit constraint_index += 4; } } // 5. load variable bounds as constraints // start configuration g_l[constraint_index] = x0_(0, 0); g_u[constraint_index] = x0_(0, 0); g_l[constraint_index + 1] = x0_(1, 0); g_u[constraint_index + 1] = x0_(1, 0); g_l[constraint_index + 2] = x0_(2, 0); g_u[constraint_index + 2] = x0_(2, 0); g_l[constraint_index + 3] = x0_(3, 0); g_u[constraint_index + 3] = x0_(3, 0); constraint_index += 4; for (int i = 1; i < horizon_; ++i) { g_l[constraint_index] = XYbounds_[0]; g_u[constraint_index] = XYbounds_[1]; g_l[constraint_index + 1] = XYbounds_[2]; g_u[constraint_index + 1] = XYbounds_[3]; g_l[constraint_index + 2] = -max_speed_reverse_; g_u[constraint_index + 2] = max_speed_forward_; constraint_index += 3; } // end configuration g_l[constraint_index] = -2e19; g_u[constraint_index] = 2e19; g_l[constraint_index + 1] = -2e19; g_u[constraint_index + 1] = 2e19; g_l[constraint_index + 2] = -2e19; g_u[constraint_index + 2] = 2e19; g_l[constraint_index + 3] = -2e19; g_u[constraint_index + 3] = 2e19; constraint_index += 4; for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = -max_steer_angle_; g_u[constraint_index] = max_steer_angle_; g_l[constraint_index + 1] = -max_acceleration_reverse_; g_u[constraint_index + 1] = max_acceleration_forward_; constraint_index += 2; } for (int i = 0; i < horizon_ + 1; ++i) { if (!use_fix_time_) { g_l[constraint_index] = min_time_sample_scaling_; g_u[constraint_index] = max_time_sample_scaling_; } else { g_l[constraint_index] = 1.0; g_u[constraint_index] = 1.0; } constraint_index++; } for (int i = 0; i < lambda_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; } for (int i = 0; i < miu_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; } for (int i = 0; i < slack_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; ++constraint_index; } ADEBUG << "constraint_index after adding obstacles constraints: " << constraint_index; ADEBUG << "get_bounds_info_ out"; return true; } bool DistanceApproachIPOPTRelaxEndSlackInterface::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) { ADEBUG << "get_starting_point"; ACHECK(init_x) << "Warm start init_x setting failed"; CHECK_EQ(horizon_, uWS_.cols()); CHECK_EQ(horizon_ + 1, xWS_.cols()); // 1. state variables 4 * (horizon_ + 1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * 4; for (int j = 0; j < 4; ++j) { x[index + j] = xWS_(j, i); } } // 2. control variable initialization, 2 * horizon_ for (int i = 0; i < horizon_; ++i) { int index = i * 2; x[control_start_index_ + index] = uWS_(0, i); x[control_start_index_ + index + 1] = uWS_(1, i); } // 2. time scale variable initialization, horizon_ + 1 for (int i = 0; i < horizon_ + 1; ++i) { x[time_start_index_ + i] = 0.5 * (min_time_sample_scaling_ + max_time_sample_scaling_); } // 3. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * obstacles_edges_sum_; for (int j = 0; j < obstacles_edges_sum_; ++j) { x[l_start_index_ + index + j] = l_warm_up_(j, i); } } // 4. lagrange constraint m, 4*obstacles_num * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * 4 * obstacles_num_; for (int j = 0; j < 4 * obstacles_num_; ++j) { x[n_start_index_ + index + j] = n_warm_up_(j, i); } } // 5. slack constraint s, obstacle_num * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * obstacles_num_; for (int j = 0; j < obstacles_num_; ++j) { x[slack_index_ + index + j] = slack_warm_up_(j, i); } } ADEBUG << "get_starting_point out"; return true; } bool DistanceApproachIPOPTRelaxEndSlackInterface::eval_f(int n, const double* x, bool new_x, double& obj_value) { eval_obj(n, x, &obj_value); return true; } bool DistanceApproachIPOPTRelaxEndSlackInterface::eval_grad_f(int n, const double* x, bool new_x, double* grad_f) { gradient(tag_f, n, x, grad_f); return true; } bool DistanceApproachIPOPTRelaxEndSlackInterface::eval_g(int n, const double* x, bool new_x, int m, double* g) { eval_constraints(n, x, m, g); // if (enable_constraint_check_) check_g(n, x, m, g); return true; } bool DistanceApproachIPOPTRelaxEndSlackInterface::eval_jac_g( int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { if (enable_jacobian_ad_) { if (values == nullptr) { // return the structure of the jacobian for (int idx = 0; idx < nnz_jac; idx++) { iRow[idx] = rind_g[idx]; jCol[idx] = cind_g[idx]; } } else { // return the values of the jacobian of the constraints sparse_jac(tag_g, m, n, 1, x, &nnz_jac, &rind_g, &cind_g, &jacval, options_g); for (int idx = 0; idx < nnz_jac; idx++) { values[idx] = jacval[idx]; } } return true; } else { return eval_jac_g_ser(n, x, new_x, m, nele_jac, iRow, jCol, values); } } bool DistanceApproachIPOPTRelaxEndSlackInterface::eval_jac_g_ser( int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { AERROR << "NOT READY"; return false; } bool DistanceApproachIPOPTRelaxEndSlackInterface::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) { // return the structure. This is a symmetric matrix, fill the lower left // triangle only. for (int idx = 0; idx < nnz_L; idx++) { iRow[idx] = rind_L[idx]; jCol[idx] = cind_L[idx]; } } else { // return the values. This is a symmetric matrix, fill the lower left // triangle only obj_lam[0] = obj_factor; for (int idx = 0; idx < m; idx++) { obj_lam[1 + idx] = lambda[idx]; } set_param_vec(tag_L, m + 1, obj_lam); sparse_hess(tag_L, n, 1, const_cast<double*>(x), &nnz_L, &rind_L, &cind_L, &hessval, options_L); for (int idx = 0; idx < nnz_L; idx++) { values[idx] = hessval[idx]; } } return true; } void DistanceApproachIPOPTRelaxEndSlackInterface::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) { int state_index = state_start_index_; int control_index = control_start_index_; int time_index = time_start_index_; int dual_l_index = l_start_index_; int dual_n_index = n_start_index_; int slack_index = slack_index_; // enable_constraint_check_: for debug only if (enable_constraint_check_) { ADEBUG << "final resolution constraint checking"; check_g(n, x, m, g); } // 1. state variables, 4 * [0, horizon] // 2. control variables, 2 * [0, horizon_-1] // 3. sampling time variables, 1 * [0, horizon_] // 4. dual_l, obstacles_edges_sum_ * [0, horizon] // 5. dual_n, obstacles_num * [0, horizon] // 6. slack_, obstacles_num * [0, horizon] for (int i = 0; i < horizon_; ++i) { state_result_(0, i) = x[state_index]; state_result_(1, i) = x[state_index + 1]; state_result_(2, i) = x[state_index + 2]; state_result_(3, i) = x[state_index + 3]; control_result_(0, i) = x[control_index]; control_result_(1, i) = x[control_index + 1]; time_result_(0, i) = ts_ * x[time_index]; for (int j = 0; j < obstacles_edges_sum_; ++j) { dual_l_result_(j, i) = x[dual_l_index + j]; } for (int k = 0; k < 4 * obstacles_num_; ++k) { dual_n_result_(k, i) = x[dual_n_index + k]; } for (int l = 0; l < obstacles_num_; ++l) { slack_result_(l, i) = x[slack_index + l]; } state_index += 4; control_index += 2; time_index++; dual_l_index += obstacles_edges_sum_; dual_n_index += 4 * obstacles_num_; slack_index += obstacles_num_; } state_result_(0, 0) = x0_(0, 0); state_result_(1, 0) = x0_(1, 0); state_result_(2, 0) = x0_(2, 0); state_result_(3, 0) = x0_(3, 0); // push back last horizon for states state_result_(0, horizon_) = xf_(0, 0); state_result_(1, horizon_) = xf_(1, 0); state_result_(2, horizon_) = xf_(2, 0); state_result_(3, horizon_) = xf_(3, 0); for (int j = 0; j < obstacles_edges_sum_; ++j) { dual_l_result_(j, horizon_) = x[dual_l_index + j]; } for (int k = 0; k < 4 * obstacles_num_; ++k) { dual_n_result_(k, horizon_) = x[dual_n_index + k]; } for (int l = 0; l < obstacles_num_; ++l) { slack_result_(l, horizon_) = x[slack_index + l]; } // memory deallocation of ADOL-C variables delete[] obj_lam; if (enable_jacobian_ad_) { free(rind_g); free(cind_g); free(jacval); } free(rind_L); free(cind_L); free(hessval); } void DistanceApproachIPOPTRelaxEndSlackInterface::get_optimization_results( Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) const { // TODO(RHe): extract slack variables for further study ADEBUG << "get_optimization_results"; *state_result = state_result_; *control_result = control_result_; *time_result = time_result_; *dual_l_result = dual_l_result_; *dual_n_result = dual_n_result_; if (!distance_approach_config_.enable_initial_final_check()) { return; } CHECK_EQ(state_result_.cols(), xWS_.cols()); CHECK_EQ(state_result_.rows(), xWS_.rows()); double state_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4; ++j) { state_diff_max = std::max(std::abs(xWS_(j, i) - state_result_(j, i)), state_diff_max); } } // 2. control variable initialization, 2 * horizon_ CHECK_EQ(control_result_.cols(), uWS_.cols()); CHECK_EQ(control_result_.rows(), uWS_.rows()); double control_diff_max = 0.0; for (int i = 0; i < horizon_; ++i) { control_diff_max = std::max(std::abs(uWS_(0, i) - control_result_(0, i)), control_diff_max); control_diff_max = std::max(std::abs(uWS_(1, i) - control_result_(1, i)), control_diff_max); } // 2. time scale variable initialization, horizon_ + 1 // 3. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1) CHECK_EQ(dual_l_result_.cols(), l_warm_up_.cols()); CHECK_EQ(dual_l_result_.rows(), l_warm_up_.rows()); double l_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { l_diff_max = std::max(std::abs(l_warm_up_(j, i) - dual_l_result_(j, i)), l_diff_max); } } // 4. lagrange constraint m, 4*obstacles_num * (horizon_+1) CHECK_EQ(n_warm_up_.cols(), dual_n_result_.cols()); CHECK_EQ(n_warm_up_.rows(), dual_n_result_.rows()); double n_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { n_diff_max = std::max(std::abs(n_warm_up_(j, i) - dual_n_result_(j, i)), n_diff_max); } } ADEBUG << "state_diff_max: " << state_diff_max; ADEBUG << "control_diff_max: " << control_diff_max; ADEBUG << "dual_l_diff_max: " << l_diff_max; ADEBUG << "dual_n_diff_max: " << n_diff_max; } //*************** start ADOL-C part *********************************** template <class T> void DistanceApproachIPOPTRelaxEndSlackInterface::eval_obj(int n, const T* x, T* obj_value) { // Objective is : // min control inputs // min input rate // min time (if the time step is not fixed) // regularization wrt warm start trajectory DCHECK(ts_ != 0) << "ts in distance_approach_ is 0"; int control_index = control_start_index_; int time_index = time_start_index_; int state_index = state_start_index_; // TODO(QiL): Initial implementation towards earlier understanding and debug // purpose, later code refine towards improving efficiency *obj_value = 0.0; // 1. objective to minimize state diff to warm up for (int i = 0; i < horizon_ + 1; ++i) { T x1_diff = x[state_index] - xWS_(0, i); T x2_diff = x[state_index + 1] - xWS_(1, i); T x3_diff = x[state_index + 2] - xWS_(2, i); T x4_abs = x[state_index + 3]; *obj_value += weight_state_x_ * x1_diff * x1_diff + weight_state_y_ * x2_diff * x2_diff + weight_state_phi_ * x3_diff * x3_diff + weight_state_v_ * x4_abs * x4_abs; state_index += 4; } // 2. objective to minimize u square for (int i = 0; i < horizon_; ++i) { *obj_value += weight_input_steer_ * x[control_index] * x[control_index] + weight_input_a_ * x[control_index + 1] * x[control_index + 1]; control_index += 2; } // 3. objective to minimize input change rate for first horizon control_index = control_start_index_; T last_time_steer_rate = (x[control_index] - last_time_u_(0, 0)) / x[time_index] / ts_; T last_time_a_rate = (x[control_index + 1] - last_time_u_(1, 0)) / x[time_index] / ts_; *obj_value += weight_stitching_steer_ * last_time_steer_rate * last_time_steer_rate + weight_stitching_a_ * last_time_a_rate * last_time_a_rate; // 4. objective to minimize input change rates, [0- horizon_ -2] time_index++; for (int i = 0; i < horizon_ - 1; ++i) { T steering_rate = (x[control_index + 2] - x[control_index]) / x[time_index] / ts_; T a_rate = (x[control_index + 3] - x[control_index + 1]) / x[time_index] / ts_; *obj_value += weight_rate_steer_ * steering_rate * steering_rate + weight_rate_a_ * a_rate * a_rate; control_index += 2; time_index++; } // 5. objective to minimize total time [0, horizon_] time_index = time_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { T first_order_penalty = weight_first_order_time_ * x[time_index]; T second_order_penalty = weight_second_order_time_ * x[time_index] * x[time_index]; *obj_value += first_order_penalty + second_order_penalty; time_index++; } // 6. end state constraints for (int i = 0; i < 4; ++i) { *obj_value += weight_end_state_ * (x[state_start_index_ + 4 * horizon_ + i] - xf_(i, 0)) * (x[state_start_index_ + 4 * horizon_ + i] - xf_(i, 0)); } // 7. slack variables for (int i = 0; i < slack_horizon_; ++i) { *obj_value += weight_slack_ * x[slack_index_ + i]; } } template <class T> void DistanceApproachIPOPTRelaxEndSlackInterface::eval_constraints(int n, const T* x, int m, T* g) { // state start index int state_index = state_start_index_; // control start index. int control_index = control_start_index_; // time start index int time_index = time_start_index_; int constraint_index = 0; // 1. state constraints 4 * [0, horizons-1] for (int i = 0; i < horizon_; ++i) { // x1 g[constraint_index] = x[state_index + 4] - (x[state_index] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * cos(x[state_index + 2] + ts_ * x[time_index] * 0.5 * x[state_index + 3] * tan(x[control_index]) / wheelbase_)); // x2 g[constraint_index + 1] = x[state_index + 5] - (x[state_index + 1] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * sin(x[state_index + 2] + ts_ * x[time_index] * 0.5 * x[state_index + 3] * tan(x[control_index]) / wheelbase_)); // x3 g[constraint_index + 2] = x[state_index + 6] - (x[state_index + 2] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * tan(x[control_index]) / wheelbase_); // x4 g[constraint_index + 3] = x[state_index + 7] - (x[state_index + 3] + ts_ * x[time_index] * x[control_index + 1]); control_index += 2; constraint_index += 4; time_index++; state_index += 4; } ADEBUG << "constraint_index after adding Euler forward dynamics constraints " "updated: " << constraint_index; // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply // steering rate as of now control_index = control_start_index_; time_index = time_start_index_; // First rate is compare first with stitch point g[constraint_index] = (x[control_index] - last_time_u_(0, 0)) / x[time_index] / ts_; control_index += 2; constraint_index++; time_index++; for (int i = 1; i < horizon_; ++i) { g[constraint_index] = (x[control_index] - x[control_index - 2]) / x[time_index] / ts_; constraint_index++; control_index += 2; time_index++; } // 3. Time constraints 1 * [0, horizons-1] time_index = time_start_index_; for (int i = 0; i < horizon_; ++i) { g[constraint_index] = x[time_index + 1] - x[time_index]; constraint_index++; time_index++; } ADEBUG << "constraint_index after adding time constraints " "updated: " << constraint_index; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 state_index = state_start_index_; int l_index = l_start_index_; int n_index = n_start_index_; int s_index = slack_index_; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); // norm(A* lambda) <= 1 T tmp1 = 0.0; T tmp2 = 0.0; for (int k = 0; k < current_edges_num; ++k) { // TODO(QiL) : replace this one directly with x tmp1 += Aj(k, 0) * x[l_index + k]; tmp2 += Aj(k, 1) * x[l_index + k]; } g[constraint_index] = tmp1 * tmp1 + tmp2 * tmp2; // G' * mu + R' * lambda == 0 g[constraint_index + 1] = x[n_index] - x[n_index + 2] + cos(x[state_index + 2]) * tmp1 + sin(x[state_index + 2]) * tmp2; g[constraint_index + 2] = x[n_index + 1] - x[n_index + 3] - sin(x[state_index + 2]) * tmp1 + cos(x[state_index + 2]) * tmp2; // -g'*mu + (A*t - b)*lambda + d > 0 T tmp3 = 0.0; for (int k = 0; k < 4; ++k) { tmp3 += -g_[k] * x[n_index + k]; } T tmp4 = 0.0; for (int k = 0; k < current_edges_num; ++k) { tmp4 += bj(k, 0) * x[l_index + k]; } g[constraint_index + 3] = tmp3 + (x[state_index] + cos(x[state_index + 2]) * offset_) * tmp1 + (x[state_index + 1] + sin(x[state_index + 2]) * offset_) * tmp2 - tmp4 + x[s_index]; // Update index edges_counter += current_edges_num; l_index += current_edges_num; n_index += 4; constraint_index += 4; ++s_index; } state_index += 4; } ADEBUG << "constraint_index after obstacles avoidance constraints " "updated: " << constraint_index; // 5. load variable bounds as constraints state_index = state_start_index_; control_index = control_start_index_; time_index = time_start_index_; l_index = l_start_index_; n_index = n_start_index_; s_index = slack_index_; // start configuration g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 2]; g[constraint_index + 3] = x[state_index + 3]; constraint_index += 4; state_index += 4; // constraints on x,y,v for (int i = 1; i < horizon_; ++i) { g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 3]; constraint_index += 3; state_index += 4; } // end configuration g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 2]; g[constraint_index + 3] = x[state_index + 3]; constraint_index += 4; state_index += 4; for (int i = 0; i < horizon_; ++i) { g[constraint_index] = x[control_index]; g[constraint_index + 1] = x[control_index + 1]; constraint_index += 2; control_index += 2; } for (int i = 0; i < horizon_ + 1; ++i) { g[constraint_index] = x[time_index]; ++constraint_index; ++time_index; } for (int i = 0; i < lambda_horizon_; ++i) { g[constraint_index] = x[l_index]; ++constraint_index; ++l_index; } for (int i = 0; i < miu_horizon_; ++i) { g[constraint_index] = x[n_index]; ++constraint_index; ++n_index; } for (int i = 0; i < slack_horizon_; ++i) { g[constraint_index] = x[s_index]; ++constraint_index; ++s_index; } } bool DistanceApproachIPOPTRelaxEndSlackInterface::check_g(int n, const double* x, int m, const double* g) { int kN = n; int kM = m; double x_u_tmp[kN]; double x_l_tmp[kN]; double g_u_tmp[kM]; double g_l_tmp[kM]; get_bounds_info(n, x_l_tmp, x_u_tmp, m, g_l_tmp, g_u_tmp); const double delta_v = 1e-4; for (int idx = 0; idx < n; ++idx) { x_u_tmp[idx] = x_u_tmp[idx] + delta_v; x_l_tmp[idx] = x_l_tmp[idx] - delta_v; if (x[idx] > x_u_tmp[idx] || x[idx] < x_l_tmp[idx]) { AINFO << "x idx unfeasible: " << idx << ", x: " << x[idx] << ", lower: " << x_l_tmp[idx] << ", upper: " << x_u_tmp[idx]; } } // m1 : dynamics constatins int m1 = 4 * horizon_; // m2 : control rate constraints (only steering) int m2 = m1 + horizon_; // m3 : sampling time equality constraints int m3 = m2 + horizon_; // m4 : obstacle constraints int m4 = m3 + 4 * obstacles_num_ * (horizon_ + 1); // 5. load variable bounds as constraints // start configuration int m5 = m4 + 3 + 1; // constraints on x,y,v int m6 = m5 + 3 * (horizon_ - 1); // end configuration int m7 = m6 + 3 + 1; // control variable bnd int m8 = m7 + 2 * horizon_; // time interval variable bnd int m9 = m8 + (horizon_ + 1); // lambda_horizon_ int m10 = m9 + lambda_horizon_; // miu_horizon_ int m11 = m10 + miu_horizon_; // slack_horizon_ int m12 = m11 + slack_horizon_; CHECK_EQ(m12, num_of_constraints_); AINFO << "dynamics constatins to: " << m1; AINFO << "control rate constraints (only steering) to: " << m2; AINFO << "sampling time equality constraints to: " << m3; AINFO << "obstacle constraints to: " << m4; AINFO << "start conf constraints to: " << m5; AINFO << "constraints on x,y,v to: " << m6; AINFO << "end constraints to: " << m7; AINFO << "control bnd to: " << m8; AINFO << "time interval constraints to: " << m9; AINFO << "lambda constraints to: " << m10; AINFO << "miu constraints to: " << m11; AINFO << "slack constraint to: " << m12; AINFO << "total constraints: " << num_of_constraints_; for (int idx = 0; idx < m; ++idx) { if (g[idx] > g_u_tmp[idx] + delta_v || g[idx] < g_l_tmp[idx] - delta_v) { AINFO << "constratins idx unfeasible: " << idx << ", g: " << g[idx] << ", lower: " << g_l_tmp[idx] << ", upper: " << g_u_tmp[idx]; } } return true; } void DistanceApproachIPOPTRelaxEndSlackInterface::generate_tapes( int n, int m, int* nnz_jac_g, int* nnz_h_lag) { std::vector<double> xp(n); std::vector<double> lamp(m); std::vector<double> zl(m); std::vector<double> zu(m); std::vector<adouble> xa(n); std::vector<adouble> g(m); std::vector<double> lam(m); double sig; adouble obj_value; double dummy = 0.0; obj_lam = new double[m + 1]; get_starting_point(n, 1, &xp[0], 0, &zl[0], &zu[0], m, 0, &lamp[0]); trace_on(tag_f); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_obj(n, &xa[0], &obj_value); obj_value >>= dummy; trace_off(); trace_on(tag_g); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { g[idx] >>= dummy; } trace_off(); trace_on(tag_L); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } for (int idx = 0; idx < m; idx++) { lam[idx] = 1.0; } sig = 1.0; eval_obj(n, &xa[0], &obj_value); obj_value *= mkparam(sig); eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { obj_value += g[idx] * mkparam(lam[idx]); } obj_value >>= dummy; trace_off(); if (enable_jacobian_ad_) { rind_g = nullptr; cind_g = nullptr; jacval = nullptr; options_g[0] = 0; /* sparsity pattern by index domains (default) */ options_g[1] = 0; /* safe mode (default) */ options_g[2] = 0; options_g[3] = 0; /* column compression (default) */ sparse_jac(tag_g, m, n, 0, &xp[0], &nnz_jac, &rind_g, &cind_g, &jacval, options_g); *nnz_jac_g = nnz_jac; } rind_L = nullptr; cind_L = nullptr; hessval = nullptr; options_L[0] = 0; options_L[1] = 1; sparse_hess(tag_L, n, 0, &xp[0], &nnz_L, &rind_L, &cind_L, &hessval, options_L); *nnz_h_lag = nnz_L; } //*************** end ADOL-C part *********************************** } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_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 */ #pragma once #include <adolc/adolc.h> #include <adolc/adolc_openmp.h> #include <adolc/adolc_sparse.h> #include <adolc/adouble.h> #include <omp.h> #include <coin/IpTNLP.hpp> #include <coin/IpTypes.hpp> #include "Eigen/Dense" #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/proto/planner_open_space_config.pb.h" #define tag_f 1 #define tag_g 2 #define tag_L 3 #define HPOFF 30 namespace apollo { namespace planning { class DistanceApproachInterface : public Ipopt::TNLP { public: virtual ~DistanceApproachInterface() = default; /** Method to return some info about the nlp */ virtual bool get_nlp_info(int& n, int& m, int& nnz_jac_g, // NOLINT int& nnz_h_lag, // NOLINT IndexStyleEnum& index_style) = 0; // NOLINT /** Method to return the bounds for my problem */ virtual bool get_bounds_info(int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) = 0; /** Method to return the starting point for the algorithm */ virtual 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) = 0; /** Method to return the objective value */ virtual bool eval_f(int n, const double* x, bool new_x, // NOLINT double& obj_value) = 0; // NOLINT /** Method to return the gradient of the objective */ virtual bool eval_grad_f(int n, const double* x, bool new_x, double* grad_f) = 0; /** Method to return the constraint residuals */ virtual bool eval_g(int n, const double* x, bool new_x, int m, double* g) = 0; /** Check unfeasible constraints for further study**/ virtual bool check_g(int n, const double* x, int m, const double* g) = 0; /** Method to return: * 1) The structure of the jacobian (if "values" is nullptr) * 2) The values of the jacobian (if "values" is not nullptr) */ virtual bool eval_jac_g(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) = 0; // sequential implementation to jac_g virtual bool eval_jac_g_ser(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) = 0; /** 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) */ virtual 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) = 0; /** @name Solution Methods */ /** This method is called when the algorithm is complete so the TNLP can * store/write the solution */ virtual 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) = 0; virtual void get_optimization_results( Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) const = 0; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_slack_osqp_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 */ #pragma once #include <limits> #include <vector> #include "Eigen/Dense" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/planning/proto/planner_open_space_config.pb.h" #include "osqp/osqp.h" namespace apollo { namespace planning { class DualVariableWarmStartSlackOSQPInterface { public: DualVariableWarmStartSlackOSQPInterface( size_t horizon, double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const Eigen::MatrixXd& xWS, const PlannerOpenSpaceConfig& planner_open_space_config); virtual ~DualVariableWarmStartSlackOSQPInterface() = default; void get_optimization_results(Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up, Eigen::MatrixXd* s_warm_up) const; bool optimize(); void assembleP(std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr); void assembleConstraint(std::vector<c_float>* A_data, std::vector<c_int>* A_indices, std::vector<c_int>* A_indptr); void assembleA(const int r, const int c, const std::vector<c_float>& P_data, const std::vector<c_int>& P_indices, const std::vector<c_int>& P_indptr); void checkSolution(const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up); void printMatrix(const int r, const int c, const std::vector<c_float>& P_data, const std::vector<c_int>& P_indices, const std::vector<c_int>& P_indptr); private: OSQPConfig osqp_config_; int num_of_variables_; int num_of_constraints_; int horizon_; double ts_; Eigen::MatrixXd ego_; int lambda_horizon_ = 0; int miu_horizon_ = 0; int slack_horizon_ = 0; double beta_ = 0.0; Eigen::MatrixXd l_warm_up_; Eigen::MatrixXd n_warm_up_; Eigen::MatrixXd slacks_; double wheelbase_; double w_ev_; double l_ev_; std::vector<double> g_; double offset_; Eigen::MatrixXi obstacles_edges_num_; int obstacles_num_; int obstacles_edges_sum_; double min_safety_distance_; // lagrangian l start index int l_start_index_ = 0; // lagrangian n start index int n_start_index_ = 0; // slack s start index int s_start_index_ = 0; // obstacles_A Eigen::MatrixXd obstacles_A_; // obstacles_b Eigen::MatrixXd obstacles_b_; // states of warm up stage Eigen::MatrixXd xWS_; // constraint A matrix in eigen format Eigen::MatrixXf constraint_A_; bool check_mode_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_osqp_interface.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/open_space/trajectory_smoother/dual_variable_warm_start_osqp_interface.h" #include "cyber/common/log.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { DualVariableWarmStartOSQPInterface::DualVariableWarmStartOSQPInterface( size_t horizon, double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const Eigen::MatrixXd& xWS, const PlannerOpenSpaceConfig& planner_open_space_config) : ts_(ts), ego_(ego), obstacles_edges_num_(obstacles_edges_num), obstacles_A_(obstacles_A), obstacles_b_(obstacles_b), xWS_(xWS) { ACHECK(horizon < std::numeric_limits<int>::max()) << "Invalid cast on horizon in open space planner"; horizon_ = static_cast<int>(horizon); ACHECK(obstacles_num < std::numeric_limits<int>::max()) << "Invalid cast on obstacles_num in open space planner"; obstacles_num_ = static_cast<int>(obstacles_num); w_ev_ = ego_(1, 0) + ego_(3, 0); l_ev_ = ego_(0, 0) + ego_(2, 0); g_ = {l_ev_ / 2, w_ev_ / 2, l_ev_ / 2, w_ev_ / 2}; offset_ = (ego_(0, 0) + ego_(2, 0)) / 2 - ego_(2, 0); obstacles_edges_sum_ = obstacles_edges_num_.sum(); l_start_index_ = 0; n_start_index_ = l_start_index_ + obstacles_edges_sum_ * (horizon_ + 1); l_warm_up_ = Eigen::MatrixXd::Zero(obstacles_edges_sum_, horizon_ + 1); n_warm_up_ = Eigen::MatrixXd::Zero(4 * obstacles_num_, horizon_ + 1); // get_nlp_info lambda_horizon_ = obstacles_edges_sum_ * (horizon_ + 1); miu_horizon_ = obstacles_num_ * 4 * (horizon_ + 1); // number of variables num_of_variables_ = lambda_horizon_ + miu_horizon_; // number of constraints num_of_constraints_ = 3 * obstacles_num_ * (horizon_ + 1) + num_of_variables_; min_safety_distance_ = planner_open_space_config.dual_variable_warm_start_config() .min_safety_distance(); check_mode_ = planner_open_space_config.dual_variable_warm_start_config().debug_osqp(); osqp_config_ = planner_open_space_config.dual_variable_warm_start_config().osqp_config(); } void printMatrix(const int r, const int c, const std::vector<c_float>& P_data, const std::vector<c_int>& P_indices, const std::vector<c_int>& P_indptr) { Eigen::MatrixXf tmp = Eigen::MatrixXf::Zero(r, c); for (size_t i = 0; i < P_indptr.size() - 1; ++i) { if (P_indptr[i] < 0 || P_indptr[i] >= static_cast<int>(P_indices.size())) { continue; } for (auto idx = P_indptr[i]; idx < P_indptr[i + 1]; ++idx) { int tmp_c = static_cast<int>(i); int tmp_r = static_cast<int>(P_indices[idx]); tmp(tmp_r, tmp_c) = static_cast<float>(P_data[idx]); } } AINFO << "row number: " << r; AINFO << "col number: " << c; for (int i = 0; i < r; ++i) { AINFO << "row number: " << i; AINFO << tmp.row(i); } } void DualVariableWarmStartOSQPInterface::assembleA( const int r, const int c, const std::vector<c_float>& P_data, const std::vector<c_int>& P_indices, const std::vector<c_int>& P_indptr) { constraint_A_ = Eigen::MatrixXf::Zero(r, c); for (size_t i = 0; i < P_indptr.size() - 1; ++i) { if (P_indptr[i] < 0 || P_indptr[i] >= static_cast<int>(P_indices.size())) { continue; } for (auto idx = P_indptr[i]; idx < P_indptr[i + 1]; ++idx) { int tmp_c = static_cast<int>(i); int tmp_r = static_cast<int>(P_indices[idx]); constraint_A_(tmp_r, tmp_c) = static_cast<float>(P_data[idx]); } } } bool DualVariableWarmStartOSQPInterface::optimize() { int kNumParam = num_of_variables_; int kNumConst = num_of_constraints_; bool succ = true; // assemble P, quadratic term in objective std::vector<c_float> P_data; std::vector<c_int> P_indices; std::vector<c_int> P_indptr; assemble_P(&P_data, &P_indices, &P_indptr); if (check_mode_) { AINFO << "print P_data in whole: "; printMatrix(kNumParam, kNumParam, P_data, P_indices, P_indptr); } // assemble q, linear term in objective c_float q[kNumParam]; for (int i = 0; i < kNumParam; ++i) { q[i] = 0.0; } // assemble A, linear term in constraints std::vector<c_float> A_data; std::vector<c_int> A_indices; std::vector<c_int> A_indptr; assemble_constraint(&A_data, &A_indices, &A_indptr); if (check_mode_) { AINFO << "print A_data in whole: "; printMatrix(kNumConst, kNumParam, A_data, A_indices, A_indptr); assembleA(kNumConst, kNumParam, A_data, A_indices, A_indptr); } // assemble lb & ub c_float lb[kNumConst]; c_float ub[kNumConst]; for (int i = 0; i < kNumConst; ++i) { lb[i] = 0.0; if (i >= 2 * obstacles_num_ * (horizon_ + 1) && i < 3 * obstacles_num_ * (horizon_ + 1)) { lb[i] = min_safety_distance_; } if (i < 2 * obstacles_num_ * (horizon_ + 1)) { ub[i] = 0.0; } else { ub[i] = 2e19; } } // Problem settings OSQPSettings* settings = reinterpret_cast<OSQPSettings*>(c_malloc(sizeof(OSQPSettings))); // Define Solver settings as default osqp_set_default_settings(settings); settings->alpha = osqp_config_.alpha(); // Change alpha parameter settings->eps_abs = osqp_config_.eps_abs(); settings->eps_rel = osqp_config_.eps_rel(); settings->max_iter = osqp_config_.max_iter(); settings->polish = osqp_config_.polish(); settings->verbose = osqp_config_.osqp_debug_log(); // Populate data OSQPData* data = reinterpret_cast<OSQPData*>(c_malloc(sizeof(OSQPData))); data->n = kNumParam; data->m = kNumConst; data->P = csc_matrix(data->n, data->n, P_data.size(), P_data.data(), P_indices.data(), P_indptr.data()); data->q = q; data->A = csc_matrix(data->m, data->n, A_data.size(), A_data.data(), A_indices.data(), A_indptr.data()); data->l = lb; data->u = ub; // Workspace OSQPWorkspace* work = nullptr; // osqp_setup(&work, data, settings); work = osqp_setup(data, settings); // Solve Problem osqp_solve(work); // check state if (work->info->status_val != 1 && work->info->status_val != 2) { AWARN << "OSQP dual warm up unsuccess, " << "return status: " << work->info->status; succ = false; } // extract primal results int variable_index = 0; // 1. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0, // horizon_l for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { l_warm_up_(j, i) = work->solution->x[variable_index]; ++variable_index; } } // 2. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { n_warm_up_(j, i) = work->solution->x[variable_index]; ++variable_index; } } succ = succ & (work->info->obj_val <= 1.0); // Cleanup osqp_cleanup(work); c_free(data->A); c_free(data->P); c_free(data); c_free(settings); return succ; } void DualVariableWarmStartOSQPInterface::check_solution( const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up) { Eigen::MatrixXf x(num_of_variables_, 1); Eigen::MatrixXf g(num_of_constraints_, 1); // extract primal results int variable_index = 0; // 1. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0, // horizon_l for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { x(variable_index, 0) = static_cast<float>(l_warm_up(j, i)); ++variable_index; } } // 2. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { x(variable_index, 0) = static_cast<float>(n_warm_up(j, i)); ++variable_index; } } g = constraint_A_ * x; int r1_index = 0; int r2_index = 2 * obstacles_num_ * (horizon_ + 1); int r3_index = 3 * obstacles_num_ * (horizon_ + 1); int r4_index = 3 * obstacles_num_ * (horizon_ + 1) + lambda_horizon_; for (int idx = r1_index; idx < r2_index; ++idx) { if (std::abs(g(idx, 0)) > 1e-6) { AERROR << "G' * mu + R' * A * lambda == 0 constraint fails, " << "constraint_index: " << idx << ", g: " << g(idx, 0); } } for (int idx = r2_index; idx < r3_index; ++idx) { if (g(idx, 0) < min_safety_distance_) { AERROR << "-g' * mu + (A * t - b) * lambda) >= d_min constraint fails, " << "constraint_index: " << idx << ", g: " << g(idx, 0); } } for (int idx = r3_index; idx < r4_index; ++idx) { if (g(idx, 0) < 0) { AERROR << "lambda box constraint fails, " << "constraint_index: " << idx << ", g: " << g(idx, 0); } } for (int idx = r4_index; idx < num_of_constraints_; ++idx) { if (g(idx, 0) < 0) { AERROR << "miu box constraint fails, " << "constraint_index: " << idx << ", g: " << g(idx, 0); } } } void DualVariableWarmStartOSQPInterface::assemble_P( std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr) { // the objective function is norm(A' * lambda) std::vector<c_float> P_tmp; int edges_counter = 0; for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj; Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); // Eigen::MatrixXd AAj(current_edges_num, current_edges_num); Aj = Aj * Aj.transpose(); CHECK_EQ(current_edges_num, Aj.cols()); CHECK_EQ(current_edges_num, Aj.rows()); for (int c = 0; c < current_edges_num; ++c) { for (int r = 0; r < current_edges_num; ++r) { P_tmp.emplace_back(Aj(r, c)); } } // Update index edges_counter += current_edges_num; } int l_index = l_start_index_; int first_row_location = 0; // the objective function is norm(A' * lambda) for (int i = 0; i < horizon_ + 1; ++i) { edges_counter = 0; for (auto item : P_tmp) { P_data->emplace_back(item); } // current assume: stationary obstacles for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); for (int c = 0; c < current_edges_num; ++c) { P_indptr->emplace_back(first_row_location); for (int r = 0; r < current_edges_num; ++r) { P_indices->emplace_back(r + l_index); } first_row_location += current_edges_num; } // Update index edges_counter += current_edges_num; l_index += current_edges_num; } } CHECK_EQ(P_indptr->size(), static_cast<size_t>(lambda_horizon_)); for (int i = lambda_horizon_; i < num_of_variables_ + 1; ++i) { P_indptr->emplace_back(first_row_location); } CHECK_EQ(P_data->size(), P_indices->size()); CHECK_EQ(P_indptr->size(), static_cast<size_t>(num_of_variables_) + 1); } void DualVariableWarmStartOSQPInterface::assemble_constraint( std::vector<c_float>* A_data, std::vector<c_int>* A_indices, std::vector<c_int>* A_indptr) { /* * The constraint matrix is as the form, * |R' * A', G'|, #: 2 * obstacles_num_ * (horizon_ + 1) * |A * t - b, -g|, #: obstacles_num_ * (horizon_ + 1) * |I, 0|, #: num_of_lambda * |0, I|, #: num_of_miu */ int r1_index = 0; int r2_index = 2 * obstacles_num_ * (horizon_ + 1); int r3_index = 3 * obstacles_num_ * (horizon_ + 1); int r4_index = 3 * obstacles_num_ * (horizon_ + 1) + lambda_horizon_; int first_row_location = 0; // lambda variables for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; Eigen::MatrixXd R(2, 2); R << cos(xWS_(2, i)), sin(xWS_(2, i)), sin(xWS_(2, i)), cos(xWS_(2, i)); Eigen::MatrixXd t_trans(1, 2); t_trans << (xWS_(0, i) + cos(xWS_(2, i)) * offset_), (xWS_(1, i) + sin(xWS_(2, i)) * offset_); // assume: stationary obstacles for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); Eigen::MatrixXd r1_block(2, current_edges_num); r1_block = R * Aj.transpose(); Eigen::MatrixXd r2_block(1, current_edges_num); r2_block = t_trans * Aj.transpose() - bj.transpose(); // insert into A matrix, col by col for (int k = 0; k < current_edges_num; ++k) { A_data->emplace_back(r1_block(0, k)); A_indices->emplace_back(r1_index); A_data->emplace_back(r1_block(1, k)); A_indices->emplace_back(r1_index + 1); A_data->emplace_back(r2_block(0, k)); A_indices->emplace_back(r2_index); A_data->emplace_back(1.0); A_indices->emplace_back(r3_index); r3_index++; A_indptr->emplace_back(first_row_location); first_row_location += 4; } // Update index edges_counter += current_edges_num; r1_index += 2; r2_index += 1; } } // miu variables // G: ((1, 0, -1, 0), (0, 1, 0, -1)) // g: g_ r1_index = 0; r2_index = 2 * obstacles_num_ * (horizon_ + 1); for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { for (int k = 0; k < 4; ++k) { // update G if (k < 2) { A_data->emplace_back(1.0); } else { A_data->emplace_back(-1.0); } A_indices->emplace_back(r1_index + k % 2); // update g' A_data->emplace_back(-g_[k]); A_indices->emplace_back(r2_index); // update I A_data->emplace_back(1.0); A_indices->emplace_back(r4_index); r4_index++; // update col index A_indptr->emplace_back(first_row_location); first_row_location += 3; } // update index r1_index += 2; r2_index += 1; } } A_indptr->emplace_back(first_row_location); CHECK_EQ(A_data->size(), A_indices->size()); CHECK_EQ(A_indptr->size(), static_cast<size_t>(num_of_variables_) + 1); } void DualVariableWarmStartOSQPInterface::get_optimization_results( Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up) const { *l_warm_up = l_warm_up_; *n_warm_up = n_warm_up_; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_osqp_interface_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_osqp_interface.h" #include <coin/IpIpoptApplication.hpp> #include <coin/IpSolveStatistics.hpp> #include "cyber/common/file.h" #include "gtest/gtest.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_ipopt_qp_interface.h" namespace apollo { namespace planning { class DualVariableWarmStartOSQPInterfaceTest : public ::testing::Test { public: virtual void SetUp() { FLAGS_planner_open_space_config_filename = "/apollo/modules/planning/testdata/conf/" "open_space_standard_parking_lot.pb.txt"; ACHECK(apollo::cyber::common::GetProtoFromFile( FLAGS_planner_open_space_config_filename, &planner_open_space_config_)) << "Failed to load open space config file " << FLAGS_planner_open_space_config_filename; ProblemSetup(); } protected: void ProblemSetup(); protected: size_t horizon_ = 5; size_t obstacles_num_ = 4; double ts_ = 0.1; Eigen::MatrixXd ego_ = Eigen::MatrixXd::Ones(4, 1); Eigen::MatrixXd last_time_u_ = Eigen::MatrixXd::Zero(2, 1); Eigen::MatrixXi obstacles_edges_num_; Eigen::MatrixXd obstacles_A_ = Eigen::MatrixXd::Ones(10, 2); Eigen::MatrixXd obstacles_b_ = Eigen::MatrixXd::Ones(10, 1); int num_of_variables_ = 0; double rx_ = 0.0; double ry_ = 0.0; double r_yaw_ = 0.0; int num_of_constraints_ = 0; std::unique_ptr<DualVariableWarmStartOSQPInterface> ptop_ = nullptr; DualVariableWarmStartIPOPTQPInterface* pt_gt_ = nullptr; PlannerOpenSpaceConfig planner_open_space_config_; }; void DualVariableWarmStartOSQPInterfaceTest::ProblemSetup() { obstacles_edges_num_ = Eigen::MatrixXi(obstacles_num_, 1); obstacles_edges_num_ << 2, 1, 2, 1; Eigen::MatrixXd xWS = Eigen::MatrixXd::Ones(4, horizon_ + 1); ptop_.reset(new DualVariableWarmStartOSQPInterface( horizon_, ts_, ego_, obstacles_edges_num_, obstacles_num_, obstacles_A_, obstacles_b_, xWS, planner_open_space_config_)); pt_gt_ = new DualVariableWarmStartIPOPTQPInterface( horizon_, ts_, ego_, obstacles_edges_num_, obstacles_num_, obstacles_A_, obstacles_b_, xWS, planner_open_space_config_); } TEST_F(DualVariableWarmStartOSQPInterfaceTest, initilization) { EXPECT_NE(ptop_, nullptr); } TEST_F(DualVariableWarmStartOSQPInterfaceTest, optimize) { int obstacles_edges_sum = obstacles_edges_num_.sum(); Eigen::MatrixXd l_warm_up(obstacles_edges_sum, horizon_ + 1); Eigen::MatrixXd n_warm_up(4 * obstacles_num_, horizon_ + 1); bool res = ptop_->optimize(); EXPECT_TRUE(res); ptop_->get_optimization_results(&l_warm_up, &n_warm_up); // regard ipopt_qp as ground truth result Eigen::MatrixXd l_warm_up_gt(obstacles_edges_sum, horizon_ + 1); Eigen::MatrixXd n_warm_up_gt(4 * obstacles_num_, horizon_ + 1); Ipopt::SmartPtr<Ipopt::TNLP> problem = pt_gt_; // Create an instance of the IpoptApplication Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory(); auto ipopt_config_tmp = planner_open_space_config_.dual_variable_warm_start_config() .ipopt_config(); app->Options()->SetIntegerValue("print_level", ipopt_config_tmp.ipopt_print_level()); app->Options()->SetIntegerValue("mumps_mem_percent", ipopt_config_tmp.mumps_mem_percent()); app->Options()->SetNumericValue("mumps_pivtol", ipopt_config_tmp.mumps_pivtol()); app->Options()->SetIntegerValue("max_iter", ipopt_config_tmp.ipopt_max_iter()); app->Options()->SetNumericValue("tol", ipopt_config_tmp.ipopt_tol()); app->Options()->SetNumericValue( "acceptable_constr_viol_tol", ipopt_config_tmp.ipopt_acceptable_constr_viol_tol()); app->Options()->SetNumericValue( "min_hessian_perturbation", ipopt_config_tmp.ipopt_min_hessian_perturbation()); app->Options()->SetNumericValue( "jacobian_regularization_value", ipopt_config_tmp.ipopt_jacobian_regularization_value()); app->Options()->SetStringValue( "print_timing_statistics", ipopt_config_tmp.ipopt_print_timing_statistics()); app->Options()->SetStringValue("alpha_for_y", ipopt_config_tmp.ipopt_alpha_for_y()); app->Options()->SetStringValue("recalc_y", ipopt_config_tmp.ipopt_recalc_y()); app->Options()->SetStringValue("mehrotra_algorithm", "yes"); app->Initialize(); app->OptimizeTNLP(problem); // Retrieve some statistics about the solve pt_gt_->get_optimization_results(&l_warm_up_gt, &n_warm_up_gt); // compare ipopt_qp and osqp results for (int r = 0; r < obstacles_edges_sum; ++r) { for (int c = 0; c < static_cast<int>(horizon_) + 1; ++c) { EXPECT_NEAR(l_warm_up(r, c), l_warm_up_gt(r, c), 1e-6) << "r: " << r << ", c: " << c; } } for (int r = 0; r < 4 * static_cast<int>(obstacles_num_); ++r) { for (int c = 0; c < static_cast<int>(horizon_) + 1; ++c) { EXPECT_NEAR(n_warm_up(r, c), n_warm_up_gt(r, c), 1e-6) << "r: " << r << ",c: " << c; } } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") load("//third_party/gpus:common.bzl", "gpu_library", "if_gpu", "if_cuda", "if_rocm") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) PLANNING_COPTS = ["-DMODULE_NAME=\\\"planning\\\""] PLANNING_FOPENMP = ["-DMODULE_NAME=\\\"planning\\\"","-fopenmp"] cc_library( name = "dual_variable_warm_start_problem", srcs = ["dual_variable_warm_start_problem.cc"], hdrs = ["dual_variable_warm_start_problem.h"], copts = PLANNING_COPTS, deps = [ ":dual_variable_warm_start_ipopt_interface", ":dual_variable_warm_start_ipopt_qp_interface", ":dual_variable_warm_start_osqp_interface", ":dual_variable_warm_start_slack_osqp_interface", "//cyber", "//modules/common/util:util_tool", ], ) cc_library( name = "dual_variable_warm_start_ipopt_interface", srcs = ["dual_variable_warm_start_ipopt_interface.cc"], hdrs = ["dual_variable_warm_start_ipopt_interface.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/util", "//modules/planning/common:planning_gflags", "//modules/planning/proto:planner_open_space_config_cc_proto", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@adolc", "@eigen", "@ipopt", ], ) cc_library( name = "dual_variable_warm_start_ipopt_qp_interface", srcs = ["dual_variable_warm_start_ipopt_qp_interface.cc"], hdrs = ["dual_variable_warm_start_ipopt_qp_interface.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/util", "//modules/planning/common:planning_gflags", "//modules/planning/proto:planner_open_space_config_cc_proto", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@adolc", "@eigen", "@ipopt", ], ) cc_library( name = "dual_variable_warm_start_osqp_interface", srcs = ["dual_variable_warm_start_osqp_interface.cc"], hdrs = ["dual_variable_warm_start_osqp_interface.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/util", "//modules/planning/common:planning_gflags", "//modules/planning/proto:planner_open_space_config_cc_proto", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@eigen", "@osqp", ], ) cc_library( name = "dual_variable_warm_start_slack_osqp_interface", srcs = ["dual_variable_warm_start_slack_osqp_interface.cc"], hdrs = ["dual_variable_warm_start_slack_osqp_interface.h"], copts = PLANNING_COPTS, deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/util", "//modules/planning/common:planning_gflags", "//modules/planning/proto:planner_open_space_config_cc_proto", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@eigen", "@osqp", ], ) cc_library( name = "distance_approach_problem", srcs = ["distance_approach_problem.cc"], hdrs = ["distance_approach_problem.h"], copts = PLANNING_FOPENMP, deps = [ ":distance_approach_ipopt_cuda_interface", ":distance_approach_ipopt_fixed_dual_interface", ":distance_approach_ipopt_fixed_ts_interface", ":distance_approach_ipopt_interface", ":distance_approach_ipopt_relax_end_interface", ":distance_approach_ipopt_relax_end_slack_interface", "//cyber", "//modules/common/util:util_tool", "//modules/planning/common:planning_gflags", "//modules/planning/proto:planner_open_space_config_cc_proto", ], ) cc_library( name = "distance_approach_ipopt_fixed_ts_interface", srcs = ["distance_approach_ipopt_fixed_ts_interface.cc"], hdrs = [ "distance_approach_interface.h", "distance_approach_ipopt_fixed_ts_interface.h", ], copts = PLANNING_FOPENMP, deps = [ "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/util", "//modules/planning/common:planning_gflags", "//modules/planning/proto:planner_open_space_config_cc_proto", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@adolc", "@eigen", "@ipopt", ], ) cc_library( name = "distance_approach_ipopt_fixed_dual_interface", srcs = ["distance_approach_ipopt_fixed_dual_interface.cc"], hdrs = [ "distance_approach_interface.h", "distance_approach_ipopt_fixed_dual_interface.h", ], copts = PLANNING_FOPENMP, deps = [ "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/util", "//modules/planning/common:planning_gflags", "//modules/planning/proto:planner_open_space_config_cc_proto", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@adolc", "@eigen", "@ipopt", ], ) cc_library( name = "distance_approach_ipopt_relax_end_interface", srcs = ["distance_approach_ipopt_relax_end_interface.cc"], hdrs = [ "distance_approach_interface.h", "distance_approach_ipopt_relax_end_interface.h", ], copts = PLANNING_FOPENMP, deps = [ "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/util", "//modules/planning/common:planning_gflags", "//modules/planning/proto:planner_open_space_config_cc_proto", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@adolc", "@eigen", "@ipopt", ], ) cc_library( name = "distance_approach_ipopt_relax_end_slack_interface", srcs = ["distance_approach_ipopt_relax_end_slack_interface.cc"], hdrs = [ "distance_approach_interface.h", "distance_approach_ipopt_relax_end_slack_interface.h", ], copts = PLANNING_FOPENMP, deps = [ "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/util", "//modules/planning/common:planning_gflags", "//modules/planning/proto:planner_open_space_config_cc_proto", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@adolc", "@eigen", "@ipopt", ], ) cc_library( name = "distance_approach_ipopt_interface", srcs = ["distance_approach_ipopt_interface.cc"], hdrs = [ "distance_approach_interface.h", "distance_approach_ipopt_interface.h", ], copts = PLANNING_FOPENMP, deps = [ "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/util", "//modules/planning/common:planning_gflags", "//modules/planning/proto:planner_open_space_config_cc_proto", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@adolc", "@eigen", "@ipopt", ], ) cc_library( name = "distance_approach_ipopt_cuda_interface", srcs = ["distance_approach_ipopt_cuda_interface.cc"], hdrs = [ "distance_approach_interface.h", "distance_approach_ipopt_cuda_interface.h", ], copts = PLANNING_FOPENMP, deps = [ "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/common/util", "//modules/planning/common:planning_gflags", "//modules/planning/proto:planner_open_space_config_cc_proto", "//modules/common_msgs/planning_msgs:planning_cc_proto", "@adolc", "@eigen", "@ipopt", ] + if_gpu([":planning_block"]), ) cc_library( name = "iterative_anchoring_smoother", srcs = ["iterative_anchoring_smoother.cc"], hdrs = ["iterative_anchoring_smoother.h"], deps = [ "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/planning/common:speed_profile_generator", "//modules/planning/common/path:discretized_path", "//modules/planning/common/speed:speed_data", "//modules/planning/common/trajectory:discretized_trajectory", "//modules/planning/math:discrete_points_math", "//modules/planning/math/discretized_points_smoothing:fem_pos_deviation_smoother", "//modules/planning/proto:planner_open_space_config_cc_proto", "@eigen", ], ) gpu_library( name = "planning_block", srcs = ["planning_block.cu"], hdrs = ["planning_block.h"], deps = [ ] + if_cuda([ "@local_config_cuda//cuda:cuda_headers", "@local_config_cuda//cuda:cudart", ]) + if_rocm([ "@local_config_rocm//rocm:rocm_headers", "@local_config_rocm//rocm:hip", ]), ) cc_test( name = "distance_approach_ipopt_interface_test", size = "small", srcs = ["distance_approach_ipopt_interface_test.cc"], copts = PLANNING_FOPENMP, linkopts = ["-lgomp"], deps = [ ":distance_approach_ipopt_interface", "//cyber", "@com_google_googletest//:gtest_main", ], ) cc_test( name = "distance_approach_ipopt_cuda_interface_test", size = "small", srcs = ["distance_approach_ipopt_cuda_interface_test.cc"], copts = PLANNING_FOPENMP, linkopts = ["-lgomp"], deps = [ ":distance_approach_ipopt_cuda_interface", "//cyber", "@com_google_googletest//:gtest_main", ] + if_cuda([ "@local_config_cuda//cuda:cudart", ]) + if_rocm([ "@local_config_rocm//rocm:hip", ]), linkstatic = True, ) cc_test( name = "distance_approach_problem_test", size = "small", srcs = ["distance_approach_problem_test.cc"], copts = PLANNING_FOPENMP, linkopts = ["-lgomp"], deps = [ ":distance_approach_problem", "//cyber", "@com_google_googletest//:gtest_main", ] + if_cuda([ "@local_config_cuda//cuda:cudart", ]) + if_rocm([ "@local_config_rocm//rocm:hip", ]), linkstatic = True, ) cc_test( name = "dual_variable_warm_start_ipopt_interface_test", size = "small", srcs = ["dual_variable_warm_start_ipopt_interface_test.cc"], deps = [ ":dual_variable_warm_start_ipopt_interface", "@com_google_googletest//:gtest_main", ], ) cc_test( name = "dual_variable_warm_start_osqp_interface_test", size = "small", srcs = ["dual_variable_warm_start_osqp_interface_test.cc"], deps = [ ":dual_variable_warm_start_ipopt_qp_interface", ":dual_variable_warm_start_osqp_interface", "@com_google_googletest//:gtest_main", "@ipopt", ], linkstatic = True, ) cc_test( name = "dual_variable_warm_start_problem_test", size = "small", srcs = ["dual_variable_warm_start_problem_test.cc"], deps = [ ":dual_variable_warm_start_problem", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_slack_osqp_interface.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/open_space/trajectory_smoother/dual_variable_warm_start_slack_osqp_interface.h" #include <algorithm> #include "cyber/common/log.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { DualVariableWarmStartSlackOSQPInterface:: DualVariableWarmStartSlackOSQPInterface( size_t horizon, double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const Eigen::MatrixXd& xWS, const PlannerOpenSpaceConfig& planner_open_space_config) : ts_(ts), ego_(ego), obstacles_edges_num_(obstacles_edges_num), obstacles_A_(obstacles_A), obstacles_b_(obstacles_b), xWS_(xWS) { ACHECK(horizon < std::numeric_limits<int>::max()) << "Invalid cast on horizon in open space planner"; horizon_ = static_cast<int>(horizon); ACHECK(obstacles_num < std::numeric_limits<int>::max()) << "Invalid cast on obstacles_num in open space planner"; obstacles_num_ = static_cast<int>(obstacles_num); w_ev_ = ego_(1, 0) + ego_(3, 0); l_ev_ = ego_(0, 0) + ego_(2, 0); g_ = {l_ev_ / 2, w_ev_ / 2, l_ev_ / 2, w_ev_ / 2}; offset_ = (ego_(0, 0) + ego_(2, 0)) / 2 - ego_(2, 0); obstacles_edges_sum_ = obstacles_edges_num_.sum(); l_start_index_ = 0; n_start_index_ = l_start_index_ + obstacles_edges_sum_ * (horizon_ + 1); s_start_index_ = n_start_index_ + 4 * obstacles_num_ * (horizon_ + 1); l_warm_up_ = Eigen::MatrixXd::Zero(obstacles_edges_sum_, horizon_ + 1); n_warm_up_ = Eigen::MatrixXd::Zero(4 * obstacles_num_, horizon_ + 1); slacks_ = Eigen::MatrixXd::Zero(obstacles_num_, horizon_ + 1); // get_nlp_info lambda_horizon_ = obstacles_edges_sum_ * (horizon_ + 1); miu_horizon_ = obstacles_num_ * 4 * (horizon_ + 1); slack_horizon_ = obstacles_num_ * (horizon_ + 1); // number of variables num_of_variables_ = lambda_horizon_ + miu_horizon_ + slack_horizon_; // number of constraints num_of_constraints_ = 3 * obstacles_num_ * (horizon_ + 1) + num_of_variables_; min_safety_distance_ = planner_open_space_config.dual_variable_warm_start_config() .min_safety_distance(); check_mode_ = planner_open_space_config.dual_variable_warm_start_config().debug_osqp(); beta_ = planner_open_space_config.dual_variable_warm_start_config().beta(); osqp_config_ = planner_open_space_config.dual_variable_warm_start_config().osqp_config(); } void DualVariableWarmStartSlackOSQPInterface::printMatrix( const int r, const int c, const std::vector<c_float>& P_data, const std::vector<c_int>& P_indices, const std::vector<c_int>& P_indptr) { Eigen::MatrixXf tmp = Eigen::MatrixXf::Zero(r, c); for (size_t i = 0; i < P_indptr.size() - 1; ++i) { if (P_indptr[i] < 0 || P_indptr[i] >= static_cast<int>(P_indices.size())) { continue; } for (auto idx = P_indptr[i]; idx < P_indptr[i + 1]; ++idx) { int tmp_c = static_cast<int>(i); int tmp_r = static_cast<int>(P_indices[idx]); tmp(tmp_r, tmp_c) = static_cast<float>(P_data[idx]); } } AINFO << "row number: " << r; AINFO << "col number: " << c; for (int i = 0; i < r; ++i) { AINFO << "row number: " << i; AINFO << tmp.row(i); } } void DualVariableWarmStartSlackOSQPInterface::assembleA( const int r, const int c, const std::vector<c_float>& P_data, const std::vector<c_int>& P_indices, const std::vector<c_int>& P_indptr) { constraint_A_ = Eigen::MatrixXf::Zero(r, c); for (size_t i = 0; i < P_indptr.size() - 1; ++i) { if (P_indptr[i] < 0 || P_indptr[i] >= static_cast<int>(P_indices.size())) { continue; } for (auto idx = P_indptr[i]; idx < P_indptr[i + 1]; ++idx) { int tmp_c = static_cast<int>(i); int tmp_r = static_cast<int>(P_indices[idx]); constraint_A_(tmp_r, tmp_c) = static_cast<float>(P_data[idx]); } } } bool DualVariableWarmStartSlackOSQPInterface::optimize() { // int kNumParam = num_of_variables_; // int kNumConst = num_of_constraints_; bool succ = true; // assemble P, quadratic term in objective std::vector<c_float> P_data; std::vector<c_int> P_indices; std::vector<c_int> P_indptr; assembleP(&P_data, &P_indices, &P_indptr); if (check_mode_) { AINFO << "print P_data in whole: "; printMatrix(num_of_variables_, num_of_variables_, P_data, P_indices, P_indptr); } // assemble q, linear term in objective, \sum{beta * slacks} c_float q[num_of_variables_]; // NOLINT for (int i = 0; i < num_of_variables_; ++i) { q[i] = 0.0; if (i >= s_start_index_) { q[i] = beta_; } } // assemble A, linear term in constraints std::vector<c_float> A_data; std::vector<c_int> A_indices; std::vector<c_int> A_indptr; assembleConstraint(&A_data, &A_indices, &A_indptr); if (check_mode_) { AINFO << "print A_data in whole: "; printMatrix(num_of_constraints_, num_of_variables_, A_data, A_indices, A_indptr); assembleA(num_of_constraints_, num_of_variables_, A_data, A_indices, A_indptr); } // assemble lb & ub, slack_variable <= 0 c_float lb[num_of_constraints_]; // NOLINT c_float ub[num_of_constraints_]; // NOLINT int slack_indx = num_of_constraints_ - slack_horizon_; for (int i = 0; i < num_of_constraints_; ++i) { lb[i] = 0.0; if (i >= slack_indx) { lb[i] = -2e19; } if (i < 2 * obstacles_num_ * (horizon_ + 1)) { ub[i] = 0.0; } else if (i < slack_indx) { ub[i] = 2e19; } else { ub[i] = 0.0; } } // Problem settings OSQPSettings* settings = reinterpret_cast<OSQPSettings*>(c_malloc(sizeof(OSQPSettings))); // Define Solver settings as default osqp_set_default_settings(settings); settings->alpha = osqp_config_.alpha(); // Change alpha parameter settings->eps_abs = osqp_config_.eps_abs(); settings->eps_rel = osqp_config_.eps_rel(); settings->max_iter = osqp_config_.max_iter(); settings->polish = osqp_config_.polish(); settings->verbose = osqp_config_.osqp_debug_log(); // Populate data OSQPData* data = reinterpret_cast<OSQPData*>(c_malloc(sizeof(OSQPData))); data->n = num_of_variables_; data->m = num_of_constraints_; data->P = csc_matrix(data->n, data->n, P_data.size(), P_data.data(), P_indices.data(), P_indptr.data()); data->q = q; data->A = csc_matrix(data->m, data->n, A_data.size(), A_data.data(), A_indices.data(), A_indptr.data()); data->l = lb; data->u = ub; // Workspace OSQPWorkspace* work = nullptr; // osqp_setup(&work, data, settings); work = osqp_setup(data, settings); // Solve Problem osqp_solve(work); // check state if (work->info->status_val != 1 && work->info->status_val != 2) { AWARN << "OSQP dual warm up unsuccess, " << "return status: " << work->info->status; succ = false; } // transfer to make lambda's norm under 1 std::vector<double> lambda_norm; int l_index = l_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); double tmp1 = 0; double tmp2 = 0; for (int k = 0; k < current_edges_num; ++k) { tmp1 += Aj(k, 0) * work->solution->x[l_index + k]; tmp2 += Aj(k, 1) * work->solution->x[l_index + k]; } // norm(A * lambda) double tmp_norm = tmp1 * tmp1 + tmp2 * tmp2; if (tmp_norm >= 1e-5) { lambda_norm.push_back(0.75 / std::sqrt(tmp_norm)); } else { lambda_norm.push_back(0.0); } edges_counter += current_edges_num; l_index += current_edges_num; } } // extract primal results int variable_index = 0; // 1. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0, // horizon_l for (int i = 0; i < horizon_ + 1; ++i) { int r_index = 0; for (int j = 0; j < obstacles_num_; ++j) { for (int k = 0; k < obstacles_edges_num_(j, 0); ++k) { l_warm_up_(r_index, i) = lambda_norm[i * obstacles_num_ + j] * work->solution->x[variable_index]; ++variable_index; ++r_index; } } } // 2. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { int r_index = 0; for (int j = 0; j < obstacles_num_; ++j) { for (int k = 0; k < 4; ++k) { n_warm_up_(r_index, i) = lambda_norm[i * obstacles_num_ + j] * work->solution->x[variable_index]; ++r_index; ++variable_index; } } } // 3. slack variables for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { slacks_(j, i) = lambda_norm[i * obstacles_num_ + j] * work->solution->x[variable_index]; ++variable_index; } } succ = succ & (work->info->obj_val <= 1.0); // Cleanup osqp_cleanup(work); c_free(data->A); c_free(data->P); c_free(data); c_free(settings); return succ; } void DualVariableWarmStartSlackOSQPInterface::checkSolution( const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up) { // TODO(Runxin): extend } void DualVariableWarmStartSlackOSQPInterface::assembleP( std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr) { // the objective function is norm(A' * lambda) std::vector<c_float> P_tmp; int edges_counter = 0; for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj; Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); // Eigen::MatrixXd AAj(current_edges_num, current_edges_num); Aj = Aj * Aj.transpose(); CHECK_EQ(current_edges_num, Aj.cols()); CHECK_EQ(current_edges_num, Aj.rows()); for (int c = 0; c < current_edges_num; ++c) { for (int r = 0; r < current_edges_num; ++r) { P_tmp.emplace_back(Aj(r, c)); } } // Update index edges_counter += current_edges_num; } int l_index = l_start_index_; int first_row_location = 0; // the objective function is norm(A' * lambda) for (int i = 0; i < horizon_ + 1; ++i) { edges_counter = 0; for (auto item : P_tmp) { P_data->emplace_back(item); } // current assumption: stationary obstacles for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); for (int c = 0; c < current_edges_num; ++c) { P_indptr->emplace_back(first_row_location); for (int r = 0; r < current_edges_num; ++r) { P_indices->emplace_back(r + l_index); } first_row_location += current_edges_num; } // Update index edges_counter += current_edges_num; l_index += current_edges_num; } } CHECK_EQ(P_indptr->size(), static_cast<size_t>(lambda_horizon_)); for (int i = lambda_horizon_; i < num_of_variables_ + 1; ++i) { P_indptr->emplace_back(first_row_location); } CHECK_EQ(P_data->size(), P_indices->size()); CHECK_EQ(P_indptr->size(), static_cast<size_t>(num_of_variables_) + 1); } void DualVariableWarmStartSlackOSQPInterface::assembleConstraint( std::vector<c_float>* A_data, std::vector<c_int>* A_indices, std::vector<c_int>* A_indptr) { /* * The constraint matrix is as the form, * |R' * A', G', 0|, #: 2 * obstacles_num_ * (horizon_ + 1) * |A * t - b, -g, I|, #: obstacles_num_ * (horizon_ + 1) * |I, 0, 0|, #: num_of_lambda * |0, I, 0|, #: num_of_miu * |0, 0, I|, #: num_of_slack */ int r1_index = 0; int r2_index = 2 * obstacles_num_ * (horizon_ + 1); int r3_index = 3 * obstacles_num_ * (horizon_ + 1); int r4_index = 3 * obstacles_num_ * (horizon_ + 1) + lambda_horizon_; int r5_index = r4_index + miu_horizon_; int first_row_location = 0; // lambda variables // lambda_horizon_ = obstacles_edges_sum_ * (horizon_ + 1); for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; Eigen::MatrixXd R(2, 2); R << cos(xWS_(2, i)), sin(xWS_(2, i)), sin(xWS_(2, i)), cos(xWS_(2, i)); Eigen::MatrixXd t_trans(1, 2); t_trans << (xWS_(0, i) + cos(xWS_(2, i)) * offset_), (xWS_(1, i) + sin(xWS_(2, i)) * offset_); // assume: stationary obstacles for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); Eigen::MatrixXd r1_block(2, current_edges_num); r1_block = R * Aj.transpose(); Eigen::MatrixXd r2_block(1, current_edges_num); r2_block = t_trans * Aj.transpose() - bj.transpose(); // insert into A matrix, col by col for (int k = 0; k < current_edges_num; ++k) { A_data->emplace_back(r1_block(0, k)); A_indices->emplace_back(r1_index); A_data->emplace_back(r1_block(1, k)); A_indices->emplace_back(r1_index + 1); A_data->emplace_back(r2_block(0, k)); A_indices->emplace_back(r2_index); A_data->emplace_back(1.0); A_indices->emplace_back(r3_index); r3_index++; A_indptr->emplace_back(first_row_location); first_row_location += 4; } // Update index edges_counter += current_edges_num; r1_index += 2; r2_index += 1; } } // miu variables, miu_horizon_ = obstacles_num_ * 4 * (horizon_ + 1); // G: ((1, 0, -1, 0), (0, 1, 0, -1)) // g: g_ r1_index = 0; r2_index = 2 * obstacles_num_ * (horizon_ + 1); for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { for (int k = 0; k < 4; ++k) { // update G if (k < 2) { A_data->emplace_back(1.0); } else { A_data->emplace_back(-1.0); } A_indices->emplace_back(r1_index + k % 2); // update g' A_data->emplace_back(-g_[k]); A_indices->emplace_back(r2_index); // update I A_data->emplace_back(1.0); A_indices->emplace_back(r4_index); r4_index++; // update col index A_indptr->emplace_back(first_row_location); first_row_location += 3; } // update index r1_index += 2; r2_index += 1; } } // slack variables // slack_horizon_ = obstacles_edges_sum_ * (horizon_ + 1); r2_index = 2 * obstacles_num_ * (horizon_ + 1); for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { A_data->emplace_back(1.0); A_indices->emplace_back(r2_index); ++r2_index; A_data->emplace_back(1.0); A_indices->emplace_back(r5_index); ++r5_index; A_indptr->emplace_back(first_row_location); first_row_location += 2; } } A_indptr->emplace_back(first_row_location); CHECK_EQ(A_data->size(), A_indices->size()); CHECK_EQ(A_indptr->size(), static_cast<size_t>(num_of_variables_) + 1); } void DualVariableWarmStartSlackOSQPInterface::get_optimization_results( Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up, Eigen::MatrixXd* s_warm_up) const { *l_warm_up = l_warm_up_; *n_warm_up = n_warm_up_; *s_warm_up = slacks_; // debug mode check slack values double max_s = slacks_(0, 0); double min_s = slacks_(0, 0); for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { max_s = std::max(max_s, slacks_(j, i)); min_s = std::min(min_s, slacks_(j, i)); } } ADEBUG << "max_s: " << max_s; ADEBUG << "min_s: " << min_s; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_interface_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_interface.h" #include "cyber/common/file.h" #include "gtest/gtest.h" namespace apollo { namespace planning { class DistanceApproachIPOPTInterfaceTest : public ::testing::Test { public: virtual void SetUp() { FLAGS_planner_open_space_config_filename = "/apollo/modules/planning/testdata/conf/" "open_space_standard_parking_lot.pb.txt"; ACHECK(apollo::cyber::common::GetProtoFromFile( FLAGS_planner_open_space_config_filename, &planner_open_space_config_)) << "Failed to load open space config file " << FLAGS_planner_open_space_config_filename; distance_approach_config_ = planner_open_space_config_.distance_approach_config(); ProblemSetup(); } protected: void ProblemSetup(); protected: size_t horizon_ = 43; size_t obstacles_num_ = 4; double ts_ = 0.5; Eigen::MatrixXd ego_ = Eigen::MatrixXd::Ones(4, 1); Eigen::MatrixXd x0_ = Eigen::MatrixXd::Ones(4, 1); Eigen::MatrixXd xf_ = 10 * Eigen::MatrixXd::Ones(4, 1); Eigen::MatrixXd last_time_u_ = Eigen::MatrixXd::Zero(2, 1); std::vector<double> XYbounds_ = {1.0, 1.0, 1.0, 1.0}; Eigen::MatrixXd xWS_ = Eigen::MatrixXd::Ones(4, 44); Eigen::MatrixXd uWS_ = Eigen::MatrixXd::Ones(2, 43); Eigen::MatrixXi obstacles_edges_num_; // {2, 1, 2, 1} size_t obstacles_edges_sum_; Eigen::MatrixXd obstacles_A_ = Eigen::MatrixXd::Ones(6, 2); Eigen::MatrixXd obstacles_b_ = Eigen::MatrixXd::Ones(6, 1); bool use_fix_time_ = false; std::unique_ptr<DistanceApproachIPOPTInterface> ptop_ = nullptr; PlannerOpenSpaceConfig planner_open_space_config_; DistanceApproachConfig distance_approach_config_; }; void DistanceApproachIPOPTInterfaceTest::ProblemSetup() { // obstacles_edges_num_ = 4 * Eigen::MatrixXi::Ones(obstacles_num_, 1); obstacles_edges_num_ = Eigen::MatrixXi(obstacles_num_, 1); obstacles_edges_num_ << 2, 1, 2, 1; obstacles_edges_sum_ = obstacles_edges_num_.sum(); Eigen::MatrixXd l_warm_up_ = Eigen::MatrixXd::Ones(obstacles_edges_sum_, horizon_ + 1); Eigen::MatrixXd n_warm_up_ = Eigen::MatrixXd::Ones(4 * obstacles_num_, horizon_ + 1); ptop_.reset(new DistanceApproachIPOPTInterface( horizon_, ts_, ego_, xWS_, uWS_, l_warm_up_, n_warm_up_, x0_, xf_, last_time_u_, XYbounds_, obstacles_edges_num_, obstacles_num_, obstacles_A_, obstacles_b_, planner_open_space_config_)); } TEST_F(DistanceApproachIPOPTInterfaceTest, initilization) { EXPECT_NE(ptop_, nullptr); } TEST_F(DistanceApproachIPOPTInterfaceTest, get_bounds_info) { int n = 1274; int m = 2194; double x_l[1274]; double x_u[1274]; double g_l[2194]; double g_u[2194]; bool res = ptop_->get_bounds_info(n, x_l, x_u, m, g_l, g_u); EXPECT_TRUE(res); } TEST_F(DistanceApproachIPOPTInterfaceTest, get_starting_point) { int n = 1274; int m = 2194; bool init_x = true; bool init_z = false; bool init_lambda = false; double x[1274]; double z_L[2194]; double z_U[2194]; double lambda[2194]; bool res = ptop_->get_starting_point(n, init_x, x, init_z, z_L, z_U, m, init_lambda, lambda); EXPECT_TRUE(res); } TEST_F(DistanceApproachIPOPTInterfaceTest, eval_f) { int n = 1274; double obj_value = 0.0; double x[1274]; std::fill_n(x, n, 1.2); bool res = ptop_->eval_f(n, x, true, obj_value); EXPECT_DOUBLE_EQ(obj_value, 1443.3600000000008) << "eval_f: " << obj_value; EXPECT_TRUE(res); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_fixed_dual_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 */ #include "modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_fixed_dual_interface.h" namespace apollo { namespace planning { DistanceApproachIPOPTFixedDualInterface:: DistanceApproachIPOPTFixedDualInterface( const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xf, const Eigen::MatrixXd& last_time_u, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const PlannerOpenSpaceConfig& planner_open_space_config) : ts_(ts), ego_(ego), xWS_(xWS), uWS_(uWS), l_warm_up_(l_warm_up), n_warm_up_(n_warm_up), x0_(x0), xf_(xf), last_time_u_(last_time_u), XYbounds_(XYbounds), obstacles_edges_num_(obstacles_edges_num), obstacles_A_(obstacles_A), obstacles_b_(obstacles_b) { ACHECK(horizon < std::numeric_limits<int>::max()) << "Invalid cast on horizon in open space planner"; horizon_ = static_cast<int>(horizon); ADEBUG << "horizon length: " << horizon_; ACHECK(obstacles_num < std::numeric_limits<int>::max()) << "Invalid cast on obstacles_num in open space planner"; obstacles_num_ = static_cast<int>(obstacles_num); w_ev_ = ego_(1, 0) + ego_(3, 0); l_ev_ = ego_(0, 0) + ego_(2, 0); g_ = {l_ev_ / 2, w_ev_ / 2, l_ev_ / 2, w_ev_ / 2}; offset_ = (ego_(0, 0) + ego_(2, 0)) / 2 - ego_(2, 0); obstacles_edges_sum_ = obstacles_edges_num_.sum(); state_result_ = Eigen::MatrixXd::Zero(4, horizon_ + 1); dual_l_result_ = Eigen::MatrixXd::Zero(obstacles_edges_sum_, horizon_ + 1); dual_n_result_ = Eigen::MatrixXd::Zero(4 * obstacles_num_, horizon_ + 1); control_result_ = Eigen::MatrixXd::Zero(2, horizon_); time_result_ = Eigen::MatrixXd::Zero(1, horizon_); state_start_index_ = 0; control_start_index_ = 4 * (horizon_ + 1); time_start_index_ = control_start_index_ + 2 * horizon_; l_start_index_ = time_start_index_ + (horizon_ + 1); n_start_index_ = l_start_index_ + obstacles_edges_sum_ * (horizon_ + 1); distance_approach_config_ = planner_open_space_config.distance_approach_config(); weight_state_x_ = distance_approach_config_.weight_x(); weight_state_y_ = distance_approach_config_.weight_y(); weight_state_phi_ = distance_approach_config_.weight_phi(); weight_state_v_ = distance_approach_config_.weight_v(); weight_input_steer_ = distance_approach_config_.weight_steer(); weight_input_a_ = distance_approach_config_.weight_a(); weight_rate_steer_ = distance_approach_config_.weight_steer_rate(); weight_rate_a_ = distance_approach_config_.weight_a_rate(); weight_stitching_steer_ = distance_approach_config_.weight_steer_stitching(); weight_stitching_a_ = distance_approach_config_.weight_a_stitching(); weight_first_order_time_ = distance_approach_config_.weight_first_order_time(); weight_second_order_time_ = distance_approach_config_.weight_second_order_time(); min_safety_distance_ = distance_approach_config_.min_safety_distance(); max_steer_angle_ = vehicle_param_.max_steer_angle() / vehicle_param_.steer_ratio(); max_speed_forward_ = distance_approach_config_.max_speed_forward(); max_speed_reverse_ = distance_approach_config_.max_speed_reverse(); max_acceleration_forward_ = distance_approach_config_.max_acceleration_forward(); max_acceleration_reverse_ = distance_approach_config_.max_acceleration_reverse(); min_time_sample_scaling_ = distance_approach_config_.min_time_sample_scaling(); max_time_sample_scaling_ = distance_approach_config_.max_time_sample_scaling(); max_steer_rate_ = vehicle_param_.max_steer_angle_rate() / vehicle_param_.steer_ratio(); use_fix_time_ = distance_approach_config_.use_fix_time(); wheelbase_ = vehicle_param_.wheel_base(); enable_constraint_check_ = distance_approach_config_.enable_constraint_check(); enable_jacobian_ad_ = distance_approach_config_.enable_jacobian_ad(); } bool DistanceApproachIPOPTFixedDualInterface::get_nlp_info( int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) { ADEBUG << "get_nlp_info"; // n1 : states variables, 4 * (N+1) int n1 = 4 * (horizon_ + 1); ADEBUG << "n1: " << n1; // n2 : control inputs variables int n2 = 2 * horizon_; ADEBUG << "n2: " << n2; // n3 : sampling time variables int n3 = horizon_ + 1; ADEBUG << "n3: " << n3; // n4 : dual multiplier associated with obstacle shape lambda_horizon_ = 0; // n5 : dual multipier associated with car shape, obstacles_num*4 * (N+1) miu_horizon_ = 0; // m1 : dynamics constatins int m1 = 4 * horizon_; // m2 : control rate constraints (only steering) int m2 = horizon_; // m3 : sampling time equality constraints int m3 = horizon_; // m4 : obstacle constraints // int m4 = 4 * obstacles_num_ * (horizon_ + 1); num_of_variables_ = n1 + n2 + n3; num_of_constraints_ = m1 + m2 + m3 + (num_of_variables_ - (horizon_ + 1) + 2); // number of variables n = num_of_variables_; ADEBUG << "num_of_variables_ " << num_of_variables_; // number of constraints m = num_of_constraints_; ADEBUG << "num_of_constraints_ " << num_of_constraints_; generate_tapes(n, m, &nnz_jac_g, &nnz_h_lag); index_style = IndexStyleEnum::C_STYLE; return true; } bool DistanceApproachIPOPTFixedDualInterface::get_bounds_info( int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) { ADEBUG << "get_bounds_info"; ACHECK(XYbounds_.size() == 4) << "XYbounds_ size is not 4, but" << XYbounds_.size(); // Variables: includes state, u, sample time and lagrange multipliers // 1. state variables, 4 * [0, horizon] // start point pose int variable_index = 0; for (int i = 0; i < 4; ++i) { x_l[i] = -2e19; x_u[i] = 2e19; } variable_index += 4; // During horizons, 2 ~ N-1 for (int i = 1; i < horizon_; ++i) { // x x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // y x_l[variable_index + 1] = -2e19; x_u[variable_index + 1] = 2e19; // phi x_l[variable_index + 2] = -2e19; x_u[variable_index + 2] = 2e19; // v x_l[variable_index + 3] = -2e19; x_u[variable_index + 3] = 2e19; variable_index += 4; } // end point pose for (int i = 0; i < 4; ++i) { x_l[variable_index + i] = -2e19; x_u[variable_index + i] = 2e19; } variable_index += 4; ADEBUG << "variable_index after adding state variables : " << variable_index; // 2. control variables, 2 * [0, horizon_-1] for (int i = 0; i < horizon_; ++i) { // steer x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // a x_l[variable_index + 1] = -2e19; x_u[variable_index + 1] = 2e19; variable_index += 2; } ADEBUG << "variable_index after adding control variables : " << variable_index; // 3. sampling time variables, 1 * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; ++variable_index; } ADEBUG << "variable_index after adding sample time : " << variable_index; ADEBUG << "sample time fix time status is : " << use_fix_time_; // Constraints: includes four state Euler forward constraints, three // Obstacle related constraints // 1. dynamics constraints 4 * [0, horizons-1] int constraint_index = 0; for (int i = 0; i < 4 * horizon_; ++i) { g_l[i] = 0.0; g_u[i] = 0.0; } constraint_index += 4 * horizon_; ADEBUG << "constraint_index after adding Euler forward dynamics constraints: " << constraint_index; // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply // steering rate as of now for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = -max_steer_rate_; g_u[constraint_index] = max_steer_rate_; ++constraint_index; } ADEBUG << "constraint_index after adding steering rate constraints: " << constraint_index; // 3. Time constraints 1 * [0, horizons-1] for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 0.0; ++constraint_index; } ADEBUG << "constraint_index after adding time constraints: " << constraint_index; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 // 5. load variable bounds as constraints // start configuration g_l[constraint_index] = x0_(0, 0); g_u[constraint_index] = x0_(0, 0); g_l[constraint_index + 1] = x0_(1, 0); g_u[constraint_index + 1] = x0_(1, 0); g_l[constraint_index + 2] = x0_(2, 0); g_u[constraint_index + 2] = x0_(2, 0); g_l[constraint_index + 3] = x0_(3, 0); g_u[constraint_index + 3] = x0_(3, 0); constraint_index += 4; for (int i = 1; i < horizon_; ++i) { g_l[constraint_index] = XYbounds_[0]; g_u[constraint_index] = XYbounds_[1]; g_l[constraint_index + 1] = XYbounds_[2]; g_u[constraint_index + 1] = XYbounds_[3]; g_l[constraint_index + 2] = -max_speed_reverse_; g_u[constraint_index + 2] = max_speed_forward_; constraint_index += 3; } // end configuration g_l[constraint_index] = xf_(0, 0); g_u[constraint_index] = xf_(0, 0); g_l[constraint_index + 1] = xf_(1, 0); g_u[constraint_index + 1] = xf_(1, 0); g_l[constraint_index + 2] = xf_(2, 0); g_u[constraint_index + 2] = xf_(2, 0); g_l[constraint_index + 3] = xf_(3, 0); g_u[constraint_index + 3] = xf_(3, 0); constraint_index += 4; for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = -max_steer_angle_; g_u[constraint_index] = max_steer_angle_; g_l[constraint_index + 1] = -max_acceleration_reverse_; g_u[constraint_index + 1] = max_acceleration_forward_; constraint_index += 2; } for (int i = 0; i < horizon_ + 1; ++i) { if (!use_fix_time_) { g_l[constraint_index] = min_time_sample_scaling_; g_u[constraint_index] = max_time_sample_scaling_; } else { g_l[constraint_index] = 1.0; g_u[constraint_index] = 1.0; } constraint_index++; } ADEBUG << "constraint_index after adding obstacles constraints: " << constraint_index; ADEBUG << "get_bounds_info_ out"; return true; } bool DistanceApproachIPOPTFixedDualInterface::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) { ADEBUG << "get_starting_point"; ACHECK(init_x) << "Warm start init_x setting failed"; CHECK_EQ(horizon_, uWS_.cols()); CHECK_EQ(horizon_ + 1, xWS_.cols()); // 1. state variables 4 * (horizon_ + 1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * 4; for (int j = 0; j < 4; ++j) { x[index + j] = xWS_(j, i); } } // 2. control variable initialization, 2 * horizon_ for (int i = 0; i < horizon_; ++i) { int index = i * 2; x[control_start_index_ + index] = uWS_(0, i); x[control_start_index_ + index + 1] = uWS_(1, i); } // 3. time scale variable initialization, horizon_ + 1 for (int i = 0; i < horizon_ + 1; ++i) { x[time_start_index_ + i] = 0.5 * (min_time_sample_scaling_ + max_time_sample_scaling_); } // check initial states if (distance_approach_config_.enable_check_initial_state()) { int kM = m; double g[kM]; eval_g(n, x, true, m, g); check_g(n, x, m, g); } ADEBUG << "get_starting_point out"; return true; } bool DistanceApproachIPOPTFixedDualInterface::eval_f(int n, const double* x, bool new_x, double& obj_value) { eval_obj(n, x, &obj_value); return true; } bool DistanceApproachIPOPTFixedDualInterface::eval_grad_f(int n, const double* x, bool new_x, double* grad_f) { gradient(tag_f, n, x, grad_f); return true; } bool DistanceApproachIPOPTFixedDualInterface::eval_g(int n, const double* x, bool new_x, int m, double* g) { eval_constraints(n, x, m, g); // if (enable_constraint_check_) check_g(n, x, m, g); return true; } bool DistanceApproachIPOPTFixedDualInterface::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) { ADEBUG << "nnz_jac: " << nnz_jac; // return the structure of the jacobian for (int idx = 0; idx < nnz_jac; idx++) { iRow[idx] = rind_g[idx]; jCol[idx] = cind_g[idx]; } } else { // return the values of the jacobian of the constraints sparse_jac(tag_g, m, n, 1, x, &nnz_jac, &rind_g, &cind_g, &jacval, options_g); for (int idx = 0; idx < nnz_jac; idx++) { values[idx] = jacval[idx]; } } return true; } bool DistanceApproachIPOPTFixedDualInterface::eval_jac_g_ser( int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { AERROR << "not ready ATM!"; return false; } bool DistanceApproachIPOPTFixedDualInterface::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) { // return the structure. This is a symmetric matrix, fill the lower left // triangle only. for (int idx = 0; idx < nnz_L; idx++) { iRow[idx] = rind_L[idx]; jCol[idx] = cind_L[idx]; } } else { // return the values. This is a symmetric matrix, fill the lower left // triangle only obj_lam[0] = obj_factor; for (int idx = 0; idx < m; idx++) { obj_lam[1 + idx] = lambda[idx]; } set_param_vec(tag_L, m + 1, obj_lam); sparse_hess(tag_L, n, 1, const_cast<double*>(x), &nnz_L, &rind_L, &cind_L, &hessval, options_L); for (int idx = 0; idx < nnz_L; idx++) { values[idx] = hessval[idx]; } } return true; } void DistanceApproachIPOPTFixedDualInterface::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) { int state_index = state_start_index_; int control_index = control_start_index_; int time_index = time_start_index_; int dual_l_index = l_start_index_; int dual_n_index = n_start_index_; // enable_constraint_check_: for debug only if (enable_constraint_check_) { ADEBUG << "final resolution constraint checking"; check_g(n, x, m, g); } // 1. state variables, 4 * [0, horizon] // 2. control variables, 2 * [0, horizon_-1] // 3. sampling time variables, 1 * [0, horizon_] // 4. dual_l obstacles_edges_sum_ * [0, horizon] // 5. dual_n obstacles_num * [0, horizon] for (int i = 0; i < horizon_; ++i) { state_result_(0, i) = x[state_index]; state_result_(1, i) = x[state_index + 1]; state_result_(2, i) = x[state_index + 2]; state_result_(3, i) = x[state_index + 3]; control_result_(0, i) = x[control_index]; control_result_(1, i) = x[control_index + 1]; time_result_(0, i) = ts_ * x[time_index]; for (int j = 0; j < obstacles_edges_sum_; ++j) { dual_l_result_(j, i) = x[dual_l_index + j]; } for (int k = 0; k < 4 * obstacles_num_; k++) { dual_n_result_(k, i) = x[dual_n_index + k]; } state_index += 4; control_index += 2; time_index++; dual_l_index += obstacles_edges_sum_; dual_n_index += 4 * obstacles_num_; } state_result_(0, 0) = x0_(0, 0); state_result_(1, 0) = x0_(1, 0); state_result_(2, 0) = x0_(2, 0); state_result_(3, 0) = x0_(3, 0); // push back last horizon for states state_result_(0, horizon_) = xf_(0, 0); state_result_(1, horizon_) = xf_(1, 0); state_result_(2, horizon_) = xf_(2, 0); state_result_(3, horizon_) = xf_(3, 0); for (int j = 0; j < obstacles_edges_sum_; ++j) { dual_l_result_(j, horizon_) = 0.0; } for (int k = 0; k < 4 * obstacles_num_; k++) { dual_n_result_(k, horizon_) = 0.0; } // memory deallocation of ADOL-C variables delete[] obj_lam; free(rind_g); free(cind_g); free(jacval); free(rind_L); free(cind_L); free(hessval); } void DistanceApproachIPOPTFixedDualInterface::get_optimization_results( Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) const { ADEBUG << "get_optimization_results"; *state_result = state_result_; *control_result = control_result_; *time_result = time_result_; *dual_l_result = dual_l_result_; *dual_n_result = dual_n_result_; if (!distance_approach_config_.enable_initial_final_check()) { return; } CHECK_EQ(state_result_.cols(), xWS_.cols()); CHECK_EQ(state_result_.rows(), xWS_.rows()); double state_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4; ++j) { state_diff_max = std::max(std::abs(xWS_(j, i) - state_result_(j, i)), state_diff_max); } } // 2. control variable initialization, 2 * horizon_ CHECK_EQ(control_result_.cols(), uWS_.cols()); CHECK_EQ(control_result_.rows(), uWS_.rows()); double control_diff_max = 0.0; for (int i = 0; i < horizon_; ++i) { control_diff_max = std::max(std::abs(uWS_(0, i) - control_result_(0, i)), control_diff_max); control_diff_max = std::max(std::abs(uWS_(1, i) - control_result_(1, i)), control_diff_max); } // 2. time scale variable initialization, horizon_ + 1 // 3. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1) CHECK_EQ(dual_l_result_.cols(), l_warm_up_.cols()); CHECK_EQ(dual_l_result_.rows(), l_warm_up_.rows()); double l_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { l_diff_max = std::max(std::abs(l_warm_up_(j, i) - dual_l_result_(j, i)), l_diff_max); } } // 4. lagrange constraint m, 4*obstacles_num * (horizon_+1) CHECK_EQ(n_warm_up_.cols(), dual_n_result_.cols()); CHECK_EQ(n_warm_up_.rows(), dual_n_result_.rows()); double n_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { n_diff_max = std::max(std::abs(n_warm_up_(j, i) - dual_n_result_(j, i)), n_diff_max); } } ADEBUG << "state_diff_max: " << state_diff_max; ADEBUG << "control_diff_max: " << control_diff_max; ADEBUG << "dual_l_diff_max: " << l_diff_max; ADEBUG << "dual_n_diff_max: " << n_diff_max; } //*************** start ADOL-C part *********************************** template <class T> void DistanceApproachIPOPTFixedDualInterface::eval_obj(int n, const T* x, T* obj_value) { // Objective is : // min control inputs // min input rate // min time (if the time step is not fixed) // regularization wrt warm start trajectory DCHECK(ts_ != 0) << "ts in distance_approach_ is 0"; int control_index = control_start_index_; int time_index = time_start_index_; int state_index = state_start_index_; // TODO(QiL): Initial implementation towards earlier understanding and debug // purpose, later code refine towards improving efficiency *obj_value = 0.0; // 1. objective to minimize state diff to warm up for (int i = 0; i < horizon_ + 1; ++i) { T x1_diff = x[state_index] - xWS_(0, i); T x2_diff = x[state_index + 1] - xWS_(1, i); T x3_diff = x[state_index + 2] - xWS_(2, i); T x4_abs = x[state_index + 3]; *obj_value += weight_state_x_ * x1_diff * x1_diff + weight_state_y_ * x2_diff * x2_diff + weight_state_phi_ * x3_diff * x3_diff + weight_state_v_ * x4_abs * x4_abs; state_index += 4; } // 2. objective to minimize u square for (int i = 0; i < horizon_; ++i) { *obj_value += weight_input_steer_ * x[control_index] * x[control_index] + weight_input_a_ * x[control_index + 1] * x[control_index + 1]; control_index += 2; } // 3. objective to minimize input change rate for first horizon control_index = control_start_index_; T last_time_steer_rate = (x[control_index] - last_time_u_(0, 0)) / x[time_index] / ts_; T last_time_a_rate = (x[control_index + 1] - last_time_u_(1, 0)) / x[time_index] / ts_; *obj_value += weight_stitching_steer_ * last_time_steer_rate * last_time_steer_rate + weight_stitching_a_ * last_time_a_rate * last_time_a_rate; // 4. objective to minimize input change rates, [0- horizon_ -2] time_index++; for (int i = 0; i < horizon_ - 1; ++i) { T steering_rate = (x[control_index + 2] - x[control_index]) / x[time_index] / ts_; T a_rate = (x[control_index + 3] - x[control_index + 1]) / x[time_index] / ts_; *obj_value += weight_rate_steer_ * steering_rate * steering_rate + weight_rate_a_ * a_rate * a_rate; control_index += 2; time_index++; } // 5. objective to minimize total time [0, horizon_] time_index = time_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { T first_order_penalty = weight_first_order_time_ * x[time_index]; T second_order_penalty = weight_second_order_time_ * x[time_index] * x[time_index]; *obj_value += first_order_penalty + second_order_penalty; time_index++; } } template <class T> void DistanceApproachIPOPTFixedDualInterface::eval_constraints(int n, const T* x, int m, T* g) { // state start index int state_index = state_start_index_; // control start index. int control_index = control_start_index_; // time start index int time_index = time_start_index_; int constraint_index = 0; // 1. state constraints 4 * [0, horizons-1] for (int i = 0; i < horizon_; ++i) { // x1 g[constraint_index] = x[state_index + 4] - (x[state_index] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * cos(x[state_index + 2] + ts_ * x[time_index] * 0.5 * x[state_index + 3] * tan(x[control_index]) / wheelbase_)); // x2 g[constraint_index + 1] = x[state_index + 5] - (x[state_index + 1] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * sin(x[state_index + 2] + ts_ * x[time_index] * 0.5 * x[state_index + 3] * tan(x[control_index]) / wheelbase_)); // x3 g[constraint_index + 2] = x[state_index + 6] - (x[state_index + 2] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * tan(x[control_index]) / wheelbase_); // x4 g[constraint_index + 3] = x[state_index + 7] - (x[state_index + 3] + ts_ * x[time_index] * x[control_index + 1]); control_index += 2; constraint_index += 4; time_index++; state_index += 4; } ADEBUG << "constraint_index after adding Euler forward dynamics constraints " "updated: " << constraint_index; // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply // steering rate as of now control_index = control_start_index_; time_index = time_start_index_; // First rate is compare first with stitch point g[constraint_index] = (x[control_index] - last_time_u_(0, 0)) / x[time_index] / ts_; control_index += 2; constraint_index++; time_index++; for (int i = 1; i < horizon_; ++i) { g[constraint_index] = (x[control_index] - x[control_index - 2]) / x[time_index] / ts_; constraint_index++; control_index += 2; time_index++; } // 3. Time constraints 1 * [0, horizons-1] time_index = time_start_index_; for (int i = 0; i < horizon_; ++i) { g[constraint_index] = x[time_index + 1] - x[time_index]; constraint_index++; time_index++; } ADEBUG << "constraint_index after adding time constraints " "updated: " << constraint_index; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 state_index = state_start_index_; // 5. load variable bounds as constraints state_index = state_start_index_; control_index = control_start_index_; time_index = time_start_index_; // start configuration g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 2]; g[constraint_index + 3] = x[state_index + 3]; constraint_index += 4; state_index += 4; // constraints on x,y,v for (int i = 1; i < horizon_; ++i) { g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 3]; constraint_index += 3; state_index += 4; } // end configuration g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 2]; g[constraint_index + 3] = x[state_index + 3]; constraint_index += 4; state_index += 4; for (int i = 0; i < horizon_; ++i) { g[constraint_index] = x[control_index]; g[constraint_index + 1] = x[control_index + 1]; constraint_index += 2; control_index += 2; } for (int i = 0; i < horizon_ + 1; ++i) { g[constraint_index] = x[time_index]; constraint_index++; time_index++; } ADEBUG << "constraint_index after adding variable box constraints updated: " << constraint_index; } bool DistanceApproachIPOPTFixedDualInterface::check_g(int n, const double* x, int m, const double* g) { int kN = n; int kM = m; double x_u_tmp[kN]; double x_l_tmp[kN]; double g_u_tmp[kM]; double g_l_tmp[kM]; get_bounds_info(n, x_l_tmp, x_u_tmp, m, g_l_tmp, g_u_tmp); const double delta_v = 1e-4; for (int idx = 0; idx < n; ++idx) { x_u_tmp[idx] = x_u_tmp[idx] + delta_v; x_l_tmp[idx] = x_l_tmp[idx] - delta_v; if (x[idx] > x_u_tmp[idx] || x[idx] < x_l_tmp[idx]) { AINFO << "x idx unfeasible: " << idx << ", x: " << x[idx] << ", lower: " << x_l_tmp[idx] << ", upper: " << x_u_tmp[idx]; } } // m1 : dynamics constatins int m1 = 4 * horizon_; // m2 : control rate constraints (only steering) int m2 = m1 + horizon_; // m3 : sampling time equality constraints int m3 = m2 + horizon_; // m4 : obstacle constraints // int m4 = m3 + 4 * obstacles_num_ * (horizon_ + 1); // 5. load variable bounds as constraints // start configuration int m5 = m3 + 3 + 1; // constraints on x,y,v int m6 = m5 + 3 * (horizon_ - 1); // end configuration int m7 = m6 + 3 + 1; // control variable bnd int m8 = m7 + 2 * horizon_; // time interval variable bnd int m9 = m8 + (horizon_ + 1); // lambda_horizon_ // int m10 = m9 + lambda_horizon_; // miu_horizon_ // int m11 = m10 + miu_horizon_; CHECK_EQ(m9, num_of_constraints_); AINFO << "dynamics constatins to: " << m1; AINFO << "control rate constraints (only steering) to: " << m2; AINFO << "sampling time equality constraints to: " << m3; AINFO << "start conf constraints to: " << m5; AINFO << "constraints on x,y,v to: " << m6; AINFO << "end constraints to: " << m7; AINFO << "control bnd to: " << m8; AINFO << "time interval constraints to: " << m9; AINFO << "total constraints: " << num_of_constraints_; for (int idx = 0; idx < m; ++idx) { if (g[idx] > g_u_tmp[idx] + delta_v || g[idx] < g_l_tmp[idx] - delta_v) { AINFO << "constratins idx unfeasible: " << idx << ", g: " << g[idx] << ", lower: " << g_l_tmp[idx] << ", upper: " << g_u_tmp[idx]; } } return true; } void DistanceApproachIPOPTFixedDualInterface::generate_tapes(int n, int m, int* nnz_jac_g, int* nnz_h_lag) { std::vector<double> xp(n); std::vector<double> lamp(m); std::vector<double> zl(m); std::vector<double> zu(m); std::vector<adouble> xa(n); std::vector<adouble> g(m); std::vector<double> lam(m); double sig; adouble obj_value; double dummy = 0.0; obj_lam = new double[m + 1]; get_starting_point(n, 1, &xp[0], 0, &zl[0], &zu[0], m, 0, &lamp[0]); trace_on(tag_f); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_obj(n, &xa[0], &obj_value); obj_value >>= dummy; trace_off(); trace_on(tag_g); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { g[idx] >>= dummy; } trace_off(); trace_on(tag_L); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } for (int idx = 0; idx < m; idx++) { lam[idx] = 1.0; } sig = 1.0; eval_obj(n, &xa[0], &obj_value); obj_value *= mkparam(sig); eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { obj_value += g[idx] * mkparam(lam[idx]); } obj_value >>= dummy; trace_off(); rind_g = nullptr; cind_g = nullptr; jacval = nullptr; options_g[0] = 0; /* sparsity pattern by index domains (default) */ options_g[1] = 0; /* safe mode (default) */ options_g[2] = 0; options_g[3] = 0; /* column compression (default) */ sparse_jac(tag_g, m, n, 0, &xp[0], &nnz_jac, &rind_g, &cind_g, &jacval, options_g); *nnz_jac_g = nnz_jac; rind_L = nullptr; cind_L = nullptr; hessval = nullptr; options_L[0] = 0; options_L[1] = 1; sparse_hess(tag_L, n, 0, &xp[0], &nnz_L, &rind_L, &cind_L, &hessval, options_L); *nnz_h_lag = nnz_L; } //*************** end ADOL-C part *********************************** } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_osqp_interface.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 <limits> #include <vector> #include "Eigen/Dense" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/planning/proto/planner_open_space_config.pb.h" #include "osqp/osqp.h" namespace apollo { namespace planning { class DualVariableWarmStartOSQPInterface { public: DualVariableWarmStartOSQPInterface( size_t horizon, double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const Eigen::MatrixXd& xWS, const PlannerOpenSpaceConfig& planner_open_space_config); virtual ~DualVariableWarmStartOSQPInterface() = default; void get_optimization_results(Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up) const; bool optimize(); void assemble_P(std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr); void assemble_constraint(std::vector<c_float>* A_data, std::vector<c_int>* A_indices, std::vector<c_int>* A_indptr); void assembleA(const int r, const int c, const std::vector<c_float>& P_data, const std::vector<c_int>& P_indices, const std::vector<c_int>& P_indptr); void check_solution(const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up); private: OSQPConfig osqp_config_; int num_of_variables_; int num_of_constraints_; int horizon_; double ts_; Eigen::MatrixXd ego_; int lambda_horizon_ = 0; int miu_horizon_ = 0; Eigen::MatrixXd l_warm_up_; Eigen::MatrixXd n_warm_up_; double wheelbase_; double w_ev_; double l_ev_; std::vector<double> g_; double offset_; Eigen::MatrixXi obstacles_edges_num_; int obstacles_num_; int obstacles_edges_sum_; double min_safety_distance_; // lagrangian l start index int l_start_index_ = 0; // lagrangian n start index int n_start_index_ = 0; // obstacles_A Eigen::MatrixXd obstacles_A_; // obstacles_b Eigen::MatrixXd obstacles_b_; // states of warm up stage Eigen::MatrixXd xWS_; // constraint A matrix in eigen format Eigen::MatrixXf constraint_A_; bool check_mode_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_cuda_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 */ #include "modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_cuda_interface.h" #include <algorithm> #include <limits> #if USE_GPU == 1 #include "modules/planning/open_space/trajectory_smoother/planning_block.h" #endif namespace apollo { namespace planning { DistanceApproachIPOPTCUDAInterface::DistanceApproachIPOPTCUDAInterface( const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xf, const Eigen::MatrixXd& last_time_u, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const PlannerOpenSpaceConfig& planner_open_space_config) : ts_(ts), ego_(ego), xWS_(xWS), uWS_(uWS), l_warm_up_(l_warm_up), n_warm_up_(n_warm_up), x0_(x0), xf_(xf), last_time_u_(last_time_u), XYbounds_(XYbounds), obstacles_edges_num_(obstacles_edges_num), obstacles_A_(obstacles_A), obstacles_b_(obstacles_b) { ACHECK(horizon < std::numeric_limits<int>::max()) << "Invalid cast on horizon in open space planner"; horizon_ = static_cast<int>(horizon); ACHECK(obstacles_num < std::numeric_limits<int>::max()) << "Invalid cast on obstacles_num in open space planner"; obstacles_num_ = static_cast<int>(obstacles_num); w_ev_ = ego_(1, 0) + ego_(3, 0); l_ev_ = ego_(0, 0) + ego_(2, 0); g_ = {l_ev_ / 2, w_ev_ / 2, l_ev_ / 2, w_ev_ / 2}; offset_ = (ego_(0, 0) + ego_(2, 0)) / 2 - ego_(2, 0); obstacles_edges_sum_ = obstacles_edges_num_.sum(); state_result_ = Eigen::MatrixXd::Zero(4, horizon_ + 1); dual_l_result_ = Eigen::MatrixXd::Zero(obstacles_edges_sum_, horizon_ + 1); dual_n_result_ = Eigen::MatrixXd::Zero(4 * obstacles_num_, horizon_ + 1); control_result_ = Eigen::MatrixXd::Zero(2, horizon_ + 1); time_result_ = Eigen::MatrixXd::Zero(1, horizon_ + 1); state_start_index_ = 0; control_start_index_ = 4 * (horizon_ + 1); time_start_index_ = control_start_index_ + 2 * horizon_; l_start_index_ = time_start_index_ + (horizon_ + 1); n_start_index_ = l_start_index_ + obstacles_edges_sum_ * (horizon_ + 1); planner_open_space_config_ = planner_open_space_config; distance_approach_config_ = planner_open_space_config_.distance_approach_config(); weight_state_x_ = distance_approach_config_.weight_x(); weight_state_y_ = distance_approach_config_.weight_y(); weight_state_phi_ = distance_approach_config_.weight_phi(); weight_state_v_ = distance_approach_config_.weight_v(); weight_input_steer_ = distance_approach_config_.weight_steer(); weight_input_a_ = distance_approach_config_.weight_a(); weight_rate_steer_ = distance_approach_config_.weight_steer_rate(); weight_rate_a_ = distance_approach_config_.weight_a_rate(); weight_stitching_steer_ = distance_approach_config_.weight_steer_stitching(); weight_stitching_a_ = distance_approach_config_.weight_a_stitching(); weight_first_order_time_ = distance_approach_config_.weight_first_order_time(); weight_second_order_time_ = distance_approach_config_.weight_second_order_time(); min_safety_distance_ = distance_approach_config_.min_safety_distance(); max_steer_angle_ = vehicle_param_.max_steer_angle() / vehicle_param_.steer_ratio(); max_speed_forward_ = distance_approach_config_.max_speed_forward(); max_speed_reverse_ = distance_approach_config_.max_speed_reverse(); max_acceleration_forward_ = distance_approach_config_.max_acceleration_forward(); max_acceleration_reverse_ = distance_approach_config_.max_acceleration_reverse(); min_time_sample_scaling_ = distance_approach_config_.min_time_sample_scaling(); max_time_sample_scaling_ = distance_approach_config_.max_time_sample_scaling(); max_steer_rate_ = vehicle_param_.max_steer_angle_rate() / vehicle_param_.steer_ratio(); use_fix_time_ = distance_approach_config_.use_fix_time(); wheelbase_ = vehicle_param_.wheel_base(); enable_constraint_check_ = distance_approach_config_.enable_constraint_check(); } bool DistanceApproachIPOPTCUDAInterface::get_nlp_info( int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) { ADEBUG << "get_nlp_info"; // n1 : states variables, 4 * (N+1) int n1 = 4 * (horizon_ + 1); ADEBUG << "n1: " << n1; // n2 : control inputs variables int n2 = 2 * horizon_; ADEBUG << "n2: " << n2; // n3 : sampling time variables int n3 = horizon_ + 1; ADEBUG << "n3: " << n3; // n4 : dual multiplier associated with obstacle shape lambda_horizon_ = obstacles_edges_num_.sum() * (horizon_ + 1); ADEBUG << "lambda_horizon_: " << lambda_horizon_; // n5 : dual multipier associated with car shape, obstacles_num*4 * (N+1) miu_horizon_ = obstacles_num_ * 4 * (horizon_ + 1); ADEBUG << "miu_horizon_: " << miu_horizon_; // m1 : dynamics constatins int m1 = 4 * horizon_; // m2 : control rate constraints (only steering) int m2 = horizon_; // m3 : sampling time equality constraints int m3 = horizon_; // m4 : obstacle constraints int m4 = 4 * obstacles_num_ * (horizon_ + 1); num_of_variables_ = n1 + n2 + n3 + lambda_horizon_ + miu_horizon_; num_of_constraints_ = m1 + m2 + m3 + m4 + (num_of_variables_ - (horizon_ + 1) + 2); // number of variables n = num_of_variables_; ADEBUG << "num_of_variables_ " << num_of_variables_; // number of constraints m = num_of_constraints_; ADEBUG << "num_of_constraints_ " << num_of_constraints_; generate_tapes(n, m, &nnz_h_lag); // // number of nonzero in Jacobian. int tmp = 0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); tmp += current_edges_num * 4 + 9 + 4; } } nnz_jac_g = 24 * horizon_ + 3 * horizon_ + 2 * horizon_ + tmp - 1 + (num_of_variables_ - (horizon_ + 1) + 2); index_style = IndexStyleEnum::C_STYLE; ADEBUG << "get_nlp_info out"; return true; } bool DistanceApproachIPOPTCUDAInterface::get_bounds_info(int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) { ADEBUG << "get_bounds_info"; ACHECK(XYbounds_.size() == 4) << "XYbounds_ size is not 4, but" << XYbounds_.size(); // Variables: includes state, u, sample time and lagrange multipliers // 1. state variables, 4 * [0, horizon] // start point pose int variable_index = 0; for (int i = 0; i < 4; ++i) { x_l[i] = -2e19; x_u[i] = 2e19; } variable_index += 4; // During horizons, 2 ~ N-1 for (int i = 1; i < horizon_; ++i) { // x x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // y x_l[variable_index + 1] = -2e19; x_u[variable_index + 1] = 2e19; // phi x_l[variable_index + 2] = -2e19; x_u[variable_index + 2] = 2e19; // v x_l[variable_index + 3] = -2e19; x_u[variable_index + 3] = 2e19; variable_index += 4; } // end point pose for (int i = 0; i < 4; ++i) { x_l[variable_index + i] = -2e19; x_u[variable_index + i] = 2e19; } variable_index += 4; ADEBUG << "variable_index after adding state variables : " << variable_index; // 2. control variables, 2 * [0, horizon_-1] for (int i = 0; i < horizon_; ++i) { // u1 x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; // u2 x_l[variable_index + 1] = -2e19; x_u[variable_index + 1] = 2e19; variable_index += 2; } ADEBUG << "variable_index after adding control variables : " << variable_index; // 3. sampling time variables, 1 * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { x_l[variable_index] = -2e19; x_u[variable_index] = 2e19; ++variable_index; } ADEBUG << "variable_index after adding sample time : " << variable_index; ADEBUG << "sample time fix time status is : " << use_fix_time_; // 4. lagrange constraint l, [0, obstacles_edges_sum_ - 1] * [0, // horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { x_l[variable_index] = 0.0; x_u[variable_index] = 2e19; // nlp_upper_bound_limit ++variable_index; } } ADEBUG << "variable_index after adding lagrange l : " << variable_index; // 5. lagrange constraint n, [0, 4*obstacles_num-1] * [0, horizon_] for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { x_l[variable_index] = 0.0; x_u[variable_index] = 2e19; // nlp_upper_bound_limit ++variable_index; } } ADEBUG << "variable_index after adding lagrange n : " << variable_index; // Constraints: includes four state Euler forward constraints, three // Obstacle related constraints // 1. dynamics constraints 4 * [0, horizons-1] int constraint_index = 0; for (int i = 0; i < 4 * horizon_; ++i) { g_l[i] = 0.0; g_u[i] = 0.0; } constraint_index += 4 * horizon_; ADEBUG << "constraint_index after adding Euler forward dynamics constraints: " << constraint_index; // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply // steering rate as of now for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = -max_steer_rate_; g_u[constraint_index] = max_steer_rate_; ++constraint_index; } ADEBUG << "constraint_index after adding steering rate constraints: " << constraint_index; // 3. Time constraints 1 * [0, horizons-1] for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 0.0; ++constraint_index; } ADEBUG << "constraint_index after adding time constraints: " << constraint_index; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { // a. norm(A'*lambda) <= 1 g_l[constraint_index] = -2e19; g_u[constraint_index] = 1.0; // b. G'*mu + R'*A*lambda = 0 g_l[constraint_index + 1] = 0.0; g_u[constraint_index + 1] = 0.0; g_l[constraint_index + 2] = 0.0; g_u[constraint_index + 2] = 0.0; // c. -g'*mu + (A*t - b)*lambda > min_safety_distance_ g_l[constraint_index + 3] = min_safety_distance_; g_u[constraint_index + 3] = 2e19; // nlp_upper_bound_limit constraint_index += 4; } } // 5. load variable bounds as constraints // start configuration g_l[constraint_index] = x0_(0, 0); g_u[constraint_index] = x0_(0, 0); g_l[constraint_index + 1] = x0_(1, 0); g_u[constraint_index + 1] = x0_(1, 0); g_l[constraint_index + 2] = x0_(2, 0); g_u[constraint_index + 2] = x0_(2, 0); g_l[constraint_index + 3] = x0_(3, 0); g_u[constraint_index + 3] = x0_(3, 0); constraint_index += 4; for (int i = 1; i < horizon_; ++i) { g_l[constraint_index] = XYbounds_[0]; g_u[constraint_index] = XYbounds_[1]; g_l[constraint_index + 1] = XYbounds_[2]; g_u[constraint_index + 1] = XYbounds_[3]; g_l[constraint_index + 2] = -max_speed_reverse_; g_u[constraint_index + 2] = max_speed_forward_; constraint_index += 3; } // end configuration g_l[constraint_index] = xf_(0, 0); g_u[constraint_index] = xf_(0, 0); g_l[constraint_index + 1] = xf_(1, 0); g_u[constraint_index + 1] = xf_(1, 0); g_l[constraint_index + 2] = xf_(2, 0); g_u[constraint_index + 2] = xf_(2, 0); g_l[constraint_index + 3] = xf_(3, 0); g_u[constraint_index + 3] = xf_(3, 0); constraint_index += 4; for (int i = 0; i < horizon_; ++i) { g_l[constraint_index] = -max_steer_angle_; g_u[constraint_index] = max_steer_angle_; g_l[constraint_index + 1] = -max_acceleration_reverse_; g_u[constraint_index + 1] = max_acceleration_forward_; constraint_index += 2; } for (int i = 0; i < horizon_ + 1; ++i) { if (!use_fix_time_) { g_l[constraint_index] = min_time_sample_scaling_; g_u[constraint_index] = max_time_sample_scaling_; } else { g_l[constraint_index] = 1.0; g_u[constraint_index] = 1.0; } constraint_index++; } for (int i = 0; i < lambda_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; } for (int i = 0; i < miu_horizon_; ++i) { g_l[constraint_index] = 0.0; g_u[constraint_index] = 2e19; constraint_index++; } ADEBUG << "constraint_index after adding obstacles constraints: " << constraint_index; ADEBUG << "get_bounds_info_ out"; return true; } bool DistanceApproachIPOPTCUDAInterface::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) { ADEBUG << "get_starting_point"; ACHECK(init_x) << "Warm start init_x setting failed"; CHECK_EQ(horizon_, uWS_.cols()); CHECK_EQ(horizon_ + 1, xWS_.cols()); // 1. state variables 4 * (horizon_ + 1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * 4; for (int j = 0; j < 4; ++j) { x[index + j] = xWS_(j, i); } } // 2. control variable initialization, 2 * horizon_ for (int i = 0; i < horizon_; ++i) { int index = i * 2; x[control_start_index_ + index] = uWS_(0, i); x[control_start_index_ + index + 1] = uWS_(1, i); } // 2. time scale variable initialization, horizon_ + 1 for (int i = 0; i < horizon_ + 1; ++i) { x[time_start_index_ + i] = 0.5 * (min_time_sample_scaling_ + max_time_sample_scaling_); } // 3. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * obstacles_edges_sum_; for (int j = 0; j < obstacles_edges_sum_; ++j) { x[l_start_index_ + index + j] = l_warm_up_(j, i); } } // 4. lagrange constraint m, 4*obstacles_num * (horizon_+1) for (int i = 0; i < horizon_ + 1; ++i) { int index = i * 4 * obstacles_num_; for (int j = 0; j < 4 * obstacles_num_; ++j) { x[n_start_index_ + index + j] = n_warm_up_(j, i); } } ADEBUG << "get_starting_point out"; return true; } bool DistanceApproachIPOPTCUDAInterface::eval_f(int n, const double* x, bool new_x, double& obj_value) { eval_obj(n, x, &obj_value); return true; } bool DistanceApproachIPOPTCUDAInterface::eval_grad_f(int n, const double* x, bool new_x, double* grad_f) { gradient(tag_f, n, x, grad_f); return true; } bool DistanceApproachIPOPTCUDAInterface::eval_grad_f_hand(int n, const double* x, bool new_x, double* grad_f) { ADEBUG << "eval_grad_f by hand"; // Objective is from eval_f: // min control inputs // min input rate // min time (if the time step is not fixed) // regularization wrt warm start trajectory DCHECK(ts_ != 0) << "ts in distance_approach_ is 0"; int control_index = control_start_index_; int time_index = time_start_index_; int state_index = state_start_index_; if (grad_f == nullptr) { AERROR << "grad_f pt is nullptr"; return false; } else { std::fill(grad_f, grad_f + n, 0.0); // 1. objective to minimize state diff to warm up for (int i = 0; i < horizon_ + 1; ++i) { grad_f[state_index] += 2 * weight_state_x_ * (x[state_index] - xWS_(0, i)); grad_f[state_index + 1] += 2 * weight_state_y_ * (x[state_index + 1] - xWS_(1, i)); grad_f[state_index + 2] += 2 * weight_state_phi_ * (x[state_index + 2] - xWS_(2, i)); grad_f[state_index + 3] = 2 * weight_state_v_ * x[state_index + 3]; state_index += 4; } // 2. objective to minimize u square for (int i = 0; i < horizon_; ++i) { grad_f[control_index] += 2 * weight_input_steer_ * x[control_index]; grad_f[control_index + 1] += 2 * weight_input_a_ * x[control_index + 1]; control_index += 2; } // 3. objective to minimize input change rate for first horizon // assume: x[time_index] > 0 control_index = control_start_index_; double last_time_steer_rate = (x[control_index] - last_time_u_(0, 0)) / x[time_index] / ts_; double last_time_a_rate = (x[control_index + 1] - last_time_u_(1, 0)) / x[time_index] / ts_; grad_f[control_index] += 2.0 * last_time_steer_rate * (weight_stitching_steer_ / x[time_index] / ts_); grad_f[control_index + 1] += 2.0 * last_time_a_rate * (weight_stitching_a_ / x[time_index] / ts_); grad_f[time_index] += -2.0 * (weight_stitching_steer_ * last_time_steer_rate * last_time_steer_rate + weight_stitching_a_ * last_time_a_rate * last_time_a_rate) / x[time_index]; // 4. objective to minimize input change rates, [0- horizon_ -2] // assume: x[time_index] > 0 time_index++; for (int i = 0; i < horizon_ - 1; ++i) { double steering_rate = (x[control_index + 2] - x[control_index]) / x[time_index] / ts_; grad_f[control_index + 2] += 2.0 * steering_rate * (weight_rate_steer_ / x[time_index] / ts_); grad_f[control_index] += -2.0 * steering_rate * (weight_rate_steer_ / x[time_index] / ts_); grad_f[time_index] += -2.0 * weight_rate_steer_ * steering_rate * steering_rate / x[time_index]; double a_rate = (x[control_index + 3] - x[control_index + 1]) / x[time_index] / ts_; grad_f[control_index + 3] += 2.0 * a_rate * (weight_rate_a_ / x[time_index] / ts_); grad_f[control_index + 1] += -2.0 * a_rate * (weight_rate_a_ / x[time_index] / ts_); grad_f[time_index] += -2.0 * weight_rate_a_ * a_rate * a_rate / x[time_index]; control_index += 2; time_index++; } // 5. objective to minimize total time [0, horizon_] time_index = time_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { grad_f[time_index] += weight_first_order_time_ + 2.0 * weight_second_order_time_ * x[time_index]; time_index++; } } return true; } bool DistanceApproachIPOPTCUDAInterface::eval_g(int n, const double* x, bool new_x, int m, double* g) { eval_constraints(n, x, m, g); if (enable_constraint_check_) { check_g(n, x, m, g); } return true; } bool DistanceApproachIPOPTCUDAInterface::eval_jac_g(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { return eval_jac_g_ser(n, x, new_x, m, nele_jac, iRow, jCol, values); } bool DistanceApproachIPOPTCUDAInterface::eval_jac_g_par(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { ADEBUG << "eval_jac_g"; CHECK_EQ(n, num_of_variables_) << "No. of variables wrong in eval_jac_g. n : " << n; CHECK_EQ(m, num_of_constraints_) << "No. of constraints wrong in eval_jac_g. n : " << m; if (values == nullptr) { int nz_index = 0; int constraint_index = 0; int state_index = state_start_index_; int control_index = control_start_index_; int time_index = time_start_index_; // 1. State Constraint with respect to variables for (int i = 0; i < horizon_; ++i) { // g(0)' with respect to x0 ~ x7 iRow[nz_index] = state_index; jCol[nz_index] = state_index; ++nz_index; iRow[nz_index] = state_index; jCol[nz_index] = state_index + 2; ++nz_index; iRow[nz_index] = state_index; jCol[nz_index] = state_index + 3; ++nz_index; iRow[nz_index] = state_index; jCol[nz_index] = state_index + 4; ++nz_index; // g(0)' with respect to u0 ~ u1' iRow[nz_index] = state_index; jCol[nz_index] = control_index; ++nz_index; iRow[nz_index] = state_index; jCol[nz_index] = control_index + 1; ++nz_index; // g(0)' with respect to time iRow[nz_index] = state_index; jCol[nz_index] = time_index; ++nz_index; // g(1)' with respect to x0 ~ x7 iRow[nz_index] = state_index + 1; jCol[nz_index] = state_index + 1; ++nz_index; iRow[nz_index] = state_index + 1; jCol[nz_index] = state_index + 2; ++nz_index; iRow[nz_index] = state_index + 1; jCol[nz_index] = state_index + 3; ++nz_index; iRow[nz_index] = state_index + 1; jCol[nz_index] = state_index + 5; ++nz_index; // g(1)' with respect to u0 ~ u1' iRow[nz_index] = state_index + 1; jCol[nz_index] = control_index; ++nz_index; iRow[nz_index] = state_index + 1; jCol[nz_index] = control_index + 1; ++nz_index; // g(1)' with respect to time iRow[nz_index] = state_index + 1; jCol[nz_index] = time_index; ++nz_index; // g(2)' with respect to x0 ~ x7 iRow[nz_index] = state_index + 2; jCol[nz_index] = state_index + 2; ++nz_index; iRow[nz_index] = state_index + 2; jCol[nz_index] = state_index + 3; ++nz_index; iRow[nz_index] = state_index + 2; jCol[nz_index] = state_index + 6; ++nz_index; // g(2)' with respect to u0 ~ u1' iRow[nz_index] = state_index + 2; jCol[nz_index] = control_index; ++nz_index; iRow[nz_index] = state_index + 2; jCol[nz_index] = control_index + 1; ++nz_index; // g(2)' with respect to time iRow[nz_index] = state_index + 2; jCol[nz_index] = time_index; ++nz_index; // g(3)' with x0 ~ x7 iRow[nz_index] = state_index + 3; jCol[nz_index] = state_index + 3; ++nz_index; iRow[nz_index] = state_index + 3; jCol[nz_index] = state_index + 7; ++nz_index; // g(3)' with respect to u0 ~ u1' iRow[nz_index] = state_index + 3; jCol[nz_index] = control_index + 1; ++nz_index; // g(3)' with respect to time iRow[nz_index] = state_index + 3; jCol[nz_index] = time_index; ++nz_index; state_index += 4; control_index += 2; time_index++; constraint_index += 4; } // 2. only have control rate constraints on u0 , range [0, horizon_-1] control_index = control_start_index_; state_index = state_start_index_; time_index = time_start_index_; // First one, with respect to u(0, 0) iRow[nz_index] = constraint_index; jCol[nz_index] = control_index; ++nz_index; // First element, with respect to time iRow[nz_index] = constraint_index; jCol[nz_index] = time_index; ++nz_index; control_index += 2; time_index++; constraint_index++; for (int i = 1; i < horizon_; ++i) { // with respect to u(0, i-1) iRow[nz_index] = constraint_index; jCol[nz_index] = control_index - 2; ++nz_index; // with respect to u(0, i) iRow[nz_index] = constraint_index; jCol[nz_index] = control_index; ++nz_index; // with respect to time iRow[nz_index] = constraint_index; jCol[nz_index] = time_index; ++nz_index; // only consider rate limits on u0 control_index += 2; constraint_index++; time_index++; } // 3. Time constraints [0, horizon_ -1] time_index = time_start_index_; for (int i = 0; i < horizon_; ++i) { // with respect to timescale(0, i-1) iRow[nz_index] = constraint_index; jCol[nz_index] = time_index; ++nz_index; // with respect to timescale(0, i) iRow[nz_index] = constraint_index; jCol[nz_index] = time_index + 1; ++nz_index; time_index++; constraint_index++; } // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 state_index = state_start_index_; int l_index = l_start_index_; int n_index = n_start_index_; #pragma omp parallel for schedule(dynamic, 1) num_threads(4) for (int iter = 0; iter < (horizon_ + 1) * obstacles_num_; iter++) { int i = iter / obstacles_num_; int j = iter % obstacles_num_; int current_edges_num = obstacles_edges_num_(j, 0); int nz_index_tmp = nz_index; int l_index_tmp = l_index; // count nz_len for (int jj = 0; jj < obstacles_num_; ++jj) { if (jj < j) { nz_index_tmp += 4 * (i + 1) * obstacles_edges_num_(jj, 0); nz_index_tmp += 13 * (i + 1); l_index_tmp += (i + 1) * obstacles_edges_num_(jj, 0); } else { nz_index_tmp += 4 * i * obstacles_edges_num_(jj, 0); nz_index_tmp += 13 * i; l_index_tmp += i * obstacles_edges_num_(jj, 0); } } int n_index_tmp = n_index + (i * obstacles_num_ + j) * 4; int constraint_index_tmp = constraint_index + (i * obstacles_num_ + j) * 4; int state_index_tmp = state_index + i * 4; // 1. norm(A* lambda == 1) for (int k = 0; k < current_edges_num; ++k) { // with respect to l iRow[nz_index_tmp] = constraint_index_tmp; jCol[nz_index_tmp] = l_index_tmp + k; ++nz_index_tmp; // current_edges_num } // 2. G' * mu + R' * lambda == 0, part 1 // With respect to x iRow[nz_index_tmp] = constraint_index_tmp + 1; jCol[nz_index_tmp] = state_index_tmp + 2; ++nz_index_tmp; // 1 // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index_tmp] = constraint_index_tmp + 1; jCol[nz_index_tmp] = l_index_tmp + k; ++nz_index_tmp; // current_edges_num } // With respect to n iRow[nz_index_tmp] = constraint_index_tmp + 1; jCol[nz_index_tmp] = n_index_tmp; ++nz_index_tmp; // 1 iRow[nz_index_tmp] = constraint_index_tmp + 1; jCol[nz_index_tmp] = n_index_tmp + 2; ++nz_index_tmp; // 1 // 2. G' * mu + R' * lambda == 0, part 2 // With respect to x iRow[nz_index_tmp] = constraint_index_tmp + 2; jCol[nz_index_tmp] = state_index_tmp + 2; ++nz_index_tmp; // 1 // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index_tmp] = constraint_index_tmp + 2; jCol[nz_index_tmp] = l_index_tmp + k; ++nz_index_tmp; // current_edges_num } // With respect to n iRow[nz_index_tmp] = constraint_index_tmp + 2; jCol[nz_index_tmp] = n_index_tmp + 1; ++nz_index_tmp; // 1 iRow[nz_index_tmp] = constraint_index_tmp + 2; jCol[nz_index_tmp] = n_index_tmp + 3; ++nz_index_tmp; // 1 // 3. -g'*mu + (A*t - b)*lambda > 0 // With respect to x iRow[nz_index_tmp] = constraint_index_tmp + 3; jCol[nz_index_tmp] = state_index_tmp; ++nz_index_tmp; // 1 iRow[nz_index_tmp] = constraint_index_tmp + 3; jCol[nz_index_tmp] = state_index_tmp + 1; ++nz_index_tmp; // 1 iRow[nz_index_tmp] = constraint_index_tmp + 3; jCol[nz_index_tmp] = state_index_tmp + 2; ++nz_index_tmp; // 1 // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index_tmp] = constraint_index_tmp + 3; jCol[nz_index_tmp] = l_index_tmp + k; ++nz_index_tmp; // current_edges_num } // with respect to n for (int k = 0; k < 4; ++k) { iRow[nz_index_tmp] = constraint_index_tmp + 3; jCol[nz_index_tmp] = n_index_tmp + k; ++nz_index_tmp; // 4 } } // update index for (int jj = 0; jj < obstacles_num_; ++jj) { nz_index += 4 * (horizon_ + 1) * obstacles_edges_num_(jj, 0); nz_index += 13 * (horizon_ + 1); } constraint_index += 4 * (horizon_ + 1) * obstacles_num_; state_index += 4 * (horizon_ + 1); // 5. load variable bounds as constraints state_index = state_start_index_; control_index = control_start_index_; time_index = time_start_index_; l_index = l_start_index_; n_index = n_start_index_; // start configuration iRow[nz_index] = constraint_index; jCol[nz_index] = state_index; nz_index++; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = state_index + 1; nz_index++; iRow[nz_index] = constraint_index + 2; jCol[nz_index] = state_index + 2; nz_index++; iRow[nz_index] = constraint_index + 3; jCol[nz_index] = state_index + 3; nz_index++; constraint_index += 4; state_index += 4; for (int i = 1; i < horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = state_index; nz_index++; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = state_index + 1; nz_index++; iRow[nz_index] = constraint_index + 2; jCol[nz_index] = state_index + 3; nz_index++; constraint_index += 3; state_index += 4; } // end configuration iRow[nz_index] = constraint_index; jCol[nz_index] = state_index; nz_index++; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = state_index + 1; nz_index++; iRow[nz_index] = constraint_index + 2; jCol[nz_index] = state_index + 2; nz_index++; iRow[nz_index] = constraint_index + 3; jCol[nz_index] = state_index + 3; nz_index++; constraint_index += 4; state_index += 4; for (int i = 0; i < horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = control_index; nz_index++; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = control_index + 1; nz_index++; constraint_index += 2; control_index += 2; } for (int i = 0; i < horizon_ + 1; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = time_index; nz_index++; constraint_index++; time_index++; } for (int i = 0; i < lambda_horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = l_index; nz_index++; constraint_index++; l_index++; } for (int i = 0; i < miu_horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = n_index; nz_index++; constraint_index++; n_index++; } CHECK_EQ(nz_index, static_cast<int>(nele_jac)); CHECK_EQ(constraint_index, static_cast<int>(m)); } else { std::fill(values, values + nele_jac, 0.0); int nz_index = 0; int time_index = time_start_index_; int state_index = state_start_index_; int control_index = control_start_index_; // TODO(QiL) : initially implemented to be debug friendly, later iterate // towards better efficiency // 1. state constraints 4 * [0, horizons-1] for (int i = 0; i < horizon_; ++i) { values[nz_index] = -1.0; ++nz_index; values[nz_index] = x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_); // a. ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * (-1) * x[time_index] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_ * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // b ++nz_index; values[nz_index] = 1.0; ++nz_index; values[nz_index] = x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) * x[time_index] * ts_ * 0.5 * x[state_index + 3] / (std::cos(x[control_index]) * std::cos(x[control_index])) / wheelbase_; // c ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * x[time_index] * ts_ * 0.5 * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // d ++nz_index; values[nz_index] = -1.0 * (ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * ts_ * 0.5 * x[control_index + 1] * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) - x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * x[state_index + 3] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_ * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // e ++nz_index; values[nz_index] = -1.0; ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // f. ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * x[time_index] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_ * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // g ++nz_index; values[nz_index] = 1.0; ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) * x[time_index] * ts_ * 0.5 * x[state_index + 3] / (std::cos(x[control_index]) * std::cos(x[control_index])) / wheelbase_); // h ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * x[time_index] * ts_ * 0.5 * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // i ++nz_index; values[nz_index] = -1.0 * (ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * ts_ * 0.5 * x[control_index + 1] * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * x[state_index + 3] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_ * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // j ++nz_index; values[nz_index] = -1.0; ++nz_index; values[nz_index] = -1.0 * x[time_index] * ts_ * std::tan(x[control_index]) / wheelbase_; // k. ++nz_index; values[nz_index] = 1.0; ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) / (std::cos(x[control_index]) * std::cos(x[control_index])) / wheelbase_); // l. ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * x[time_index] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_); // m. ++nz_index; values[nz_index] = -1.0 * (ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::tan(x[control_index]) / wheelbase_ + x[time_index] * ts_ * ts_ * 0.5 * x[control_index + 1] * std::tan(x[control_index]) / wheelbase_); // n. ++nz_index; values[nz_index] = -1.0; ++nz_index; values[nz_index] = 1.0; ++nz_index; values[nz_index] = -1.0 * ts_ * x[time_index]; // o. ++nz_index; values[nz_index] = -1.0 * ts_ * x[control_index + 1]; // p. ++nz_index; state_index += 4; control_index += 2; time_index++; } // 2. control rate constraints 1 * [0, horizons-1] control_index = control_start_index_; state_index = state_start_index_; time_index = time_start_index_; // First horizon // with respect to u(0, 0) values[nz_index] = 1.0 / x[time_index] / ts_; // q ++nz_index; // with respect to time values[nz_index] = -1.0 * (x[control_index] - last_time_u_(0, 0)) / x[time_index] / x[time_index] / ts_; ++nz_index; time_index++; control_index += 2; for (int i = 1; i < horizon_; ++i) { // with respect to u(0, i-1) values[nz_index] = -1.0 / x[time_index] / ts_; ++nz_index; // with respect to u(0, i) values[nz_index] = 1.0 / x[time_index] / ts_; ++nz_index; // with respect to time values[nz_index] = -1.0 * (x[control_index] - x[control_index - 2]) / x[time_index] / x[time_index] / ts_; ++nz_index; control_index += 2; time_index++; } ADEBUG << "After fulfilled control rate constraints derivative, nz_index : " << nz_index << " nele_jac : " << nele_jac; // 3. Time constraints [0, horizon_ -1] time_index = time_start_index_; for (int i = 0; i < horizon_; ++i) { // with respect to timescale(0, i-1) values[nz_index] = -1.0; ++nz_index; // with respect to timescale(0, i) values[nz_index] = 1.0; ++nz_index; time_index++; } ADEBUG << "After fulfilled time constraints derivative, nz_index : " << nz_index << " nele_jac : " << nele_jac; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 state_index = state_start_index_; int l_index = l_start_index_; int n_index = n_start_index_; #pragma omp parallel for schedule(dynamic, 1) num_threads(4) for (int iter = 0; iter < (horizon_ + 1) * obstacles_num_; iter++) { int i = iter / obstacles_num_; int j = iter % obstacles_num_; int current_edges_num = obstacles_edges_num_(j, 0); int edges_counter = 0; int nz_index_tmp = nz_index; int l_index_tmp = l_index; // count nz_len for (int jj = 0; jj < obstacles_num_; ++jj) { if (jj < j) { nz_index_tmp += 4 * (i + 1) * obstacles_edges_num_(jj, 0); nz_index_tmp += 13 * (i + 1); l_index_tmp += (i + 1) * obstacles_edges_num_(jj, 0); edges_counter += obstacles_edges_num_(jj, 0); } else { nz_index_tmp += 4 * i * obstacles_edges_num_(jj, 0); nz_index_tmp += 13 * i; l_index_tmp += i * obstacles_edges_num_(jj, 0); } } int n_index_tmp = n_index + (i * obstacles_num_ + j) * 4; int state_index_tmp = state_index + i * 4; Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); // TODO(QiL) : Remove redundant calculation double tmp1 = 0; double tmp2 = 0; for (int k = 0; k < current_edges_num; ++k) { // TODO(QiL) : replace this one directly with x tmp1 += Aj(k, 0) * x[l_index_tmp + k]; tmp2 += Aj(k, 1) * x[l_index_tmp + k]; } // 1. norm(A* lambda == 1) for (int k = 0; k < current_edges_num; ++k) { // with respect to l values[nz_index_tmp] = 2 * tmp1 * Aj(k, 0) + 2 * tmp2 * Aj(k, 1); // t0~tk ++nz_index_tmp; // current_edges_num } // 2. G' * mu + R' * lambda == 0, part 1 // With respect to x values[nz_index_tmp] = -std::sin(x[state_index_tmp + 2]) * tmp1 + std::cos(x[state_index_tmp + 2]) * tmp2; // u ++nz_index_tmp; // 1 // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index_tmp] = std::cos(x[state_index_tmp + 2]) * Aj(k, 0) + std::sin(x[state_index_tmp + 2]) * Aj(k, 1); // v0~vn ++nz_index_tmp; // current_edges_num } // With respect to n values[nz_index_tmp] = 1.0; // w0 ++nz_index_tmp; // 1 values[nz_index_tmp] = -1.0; // w2 ++nz_index_tmp; // 1 // 3. G' * mu + R' * lambda == 0, part 2 // With respect to x values[nz_index_tmp] = -std::cos(x[state_index_tmp + 2]) * tmp1 - std::sin(x[state_index_tmp + 2]) * tmp2; // x ++nz_index_tmp; // 1 // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index_tmp] = -std::sin(x[state_index_tmp + 2]) * Aj(k, 0) + std::cos(x[state_index_tmp + 2]) * Aj(k, 1); // y0~yn ++nz_index_tmp; // current_edges_num } // With respect to n values[nz_index_tmp] = 1.0; // z1 ++nz_index_tmp; // 1 values[nz_index_tmp] = -1.0; // z3 ++nz_index_tmp; // 1 // 3. -g'*mu + (A*t - b)*lambda > 0 double tmp3 = 0.0; double tmp4 = 0.0; for (int k = 0; k < 4; ++k) { tmp3 += -g_[k] * x[n_index_tmp + k]; } for (int k = 0; k < current_edges_num; ++k) { tmp4 += bj(k, 0) * x[l_index_tmp + k]; } // With respect to x values[nz_index_tmp] = tmp1; // aa1 ++nz_index_tmp; // 1 values[nz_index_tmp] = tmp2; // bb1 ++nz_index_tmp; // 1 values[nz_index_tmp] = -std::sin(x[state_index_tmp + 2]) * offset_ * tmp1 + std::cos(x[state_index_tmp + 2]) * offset_ * tmp2; // cc1 ++nz_index_tmp; // 1 // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index_tmp] = (x[state_index_tmp] + std::cos(x[state_index_tmp + 2]) * offset_) * Aj(k, 0) + (x[state_index_tmp + 1] + std::sin(x[state_index_tmp + 2]) * offset_) * Aj(k, 1) - bj(k, 0); // ddk ++nz_index_tmp; // current_edges_num } // with respect to n for (int k = 0; k < 4; ++k) { values[nz_index_tmp] = -g_[k]; // eek ++nz_index_tmp; // 4 } } // update index for (int jj = 0; jj < obstacles_num_; ++jj) { nz_index += 4 * (horizon_ + 1) * obstacles_edges_num_(jj, 0); nz_index += 13 * (horizon_ + 1); } // 5. load variable bounds as constraints state_index = state_start_index_; control_index = control_start_index_; time_index = time_start_index_; l_index = l_start_index_; n_index = n_start_index_; // start configuration values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; for (int i = 1; i < horizon_; ++i) { values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; } // end configuration values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; for (int i = 0; i < horizon_; ++i) { values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; } for (int i = 0; i < horizon_ + 1; ++i) { values[nz_index] = 1.0; nz_index++; } for (int i = 0; i < lambda_horizon_; ++i) { values[nz_index] = 1.0; nz_index++; } for (int i = 0; i < miu_horizon_; ++i) { values[nz_index] = 1.0; nz_index++; } ADEBUG << "eval_jac_g, fulfilled obstacle constraint values"; CHECK_EQ(nz_index, static_cast<int>(nele_jac)); } ADEBUG << "eval_jac_g done"; return true; } // NOLINT bool DistanceApproachIPOPTCUDAInterface::eval_jac_g_ser(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { ADEBUG << "eval_jac_g"; CHECK_EQ(n, num_of_variables_) << "No. of variables wrong in eval_jac_g. n : " << n; CHECK_EQ(m, num_of_constraints_) << "No. of constraints wrong in eval_jac_g. n : " << m; if (values == nullptr) { int nz_index = 0; int constraint_index = 0; int state_index = state_start_index_; int control_index = control_start_index_; int time_index = time_start_index_; // 1. State Constraint with respect to variables for (int i = 0; i < horizon_; ++i) { // g(0)' with respect to x0 ~ x7 iRow[nz_index] = state_index; jCol[nz_index] = state_index; ++nz_index; iRow[nz_index] = state_index; jCol[nz_index] = state_index + 2; ++nz_index; iRow[nz_index] = state_index; jCol[nz_index] = state_index + 3; ++nz_index; iRow[nz_index] = state_index; jCol[nz_index] = state_index + 4; ++nz_index; // g(0)' with respect to u0 ~ u1' iRow[nz_index] = state_index; jCol[nz_index] = control_index; ++nz_index; iRow[nz_index] = state_index; jCol[nz_index] = control_index + 1; ++nz_index; // g(0)' with respect to time iRow[nz_index] = state_index; jCol[nz_index] = time_index; ++nz_index; // g(1)' with respect to x0 ~ x7 iRow[nz_index] = state_index + 1; jCol[nz_index] = state_index + 1; ++nz_index; iRow[nz_index] = state_index + 1; jCol[nz_index] = state_index + 2; ++nz_index; iRow[nz_index] = state_index + 1; jCol[nz_index] = state_index + 3; ++nz_index; iRow[nz_index] = state_index + 1; jCol[nz_index] = state_index + 5; ++nz_index; // g(1)' with respect to u0 ~ u1' iRow[nz_index] = state_index + 1; jCol[nz_index] = control_index; ++nz_index; iRow[nz_index] = state_index + 1; jCol[nz_index] = control_index + 1; ++nz_index; // g(1)' with respect to time iRow[nz_index] = state_index + 1; jCol[nz_index] = time_index; ++nz_index; // g(2)' with respect to x0 ~ x7 iRow[nz_index] = state_index + 2; jCol[nz_index] = state_index + 2; ++nz_index; iRow[nz_index] = state_index + 2; jCol[nz_index] = state_index + 3; ++nz_index; iRow[nz_index] = state_index + 2; jCol[nz_index] = state_index + 6; ++nz_index; // g(2)' with respect to u0 ~ u1' iRow[nz_index] = state_index + 2; jCol[nz_index] = control_index; ++nz_index; iRow[nz_index] = state_index + 2; jCol[nz_index] = control_index + 1; ++nz_index; // g(2)' with respect to time iRow[nz_index] = state_index + 2; jCol[nz_index] = time_index; ++nz_index; // g(3)' with x0 ~ x7 iRow[nz_index] = state_index + 3; jCol[nz_index] = state_index + 3; ++nz_index; iRow[nz_index] = state_index + 3; jCol[nz_index] = state_index + 7; ++nz_index; // g(3)' with respect to u0 ~ u1' iRow[nz_index] = state_index + 3; jCol[nz_index] = control_index + 1; ++nz_index; // g(3)' with respect to time iRow[nz_index] = state_index + 3; jCol[nz_index] = time_index; ++nz_index; state_index += 4; control_index += 2; time_index++; constraint_index += 4; } // 2. only have control rate constraints on u0 , range [0, horizon_-1] control_index = control_start_index_; state_index = state_start_index_; time_index = time_start_index_; // First one, with respect to u(0, 0) iRow[nz_index] = constraint_index; jCol[nz_index] = control_index; ++nz_index; // First element, with respect to time iRow[nz_index] = constraint_index; jCol[nz_index] = time_index; ++nz_index; control_index += 2; time_index++; constraint_index++; for (int i = 1; i < horizon_; ++i) { // with respect to u(0, i-1) iRow[nz_index] = constraint_index; jCol[nz_index] = control_index - 2; ++nz_index; // with respect to u(0, i) iRow[nz_index] = constraint_index; jCol[nz_index] = control_index; ++nz_index; // with respect to time iRow[nz_index] = constraint_index; jCol[nz_index] = time_index; ++nz_index; // only consider rate limits on u0 control_index += 2; constraint_index++; time_index++; } // 3. Time constraints [0, horizon_ -1] time_index = time_start_index_; for (int i = 0; i < horizon_; ++i) { // with respect to timescale(0, i-1) iRow[nz_index] = constraint_index; jCol[nz_index] = time_index; ++nz_index; // with respect to timescale(0, i) iRow[nz_index] = constraint_index; jCol[nz_index] = time_index + 1; ++nz_index; time_index++; constraint_index++; } // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 state_index = state_start_index_; int l_index = l_start_index_; int n_index = n_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); // 1. norm(A* lambda == 1) for (int k = 0; k < current_edges_num; ++k) { // with respect to l iRow[nz_index] = constraint_index; jCol[nz_index] = l_index + k; ++nz_index; } // 2. G' * mu + R' * lambda == 0, part 1 // With respect to x iRow[nz_index] = constraint_index + 1; jCol[nz_index] = state_index + 2; ++nz_index; // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index] = constraint_index + 1; jCol[nz_index] = l_index + k; ++nz_index; } // With respect to n iRow[nz_index] = constraint_index + 1; jCol[nz_index] = n_index; ++nz_index; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = n_index + 2; ++nz_index; // 2. G' * mu + R' * lambda == 0, part 2 // With respect to x iRow[nz_index] = constraint_index + 2; jCol[nz_index] = state_index + 2; ++nz_index; // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index] = constraint_index + 2; jCol[nz_index] = l_index + k; ++nz_index; } // With respect to n iRow[nz_index] = constraint_index + 2; jCol[nz_index] = n_index + 1; ++nz_index; iRow[nz_index] = constraint_index + 2; jCol[nz_index] = n_index + 3; ++nz_index; // -g'*mu + (A*t - b)*lambda > 0 // With respect to x iRow[nz_index] = constraint_index + 3; jCol[nz_index] = state_index; ++nz_index; iRow[nz_index] = constraint_index + 3; jCol[nz_index] = state_index + 1; ++nz_index; iRow[nz_index] = constraint_index + 3; jCol[nz_index] = state_index + 2; ++nz_index; // with respect to l for (int k = 0; k < current_edges_num; ++k) { iRow[nz_index] = constraint_index + 3; jCol[nz_index] = l_index + k; ++nz_index; } // with respect to n for (int k = 0; k < 4; ++k) { iRow[nz_index] = constraint_index + 3; jCol[nz_index] = n_index + k; ++nz_index; } // Update index l_index += current_edges_num; n_index += 4; constraint_index += 4; } state_index += 4; } // 5. load variable bounds as constraints state_index = state_start_index_; control_index = control_start_index_; time_index = time_start_index_; l_index = l_start_index_; n_index = n_start_index_; // start configuration iRow[nz_index] = constraint_index; jCol[nz_index] = state_index; nz_index++; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = state_index + 1; nz_index++; iRow[nz_index] = constraint_index + 2; jCol[nz_index] = state_index + 2; nz_index++; iRow[nz_index] = constraint_index + 3; jCol[nz_index] = state_index + 3; nz_index++; constraint_index += 4; state_index += 4; for (int i = 1; i < horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = state_index; nz_index++; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = state_index + 1; nz_index++; iRow[nz_index] = constraint_index + 2; jCol[nz_index] = state_index + 3; nz_index++; constraint_index += 3; state_index += 4; } // end configuration iRow[nz_index] = constraint_index; jCol[nz_index] = state_index; nz_index++; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = state_index + 1; nz_index++; iRow[nz_index] = constraint_index + 2; jCol[nz_index] = state_index + 2; nz_index++; iRow[nz_index] = constraint_index + 3; jCol[nz_index] = state_index + 3; nz_index++; constraint_index += 4; state_index += 4; for (int i = 0; i < horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = control_index; nz_index++; iRow[nz_index] = constraint_index + 1; jCol[nz_index] = control_index + 1; nz_index++; constraint_index += 2; control_index += 2; } for (int i = 0; i < horizon_ + 1; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = time_index; nz_index++; constraint_index++; time_index++; } for (int i = 0; i < lambda_horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = l_index; nz_index++; constraint_index++; l_index++; } for (int i = 0; i < miu_horizon_; ++i) { iRow[nz_index] = constraint_index; jCol[nz_index] = n_index; nz_index++; constraint_index++; n_index++; } CHECK_EQ(nz_index, static_cast<int>(nele_jac)); CHECK_EQ(constraint_index, static_cast<int>(m)); } else { std::fill(values, values + nele_jac, 0.0); int nz_index = 0; int time_index = time_start_index_; int state_index = state_start_index_; int control_index = control_start_index_; // TODO(QiL) : initially implemented to be debug friendly, later iterate // towards better efficiency // 1. state constraints 4 * [0, horizons-1] for (int i = 0; i < horizon_; ++i) { values[nz_index] = -1.0; ++nz_index; values[nz_index] = x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_); // a. ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * (-1) * x[time_index] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_ * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // b ++nz_index; values[nz_index] = 1.0; ++nz_index; values[nz_index] = x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) * x[time_index] * ts_ * 0.5 * x[state_index + 3] / (std::cos(x[control_index]) * std::cos(x[control_index])) / wheelbase_; // c ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * x[time_index] * ts_ * 0.5 * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // d ++nz_index; values[nz_index] = -1.0 * (ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * ts_ * 0.5 * x[control_index + 1] * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) - x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * x[state_index + 3] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_ * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // e ++nz_index; values[nz_index] = -1.0; ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // f. ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * x[time_index] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_ * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // g ++nz_index; values[nz_index] = 1.0; ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) * x[time_index] * ts_ * 0.5 * x[state_index + 3] / (std::cos(x[control_index]) * std::cos(x[control_index])) / wheelbase_); // h ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * x[time_index] * ts_ * 0.5 * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // i ++nz_index; values[nz_index] = -1.0 * (ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * ts_ * 0.5 * x[control_index + 1] * std::sin(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_) + x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * x[state_index + 3] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_ * std::cos(x[state_index + 2] + x[time_index] * ts_ * 0.5 * x[state_index + 3] * std::tan(x[control_index]) / wheelbase_)); // j ++nz_index; values[nz_index] = -1.0; ++nz_index; values[nz_index] = -1.0 * x[time_index] * ts_ * std::tan(x[control_index]) / wheelbase_; // k. ++nz_index; values[nz_index] = 1.0; ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) / (std::cos(x[control_index]) * std::cos(x[control_index])) / wheelbase_); // l. ++nz_index; values[nz_index] = -1.0 * (x[time_index] * ts_ * x[time_index] * ts_ * 0.5 * std::tan(x[control_index]) / wheelbase_); // m. ++nz_index; values[nz_index] = -1.0 * (ts_ * (x[state_index + 3] + x[time_index] * ts_ * 0.5 * x[control_index + 1]) * std::tan(x[control_index]) / wheelbase_ + x[time_index] * ts_ * ts_ * 0.5 * x[control_index + 1] * std::tan(x[control_index]) / wheelbase_); // n. ++nz_index; values[nz_index] = -1.0; ++nz_index; values[nz_index] = 1.0; ++nz_index; values[nz_index] = -1.0 * ts_ * x[time_index]; // o. ++nz_index; values[nz_index] = -1.0 * ts_ * x[control_index + 1]; // p. ++nz_index; state_index += 4; control_index += 2; time_index++; } // 2. control rate constraints 1 * [0, horizons-1] control_index = control_start_index_; state_index = state_start_index_; time_index = time_start_index_; // First horizon // with respect to u(0, 0) values[nz_index] = 1.0 / x[time_index] / ts_; // q ++nz_index; // with respect to time values[nz_index] = -1.0 * (x[control_index] - last_time_u_(0, 0)) / x[time_index] / x[time_index] / ts_; ++nz_index; time_index++; control_index += 2; for (int i = 1; i < horizon_; ++i) { // with respect to u(0, i-1) values[nz_index] = -1.0 / x[time_index] / ts_; ++nz_index; // with respect to u(0, i) values[nz_index] = 1.0 / x[time_index] / ts_; ++nz_index; // with respect to time values[nz_index] = -1.0 * (x[control_index] - x[control_index - 2]) / x[time_index] / x[time_index] / ts_; ++nz_index; control_index += 2; time_index++; } ADEBUG << "After fulfilled control rate constraints derivative, nz_index : " << nz_index << " nele_jac : " << nele_jac; // 3. Time constraints [0, horizon_ -1] time_index = time_start_index_; for (int i = 0; i < horizon_; ++i) { // with respect to timescale(0, i-1) values[nz_index] = -1.0; ++nz_index; // with respect to timescale(0, i) values[nz_index] = 1.0; ++nz_index; time_index++; } ADEBUG << "After fulfilled time constraints derivative, nz_index : " << nz_index << " nele_jac : " << nele_jac; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 state_index = state_start_index_; int l_index = l_start_index_; int n_index = n_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); // TODO(QiL) : Remove redundant calculation double tmp1 = 0; double tmp2 = 0; for (int k = 0; k < current_edges_num; ++k) { // TODO(QiL) : replace this one directly with x tmp1 += Aj(k, 0) * x[l_index + k]; tmp2 += Aj(k, 1) * x[l_index + k]; } // 1. norm(A* lambda == 1) for (int k = 0; k < current_edges_num; ++k) { // with respect to l values[nz_index] = 2 * tmp1 * Aj(k, 0) + 2 * tmp2 * Aj(k, 1); // t0~tk ++nz_index; } // 2. G' * mu + R' * lambda == 0, part 1 // With respect to x values[nz_index] = -std::sin(x[state_index + 2]) * tmp1 + std::cos(x[state_index + 2]) * tmp2; // u ++nz_index; // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index] = std::cos(x[state_index + 2]) * Aj(k, 0) + std::sin(x[state_index + 2]) * Aj(k, 1); // v0~vn ++nz_index; } // With respect to n values[nz_index] = 1.0; // w0 ++nz_index; values[nz_index] = -1.0; // w2 ++nz_index; // 3. G' * mu + R' * lambda == 0, part 2 // With respect to x values[nz_index] = -std::cos(x[state_index + 2]) * tmp1 - std::sin(x[state_index + 2]) * tmp2; // x ++nz_index; // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index] = -std::sin(x[state_index + 2]) * Aj(k, 0) + std::cos(x[state_index + 2]) * Aj(k, 1); // y0~yn ++nz_index; } // With respect to n values[nz_index] = 1.0; // z1 ++nz_index; values[nz_index] = -1.0; // z3 ++nz_index; // 3. -g'*mu + (A*t - b)*lambda > 0 double tmp3 = 0.0; double tmp4 = 0.0; for (int k = 0; k < 4; ++k) { tmp3 += -g_[k] * x[n_index + k]; } for (int k = 0; k < current_edges_num; ++k) { tmp4 += bj(k, 0) * x[l_index + k]; } // With respect to x values[nz_index] = tmp1; // aa1 ++nz_index; values[nz_index] = tmp2; // bb1 ++nz_index; values[nz_index] = -std::sin(x[state_index + 2]) * offset_ * tmp1 + std::cos(x[state_index + 2]) * offset_ * tmp2; // cc1 ++nz_index; // with respect to l for (int k = 0; k < current_edges_num; ++k) { values[nz_index] = (x[state_index] + std::cos(x[state_index + 2]) * offset_) * Aj(k, 0) + (x[state_index + 1] + std::sin(x[state_index + 2]) * offset_) * Aj(k, 1) - bj(k, 0); // ddk ++nz_index; } // with respect to n for (int k = 0; k < 4; ++k) { values[nz_index] = -g_[k]; // eek ++nz_index; } // Update index edges_counter += current_edges_num; l_index += current_edges_num; n_index += 4; } state_index += 4; } // 5. load variable bounds as constraints state_index = state_start_index_; control_index = control_start_index_; time_index = time_start_index_; l_index = l_start_index_; n_index = n_start_index_; // start configuration values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; for (int i = 1; i < horizon_; ++i) { values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; } // end configuration values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; for (int i = 0; i < horizon_; ++i) { values[nz_index] = 1.0; nz_index++; values[nz_index] = 1.0; nz_index++; } for (int i = 0; i < horizon_ + 1; ++i) { values[nz_index] = 1.0; nz_index++; } for (int i = 0; i < lambda_horizon_; ++i) { values[nz_index] = 1.0; nz_index++; } for (int i = 0; i < miu_horizon_; ++i) { values[nz_index] = 1.0; nz_index++; } ADEBUG << "eval_jac_g, fulfilled obstacle constraint values"; CHECK_EQ(nz_index, static_cast<int>(nele_jac)); } ADEBUG << "eval_jac_g done"; return true; } // NOLINT bool DistanceApproachIPOPTCUDAInterface::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) { // return the structure. This is a symmetric matrix, fill the lower left // triangle only. #if USE_GPU == 1 fill_lower_left(iRow, jCol, rind_L, cind_L, nnz_L); #else AFATAL << "CUDA enabled without GPU!"; #endif } else { // return the values. This is a symmetric matrix, fill the lower left // triangle only obj_lam[0] = obj_factor; #if USE_GPU == 1 data_transfer(&obj_lam[1], lambda, m); #else AFATAL << "CUDA enabled without GPU!"; #endif set_param_vec(tag_L, m + 1, obj_lam); sparse_hess(tag_L, n, 1, const_cast<double*>(x), &nnz_L, &rind_L, &cind_L, &hessval, options_L); #if USE_GPU == 1 if (!data_transfer(values, hessval, nnz_L)) { for (int idx = 0; idx < nnz_L; idx++) { values[idx] = hessval[idx]; } } #endif } return true; } void DistanceApproachIPOPTCUDAInterface::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) { ADEBUG << "finalize_solution"; int state_index = state_start_index_; int control_index = control_start_index_; int time_index = time_start_index_; int dual_l_index = l_start_index_; int dual_n_index = n_start_index_; // 1. state variables, 4 * [0, horizon] // 2. control variables, 2 * [0, horizon_-1] // 3. sampling time variables, 1 * [0, horizon_] // 4. dual_l obstacles_edges_sum_ * [0, horizon] // 5. dual_n obstacles_num * [0, horizon] for (int i = 0; i < horizon_; ++i) { state_result_(0, i) = x[state_index]; state_result_(1, i) = x[state_index + 1]; state_result_(2, i) = x[state_index + 2]; state_result_(3, i) = x[state_index + 3]; control_result_(0, i) = x[control_index]; control_result_(1, i) = x[control_index + 1]; time_result_(0, i) = x[time_index]; for (int j = 0; j < obstacles_edges_sum_; ++j) { dual_l_result_(j, i) = x[dual_l_index + j]; } for (int k = 0; k < 4 * obstacles_num_; k++) { dual_n_result_(k, i) = x[dual_n_index + k]; } state_index += 4; control_index += 2; time_index++; dual_l_index += obstacles_edges_sum_; dual_n_index += 4 * obstacles_num_; } state_result_(0, 0) = x0_(0, 0); state_result_(1, 0) = x0_(1, 0); state_result_(2, 0) = x0_(2, 0); state_result_(3, 0) = x0_(3, 0); // push back last horizon for state and time variables state_result_(0, horizon_) = xf_(0, 0); state_result_(1, horizon_) = xf_(1, 0); state_result_(2, horizon_) = xf_(2, 0); state_result_(3, horizon_) = xf_(3, 0); time_result_(0, horizon_) = x[time_index]; time_result_ = ts_ * time_result_; for (int j = 0; j < obstacles_edges_sum_; ++j) { dual_l_result_(j, horizon_) = x[dual_l_index + j]; } for (int k = 0; k < 4 * obstacles_num_; k++) { dual_n_result_(k, horizon_) = x[dual_n_index + k]; } // memory deallocation of ADOL-C variables delete[] obj_lam; free(rind_L); free(cind_L); free(hessval); ADEBUG << "finalize_solution done!"; } void DistanceApproachIPOPTCUDAInterface::get_optimization_results( Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) const { ADEBUG << "get_optimization_results"; *state_result = state_result_; *control_result = control_result_; *time_result = time_result_; *dual_l_result = dual_l_result_; *dual_n_result = dual_n_result_; if (!distance_approach_config_.enable_initial_final_check()) { return; } CHECK_EQ(state_result_.cols(), xWS_.cols()); CHECK_EQ(state_result_.rows(), xWS_.rows()); double state_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4; ++j) { state_diff_max = std::max(std::abs(xWS_(j, i) - state_result_(j, i)), state_diff_max); } } // 2. control variable initialization, 2 * horizon_ // CHECK_EQ(control_result_.cols(), uWS_.cols()); CHECK_EQ(control_result_.rows(), uWS_.rows()); double control_diff_max = 0.0; for (int i = 0; i < horizon_; ++i) { control_diff_max = std::max(std::abs(uWS_(0, i) - control_result_(0, i)), control_diff_max); control_diff_max = std::max(std::abs(uWS_(1, i) - control_result_(1, i)), control_diff_max); } // 2. time scale variable initialization, horizon_ + 1, no // 3. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1) CHECK_EQ(dual_l_result_.cols(), l_warm_up_.cols()); CHECK_EQ(dual_l_result_.rows(), l_warm_up_.rows()); double l_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < obstacles_edges_sum_; ++j) { l_diff_max = std::max(std::abs(l_warm_up_(j, i) - dual_l_result_(j, i)), l_diff_max); } } // 4. lagrange constraint m, 4*obstacles_num * (horizon_+1) CHECK_EQ(n_warm_up_.cols(), dual_n_result_.cols()); CHECK_EQ(n_warm_up_.rows(), dual_n_result_.rows()); double n_diff_max = 0.0; for (int i = 0; i < horizon_ + 1; ++i) { for (int j = 0; j < 4 * obstacles_num_; ++j) { n_diff_max = std::max(std::abs(n_warm_up_(j, i) - dual_n_result_(j, i)), n_diff_max); } } ADEBUG << "state_diff_max: " << state_diff_max; ADEBUG << "control_diff_max: " << control_diff_max; ADEBUG << "dual_l_diff_max: " << l_diff_max; ADEBUG << "dual_n_diff_max: " << n_diff_max; } //*************** start ADOL-C part *********************************** template <class T> bool DistanceApproachIPOPTCUDAInterface::eval_obj(int n, const T* x, T* obj_value) { ADEBUG << "eval_obj"; // Objective is : // min control inputs // min input rate // min time (if the time step is not fixed) // regularization wrt warm start trajectory DCHECK(ts_ != 0) << "ts in distance_approach_ is 0"; int control_index = control_start_index_; int time_index = time_start_index_; int state_index = state_start_index_; // TODO(QiL): Initial implementation towards earlier understanding and debug // purpose, later code refine towards improving efficiency *obj_value = 0.0; // 1. objective to minimize state diff to warm up for (int i = 0; i < horizon_ + 1; ++i) { T x1_diff = x[state_index] - xWS_(0, i); T x2_diff = x[state_index + 1] - xWS_(1, i); T x3_diff = x[state_index + 2] - xWS_(2, i); T x4_abs = x[state_index + 3]; *obj_value += weight_state_x_ * x1_diff * x1_diff + weight_state_y_ * x2_diff * x2_diff + weight_state_phi_ * x3_diff * x3_diff + weight_state_v_ * x4_abs * x4_abs; state_index += 4; } // 2. objective to minimize u square for (int i = 0; i < horizon_; ++i) { *obj_value += weight_input_steer_ * x[control_index] * x[control_index] + weight_input_a_ * x[control_index + 1] * x[control_index + 1]; control_index += 2; } // 3. objective to minimize input change rate for first horizon control_index = control_start_index_; T last_time_steer_rate = (x[control_index] - last_time_u_(0, 0)) / x[time_index] / ts_; T last_time_a_rate = (x[control_index + 1] - last_time_u_(1, 0)) / x[time_index] / ts_; *obj_value += weight_stitching_steer_ * last_time_steer_rate * last_time_steer_rate + weight_stitching_a_ * last_time_a_rate * last_time_a_rate; // 4. objective to minimize input change rates, [0- horizon_ -2] time_index++; for (int i = 0; i < horizon_ - 1; ++i) { T steering_rate = (x[control_index + 2] - x[control_index]) / x[time_index] / ts_; T a_rate = (x[control_index + 3] - x[control_index + 1]) / x[time_index] / ts_; *obj_value += weight_rate_steer_ * steering_rate * steering_rate + weight_rate_a_ * a_rate * a_rate; control_index += 2; time_index++; } // 5. objective to minimize total time [0, horizon_] time_index = time_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { T first_order_penalty = weight_first_order_time_ * x[time_index]; T second_order_penalty = weight_second_order_time_ * x[time_index] * x[time_index]; *obj_value += first_order_penalty + second_order_penalty; time_index++; } ADEBUG << "objective value after this iteration : " << *obj_value; return true; } template <class T> bool DistanceApproachIPOPTCUDAInterface::eval_constraints(int n, const T* x, int m, T* g) { ADEBUG << "eval_constraints"; // state start index int state_index = state_start_index_; // control start index. int control_index = control_start_index_; // time start index int time_index = time_start_index_; int constraint_index = 0; // // 1. state constraints 4 * [0, horizons-1] for (int i = 0; i < horizon_; ++i) { // x1 // TODO(QiL) : optimize and remove redundant calculation in next // iteration. g[constraint_index] = x[state_index + 4] - (x[state_index] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * cos(x[state_index + 2] + ts_ * x[time_index] * 0.5 * x[state_index + 3] * tan(x[control_index]) / wheelbase_)); // x2 g[constraint_index + 1] = x[state_index + 5] - (x[state_index + 1] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * sin(x[state_index + 2] + ts_ * x[time_index] * 0.5 * x[state_index + 3] * tan(x[control_index]) / wheelbase_)); // x3 g[constraint_index + 2] = x[state_index + 6] - (x[state_index + 2] + ts_ * x[time_index] * (x[state_index + 3] + ts_ * x[time_index] * 0.5 * x[control_index + 1]) * tan(x[control_index]) / wheelbase_); // x4 g[constraint_index + 3] = x[state_index + 7] - (x[state_index + 3] + ts_ * x[time_index] * x[control_index + 1]); control_index += 2; constraint_index += 4; time_index++; state_index += 4; } ADEBUG << "constraint_index after adding Euler forward dynamics constraints " "updated: " << constraint_index; // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply // steering rate as of now control_index = control_start_index_; time_index = time_start_index_; // First rate is compare first with stitch point g[constraint_index] = (x[control_index] - last_time_u_(0, 0)) / x[time_index] / ts_; control_index += 2; constraint_index++; time_index++; for (int i = 1; i < horizon_; ++i) { g[constraint_index] = (x[control_index] - x[control_index - 2]) / x[time_index] / ts_; constraint_index++; control_index += 2; time_index++; } // 3. Time constraints 1 * [0, horizons-1] time_index = time_start_index_; for (int i = 0; i < horizon_; ++i) { g[constraint_index] = x[time_index + 1] - x[time_index]; constraint_index++; time_index++; } ADEBUG << "constraint_index after adding time constraints " "updated: " << constraint_index; // 4. Three obstacles related equal constraints, one equality constraints, // [0, horizon_] * [0, obstacles_num_-1] * 4 state_index = state_start_index_; int l_index = l_start_index_; int n_index = n_start_index_; for (int i = 0; i < horizon_ + 1; ++i) { int edges_counter = 0; for (int j = 0; j < obstacles_num_; ++j) { int current_edges_num = obstacles_edges_num_(j, 0); Eigen::MatrixXd Aj = obstacles_A_.block(edges_counter, 0, current_edges_num, 2); Eigen::MatrixXd bj = obstacles_b_.block(edges_counter, 0, current_edges_num, 1); // norm(A* lambda) <= 1 T tmp1 = 0.0; T tmp2 = 0.0; for (int k = 0; k < current_edges_num; ++k) { // TODO(QiL) : replace this one directly with x tmp1 += Aj(k, 0) * x[l_index + k]; tmp2 += Aj(k, 1) * x[l_index + k]; } g[constraint_index] = tmp1 * tmp1 + tmp2 * tmp2; // G' * mu + R' * lambda == 0 g[constraint_index + 1] = x[n_index] - x[n_index + 2] + cos(x[state_index + 2]) * tmp1 + sin(x[state_index + 2]) * tmp2; g[constraint_index + 2] = x[n_index + 1] - x[n_index + 3] - sin(x[state_index + 2]) * tmp1 + cos(x[state_index + 2]) * tmp2; // -g'*mu + (A*t - b)*lambda > 0 T tmp3 = 0.0; for (int k = 0; k < 4; ++k) { tmp3 += -g_[k] * x[n_index + k]; } T tmp4 = 0.0; for (int k = 0; k < current_edges_num; ++k) { tmp4 += bj(k, 0) * x[l_index + k]; } g[constraint_index + 3] = tmp3 + (x[state_index] + cos(x[state_index + 2]) * offset_) * tmp1 + (x[state_index + 1] + sin(x[state_index + 2]) * offset_) * tmp2 - tmp4; // Update index edges_counter += current_edges_num; l_index += current_edges_num; n_index += 4; constraint_index += 4; } state_index += 4; } ADEBUG << "constraint_index after obstacles avoidance constraints " "updated: " << constraint_index; // 5. load variable bounds as constraints state_index = state_start_index_; control_index = control_start_index_; time_index = time_start_index_; l_index = l_start_index_; n_index = n_start_index_; // start configuration g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 2]; g[constraint_index + 3] = x[state_index + 3]; constraint_index += 4; state_index += 4; // constraints on x,y,v for (int i = 1; i < horizon_; ++i) { g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 3]; constraint_index += 3; state_index += 4; } // end configuration g[constraint_index] = x[state_index]; g[constraint_index + 1] = x[state_index + 1]; g[constraint_index + 2] = x[state_index + 2]; g[constraint_index + 3] = x[state_index + 3]; constraint_index += 4; state_index += 4; for (int i = 0; i < horizon_; ++i) { g[constraint_index] = x[control_index]; g[constraint_index + 1] = x[control_index + 1]; constraint_index += 2; control_index += 2; } for (int i = 0; i < horizon_ + 1; ++i) { g[constraint_index] = x[time_index]; constraint_index++; time_index++; } for (int i = 0; i < lambda_horizon_; ++i) { g[constraint_index] = x[l_index]; constraint_index++; l_index++; } for (int i = 0; i < miu_horizon_; ++i) { g[constraint_index] = x[n_index]; constraint_index++; n_index++; } return true; } bool DistanceApproachIPOPTCUDAInterface::check_g(int n, const double* x, int m, const double* g) { int kN = n; int kM = m; double x_u_tmp[kN]; double x_l_tmp[kN]; double g_u_tmp[kM]; double g_l_tmp[kM]; get_bounds_info(n, x_l_tmp, x_u_tmp, m, g_l_tmp, g_u_tmp); double delta_v = 1e-4; for (int idx = 0; idx < n; ++idx) { x_u_tmp[idx] = x_u_tmp[idx] + delta_v; x_l_tmp[idx] = x_l_tmp[idx] - delta_v; if (x[idx] > x_u_tmp[idx] || x[idx] < x_l_tmp[idx]) { ADEBUG << "x idx unfeasible: " << idx << ", x: " << x[idx] << ", lower: " << x_l_tmp[idx] << ", upper: " << x_u_tmp[idx]; } } // m1 : dynamics constatins int m1 = 4 * horizon_; // m2 : control rate constraints (only steering) int m2 = m1 + horizon_; // m3 : sampling time equality constraints int m3 = m2 + horizon_; // m4 : obstacle constraints int m4 = m3 + 4 * obstacles_num_ * (horizon_ + 1); // 5. load variable bounds as constraints // start configuration int m5 = m4 + 3 + 1; // constraints on x,y,v int m6 = m5 + 3 * (horizon_ - 1); // end configuration int m7 = m6 + 3 + 1; // control variable bnd int m8 = m7 + 2 * horizon_; // time interval variable bnd int m9 = m8 + (horizon_ + 1); // lambda_horizon_ int m10 = m9 + lambda_horizon_; // miu_horizon_ int m11 = m10 + miu_horizon_; ADEBUG << "dynamics constatins to: " << m1; ADEBUG << "control rate constraints (only steering) to: " << m2; ADEBUG << "sampling time equality constraints to: " << m3; ADEBUG << "obstacle constraints to: " << m4; ADEBUG << "start conf constraints to: " << m5; ADEBUG << "constraints on x,y,v to: " << m6; ADEBUG << "end constraints to: " << m7; ADEBUG << "control bnd to: " << m8; ADEBUG << "time interval constraints to: " << m9; ADEBUG << "lambda constraints to: " << m10; ADEBUG << "miu constraints to: " << m11; ADEBUG << "total variables: " << num_of_variables_; for (int idx = 0; idx < m; ++idx) { if (g[idx] > g_u_tmp[idx] + delta_v || g[idx] < g_l_tmp[idx] - delta_v) { ADEBUG << "constratins idx unfeasible: " << idx << ", g: " << g[idx] << ", lower: " << g_l_tmp[idx] << ", upper: " << g_u_tmp[idx]; } } return true; } void DistanceApproachIPOPTCUDAInterface::generate_tapes(int n, int m, int* nnz_h_lag) { std::vector<double> xp(n); std::vector<double> lamp(m); std::vector<double> zl(m); std::vector<double> zu(m); std::vector<adouble> xa(n); std::vector<adouble> g(m); std::vector<double> lam(m); double sig; adouble obj_value; double dummy = 0.0; obj_lam = new double[m + 1]; get_starting_point(n, 1, &xp[0], 0, &zl[0], &zu[0], m, 0, &lamp[0]); trace_on(tag_f); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_obj(n, &xa[0], &obj_value); obj_value >>= dummy; trace_off(); trace_on(tag_g); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { g[idx] >>= dummy; } trace_off(); trace_on(tag_L); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } for (int idx = 0; idx < m; idx++) { lam[idx] = 1.0; } sig = 1.0; eval_obj(n, &xa[0], &obj_value); obj_value *= mkparam(sig); eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { obj_value += g[idx] * mkparam(lam[idx]); } obj_value >>= dummy; trace_off(); rind_L = nullptr; cind_L = nullptr; hessval = nullptr; options_L[0] = 0; options_L[1] = 1; sparse_hess(tag_L, n, 0, &xp[0], &nnz_L, &rind_L, &cind_L, &hessval, options_L); *nnz_h_lag = nnz_L; } //*************** end ADOL-C part *********************************** } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_interface.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 <algorithm> #include <limits> #include <vector> #include <omp.h> #include <adolc/adolc.h> #include <adolc/adolc_openmp.h> #include <adolc/adolc_sparse.h> #include <adolc/adouble.h> #include <coin/IpTNLP.hpp> #include <coin/IpTypes.hpp> #include "Eigen/Dense" #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/open_space/trajectory_smoother/distance_approach_interface.h" #include "modules/planning/proto/planner_open_space_config.pb.h" #define tag_f 1 #define tag_g 2 #define tag_L 3 #define HPOFF 30 namespace apollo { namespace planning { class DistanceApproachIPOPTInterface : public DistanceApproachInterface { public: DistanceApproachIPOPTInterface( const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS, const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up, const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xf, const Eigen::MatrixXd& last_time_u, const std::vector<double>& XYbounds, const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const PlannerOpenSpaceConfig& planner_open_space_config); virtual ~DistanceApproachIPOPTInterface() = default; /** Method to return some info about the nlp */ bool get_nlp_info(int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, // NOLINT IndexStyleEnum& index_style) override; // NOLINT /** 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; /** Check unfeasible constraints for further study**/ bool check_g(int n, const double* x, int m, const double* g); /** 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; // sequential implementation to jac_g bool eval_jac_g_ser(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 get_optimization_results(Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result, Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result, Eigen::MatrixXd* dual_n_result) const override; //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> void eval_obj(int n, const T* x, T* obj_value); /** Template to compute constraints */ template <class T> void eval_constraints(int n, const T* x, int m, T* g); /** Method to generate the required tapes by ADOL-C*/ void generate_tapes(int n, int m, int* nnz_jac_g, int* nnz_h_lag); //*************** end ADOL-C part *********************************** private: int num_of_variables_ = 0; int num_of_constraints_ = 0; int horizon_ = 0; int lambda_horizon_ = 0; int miu_horizon_ = 0; double ts_ = 0.0; Eigen::MatrixXd ego_; Eigen::MatrixXd xWS_; Eigen::MatrixXd uWS_; Eigen::MatrixXd l_warm_up_; Eigen::MatrixXd n_warm_up_; Eigen::MatrixXd x0_; Eigen::MatrixXd xf_; Eigen::MatrixXd last_time_u_; std::vector<double> XYbounds_; // debug flag bool enable_constraint_check_; // penalty double weight_state_x_ = 0.0; double weight_state_y_ = 0.0; double weight_state_phi_ = 0.0; double weight_state_v_ = 0.0; double weight_input_steer_ = 0.0; double weight_input_a_ = 0.0; double weight_rate_steer_ = 0.0; double weight_rate_a_ = 0.0; double weight_stitching_steer_ = 0.0; double weight_stitching_a_ = 0.0; double weight_first_order_time_ = 0.0; double weight_second_order_time_ = 0.0; double w_ev_ = 0.0; double l_ev_ = 0.0; std::vector<double> g_; double offset_ = 0.0; Eigen::MatrixXi obstacles_edges_num_; int obstacles_num_ = 0; int obstacles_edges_sum_ = 0; double wheelbase_ = 0.0; Eigen::MatrixXd state_result_; Eigen::MatrixXd dual_l_result_; Eigen::MatrixXd dual_n_result_; Eigen::MatrixXd control_result_; Eigen::MatrixXd time_result_; // obstacles_A Eigen::MatrixXd obstacles_A_; // obstacles_b Eigen::MatrixXd obstacles_b_; // whether to use fix time bool use_fix_time_ = false; // state start index int state_start_index_ = 0; // control start index. int control_start_index_ = 0; // time start index int time_start_index_ = 0; // lagrangian l start index int l_start_index_ = 0; // lagrangian n start index int n_start_index_ = 0; double min_safety_distance_ = 0.0; double max_safety_distance_ = 0.0; double max_steer_angle_ = 0.0; double max_speed_forward_ = 0.0; double max_speed_reverse_ = 0.0; double max_acceleration_forward_ = 0.0; double max_acceleration_reverse_ = 0.0; double min_time_sample_scaling_ = 0.0; double max_time_sample_scaling_ = 0.0; double max_steer_rate_ = 0.0; double max_lambda_ = 0.0; double max_miu_ = 0.0; bool enable_jacobian_ad_ = false; private: DistanceApproachConfig distance_approach_config_; const common::VehicleParam vehicle_param_ = common::VehicleConfigHelper::GetConfig().vehicle_param(); private: //*************** start ADOL-C part *********************************** double* obj_lam; //** variables for sparsity exploitation unsigned int* rind_g; /* row indices */ unsigned int* cind_g; /* column indices */ double* jacval; /* values */ unsigned int* rind_L; /* row indices */ unsigned int* cind_L; /* column indices */ double* hessval; /* values */ int nnz_jac; int nnz_L; int options_g[4]; int options_L[4]; //*************** end ADOL-C part *********************************** }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/iterative_anchoring_smoother.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/open_space/trajectory_smoother/iterative_anchoring_smoother.h" #include <algorithm> #include <limits> #include <random> #include "cyber/common/log.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/planning/math/discrete_points_math.h" #include "modules/planning/math/discretized_points_smoothing/fem_pos_deviation_smoother.h" #include "modules/planning/math/piecewise_jerk/piecewise_jerk_speed_problem.h" #include "modules/planning/proto/planner_open_space_config.pb.h" namespace apollo { namespace planning { using apollo::common::PathPoint; using apollo::common::TrajectoryPoint; using apollo::common::math::Box2d; using apollo::common::math::LineSegment2d; using apollo::common::math::NormalizeAngle; using apollo::common::math::Vec2d; IterativeAnchoringSmoother::IterativeAnchoringSmoother( const PlannerOpenSpaceConfig& planner_open_space_config) { // TODO(Jinyun, Yu): refactor after stabilized. const auto& vehicle_param = common::VehicleConfigHelper::Instance()->GetConfig().vehicle_param(); ego_length_ = vehicle_param.length(); ego_width_ = vehicle_param.width(); center_shift_distance_ = ego_length_ / 2.0 - vehicle_param.back_edge_to_center(); planner_open_space_config_ = planner_open_space_config; } bool IterativeAnchoringSmoother::Smooth( const Eigen::MatrixXd& xWS, const double init_a, const double init_v, const std::vector<std::vector<Vec2d>>& obstacles_vertices_vec, DiscretizedTrajectory* discretized_trajectory) { if (xWS.cols() < 2) { AERROR << "reference points size smaller than two, smoother early " "returned"; return false; } const auto start_timestamp = std::chrono::system_clock::now(); // Set gear of the trajectory gear_ = CheckGear(xWS); // Set obstacle in form of linesegments std::vector<std::vector<LineSegment2d>> obstacles_linesegments_vec; for (const auto& obstacle_vertices : obstacles_vertices_vec) { size_t vertices_num = obstacle_vertices.size(); std::vector<LineSegment2d> obstacle_linesegments; for (size_t i = 0; i + 1 < vertices_num; ++i) { LineSegment2d line_segment = LineSegment2d(obstacle_vertices[i], obstacle_vertices[i + 1]); obstacle_linesegments.emplace_back(line_segment); } obstacles_linesegments_vec.emplace_back(obstacle_linesegments); } obstacles_linesegments_vec_ = std::move(obstacles_linesegments_vec); // Interpolate the traj DiscretizedPath warm_start_path; size_t xWS_size = xWS.cols(); double accumulated_s = 0.0; Vec2d last_path_point(xWS(0, 0), xWS(1, 0)); for (size_t i = 0; i < xWS_size; ++i) { Vec2d cur_path_point(xWS(0, i), xWS(1, i)); accumulated_s += cur_path_point.DistanceTo(last_path_point); PathPoint path_point; path_point.set_x(xWS(0, i)); path_point.set_y(xWS(1, i)); path_point.set_theta(xWS(2, i)); path_point.set_s(accumulated_s); warm_start_path.push_back(std::move(path_point)); last_path_point = cur_path_point; } const double interpolated_delta_s = planner_open_space_config_.iterative_anchoring_smoother_config() .interpolated_delta_s(); std::vector<std::pair<double, double>> interpolated_warm_start_point2ds; double path_length = warm_start_path.Length(); double delta_s = path_length / std::ceil(path_length / interpolated_delta_s); path_length += delta_s * 1.0e-6; for (double s = 0; s < path_length; s += delta_s) { const auto point2d = warm_start_path.Evaluate(s); interpolated_warm_start_point2ds.emplace_back(point2d.x(), point2d.y()); } const size_t interpolated_size = interpolated_warm_start_point2ds.size(); if (interpolated_size < 4) { AERROR << "interpolated_warm_start_path smaller than 4, can't enforce " "heading continuity"; return false; } else if (interpolated_size < 6) { ADEBUG << "interpolated_warm_start_path smaller than 4, can't enforce " "initial zero kappa"; enforce_initial_kappa_ = false; } else { enforce_initial_kappa_ = true; } // Adjust heading to ensure heading continuity AdjustStartEndHeading(xWS, &interpolated_warm_start_point2ds); // Reset path profile by discrete point heading and curvature estimation DiscretizedPath interpolated_warm_start_path; if (!SetPathProfile(interpolated_warm_start_point2ds, &interpolated_warm_start_path)) { AERROR << "Set path profile fails"; return false; } // Generate feasible bounds for each path point std::vector<double> bounds; if (!GenerateInitialBounds(interpolated_warm_start_path, &bounds)) { AERROR << "Generate initial bounds failed, path point to close to obstacle"; return false; } // Check initial path collision avoidance, if it fails, smoother assumption // fails. Try reanchoring input_colliding_point_index_.clear(); if (!CheckCollisionAvoidance(interpolated_warm_start_path, &input_colliding_point_index_)) { AERROR << "Interpolated input path points colliding with obstacle"; // if (!ReAnchoring(colliding_point_index, &interpolated_warm_start_path)) { // AERROR << "Fail to reanchor colliding input path points"; // return false; // } } const auto path_smooth_start_timestamp = std::chrono::system_clock::now(); // Smooth path to have smoothed x, y, phi, kappa and s DiscretizedPath smoothed_path_points; if (!SmoothPath(interpolated_warm_start_path, bounds, &smoothed_path_points)) { return false; } const auto path_smooth_end_timestamp = std::chrono::system_clock::now(); std::chrono::duration<double> path_smooth_diff = path_smooth_end_timestamp - path_smooth_start_timestamp; ADEBUG << "iterative anchoring path smoother time: " << path_smooth_diff.count() * 1000.0 << " ms."; const auto speed_smooth_start_timestamp = std::chrono::system_clock::now(); // Smooth speed to have smoothed v and a SpeedData smoothed_speeds; if (!SmoothSpeed(init_a, init_v, smoothed_path_points.Length(), &smoothed_speeds)) { return false; } // TODO(Jinyun): Evaluate performance // SpeedData smoothed_speeds; // if (!GenerateStopProfileFromPolynomial( // init_a, init_v, smoothed_path_points.Length(), &smoothed_speeds)) { // return false; // } const auto speed_smooth_end_timestamp = std::chrono::system_clock::now(); std::chrono::duration<double> speed_smooth_diff = speed_smooth_end_timestamp - speed_smooth_start_timestamp; ADEBUG << "iterative anchoring speed smoother time: " << speed_smooth_diff.count() * 1000.0 << " ms."; // Combine path and speed if (!CombinePathAndSpeed(smoothed_path_points, smoothed_speeds, discretized_trajectory)) { return false; } AdjustPathAndSpeedByGear(discretized_trajectory); const auto end_timestamp = std::chrono::system_clock::now(); std::chrono::duration<double> diff = end_timestamp - start_timestamp; ADEBUG << "iterative anchoring smoother total time: " << diff.count() * 1000.0 << " ms."; ADEBUG << "discretized_trajectory size " << discretized_trajectory->size(); return true; } void IterativeAnchoringSmoother::AdjustStartEndHeading( const Eigen::MatrixXd& xWS, std::vector<std::pair<double, double>>* const point2d) { // Sanity check CHECK_NOTNULL(point2d); CHECK_GT(xWS.cols(), 1); CHECK_GT(point2d->size(), 3U); // Set initial heading and bounds const double initial_heading = xWS(2, 0); const double end_heading = xWS(2, xWS.cols() - 1); // Adjust the point position to have heading by finite element difference of // the point and the other point equal to the given warm start initial or end // heading const double first_to_second_dx = point2d->at(1).first - point2d->at(0).first; const double first_to_second_dy = point2d->at(1).second - point2d->at(0).second; const double first_to_second_s = std::sqrt(first_to_second_dx * first_to_second_dx + first_to_second_dy * first_to_second_dy); Vec2d first_point(point2d->at(0).first, point2d->at(0).second); Vec2d initial_vec(first_to_second_s, 0); initial_vec.SelfRotate(gear_ ? initial_heading : NormalizeAngle(initial_heading + M_PI)); initial_vec += first_point; point2d->at(1) = std::make_pair(initial_vec.x(), initial_vec.y()); const size_t path_size = point2d->size(); const double second_last_to_last_dx = point2d->at(path_size - 1).first - point2d->at(path_size - 2).first; const double second_last_to_last_dy = point2d->at(path_size - 1).second - point2d->at(path_size - 2).second; const double second_last_to_last_s = std::sqrt(second_last_to_last_dx * second_last_to_last_dx + second_last_to_last_dy * second_last_to_last_dy); Vec2d last_point(point2d->at(path_size - 1).first, point2d->at(path_size - 1).second); Vec2d end_vec(second_last_to_last_s, 0); end_vec.SelfRotate(gear_ ? NormalizeAngle(end_heading + M_PI) : end_heading); end_vec += last_point; point2d->at(path_size - 2) = std::make_pair(end_vec.x(), end_vec.y()); } bool IterativeAnchoringSmoother::ReAnchoring( const std::vector<size_t>& colliding_point_index, DiscretizedPath* path_points) { CHECK_NOTNULL(path_points); if (colliding_point_index.empty()) { ADEBUG << "no point needs to be re-anchored"; return true; } CHECK_GT(path_points->size(), *(std::max_element(colliding_point_index.begin(), colliding_point_index.end()))); for (const auto index : colliding_point_index) { if (index == 0 || index == path_points->size() - 1) { AERROR << "Initial and end points collision avoid condition failed."; return false; } if (index == 1 || index == path_points->size() - 2) { AERROR << "second to last point or second point pos reanchored. Heading " "discontinuity might " "happen"; } } // TODO(Jinyun): move to confs const size_t reanchoring_trails_num = static_cast<size_t>( planner_open_space_config_.iterative_anchoring_smoother_config() .reanchoring_trails_num()); const double reanchoring_pos_stddev = planner_open_space_config_.iterative_anchoring_smoother_config() .reanchoring_pos_stddev(); const double reanchoring_length_stddev = planner_open_space_config_.iterative_anchoring_smoother_config() .reanchoring_length_stddev(); std::random_device rd; std::default_random_engine gen = std::default_random_engine(rd()); std::normal_distribution<> pos_dis{0, reanchoring_pos_stddev}; std::normal_distribution<> length_dis{0, reanchoring_length_stddev}; for (const auto index : colliding_point_index) { bool reanchoring_success = false; for (size_t i = 0; i < reanchoring_trails_num; ++i) { // Get ego box for collision check on collision point index bool is_colliding = false; for (size_t j = index - 1; j < index + 2; ++j) { const double heading = gear_ ? path_points->at(j).theta() : NormalizeAngle(path_points->at(j).theta() + M_PI); Box2d ego_box({path_points->at(j).x() + center_shift_distance_ * std::cos(heading), path_points->at(j).y() + center_shift_distance_ * std::sin(heading)}, heading, ego_length_, ego_width_); for (const auto& obstacle_linesegments : obstacles_linesegments_vec_) { for (const LineSegment2d& linesegment : obstacle_linesegments) { if (ego_box.HasOverlap(linesegment)) { is_colliding = true; break; } } if (is_colliding) { break; } } if (is_colliding) { break; } } if (is_colliding) { // Adjust the point by randomly move around the original points if (index == 1) { const double adjust_theta = path_points->at(index - 1).theta(); const double delta_s = std::abs(path_points->at(index).s() - path_points->at(index - 1).s()); double rand_dev = common::math::Clamp(length_dis(gen), 0.8, -0.8); double adjusted_delta_s = delta_s * (1.0 + rand_dev); path_points->at(index).set_x(path_points->at(index - 1).x() + adjusted_delta_s * std::cos(adjust_theta)); path_points->at(index).set_y(path_points->at(index - 1).y() + adjusted_delta_s * std::sin(adjust_theta)); } else if (index == path_points->size() - 2) { const double adjust_theta = NormalizeAngle(path_points->at(index + 1).theta() + M_PI); const double delta_s = std::abs(path_points->at(index + 1).s() - path_points->at(index).s()); double rand_dev = common::math::Clamp(length_dis(gen), 0.8, -0.8); double adjusted_delta_s = delta_s * (1.0 + rand_dev); path_points->at(index).set_x(path_points->at(index + 1).x() + adjusted_delta_s * std::cos(adjust_theta)); path_points->at(index).set_y(path_points->at(index + 1).y() + adjusted_delta_s * std::sin(adjust_theta)); } else { double rand_dev_x = common::math::Clamp(pos_dis(gen), 2.0 * reanchoring_pos_stddev, -2.0 * reanchoring_pos_stddev); double rand_dev_y = common::math::Clamp(pos_dis(gen), 2.0 * reanchoring_pos_stddev, -2.0 * reanchoring_pos_stddev); path_points->at(index).set_x(path_points->at(index).x() + rand_dev_x); path_points->at(index).set_y(path_points->at(index).y() + rand_dev_y); } // Adjust heading accordingly // TODO(Jinyun): refactor into math module // current point heading adjustment for (size_t i = index - 1; i < index + 2; ++i) { path_points->at(i).set_theta(CalcHeadings(*path_points, i)); } } else { reanchoring_success = true; break; } } if (!reanchoring_success) { AERROR << "interpolated points at index " << index << "can't be successfully reanchored"; return false; } } return true; } bool IterativeAnchoringSmoother::GenerateInitialBounds( const DiscretizedPath& path_points, std::vector<double>* initial_bounds) { CHECK_NOTNULL(initial_bounds); initial_bounds->clear(); const bool estimate_bound = planner_open_space_config_.iterative_anchoring_smoother_config() .estimate_bound(); const double default_bound = planner_open_space_config_.iterative_anchoring_smoother_config() .default_bound(); const double vehicle_shortest_dimension = planner_open_space_config_.iterative_anchoring_smoother_config() .vehicle_shortest_dimension(); const double kEpislon = 1e-8; if (!estimate_bound) { std::vector<double> default_bounds(path_points.size(), default_bound); *initial_bounds = std::move(default_bounds); return true; } // TODO(Jinyun): refine obstacle formulation and speed it up for (const auto& path_point : path_points) { double min_bound = std::numeric_limits<double>::infinity(); for (const auto& obstacle_linesegments : obstacles_linesegments_vec_) { for (const LineSegment2d& linesegment : obstacle_linesegments) { min_bound = std::min(min_bound, linesegment.DistanceTo({path_point.x(), path_point.y()})); } } min_bound -= vehicle_shortest_dimension; min_bound = min_bound < kEpislon ? 0.0 : min_bound; initial_bounds->push_back(min_bound); } return true; } bool IterativeAnchoringSmoother::SmoothPath( const DiscretizedPath& raw_path_points, const std::vector<double>& bounds, DiscretizedPath* smoothed_path_points) { std::vector<std::pair<double, double>> raw_point2d; std::vector<double> flexible_bounds; for (const auto& path_point : raw_path_points) { raw_point2d.emplace_back(path_point.x(), path_point.y()); } flexible_bounds = bounds; FemPosDeviationSmoother fem_pos_smoother( planner_open_space_config_.iterative_anchoring_smoother_config() .fem_pos_deviation_smoother_config()); // TODO(Jinyun): move to confs const size_t max_iteration_num = 50; bool is_collision_free = false; std::vector<size_t> colliding_point_index; std::vector<std::pair<double, double>> smoothed_point2d; size_t counter = 0; while (!is_collision_free) { if (counter > max_iteration_num) { AERROR << "Maximum iteration reached, path smoother early stops"; return true; } AdjustPathBounds(colliding_point_index, &flexible_bounds); std::vector<double> opt_x; std::vector<double> opt_y; if (!fem_pos_smoother.Solve(raw_point2d, flexible_bounds, &opt_x, &opt_y)) { AERROR << "Smoothing path fails"; return false; } if (opt_x.size() < 2 || opt_y.size() < 2) { AERROR << "Return by fem_pos_smoother is wrong. Size smaller than 2 "; return false; } CHECK_EQ(opt_x.size(), opt_y.size()); size_t point_size = opt_x.size(); smoothed_point2d.clear(); for (size_t i = 0; i < point_size; ++i) { smoothed_point2d.emplace_back(opt_x[i], opt_y[i]); } if (!SetPathProfile(smoothed_point2d, smoothed_path_points)) { AERROR << "Set path profile fails"; return false; } is_collision_free = CheckCollisionAvoidance(*smoothed_path_points, &colliding_point_index); ADEBUG << "loop iteration number is " << counter; ++counter; } return true; } bool IterativeAnchoringSmoother::CheckCollisionAvoidance( const DiscretizedPath& path_points, std::vector<size_t>* colliding_point_index) { CHECK_NOTNULL(colliding_point_index); colliding_point_index->clear(); size_t path_points_size = path_points.size(); for (size_t i = 0; i < path_points_size; ++i) { // Skip checking collision for thoese points colliding originally bool skip_checking = false; for (const auto index : input_colliding_point_index_) { if (i == index) { skip_checking = true; break; } } if (skip_checking) { continue; } const double heading = gear_ ? path_points[i].theta() : NormalizeAngle(path_points[i].theta() + M_PI); Box2d ego_box( {path_points[i].x() + center_shift_distance_ * std::cos(heading), path_points[i].y() + center_shift_distance_ * std::sin(heading)}, heading, ego_length_, ego_width_); bool is_colliding = false; for (const auto& obstacle_linesegments : obstacles_linesegments_vec_) { for (const LineSegment2d& linesegment : obstacle_linesegments) { if (ego_box.HasOverlap(linesegment)) { colliding_point_index->push_back(i); ADEBUG << "point at " << i << "collied with LineSegment " << linesegment.DebugString(); is_colliding = true; break; } } if (is_colliding) { break; } } } if (!colliding_point_index->empty()) { return false; } return true; } void IterativeAnchoringSmoother::AdjustPathBounds( const std::vector<size_t>& colliding_point_index, std::vector<double>* bounds) { CHECK_NOTNULL(bounds); const double collision_decrease_ratio = planner_open_space_config_.iterative_anchoring_smoother_config() .collision_decrease_ratio(); for (const auto index : colliding_point_index) { bounds->at(index) *= collision_decrease_ratio; } // Anchor the end points to enforce the initial end end heading continuity and // zero kappa bounds->at(0) = 0.0; bounds->at(1) = 0.0; bounds->at(bounds->size() - 1) = 0.0; bounds->at(bounds->size() - 2) = 0.0; if (enforce_initial_kappa_) { bounds->at(2) = 0.0; } } bool IterativeAnchoringSmoother::SetPathProfile( const std::vector<std::pair<double, double>>& point2d, DiscretizedPath* raw_path_points) { CHECK_NOTNULL(raw_path_points); raw_path_points->clear(); // Compute path profile std::vector<double> headings; std::vector<double> kappas; std::vector<double> dkappas; std::vector<double> accumulated_s; if (!DiscretePointsMath::ComputePathProfile( point2d, &headings, &accumulated_s, &kappas, &dkappas)) { return false; } CHECK_EQ(point2d.size(), headings.size()); CHECK_EQ(point2d.size(), kappas.size()); CHECK_EQ(point2d.size(), dkappas.size()); CHECK_EQ(point2d.size(), accumulated_s.size()); // Load into path point size_t points_size = point2d.size(); for (size_t i = 0; i < points_size; ++i) { PathPoint path_point; path_point.set_x(point2d[i].first); path_point.set_y(point2d[i].second); path_point.set_theta(headings[i]); path_point.set_s(accumulated_s[i]); path_point.set_kappa(kappas[i]); path_point.set_dkappa(dkappas[i]); raw_path_points->push_back(std::move(path_point)); } return true; } bool IterativeAnchoringSmoother::CheckGear(const Eigen::MatrixXd& xWS) { CHECK_GT(xWS.size(), 1); double init_heading_angle = xWS(2, 0); const Vec2d init_tracking_vector(xWS(0, 1) - xWS(0, 0), xWS(1, 1) - xWS(1, 0)); double init_tracking_angle = init_tracking_vector.Angle(); return std::abs(NormalizeAngle(init_tracking_angle - init_heading_angle)) < M_PI_2; } bool IterativeAnchoringSmoother::SmoothSpeed(const double init_a, const double init_v, const double path_length, SpeedData* smoothed_speeds) { const double max_forward_v = planner_open_space_config_.iterative_anchoring_smoother_config() .max_forward_v(); const double max_reverse_v = planner_open_space_config_.iterative_anchoring_smoother_config() .max_reverse_v(); const double max_forward_acc = planner_open_space_config_.iterative_anchoring_smoother_config() .max_forward_acc(); const double max_reverse_acc = planner_open_space_config_.iterative_anchoring_smoother_config() .max_reverse_acc(); const double max_acc_jerk = planner_open_space_config_.iterative_anchoring_smoother_config() .max_acc_jerk(); const double delta_t = planner_open_space_config_.iterative_anchoring_smoother_config() .delta_t(); const double total_t = 2 * path_length / max_reverse_acc * 10; ADEBUG << "total_t is : " << total_t; const size_t num_of_knots = static_cast<size_t>(total_t / delta_t) + 1; PiecewiseJerkSpeedProblem piecewise_jerk_problem( num_of_knots, delta_t, {0.0, std::abs(init_v), std::abs(init_a)}); auto s_curve_config = planner_open_space_config_.iterative_anchoring_smoother_config() .s_curve_config(); // set end constraints std::vector<std::pair<double, double>> x_bounds(num_of_knots, {0.0, path_length}); const double max_v = gear_ ? max_forward_v : max_reverse_v; const double max_acc = gear_ ? max_forward_acc : max_reverse_acc; const auto upper_dx = std::fmax(max_v, std::abs(init_v)); std::vector<std::pair<double, double>> dx_bounds(num_of_knots, {0.0, upper_dx}); std::vector<std::pair<double, double>> ddx_bounds(num_of_knots, {-max_acc, max_acc}); x_bounds[num_of_knots - 1] = std::make_pair(path_length, path_length); dx_bounds[num_of_knots - 1] = std::make_pair(0.0, 0.0); ddx_bounds[num_of_knots - 1] = std::make_pair(0.0, 0.0); std::vector<double> x_ref(num_of_knots, path_length); piecewise_jerk_problem.set_x_ref(s_curve_config.ref_s_weight(), std::move(x_ref)); piecewise_jerk_problem.set_weight_ddx(s_curve_config.acc_weight()); piecewise_jerk_problem.set_weight_dddx(s_curve_config.jerk_weight()); piecewise_jerk_problem.set_x_bounds(std::move(x_bounds)); piecewise_jerk_problem.set_dx_bounds(std::move(dx_bounds)); piecewise_jerk_problem.set_ddx_bounds(std::move(ddx_bounds)); piecewise_jerk_problem.set_dddx_bound(max_acc_jerk); // Solve the problem if (!piecewise_jerk_problem.Optimize()) { AERROR << "Piecewise jerk speed optimizer failed!"; return false; } // 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(); // Assign speed point by gear smoothed_speeds->AppendSpeedPoint(s[0], 0.0, ds[0], dds[0], 0.0); const double kEpislon = 1.0e-4; const double sEpislon = 1.0e-1; for (size_t i = 1; i < num_of_knots; ++i) { if (s[i - 1] - s[i] > kEpislon) { AERROR << "unexpected decreasing s in speed smoothing at time " << static_cast<double>(i) * delta_t << "with total time " << total_t; return false; } smoothed_speeds->AppendSpeedPoint(s[i], delta_t * static_cast<double>(i), ds[i], dds[i], (dds[i] - dds[i - 1]) / delta_t); // Cut the speed data when it is about to meet end condition if (path_length - s[i] < sEpislon) { break; } } return true; } bool IterativeAnchoringSmoother::CombinePathAndSpeed( const DiscretizedPath& path_points, const SpeedData& speed_points, DiscretizedTrajectory* discretized_trajectory) { CHECK_NOTNULL(discretized_trajectory); discretized_trajectory->clear(); // TODO(Jinyun): move to confs const double kDenseTimeResolution = 0.1; const double time_horizon = speed_points.TotalTime() + kDenseTimeResolution * 1.0e-6; if (path_points.empty()) { AERROR << "path data is empty"; return false; } ADEBUG << "speed_points.TotalTime() " << speed_points.TotalTime(); for (double cur_rel_time = 0.0; cur_rel_time < time_horizon; cur_rel_time += kDenseTimeResolution) { common::SpeedPoint speed_point; if (!speed_points.EvaluateByTime(cur_rel_time, &speed_point)) { AERROR << "Fail to get speed point with relative time " << cur_rel_time; return false; } if (speed_point.s() > path_points.Length()) { break; } common::PathPoint path_point = path_points.Evaluate(speed_point.s()); common::TrajectoryPoint trajectory_point; trajectory_point.mutable_path_point()->CopyFrom(path_point); trajectory_point.set_v(speed_point.v()); trajectory_point.set_a(speed_point.a()); trajectory_point.set_relative_time(speed_point.t()); discretized_trajectory->AppendTrajectoryPoint(trajectory_point); } ADEBUG << "path length before combine " << path_points.Length(); ADEBUG << "trajectory length after combine " << discretized_trajectory->GetSpatialLength(); return true; } void IterativeAnchoringSmoother::AdjustPathAndSpeedByGear( DiscretizedTrajectory* discretized_trajectory) { if (gear_) { return; } std::for_each( discretized_trajectory->begin(), discretized_trajectory->end(), [](TrajectoryPoint& trajectory_point) { trajectory_point.mutable_path_point()->set_theta( NormalizeAngle(trajectory_point.path_point().theta() + M_PI)); trajectory_point.mutable_path_point()->set_s( -1.0 * trajectory_point.path_point().s()); trajectory_point.mutable_path_point()->set_kappa( -1.0 * trajectory_point.path_point().kappa()); // dkappa stays the same as direction of both kappa and s are reversed trajectory_point.set_v(-1.0 * trajectory_point.v()); trajectory_point.set_a(-1.0 * trajectory_point.a()); }); } bool IterativeAnchoringSmoother::GenerateStopProfileFromPolynomial( const double init_acc, const double init_speed, const double stop_distance, SpeedData* smoothed_speeds) { static constexpr double kMaxT = 8.0; static constexpr double kUnitT = 0.2; for (double t = 2.0; t <= kMaxT; t += kUnitT) { QuinticPolynomialCurve1d curve(0.0, init_speed, init_acc, stop_distance, 0.0, 0.0, t); if (!IsValidPolynomialProfile(curve)) { continue; } for (double curve_t = 0.0; curve_t <= t; curve_t += kUnitT) { const double curve_s = curve.Evaluate(0, curve_t); const double curve_v = curve.Evaluate(1, curve_t); const double curve_a = curve.Evaluate(2, curve_t); const double curve_da = curve.Evaluate(3, curve_t); smoothed_speeds->AppendSpeedPoint(curve_s, curve_t, curve_v, curve_a, curve_da); } return true; } AERROR << "GenerateStopProfileFromPolynomial fails."; return false; } bool IterativeAnchoringSmoother::IsValidPolynomialProfile( const QuinticPolynomialCurve1d& curve) { for (double evaluate_t = 0.1; evaluate_t <= curve.ParamLength(); evaluate_t += 0.2) { const double v = curve.Evaluate(1, evaluate_t); const double a = curve.Evaluate(2, evaluate_t); static constexpr double kEpsilon = 1e-3; if (v < -kEpsilon || a > 1.0) { return false; } } return true; } double IterativeAnchoringSmoother::CalcHeadings( const DiscretizedPath& path_points, const size_t index) { CHECK_GT(path_points.size(), 2U); double dx = 0.0; double dy = 0.0; if (index == 0) { dx = path_points[index + 1].x() - path_points[index].x(); dy = path_points[index + 1].y() - path_points[index].y(); } else if (index == path_points.size() - 1) { dx = path_points[index].x() - path_points[index - 1].x(); dy = path_points[index].y() - path_points[index - 1].y(); } else { dx = 0.5 * (path_points[index + 1].x() - path_points[index - 1].x()); dy = 0.5 * (path_points[index + 1].y() - path_points[index - 1].y()); } return std::atan2(dy, dx); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_problem.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 "Eigen/Dense" #include "modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_ipopt_interface.h" #include "modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_ipopt_qp_interface.h" #include "modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_osqp_interface.h" #include "modules/planning/open_space/trajectory_smoother/dual_variable_warm_start_slack_osqp_interface.h" #include "modules/common_msgs/planning_msgs/planning.pb.h" namespace apollo { namespace planning { class DualVariableWarmStartProblem { public: explicit DualVariableWarmStartProblem( const PlannerOpenSpaceConfig& planner_open_space_config); virtual ~DualVariableWarmStartProblem() = default; bool Solve(const size_t horizon, const double ts, const Eigen::MatrixXd& ego, const size_t obstacles_num, const Eigen::MatrixXi& obstacles_edges_num, const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b, const Eigen::MatrixXd& xWS, Eigen::MatrixXd* l_warm_up, Eigen::MatrixXd* n_warm_up, Eigen::MatrixXd* s_warm_up); private: PlannerOpenSpaceConfig planner_open_space_config_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/trajectory_smoother/iterative_anchoring_smoother.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 <utility> #include <vector> #include "Eigen/Eigen" #include "modules/common_msgs/planning_msgs/planning.pb.h" #include "modules/common/math/box2d.h" #include "modules/common/math/line_segment2d.h" #include "modules/common/math/vec2d.h" #include "modules/planning/common/path/discretized_path.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/planner_open_space_config.pb.h" namespace apollo { namespace planning { class IterativeAnchoringSmoother { public: IterativeAnchoringSmoother( const PlannerOpenSpaceConfig& planner_open_space_config); ~IterativeAnchoringSmoother() = default; bool Smooth(const Eigen::MatrixXd& xWS, const double init_a, const double init_v, const std::vector<std::vector<common::math::Vec2d>>& obstacles_vertices_vec, DiscretizedTrajectory* discretized_trajectory); private: void AdjustStartEndHeading( const Eigen::MatrixXd& xWS, std::vector<std::pair<double, double>>* const point2d); bool ReAnchoring(const std::vector<size_t>& colliding_point_index, DiscretizedPath* path_points); bool GenerateInitialBounds(const DiscretizedPath& path_points, std::vector<double>* initial_bounds); bool SmoothPath(const DiscretizedPath& raw_path_points, const std::vector<double>& bounds, DiscretizedPath* smoothed_path_points); bool CheckCollisionAvoidance(const DiscretizedPath& path_points, std::vector<size_t>* colliding_point_index); void AdjustPathBounds(const std::vector<size_t>& colliding_point_index, std::vector<double>* bounds); bool SetPathProfile(const std::vector<std::pair<double, double>>& point2d, DiscretizedPath* raw_path_points); bool CheckGear(const Eigen::MatrixXd& xWS); bool SmoothSpeed(const double init_a, const double init_v, const double path_length, SpeedData* smoothed_speeds); bool CombinePathAndSpeed(const DiscretizedPath& path_points, const SpeedData& speed_points, DiscretizedTrajectory* discretized_trajectory); void AdjustPathAndSpeedByGear(DiscretizedTrajectory* discretized_trajectory); bool GenerateStopProfileFromPolynomial(const double init_acc, const double init_speed, const double stop_distance, SpeedData* smoothed_speeds); bool IsValidPolynomialProfile(const QuinticPolynomialCurve1d& curve); // @brief: a helper function on discrete point heading adjustment double CalcHeadings(const DiscretizedPath& path_points, const size_t index); private: // vehicle_param double ego_length_ = 0.0; double ego_width_ = 0.0; double center_shift_distance_ = 0.0; std::vector<std::vector<common::math::LineSegment2d>> obstacles_linesegments_vec_; std::vector<size_t> input_colliding_point_index_; bool enforce_initial_kappa_ = true; // gear DRIVE as true and gear REVERSE as false bool gear_ = false; PlannerOpenSpaceConfig planner_open_space_config_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/coarse_trajectory_generator/node3d.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* * @file */ #pragma once #include <memory> #include <string> #include <vector> #include "modules/common/math/box2d.h" #include "modules/planning/constraint_checker/collision_checker.h" #include "modules/planning/proto/planner_open_space_config.pb.h" namespace apollo { namespace planning { class Node3d { public: Node3d(const double x, const double y, const double phi); Node3d(const double x, const double y, const double phi, const std::vector<double>& XYbounds, const PlannerOpenSpaceConfig& open_space_conf); Node3d(const std::vector<double>& traversed_x, const std::vector<double>& traversed_y, const std::vector<double>& traversed_phi, const std::vector<double>& XYbounds, const PlannerOpenSpaceConfig& open_space_conf); virtual ~Node3d() = default; static apollo::common::math::Box2d GetBoundingBox( const common::VehicleParam& vehicle_param_, const double x, const double y, const double phi); double GetCost() const { return traj_cost_ + heuristic_cost_; } double GetTrajCost() const { return traj_cost_; } double GetHeuCost() const { return heuristic_cost_; } int GetGridX() const { return x_grid_; } int GetGridY() const { return y_grid_; } int GetGridPhi() const { return phi_grid_; } double GetX() const { return x_; } double GetY() const { return y_; } double GetPhi() const { return phi_; } bool operator==(const Node3d& right) const; const std::string& GetIndex() const { return index_; } size_t GetStepSize() const { return step_size_; } bool GetDirec() const { return direction_; } double GetSteer() const { return steering_; } std::shared_ptr<Node3d> GetPreNode() const { return pre_node_; } const std::vector<double>& GetXs() const { return traversed_x_; } const std::vector<double>& GetYs() const { return traversed_y_; } const std::vector<double>& GetPhis() const { return traversed_phi_; } void SetPre(std::shared_ptr<Node3d> pre_node) { pre_node_ = pre_node; } void SetDirec(bool direction) { direction_ = direction; } void SetTrajCost(double cost) { traj_cost_ = cost; } void SetHeuCost(double cost) { heuristic_cost_ = cost; } void SetSteer(double steering) { steering_ = steering; } private: static std::string ComputeStringIndex(int x_grid, int y_grid, int phi_grid); private: double x_ = 0.0; double y_ = 0.0; double phi_ = 0.0; size_t step_size_ = 1; std::vector<double> traversed_x_; std::vector<double> traversed_y_; std::vector<double> traversed_phi_; int x_grid_ = 0; int y_grid_ = 0; int phi_grid_ = 0; std::string index_; double traj_cost_ = 0.0; double heuristic_cost_ = 0.0; double cost_ = 0.0; std::shared_ptr<Node3d> pre_node_ = nullptr; double steering_ = 0.0; // true for moving forward and false for moving backward bool direction_ = true; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/coarse_trajectory_generator/node3d.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/open_space/coarse_trajectory_generator/node3d.h" #include "absl/strings/str_cat.h" namespace apollo { namespace planning { using apollo::common::math::Box2d; Node3d::Node3d(double x, double y, double phi) { x_ = x; y_ = y; phi_ = phi; } Node3d::Node3d(double x, double y, double phi, const std::vector<double>& XYbounds, const PlannerOpenSpaceConfig& open_space_conf) { CHECK_EQ(XYbounds.size(), 4U) << "XYbounds size is not 4, but" << XYbounds.size(); x_ = x; y_ = y; phi_ = phi; x_grid_ = static_cast<int>( (x_ - XYbounds[0]) / open_space_conf.warm_start_config().xy_grid_resolution()); y_grid_ = static_cast<int>( (y_ - XYbounds[2]) / open_space_conf.warm_start_config().xy_grid_resolution()); phi_grid_ = static_cast<int>( (phi_ - (-M_PI)) / open_space_conf.warm_start_config().phi_grid_resolution()); traversed_x_.push_back(x); traversed_y_.push_back(y); traversed_phi_.push_back(phi); index_ = ComputeStringIndex(x_grid_, y_grid_, phi_grid_); } Node3d::Node3d(const std::vector<double>& traversed_x, const std::vector<double>& traversed_y, const std::vector<double>& traversed_phi, const std::vector<double>& XYbounds, const PlannerOpenSpaceConfig& open_space_conf) { CHECK_EQ(XYbounds.size(), 4U) << "XYbounds size is not 4, but" << XYbounds.size(); CHECK_EQ(traversed_x.size(), traversed_y.size()); CHECK_EQ(traversed_x.size(), traversed_phi.size()); x_ = traversed_x.back(); y_ = traversed_y.back(); phi_ = traversed_phi.back(); // XYbounds in xmin, xmax, ymin, ymax x_grid_ = static_cast<int>( (x_ - XYbounds[0]) / open_space_conf.warm_start_config().xy_grid_resolution()); y_grid_ = static_cast<int>( (y_ - XYbounds[2]) / open_space_conf.warm_start_config().xy_grid_resolution()); phi_grid_ = static_cast<int>( (phi_ - (-M_PI)) / open_space_conf.warm_start_config().phi_grid_resolution()); traversed_x_ = traversed_x; traversed_y_ = traversed_y; traversed_phi_ = traversed_phi; index_ = ComputeStringIndex(x_grid_, y_grid_, phi_grid_); step_size_ = traversed_x.size(); } Box2d Node3d::GetBoundingBox(const common::VehicleParam& vehicle_param_, const double x, const double y, const double phi) { double ego_length = vehicle_param_.length(); double ego_width = vehicle_param_.width(); double shift_distance = ego_length / 2.0 - vehicle_param_.back_edge_to_center(); Box2d ego_box( {x + shift_distance * std::cos(phi), y + shift_distance * std::sin(phi)}, phi, ego_length, ego_width); return ego_box; } bool Node3d::operator==(const Node3d& right) const { return right.GetIndex() == index_; } std::string Node3d::ComputeStringIndex(int x_grid, int y_grid, int phi_grid) { return absl::StrCat(x_grid, "_", y_grid, "_", phi_grid); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/coarse_trajectory_generator/hybrid_a_star.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/open_space/coarse_trajectory_generator/hybrid_a_star.h" #include <limits> #include "modules/planning/math/piecewise_jerk/piecewise_jerk_speed_problem.h" namespace apollo { namespace planning { using apollo::common::math::Box2d; using apollo::common::math::Vec2d; using apollo::cyber::Clock; HybridAStar::HybridAStar(const PlannerOpenSpaceConfig& open_space_conf) { planner_open_space_config_.CopyFrom(open_space_conf); reed_shepp_generator_ = std::make_unique<ReedShepp>(vehicle_param_, planner_open_space_config_); grid_a_star_heuristic_generator_ = std::make_unique<GridSearch>(planner_open_space_config_); next_node_num_ = planner_open_space_config_.warm_start_config().next_node_num(); max_steer_angle_ = vehicle_param_.max_steer_angle() / vehicle_param_.steer_ratio() * planner_open_space_config_.warm_start_config() .traj_kappa_contraint_ratio(); step_size_ = planner_open_space_config_.warm_start_config().step_size(); xy_grid_resolution_ = planner_open_space_config_.warm_start_config().xy_grid_resolution(); delta_t_ = planner_open_space_config_.delta_t(); traj_forward_penalty_ = planner_open_space_config_.warm_start_config().traj_forward_penalty(); traj_back_penalty_ = planner_open_space_config_.warm_start_config().traj_back_penalty(); traj_gear_switch_penalty_ = planner_open_space_config_.warm_start_config().traj_gear_switch_penalty(); traj_steer_penalty_ = planner_open_space_config_.warm_start_config().traj_steer_penalty(); traj_steer_change_penalty_ = planner_open_space_config_.warm_start_config() .traj_steer_change_penalty(); acc_weight_ = planner_open_space_config_.iterative_anchoring_smoother_config() .s_curve_config() .acc_weight(); jerk_weight_ = planner_open_space_config_.iterative_anchoring_smoother_config() .s_curve_config() .jerk_weight(); kappa_penalty_weight_ = planner_open_space_config_.iterative_anchoring_smoother_config() .s_curve_config() .kappa_penalty_weight(); ref_s_weight_ = planner_open_space_config_.iterative_anchoring_smoother_config() .s_curve_config() .ref_s_weight(); ref_v_weight_ = planner_open_space_config_.iterative_anchoring_smoother_config() .s_curve_config() .ref_v_weight(); max_forward_v_ = planner_open_space_config_.iterative_anchoring_smoother_config() .max_forward_v(); max_reverse_v_ = planner_open_space_config_.iterative_anchoring_smoother_config() .max_reverse_v(); max_forward_acc_ = planner_open_space_config_.iterative_anchoring_smoother_config() .max_forward_acc(); max_reverse_acc_ = planner_open_space_config_.iterative_anchoring_smoother_config() .max_reverse_acc(); max_acc_jerk_ = planner_open_space_config_.iterative_anchoring_smoother_config() .max_acc_jerk(); } bool HybridAStar::AnalyticExpansion(std::shared_ptr<Node3d> current_node) { std::shared_ptr<ReedSheppPath> reeds_shepp_to_check = std::make_shared<ReedSheppPath>(); if (!reed_shepp_generator_->ShortestRSP(current_node, end_node_, reeds_shepp_to_check)) { AERROR << "ShortestRSP failed"; return false; } if (!RSPCheck(reeds_shepp_to_check)) { return false; } AINFO << "Reach the end configuration with Reed Sharp"; AINFO << "current node x" << current_node->GetX() << "," << current_node->GetY(); AINFO << "final node x" << end_node_->GetX() << "," << end_node_->GetY(); AINFO << "distance " << sqrt(pow((current_node->GetX() - end_node_->GetX()), 2) + pow((current_node->GetY() - end_node_->GetY()), 2)); AINFO << "delta phi" << current_node->GetPhi() - end_node_->GetPhi(); AINFO << "reed shepp set_type,gear,length"; for (size_t i = 0; i < reeds_shepp_to_check->segs_types.size(); i++) { AINFO << reeds_shepp_to_check->segs_types[i] << ", " << reeds_shepp_to_check->gear[i] << "," << reeds_shepp_to_check->segs_lengths[i]; } AINFO << reeds_shepp_to_check->x.front() << "," << reeds_shepp_to_check->y.front(); AINFO << reeds_shepp_to_check->x.back() << "," << reeds_shepp_to_check->y.back(); // load the whole RSP as nodes and add to the close set final_node_ = LoadRSPinCS(reeds_shepp_to_check, current_node); return true; } bool HybridAStar::RSPCheck( const std::shared_ptr<ReedSheppPath> reeds_shepp_to_end) { std::shared_ptr<Node3d> node = std::shared_ptr<Node3d>(new Node3d( reeds_shepp_to_end->x, reeds_shepp_to_end->y, reeds_shepp_to_end->phi, XYbounds_, planner_open_space_config_)); return ValidityCheck(node); } bool HybridAStar::ValidityCheck(std::shared_ptr<Node3d> node) { CHECK_NOTNULL(node); CHECK_GT(node->GetStepSize(), 0U); if (obstacles_linesegments_vec_.empty()) { return true; } size_t node_step_size = node->GetStepSize(); const auto& traversed_x = node->GetXs(); const auto& traversed_y = node->GetYs(); const auto& traversed_phi = node->GetPhis(); // The first {x, y, phi} is collision free unless they are start and end // configuration of search problem size_t check_start_index = 0; if (node_step_size == 1) { check_start_index = 0; } else { check_start_index = 1; } for (size_t i = check_start_index; i < node_step_size; ++i) { if (traversed_x[i] > XYbounds_[1] || traversed_x[i] < XYbounds_[0] || traversed_y[i] > XYbounds_[3] || traversed_y[i] < XYbounds_[2]) { return false; } Box2d bounding_box = Node3d::GetBoundingBox( vehicle_param_, traversed_x[i], traversed_y[i], traversed_phi[i]); for (const auto& obstacle_linesegments : obstacles_linesegments_vec_) { for (const common::math::LineSegment2d& linesegment : obstacle_linesegments) { if (bounding_box.HasOverlap(linesegment)) { ADEBUG << "collision start at x: " << linesegment.start().x(); ADEBUG << "collision start at y: " << linesegment.start().y(); ADEBUG << "collision end at x: " << linesegment.end().x(); ADEBUG << "collision end at y: " << linesegment.end().y(); return false; } } } } return true; } std::shared_ptr<Node3d> HybridAStar::LoadRSPinCS( const std::shared_ptr<ReedSheppPath> reeds_shepp_to_end, std::shared_ptr<Node3d> current_node) { std::shared_ptr<Node3d> end_node = std::shared_ptr<Node3d>(new Node3d( reeds_shepp_to_end->x, reeds_shepp_to_end->y, reeds_shepp_to_end->phi, XYbounds_, planner_open_space_config_)); end_node->SetPre(current_node); close_set_.emplace(end_node->GetIndex(), end_node); return end_node; } std::shared_ptr<Node3d> HybridAStar::Next_node_generator( std::shared_ptr<Node3d> current_node, size_t next_node_index) { double steering = 0.0; double traveled_distance = 0.0; if (next_node_index < static_cast<double>(next_node_num_) / 2) { steering = -max_steer_angle_ + (2 * max_steer_angle_ / (static_cast<double>(next_node_num_) / 2 - 1)) * static_cast<double>(next_node_index); traveled_distance = step_size_; } else { size_t index = next_node_index - next_node_num_ / 2; steering = -max_steer_angle_ + (2 * max_steer_angle_ / (static_cast<double>(next_node_num_) / 2 - 1)) * static_cast<double>(index); traveled_distance = -step_size_; } // take above motion primitive to generate a curve driving the car to a // different grid double arc = std::sqrt(2) * xy_grid_resolution_; std::vector<double> intermediate_x; std::vector<double> intermediate_y; std::vector<double> intermediate_phi; double last_x = current_node->GetX(); double last_y = current_node->GetY(); double last_phi = current_node->GetPhi(); intermediate_x.push_back(last_x); intermediate_y.push_back(last_y); intermediate_phi.push_back(last_phi); for (size_t i = 0; i < arc / step_size_; ++i) { const double next_x = last_x + traveled_distance * std::cos(last_phi); const double next_y = last_y + traveled_distance * std::sin(last_phi); const double next_phi = common::math::NormalizeAngle( last_phi + traveled_distance / vehicle_param_.wheel_base() * std::tan(steering)); intermediate_x.push_back(next_x); intermediate_y.push_back(next_y); intermediate_phi.push_back(next_phi); last_x = next_x; last_y = next_y; last_phi = next_phi; } // check if the vehicle runs outside of XY boundary if (intermediate_x.back() > XYbounds_[1] || intermediate_x.back() < XYbounds_[0] || intermediate_y.back() > XYbounds_[3] || intermediate_y.back() < XYbounds_[2]) { return nullptr; } std::shared_ptr<Node3d> next_node = std::shared_ptr<Node3d>( new Node3d(intermediate_x, intermediate_y, intermediate_phi, XYbounds_, planner_open_space_config_)); next_node->SetPre(current_node); next_node->SetDirec(traveled_distance > 0.0); next_node->SetSteer(steering); return next_node; } void HybridAStar::CalculateNodeCost(std::shared_ptr<Node3d> current_node, std::shared_ptr<Node3d> next_node) { next_node->SetTrajCost(current_node->GetTrajCost() + TrajCost(current_node, next_node)); // evaluate heuristic cost double optimal_path_cost = 0.0; optimal_path_cost += HoloObstacleHeuristic(next_node); next_node->SetHeuCost(optimal_path_cost); } double HybridAStar::TrajCost(std::shared_ptr<Node3d> current_node, std::shared_ptr<Node3d> next_node) { // evaluate cost on the trajectory and add current cost double piecewise_cost = 0.0; if (next_node->GetDirec()) { piecewise_cost += static_cast<double>(next_node->GetStepSize() - 1) * step_size_ * traj_forward_penalty_; } else { piecewise_cost += static_cast<double>(next_node->GetStepSize() - 1) * step_size_ * traj_back_penalty_; } if (current_node->GetDirec() != next_node->GetDirec()) { piecewise_cost += traj_gear_switch_penalty_; } piecewise_cost += traj_steer_penalty_ * std::abs(next_node->GetSteer()); piecewise_cost += traj_steer_change_penalty_ * std::abs(next_node->GetSteer() - current_node->GetSteer()); return piecewise_cost; } double HybridAStar::HoloObstacleHeuristic(std::shared_ptr<Node3d> next_node) { return grid_a_star_heuristic_generator_->CheckDpMap(next_node->GetX(), next_node->GetY()); } bool HybridAStar::GetResult(HybridAStartResult* result) { std::shared_ptr<Node3d> current_node = final_node_; std::vector<double> hybrid_a_x; std::vector<double> hybrid_a_y; std::vector<double> hybrid_a_phi; while (current_node->GetPreNode() != nullptr) { std::vector<double> x = current_node->GetXs(); std::vector<double> y = current_node->GetYs(); std::vector<double> phi = current_node->GetPhis(); if (x.empty() || y.empty() || phi.empty()) { AERROR << "result size check failed"; return false; } if (x.size() != y.size() || x.size() != phi.size()) { AERROR << "states sizes are not equal"; return false; } std::reverse(x.begin(), x.end()); std::reverse(y.begin(), y.end()); std::reverse(phi.begin(), phi.end()); x.pop_back(); y.pop_back(); phi.pop_back(); hybrid_a_x.insert(hybrid_a_x.end(), x.begin(), x.end()); hybrid_a_y.insert(hybrid_a_y.end(), y.begin(), y.end()); hybrid_a_phi.insert(hybrid_a_phi.end(), phi.begin(), phi.end()); current_node = current_node->GetPreNode(); } hybrid_a_x.push_back(current_node->GetX()); hybrid_a_y.push_back(current_node->GetY()); hybrid_a_phi.push_back(current_node->GetPhi()); std::reverse(hybrid_a_x.begin(), hybrid_a_x.end()); std::reverse(hybrid_a_y.begin(), hybrid_a_y.end()); std::reverse(hybrid_a_phi.begin(), hybrid_a_phi.end()); (*result).x = hybrid_a_x; (*result).y = hybrid_a_y; (*result).phi = hybrid_a_phi; if (!GetTemporalProfile(result)) { AERROR << "GetSpeedProfile from Hybrid Astar path fails"; return false; } if (result->x.size() != result->y.size() || result->x.size() != result->v.size() || result->x.size() != result->phi.size()) { AERROR << "state sizes not equal, " << "result->x.size(): " << result->x.size() << "result->y.size()" << result->y.size() << "result->phi.size()" << result->phi.size() << "result->v.size()" << result->v.size(); return false; } if (result->a.size() != result->steer.size() || result->x.size() - result->a.size() != 1) { AERROR << "control sizes not equal or not right"; AERROR << " acceleration size: " << result->a.size(); AERROR << " steer size: " << result->steer.size(); AERROR << " x size: " << result->x.size(); return false; } return true; } bool HybridAStar::GenerateSpeedAcceleration(HybridAStartResult* result) { // Sanity Check if (result->x.size() < 2 || result->y.size() < 2 || result->phi.size() < 2) { AERROR << "result size check when generating speed and acceleration fail"; return false; } const size_t x_size = result->x.size(); // load velocity from position // initial and end speed are set to be zeros result->v.push_back(0.0); for (size_t i = 1; i + 1 < x_size; ++i) { double discrete_v = (((result->x[i + 1] - result->x[i]) / delta_t_) * std::cos(result->phi[i]) + ((result->x[i] - result->x[i - 1]) / delta_t_) * std::cos(result->phi[i])) / 2.0 + (((result->y[i + 1] - result->y[i]) / delta_t_) * std::sin(result->phi[i]) + ((result->y[i] - result->y[i - 1]) / delta_t_) * std::sin(result->phi[i])) / 2.0; result->v.push_back(discrete_v); } result->v.push_back(0.0); // load acceleration from velocity for (size_t i = 0; i + 1 < x_size; ++i) { const double discrete_a = (result->v[i + 1] - result->v[i]) / delta_t_; result->a.push_back(discrete_a); } // load steering from phi for (size_t i = 0; i + 1 < x_size; ++i) { double discrete_steer = (result->phi[i + 1] - result->phi[i]) * vehicle_param_.wheel_base() / step_size_; if (result->v[i] > 0.0) { discrete_steer = std::atan(discrete_steer); } else { discrete_steer = std::atan(-discrete_steer); } result->steer.push_back(discrete_steer); } return true; } bool HybridAStar::GenerateSCurveSpeedAcceleration(HybridAStartResult* result) { // sanity check CHECK_NOTNULL(result); if (result->x.size() < 2 || result->y.size() < 2 || result->phi.size() < 2) { AERROR << "result size check when generating speed and acceleration fail"; return false; } if (result->x.size() != result->y.size() || result->x.size() != result->phi.size()) { AERROR << "result sizes not equal"; return false; } // get gear info double init_heading = result->phi.front(); const Vec2d init_tracking_vector(result->x[1] - result->x[0], result->y[1] - result->y[0]); const double gear = std::abs(common::math::NormalizeAngle( init_heading - init_tracking_vector.Angle())) < M_PI_2; // get path lengh size_t path_points_size = result->x.size(); double accumulated_s = 0.0; result->accumulated_s.clear(); auto last_x = result->x.front(); auto last_y = result->y.front(); for (size_t i = 0; i < path_points_size; ++i) { double x_diff = result->x[i] - last_x; double y_diff = result->y[i] - last_y; accumulated_s += std::sqrt(x_diff * x_diff + y_diff * y_diff); result->accumulated_s.push_back(accumulated_s); last_x = result->x[i]; last_y = result->y[i]; } // assume static initial state const double init_v = 0.0; const double init_a = 0.0; // minimum time speed optimization // TODO(Jinyun): move to confs SpeedData speed_data; // TODO(Jinyun): explore better time horizon heuristic const double path_length = result->accumulated_s.back(); const double total_t = std::max(gear ? 1.5 * (max_forward_v_ * max_forward_v_ + path_length * max_forward_acc_) / (max_forward_acc_ * max_forward_v_) : 1.5 * (max_reverse_v_ * max_reverse_v_ + path_length * max_reverse_acc_) / (max_reverse_acc_ * max_reverse_v_), 10.0); if (total_t + delta_t_ >= delta_t_ * std::numeric_limits<size_t>::max()) { AERROR << "Number of knots overflow. total_t: " << total_t << ", delta_t: " << delta_t_; return false; } const size_t num_of_knots = static_cast<size_t>(total_t / delta_t_) + 1; PiecewiseJerkSpeedProblem piecewise_jerk_problem( num_of_knots, delta_t_, {0.0, std::abs(init_v), std::abs(init_a)}); // set end constraints std::vector<std::pair<double, double>> x_bounds(num_of_knots, {0.0, path_length}); const double max_v = gear ? max_forward_v_ : max_reverse_v_; const double max_acc = gear ? max_forward_acc_ : max_reverse_acc_; const auto upper_dx = std::fmax(max_v, std::abs(init_v)); std::vector<std::pair<double, double>> dx_bounds(num_of_knots, {0.0, upper_dx}); std::vector<std::pair<double, double>> ddx_bounds(num_of_knots, {-max_acc, max_acc}); x_bounds[num_of_knots - 1] = std::make_pair(path_length, path_length); dx_bounds[num_of_knots - 1] = std::make_pair(0.0, 0.0); ddx_bounds[num_of_knots - 1] = std::make_pair(0.0, 0.0); // TODO(Jinyun): move to confs std::vector<double> x_ref(num_of_knots, path_length); piecewise_jerk_problem.set_x_ref(ref_s_weight_, std::move(x_ref)); piecewise_jerk_problem.set_dx_ref(ref_v_weight_, max_v * 0.8); piecewise_jerk_problem.set_weight_ddx(acc_weight_); piecewise_jerk_problem.set_weight_dddx(jerk_weight_); piecewise_jerk_problem.set_x_bounds(std::move(x_bounds)); piecewise_jerk_problem.set_dx_bounds(std::move(dx_bounds)); piecewise_jerk_problem.set_ddx_bounds(std::move(ddx_bounds)); piecewise_jerk_problem.set_dddx_bound(max_acc_jerk_); // solve the problem if (!piecewise_jerk_problem.Optimize()) { AERROR << "Piecewise jerk speed optimizer failed!"; return false; } // 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(); // assign speed point by gear speed_data.AppendSpeedPoint(s[0], 0.0, ds[0], dds[0], 0.0); const double kEpislon = 1.0e-6; const double sEpislon = 1.0e-6; for (size_t i = 1; i < num_of_knots; ++i) { if (s[i - 1] - s[i] > kEpislon) { ADEBUG << "unexpected decreasing s in speed smoothing at time " << static_cast<double>(i) * delta_t_ << "with total time " << total_t; break; } speed_data.AppendSpeedPoint(s[i], delta_t_ * static_cast<double>(i), ds[i], dds[i], (dds[i] - dds[i - 1]) / delta_t_); // cut the speed data when it is about to meet end condition if (path_length - s[i] < sEpislon) { break; } } // combine speed and path profile DiscretizedPath path_data; for (size_t i = 0; i < path_points_size; ++i) { common::PathPoint path_point; path_point.set_x(result->x[i]); path_point.set_y(result->y[i]); path_point.set_theta(result->phi[i]); path_point.set_s(result->accumulated_s[i]); path_data.push_back(std::move(path_point)); } HybridAStartResult combined_result; // TODO(Jinyun): move to confs const double kDenseTimeResoltuion = 0.5; const double time_horizon = speed_data.TotalTime() + kDenseTimeResoltuion * 1.0e-6; if (path_data.empty()) { AERROR << "path data is empty"; return false; } for (double cur_rel_time = 0.0; cur_rel_time < time_horizon; cur_rel_time += kDenseTimeResoltuion) { common::SpeedPoint speed_point; if (!speed_data.EvaluateByTime(cur_rel_time, &speed_point)) { AERROR << "Fail to get speed point with relative time " << cur_rel_time; return false; } if (speed_point.s() > path_data.Length()) { break; } common::PathPoint path_point = path_data.Evaluate(speed_point.s()); combined_result.x.push_back(path_point.x()); combined_result.y.push_back(path_point.y()); combined_result.phi.push_back(path_point.theta()); combined_result.accumulated_s.push_back(path_point.s()); if (!gear) { combined_result.v.push_back(-speed_point.v()); combined_result.a.push_back(-speed_point.a()); } else { combined_result.v.push_back(speed_point.v()); combined_result.a.push_back(speed_point.a()); } } combined_result.a.pop_back(); // recalc step size path_points_size = combined_result.x.size(); // load steering from phi for (size_t i = 0; i + 1 < path_points_size; ++i) { double discrete_steer = (combined_result.phi[i + 1] - combined_result.phi[i]) * vehicle_param_.wheel_base() / (combined_result.accumulated_s[i + 1] - combined_result.accumulated_s[i]); discrete_steer = gear ? std::atan(discrete_steer) : std::atan(-discrete_steer); combined_result.steer.push_back(discrete_steer); } *result = combined_result; return true; } bool HybridAStar::TrajectoryPartition( const HybridAStartResult& result, std::vector<HybridAStartResult>* partitioned_result) { const auto& x = result.x; const auto& y = result.y; const auto& phi = result.phi; if (x.size() != y.size() || x.size() != phi.size()) { AERROR << "states sizes are not equal when do trajectory partitioning of " "Hybrid A Star result"; return false; } size_t horizon = x.size(); partitioned_result->clear(); partitioned_result->emplace_back(); auto* current_traj = &(partitioned_result->back()); double heading_angle = phi.front(); const Vec2d init_tracking_vector(x[1] - x[0], y[1] - y[0]); double tracking_angle = init_tracking_vector.Angle(); bool current_gear = std::abs(common::math::NormalizeAngle(tracking_angle - heading_angle)) < (M_PI_2); for (size_t i = 0; i < horizon - 1; ++i) { heading_angle = phi[i]; const Vec2d tracking_vector(x[i + 1] - x[i], y[i + 1] - y[i]); tracking_angle = tracking_vector.Angle(); bool gear = std::abs(common::math::NormalizeAngle(tracking_angle - heading_angle)) < (M_PI_2); if (gear != current_gear) { current_traj->x.push_back(x[i]); current_traj->y.push_back(y[i]); current_traj->phi.push_back(phi[i]); partitioned_result->emplace_back(); current_traj = &(partitioned_result->back()); current_gear = gear; } current_traj->x.push_back(x[i]); current_traj->y.push_back(y[i]); current_traj->phi.push_back(phi[i]); } current_traj->x.push_back(x.back()); current_traj->y.push_back(y.back()); current_traj->phi.push_back(phi.back()); const auto start_timestamp = std::chrono::system_clock::now(); // Retrieve v, a and steer from path for (auto& result : *partitioned_result) { if (FLAGS_use_s_curve_speed_smooth) { if (!GenerateSCurveSpeedAcceleration(&result)) { AERROR << "GenerateSCurveSpeedAcceleration fail"; return false; } } else { if (!GenerateSpeedAcceleration(&result)) { AERROR << "GenerateSpeedAcceleration fail"; return false; } } } const auto end_timestamp = std::chrono::system_clock::now(); std::chrono::duration<double> diff = end_timestamp - start_timestamp; ADEBUG << "speed profile total time: " << diff.count() * 1000.0 << " ms."; return true; } bool HybridAStar::GetTemporalProfile(HybridAStartResult* result) { std::vector<HybridAStartResult> partitioned_results; if (!TrajectoryPartition(*result, &partitioned_results)) { AERROR << "TrajectoryPartition fail"; return false; } ADEBUG << "PARTION SIZE " << partitioned_results.size(); HybridAStartResult stitched_result; for (const auto& result : partitioned_results) { std::copy(result.x.begin(), result.x.end() - 1, std::back_inserter(stitched_result.x)); std::copy(result.y.begin(), result.y.end() - 1, std::back_inserter(stitched_result.y)); std::copy(result.phi.begin(), result.phi.end() - 1, std::back_inserter(stitched_result.phi)); std::copy(result.v.begin(), result.v.end() - 1, std::back_inserter(stitched_result.v)); std::copy(result.a.begin(), result.a.end(), std::back_inserter(stitched_result.a)); std::copy(result.steer.begin(), result.steer.end(), std::back_inserter(stitched_result.steer)); } stitched_result.x.push_back(partitioned_results.back().x.back()); stitched_result.y.push_back(partitioned_results.back().y.back()); stitched_result.phi.push_back(partitioned_results.back().phi.back()); stitched_result.v.push_back(partitioned_results.back().v.back()); *result = stitched_result; return true; } bool HybridAStar::Plan( double sx, double sy, double sphi, double ex, double ey, double ephi, const std::vector<double>& XYbounds, const std::vector<std::vector<common::math::Vec2d>>& obstacles_vertices_vec, HybridAStartResult* result) { // clear containers open_set_.clear(); close_set_.clear(); open_pq_ = decltype(open_pq_)(); final_node_ = nullptr; std::vector<std::vector<common::math::LineSegment2d>> obstacles_linesegments_vec; for (const auto& obstacle_vertices : obstacles_vertices_vec) { size_t vertices_num = obstacle_vertices.size(); std::vector<common::math::LineSegment2d> obstacle_linesegments; for (size_t i = 0; i < vertices_num - 1; ++i) { common::math::LineSegment2d line_segment = common::math::LineSegment2d( obstacle_vertices[i], obstacle_vertices[i + 1]); obstacle_linesegments.emplace_back(line_segment); } obstacles_linesegments_vec.emplace_back(obstacle_linesegments); } obstacles_linesegments_vec_ = std::move(obstacles_linesegments_vec); std::stringstream ssm; ssm << "roi boundary" << std::endl; for (auto vec : obstacles_linesegments_vec_) { for (auto linesg : vec) { ssm << linesg.start().x() << "," << linesg.start().y() << std::endl; ssm << linesg.end().x() << "," << linesg.end().y() << std::endl; } } ssm << "--vehicle start box" << std::endl; Vec2d sposition(sx, sy); Vec2d svec_to_center((vehicle_param_.front_edge_to_center() - vehicle_param_.back_edge_to_center()) / 2.0, (vehicle_param_.left_edge_to_center() - vehicle_param_.right_edge_to_center()) / 2.0); Vec2d scenter(sposition + svec_to_center.rotate(sphi)); Box2d sbox(scenter, sphi, vehicle_param_.length(), vehicle_param_.width()); for (auto corner : sbox.GetAllCorners()) ssm << corner.x() << "," << corner.y() << std::endl; ssm << "--vehicle end box" << std::endl; Vec2d eposition(ex, ey); Vec2d evec_to_center((vehicle_param_.front_edge_to_center() - vehicle_param_.back_edge_to_center()) / 2.0, (vehicle_param_.left_edge_to_center() - vehicle_param_.right_edge_to_center()) / 2.0); Vec2d ecenter(eposition + evec_to_center.rotate(ephi)); Box2d ebox(ecenter, ephi, vehicle_param_.length(), vehicle_param_.width()); for (auto corner : ebox.GetAllCorners()) ssm << corner.x() << "," << corner.y() << std::endl; // load XYbounds ssm << "--" << std::endl; ssm << "XYbounds" << std::endl; ssm << XYbounds[0] << ", " << XYbounds[1] << std::endl; ssm << XYbounds[2] << ", " << XYbounds[3] << std::endl; XYbounds_ = XYbounds; // load nodes and obstacles start_node_.reset( new Node3d({sx}, {sy}, {sphi}, XYbounds_, planner_open_space_config_)); end_node_.reset( new Node3d({ex}, {ey}, {ephi}, XYbounds_, planner_open_space_config_)); AINFO << "start node" << sx << "," << sy << "," << sphi; AINFO << "end node " << ex << "," << ey << "," << ephi; if (!ValidityCheck(start_node_)) { AERROR << "start_node in collision with obstacles"; AERROR << start_node_->GetX() << "," << start_node_->GetY() << "," << start_node_->GetPhi(); AERROR << ssm.str(); return false; } if (!ValidityCheck(end_node_)) { AERROR << "end_node in collision with obstacles"; return false; } double map_time = Clock::NowInSeconds(); grid_a_star_heuristic_generator_->GenerateDpMap(ex, ey, XYbounds_, obstacles_linesegments_vec_); ADEBUG << "map time " << Clock::NowInSeconds() - map_time; // load open set, pq open_set_.emplace(start_node_->GetIndex(), start_node_); open_pq_.emplace(start_node_->GetIndex(), start_node_->GetCost()); // Hybrid A* begins size_t explored_node_num = 0; double astar_start_time = Clock::NowInSeconds(); double heuristic_time = 0.0; double rs_time = 0.0; while (!open_pq_.empty()) { // take out the lowest cost neighboring node const std::string current_id = open_pq_.top().first; open_pq_.pop(); std::shared_ptr<Node3d> current_node = open_set_[current_id]; // check if an analystic curve could be connected from current // configuration to the end configuration without collision. if so, search // ends. const double rs_start_time = Clock::NowInSeconds(); if (AnalyticExpansion(current_node)) { break; } const double rs_end_time = Clock::NowInSeconds(); rs_time += rs_end_time - rs_start_time; close_set_.emplace(current_node->GetIndex(), current_node); for (size_t i = 0; i < next_node_num_; ++i) { std::shared_ptr<Node3d> next_node = Next_node_generator(current_node, i); // boundary check failure handle if (next_node == nullptr) { continue; } // check if the node is already in the close set if (close_set_.find(next_node->GetIndex()) != close_set_.end()) { continue; } // collision check if (!ValidityCheck(next_node)) { continue; } if (open_set_.find(next_node->GetIndex()) == open_set_.end()) { explored_node_num++; const double start_time = Clock::NowInSeconds(); CalculateNodeCost(current_node, next_node); const double end_time = Clock::NowInSeconds(); heuristic_time += end_time - start_time; open_set_.emplace(next_node->GetIndex(), next_node); open_pq_.emplace(next_node->GetIndex(), next_node->GetCost()); } } } if (final_node_ == nullptr) { AERROR << "Hybrid A searching return null ptr(open_set ran out)"; AINFO << ssm.str(); return false; } if (!GetResult(result)) { AERROR << "GetResult failed"; return false; } ADEBUG << "explored node num is " << explored_node_num; ADEBUG << "heuristic time is " << heuristic_time; ADEBUG << "reed shepp time is " << rs_time; ADEBUG << "hybrid astar total time is " << Clock::NowInSeconds() - astar_start_time; return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/coarse_trajectory_generator/hybrid_a_star.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 <memory> #include <queue> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/planning/proto/planner_open_space_config.pb.h" #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "cyber/time/clock.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/math_utils.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/open_space/coarse_trajectory_generator/grid_search.h" #include "modules/planning/open_space/coarse_trajectory_generator/node3d.h" #include "modules/planning/open_space/coarse_trajectory_generator/reeds_shepp_path.h" namespace apollo { namespace planning { struct HybridAStartResult { std::vector<double> x; std::vector<double> y; std::vector<double> phi; std::vector<double> v; std::vector<double> a; std::vector<double> steer; std::vector<double> accumulated_s; }; class HybridAStar { public: explicit HybridAStar(const PlannerOpenSpaceConfig& open_space_conf); virtual ~HybridAStar() = default; bool Plan(double sx, double sy, double sphi, double ex, double ey, double ephi, const std::vector<double>& XYbounds, const std::vector<std::vector<common::math::Vec2d>>& obstacles_vertices_vec, HybridAStartResult* result); bool TrajectoryPartition(const HybridAStartResult& result, std::vector<HybridAStartResult>* partitioned_result); private: bool AnalyticExpansion(std::shared_ptr<Node3d> current_node); // check collision and validity bool ValidityCheck(std::shared_ptr<Node3d> node); // check Reeds Shepp path collision and validity bool RSPCheck(const std::shared_ptr<ReedSheppPath> reeds_shepp_to_end); // load the whole RSP as nodes and add to the close set std::shared_ptr<Node3d> LoadRSPinCS( const std::shared_ptr<ReedSheppPath> reeds_shepp_to_end, std::shared_ptr<Node3d> current_node); std::shared_ptr<Node3d> Next_node_generator( std::shared_ptr<Node3d> current_node, size_t next_node_index); void CalculateNodeCost(std::shared_ptr<Node3d> current_node, std::shared_ptr<Node3d> next_node); double TrajCost(std::shared_ptr<Node3d> current_node, std::shared_ptr<Node3d> next_node); double HoloObstacleHeuristic(std::shared_ptr<Node3d> next_node); bool GetResult(HybridAStartResult* result); bool GetTemporalProfile(HybridAStartResult* result); bool GenerateSpeedAcceleration(HybridAStartResult* result); bool GenerateSCurveSpeedAcceleration(HybridAStartResult* result); private: PlannerOpenSpaceConfig planner_open_space_config_; common::VehicleParam vehicle_param_ = common::VehicleConfigHelper::GetConfig().vehicle_param(); size_t next_node_num_ = 0; double max_steer_angle_ = 0.0; double step_size_ = 0.0; double xy_grid_resolution_ = 0.0; double delta_t_ = 0.0; double traj_forward_penalty_ = 0.0; double traj_back_penalty_ = 0.0; double traj_gear_switch_penalty_ = 0.0; double traj_steer_penalty_ = 0.0; double traj_steer_change_penalty_ = 0.0; double heu_rs_forward_penalty_ = 0.0; double heu_rs_back_penalty_ = 0.0; double heu_rs_gear_switch_penalty_ = 0.0; double heu_rs_steer_penalty_ = 0.0; double heu_rs_steer_change_penalty_ = 0.0; double acc_weight_ = 0.0; double jerk_weight_ = 0.0; double kappa_penalty_weight_ = 0.0; double ref_s_weight_ = 0.0; double ref_v_weight_ = 0.0; double max_forward_v_ = 0.0; double max_reverse_v_ = 0.0; double max_forward_acc_ = 0.0; double max_reverse_acc_ = 0.0; double max_acc_jerk_ = 0.0; std::vector<double> XYbounds_; std::shared_ptr<Node3d> start_node_; std::shared_ptr<Node3d> end_node_; std::shared_ptr<Node3d> final_node_; std::vector<std::vector<common::math::LineSegment2d>> obstacles_linesegments_vec_; struct cmp { bool operator()(const std::pair<std::string, double>& left, const std::pair<std::string, double>& right) const { return left.second >= right.second; } }; std::priority_queue<std::pair<std::string, double>, std::vector<std::pair<std::string, double>>, cmp> open_pq_; std::unordered_map<std::string, std::shared_ptr<Node3d>> open_set_; std::unordered_map<std::string, std::shared_ptr<Node3d>> close_set_; std::unique_ptr<ReedShepp> reed_shepp_generator_; std::unique_ptr<GridSearch> grid_a_star_heuristic_generator_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/coarse_trajectory_generator/node3d_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* * @file */ #include "modules/planning/open_space/coarse_trajectory_generator/node3d.h" #include "gtest/gtest.h" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/math/box2d.h" #include "modules/common/math/vec2d.h" namespace apollo { namespace planning { using apollo::common::math::Box2d; using apollo::common::math::Vec2d; class Node3dTest : public ::testing::Test { public: virtual void SetUp() { node_ = std::unique_ptr<Node3d>(new Node3d(0.0, 0.0, 0.0)); } protected: std::unique_ptr<Node3d> node_; common::VehicleParam vehicle_param_ = common::VehicleConfigHelper::GetConfig().vehicle_param(); }; TEST_F(Node3dTest, GetBoundingBox) { Box2d test_box = Node3d::GetBoundingBox(vehicle_param_, 0.0, 0.0, 0.0); double ego_length = vehicle_param_.length(); double ego_width = vehicle_param_.width(); Box2d gold_box({0.0, 0.0}, 0.0, ego_length, ego_width); double shift_distance = ego_length / 2.0 - vehicle_param_.back_edge_to_center(); Vec2d shift_vec{shift_distance * std::cos(0.0), shift_distance * std::sin(0.0)}; gold_box.Shift(shift_vec); ASSERT_EQ(test_box.heading(), gold_box.heading()); ASSERT_EQ(test_box.center_x(), gold_box.center_x()); ASSERT_EQ(test_box.center_y(), gold_box.center_y()); ASSERT_EQ(test_box.length(), gold_box.length()); ASSERT_EQ(test_box.width(), gold_box.width()); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/coarse_trajectory_generator/grid_search.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/open_space/coarse_trajectory_generator/grid_search.h" namespace apollo { namespace planning { GridSearch::GridSearch(const PlannerOpenSpaceConfig& open_space_conf) { xy_grid_resolution_ = open_space_conf.warm_start_config().grid_a_star_xy_resolution(); node_radius_ = open_space_conf.warm_start_config().node_radius(); } double GridSearch::EuclidDistance(const double x1, const double y1, const double x2, const double y2) { return std::sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } bool GridSearch::CheckConstraints(std::shared_ptr<Node2d> node) { const double node_grid_x = node->GetGridX(); const double node_grid_y = node->GetGridY(); if (node_grid_x > max_grid_x_ || node_grid_x < 0 || node_grid_y > max_grid_y_ || node_grid_y < 0) { return false; } if (obstacles_linesegments_vec_.empty()) { return true; } for (const auto& obstacle_linesegments : obstacles_linesegments_vec_) { for (const common::math::LineSegment2d& linesegment : obstacle_linesegments) { if (linesegment.DistanceTo({node->GetGridX(), node->GetGridY()}) < node_radius_) { return false; } } } return true; } std::vector<std::shared_ptr<Node2d>> GridSearch::GenerateNextNodes( std::shared_ptr<Node2d> current_node) { double current_node_x = current_node->GetGridX(); double current_node_y = current_node->GetGridY(); double current_node_path_cost = current_node->GetPathCost(); double diagonal_distance = std::sqrt(2.0); std::vector<std::shared_ptr<Node2d>> next_nodes; std::shared_ptr<Node2d> up = std::make_shared<Node2d>(current_node_x, current_node_y + 1.0, XYbounds_); up->SetPathCost(current_node_path_cost + 1.0); std::shared_ptr<Node2d> up_right = std::make_shared<Node2d>( current_node_x + 1.0, current_node_y + 1.0, XYbounds_); up_right->SetPathCost(current_node_path_cost + diagonal_distance); std::shared_ptr<Node2d> right = std::make_shared<Node2d>(current_node_x + 1.0, current_node_y, XYbounds_); right->SetPathCost(current_node_path_cost + 1.0); std::shared_ptr<Node2d> down_right = std::make_shared<Node2d>( current_node_x + 1.0, current_node_y - 1.0, XYbounds_); down_right->SetPathCost(current_node_path_cost + diagonal_distance); std::shared_ptr<Node2d> down = std::make_shared<Node2d>(current_node_x, current_node_y - 1.0, XYbounds_); down->SetPathCost(current_node_path_cost + 1.0); std::shared_ptr<Node2d> down_left = std::make_shared<Node2d>( current_node_x - 1.0, current_node_y - 1.0, XYbounds_); down_left->SetPathCost(current_node_path_cost + diagonal_distance); std::shared_ptr<Node2d> left = std::make_shared<Node2d>(current_node_x - 1.0, current_node_y, XYbounds_); left->SetPathCost(current_node_path_cost + 1.0); std::shared_ptr<Node2d> up_left = std::make_shared<Node2d>( current_node_x - 1.0, current_node_y + 1.0, XYbounds_); up_left->SetPathCost(current_node_path_cost + diagonal_distance); next_nodes.emplace_back(up); next_nodes.emplace_back(up_right); next_nodes.emplace_back(right); next_nodes.emplace_back(down_right); next_nodes.emplace_back(down); next_nodes.emplace_back(down_left); next_nodes.emplace_back(left); next_nodes.emplace_back(up_left); return next_nodes; } bool GridSearch::GenerateAStarPath( const double sx, const double sy, const double ex, const double ey, const std::vector<double>& XYbounds, const std::vector<std::vector<common::math::LineSegment2d>>& obstacles_linesegments_vec, GridAStartResult* result) { std::priority_queue<std::pair<std::string, double>, std::vector<std::pair<std::string, double>>, cmp> open_pq; std::unordered_map<std::string, std::shared_ptr<Node2d>> open_set; std::unordered_map<std::string, std::shared_ptr<Node2d>> close_set; XYbounds_ = XYbounds; std::shared_ptr<Node2d> start_node = std::make_shared<Node2d>(sx, sy, xy_grid_resolution_, XYbounds_); std::shared_ptr<Node2d> end_node = std::make_shared<Node2d>(ex, ey, xy_grid_resolution_, XYbounds_); std::shared_ptr<Node2d> final_node_ = nullptr; obstacles_linesegments_vec_ = obstacles_linesegments_vec; open_set.emplace(start_node->GetIndex(), start_node); open_pq.emplace(start_node->GetIndex(), start_node->GetCost()); // Grid a star begins size_t explored_node_num = 0; while (!open_pq.empty()) { std::string current_id = open_pq.top().first; open_pq.pop(); std::shared_ptr<Node2d> current_node = open_set[current_id]; // Check destination if (*(current_node) == *(end_node)) { final_node_ = current_node; break; } close_set.emplace(current_node->GetIndex(), current_node); std::vector<std::shared_ptr<Node2d>> next_nodes = std::move(GenerateNextNodes(current_node)); for (auto& next_node : next_nodes) { if (!CheckConstraints(next_node)) { continue; } if (close_set.find(next_node->GetIndex()) != close_set.end()) { continue; } if (open_set.find(next_node->GetIndex()) == open_set.end()) { ++explored_node_num; next_node->SetHeuristic( EuclidDistance(next_node->GetGridX(), next_node->GetGridY(), end_node->GetGridX(), end_node->GetGridY())); next_node->SetPreNode(current_node); open_set.emplace(next_node->GetIndex(), next_node); open_pq.emplace(next_node->GetIndex(), next_node->GetCost()); } } } if (final_node_ == nullptr) { AERROR << "Grid A searching return null ptr(open_set ran out)"; return false; } LoadGridAStarResult(result); ADEBUG << "explored node num is " << explored_node_num; return true; } bool GridSearch::GenerateDpMap( const double ex, const double ey, const std::vector<double>& XYbounds, const std::vector<std::vector<common::math::LineSegment2d>>& obstacles_linesegments_vec) { std::priority_queue<std::pair<std::string, double>, std::vector<std::pair<std::string, double>>, cmp> open_pq; std::unordered_map<std::string, std::shared_ptr<Node2d>> open_set; dp_map_ = decltype(dp_map_)(); XYbounds_ = XYbounds; // XYbounds with xmin, xmax, ymin, ymax max_grid_y_ = std::round((XYbounds_[3] - XYbounds_[2]) / xy_grid_resolution_); max_grid_x_ = std::round((XYbounds_[1] - XYbounds_[0]) / xy_grid_resolution_); std::shared_ptr<Node2d> end_node = std::make_shared<Node2d>(ex, ey, xy_grid_resolution_, XYbounds_); obstacles_linesegments_vec_ = obstacles_linesegments_vec; open_set.emplace(end_node->GetIndex(), end_node); open_pq.emplace(end_node->GetIndex(), end_node->GetCost()); // Grid a star begins size_t explored_node_num = 0; while (!open_pq.empty()) { const std::string current_id = open_pq.top().first; open_pq.pop(); std::shared_ptr<Node2d> current_node = open_set[current_id]; dp_map_.emplace(current_node->GetIndex(), current_node); std::vector<std::shared_ptr<Node2d>> next_nodes = std::move(GenerateNextNodes(current_node)); for (auto& next_node : next_nodes) { if (!CheckConstraints(next_node)) { continue; } if (dp_map_.find(next_node->GetIndex()) != dp_map_.end()) { continue; } if (open_set.find(next_node->GetIndex()) == open_set.end()) { ++explored_node_num; next_node->SetPreNode(current_node); open_set.emplace(next_node->GetIndex(), next_node); open_pq.emplace(next_node->GetIndex(), next_node->GetCost()); } else { if (open_set[next_node->GetIndex()]->GetCost() > next_node->GetCost()) { open_set[next_node->GetIndex()]->SetCost(next_node->GetCost()); open_set[next_node->GetIndex()]->SetPreNode(current_node); } } } } ADEBUG << "explored node num is " << explored_node_num; return true; } double GridSearch::CheckDpMap(const double sx, const double sy) { std::string index = Node2d::CalcIndex(sx, sy, xy_grid_resolution_, XYbounds_); if (dp_map_.find(index) != dp_map_.end()) { return dp_map_[index]->GetCost() * xy_grid_resolution_; } else { return std::numeric_limits<double>::infinity(); } } void GridSearch::LoadGridAStarResult(GridAStartResult* result) { (*result).path_cost = final_node_->GetPathCost() * xy_grid_resolution_; std::shared_ptr<Node2d> current_node = final_node_; std::vector<double> grid_a_x; std::vector<double> grid_a_y; while (current_node->GetPreNode() != nullptr) { grid_a_x.push_back(current_node->GetGridX() * xy_grid_resolution_ + XYbounds_[0]); grid_a_y.push_back(current_node->GetGridY() * xy_grid_resolution_ + XYbounds_[2]); current_node = current_node->GetPreNode(); } std::reverse(grid_a_x.begin(), grid_a_x.end()); std::reverse(grid_a_y.begin(), grid_a_y.end()); (*result).x = std::move(grid_a_x); (*result).y = std::move(grid_a_y); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/coarse_trajectory_generator/reeds_shepp_path.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 <limits> #include <memory> #include <string> #include <utility> #include <vector> #include <omp.h> #include "cyber/common/log.h" #include "cyber/common/macros.h" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/math/math_utils.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/open_space/coarse_trajectory_generator/node3d.h" #include "modules/planning/proto/planner_open_space_config.pb.h" namespace apollo { namespace planning { struct ReedSheppPath { std::vector<double> segs_lengths; std::vector<char> segs_types; double total_length = 0.0; std::vector<double> x; std::vector<double> y; std::vector<double> phi; // true for driving forward and false for driving backward std::vector<bool> gear; }; struct RSPParam { bool flag = false; double t = 0.0; double u = 0.0; double v = 0.0; }; class ReedShepp { public: ReedShepp(const common::VehicleParam& vehicle_param, const PlannerOpenSpaceConfig& open_space_conf); virtual ~ReedShepp() = default; // Pick the shortest path from all possible combination of movement primitives // by Reed Shepp bool ShortestRSP(const std::shared_ptr<Node3d> start_node, const std::shared_ptr<Node3d> end_node, std::shared_ptr<ReedSheppPath> optimal_path); protected: // Generate all possible combination of movement primitives by Reed Shepp and // interpolate them bool GenerateRSPs(const std::shared_ptr<Node3d> start_node, const std::shared_ptr<Node3d> end_node, std::vector<ReedSheppPath>* all_possible_paths); // Set the general profile of the movement primitives bool GenerateRSP(const std::shared_ptr<Node3d> start_node, const std::shared_ptr<Node3d> end_node, std::vector<ReedSheppPath>* all_possible_paths); // Set the general profile of the movement primitives, parallel implementation bool GenerateRSPPar(const std::shared_ptr<Node3d> start_node, const std::shared_ptr<Node3d> end_node, std::vector<ReedSheppPath>* all_possible_paths); // Set local exact configurations profile of each movement primitive bool GenerateLocalConfigurations(const std::shared_ptr<Node3d> start_node, const std::shared_ptr<Node3d> end_node, ReedSheppPath* shortest_path); // Interpolation usde in GenetateLocalConfiguration void Interpolation(const int index, const double pd, const char m, const double ox, const double oy, const double ophi, std::vector<double>* px, std::vector<double>* py, std::vector<double>* pphi, std::vector<bool>* pgear); // motion primitives combination setup function bool SetRSP(const int size, const double* lengths, const char* types, std::vector<ReedSheppPath>* all_possible_paths); // setRSP parallel version bool SetRSPPar(const int size, const double* lengths, const std::string& types, std::vector<ReedSheppPath>* all_possible_paths, const int idx); // Six different combination of motion primitive in Reed Shepp path used in // GenerateRSP() bool SCS(const double x, const double y, const double phi, std::vector<ReedSheppPath>* all_possible_paths); bool CSC(const double x, const double y, const double phi, std::vector<ReedSheppPath>* all_possible_paths); bool CCC(const double x, const double y, const double phi, std::vector<ReedSheppPath>* all_possible_paths); bool CCCC(const double x, const double y, const double phi, std::vector<ReedSheppPath>* all_possible_paths); bool CCSC(const double x, const double y, const double phi, std::vector<ReedSheppPath>* all_possible_paths); bool CCSCC(const double x, const double y, const double phi, std::vector<ReedSheppPath>* all_possible_paths); // different options for different combination of motion primitives void LSL(const double x, const double y, const double phi, RSPParam* param); void LSR(const double x, const double y, const double phi, RSPParam* param); void LRL(const double x, const double y, const double phi, RSPParam* param); void SLS(const double x, const double y, const double phi, RSPParam* param); void LRLRn(const double x, const double y, const double phi, RSPParam* param); void LRLRp(const double x, const double y, const double phi, RSPParam* param); void LRSR(const double x, const double y, const double phi, RSPParam* param); void LRSL(const double x, const double y, const double phi, RSPParam* param); void LRSLR(const double x, const double y, const double phi, RSPParam* param); std::pair<double, double> calc_tau_omega(const double u, const double v, const double xi, const double eta, const double phi); protected: common::VehicleParam vehicle_param_; PlannerOpenSpaceConfig planner_open_space_config_; double max_kappa_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/coarse_trajectory_generator/reeds_shepp_path_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* * @file */ #include "modules/planning/open_space/coarse_trajectory_generator/reeds_shepp_path.h" #include "cyber/common/file.h" #include "gtest/gtest.h" #include "modules/common_msgs/config_msgs/vehicle_config.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/util/util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/open_space/coarse_trajectory_generator/node3d.h" #include "modules/planning/proto/planner_open_space_config.pb.h" namespace apollo { namespace planning { class reeds_shepp : public ::testing::Test { public: virtual void SetUp() { ASSERT_TRUE(cyber::common::GetProtoFromFile( FLAGS_planner_open_space_config_filename, &planner_open_space_config_)); vehicle_param_ = common::VehicleConfigHelper::GetConfig().vehicle_param(); reedshepp_test = std::unique_ptr<ReedShepp>( new ReedShepp(vehicle_param_, planner_open_space_config_)); XYbounds_.push_back(-1000.0); XYbounds_.push_back(1000.0); XYbounds_.push_back(-1000.0); XYbounds_.push_back(1000.0); } void check(std::shared_ptr<Node3d> start_node, std::shared_ptr<Node3d> end_node, std::shared_ptr<ReedSheppPath> optimal_path) { ASSERT_LT(start_node->GetX() - ((*optimal_path).x).front(), 0.01); ASSERT_LT(start_node->GetY() - ((*optimal_path).y).front(), 0.01); ASSERT_LT(start_node->GetPhi() - ((*optimal_path).phi).front(), 0.01); ASSERT_LT(end_node->GetX() - ((*optimal_path).x).back(), 0.01); ASSERT_LT(end_node->GetY() - ((*optimal_path).y).back(), 0.01); ASSERT_LT(end_node->GetPhi() - ((*optimal_path).phi).back(), 0.01); ASSERT_GT((*optimal_path).x.size(), 1); for (size_t i = 1; i < (*optimal_path).x.size(); ++i) { double gold_interval = std::sqrt( planner_open_space_config_.warm_start_config().step_size() * planner_open_space_config_.warm_start_config().step_size() + planner_open_space_config_.warm_start_config().step_size() * planner_open_space_config_.warm_start_config().step_size()); double interval = std::sqrt( ((*optimal_path).x.at(i) - (*optimal_path).x.at(i - 1)) * ((*optimal_path).x.at(i) - (*optimal_path).x.at(i - 1)) + ((*optimal_path).y.at(i) - (*optimal_path).y.at(i - 1)) * ((*optimal_path).y.at(i) - (*optimal_path).y.at(i - 1))); ASSERT_LT(interval, gold_interval); } } protected: common::VehicleParam vehicle_param_; PlannerOpenSpaceConfig planner_open_space_config_; std::unique_ptr<ReedShepp> reedshepp_test; std::vector<double> XYbounds_; }; TEST_F(reeds_shepp, test_set_1) { std::shared_ptr<Node3d> start_node = std::shared_ptr<Node3d>(new Node3d( 0.0, 0.0, 10.0 * M_PI / 180.0, XYbounds_, planner_open_space_config_)); std::shared_ptr<Node3d> end_node = std::shared_ptr<Node3d>(new Node3d( 7.0, -8.0, 50.0 * M_PI / 180.0, XYbounds_, planner_open_space_config_)); std::shared_ptr<ReedSheppPath> optimal_path = std::shared_ptr<ReedSheppPath>(new ReedSheppPath()); if (!reedshepp_test->ShortestRSP(start_node, end_node, optimal_path)) { ADEBUG << "generating short RSP not successful"; } check(start_node, end_node, optimal_path); } TEST_F(reeds_shepp, test_set_2) { std::shared_ptr<Node3d> start_node = std::shared_ptr<Node3d>(new Node3d( 0.0, 0.0, 10.0 * M_PI / 180.0, XYbounds_, planner_open_space_config_)); std::shared_ptr<Node3d> end_node = std::shared_ptr<Node3d>(new Node3d( 7.0, -8.0, -50.0 * M_PI / 180.0, XYbounds_, planner_open_space_config_)); std::shared_ptr<ReedSheppPath> optimal_path = std::shared_ptr<ReedSheppPath>(new ReedSheppPath()); if (!reedshepp_test->ShortestRSP(start_node, end_node, optimal_path)) { ADEBUG << "generating short RSP not successful"; } check(start_node, end_node, optimal_path); } TEST_F(reeds_shepp, test_set_3) { std::shared_ptr<Node3d> start_node = std::shared_ptr<Node3d>(new Node3d( 0.0, 10.0, -10.0 * M_PI / 180.0, XYbounds_, planner_open_space_config_)); std::shared_ptr<Node3d> end_node = std::shared_ptr<Node3d>(new Node3d( -7.0, -8.0, -50.0 * M_PI / 180.0, XYbounds_, planner_open_space_config_)); std::shared_ptr<ReedSheppPath> optimal_path = std::shared_ptr<ReedSheppPath>(new ReedSheppPath()); if (!reedshepp_test->ShortestRSP(start_node, end_node, optimal_path)) { ADEBUG << "generating short RSP not successful"; } check(start_node, end_node, optimal_path); } TEST_F(reeds_shepp, test_set_4) { std::shared_ptr<Node3d> start_node = std::shared_ptr<Node3d>(new Node3d( 0.0, 10.0, -10.0 * M_PI / 180.0, XYbounds_, planner_open_space_config_)); std::shared_ptr<Node3d> end_node = std::shared_ptr<Node3d>(new Node3d( -7.0, -8.0, 150.0 * M_PI / 180.0, XYbounds_, planner_open_space_config_)); std::shared_ptr<ReedSheppPath> optimal_path = std::shared_ptr<ReedSheppPath>(new ReedSheppPath()); if (!reedshepp_test->ShortestRSP(start_node, end_node, optimal_path)) { ADEBUG << "generating short RSP not successful"; } check(start_node, end_node, optimal_path); } TEST_F(reeds_shepp, test_set_5) { std::shared_ptr<Node3d> start_node = std::shared_ptr<Node3d>(new Node3d( 0.0, 10.0, -10.0 * M_PI / 180.0, XYbounds_, planner_open_space_config_)); std::shared_ptr<Node3d> end_node = std::shared_ptr<Node3d>(new Node3d( 7.0, 8.0, 150.0 * M_PI / 180.0, XYbounds_, planner_open_space_config_)); std::shared_ptr<ReedSheppPath> optimal_path = std::shared_ptr<ReedSheppPath>(new ReedSheppPath()); if (!reedshepp_test->ShortestRSP(start_node, end_node, optimal_path)) { ADEBUG << "generating short RSP not successful"; } check(start_node, end_node, optimal_path); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/coarse_trajectory_generator/grid_search.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 <limits> #include <memory> #include <queue> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "absl/strings/str_cat.h" #include "cyber/common/log.h" #include "modules/common/math/line_segment2d.h" #include "modules/planning/proto/planner_open_space_config.pb.h" namespace apollo { namespace planning { class Node2d { public: Node2d(const double x, const double y, const double xy_resolution, const std::vector<double>& XYbounds) { // XYbounds with xmin, xmax, ymin, ymax grid_x_ = static_cast<int>((x - XYbounds[0]) / xy_resolution); grid_y_ = static_cast<int>((y - XYbounds[2]) / xy_resolution); index_ = ComputeStringIndex(grid_x_, grid_y_); } Node2d(const int grid_x, const int grid_y, const std::vector<double>& XYbounds) { grid_x_ = grid_x; grid_y_ = grid_y; index_ = ComputeStringIndex(grid_x_, grid_y_); } void SetPathCost(const double path_cost) { path_cost_ = path_cost; cost_ = path_cost_ + heuristic_; } void SetHeuristic(const double heuristic) { heuristic_ = heuristic; cost_ = path_cost_ + heuristic_; } void SetCost(const double cost) { cost_ = cost; } void SetPreNode(std::shared_ptr<Node2d> pre_node) { pre_node_ = pre_node; } double GetGridX() const { return grid_x_; } double GetGridY() const { return grid_y_; } double GetPathCost() const { return path_cost_; } double GetHeuCost() const { return heuristic_; } double GetCost() const { return cost_; } const std::string& GetIndex() const { return index_; } std::shared_ptr<Node2d> GetPreNode() const { return pre_node_; } static std::string CalcIndex(const double x, const double y, const double xy_resolution, const std::vector<double>& XYbounds) { // XYbounds with xmin, xmax, ymin, ymax int grid_x = static_cast<int>((x - XYbounds[0]) / xy_resolution); int grid_y = static_cast<int>((y - XYbounds[2]) / xy_resolution); return ComputeStringIndex(grid_x, grid_y); } bool operator==(const Node2d& right) const { return right.GetIndex() == index_; } private: static std::string ComputeStringIndex(int x_grid, int y_grid) { return absl::StrCat(x_grid, "_", y_grid); } private: int grid_x_ = 0; int grid_y_ = 0; double path_cost_ = 0.0; double heuristic_ = 0.0; double cost_ = 0.0; std::string index_; std::shared_ptr<Node2d> pre_node_ = nullptr; }; struct GridAStartResult { std::vector<double> x; std::vector<double> y; double path_cost = 0.0; }; class GridSearch { public: explicit GridSearch(const PlannerOpenSpaceConfig& open_space_conf); virtual ~GridSearch() = default; bool GenerateAStarPath( const double sx, const double sy, const double ex, const double ey, const std::vector<double>& XYbounds, const std::vector<std::vector<common::math::LineSegment2d>>& obstacles_linesegments_vec, GridAStartResult* result); bool GenerateDpMap( const double ex, const double ey, const std::vector<double>& XYbounds, const std::vector<std::vector<common::math::LineSegment2d>>& obstacles_linesegments_vec); double CheckDpMap(const double sx, const double sy); private: double EuclidDistance(const double x1, const double y1, const double x2, const double y2); std::vector<std::shared_ptr<Node2d>> GenerateNextNodes( std::shared_ptr<Node2d> node); bool CheckConstraints(std::shared_ptr<Node2d> node); void LoadGridAStarResult(GridAStartResult* result); private: double xy_grid_resolution_ = 0.0; double node_radius_ = 0.0; std::vector<double> XYbounds_; double max_grid_x_ = 0.0; double max_grid_y_ = 0.0; std::shared_ptr<Node2d> start_node_; std::shared_ptr<Node2d> end_node_; std::shared_ptr<Node2d> final_node_; std::vector<std::vector<common::math::LineSegment2d>> obstacles_linesegments_vec_; struct cmp { bool operator()(const std::pair<std::string, double>& left, const std::pair<std::string, double>& right) const { return left.second >= right.second; } }; std::unordered_map<std::string, std::shared_ptr<Node2d>> dp_map_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/coarse_trajectory_generator/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 = "node3d", srcs = ["node3d.cc"], hdrs = ["node3d.h"], copts = PLANNING_COPTS, deps = [ "//cyber", "//modules/common/math", "//modules/planning/common:obstacle", "//modules/planning/constraint_checker:collision_checker", "//modules/planning/proto:planner_open_space_config_cc_proto", ], ) cc_library( name = "reeds_shepp_path", srcs = ["reeds_shepp_path.cc"], hdrs = ["reeds_shepp_path.h"], copts = [ "-DMODULE_NAME=\\\"planning\\\"", "-fopenmp", ], deps = [ "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/planning/common:planning_gflags", "//modules/planning/open_space/coarse_trajectory_generator:node3d", "//modules/planning/proto:planner_open_space_config_cc_proto", "@adolc", ], ) cc_library( name = "grid_search", srcs = ["grid_search.cc"], hdrs = ["grid_search.h"], copts = PLANNING_COPTS, deps = [ "//cyber", "//modules/common/math", "//modules/planning/proto:planner_open_space_config_cc_proto", ], ) cc_library( name = "open_space_utils", copts = PLANNING_COPTS, deps = [ "//modules/planning/open_space/coarse_trajectory_generator:grid_search", "//modules/planning/open_space/coarse_trajectory_generator:node3d", "//modules/planning/open_space/coarse_trajectory_generator:reeds_shepp_path", ], ) cc_library( name = "hybrid_a_star", srcs = ["hybrid_a_star.cc"], hdrs = ["hybrid_a_star.h"], copts = PLANNING_COPTS, deps = [ ":open_space_utils", "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/planning/common:obstacle", "//modules/planning/common:planning_gflags", "//modules/planning/math/piecewise_jerk:piecewise_jerk_speed_problem", "//modules/planning/proto:planner_open_space_config_cc_proto", ], ) cc_test( name = "reeds_shepp_path_test", size = "small", srcs = ["reeds_shepp_path_test.cc"], linkopts = ["-lgomp"], deps = [ ":open_space_utils", "//cyber", "//modules/common/configs:vehicle_config_helper", "//modules/common/math", "//modules/planning/proto:planner_open_space_config_cc_proto", "@com_google_googletest//:gtest_main", ], ) cc_test( name = "node3d_test", size = "small", srcs = ["node3d_test.cc"], linkopts = ["-lgomp"], deps = [ ":open_space_utils", "//cyber", "@com_google_googletest//:gtest_main", ], ) cc_test( name = "hybrid_a_star_test", size = "small", srcs = ["hybrid_a_star_test.cc"], linkopts = ["-lgomp"], deps = [ ":hybrid_a_star", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/coarse_trajectory_generator/hybrid_a_star_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /* * @file */ #include "modules/planning/open_space/coarse_trajectory_generator/hybrid_a_star.h" #include "cyber/common/file.h" #include "gtest/gtest.h" #include "modules/common/math/box2d.h" #include "modules/common/math/vec2d.h" #include "modules/planning/common/obstacle.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::math::Vec2d; class HybridATest : public ::testing::Test { public: virtual void SetUp() { FLAGS_planner_open_space_config_filename = "/apollo/modules/planning/testdata/conf/" "open_space_standard_parking_lot.pb.txt"; ACHECK(apollo::cyber::common::GetProtoFromFile( FLAGS_planner_open_space_config_filename, &planner_open_space_config_)) << "Failed to load open space config file " << FLAGS_planner_open_space_config_filename; hybrid_test = std::unique_ptr<HybridAStar>( new HybridAStar(planner_open_space_config_)); } protected: std::unique_ptr<HybridAStar> hybrid_test; PlannerOpenSpaceConfig planner_open_space_config_; }; TEST_F(HybridATest, test1) { double sx = -15.0; double sy = 0.0; double sphi = 0.0; double ex = 15.0; double ey = 0.0; double ephi = 0.0; std::vector<std::vector<Vec2d>> obstacles_list; HybridAStartResult result; Vec2d obstacle_vertice_a(1.0, 0.0); Vec2d obstacle_vertice_b(-1.0, 0.0); std::vector<Vec2d> obstacle = {obstacle_vertice_a, obstacle_vertice_b}; // load xy boundary into the Plan() from configuration(Independent from frame) std::vector<double> XYbounds_; XYbounds_.push_back(-50.0); XYbounds_.push_back(50.0); XYbounds_.push_back(-50.0); XYbounds_.push_back(50.0); obstacles_list.emplace_back(obstacle); ASSERT_TRUE(hybrid_test->Plan(sx, sy, sphi, ex, ey, ephi, XYbounds_, obstacles_list, &result)); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/open_space
apollo_public_repos/apollo/modules/planning/open_space/coarse_trajectory_generator/reeds_shepp_path.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/open_space/coarse_trajectory_generator/reeds_shepp_path.h" namespace apollo { namespace planning { ReedShepp::ReedShepp(const common::VehicleParam& vehicle_param, const PlannerOpenSpaceConfig& open_space_conf) : vehicle_param_(vehicle_param), planner_open_space_config_(open_space_conf) { max_kappa_ = std::tan(vehicle_param_.max_steer_angle() * planner_open_space_config_.warm_start_config() .traj_kappa_contraint_ratio() / vehicle_param_.steer_ratio()) / vehicle_param_.wheel_base(); AINFO << "max kappa: " << max_kappa_; AINFO_IF(FLAGS_enable_parallel_hybrid_a) << "parallel REEDShepp"; } std::pair<double, double> ReedShepp::calc_tau_omega(const double u, const double v, const double xi, const double eta, const double phi) { double delta = common::math::NormalizeAngle(u - v); double A = std::sin(u) - std::sin(delta); double B = std::cos(u) - std::cos(delta) - 1.0; double t1 = std::atan2(eta * A - xi * B, xi * A + eta * B); double t2 = 2.0 * (std::cos(delta) - std::cos(v) - std::cos(u)) + 3.0; double tau = 0.0; if (t2 < 0) { tau = common::math::NormalizeAngle(t1 + M_PI); } else { tau = common::math::NormalizeAngle(t1); } double omega = common::math::NormalizeAngle(tau - u + v - phi); return std::make_pair(tau, omega); } bool ReedShepp::ShortestRSP(const std::shared_ptr<Node3d> start_node, const std::shared_ptr<Node3d> end_node, std::shared_ptr<ReedSheppPath> optimal_path) { std::vector<ReedSheppPath> all_possible_paths; if (!GenerateRSPs(start_node, end_node, &all_possible_paths)) { ADEBUG << "Fail to generate different combination of Reed Shepp " "paths"; return false; } double optimal_path_length = std::numeric_limits<double>::infinity(); size_t optimal_path_index = 0; size_t paths_size = all_possible_paths.size(); for (size_t i = 0; i < paths_size; ++i) { if (all_possible_paths.at(i).total_length > 0 && all_possible_paths.at(i).total_length < optimal_path_length) { optimal_path_index = i; optimal_path_length = all_possible_paths.at(i).total_length; } } if (!GenerateLocalConfigurations(start_node, end_node, &(all_possible_paths[optimal_path_index]))) { ADEBUG << "Fail to generate local configurations(x, y, phi) in SetRSP"; return false; } if (std::abs(all_possible_paths[optimal_path_index].x.back() - end_node->GetX()) > 1e-3 || std::abs(all_possible_paths[optimal_path_index].y.back() - end_node->GetY()) > 1e-3 || std::abs(all_possible_paths[optimal_path_index].phi.back() - end_node->GetPhi()) > 1e-3) { ADEBUG << "RSP end position not right"; for (size_t i = 0; i < all_possible_paths[optimal_path_index].segs_types.size(); ++i) { ADEBUG << "types are " << all_possible_paths[optimal_path_index].segs_types[i]; } ADEBUG << "x, y, phi are: " << all_possible_paths[optimal_path_index].x.back() << ", " << all_possible_paths[optimal_path_index].y.back() << ", " << all_possible_paths[optimal_path_index].phi.back(); ADEBUG << "end x, y, phi are: " << end_node->GetX() << ", " << end_node->GetY() << ", " << end_node->GetPhi(); return false; } (*optimal_path).x = all_possible_paths[optimal_path_index].x; (*optimal_path).y = all_possible_paths[optimal_path_index].y; (*optimal_path).phi = all_possible_paths[optimal_path_index].phi; (*optimal_path).gear = all_possible_paths[optimal_path_index].gear; (*optimal_path).total_length = all_possible_paths[optimal_path_index].total_length; (*optimal_path).segs_types = all_possible_paths[optimal_path_index].segs_types; (*optimal_path).segs_lengths = all_possible_paths[optimal_path_index].segs_lengths; return true; } bool ReedShepp::GenerateRSPs(const std::shared_ptr<Node3d> start_node, const std::shared_ptr<Node3d> end_node, std::vector<ReedSheppPath>* all_possible_paths) { if (FLAGS_enable_parallel_hybrid_a) { // AINFO << "parallel hybrid a*"; if (!GenerateRSPPar(start_node, end_node, all_possible_paths)) { ADEBUG << "Fail to generate general profile of different RSPs"; return false; } } else { if (!GenerateRSP(start_node, end_node, all_possible_paths)) { AERROR << "Fail to generate general profile of different RSPs"; return false; } } return true; } bool ReedShepp::GenerateRSP(const std::shared_ptr<Node3d> start_node, const std::shared_ptr<Node3d> end_node, std::vector<ReedSheppPath>* all_possible_paths) { double dx = end_node->GetX() - start_node->GetX(); double dy = end_node->GetY() - start_node->GetY(); double dphi = end_node->GetPhi() - start_node->GetPhi(); double c = std::cos(start_node->GetPhi()); double s = std::sin(start_node->GetPhi()); // normalize the initial point to (0,0,0) double x = (c * dx + s * dy) * max_kappa_; double y = (-s * dx + c * dy) * max_kappa_; if (!SCS(x, y, dphi, all_possible_paths)) { ADEBUG << "Fail at SCS"; } if (!CSC(x, y, dphi, all_possible_paths)) { ADEBUG << "Fail at CSC"; } if (!CCC(x, y, dphi, all_possible_paths)) { ADEBUG << "Fail at CCC"; } if (!CCCC(x, y, dphi, all_possible_paths)) { ADEBUG << "Fail at CCCC"; } if (!CCSC(x, y, dphi, all_possible_paths)) { ADEBUG << "Fail at CCSC"; } if (!CCSCC(x, y, dphi, all_possible_paths)) { ADEBUG << "Fail at CCSCC"; } if (all_possible_paths->empty()) { ADEBUG << "No path generated by certain two configurations"; return false; } return true; } bool ReedShepp::SCS(const double x, const double y, const double phi, std::vector<ReedSheppPath>* all_possible_paths) { RSPParam SLS_param; SLS(x, y, phi, &SLS_param); double SLS_lengths[3] = {SLS_param.t, SLS_param.u, SLS_param.v}; char SLS_types[] = "SLS"; if (SLS_param.flag && !SetRSP(3, SLS_lengths, SLS_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with SLS_param"; return false; } RSPParam SRS_param; SLS(x, -y, -phi, &SRS_param); double SRS_lengths[3] = {SRS_param.t, SRS_param.u, SRS_param.v}; char SRS_types[] = "SRS"; if (SRS_param.flag && !SetRSP(3, SRS_lengths, SRS_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with SRS_param"; return false; } return true; } bool ReedShepp::CSC(const double x, const double y, const double phi, std::vector<ReedSheppPath>* all_possible_paths) { RSPParam LSL1_param; LSL(x, y, phi, &LSL1_param); double LSL1_lengths[3] = {LSL1_param.t, LSL1_param.u, LSL1_param.v}; char LSL1_types[] = "LSL"; if (LSL1_param.flag && !SetRSP(3, LSL1_lengths, LSL1_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LSL_param"; return false; } RSPParam LSL2_param; LSL(-x, y, -phi, &LSL2_param); double LSL2_lengths[3] = {-LSL2_param.t, -LSL2_param.u, -LSL2_param.v}; char LSL2_types[] = "LSL"; if (LSL2_param.flag && !SetRSP(3, LSL2_lengths, LSL2_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LSL2_param"; return false; } RSPParam LSL3_param; LSL(x, -y, -phi, &LSL3_param); double LSL3_lengths[3] = {LSL3_param.t, LSL3_param.u, LSL3_param.v}; char LSL3_types[] = "RSR"; if (LSL3_param.flag && !SetRSP(3, LSL3_lengths, LSL3_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LSL3_param"; return false; } RSPParam LSL4_param; LSL(-x, -y, phi, &LSL4_param); double LSL4_lengths[3] = {-LSL4_param.t, -LSL4_param.u, -LSL4_param.v}; char LSL4_types[] = "RSR"; if (LSL4_param.flag && !SetRSP(3, LSL4_lengths, LSL4_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LSL4_param"; return false; } RSPParam LSR1_param; LSR(x, y, phi, &LSR1_param); double LSR1_lengths[3] = {LSR1_param.t, LSR1_param.u, LSR1_param.v}; char LSR1_types[] = "LSR"; if (LSR1_param.flag && !SetRSP(3, LSR1_lengths, LSR1_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LSR1_param"; return false; } RSPParam LSR2_param; LSR(-x, y, -phi, &LSR2_param); double LSR2_lengths[3] = {-LSR2_param.t, -LSR2_param.u, -LSR2_param.v}; char LSR2_types[] = "LSR"; if (LSR2_param.flag && !SetRSP(3, LSR2_lengths, LSR2_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LSR2_param"; return false; } RSPParam LSR3_param; LSR(x, -y, -phi, &LSR3_param); double LSR3_lengths[3] = {LSR3_param.t, LSR3_param.u, LSR3_param.v}; char LSR3_types[] = "RSL"; if (LSR3_param.flag && !SetRSP(3, LSR3_lengths, LSR3_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LSR3_param"; return false; } RSPParam LSR4_param; LSR(-x, -y, phi, &LSR4_param); double LSR4_lengths[3] = {-LSR4_param.t, -LSR4_param.u, -LSR4_param.v}; char LSR4_types[] = "RSL"; if (LSR4_param.flag && !SetRSP(3, LSR4_lengths, LSR4_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LSR4_param"; return false; } return true; } bool ReedShepp::CCC(const double x, const double y, const double phi, std::vector<ReedSheppPath>* all_possible_paths) { RSPParam LRL1_param; LRL(x, y, phi, &LRL1_param); double LRL1_lengths[3] = {LRL1_param.t, LRL1_param.u, LRL1_param.v}; char LRL1_types[] = "LRL"; if (LRL1_param.flag && !SetRSP(3, LRL1_lengths, LRL1_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRL_param"; return false; } RSPParam LRL2_param; LRL(-x, y, -phi, &LRL2_param); double LRL2_lengths[3] = {-LRL2_param.t, -LRL2_param.u, -LRL2_param.v}; char LRL2_types[] = "LRL"; if (LRL2_param.flag && !SetRSP(3, LRL2_lengths, LRL2_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRL2_param"; return false; } RSPParam LRL3_param; LRL(x, -y, -phi, &LRL3_param); double LRL3_lengths[3] = {LRL3_param.t, LRL3_param.u, LRL3_param.v}; char LRL3_types[] = "RLR"; if (LRL3_param.flag && !SetRSP(3, LRL3_lengths, LRL3_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRL3_param"; return false; } RSPParam LRL4_param; LRL(-x, -y, phi, &LRL4_param); double LRL4_lengths[3] = {-LRL4_param.t, -LRL4_param.u, -LRL4_param.v}; char LRL4_types[] = "RLR"; if (LRL4_param.flag && !SetRSP(3, LRL4_lengths, LRL4_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRL4_param"; return false; } // backward double xb = x * std::cos(phi) + y * std::sin(phi); double yb = x * std::sin(phi) - y * std::cos(phi); RSPParam LRL5_param; LRL(xb, yb, phi, &LRL5_param); double LRL5_lengths[3] = {LRL5_param.v, LRL5_param.u, LRL5_param.t}; char LRL5_types[] = "LRL"; if (LRL5_param.flag && !SetRSP(3, LRL5_lengths, LRL5_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRL5_param"; return false; } RSPParam LRL6_param; LRL(-xb, yb, -phi, &LRL6_param); double LRL6_lengths[3] = {-LRL6_param.v, -LRL6_param.u, -LRL6_param.t}; char LRL6_types[] = "LRL"; if (LRL6_param.flag && !SetRSP(3, LRL6_lengths, LRL6_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRL6_param"; return false; } RSPParam LRL7_param; LRL(xb, -yb, -phi, &LRL7_param); double LRL7_lengths[3] = {LRL7_param.v, LRL7_param.u, LRL7_param.t}; char LRL7_types[] = "RLR"; if (LRL7_param.flag && !SetRSP(3, LRL7_lengths, LRL7_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRL7_param"; return false; } RSPParam LRL8_param; LRL(-xb, -yb, phi, &LRL8_param); double LRL8_lengths[3] = {-LRL8_param.v, -LRL8_param.u, -LRL8_param.t}; char LRL8_types[] = "RLR"; if (LRL8_param.flag && !SetRSP(3, LRL8_lengths, LRL8_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRL8_param"; return false; } return true; } bool ReedShepp::CCCC(const double x, const double y, const double phi, std::vector<ReedSheppPath>* all_possible_paths) { RSPParam LRLRn1_param; LRLRn(x, y, phi, &LRLRn1_param); double LRLRn1_lengths[4] = {LRLRn1_param.t, LRLRn1_param.u, -LRLRn1_param.u, LRLRn1_param.v}; char LRLRn1_types[] = "LRLR"; if (LRLRn1_param.flag && !SetRSP(4, LRLRn1_lengths, LRLRn1_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRLRn_param"; return false; } RSPParam LRLRn2_param; LRLRn(-x, y, -phi, &LRLRn2_param); double LRLRn2_lengths[4] = {-LRLRn2_param.t, -LRLRn2_param.u, LRLRn2_param.u, -LRLRn2_param.v}; char LRLRn2_types[] = "LRLR"; if (LRLRn2_param.flag && !SetRSP(4, LRLRn2_lengths, LRLRn2_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRLRn2_param"; return false; } RSPParam LRLRn3_param; LRLRn(x, -y, -phi, &LRLRn3_param); double LRLRn3_lengths[4] = {LRLRn3_param.t, LRLRn3_param.u, -LRLRn3_param.u, LRLRn3_param.v}; char LRLRn3_types[] = "RLRL"; if (LRLRn3_param.flag && !SetRSP(4, LRLRn3_lengths, LRLRn3_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRLRn3_param"; return false; } RSPParam LRLRn4_param; LRLRn(-x, -y, phi, &LRLRn4_param); double LRLRn4_lengths[4] = {-LRLRn4_param.t, -LRLRn4_param.u, LRLRn4_param.u, -LRLRn4_param.v}; char LRLRn4_types[] = "RLRL"; if (LRLRn4_param.flag && !SetRSP(4, LRLRn4_lengths, LRLRn4_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRLRn4_param"; return false; } RSPParam LRLRp1_param; LRLRp(x, y, phi, &LRLRp1_param); double LRLRp1_lengths[4] = {LRLRp1_param.t, LRLRp1_param.u, LRLRp1_param.u, LRLRp1_param.v}; char LRLRp1_types[] = "LRLR"; if (LRLRp1_param.flag && !SetRSP(4, LRLRp1_lengths, LRLRp1_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRLRp1_param"; return false; } RSPParam LRLRp2_param; LRLRp(-x, y, -phi, &LRLRp2_param); double LRLRp2_lengths[4] = {-LRLRp2_param.t, -LRLRp2_param.u, -LRLRp2_param.u, -LRLRp2_param.v}; char LRLRp2_types[] = "LRLR"; if (LRLRp2_param.flag && !SetRSP(4, LRLRp2_lengths, LRLRp2_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRLRp2_param"; return false; } RSPParam LRLRp3_param; LRLRp(x, -y, -phi, &LRLRp3_param); double LRLRp3_lengths[4] = {LRLRp3_param.t, LRLRp3_param.u, LRLRp3_param.u, LRLRp3_param.v}; char LRLRp3_types[] = "RLRL"; if (LRLRp3_param.flag && !SetRSP(4, LRLRp3_lengths, LRLRp3_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRLRp3_param"; return false; } RSPParam LRLRp4_param; LRLRp(-x, -y, phi, &LRLRp4_param); double LRLRp4_lengths[4] = {-LRLRp4_param.t, -LRLRp4_param.u, -LRLRp4_param.u, -LRLRp4_param.v}; char LRLRp4_types[] = "RLRL"; if (LRLRp4_param.flag && !SetRSP(4, LRLRp4_lengths, LRLRp4_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRLRp4_param"; return false; } return true; } bool ReedShepp::CCSC(const double x, const double y, const double phi, std::vector<ReedSheppPath>* all_possible_paths) { RSPParam LRSL1_param; LRSL(x, y, phi, &LRSL1_param); double LRSL1_lengths[4] = {LRSL1_param.t, -0.5 * M_PI, LRSL1_param.u, LRSL1_param.v}; char LRSL1_types[] = "LRSL"; if (LRSL1_param.flag && !SetRSP(4, LRSL1_lengths, LRSL1_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSL1_param"; return false; } RSPParam LRSL2_param; LRSL(-x, y, -phi, &LRSL2_param); double LRSL2_lengths[4] = {-LRSL2_param.t, 0.5 * M_PI, -LRSL2_param.u, -LRSL2_param.v}; char LRSL2_types[] = "LRSL"; if (LRSL2_param.flag && !SetRSP(4, LRSL2_lengths, LRSL2_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSL2_param"; return false; } RSPParam LRSL3_param; LRSL(x, -y, -phi, &LRSL3_param); double LRSL3_lengths[4] = {LRSL3_param.t, -0.5 * M_PI, LRSL3_param.u, LRSL3_param.v}; char LRSL3_types[] = "RLSR"; if (LRSL3_param.flag && !SetRSP(4, LRSL3_lengths, LRSL3_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSL3_param"; return false; } RSPParam LRSL4_param; LRSL(-x, -y, phi, &LRSL4_param); double LRSL4_lengths[4] = {-LRSL4_param.t, 0.5 * M_PI, -LRSL4_param.u, -LRSL4_param.v}; char LRSL4_types[] = "RLSR"; if (LRSL4_param.flag && !SetRSP(4, LRSL4_lengths, LRSL4_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSL4_param"; return false; } RSPParam LRSR1_param; LRSR(x, y, phi, &LRSR1_param); double LRSR1_lengths[4] = {LRSR1_param.t, -0.5 * M_PI, LRSR1_param.u, LRSR1_param.v}; char LRSR1_types[] = "LRSR"; if (LRSR1_param.flag && !SetRSP(4, LRSR1_lengths, LRSR1_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSR1_param"; return false; } RSPParam LRSR2_param; LRSR(-x, y, -phi, &LRSR2_param); double LRSR2_lengths[4] = {-LRSR2_param.t, 0.5 * M_PI, -LRSR2_param.u, -LRSR2_param.v}; char LRSR2_types[] = "LRSR"; if (LRSR2_param.flag && !SetRSP(4, LRSR2_lengths, LRSR2_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSR2_param"; return false; } RSPParam LRSR3_param; LRSR(x, -y, -phi, &LRSR3_param); double LRSR3_lengths[4] = {LRSR3_param.t, -0.5 * M_PI, LRSR3_param.u, LRSR3_param.v}; char LRSR3_types[] = "RLSL"; if (LRSR3_param.flag && !SetRSP(4, LRSR3_lengths, LRSR3_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSR3_param"; return false; } RSPParam LRSR4_param; LRSR(-x, -y, phi, &LRSR4_param); double LRSR4_lengths[4] = {-LRSR4_param.t, 0.5 * M_PI, -LRSR4_param.u, -LRSR4_param.v}; char LRSR4_types[] = "RLSL"; if (LRSR4_param.flag && !SetRSP(4, LRSR4_lengths, LRSR4_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSR4_param"; return false; } // backward double xb = x * std::cos(phi) + y * std::sin(phi); double yb = x * std::sin(phi) - y * std::cos(phi); RSPParam LRSL5_param; LRSL(xb, yb, phi, &LRSL5_param); double LRSL5_lengths[4] = {LRSL5_param.v, LRSL5_param.u, -0.5 * M_PI, LRSL5_param.t}; char LRSL5_types[] = "LSRL"; if (LRSL5_param.flag && !SetRSP(4, LRSL5_lengths, LRSL5_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRLRn_param"; return false; } RSPParam LRSL6_param; LRSL(-xb, yb, -phi, &LRSL6_param); double LRSL6_lengths[4] = {-LRSL6_param.v, -LRSL6_param.u, 0.5 * M_PI, -LRSL6_param.t}; char LRSL6_types[] = "LSRL"; if (LRSL6_param.flag && !SetRSP(4, LRSL6_lengths, LRSL6_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSL6_param"; return false; } RSPParam LRSL7_param; LRSL(xb, -yb, -phi, &LRSL7_param); double LRSL7_lengths[4] = {LRSL7_param.v, LRSL7_param.u, -0.5 * M_PI, LRSL7_param.t}; char LRSL7_types[] = "RSLR"; if (LRSL7_param.flag && !SetRSP(4, LRSL7_lengths, LRSL7_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSL7_param"; return false; } RSPParam LRSL8_param; LRSL(-xb, -yb, phi, &LRSL8_param); double LRSL8_lengths[4] = {-LRSL8_param.v, -LRSL8_param.u, 0.5 * M_PI, -LRSL8_param.t}; char LRSL8_types[] = "RSLR"; if (LRSL8_param.flag && !SetRSP(4, LRSL8_lengths, LRSL8_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSL8_param"; return false; } RSPParam LRSR5_param; LRSR(xb, yb, phi, &LRSR5_param); double LRSR5_lengths[4] = {LRSR5_param.v, LRSR5_param.u, -0.5 * M_PI, LRSR5_param.t}; char LRSR5_types[] = "RSRL"; if (LRSR5_param.flag && !SetRSP(4, LRSR5_lengths, LRSR5_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSR5_param"; return false; } RSPParam LRSR6_param; LRSR(-xb, yb, -phi, &LRSR6_param); double LRSR6_lengths[4] = {-LRSR6_param.v, -LRSR6_param.u, 0.5 * M_PI, -LRSR6_param.t}; char LRSR6_types[] = "RSRL"; if (LRSR6_param.flag && !SetRSP(4, LRSR6_lengths, LRSR6_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSR6_param"; return false; } RSPParam LRSR7_param; LRSR(xb, -yb, -phi, &LRSR7_param); double LRSR7_lengths[4] = {LRSR7_param.v, LRSR7_param.u, -0.5 * M_PI, LRSR7_param.t}; char LRSR7_types[] = "LSLR"; if (LRSR7_param.flag && !SetRSP(4, LRSR7_lengths, LRSR7_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSR7_param"; return false; } RSPParam LRSR8_param; LRSR(-xb, -yb, phi, &LRSR8_param); double LRSR8_lengths[4] = {-LRSR8_param.v, -LRSR8_param.u, 0.5 * M_PI, -LRSR8_param.t}; char LRSR8_types[] = "LSLR"; if (LRSR8_param.flag && !SetRSP(4, LRSR8_lengths, LRSR8_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSR8_param"; return false; } return true; } bool ReedShepp::CCSCC(const double x, const double y, const double phi, std::vector<ReedSheppPath>* all_possible_paths) { RSPParam LRSLR1_param; LRSLR(x, y, phi, &LRSLR1_param); double LRSLR1_lengths[5] = {LRSLR1_param.t, -0.5 * M_PI, LRSLR1_param.u, -0.5 * M_PI, LRSLR1_param.v}; char LRSLR1_types[] = "LRSLR"; if (LRSLR1_param.flag && !SetRSP(5, LRSLR1_lengths, LRSLR1_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSLR1_param"; return false; } RSPParam LRSLR2_param; LRSLR(-x, y, -phi, &LRSLR2_param); double LRSLR2_lengths[5] = {-LRSLR2_param.t, 0.5 * M_PI, -LRSLR2_param.u, 0.5 * M_PI, -LRSLR2_param.v}; char LRSLR2_types[] = "LRSLR"; if (LRSLR2_param.flag && !SetRSP(5, LRSLR2_lengths, LRSLR2_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSLR2_param"; return false; } RSPParam LRSLR3_param; LRSLR(x, -y, -phi, &LRSLR3_param); double LRSLR3_lengths[5] = {LRSLR3_param.t, -0.5 * M_PI, LRSLR3_param.u, -0.5 * M_PI, LRSLR3_param.v}; char LRSLR3_types[] = "RLSRL"; if (LRSLR3_param.flag && !SetRSP(5, LRSLR3_lengths, LRSLR3_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSLR3_param"; return false; } RSPParam LRSLR4_param; LRSLR(-x, -y, phi, &LRSLR4_param); double LRSLR4_lengths[5] = {-LRSLR4_param.t, 0.5 * M_PI, -LRSLR4_param.u, 0.5 * M_PI, -LRSLR4_param.v}; char LRSLR4_types[] = "RLSRL"; if (LRSLR4_param.flag && !SetRSP(5, LRSLR4_lengths, LRSLR4_types, all_possible_paths)) { ADEBUG << "Fail at SetRSP with LRSLR4_param"; return false; } return true; } void ReedShepp::LSL(const double x, const double y, const double phi, RSPParam* param) { std::pair<double, double> polar = common::math::Cartesian2Polar(x - std::sin(phi), y - 1.0 + std::cos(phi)); double u = polar.first; double t = polar.second; double v = 0.0; if (t >= 0.0) { v = common::math::NormalizeAngle(phi - t); if (v >= 0.0) { param->flag = true; param->u = u; param->t = t; param->v = v; } } } void ReedShepp::LSR(const double x, const double y, const double phi, RSPParam* param) { std::pair<double, double> polar = common::math::Cartesian2Polar(x + std::sin(phi), y - 1.0 - std::cos(phi)); double u1 = polar.first * polar.first; double t1 = polar.second; double u = 0.0; double theta = 0.0; double t = 0.0; double v = 0.0; if (u1 >= 4.0) { u = std::sqrt(u1 - 4.0); theta = std::atan2(2.0, u); t = common::math::NormalizeAngle(t1 + theta); v = common::math::NormalizeAngle(t - phi); if (t >= 0.0 && v >= 0.0) { param->flag = true; param->u = u; param->t = t; param->v = v; } } } void ReedShepp::LRL(const double x, const double y, const double phi, RSPParam* param) { std::pair<double, double> polar = common::math::Cartesian2Polar(x - std::sin(phi), y - 1.0 + std::cos(phi)); double u1 = polar.first; double t1 = polar.second; double u = 0.0; double t = 0.0; double v = 0.0; if (u1 <= 4.0) { u = -2.0 * std::asin(0.25 * u1); t = common::math::NormalizeAngle(t1 + 0.5 * u + M_PI); v = common::math::NormalizeAngle(phi - t + u); if (t >= 0.0 && u <= 0.0) { param->flag = true; param->u = u; param->t = t; param->v = v; } } } void ReedShepp::SLS(const double x, const double y, const double phi, RSPParam* param) { double phi_mod = common::math::NormalizeAngle(phi); double xd = 0.0; double u = 0.0; double t = 0.0; double v = 0.0; double epsilon = 1e-1; if (y > 0.0 && phi_mod > epsilon && phi_mod < M_PI) { xd = -y / std::tan(phi_mod) + x; t = xd - std::tan(phi_mod / 2.0); u = phi_mod; v = std::sqrt((x - xd) * (x - xd) + y * y) - tan(phi_mod / 2.0); param->flag = true; param->u = u; param->t = t; param->v = v; } else if (y < 0.0 && phi_mod > epsilon && phi_mod < M_PI) { xd = -y / std::tan(phi_mod) + x; t = xd - std::tan(phi_mod / 2.0); u = phi_mod; v = -std::sqrt((x - xd) * (x - xd) + y * y) - std::tan(phi_mod / 2.0); param->flag = true; param->u = u; param->t = t; param->v = v; } } void ReedShepp::LRLRn(const double x, const double y, const double phi, RSPParam* param) { double xi = x + std::sin(phi); double eta = y - 1.0 - std::cos(phi); double rho = 0.25 * (2.0 + std::sqrt(xi * xi + eta * eta)); double u = 0.0; if (rho <= 1.0 && rho >= 0.0) { u = std::acos(rho); if (u >= 0 && u <= 0.5 * M_PI) { std::pair<double, double> tau_omega = calc_tau_omega(u, -u, xi, eta, phi); if (tau_omega.first >= 0.0 && tau_omega.second <= 0.0) { param->flag = true; param->u = u; param->t = tau_omega.first; param->v = tau_omega.second; } } } } void ReedShepp::LRLRp(const double x, const double y, const double phi, RSPParam* param) { double xi = x + std::sin(phi); double eta = y - 1.0 - std::cos(phi); double rho = (20.0 - xi * xi - eta * eta) / 16.0; double u = 0.0; if (rho <= 1.0 && rho >= 0.0) { u = -std::acos(rho); if (u >= 0 && u <= 0.5 * M_PI) { std::pair<double, double> tau_omega = calc_tau_omega(u, u, xi, eta, phi); if (tau_omega.first >= 0.0 && tau_omega.second >= 0.0) { param->flag = true; param->u = u; param->t = tau_omega.first; param->v = tau_omega.second; } } } } void ReedShepp::LRSR(const double x, const double y, const double phi, RSPParam* param) { double xi = x + std::sin(phi); double eta = y - 1.0 - std::cos(phi); std::pair<double, double> polar = common::math::Cartesian2Polar(-eta, xi); double rho = polar.first; double theta = polar.second; double t = 0.0; double u = 0.0; double v = 0.0; if (rho >= 2.0) { t = theta; u = 2.0 - rho; v = common::math::NormalizeAngle(t + 0.5 * M_PI - phi); if (t >= 0.0 && u <= 0.0 && v <= 0.0) { param->flag = true; param->u = u; param->t = t; param->v = v; } } } void ReedShepp::LRSL(const double x, const double y, const double phi, RSPParam* param) { double xi = x - std::sin(phi); double eta = y - 1.0 + std::cos(phi); std::pair<double, double> polar = common::math::Cartesian2Polar(xi, eta); double rho = polar.first; double theta = polar.second; double r = 0.0; double t = 0.0; double u = 0.0; double v = 0.0; if (rho >= 2.0) { r = std::sqrt(rho * rho - 4.0); u = 2.0 - r; t = common::math::NormalizeAngle(theta + std::atan2(r, -2.0)); v = common::math::NormalizeAngle(phi - 0.5 * M_PI - t); if (t >= 0.0 && u <= 0.0 && v <= 0.0) { param->flag = true; param->u = u; param->t = t; param->v = v; } } } void ReedShepp::LRSLR(const double x, const double y, const double phi, RSPParam* param) { double xi = x + std::sin(phi); double eta = y - 1.0 - std::cos(phi); std::pair<double, double> polar = common::math::Cartesian2Polar(xi, eta); double rho = polar.first; double t = 0.0; double u = 0.0; double v = 0.0; if (rho >= 2.0) { u = 4.0 - std::sqrt(rho * rho - 4.0); if (u <= 0.0) { t = common::math::NormalizeAngle( atan2((4.0 - u) * xi - 2.0 * eta, -2.0 * xi + (u - 4.0) * eta)); v = common::math::NormalizeAngle(t - phi); if (t >= 0.0 && v >= 0.0) { param->flag = true; param->u = u; param->t = t; param->v = v; } } } } bool ReedShepp::SetRSP(const int size, const double* lengths, const char* types, std::vector<ReedSheppPath>* all_possible_paths) { ReedSheppPath path; std::vector<double> length_vec(lengths, lengths + size); std::vector<char> type_vec(types, types + size); path.segs_lengths = length_vec; path.segs_types = type_vec; double sum = 0.0; for (int i = 0; i < size; ++i) { sum += std::abs(lengths[i]); } path.total_length = sum; if (path.total_length <= 0.0) { AERROR << "total length smaller than 0"; return false; } all_possible_paths->emplace_back(path); return true; } // TODO(Jinyun) : reformulate GenerateLocalConfigurations. bool ReedShepp::GenerateLocalConfigurations( const std::shared_ptr<Node3d> start_node, const std::shared_ptr<Node3d> end_node, ReedSheppPath* shortest_path) { double step_scaled = planner_open_space_config_.warm_start_config().step_size() * max_kappa_; size_t point_num = static_cast<size_t>( std::floor(shortest_path->total_length / step_scaled + static_cast<double>(shortest_path->segs_lengths.size()) + 4)); std::vector<double> px(point_num, 0.0); std::vector<double> py(point_num, 0.0); std::vector<double> pphi(point_num, 0.0); std::vector<bool> pgear(point_num, true); int index = 1; double d = 0.0; double pd = 0.0; double ll = 0.0; if (shortest_path->segs_lengths.at(0) > 0.0) { pgear.at(0) = true; d = step_scaled; } else { pgear.at(0) = false; d = -step_scaled; } pd = d; for (size_t i = 0; i < shortest_path->segs_types.size(); ++i) { char m = shortest_path->segs_types.at(i); double l = shortest_path->segs_lengths.at(i); if (l > 0.0) { d = step_scaled; } else { d = -step_scaled; } double ox = px.at(index); double oy = py.at(index); double ophi = pphi.at(index); index--; if (i >= 1 && shortest_path->segs_lengths.at(i - 1) * shortest_path->segs_lengths.at(i) > 0) { pd = -d - ll; } else { pd = d - ll; } while (std::abs(pd) <= std::abs(l)) { index++; Interpolation(index, pd, m, ox, oy, ophi, &px, &py, &pphi, &pgear); pd += d; } ll = l - pd - d; index++; Interpolation(index, l, m, ox, oy, ophi, &px, &py, &pphi, &pgear); } double epsilon = 1e-15; while (std::fabs(px.back()) < epsilon && std::fabs(py.back()) < epsilon && std::fabs(pphi.back()) < epsilon && pgear.back()) { px.pop_back(); py.pop_back(); pphi.pop_back(); pgear.pop_back(); } for (size_t i = 0; i < px.size(); ++i) { shortest_path->x.push_back(std::cos(-start_node->GetPhi()) * px.at(i) + std::sin(-start_node->GetPhi()) * py.at(i) + start_node->GetX()); shortest_path->y.push_back(-std::sin(-start_node->GetPhi()) * px.at(i) + std::cos(-start_node->GetPhi()) * py.at(i) + start_node->GetY()); shortest_path->phi.push_back( common::math::NormalizeAngle(pphi.at(i) + start_node->GetPhi())); } shortest_path->gear = pgear; for (size_t i = 0; i < shortest_path->segs_lengths.size(); ++i) { shortest_path->segs_lengths.at(i) = shortest_path->segs_lengths.at(i) / max_kappa_; } shortest_path->total_length = shortest_path->total_length / max_kappa_; return true; } void ReedShepp::Interpolation(const int index, const double pd, const char m, const double ox, const double oy, const double ophi, std::vector<double>* px, std ::vector<double>* py, std::vector<double>* pphi, std::vector<bool>* pgear) { double ldx = 0.0; double ldy = 0.0; double gdx = 0.0; double gdy = 0.0; if (m == 'S') { px->at(index) = ox + pd / max_kappa_ * std::cos(ophi); py->at(index) = oy + pd / max_kappa_ * std::sin(ophi); pphi->at(index) = ophi; } else { ldx = std::sin(pd) / max_kappa_; if (m == 'L') { ldy = (1.0 - std::cos(pd)) / max_kappa_; } else if (m == 'R') { ldy = (1.0 - std::cos(pd)) / -max_kappa_; } gdx = std::cos(-ophi) * ldx + std::sin(-ophi) * ldy; gdy = -std::sin(-ophi) * ldx + std::cos(-ophi) * ldy; px->at(index) = ox + gdx; py->at(index) = oy + gdy; } if (pd > 0.0) { pgear->at(index) = true; } else { pgear->at(index) = false; } if (m == 'L') { pphi->at(index) = ophi + pd; } else if (m == 'R') { pphi->at(index) = ophi - pd; } } bool ReedShepp::SetRSPPar(const int size, const double* lengths, const std::string& types, std::vector<ReedSheppPath>* all_possible_paths, const int idx) { ReedSheppPath path; std::vector<double> length_vec(lengths, lengths + size); std::vector<char> type_vec(types.begin(), types.begin() + size); path.segs_lengths = length_vec; path.segs_types = type_vec; double sum = 0.0; for (int i = 0; i < size; ++i) { sum += std::abs(lengths[i]); } path.total_length = sum; if (path.total_length <= 0.0) { AERROR << "total length smaller than 0"; return false; } all_possible_paths->at(idx) = path; return true; } bool ReedShepp::GenerateRSPPar(const std::shared_ptr<Node3d> start_node, const std::shared_ptr<Node3d> end_node, std::vector<ReedSheppPath>* all_possible_paths) { double dx = end_node->GetX() - start_node->GetX(); double dy = end_node->GetY() - start_node->GetY(); double dphi = end_node->GetPhi() - start_node->GetPhi(); double c = std::cos(start_node->GetPhi()); double s = std::sin(start_node->GetPhi()); // normalize the initial point to (0,0,0) double x = (c * dx + s * dy) * this->max_kappa_; double y = (-s * dx + c * dy) * this->max_kappa_; // backward double xb = x * std::cos(dphi) + y * std::sin(dphi); double yb = x * std::sin(dphi) - y * std::cos(dphi); int RSP_nums = 46; all_possible_paths->resize(RSP_nums); bool succ = true; #pragma omp parallel for schedule(dynamic, 2) num_threads(8) for (int i = 0; i < RSP_nums; ++i) { RSPParam RSP_param; int tmp_length = 0; double RSP_lengths[5] = {0.0, 0.0, 0.0, 0.0, 0.0}; double x_param = 1.0; double y_param = 1.0; std::string rd_type; if (i > 2 && i % 2) { x_param = -1.0; } if (i > 2 && i % 4 < 2) { y_param = -1.0; } if (i < 2) { // SCS case if (i == 1) { y_param = -1.0; rd_type = "SRS"; } else { rd_type = "SLS"; } SLS(x, y_param * y, y_param * dphi, &RSP_param); tmp_length = 3; RSP_lengths[0] = RSP_param.t; RSP_lengths[1] = RSP_param.u; RSP_lengths[2] = RSP_param.v; } else if (i < 6) { // CSC, LSL case LSL(x_param * x, y_param * y, x_param * y_param * dphi, &RSP_param); if (y_param > 0) { rd_type = "LSL"; } else { rd_type = "RSR"; } tmp_length = 3; RSP_lengths[0] = x_param * RSP_param.t; RSP_lengths[1] = x_param * RSP_param.u; RSP_lengths[2] = x_param * RSP_param.v; } else if (i < 10) { // CSC, LSR case LSR(x_param * x, y_param * y, x_param * y_param * dphi, &RSP_param); if (y_param > 0) { rd_type = "LSR"; } else { rd_type = "RSL"; } tmp_length = 3; RSP_lengths[0] = x_param * RSP_param.t; RSP_lengths[1] = x_param * RSP_param.u; RSP_lengths[2] = x_param * RSP_param.v; } else if (i < 14) { // CCC, LRL case LRL(x_param * x, y_param * y, x_param * y_param * dphi, &RSP_param); if (y_param > 0) { rd_type = "LRL"; } else { rd_type = "RLR"; } tmp_length = 3; RSP_lengths[0] = x_param * RSP_param.t; RSP_lengths[1] = x_param * RSP_param.u; RSP_lengths[2] = x_param * RSP_param.v; } else if (i < 18) { // CCC, LRL case, backward LRL(x_param * xb, y_param * yb, x_param * y_param * dphi, &RSP_param); if (y_param > 0) { rd_type = "LRL"; } else { rd_type = "RLR"; } tmp_length = 3; RSP_lengths[0] = x_param * RSP_param.v; RSP_lengths[1] = x_param * RSP_param.u; RSP_lengths[2] = x_param * RSP_param.t; } else if (i < 22) { // CCCC, LRLRn LRLRn(x_param * x, y_param * y, x_param * y_param * dphi, &RSP_param); if (y_param > 0.0) { rd_type = "LRLR"; } else { rd_type = "RLRL"; } tmp_length = 4; RSP_lengths[0] = x_param * RSP_param.t; RSP_lengths[1] = x_param * RSP_param.u; RSP_lengths[2] = -x_param * RSP_param.u; RSP_lengths[3] = x_param * RSP_param.v; } else if (i < 26) { // CCCC, LRLRp LRLRp(x_param * x, y_param * y, x_param * y_param * dphi, &RSP_param); if (y_param > 0.0) { rd_type = "LRLR"; } else { rd_type = "RLRL"; } tmp_length = 4; RSP_lengths[0] = x_param * RSP_param.t; RSP_lengths[1] = x_param * RSP_param.u; RSP_lengths[2] = -x_param * RSP_param.u; RSP_lengths[3] = x_param * RSP_param.v; } else if (i < 30) { // CCSC, LRLRn tmp_length = 4; LRLRn(x_param * x, y_param * y, x_param * y_param * dphi, &RSP_param); if (y_param > 0.0) { rd_type = "LRSL"; } else { rd_type = "RLSR"; } RSP_lengths[0] = x_param * RSP_param.t; if (x_param < 0 && y_param > 0) { RSP_lengths[1] = 0.5 * M_PI; } else { RSP_lengths[1] = -0.5 * M_PI; } if (x_param > 0 && y_param < 0) { RSP_lengths[2] = RSP_param.u; } else { RSP_lengths[2] = -RSP_param.u; } RSP_lengths[3] = x_param * RSP_param.v; } else if (i < 34) { // CCSC, LRLRp tmp_length = 4; LRLRp(x_param * x, y_param * y, x_param * y_param * dphi, &RSP_param); if (y_param) { rd_type = "LRSR"; } else { rd_type = "RLSL"; } RSP_lengths[0] = x_param * RSP_param.t; if (x_param < 0 && y_param > 0) { RSP_lengths[1] = 0.5 * M_PI; } else { RSP_lengths[1] = -0.5 * M_PI; } RSP_lengths[2] = x_param * RSP_param.u; RSP_lengths[3] = x_param * RSP_param.v; } else if (i < 38) { // CCSC, LRLRn, backward tmp_length = 4; LRLRn(x_param * xb, y_param * yb, x_param * y_param * dphi, &RSP_param); if (y_param > 0) { rd_type = "LSRL"; } else { rd_type = "RSLR"; } RSP_lengths[0] = x_param * RSP_param.v; RSP_lengths[1] = x_param * RSP_param.u; RSP_lengths[2] = -x_param * 0.5 * M_PI; RSP_lengths[3] = x_param * RSP_param.t; } else if (i < 42) { // CCSC, LRLRp, backward tmp_length = 4; LRLRp(x_param * xb, y_param * yb, x_param * y_param * dphi, &RSP_param); if (y_param > 0) { rd_type = "RSRL"; } else { rd_type = "LSLR"; } RSP_lengths[0] = x_param * RSP_param.v; RSP_lengths[1] = x_param * RSP_param.u; RSP_lengths[2] = -x_param * M_PI * 0.5; RSP_lengths[3] = x_param * RSP_param.t; } else { // CCSCC, LRSLR tmp_length = 5; LRSLR(x_param * x, y_param * y, x_param * y_param * dphi, &RSP_param); if (y_param > 0.0) { rd_type = "LRSLR"; } else { rd_type = "RLSRL"; } RSP_lengths[0] = x_param * RSP_param.t; RSP_lengths[1] = -x_param * 0.5 * M_PI; RSP_lengths[2] = x_param * RSP_param.u; RSP_lengths[3] = -x_param * 0.5 * M_PI; RSP_lengths[4] = x_param * RSP_param.v; } if (tmp_length > 0) { if (RSP_param.flag && !SetRSPPar(tmp_length, RSP_lengths, rd_type, all_possible_paths, i)) { AERROR << "Fail at SetRSP, idx#: " << i; succ = false; } } } if (!succ) { AERROR << "RSP parallel fails"; return false; } if (all_possible_paths->size() == 0) { AERROR << "No path generated by certain two configurations"; return false; } return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/math/curve_math.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 curve_math.h **/ #pragma once namespace apollo { namespace planning { class CurveMath { public: CurveMath() = delete; /** * @brief Compute the curvature (kappa) given curve X = (x(t), y(t)) * which t is an arbitrary parameter. * @param dx dx / dt * @param d2x d(dx) / dt * @param dy dy / dt * @param d2y d(dy) / dt * @return the curvature */ static double ComputeCurvature(const double dx, const double d2x, const double dy, const double d2y); /** * @brief Compute the curvature change rate w.r.t. curve length (dkappa) given * curve X = (x(t), y(t)) * which t is an arbitrary parameter. * @param dx dx / dt * @param d2x d(dx) / dt * @param dy dy / dt * @param d2y d(dy) / dt * @param d3x d(d2x) / dt * @param d3y d(d2y) / dt * @return the curvature change rate */ static double ComputeCurvatureDerivative(const double dx, const double d2x, const double d3x, const double dy, const double d2y, const double d3y); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/math/discrete_points_math.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 discrete_points_math.h **/ #pragma once #include <utility> #include <vector> namespace apollo { namespace planning { class DiscretePointsMath { public: DiscretePointsMath() = delete; static bool ComputePathProfile( const std::vector<std::pair<double, double>>& xy_points, std::vector<double>* headings, std::vector<double>* accumulated_s, std::vector<double>* kappas, std::vector<double>* dkappas); }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/math/curve_math_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 curvature_math_test.cc **/ #include "modules/planning/math/curve_math.h" #include <cmath> #include "gtest/gtest.h" namespace apollo { namespace planning { TEST(TestSuite, curvature_math_test) { // Straight line double curvature = CurveMath::ComputeCurvature(1.0, 0.0, 1.0, 0.0); EXPECT_NEAR(curvature, 0.0, 1e-6); double curvature_derivative = CurveMath::ComputeCurvatureDerivative(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); EXPECT_NEAR(curvature_derivative, 0.0, 1e-6); // Unit circle X = (std::cos(t), std::sin(t)), at t = 0.0 curvature = CurveMath::ComputeCurvature(0.0, -1, 1.0, 0.0); EXPECT_NEAR(curvature, 1.0, 1e-6); // Unit circle X = (std::cos(t), std::sin(t)), at t = PI/4, double cos_angle = std::cos(M_PI / 4); double sin_angle = std::sin(M_PI / 4); curvature = CurveMath::ComputeCurvature(-sin_angle, -cos_angle, cos_angle, -sin_angle); EXPECT_NEAR(curvature, 1.0, 1e-6); curvature_derivative = CurveMath::ComputeCurvatureDerivative( -sin_angle, -cos_angle, sin_angle, cos_angle, -sin_angle, -cos_angle); EXPECT_NEAR(curvature_derivative, 0.0, 1e-6); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/math/polynomial_xd.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: polynomial_xd.h **/ #pragma once #include <cinttypes> #include <vector> namespace apollo { namespace planning { class PolynomialXd { public: PolynomialXd() = default; explicit PolynomialXd(const std::uint32_t order); explicit PolynomialXd(const std::vector<double>& params); double operator()(const double value) const; double operator[](const std::uint32_t index) const; void SetParams(const std::vector<double>& params); static PolynomialXd DerivedFrom(const PolynomialXd& base); static PolynomialXd IntegratedFrom(const PolynomialXd& base, const double intercept = 0.0); std::uint32_t order() const; const std::vector<double>& params() const; private: std::vector<double> params_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/math/polynomial_xd.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: polynomial_xd.cc **/ #include "modules/planning/math/polynomial_xd.h" #include "cyber/common/log.h" namespace apollo { namespace planning { PolynomialXd::PolynomialXd(const std::uint32_t order) : params_(order + 1, 0.0) { CHECK_GE(order, 0U); } PolynomialXd::PolynomialXd(const std::vector<double>& params) : params_(params) { ACHECK(!params.empty()); } std::uint32_t PolynomialXd::order() const { return static_cast<std::uint32_t>(params_.size()) - 1; } void PolynomialXd::SetParams(const std::vector<double>& params) { ACHECK(!params.empty()); params_ = params; } const std::vector<double>& PolynomialXd::params() const { return params_; } PolynomialXd PolynomialXd::DerivedFrom(const PolynomialXd& base) { std::vector<double> params; if (base.order() <= 0) { params.clear(); } else { params.resize(base.params().size() - 1); for (std::uint32_t i = 1; i < base.order() + 1; ++i) { params[i - 1] = base[i] * i; } } return PolynomialXd(params); } PolynomialXd PolynomialXd::IntegratedFrom(const PolynomialXd& base, const double intercept) { std::vector<double> params; params.resize(base.params().size() + 1); params[0] = intercept; for (std::uint32_t i = 0; i < base.params().size(); ++i) { params[i + 1] = base[i] / (i + 1); } return PolynomialXd(params); } double PolynomialXd::operator()(const double value) const { double result = 0.0; for (auto rit = params_.rbegin(); rit != params_.rend(); ++rit) { result *= value; result += (*rit); } return result; } double PolynomialXd::operator[](const std::uint32_t index) const { if (index >= params_.size()) { return 0.0; } else { return params_[index]; } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/math/curve_math.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 curve_math.cc **/ #include "modules/planning/math/curve_math.h" #include <cmath> namespace apollo { namespace planning { // kappa = (dx * d2y - dy * d2x) / [(dx * dx + dy * dy)^(3/2)] double CurveMath::ComputeCurvature(const double dx, const double d2x, const double dy, const double d2y) { const double a = dx * d2y - dy * d2x; auto norm_square = dx * dx + dy * dy; auto norm = std::sqrt(norm_square); const double b = norm * norm_square; return a / b; } double CurveMath::ComputeCurvatureDerivative(const double dx, const double d2x, const double d3x, const double dy, const double d2y, const double d3y) { const double a = dx * d2y - dy * d2x; const double b = dx * d3y - dy * d3x; const double c = dx * d2x + dy * d2y; const double d = dx * dx + dy * dy; return (b * d - 3.0 * a * c) / (d * d * d); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/math/discrete_points_math.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 discrete_points_math.cc **/ #include "modules/planning/math/discrete_points_math.h" #include <cmath> #include "cyber/common/log.h" namespace apollo { namespace planning { bool DiscretePointsMath::ComputePathProfile( const std::vector<std::pair<double, double>>& xy_points, std::vector<double>* headings, std::vector<double>* accumulated_s, std::vector<double>* kappas, std::vector<double>* dkappas) { CHECK_NOTNULL(headings); CHECK_NOTNULL(kappas); CHECK_NOTNULL(dkappas); headings->clear(); kappas->clear(); dkappas->clear(); if (xy_points.size() < 2) { return false; } std::vector<double> dxs; std::vector<double> dys; std::vector<double> y_over_s_first_derivatives; std::vector<double> x_over_s_first_derivatives; std::vector<double> y_over_s_second_derivatives; std::vector<double> x_over_s_second_derivatives; // Get finite difference approximated dx and dy for heading and kappa // calculation std::size_t points_size = xy_points.size(); for (std::size_t i = 0; i < points_size; ++i) { double x_delta = 0.0; double y_delta = 0.0; if (i == 0) { x_delta = (xy_points[i + 1].first - xy_points[i].first); y_delta = (xy_points[i + 1].second - xy_points[i].second); } else if (i == points_size - 1) { x_delta = (xy_points[i].first - xy_points[i - 1].first); y_delta = (xy_points[i].second - xy_points[i - 1].second); } else { x_delta = 0.5 * (xy_points[i + 1].first - xy_points[i - 1].first); y_delta = 0.5 * (xy_points[i + 1].second - xy_points[i - 1].second); } dxs.push_back(x_delta); dys.push_back(y_delta); } // Heading calculation for (std::size_t i = 0; i < points_size; ++i) { headings->push_back(std::atan2(dys[i], dxs[i])); } // Get linear interpolated s for dkappa calculation double distance = 0.0; accumulated_s->push_back(distance); double fx = xy_points[0].first; double fy = xy_points[0].second; double nx = 0.0; double ny = 0.0; for (std::size_t i = 1; i < points_size; ++i) { nx = xy_points[i].first; ny = xy_points[i].second; double end_segment_s = std::sqrt((fx - nx) * (fx - nx) + (fy - ny) * (fy - ny)); accumulated_s->push_back(end_segment_s + distance); distance += end_segment_s; fx = nx; fy = ny; } // Get finite difference approximated first derivative of y and x respective // to s for kappa calculation for (std::size_t i = 0; i < points_size; ++i) { double xds = 0.0; double yds = 0.0; if (i == 0) { xds = (xy_points[i + 1].first - xy_points[i].first) / (accumulated_s->at(i + 1) - accumulated_s->at(i)); yds = (xy_points[i + 1].second - xy_points[i].second) / (accumulated_s->at(i + 1) - accumulated_s->at(i)); } else if (i == points_size - 1) { xds = (xy_points[i].first - xy_points[i - 1].first) / (accumulated_s->at(i) - accumulated_s->at(i - 1)); yds = (xy_points[i].second - xy_points[i - 1].second) / (accumulated_s->at(i) - accumulated_s->at(i - 1)); } else { xds = (xy_points[i + 1].first - xy_points[i - 1].first) / (accumulated_s->at(i + 1) - accumulated_s->at(i - 1)); yds = (xy_points[i + 1].second - xy_points[i - 1].second) / (accumulated_s->at(i + 1) - accumulated_s->at(i - 1)); } x_over_s_first_derivatives.push_back(xds); y_over_s_first_derivatives.push_back(yds); } // Get finite difference approximated second derivative of y and x respective // to s for kappa calculation for (std::size_t i = 0; i < points_size; ++i) { double xdds = 0.0; double ydds = 0.0; if (i == 0) { xdds = (x_over_s_first_derivatives[i + 1] - x_over_s_first_derivatives[i]) / (accumulated_s->at(i + 1) - accumulated_s->at(i)); ydds = (y_over_s_first_derivatives[i + 1] - y_over_s_first_derivatives[i]) / (accumulated_s->at(i + 1) - accumulated_s->at(i)); } else if (i == points_size - 1) { xdds = (x_over_s_first_derivatives[i] - x_over_s_first_derivatives[i - 1]) / (accumulated_s->at(i) - accumulated_s->at(i - 1)); ydds = (y_over_s_first_derivatives[i] - y_over_s_first_derivatives[i - 1]) / (accumulated_s->at(i) - accumulated_s->at(i - 1)); } else { xdds = (x_over_s_first_derivatives[i + 1] - x_over_s_first_derivatives[i - 1]) / (accumulated_s->at(i + 1) - accumulated_s->at(i - 1)); ydds = (y_over_s_first_derivatives[i + 1] - y_over_s_first_derivatives[i - 1]) / (accumulated_s->at(i + 1) - accumulated_s->at(i - 1)); } x_over_s_second_derivatives.push_back(xdds); y_over_s_second_derivatives.push_back(ydds); } for (std::size_t i = 0; i < points_size; ++i) { double xds = x_over_s_first_derivatives[i]; double yds = y_over_s_first_derivatives[i]; double xdds = x_over_s_second_derivatives[i]; double ydds = y_over_s_second_derivatives[i]; double kappa = (xds * ydds - yds * xdds) / (std::sqrt(xds * xds + yds * yds) * (xds * xds + yds * yds) + 1e-6); kappas->push_back(kappa); } // Dkappa calculation for (std::size_t i = 0; i < points_size; ++i) { double dkappa = 0.0; if (i == 0) { dkappa = (kappas->at(i + 1) - kappas->at(i)) / (accumulated_s->at(i + 1) - accumulated_s->at(i)); } else if (i == points_size - 1) { dkappa = (kappas->at(i) - kappas->at(i - 1)) / (accumulated_s->at(i) - accumulated_s->at(i - 1)); } else { dkappa = (kappas->at(i + 1) - kappas->at(i - 1)) / (accumulated_s->at(i + 1) - accumulated_s->at(i - 1)); } dkappas->push_back(dkappa); } return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning
apollo_public_repos/apollo/modules/planning/math/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 = "curve_math", srcs = ["curve_math.cc"], hdrs = ["curve_math.h"], ) cc_library( name = "discrete_points_math", srcs = ["discrete_points_math.cc"], hdrs = ["discrete_points_math.h"], copts = PLANNING_COPTS, deps = [ "//cyber", ], ) cc_test( name = "curve_math_test", size = "small", srcs = ["curve_math_test.cc"], deps = [ ":curve_math", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "polynomial_xd", srcs = ["polynomial_xd.cc"], hdrs = ["polynomial_xd.h"], copts = PLANNING_COPTS, deps = [ "//cyber", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/cubic_polynomial_curve1d_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/math/curve1d/cubic_polynomial_curve1d.h" #include "gtest/gtest.h" #include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h" namespace apollo { namespace planning { TEST(CubicPolynomialCurve1dTest, Evaluate) { { double x0 = 0.0; double dx0 = 0.0; double ddx0 = 0.0; double x1 = 10.0; double param = 8.0; CubicPolynomialCurve1d curve(x0, dx0, ddx0, x1, param); EXPECT_NEAR(x1, curve.Evaluate(0, param), 1e-8); EXPECT_NEAR(0, curve.Evaluate(0, 0.0), 1e-8); EXPECT_NEAR(0, curve.Evaluate(1, 0.0), 1e-8); EXPECT_NEAR(0, curve.Evaluate(2, 0.0), 1e-8); } { double x0 = 0.0; double dx0 = 0.0; double ddx0 = 0.0; double x1 = 5.0; double param = 3.0; CubicPolynomialCurve1d curve(x0, dx0, ddx0, x1, param); EXPECT_NEAR(x1, curve.Evaluate(0, param), 1e-8); EXPECT_NEAR(0, curve.Evaluate(0, 0.0), 1e-8); EXPECT_NEAR(0, curve.Evaluate(1, 0.0), 1e-8); EXPECT_NEAR(0, curve.Evaluate(2, 0.0), 1e-8); } { double x0 = 1.0; double dx0 = 2.0; double ddx0 = 3.0; double x1 = 5.0; double param = 3.0; CubicPolynomialCurve1d curve(x0, dx0, ddx0, x1, param); EXPECT_NEAR(x1, curve.Evaluate(0, param), 1e-8); EXPECT_NEAR(x0, curve.Evaluate(0, 0.0), 1e-8); EXPECT_NEAR(dx0, curve.Evaluate(1, 0.0), 1e-8); EXPECT_NEAR(ddx0, curve.Evaluate(2, 0.0), 1e-8); } } TEST(CubicPolynomialCurve1dTest, derived_from_quartic_curve) { QuarticPolynomialCurve1d quartic_curve(0., 0., 0.5, 1., 1., 2.); CubicPolynomialCurve1d cubic_curve; cubic_curve.DerivedFromQuarticCurve(quartic_curve); for (double value = 0; value < 2.1; value += 0.1) { EXPECT_NEAR(quartic_curve.Evaluate(1, value), cubic_curve.Evaluate(0, value), 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(2, value), cubic_curve.Evaluate(1, value), 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(3, value), cubic_curve.Evaluate(2, value), 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(4, value), cubic_curve.Evaluate(3, value), 1e-8); } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/quartic_polynomial_curve1d_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h" #include "gtest/gtest.h" #include "modules/planning/math/curve1d/cubic_polynomial_curve1d.h" #include "modules/planning/math/curve1d/quintic_polynomial_curve1d.h" namespace apollo { namespace planning { TEST(QuarticPolynomialCurve1dTest, Evaluate) { { double x0 = 0.0; double dx0 = 0.0; double ddx0 = 0.0; double dx1 = 10.0; double ddx1 = 1.0; double param = 8.0; QuarticPolynomialCurve1d curve(x0, dx0, ddx0, dx1, ddx1, param); EXPECT_NEAR(dx1, curve.Evaluate(1, param), 1e-8); EXPECT_NEAR(ddx1, curve.Evaluate(2, param), 1e-8); EXPECT_NEAR(0, curve.Evaluate(0, 0.0), 1e-8); EXPECT_NEAR(0, curve.Evaluate(1, 0.0), 1e-8); EXPECT_NEAR(0, curve.Evaluate(2, 0.0), 1e-8); } { double x0 = 0.0; double dx0 = 0.0; double ddx0 = 0.0; double dx1 = 5.0; double ddx1 = 1.0; double param = 3.0; QuarticPolynomialCurve1d curve(x0, dx0, ddx0, dx1, ddx1, param); EXPECT_NEAR(dx1, curve.Evaluate(1, param), 1e-8); EXPECT_NEAR(ddx1, curve.Evaluate(2, param), 1e-8); EXPECT_NEAR(0, curve.Evaluate(0, 0.0), 1e-8); EXPECT_NEAR(0, curve.Evaluate(1, 0.0), 1e-8); EXPECT_NEAR(0, curve.Evaluate(2, 0.0), 1e-8); } { double x0 = 1.0; double dx0 = 2.0; double ddx0 = 3.0; double dx1 = 5.0; double ddx1 = 1.0; double param = 3.0; QuarticPolynomialCurve1d curve(x0, dx0, ddx0, dx1, ddx1, param); EXPECT_NEAR(dx1, curve.Evaluate(1, param), 1e-8); EXPECT_NEAR(ddx1, curve.Evaluate(2, param), 1e-8); EXPECT_NEAR(x0, curve.Evaluate(0, 0.0), 1e-8); EXPECT_NEAR(dx0, curve.Evaluate(1, 0.0), 1e-8); EXPECT_NEAR(ddx0, curve.Evaluate(2, 0.0), 1e-8); } } TEST(QuarticPolynomialCurve1dTest, IntegratedFromCubicCurve) { CubicPolynomialCurve1d cubic_curve(1, 2, 3, 2, 5); QuarticPolynomialCurve1d quartic_curve; quartic_curve.IntegratedFromCubicCurve(cubic_curve, 0.0); for (double value = 0.0; value < 5.1; value += 1) { EXPECT_NEAR(quartic_curve.Evaluate(1, value), cubic_curve.Evaluate(0, value), 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(2, value), cubic_curve.Evaluate(1, value), 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(3, value), cubic_curve.Evaluate(2, value), 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(4, value), cubic_curve.Evaluate(3, value), 1e-8); } } TEST(QuarticPolynomialCurve1dTest, DerivedFromQuinticCurve) { QuinticPolynomialCurve1d quintic_curve(1, 2, 3, 2, 1, 2, 5); QuarticPolynomialCurve1d quartic_curve; quartic_curve.DerivedFromQuinticCurve(quintic_curve); for (double value = 0.0; value < 5.1; value += 1) { EXPECT_NEAR(quartic_curve.Evaluate(0, value), quintic_curve.Evaluate(1, value), 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(1, value), quintic_curve.Evaluate(2, value), 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(2, value), quintic_curve.Evaluate(3, value), 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(3, value), quintic_curve.Evaluate(4, value), 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(4, value), quintic_curve.Evaluate(5, value), 1e-8); } } TEST(QuarticPolynomialCurve1dTest, FitWithEndPointFirstOrder) { QuarticPolynomialCurve1d quartic_curve(1, 2, 4, 2, 1, 3); quartic_curve.FitWithEndPointFirstOrder(2, 3, 2, 1, 2, 5); EXPECT_NEAR(quartic_curve.Evaluate(0, 0), 2, 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(1, 0), 3, 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(2, 0), 2, 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(0, 5), 1, 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(1, 5), 2, 1e-8); EXPECT_NEAR(quartic_curve.ParamLength(), 5, 1e-8); } TEST(QuarticPolynomialCurve1dTest, FitWithEndPointSecondOrder) { QuarticPolynomialCurve1d quartic_curve(1, 2, 4, 2, 1, 3); quartic_curve.FitWithEndPointSecondOrder(2, 7, 2, 6, 2, 8); EXPECT_NEAR(quartic_curve.Evaluate(0, 0), 2, 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(1, 0), 7, 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(0, 8), 2, 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(1, 8), 6, 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(2, 8), 2, 1e-8); EXPECT_NEAR(quartic_curve.ParamLength(), 8, 1e-8); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/piecewise_quintic_spiral_path.h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <string> #include <vector> #include "modules/planning/math/curve1d/curve1d.h" #include "modules/planning/math/curve1d/quintic_spiral_path.h" namespace apollo { namespace planning { class PiecewiseQuinticSpiralPath : public Curve1d { public: PiecewiseQuinticSpiralPath(const double theta, const double kappa, const double dkappa); virtual ~PiecewiseQuinticSpiralPath() = default; void Append(const double theta, const double kappa, const double dkappa, const double delta_s); double Evaluate(const std::uint32_t order, const double param) const override; double DeriveKappaS(const double s) const; double ParamLength() const override; std::string ToString() const override { return "PiecewiseQuinticSpiralPath"; } private: size_t LocatePiece(const double param) const; std::vector<QuinticSpiralPath> pieces_; std::vector<double> accumulated_s_; double last_theta_ = 0.0; double last_kappa_ = 0.0; double last_dkappa_ = 0.0; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/quintic_spiral_path_with_derivation.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 <unordered_map> #include <utility> #include "cyber/common/log.h" #include "modules/common/math/integral.h" #include "modules/planning/math/curve1d/quintic_polynomial_curve1d.h" namespace apollo { namespace planning { template <size_t N> class QuinticSpiralPathWithDerivation : public QuinticPolynomialCurve1d { public: QuinticSpiralPathWithDerivation() = default; QuinticSpiralPathWithDerivation(const std::array<double, 3>& start, const std::array<double, 3>& end, const double delta_s); QuinticSpiralPathWithDerivation(const double theta0, const double kappa0, const double dkappa0, const double theta1, const double kappa1, const double dkappa1, const double delta_s); virtual ~QuinticSpiralPathWithDerivation() = default; double evaluate(const size_t order, const size_t i, const size_t n); double ComputeCartesianDeviationX() const { return dx_; } double ComputeCartesianDeviationY() const { return dy_; } std::pair<double, double> DeriveCartesianDeviation(const size_t param_index); double DeriveKappaDerivative(const size_t param_index, const int i, const int n); double DeriveDKappaDerivative(const size_t param_index, const int i, const int n); static const size_t THETA0 = 0; static const size_t KAPPA0 = 1; static const size_t DKAPPA0 = 2; static const size_t THETA1 = 3; static const size_t KAPPA1 = 4; static const size_t DKAPPA1 = 5; static const size_t DELTA_S = 6; static const size_t INDEX_MAX = 7; double ComputeCartesianDeviationX(const double s) const { auto cos_theta = [this](const double s) { const auto a = Evaluate(0, s); return std::cos(a); }; return common::math::IntegrateByGaussLegendre<N>(cos_theta, 0.0, s); } double ComputeCartesianDeviationY(const double s) const { auto sin_theta = [this](const double s) { const auto a = Evaluate(0, s); return std::sin(a); }; return common::math::IntegrateByGaussLegendre<N>(sin_theta, 0.0, s); } private: double DeriveCosTheta(const size_t param_index, const double r) const; double DeriveSinTheta(const size_t param_index, const double r) const; double DeriveThetaDerivative(const size_t param_index, const double r) const; std::array<std::array<double, 7>, 6> coef_deriv_; std::unordered_map<size_t, double> cache_evaluate_; std::unordered_map<size_t, std::pair<double, double>> cache_cartesian_deriv_; std::unordered_map<size_t, double> cache_kappa_deriv_; std::unordered_map<size_t, double> cache_dkappa_deriv_; double dx_ = 0.0; double dy_ = 0.0; std::array<double, N> gauss_points_; std::array<double, N> gauss_point_weights_; }; template <size_t N> QuinticSpiralPathWithDerivation<N>::QuinticSpiralPathWithDerivation( const double x0, const double dx0, const double ddx0, const double x1, const double dx1, const double ddx1, const double s) : QuinticPolynomialCurve1d(x0, dx0, ddx0, x1, dx1, ddx1, s) { ACHECK(s > 0.0); auto gauss_points = common::math::GetGaussLegendrePoints<N>(); gauss_points_ = gauss_points.first; gauss_point_weights_ = gauss_points.second; dx_ = ComputeCartesianDeviationX(s); dy_ = ComputeCartesianDeviationY(s); double s2 = s * s; double s3 = s2 * s; double s4 = s3 * s; double s5 = s2 * s3; double s6 = s3 * s3; for (size_t i = 0; i < 6; ++i) { for (size_t j = 0; j < 7; ++j) { coef_deriv_[i][j] = 0.0; } } // derive a // double a = -6.0 * x0 / p5 - 3.0 * dx0 / p4 - 0.5 * ddx0 / p3 + 6.0 * x1 / // p5 - 3.0 * dx1 / p4 + 0.5 * ddx1 / p3; coef_deriv_[5][0] = -6.0 / s5; coef_deriv_[5][1] = -3.0 / s4; coef_deriv_[5][2] = -0.5 / s3; coef_deriv_[5][3] = 6.0 / s5; coef_deriv_[5][4] = -3.0 / s4; coef_deriv_[5][5] = 0.5 / s3; coef_deriv_[5][6] = 30.0 * x0 / s6 + 12.0 * dx0 / s5 + 1.5 * ddx0 / s4 - 30.0 * x1 / s6 + 12.0 * dx1 / s5 - 1.5 * ddx1 / s4; // derive b // double b = 15.0 * x0 / p4 + 8.0 * dx0 / p3 + 1.5 * ddx0 / p2 - 15.0 * x1 / // p4 + 7.0 * dx1 / p3 - ddx1 / p2; coef_deriv_[4][0] = 15.0 / s4; coef_deriv_[4][1] = 8.0 / s3; coef_deriv_[4][2] = 1.5 / s2; coef_deriv_[4][3] = -15.0 / s4; coef_deriv_[4][4] = 7.0 / s3; coef_deriv_[4][5] = -1.0 / s2; coef_deriv_[4][6] = -60.0 * x0 / s5 - 24.0 * dx0 / s4 - 3.0 * ddx0 / s3 + 60.0 * x1 / s5 - 21.0 * dx1 / s4 + 2.0 * ddx1 / s3; // derive c // double c = -10.0 * x0 / p3 - 6.0 * dx0 / p2 - 1.5 * ddx0 / p + 10.0 * x1 / // p3 - 4.0 * dx1 / p2 + 0.5 * ddx1 / p; coef_deriv_[3][0] = -10.0 / s3; coef_deriv_[3][1] = -6.0 / s2; coef_deriv_[3][2] = -1.5 / s; coef_deriv_[3][3] = 10.0 / s3; coef_deriv_[3][4] = -4.0 / s2; coef_deriv_[3][5] = 0.5 / s; coef_deriv_[3][6] = 30.0 * x0 / s4 + 12.0 * dx0 / s3 + 1.5 * ddx0 / s2 - 30.0 * x1 / s4 + 8.0 * dx1 / s3 - 0.5 * ddx1 / s2; // derive d // double d = 0.5 * ddx0; coef_deriv_[2][2] = 0.5; // derive e // double e = dx0; coef_deriv_[1][1] = 1.0; // derive f // double f = x0; coef_deriv_[0][0] = 1.0; } template <size_t N> QuinticSpiralPathWithDerivation<N>::QuinticSpiralPathWithDerivation( const std::array<double, 3>& start, const std::array<double, 3>& end, const double delta_s) : QuinticSpiralPathWithDerivation<N>(start[0], start[1], start[2], end[0], end[1], end[2], delta_s) {} template <size_t N> double QuinticSpiralPathWithDerivation<N>::evaluate(const size_t order, const size_t i, const size_t n) { auto key = order * 100 + n * 10 + i; if (cache_evaluate_.find(key) != cache_evaluate_.end()) { return cache_evaluate_[key]; } auto res = Evaluate(order, static_cast<double>(i) / static_cast<double>(n) * param_); cache_evaluate_[key] = res; return res; } template <size_t N> std::pair<double, double> QuinticSpiralPathWithDerivation<N>::DeriveCartesianDeviation( const size_t param_index) { if (cache_cartesian_deriv_.find(param_index) != cache_cartesian_deriv_.end()) { return cache_cartesian_deriv_[param_index]; } const auto& g = gauss_points_; const auto& w = gauss_point_weights_; std::pair<double, double> cartesian_deviation = {0.0, 0.0}; if (param_index != DELTA_S) { for (size_t i = 0; i < N; ++i) { double r = 0.5 * g[i] + 0.5; cartesian_deviation.first += w[i] * DeriveCosTheta(param_index, r); cartesian_deviation.second += w[i] * DeriveSinTheta(param_index, r); } cartesian_deviation.first *= param_ * 0.5; cartesian_deviation.second *= param_ * 0.5; } else { for (size_t i = 0; i < N; ++i) { double r = 0.5 * g[i] + 0.5; cartesian_deviation.first += w[i] * DeriveCosTheta(param_index, r); cartesian_deviation.second += w[i] * DeriveSinTheta(param_index, r); } cartesian_deviation.first *= param_ * 0.5; cartesian_deviation.second *= param_ * 0.5; for (size_t i = 0; i < N; ++i) { double r = 0.5 * g[i] + 0.5; auto theta = Evaluate(0, r * param_); cartesian_deviation.first += 0.5 * w[i] * std::cos(theta); cartesian_deviation.second += 0.5 * w[i] * std::sin(theta); } } cache_cartesian_deriv_[param_index] = cartesian_deviation; return cartesian_deviation; } template <size_t N> double QuinticSpiralPathWithDerivation<N>::DeriveKappaDerivative( const size_t param_index, const int i, const int n) { auto key = param_index * INDEX_MAX + i; if (cache_kappa_deriv_.find(key) != cache_kappa_deriv_.end()) { return cache_kappa_deriv_[key]; } auto r = static_cast<double>(i) / static_cast<double>(n); double s = param_ * r; double s2 = s * s; double s3 = s2 * s; double s4 = s2 * s2; double derivative = 5.0 * coef_deriv_[5][param_index] * s4 + 4.0 * coef_deriv_[4][param_index] * s3 + 3.0 * coef_deriv_[3][param_index] * s2 + 2.0 * coef_deriv_[2][param_index] * s + coef_deriv_[1][param_index]; if (param_index == DELTA_S) { derivative += 20.0 * coef_[5] * s3 * r + 12.0 * coef_[4] * s2 * r + 6.0 * coef_[3] * s * r + 2.0 * coef_[2] * r; } cache_kappa_deriv_[key] = derivative; return derivative; } template <size_t N> double QuinticSpiralPathWithDerivation<N>::DeriveDKappaDerivative( const size_t param_index, const int i, const int n) { auto key = param_index * INDEX_MAX + i; if (cache_dkappa_deriv_.find(key) != cache_dkappa_deriv_.end()) { return cache_dkappa_deriv_[key]; } auto r = static_cast<double>(i) / static_cast<double>(n); double s = param_ * r; double s2 = s * s; double s3 = s2 * s; double derivative = 20.0 * coef_deriv_[5][param_index] * s3 + 12.0 * coef_deriv_[4][param_index] * s2 + 6.0 * coef_deriv_[3][param_index] * s + 2.0 * coef_deriv_[2][param_index]; if (param_index == DELTA_S) { derivative += 60.0 * coef_[5] * s2 * r + 24.0 * coef_[4] * s * r + 6.0 * coef_[3] * r; } cache_dkappa_deriv_[key] = derivative; return derivative; } template <size_t N> double QuinticSpiralPathWithDerivation<N>::DeriveThetaDerivative( const size_t param_index, const double r) const { double s = param_ * r; double s2 = s * s; double s3 = s2 * s; double s4 = s2 * s2; double s5 = s3 * s2; double derivative = coef_deriv_[5][param_index] * s5 + coef_deriv_[4][param_index] * s4 + coef_deriv_[3][param_index] * s3 + coef_deriv_[2][param_index] * s2 + coef_deriv_[1][param_index] * s + coef_deriv_[0][param_index]; if (param_index == DELTA_S) { derivative += coef_[5] * 5.0 * s4 * r + coef_[4] * 4.0 * s3 * r + coef_[3] * 3.0 * s2 * r + coef_[2] * 2.0 * s * r + coef_[1] * r; } return derivative; } template <size_t N> double QuinticSpiralPathWithDerivation<N>::DeriveCosTheta( const size_t param_index, const double r) const { double g = param_ * r; double theta = Evaluate(0, g); double derivative = -std::sin(theta) * DeriveThetaDerivative(param_index, r); return derivative; } template <size_t N> double QuinticSpiralPathWithDerivation<N>::DeriveSinTheta( const size_t param_index, const double r) const { double g = param_ * r; double theta = Evaluate(0, g); double derivative = std::cos(theta) * DeriveThetaDerivative(param_index, r); return derivative; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/quintic_polynomial_curve1d.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 quintic_polynomial_curve1d.cc **/ #include "modules/planning/math/curve1d/quintic_polynomial_curve1d.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "cyber/common/log.h" namespace apollo { namespace planning { QuinticPolynomialCurve1d::QuinticPolynomialCurve1d( const std::array<double, 3>& start, const std::array<double, 3>& end, const double param) : QuinticPolynomialCurve1d(start[0], start[1], start[2], end[0], end[1], end[2], param) {} QuinticPolynomialCurve1d::QuinticPolynomialCurve1d( const double x0, const double dx0, const double ddx0, const double x1, const double dx1, const double ddx1, const double param) { ComputeCoefficients(x0, dx0, ddx0, x1, dx1, ddx1, param); start_condition_[0] = x0; start_condition_[1] = dx0; start_condition_[2] = ddx0; end_condition_[0] = x1; end_condition_[1] = dx1; end_condition_[2] = ddx1; param_ = param; } QuinticPolynomialCurve1d::QuinticPolynomialCurve1d( const QuinticPolynomialCurve1d& other) { param_ = other.param_; coef_ = other.coef_; } double QuinticPolynomialCurve1d::Evaluate(const uint32_t order, const double p) const { switch (order) { case 0: { return ((((coef_[5] * p + coef_[4]) * p + coef_[3]) * p + coef_[2]) * p + coef_[1]) * p + coef_[0]; } case 1: { return (((5.0 * coef_[5] * p + 4.0 * coef_[4]) * p + 3.0 * coef_[3]) * p + 2.0 * coef_[2]) * p + coef_[1]; } case 2: { return (((20.0 * coef_[5] * p + 12.0 * coef_[4]) * p) + 6.0 * coef_[3]) * p + 2.0 * coef_[2]; } case 3: { return (60.0 * coef_[5] * p + 24.0 * coef_[4]) * p + 6.0 * coef_[3]; } case 4: { return 120.0 * coef_[5] * p + 24.0 * coef_[4]; } case 5: { return 120.0 * coef_[5]; } default: return 0.0; } } void QuinticPolynomialCurve1d::SetParam(const double x0, const double dx0, const double ddx0, const double x1, const double dx1, const double ddx1, const double param) { ComputeCoefficients(x0, dx0, ddx0, x1, dx1, ddx1, param); param_ = param; } void QuinticPolynomialCurve1d::IntegratedFromQuarticCurve( const PolynomialCurve1d& other, const double init_value) { CHECK_EQ(other.Order(), 4U); param_ = other.ParamLength(); coef_[0] = init_value; for (size_t i = 0; i < 5; ++i) { coef_[i + 1] = other.Coef(i) / (static_cast<double>(i) + 1); } } void QuinticPolynomialCurve1d::ComputeCoefficients( const double x0, const double dx0, const double ddx0, const double x1, const double dx1, const double ddx1, const double p) { CHECK_GT(p, 0.0); coef_[0] = x0; coef_[1] = dx0; coef_[2] = ddx0 / 2.0; const double p2 = p * p; const double p3 = p * p2; // the direct analytical method is at least 6 times faster than using matrix // inversion. const double c0 = (x1 - 0.5 * p2 * ddx0 - dx0 * p - x0) / p3; const double c1 = (dx1 - ddx0 * p - dx0) / p2; const double c2 = (ddx1 - ddx0) / p; coef_[3] = 0.5 * (20.0 * c0 - 8.0 * c1 + c2); coef_[4] = (-15.0 * c0 + 7.0 * c1 - c2) / p; coef_[5] = (6.0 * c0 - 3.0 * c1 + 0.5 * c2) / p2; } std::string QuinticPolynomialCurve1d::ToString() const { return absl::StrCat(absl::StrJoin(coef_, "\t"), param_, "\n"); } double QuinticPolynomialCurve1d::Coef(const size_t order) const { CHECK_GT(6U, order); return coef_[order]; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/cubic_polynomial_curve1d.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #pragma once #include <array> #include <string> #include "modules/planning/math/curve1d/polynomial_curve1d.h" namespace apollo { namespace planning { class CubicPolynomialCurve1d : public PolynomialCurve1d { public: CubicPolynomialCurve1d() = default; virtual ~CubicPolynomialCurve1d() = default; CubicPolynomialCurve1d(const std::array<double, 3>& start, const double end, const double param); /** * x0 is the value when f(x = 0); * dx0 is the value when f'(x = 0); * ddx0 is the value when f''(x = 0); * f(x = param) = x1 */ CubicPolynomialCurve1d(const double x0, const double dx0, const double ddx0, const double x1, const double param); void DerivedFromQuarticCurve(const PolynomialCurve1d& other); double Evaluate(const std::uint32_t order, const double p) const override; double ParamLength() const override { return param_; } std::string ToString() const override; double Coef(const size_t order) const override; size_t Order() const override { return 3; } private: void ComputeCoefficients(const double x0, const double dx0, const double ddx0, const double x1, const double param); std::array<double, 4> coef_ = {{0.0, 0.0, 0.0, 0.0}}; std::array<double, 3> start_condition_ = {{0.0, 0.0, 0.0}}; double end_condition_ = 0.0; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/quartic_polynomial_curve1d.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 quartic_polynomial_curve1d.cc **/ #include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "cyber/common/log.h" namespace apollo { namespace planning { QuarticPolynomialCurve1d::QuarticPolynomialCurve1d( const std::array<double, 3>& start, const std::array<double, 2>& end, const double param) : QuarticPolynomialCurve1d(start[0], start[1], start[2], end[0], end[1], param) {} QuarticPolynomialCurve1d::QuarticPolynomialCurve1d( const double x0, const double dx0, const double ddx0, const double dx1, const double ddx1, const double param) { param_ = param; start_condition_[0] = x0; start_condition_[1] = dx0; start_condition_[2] = ddx0; end_condition_[0] = dx1; end_condition_[1] = ddx1; ComputeCoefficients(x0, dx0, ddx0, dx1, ddx1, param); } QuarticPolynomialCurve1d::QuarticPolynomialCurve1d( const QuarticPolynomialCurve1d& other) { param_ = other.param_; coef_ = other.coef_; } double QuarticPolynomialCurve1d::Evaluate(const std::uint32_t order, const double p) const { switch (order) { case 0: { return (((coef_[4] * p + coef_[3]) * p + coef_[2]) * p + coef_[1]) * p + coef_[0]; } case 1: { return ((4.0 * coef_[4] * p + 3.0 * coef_[3]) * p + 2.0 * coef_[2]) * p + coef_[1]; } case 2: { return (12.0 * coef_[4] * p + 6.0 * coef_[3]) * p + 2.0 * coef_[2]; } case 3: { return 24.0 * coef_[4] * p + 6.0 * coef_[3]; } case 4: { return 24.0 * coef_[4]; } default: return 0.0; } } QuarticPolynomialCurve1d& QuarticPolynomialCurve1d::FitWithEndPointFirstOrder( const double x0, const double dx0, const double ddx0, const double x1, const double dx1, const double p) { CHECK_GT(p, 0.0); param_ = p; coef_[0] = x0; coef_[1] = dx0; coef_[2] = 0.5 * ddx0; double p2 = p * p; double p3 = p2 * p; double p4 = p3 * p; double b0 = x1 - coef_[0] - coef_[1] * p - coef_[2] * p2; double b1 = dx1 - dx0 - ddx0 * p; coef_[4] = (b1 * p - 3 * b0) / p4; coef_[3] = (4 * b0 - b1 * p) / p3; return *this; } QuarticPolynomialCurve1d& QuarticPolynomialCurve1d::FitWithEndPointSecondOrder( const double x0, const double dx0, const double x1, const double dx1, const double ddx1, const double p) { CHECK_GT(p, 0.0); param_ = p; coef_[0] = x0; coef_[1] = dx0; double p2 = p * p; double p3 = p2 * p; double p4 = p3 * p; double b0 = x1 - coef_[0] - coef_[1] * p; double b1 = dx1 - coef_[1]; double c1 = b1 * p; double c2 = ddx1 * p2; coef_[2] = (0.5 * c2 - 3 * c1 + 6 * b0) / p2; coef_[3] = (-c2 + 5 * c1 - 8 * b0) / p3; coef_[4] = (0.5 * c2 - 2 * c1 + 3 * b0) / p4; return *this; } QuarticPolynomialCurve1d& QuarticPolynomialCurve1d::IntegratedFromCubicCurve( const PolynomialCurve1d& other, const double init_value) { CHECK_EQ(other.Order(), 3U); param_ = other.ParamLength(); coef_[0] = init_value; for (size_t i = 0; i < 4; ++i) { coef_[i + 1] = other.Coef(i) / (static_cast<double>(i) + 1); } return *this; } QuarticPolynomialCurve1d& QuarticPolynomialCurve1d::DerivedFromQuinticCurve( const PolynomialCurve1d& other) { CHECK_EQ(other.Order(), 5U); param_ = other.ParamLength(); for (size_t i = 1; i < 6; ++i) { coef_[i - 1] = other.Coef(i) * static_cast<double>(i); } return *this; } void QuarticPolynomialCurve1d::ComputeCoefficients( const double x0, const double dx0, const double ddx0, const double dx1, const double ddx1, const double p) { CHECK_GT(p, 0.0); coef_[0] = x0; coef_[1] = dx0; coef_[2] = 0.5 * ddx0; double b0 = dx1 - ddx0 * p - dx0; double b1 = ddx1 - ddx0; double p2 = p * p; double p3 = p2 * p; coef_[3] = (3 * b0 - b1 * p) / (3 * p2); coef_[4] = (-2 * b0 + b1 * p) / (4 * p3); } std::string QuarticPolynomialCurve1d::ToString() const { return absl::StrCat(absl::StrJoin(coef_, "\t"), param_, "\n"); } double QuarticPolynomialCurve1d::Coef(const size_t order) const { CHECK_GT(5U, order); return coef_[order]; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/polynomial_curve1d.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 polynomial_curve1d.h **/ #pragma once #include "modules/planning/math/curve1d/curve1d.h" namespace apollo { namespace planning { class PolynomialCurve1d : public Curve1d { public: PolynomialCurve1d() = default; virtual ~PolynomialCurve1d() = default; virtual double Coef(const size_t order) const = 0; virtual size_t Order() const = 0; protected: double param_ = 0.0; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/quintic_polynomial_curve1d.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 quintic_polynomial_curve1d.h **/ #pragma once #include <array> #include <string> #include "modules/planning/math/curve1d/polynomial_curve1d.h" namespace apollo { namespace planning { // 1D quintic polynomial curve: // (x0, dx0, ddx0) -- [0, param] --> (x1, dx1, ddx1) class QuinticPolynomialCurve1d : public PolynomialCurve1d { public: QuinticPolynomialCurve1d() = default; QuinticPolynomialCurve1d(const std::array<double, 3>& start, const std::array<double, 3>& end, const double param); QuinticPolynomialCurve1d(const double x0, const double dx0, const double ddx0, const double x1, const double dx1, const double ddx1, const double param); QuinticPolynomialCurve1d(const QuinticPolynomialCurve1d& other); void SetParam(const double x0, const double dx0, const double ddx0, const double x1, const double dx1, const double ddx1, const double param); void IntegratedFromQuarticCurve(const PolynomialCurve1d& other, const double init_value); virtual ~QuinticPolynomialCurve1d() = default; double Evaluate(const std::uint32_t order, const double p) const override; double ParamLength() const override { return param_; } std::string ToString() const override; double Coef(const size_t order) const override; size_t Order() const override { return 5; } protected: void ComputeCoefficients(const double x0, const double dx0, const double ddx0, const double x1, const double dx1, const double ddx1, const double param); // f = sum(coef_[i] * x^i), i from 0 to 5 std::array<double, 6> coef_{{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}}; std::array<double, 3> start_condition_{{0.0, 0.0, 0.0}}; std::array<double, 3> end_condition_{{0.0, 0.0, 0.0}}; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/piecewise_quintic_spiral_path.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/math/curve1d/piecewise_quintic_spiral_path.h" namespace apollo { namespace planning { PiecewiseQuinticSpiralPath::PiecewiseQuinticSpiralPath(const double theta, const double kappa, const double dkappa) : last_theta_(theta), last_kappa_(kappa), last_dkappa_(dkappa) { accumulated_s_.push_back(0.0); } void PiecewiseQuinticSpiralPath::Append(const double theta, const double kappa, const double dkappa, const double delta_s) { double s = delta_s + accumulated_s_.back(); accumulated_s_.push_back(s); pieces_.emplace_back(last_theta_, last_kappa_, last_dkappa_, theta, kappa, dkappa, delta_s); last_theta_ = theta; last_kappa_ = kappa; last_dkappa_ = dkappa; } double PiecewiseQuinticSpiralPath::Evaluate(const std::uint32_t order, const double s) const { auto index = LocatePiece(s); return pieces_[index].Evaluate(order, s - accumulated_s_[index]); } double PiecewiseQuinticSpiralPath::DeriveKappaS(const double s) const { auto index = LocatePiece(s); const auto& piece = pieces_[index]; double ratio = (s - accumulated_s_[index]) / piece.ParamLength(); return piece.DeriveKappaDerivative(QuinticSpiralPath::DELTA_S, ratio); } double PiecewiseQuinticSpiralPath::ParamLength() const { return accumulated_s_.back(); } size_t PiecewiseQuinticSpiralPath::LocatePiece(const double s) const { ACHECK(s >= accumulated_s_.front() && s <= accumulated_s_.back()); auto it_lower = std::lower_bound(accumulated_s_.begin(), accumulated_s_.end(), s); if (it_lower == accumulated_s_.begin()) { return 0; } else { return std::distance(accumulated_s_.begin(), it_lower) - 1; } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/quintic_polynomial_curve1d_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/math/curve1d/quintic_polynomial_curve1d.h" #include "gtest/gtest.h" #include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h" namespace apollo { namespace planning { TEST(QuinticPolynomialCurve1dTest, basic_test) { double x0 = 0.0; double dx0 = 1.0; double ddx0 = 0.8; double x1 = 10.0; double dx1 = 5.0; double ddx1 = 0.0; double t = 8.0; QuinticPolynomialCurve1d curve(x0, dx0, ddx0, x1, dx1, ddx1, t); auto e_x0 = curve.Evaluate(0, 0.0); auto e_dx0 = curve.Evaluate(1, 0.0); auto e_ddx0 = curve.Evaluate(2, 0.0); auto e_x1 = curve.Evaluate(0, t); auto e_dx1 = curve.Evaluate(1, t); auto e_ddx1 = curve.Evaluate(2, t); auto e_t = curve.ParamLength(); EXPECT_NEAR(x0, e_x0, 1.0e-6); EXPECT_NEAR(dx0, e_dx0, 1.0e-6); EXPECT_NEAR(ddx0, e_ddx0, 1.0e-6); EXPECT_NEAR(x1, e_x1, 1.0e-6); EXPECT_NEAR(dx1, e_dx1, 1.0e-6); EXPECT_NEAR(ddx1, e_ddx1, 1.0e-6); EXPECT_NEAR(t, e_t, 1.0e-6); } TEST(QuinticPolynomialCurve1dTest, IntegratedFromQuarticCurve) { QuarticPolynomialCurve1d quartic_curve(2, 1, 4, 3, 2, 4); QuinticPolynomialCurve1d quintic_curve; quintic_curve.IntegratedFromQuarticCurve(quartic_curve, 1); for (double value = 0.0; value < 4.1; value += 0.1) { EXPECT_NEAR(quartic_curve.Evaluate(0, value), quintic_curve.Evaluate(1, value), 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(1, value), quintic_curve.Evaluate(2, value), 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(2, value), quintic_curve.Evaluate(3, value), 1e-8); EXPECT_NEAR(quartic_curve.Evaluate(3, value), quintic_curve.Evaluate(4, value), 1e-8); } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/piecewise_quintic_spiral_path_test.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/math/curve1d/piecewise_quintic_spiral_path.h" #include "gtest/gtest.h" #include "modules/planning/math/curve1d/quintic_spiral_path.h" namespace apollo { namespace planning { TEST(PiecewiseQuinticSpiralPath, Evaluate) { double theta0 = 0.0; double kappa0 = 0.0; double dkappa0 = 0.0; double delta_s0 = 1.0; double theta1 = 0.1; double kappa1 = 1.0; double dkappa1 = 0.0; QuinticSpiralPath path0(theta0, kappa0, dkappa0, theta1, kappa1, dkappa1, delta_s0); double theta2 = 0.2; double kappa2 = 1.0; double dkappa2 = 0.0; double delta_s1 = 2.0; QuinticSpiralPath path1(theta1, kappa1, dkappa1, theta2, kappa2, dkappa2, delta_s1); PiecewiseQuinticSpiralPath piecewise_path(theta0, kappa0, dkappa0); piecewise_path.Append(theta1, kappa1, dkappa1, delta_s0); piecewise_path.Append(theta2, kappa2, dkappa2, delta_s1); EXPECT_NEAR(delta_s0 + delta_s1, piecewise_path.ParamLength(), 1.0e-8); EXPECT_NEAR(path0.Evaluate(0, 0.0), piecewise_path.Evaluate(0, 0.0), 1.0e-8); EXPECT_NEAR(path1.Evaluate(0, 0.0), piecewise_path.Evaluate(0, delta_s0), 1.0e-8); EXPECT_NEAR(path1.Evaluate(0, path1.ParamLength()), piecewise_path.Evaluate(0, piecewise_path.ParamLength()), 1.0e-8); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/cubic_polynomial_curve1d.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/math/curve1d/cubic_polynomial_curve1d.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "cyber/common/log.h" namespace apollo { namespace planning { CubicPolynomialCurve1d::CubicPolynomialCurve1d( const std::array<double, 3>& start, const double end, const double param) : CubicPolynomialCurve1d(start[0], start[1], start[2], end, param) {} CubicPolynomialCurve1d::CubicPolynomialCurve1d(const double x0, const double dx0, const double ddx0, const double x1, const double param) { ComputeCoefficients(x0, dx0, ddx0, x1, param); param_ = param; start_condition_[0] = x0; start_condition_[1] = dx0; start_condition_[2] = ddx0; end_condition_ = x1; } void CubicPolynomialCurve1d::DerivedFromQuarticCurve( const PolynomialCurve1d& other) { CHECK_EQ(other.Order(), 4U); param_ = other.ParamLength(); for (size_t i = 1; i < 5; ++i) { coef_[i - 1] = other.Coef(i) * static_cast<double>(i); } } double CubicPolynomialCurve1d::Evaluate(const std::uint32_t order, const double p) const { switch (order) { case 0: { return ((coef_[3] * p + coef_[2]) * p + coef_[1]) * p + coef_[0]; } case 1: { return (3.0 * coef_[3] * p + 2.0 * coef_[2]) * p + coef_[1]; } case 2: { return 6.0 * coef_[3] * p + 2.0 * coef_[2]; } case 3: { return 6.0 * coef_[3]; } default: return 0.0; } } std::string CubicPolynomialCurve1d::ToString() const { return absl::StrCat(absl::StrJoin(coef_, "\t"), param_, "\n"); } void CubicPolynomialCurve1d::ComputeCoefficients(const double x0, const double dx0, const double ddx0, const double x1, const double param) { DCHECK(param > 0.0); const double p2 = param * param; const double p3 = param * p2; coef_[0] = x0; coef_[1] = dx0; coef_[2] = 0.5 * ddx0; coef_[3] = (x1 - x0 - dx0 * param - coef_[2] * p2) / p3; } double CubicPolynomialCurve1d::Coef(const size_t order) const { CHECK_GT(4U, order); return coef_[order]; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/curve1d.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 curve1d.h **/ #pragma once #include <string> namespace apollo { namespace planning { // Base type for various types of 1-dimensional curves class Curve1d { public: Curve1d() = default; virtual ~Curve1d() = default; virtual double Evaluate(const std::uint32_t order, const double param) const = 0; virtual double ParamLength() const = 0; virtual std::string ToString() const = 0; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/quartic_polynomial_curve1d.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 quartic_polynomial_curve1d.h **/ #pragma once #include <array> #include <string> #include "modules/planning/math/curve1d/polynomial_curve1d.h" namespace apollo { namespace planning { // 1D quartic polynomial curve: (x0, dx0, ddx0) -- [0, param] --> (dx1, ddx1) class QuarticPolynomialCurve1d : public PolynomialCurve1d { public: QuarticPolynomialCurve1d() = default; QuarticPolynomialCurve1d(const std::array<double, 3>& start, const std::array<double, 2>& end, const double param); QuarticPolynomialCurve1d(const double x0, const double dx0, const double ddx0, const double dx1, const double ddx1, const double param); QuarticPolynomialCurve1d(const QuarticPolynomialCurve1d& other); virtual ~QuarticPolynomialCurve1d() = default; double Evaluate(const std::uint32_t order, const double p) const override; /** * Interface with refine quartic polynomial by meets end first order * and start second order boundary condition: * @param x0 init point x location * @param dx0 init point derivative * @param ddx0 init point second order derivative * @param x1 end point x location * @param dx1 end point derivative * @param param parameter length * @return self */ QuarticPolynomialCurve1d& FitWithEndPointFirstOrder( const double x0, const double dx0, const double ddx0, const double x1, const double dx1, const double param); /** * Interface with refine quartic polynomial by meets end point second order * and start point first order boundary condition */ QuarticPolynomialCurve1d& FitWithEndPointSecondOrder( const double x0, const double dx0, const double x1, const double dx1, const double ddx1, const double param); /* * Integrated from cubic curve with init value */ QuarticPolynomialCurve1d& IntegratedFromCubicCurve( const PolynomialCurve1d& other, const double init_value); /* * Derived from quintic curve */ QuarticPolynomialCurve1d& DerivedFromQuinticCurve( const PolynomialCurve1d& other); double ParamLength() const override { return param_; } std::string ToString() const override; double Coef(const size_t order) const override; size_t Order() const override { return 4; } private: void ComputeCoefficients(const double x0, const double dx0, const double ddx0, const double dx1, const double ddx1, const double param); std::array<double, 5> coef_ = {{0.0, 0.0, 0.0, 0.0, 0.0}}; std::array<double, 3> start_condition_ = {{0.0, 0.0, 0.0}}; std::array<double, 2> end_condition_ = {{0.0, 0.0}}; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/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 = "curve1d", hdrs = ["curve1d.h"], ) cc_library( name = "polynomial_curve1d", hdrs = ["polynomial_curve1d.h"], deps = [ ":curve1d", ], ) cc_library( name = "quartic_polynomial_curve1d", srcs = ["quartic_polynomial_curve1d.cc"], hdrs = ["quartic_polynomial_curve1d.h"], deps = [ ":polynomial_curve1d", "//cyber", "//modules/common/util:util_tool", "@com_google_absl//:absl", ], ) cc_test( name = "quartic_polynomial_curve1d_test", size = "small", srcs = ["quartic_polynomial_curve1d_test.cc"], copts = PLANNING_COPTS, deps = [ ":cubic_polynomial_curve1d", ":quartic_polynomial_curve1d", ":quintic_polynomial_curve1d", "//cyber", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "quintic_polynomial_curve1d", srcs = ["quintic_polynomial_curve1d.cc"], hdrs = ["quintic_polynomial_curve1d.h"], deps = [ ":polynomial_curve1d", "//cyber", "//modules/common/util:util_tool", "@com_google_absl//:absl", ], ) cc_library( name = "cubic_polynomial_curve1d", srcs = ["cubic_polynomial_curve1d.cc"], hdrs = ["cubic_polynomial_curve1d.h"], copts = PLANNING_COPTS, deps = [ ":polynomial_curve1d", ":quartic_polynomial_curve1d", "//cyber", "@com_google_absl//:absl", ], ) cc_test( name = "cubic_polynomial_curve1d_test", size = "small", srcs = ["cubic_polynomial_curve1d_test.cc"], deps = [ ":cubic_polynomial_curve1d", ":quartic_polynomial_curve1d", "//cyber", "@com_google_googletest//:gtest_main", ], ) cc_library( name = "quintic_spiral_path", srcs = ["quintic_spiral_path.cc"], hdrs = [ "quintic_spiral_path.h", "quintic_spiral_path_with_derivation.h", ], copts = PLANNING_COPTS, deps = [ ":quintic_polynomial_curve1d", "//cyber", "//modules/common/math", "@com_google_absl//:absl", ], ) cc_library( name = "piecewise_quintic_spiral_path", srcs = ["piecewise_quintic_spiral_path.cc"], hdrs = ["piecewise_quintic_spiral_path.h"], copts = PLANNING_COPTS, deps = [ ":quintic_spiral_path", "//cyber", "//modules/common/math", "@com_google_absl//:absl", ], ) cc_test( name = "quintic_polynomial_curve1d_test", size = "small", srcs = ["quintic_polynomial_curve1d_test.cc"], copts = PLANNING_COPTS, deps = [ ":quartic_polynomial_curve1d", ":quintic_polynomial_curve1d", "//cyber", "@com_google_googletest//:gtest_main", ], ) cc_test( name = "piecewise_quintic_spiral_path_test", size = "small", srcs = ["piecewise_quintic_spiral_path_test.cc"], copts = PLANNING_COPTS, deps = [ ":piecewise_quintic_spiral_path", "//cyber", "@com_google_googletest//:gtest_main", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/quintic_spiral_path.h
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file quintic_spiral_path.h **/ #pragma once #include <utility> #include "cyber/common/log.h" #include "modules/common/math/angle.h" #include "modules/common/math/integral.h" #include "modules/planning/math/curve1d/quintic_polynomial_curve1d.h" namespace apollo { namespace planning { /** * Describe a quintic spiral path * Map (theta0, kappa0, dkappa0) ----- delta_s -----> (theta1, kappa1, dkappa1) */ class QuinticSpiralPath : public QuinticPolynomialCurve1d { public: QuinticSpiralPath() = default; QuinticSpiralPath(const std::array<double, 3>& start, const std::array<double, 3>& end, const double delta_s); QuinticSpiralPath(const double theta0, const double kappa0, const double dkappa0, const double theta1, const double kappa1, const double dkappa1, const double delta_s); template <size_t N> double ComputeCartesianDeviationX(const double s) const { auto cos_theta = [this](const double s) { const auto a = Evaluate(0, s); return std::cos(a); }; return common::math::IntegrateByGaussLegendre<N>(cos_theta, 0.0, s); } template <size_t N> double ComputeCartesianDeviationY(const double s) const { auto sin_theta = [this](const double s) { const auto a = Evaluate(0, s); return std::sin(a); }; return common::math::IntegrateByGaussLegendre<N>(sin_theta, 0.0, s); } template <size_t N> std::pair<double, double> DeriveCartesianDeviation( const size_t param_index) const { auto gauss_points = common::math::GetGaussLegendrePoints<N>(); std::array<double, N> x = gauss_points.first; std::array<double, N> w = gauss_points.second; std::pair<double, double> cartesian_deviation = {0.0, 0.0}; for (size_t i = 0; i < N; ++i) { double r = 0.5 * x[i] + 0.5; auto curr_theta = Evaluate(0, r * param_); double derived_theta = DeriveTheta(param_index, r); cartesian_deviation.first += w[i] * (-std::sin(curr_theta)) * derived_theta; cartesian_deviation.second += w[i] * std::cos(curr_theta) * derived_theta; } cartesian_deviation.first *= param_ * 0.5; cartesian_deviation.second *= param_ * 0.5; if (param_index == DELTA_S) { for (size_t i = 0; i < N; ++i) { double r = 0.5 * x[i] + 0.5; auto theta_angle = Evaluate(0, r * param_); cartesian_deviation.first += 0.5 * w[i] * std::cos(theta_angle); cartesian_deviation.second += 0.5 * w[i] * std::sin(theta_angle); } } return cartesian_deviation; } double DeriveKappaDerivative(const size_t param_index, const double ratio) const; double DeriveDKappaDerivative(const size_t param_index, const double ratio) const; double DeriveD2KappaDerivative(const size_t param_index, const double r) const; static const size_t THETA0 = 0; static const size_t KAPPA0 = 1; static const size_t DKAPPA0 = 2; static const size_t THETA1 = 3; static const size_t KAPPA1 = 4; static const size_t DKAPPA1 = 5; static const size_t DELTA_S = 6; private: double DeriveTheta(const size_t param_index, const double delta_s_ratio) const; std::array<std::array<double, 7>, 6> coef_deriv_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/curve1d/quintic_spiral_path.cc
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file quintic_spiral_path.cpp **/ #include "modules/planning/math/curve1d/quintic_spiral_path.h" namespace apollo { namespace planning { QuinticSpiralPath::QuinticSpiralPath(const double x0, const double dx0, const double ddx0, const double x1, const double dx1, const double ddx1, const double p) : QuinticPolynomialCurve1d(x0, dx0, ddx0, x1, dx1, ddx1, p) { ACHECK(p > 0.0); double p2 = p * p; double p3 = p2 * p; double p4 = p3 * p; double p5 = p2 * p3; double p6 = p3 * p3; // derive a // double a = -6.0 * x0 / p5 - 3.0 * dx0 / p4 - 0.5 * ddx0 / p3 + 6.0 * x1 / // p5 - 3.0 * dx1 / p4 + 0.5 * ddx1 / p3; coef_deriv_[5][0] = -6.0 / p5; coef_deriv_[5][1] = -3.0 / p4; coef_deriv_[5][2] = -0.5 / p3; coef_deriv_[5][3] = 6.0 / p5; coef_deriv_[5][4] = -3.0 / p4; coef_deriv_[5][5] = 0.5 / p3; coef_deriv_[5][6] = 30.0 * x0 / p6 + 12.0 * dx0 / p5 + 1.5 * ddx0 / p4 - 30.0 * x1 / p6 + 12.0 * dx1 / p5 - 1.5 * ddx1 / p4; // derive b // double b = 15.0 * x0 / p4 + 8.0 * dx0 / p3 + 1.5 * ddx0 / p2 - 15.0 * x1 / // p4 + 7.0 * dx1 / p3 - ddx1 / p2; coef_deriv_[4][0] = 15.0 / p4; coef_deriv_[4][1] = 8.0 / p3; coef_deriv_[4][2] = 1.5 / p2; coef_deriv_[4][3] = -15.0 / p4; coef_deriv_[4][4] = 7.0 / p3; coef_deriv_[4][5] = -1.0 / p2; coef_deriv_[4][6] = -60.0 * x0 / p5 - 24.0 * dx0 / p4 - 3.0 * ddx0 / p3 + 60.0 * x1 / p5 - 21.0 * dx1 / p4 + 2.0 * ddx1 / p3; // derive c // double c = -10.0 * x0 / p3 - 6.0 * dx0 / p2 - 1.5 * ddx0 / p + 10.0 * x1 / // p3 - 4.0 * dx1 / p2 + 0.5 * ddx1 / p; coef_deriv_[3][0] = -10.0 / p3; coef_deriv_[3][1] = -6.0 / p2; coef_deriv_[3][2] = -1.5 / p; coef_deriv_[3][3] = 10.0 / p3; coef_deriv_[3][4] = -4.0 / p2; coef_deriv_[3][5] = 0.5 / p; coef_deriv_[3][6] = 30.0 * x0 / p4 + 12.0 * dx0 / p3 + 1.5 * ddx0 / p2 - 30.0 * x1 / p4 + 8.0 * dx1 / p3 - 0.5 * ddx1 / p2; // derive d // double d = 0.5 * ddx0; coef_deriv_[2][0] = 0.0; coef_deriv_[2][1] = 0.0; coef_deriv_[2][2] = 0.5; coef_deriv_[2][3] = 0.0; coef_deriv_[2][4] = 0.0; coef_deriv_[2][5] = 0.0; coef_deriv_[2][6] = 0.0; // derive e // double e = dx0; coef_deriv_[1][0] = 0.0; coef_deriv_[1][1] = 1.0; coef_deriv_[1][2] = 0.0; coef_deriv_[1][3] = 0.0; coef_deriv_[1][4] = 0.0; coef_deriv_[1][5] = 0.0; coef_deriv_[1][6] = 0.0; // derive f // double f = x0; coef_deriv_[0][0] = 1.0; coef_deriv_[0][1] = 0.0; coef_deriv_[0][2] = 0.0; coef_deriv_[0][3] = 0.0; coef_deriv_[0][4] = 0.0; coef_deriv_[0][5] = 0.0; coef_deriv_[0][6] = 0.0; } QuinticSpiralPath::QuinticSpiralPath(const std::array<double, 3>& start, const std::array<double, 3>& end, const double delta_s) : QuinticSpiralPath(start[0], start[1], start[2], end[0], end[1], end[2], delta_s) {} double QuinticSpiralPath::DeriveTheta(const size_t param_index, const double r) const { double s = param_ * r; double s2 = s * s; double s3 = s2 * s; double s4 = s2 * s2; double s5 = s3 * s2; double derivative = coef_deriv_[5][param_index] * s5 + coef_deriv_[4][param_index] * s4 + coef_deriv_[3][param_index] * s3 + coef_deriv_[2][param_index] * s2 + coef_deriv_[1][param_index] * s + coef_deriv_[0][param_index]; if (param_index == DELTA_S) { derivative += coef_[5] * 5.0 * s4 * r + coef_[4] * 4.0 * s3 * r + coef_[3] * 3.0 * s2 * r + coef_[2] * 2.0 * s * r + coef_[1] * r; } return derivative; } double QuinticSpiralPath::DeriveKappaDerivative(const size_t param_index, const double r) const { double s = param_ * r; double s2 = s * s; double s3 = s2 * s; double s4 = s2 * s2; double derivative = 5.0 * coef_deriv_[5][param_index] * s4 + 4.0 * coef_deriv_[4][param_index] * s3 + 3.0 * coef_deriv_[3][param_index] * s2 + 2.0 * coef_deriv_[2][param_index] * s + coef_deriv_[1][param_index]; if (param_index == DELTA_S) { derivative += 5.0 * coef_[5] * 4.0 * s3 * r + 4.0 * coef_[4] * 3.0 * s2 * r + 3.0 * coef_[3] * 2.0 * s * r + 2.0 * coef_[2] * r; } return derivative; } double QuinticSpiralPath::DeriveDKappaDerivative(const size_t param_index, const double r) const { double s = param_ * r; double s2 = s * s; double s3 = s2 * s; double derivative = 20.0 * coef_deriv_[5][param_index] * s3 + 12.0 * coef_deriv_[4][param_index] * s2 + 6.0 * coef_deriv_[3][param_index] * s + 2.0 * coef_deriv_[2][param_index]; if (param_index == DELTA_S) { derivative += 20.0 * coef_[5] * 3.0 * s2 * r + 12.0 * coef_[4] * 2.0 * s * r + 6.0 * coef_[3] * r; } return derivative; } double QuinticSpiralPath::DeriveD2KappaDerivative(const size_t param_index, const double r) const { double s = param_ * r; double s2 = s * s; double derivative = 60.0 * coef_deriv_[5][param_index] * s2 + 24.0 * coef_deriv_[4][param_index] * s + 6.0 * coef_deriv_[3][param_index]; if (param_index == DELTA_S) { derivative += 60.0 * coef_[5] * 2.0 * s * r + 24.0 * coef_[4] * r; } return derivative; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/piecewise_jerk/piecewise_jerk_problem.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 <tuple> #include <utility> #include <vector> #include "osqp/osqp.h" namespace apollo { namespace planning { /* * @brief: * This class solve an optimization problem: * x * | * | P(s1, x1) P(s2, x2) * | P(s0, x0) ... P(s(k-1), x(k-1)) * |P(start) * | * |________________________________________________________ s * * we suppose s(k+1) - s(k) == s(k) - s(k-1) * * Given the x, x', x'' at P(start), The goal is to find x0, x1, ... x(k-1) * which makes the line P(start), P0, P(1) ... P(k-1) "smooth". */ class PiecewiseJerkProblem { public: PiecewiseJerkProblem(const size_t num_of_knots, const double delta_s, const std::array<double, 3>& x_init); virtual ~PiecewiseJerkProblem() = default; void set_x_bounds(std::vector<std::pair<double, double>> x_bounds); void set_x_bounds(const double x_lower_bound, const double x_upper_bound); void set_dx_bounds(std::vector<std::pair<double, double>> dx_bounds); void set_dx_bounds(const double dx_lower_bound, const double dx_upper_bound); void set_ddx_bounds(std::vector<std::pair<double, double>> ddx_bounds); void set_ddx_bounds(const double ddx_lower_bound, const double ddx_upper_bound); void set_dddx_bound(const double dddx_bound) { set_dddx_bound(-dddx_bound, dddx_bound); } void set_dddx_bound(const double dddx_lower_bound, const double dddx_upper_bound) { dddx_bound_.first = dddx_lower_bound; dddx_bound_.second = dddx_upper_bound; } void set_weight_x(const double weight_x) { weight_x_ = weight_x; } void set_weight_dx(const double weight_dx) { weight_dx_ = weight_dx; } void set_weight_ddx(const double weight_ddx) { weight_ddx_ = weight_ddx; } void set_weight_dddx(const double weight_dddx) { weight_dddx_ = weight_dddx; } void set_scale_factor(const std::array<double, 3>& scale_factor) { scale_factor_ = scale_factor; } /** * @brief Set the x ref object and the uniform x_ref weighting * * @param weight_x_ref: uniform weighting for x_ref * @param x_ref: objective value of x */ void set_x_ref(const double weight_x_ref, std::vector<double> x_ref); /** * @brief Set the x ref object and piecewised x_ref weightings * * @param weight_x_ref_vec: piecewised x_ref weightings * @param x_ref: objective value of x */ void set_x_ref(std::vector<double> weight_x_ref_vec, std::vector<double> x_ref); void set_end_state_ref(const std::array<double, 3>& weight_end_state, const std::array<double, 3>& end_state_ref); virtual bool Optimize(const int max_iter = 4000); const std::vector<double>& opt_x() const { return x_; } const std::vector<double>& opt_dx() const { return dx_; } const std::vector<double>& opt_ddx() const { return ddx_; } protected: // naming convention follows osqp solver. virtual void CalculateKernel(std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr) = 0; virtual void CalculateOffset(std::vector<c_float>* q) = 0; virtual void CalculateAffineConstraint(std::vector<c_float>* A_data, std::vector<c_int>* A_indices, std::vector<c_int>* A_indptr, std::vector<c_float>* lower_bounds, std::vector<c_float>* upper_bounds); virtual OSQPSettings* SolverDefaultSettings(); OSQPData* FormulateProblem(); void FreeData(OSQPData* data); template <typename T> T* CopyData(const std::vector<T>& vec) { T* data = new T[vec.size()]; memcpy(data, vec.data(), sizeof(T) * vec.size()); return data; } protected: size_t num_of_knots_ = 0; // output std::vector<double> x_; std::vector<double> dx_; std::vector<double> ddx_; std::array<double, 3> x_init_; std::array<double, 3> scale_factor_ = {{1.0, 1.0, 1.0}}; std::vector<std::pair<double, double>> x_bounds_; std::vector<std::pair<double, double>> dx_bounds_; std::vector<std::pair<double, double>> ddx_bounds_; std::pair<double, double> dddx_bound_; double weight_x_ = 0.0; double weight_dx_ = 0.0; double weight_ddx_ = 0.0; double weight_dddx_ = 0.0; double delta_s_ = 1.0; bool has_x_ref_ = false; double weight_x_ref_ = 0.0; std::vector<double> x_ref_; // un-uniformed weighting std::vector<double> weight_x_ref_vec_; bool has_end_state_ref_ = false; std::array<double, 3> weight_end_state_ = {{0.0, 0.0, 0.0}}; std::array<double, 3> end_state_ref_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/piecewise_jerk/piecewise_jerk_path_problem.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 <utility> #include <vector> #include "modules/planning/math/piecewise_jerk/piecewise_jerk_problem.h" namespace apollo { namespace planning { /* * @brief: * FEM stands for finite element method. * This class solve an optimization problem: * x * | * | P(s1, x1) P(s2, x2) * | P(s0, x0) ... P(s(k-1), x(k-1)) * |P(start) * | * |________________________________________________________ s * * we suppose s(k+1) - s(k) == s(k) - s(k-1) * * Given the x, x', x'' at P(start), The goal is to find x0, x1, ... x(k-1) * which makes the line P(start), P0, P(1) ... P(k-1) "smooth". */ class PiecewiseJerkPathProblem : public PiecewiseJerkProblem { public: PiecewiseJerkPathProblem(const size_t num_of_knots, const double delta_s, const std::array<double, 3>& x_init); virtual ~PiecewiseJerkPathProblem() = default; protected: void CalculateKernel(std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr) override; void CalculateOffset(std::vector<c_float>* q) override; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/piecewise_jerk/piecewise_jerk_problem.cc
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/math/piecewise_jerk/piecewise_jerk_problem.h" #include "cyber/common/log.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace { constexpr double kMaxVariableRange = 1.0e10; } // namespace PiecewiseJerkProblem::PiecewiseJerkProblem( const size_t num_of_knots, const double delta_s, const std::array<double, 3>& x_init) { CHECK_GE(num_of_knots, 2U); num_of_knots_ = num_of_knots; x_init_ = x_init; delta_s_ = delta_s; x_bounds_.resize(num_of_knots_, std::make_pair(-kMaxVariableRange, kMaxVariableRange)); dx_bounds_.resize(num_of_knots_, std::make_pair(-kMaxVariableRange, kMaxVariableRange)); ddx_bounds_.resize(num_of_knots_, std::make_pair(-kMaxVariableRange, kMaxVariableRange)); weight_x_ref_vec_ = std::vector<double>(num_of_knots_, 0.0); } OSQPData* PiecewiseJerkProblem::FormulateProblem() { // calculate kernel std::vector<c_float> P_data; std::vector<c_int> P_indices; std::vector<c_int> P_indptr; CalculateKernel(&P_data, &P_indices, &P_indptr); // calculate affine constraints std::vector<c_float> A_data; std::vector<c_int> A_indices; std::vector<c_int> A_indptr; std::vector<c_float> lower_bounds; std::vector<c_float> upper_bounds; CalculateAffineConstraint(&A_data, &A_indices, &A_indptr, &lower_bounds, &upper_bounds); // calculate offset std::vector<c_float> q; CalculateOffset(&q); OSQPData* data = reinterpret_cast<OSQPData*>(c_malloc(sizeof(OSQPData))); CHECK_EQ(lower_bounds.size(), upper_bounds.size()); size_t kernel_dim = 3 * num_of_knots_; size_t num_affine_constraint = lower_bounds.size(); data->n = kernel_dim; data->m = num_affine_constraint; data->P = csc_matrix(kernel_dim, kernel_dim, P_data.size(), CopyData(P_data), CopyData(P_indices), CopyData(P_indptr)); data->q = CopyData(q); data->A = csc_matrix(num_affine_constraint, kernel_dim, A_data.size(), CopyData(A_data), CopyData(A_indices), CopyData(A_indptr)); data->l = CopyData(lower_bounds); data->u = CopyData(upper_bounds); return data; } bool PiecewiseJerkProblem::Optimize(const int max_iter) { OSQPData* data = FormulateProblem(); OSQPSettings* settings = SolverDefaultSettings(); settings->max_iter = max_iter; OSQPWorkspace* osqp_work = nullptr; osqp_work = osqp_setup(data, settings); // osqp_setup(&osqp_work, data, settings); osqp_solve(osqp_work); auto status = osqp_work->info->status_val; if (status < 0 || (status != 1 && status != 2)) { AERROR << "failed optimization status:\t" << osqp_work->info->status; osqp_cleanup(osqp_work); FreeData(data); c_free(settings); return false; } else if (osqp_work->solution == nullptr) { AERROR << "The solution from OSQP is nullptr"; osqp_cleanup(osqp_work); FreeData(data); c_free(settings); return false; } // extract primal results x_.resize(num_of_knots_); dx_.resize(num_of_knots_); ddx_.resize(num_of_knots_); for (size_t i = 0; i < num_of_knots_; ++i) { x_.at(i) = osqp_work->solution->x[i] / scale_factor_[0]; dx_.at(i) = osqp_work->solution->x[i + num_of_knots_] / scale_factor_[1]; ddx_.at(i) = osqp_work->solution->x[i + 2 * num_of_knots_] / scale_factor_[2]; } // Cleanup osqp_cleanup(osqp_work); FreeData(data); c_free(settings); return true; } void PiecewiseJerkProblem::CalculateAffineConstraint( std::vector<c_float>* A_data, std::vector<c_int>* A_indices, std::vector<c_int>* A_indptr, std::vector<c_float>* lower_bounds, std::vector<c_float>* upper_bounds) { // 3N params bounds on x, x', x'' // 3(N-1) constraints on x, x', x'' // 3 constraints on x_init_ const int n = static_cast<int>(num_of_knots_); const int num_of_variables = 3 * n; const int num_of_constraints = num_of_variables + 3 * (n - 1) + 3; lower_bounds->resize(num_of_constraints); upper_bounds->resize(num_of_constraints); std::vector<std::vector<std::pair<c_int, c_float>>> variables( num_of_variables); int constraint_index = 0; // set x, x', x'' bounds for (int i = 0; i < num_of_variables; ++i) { if (i < n) { variables[i].emplace_back(constraint_index, 1.0); lower_bounds->at(constraint_index) = x_bounds_[i].first * scale_factor_[0]; upper_bounds->at(constraint_index) = x_bounds_[i].second * scale_factor_[0]; } else if (i < 2 * n) { variables[i].emplace_back(constraint_index, 1.0); lower_bounds->at(constraint_index) = dx_bounds_[i - n].first * scale_factor_[1]; upper_bounds->at(constraint_index) = dx_bounds_[i - n].second * scale_factor_[1]; } else { variables[i].emplace_back(constraint_index, 1.0); lower_bounds->at(constraint_index) = ddx_bounds_[i - 2 * n].first * scale_factor_[2]; upper_bounds->at(constraint_index) = ddx_bounds_[i - 2 * n].second * scale_factor_[2]; } ++constraint_index; } CHECK_EQ(constraint_index, num_of_variables); // x(i->i+1)''' = (x(i+1)'' - x(i)'') / delta_s for (int i = 0; i + 1 < n; ++i) { variables[2 * n + i].emplace_back(constraint_index, -1.0); variables[2 * n + i + 1].emplace_back(constraint_index, 1.0); lower_bounds->at(constraint_index) = dddx_bound_.first * delta_s_ * scale_factor_[2]; upper_bounds->at(constraint_index) = dddx_bound_.second * delta_s_ * scale_factor_[2]; ++constraint_index; } // x(i+1)' - x(i)' - 0.5 * delta_s * x(i)'' - 0.5 * delta_s * x(i+1)'' = 0 for (int i = 0; i + 1 < n; ++i) { variables[n + i].emplace_back(constraint_index, -1.0 * scale_factor_[2]); variables[n + i + 1].emplace_back(constraint_index, 1.0 * scale_factor_[2]); variables[2 * n + i].emplace_back(constraint_index, -0.5 * delta_s_ * scale_factor_[1]); variables[2 * n + i + 1].emplace_back(constraint_index, -0.5 * delta_s_ * scale_factor_[1]); lower_bounds->at(constraint_index) = 0.0; upper_bounds->at(constraint_index) = 0.0; ++constraint_index; } // x(i+1) - x(i) - delta_s * x(i)' // - 1/3 * delta_s^2 * x(i)'' - 1/6 * delta_s^2 * x(i+1)'' auto delta_s_sq_ = delta_s_ * delta_s_; for (int i = 0; i + 1 < n; ++i) { variables[i].emplace_back(constraint_index, -1.0 * scale_factor_[1] * scale_factor_[2]); variables[i + 1].emplace_back(constraint_index, 1.0 * scale_factor_[1] * scale_factor_[2]); variables[n + i].emplace_back( constraint_index, -delta_s_ * scale_factor_[0] * scale_factor_[2]); variables[2 * n + i].emplace_back( constraint_index, -delta_s_sq_ / 3.0 * scale_factor_[0] * scale_factor_[1]); variables[2 * n + i + 1].emplace_back( constraint_index, -delta_s_sq_ / 6.0 * scale_factor_[0] * scale_factor_[1]); lower_bounds->at(constraint_index) = 0.0; upper_bounds->at(constraint_index) = 0.0; ++constraint_index; } // constrain on x_init variables[0].emplace_back(constraint_index, 1.0); lower_bounds->at(constraint_index) = x_init_[0] * scale_factor_[0]; upper_bounds->at(constraint_index) = x_init_[0] * scale_factor_[0]; ++constraint_index; variables[n].emplace_back(constraint_index, 1.0); lower_bounds->at(constraint_index) = x_init_[1] * scale_factor_[1]; upper_bounds->at(constraint_index) = x_init_[1] * scale_factor_[1]; ++constraint_index; variables[2 * n].emplace_back(constraint_index, 1.0); lower_bounds->at(constraint_index) = x_init_[2] * scale_factor_[2]; upper_bounds->at(constraint_index) = x_init_[2] * scale_factor_[2]; ++constraint_index; CHECK_EQ(constraint_index, num_of_constraints); int ind_p = 0; for (int i = 0; i < num_of_variables; ++i) { A_indptr->push_back(ind_p); for (const auto& variable_nz : variables[i]) { // coefficient A_data->push_back(variable_nz.second); // constraint index A_indices->push_back(variable_nz.first); ++ind_p; } } // We indeed need this line because of // https://github.com/oxfordcontrol/osqp/blob/master/src/cs.c#L255 A_indptr->push_back(ind_p); } OSQPSettings* PiecewiseJerkProblem::SolverDefaultSettings() { // Define Solver default settings OSQPSettings* settings = reinterpret_cast<OSQPSettings*>(c_malloc(sizeof(OSQPSettings))); osqp_set_default_settings(settings); settings->polish = true; settings->verbose = FLAGS_enable_osqp_debug; settings->scaled_termination = true; return settings; } void PiecewiseJerkProblem::set_x_bounds( std::vector<std::pair<double, double>> x_bounds) { CHECK_EQ(x_bounds.size(), num_of_knots_); x_bounds_ = std::move(x_bounds); } void PiecewiseJerkProblem::set_dx_bounds( std::vector<std::pair<double, double>> dx_bounds) { CHECK_EQ(dx_bounds.size(), num_of_knots_); dx_bounds_ = std::move(dx_bounds); } void PiecewiseJerkProblem::set_ddx_bounds( std::vector<std::pair<double, double>> ddx_bounds) { CHECK_EQ(ddx_bounds.size(), num_of_knots_); ddx_bounds_ = std::move(ddx_bounds); } void PiecewiseJerkProblem::set_x_bounds(const double x_lower_bound, const double x_upper_bound) { for (auto& x : x_bounds_) { x.first = x_lower_bound; x.second = x_upper_bound; } } void PiecewiseJerkProblem::set_dx_bounds(const double dx_lower_bound, const double dx_upper_bound) { for (auto& x : dx_bounds_) { x.first = dx_lower_bound; x.second = dx_upper_bound; } } void PiecewiseJerkProblem::set_ddx_bounds(const double ddx_lower_bound, const double ddx_upper_bound) { for (auto& x : ddx_bounds_) { x.first = ddx_lower_bound; x.second = ddx_upper_bound; } } void PiecewiseJerkProblem::set_x_ref(const double weight_x_ref, std::vector<double> x_ref) { CHECK_EQ(x_ref.size(), num_of_knots_); weight_x_ref_ = weight_x_ref; // set uniform weighting weight_x_ref_vec_ = std::vector<double>(num_of_knots_, weight_x_ref); x_ref_ = std::move(x_ref); has_x_ref_ = true; } void PiecewiseJerkProblem::set_x_ref(std::vector<double> weight_x_ref_vec, std::vector<double> x_ref) { CHECK_EQ(x_ref.size(), num_of_knots_); CHECK_EQ(weight_x_ref_vec.size(), num_of_knots_); // set piecewise weighting weight_x_ref_vec_ = std::move(weight_x_ref_vec); x_ref_ = std::move(x_ref); has_x_ref_ = true; } void PiecewiseJerkProblem::set_end_state_ref( const std::array<double, 3>& weight_end_state, const std::array<double, 3>& end_state_ref) { weight_end_state_ = weight_end_state; end_state_ref_ = end_state_ref; has_end_state_ref_ = true; } void PiecewiseJerkProblem::FreeData(OSQPData* data) { delete[] data->q; delete[] data->l; delete[] data->u; delete[] data->P->i; delete[] data->P->p; delete[] data->P->x; delete[] data->A->i; delete[] data->A->p; delete[] data->A->x; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/piecewise_jerk/piecewise_jerk_speed_problem.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 <utility> #include <vector> #include "modules/planning/math/piecewise_jerk/piecewise_jerk_problem.h" namespace apollo { namespace planning { /* * @brief: * This class solve the path time optimization problem: * s * | * | P(t1, s1) P(t2, s2) * | P(t0, s0) ... P(t(k-1), s(k-1)) * |P(start) * | * |________________________________________________________ t * * we suppose t(k+1) - t(k) == t(k) - t(k-1) * * Given the s, s', s'' at P(start), The goal is to find t0, t1, ... t(k-1) * which makes the line P(start), P0, P(1) ... P(k-1) "smooth". */ class PiecewiseJerkSpeedProblem : public PiecewiseJerkProblem { public: PiecewiseJerkSpeedProblem(const size_t num_of_knots, const double delta_s, const std::array<double, 3>& x_init); virtual ~PiecewiseJerkSpeedProblem() = default; void set_dx_ref(const double weight_dx_ref, const double dx_ref); void set_penalty_dx(std::vector<double> penalty_dx); protected: // naming convention follows osqp solver. void CalculateKernel(std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr) override; void CalculateOffset(std::vector<c_float>* q) override; OSQPSettings* SolverDefaultSettings() override; bool has_dx_ref_ = false; double weight_dx_ref_ = 0.0; double dx_ref_ = 0.0; std::vector<double> penalty_dx_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/piecewise_jerk/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "piecewise_jerk_problem", srcs = ["piecewise_jerk_problem.cc"], hdrs = ["piecewise_jerk_problem.h"], copts = [ "-DMODULE_NAME=\\\"planning\\\"", ], deps = [ "//cyber", "//modules/planning/common:planning_gflags", "@osqp", ], ) cc_library( name = "piecewise_jerk_path_problem", srcs = ["piecewise_jerk_path_problem.cc"], hdrs = ["piecewise_jerk_path_problem.h"], deps = [ ":piecewise_jerk_problem", ], ) cc_library( name = "piecewise_jerk_speed_problem", srcs = ["piecewise_jerk_speed_problem.cc"], hdrs = ["piecewise_jerk_speed_problem.h"], deps = [ ":piecewise_jerk_problem", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/piecewise_jerk/piecewise_jerk_speed_problem.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/math/piecewise_jerk/piecewise_jerk_speed_problem.h" #include "cyber/common/log.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { PiecewiseJerkSpeedProblem::PiecewiseJerkSpeedProblem( const size_t num_of_knots, const double delta_s, const std::array<double, 3>& x_init) : PiecewiseJerkProblem(num_of_knots, delta_s, x_init) { penalty_dx_.resize(num_of_knots_, 0.0); } void PiecewiseJerkSpeedProblem::set_dx_ref(const double weight_dx_ref, const double dx_ref) { weight_dx_ref_ = weight_dx_ref; dx_ref_ = dx_ref; has_dx_ref_ = true; } void PiecewiseJerkSpeedProblem::set_penalty_dx(std::vector<double> penalty_dx) { CHECK_EQ(penalty_dx.size(), num_of_knots_); penalty_dx_ = std::move(penalty_dx); } void PiecewiseJerkSpeedProblem::CalculateKernel(std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr) { const int n = static_cast<int>(num_of_knots_); const int kNumParam = 3 * n; const int kNumValue = 4 * n - 1; std::vector<std::vector<std::pair<c_int, c_float>>> columns; columns.resize(kNumParam); int value_index = 0; // x(i)^2 * w_x_ref for (int i = 0; i < n - 1; ++i) { columns[i].emplace_back( i, weight_x_ref_ / (scale_factor_[0] * scale_factor_[0])); ++value_index; } // x(n-1)^2 * (w_x_ref + w_end_x) columns[n - 1].emplace_back(n - 1, (weight_x_ref_ + weight_end_state_[0]) / (scale_factor_[0] * scale_factor_[0])); ++value_index; // x(i)'^2 * (w_dx_ref + penalty_dx) for (int i = 0; i < n - 1; ++i) { columns[n + i].emplace_back(n + i, (weight_dx_ref_ + penalty_dx_[i]) / (scale_factor_[1] * scale_factor_[1])); ++value_index; } // x(n-1)'^2 * (w_dx_ref + penalty_dx + w_end_dx) columns[2 * n - 1].emplace_back( 2 * n - 1, (weight_dx_ref_ + penalty_dx_[n - 1] + weight_end_state_[1]) / (scale_factor_[1] * scale_factor_[1])); ++value_index; auto delta_s_square = delta_s_ * delta_s_; // x(i)''^2 * (w_ddx + 2 * w_dddx / delta_s^2) columns[2 * n].emplace_back(2 * n, (weight_ddx_ + weight_dddx_ / delta_s_square) / (scale_factor_[2] * scale_factor_[2])); ++value_index; for (int i = 1; i < n - 1; ++i) { columns[2 * n + i].emplace_back( 2 * n + i, (weight_ddx_ + 2.0 * weight_dddx_ / delta_s_square) / (scale_factor_[2] * scale_factor_[2])); ++value_index; } columns[3 * n - 1].emplace_back( 3 * n - 1, (weight_ddx_ + weight_dddx_ / delta_s_square + weight_end_state_[2]) / (scale_factor_[2] * scale_factor_[2])); ++value_index; // -2 * w_dddx / delta_s^2 * x(i)'' * x(i + 1)'' for (int i = 0; i < n - 1; ++i) { columns[2 * n + i].emplace_back(2 * n + i + 1, -2.0 * weight_dddx_ / delta_s_square / (scale_factor_[2] * scale_factor_[2])); ++value_index; } CHECK_EQ(value_index, kNumValue); int ind_p = 0; for (int i = 0; i < kNumParam; ++i) { P_indptr->push_back(ind_p); for (const auto& row_data_pair : columns[i]) { P_data->push_back(row_data_pair.second * 2.0); P_indices->push_back(row_data_pair.first); ++ind_p; } } P_indptr->push_back(ind_p); } void PiecewiseJerkSpeedProblem::CalculateOffset(std::vector<c_float>* q) { CHECK_NOTNULL(q); const int n = static_cast<int>(num_of_knots_); const int kNumParam = 3 * n; q->resize(kNumParam); for (int i = 0; i < n; ++i) { if (has_x_ref_) { q->at(i) += -2.0 * weight_x_ref_ * x_ref_[i] / scale_factor_[0]; } if (has_dx_ref_) { q->at(n + i) += -2.0 * weight_dx_ref_ * dx_ref_ / scale_factor_[1]; } } if (has_end_state_ref_) { q->at(n - 1) += -2.0 * weight_end_state_[0] * end_state_ref_[0] / scale_factor_[0]; q->at(2 * n - 1) += -2.0 * weight_end_state_[1] * end_state_ref_[1] / scale_factor_[1]; q->at(3 * n - 1) += -2.0 * weight_end_state_[2] * end_state_ref_[2] / scale_factor_[2]; } } OSQPSettings* PiecewiseJerkSpeedProblem::SolverDefaultSettings() { // Define Solver default settings OSQPSettings* settings = reinterpret_cast<OSQPSettings*>(c_malloc(sizeof(OSQPSettings))); osqp_set_default_settings(settings); settings->eps_abs = 1e-4; settings->eps_rel = 1e-4; settings->eps_prim_inf = 1e-5; settings->eps_dual_inf = 1e-5; settings->polish = true; settings->verbose = FLAGS_enable_osqp_debug; settings->scaled_termination = true; return settings; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/piecewise_jerk/piecewise_jerk_path_problem.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/math/piecewise_jerk/piecewise_jerk_path_problem.h" #include "cyber/common/log.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { PiecewiseJerkPathProblem::PiecewiseJerkPathProblem( const size_t num_of_knots, const double delta_s, const std::array<double, 3>& x_init) : PiecewiseJerkProblem(num_of_knots, delta_s, x_init) {} void PiecewiseJerkPathProblem::CalculateKernel(std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr) { const int n = static_cast<int>(num_of_knots_); const int num_of_variables = 3 * n; const int num_of_nonzeros = num_of_variables + (n - 1); std::vector<std::vector<std::pair<c_int, c_float>>> columns(num_of_variables); int value_index = 0; // x(i)^2 * (w_x + w_x_ref[i]), w_x_ref might be a uniform value for all x(i) // or piecewise values for different x(i) for (int i = 0; i < n - 1; ++i) { columns[i].emplace_back(i, (weight_x_ + weight_x_ref_vec_[i]) / (scale_factor_[0] * scale_factor_[0])); ++value_index; } // x(n-1)^2 * (w_x + w_x_ref[n-1] + w_end_x) columns[n - 1].emplace_back( n - 1, (weight_x_ + weight_x_ref_vec_[n - 1] + weight_end_state_[0]) / (scale_factor_[0] * scale_factor_[0])); ++value_index; // x(i)'^2 * w_dx for (int i = 0; i < n - 1; ++i) { columns[n + i].emplace_back( n + i, weight_dx_ / (scale_factor_[1] * scale_factor_[1])); ++value_index; } // x(n-1)'^2 * (w_dx + w_end_dx) columns[2 * n - 1].emplace_back(2 * n - 1, (weight_dx_ + weight_end_state_[1]) / (scale_factor_[1] * scale_factor_[1])); ++value_index; auto delta_s_square = delta_s_ * delta_s_; // x(i)''^2 * (w_ddx + 2 * w_dddx / delta_s^2) columns[2 * n].emplace_back(2 * n, (weight_ddx_ + weight_dddx_ / delta_s_square) / (scale_factor_[2] * scale_factor_[2])); ++value_index; for (int i = 1; i < n - 1; ++i) { columns[2 * n + i].emplace_back( 2 * n + i, (weight_ddx_ + 2.0 * weight_dddx_ / delta_s_square) / (scale_factor_[2] * scale_factor_[2])); ++value_index; } columns[3 * n - 1].emplace_back( 3 * n - 1, (weight_ddx_ + weight_dddx_ / delta_s_square + weight_end_state_[2]) / (scale_factor_[2] * scale_factor_[2])); ++value_index; // -2 * w_dddx / delta_s^2 * x(i)'' * x(i + 1)'' for (int i = 0; i < n - 1; ++i) { columns[2 * n + i].emplace_back(2 * n + i + 1, (-2.0 * weight_dddx_ / delta_s_square) / (scale_factor_[2] * scale_factor_[2])); ++value_index; } CHECK_EQ(value_index, num_of_nonzeros); int ind_p = 0; for (int i = 0; i < num_of_variables; ++i) { P_indptr->push_back(ind_p); for (const auto& row_data_pair : columns[i]) { P_data->push_back(row_data_pair.second * 2.0); P_indices->push_back(row_data_pair.first); ++ind_p; } } P_indptr->push_back(ind_p); } void PiecewiseJerkPathProblem::CalculateOffset(std::vector<c_float>* q) { CHECK_NOTNULL(q); const int n = static_cast<int>(num_of_knots_); const int kNumParam = 3 * n; q->resize(kNumParam, 0.0); if (has_x_ref_) { for (int i = 0; i < n; ++i) { q->at(i) += -2.0 * weight_x_ref_vec_.at(i) * x_ref_[i] / scale_factor_[0]; } } if (has_end_state_ref_) { q->at(n - 1) += -2.0 * weight_end_state_[0] * end_state_ref_[0] / scale_factor_[0]; q->at(2 * n - 1) += -2.0 * weight_end_state_[1] * end_state_ref_[1] / scale_factor_[1]; q->at(3 * n - 1) += -2.0 * weight_end_state_[2] * end_state_ref_[2] / scale_factor_[2]; } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/discretized_points_smoothing/fem_pos_deviation_osqp_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 **/ #pragma once #include <utility> #include <vector> #include "osqp/osqp.h" namespace apollo { namespace planning { class FemPosDeviationOsqpInterface { public: FemPosDeviationOsqpInterface() = default; virtual ~FemPosDeviationOsqpInterface() = default; void set_ref_points( const std::vector<std::pair<double, double>>& ref_points) { ref_points_ = ref_points; } void set_bounds_around_refs(const std::vector<double>& bounds_around_refs) { bounds_around_refs_ = bounds_around_refs; } void set_weight_fem_pos_deviation(const double weight_fem_pos_deviation) { weight_fem_pos_deviation_ = weight_fem_pos_deviation; } void set_weight_path_length(const double weight_path_length) { weight_path_length_ = weight_path_length; } void set_weight_ref_deviation(const double weight_ref_deviation) { weight_ref_deviation_ = weight_ref_deviation; } void set_max_iter(const int max_iter) { max_iter_ = max_iter; } void set_time_limit(const double time_limit) { time_limit_ = time_limit; } void set_verbose(const bool verbose) { verbose_ = verbose; } void set_scaled_termination(const bool scaled_termination) { scaled_termination_ = scaled_termination; } void set_warm_start(const bool warm_start) { warm_start_ = warm_start; } bool Solve(); const std::vector<double>& opt_x() const { return x_; } const std::vector<double>& opt_y() const { return y_; } private: void CalculateKernel(std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr); void CalculateOffset(std::vector<c_float>* q); void CalculateAffineConstraint(std::vector<c_float>* A_data, std::vector<c_int>* A_indices, std::vector<c_int>* A_indptr, std::vector<c_float>* lower_bounds, std::vector<c_float>* upper_bounds); void SetPrimalWarmStart(std::vector<c_float>* primal_warm_start); bool OptimizeWithOsqp( const size_t kernel_dim, const size_t num_affine_constraint, std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr, std::vector<c_float>* A_data, std::vector<c_int>* A_indices, std::vector<c_int>* A_indptr, std::vector<c_float>* lower_bounds, std::vector<c_float>* upper_bounds, std::vector<c_float>* q, std::vector<c_float>* primal_warm_start, OSQPData* data, OSQPWorkspace** work, OSQPSettings* settings); private: // Reference points and deviation bounds std::vector<std::pair<double, double>> ref_points_; std::vector<double> bounds_around_refs_; // Weights in optimization cost function double weight_fem_pos_deviation_ = 1.0e5; double weight_path_length_ = 1.0; double weight_ref_deviation_ = 1.0; // Settings of osqp int max_iter_ = 4000; double time_limit_ = 0.0; bool verbose_ = false; bool scaled_termination_ = true; bool warm_start_ = true; // Optimization problem definitions int num_of_points_ = 0; int num_of_variables_ = 0; int num_of_constraints_ = 0; // Optimized_result std::vector<double> x_; std::vector<double> y_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/discretized_points_smoothing/fem_pos_deviation_smoother.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/math/discretized_points_smoothing/fem_pos_deviation_smoother.h" #include <coin/IpIpoptApplication.hpp> #include <coin/IpSolveStatistics.hpp> #include "cyber/common/log.h" #include "modules/planning/math/discretized_points_smoothing/fem_pos_deviation_ipopt_interface.h" #include "modules/planning/math/discretized_points_smoothing/fem_pos_deviation_osqp_interface.h" #include "modules/planning/math/discretized_points_smoothing/fem_pos_deviation_sqp_osqp_interface.h" namespace apollo { namespace planning { FemPosDeviationSmoother::FemPosDeviationSmoother( const FemPosDeviationSmootherConfig& config) : config_(config) {} bool FemPosDeviationSmoother::Solve( const std::vector<std::pair<double, double>>& raw_point2d, const std::vector<double>& bounds, std::vector<double>* opt_x, std::vector<double>* opt_y) { if (config_.apply_curvature_constraint()) { if (config_.use_sqp()) { return SqpWithOsqp(raw_point2d, bounds, opt_x, opt_y); } else { return NlpWithIpopt(raw_point2d, bounds, opt_x, opt_y); } } else { return QpWithOsqp(raw_point2d, bounds, opt_x, opt_y); } return true; } bool FemPosDeviationSmoother::QpWithOsqp( const std::vector<std::pair<double, double>>& raw_point2d, const std::vector<double>& bounds, std::vector<double>* opt_x, std::vector<double>* opt_y) { if (opt_x == nullptr || opt_y == nullptr) { AERROR << "opt_x or opt_y is nullptr"; return false; } FemPosDeviationOsqpInterface solver; solver.set_weight_fem_pos_deviation(config_.weight_fem_pos_deviation()); solver.set_weight_path_length(config_.weight_path_length()); solver.set_weight_ref_deviation(config_.weight_ref_deviation()); solver.set_max_iter(config_.max_iter()); solver.set_time_limit(config_.time_limit()); solver.set_verbose(config_.verbose()); solver.set_scaled_termination(config_.scaled_termination()); solver.set_warm_start(config_.warm_start()); solver.set_ref_points(raw_point2d); solver.set_bounds_around_refs(bounds); if (!solver.Solve()) { return false; } *opt_x = solver.opt_x(); *opt_y = solver.opt_y(); return true; } bool FemPosDeviationSmoother::SqpWithOsqp( const std::vector<std::pair<double, double>>& raw_point2d, const std::vector<double>& bounds, std::vector<double>* opt_x, std::vector<double>* opt_y) { if (opt_x == nullptr || opt_y == nullptr) { AERROR << "opt_x or opt_y is nullptr"; return false; } FemPosDeviationSqpOsqpInterface solver; solver.set_weight_fem_pos_deviation(config_.weight_fem_pos_deviation()); solver.set_weight_path_length(config_.weight_path_length()); solver.set_weight_ref_deviation(config_.weight_ref_deviation()); solver.set_weight_curvature_constraint_slack_var( config_.weight_curvature_constraint_slack_var()); solver.set_curvature_constraint(config_.curvature_constraint()); solver.set_sqp_sub_max_iter(config_.sqp_sub_max_iter()); solver.set_sqp_ftol(config_.sqp_ftol()); solver.set_sqp_pen_max_iter(config_.sqp_pen_max_iter()); solver.set_sqp_ctol(config_.sqp_ctol()); solver.set_max_iter(config_.max_iter()); solver.set_time_limit(config_.time_limit()); solver.set_verbose(config_.verbose()); solver.set_scaled_termination(config_.scaled_termination()); solver.set_warm_start(config_.warm_start()); solver.set_ref_points(raw_point2d); solver.set_bounds_around_refs(bounds); if (!solver.Solve()) { return false; } std::vector<std::pair<double, double>> opt_xy = solver.opt_xy(); // TODO(Jinyun): unify output data container opt_x->resize(opt_xy.size()); opt_y->resize(opt_xy.size()); for (size_t i = 0; i < opt_xy.size(); ++i) { (*opt_x)[i] = opt_xy[i].first; (*opt_y)[i] = opt_xy[i].second; } return true; } bool FemPosDeviationSmoother::NlpWithIpopt( const std::vector<std::pair<double, double>>& raw_point2d, const std::vector<double>& bounds, std::vector<double>* opt_x, std::vector<double>* opt_y) { if (opt_x == nullptr || opt_y == nullptr) { AERROR << "opt_x or opt_y is nullptr"; return false; } FemPosDeviationIpoptInterface* smoother = new FemPosDeviationIpoptInterface(raw_point2d, bounds); smoother->set_weight_fem_pos_deviation(config_.weight_fem_pos_deviation()); smoother->set_weight_path_length(config_.weight_path_length()); smoother->set_weight_ref_deviation(config_.weight_ref_deviation()); smoother->set_weight_curvature_constraint_slack_var( config_.weight_curvature_constraint_slack_var()); smoother->set_curvature_constraint(config_.curvature_constraint()); Ipopt::SmartPtr<Ipopt::TNLP> problem = smoother; // Create an instance of the IpoptApplication Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory(); app->Options()->SetIntegerValue("print_level", static_cast<int>(config_.print_level())); app->Options()->SetIntegerValue( "max_iter", static_cast<int>(config_.max_num_of_iterations())); app->Options()->SetIntegerValue( "acceptable_iter", static_cast<int>(config_.acceptable_num_of_iterations())); app->Options()->SetNumericValue("tol", config_.tol()); app->Options()->SetNumericValue("acceptable_tol", config_.acceptable_tol()); Ipopt::ApplicationReturnStatus status = app->Initialize(); if (status != Ipopt::Solve_Succeeded) { AERROR << "*** Error during initialization!"; return false; } status = app->OptimizeTNLP(problem); 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!"; } else { AERROR << "Solver fails with return code: " << static_cast<int>(status); return false; } smoother->get_optimization_results(opt_x, opt_y); return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/discretized_points_smoothing/fem_pos_deviation_smoother.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 <utility> #include <vector> #include "modules/planning/proto/math/fem_pos_deviation_smoother_config.pb.h" namespace apollo { namespace planning { /* * @brief: * This class solve an optimization problem: * Y * | * | P(x1, y1) P(x2, y2) * | P(x0, y0) ... P(x(k-1), y(k-1)) * |P(start) * | * |________________________________________________________ X * * * Given an initial set of points from 0 to k-1, The goal is to find a set of * points which makes the line P(start), P0, P(1) ... P(k-1) "smooth". */ class FemPosDeviationSmoother { public: explicit FemPosDeviationSmoother(const FemPosDeviationSmootherConfig& config); bool Solve(const std::vector<std::pair<double, double>>& raw_point2d, const std::vector<double>& bounds, std::vector<double>* opt_x, std::vector<double>* opt_y); bool QpWithOsqp(const std::vector<std::pair<double, double>>& raw_point2d, const std::vector<double>& bounds, std::vector<double>* opt_x, std::vector<double>* opt_y); bool NlpWithIpopt(const std::vector<std::pair<double, double>>& raw_point2d, const std::vector<double>& bounds, std::vector<double>* opt_x, std::vector<double>* opt_y); bool SqpWithOsqp(const std::vector<std::pair<double, double>>& raw_point2d, const std::vector<double>& bounds, std::vector<double>* opt_x, std::vector<double>* opt_y); private: FemPosDeviationSmootherConfig config_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/discretized_points_smoothing/fem_pos_deviation_sqp_osqp_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 **/ #pragma once #include <utility> #include <vector> #include "osqp/osqp.h" namespace apollo { namespace planning { class FemPosDeviationSqpOsqpInterface { public: FemPosDeviationSqpOsqpInterface() = default; virtual ~FemPosDeviationSqpOsqpInterface() = default; void set_ref_points( const std::vector<std::pair<double, double>>& ref_points) { ref_points_ = ref_points; } void set_bounds_around_refs(const std::vector<double>& bounds_around_refs) { bounds_around_refs_ = bounds_around_refs; } void set_weight_fem_pos_deviation(const double weight_fem_pos_deviation) { weight_fem_pos_deviation_ = weight_fem_pos_deviation; } void set_weight_path_length(const double weight_path_length) { weight_path_length_ = weight_path_length; } void set_weight_ref_deviation(const double weight_ref_deviation) { weight_ref_deviation_ = weight_ref_deviation; } void set_weight_curvature_constraint_slack_var( const double weight_curvature_constraint_slack_var) { weight_curvature_constraint_slack_var_ = weight_curvature_constraint_slack_var; } void set_curvature_constraint(const double curvature_constraint) { curvature_constraint_ = curvature_constraint; } void set_max_iter(const int max_iter) { max_iter_ = max_iter; } void set_time_limit(const double time_limit) { time_limit_ = time_limit; } void set_verbose(const bool verbose) { verbose_ = verbose; } void set_scaled_termination(const bool scaled_termination) { scaled_termination_ = scaled_termination; } void set_warm_start(const bool warm_start) { warm_start_ = warm_start; } void set_sqp_pen_max_iter(const int sqp_pen_max_iter) { sqp_pen_max_iter_ = sqp_pen_max_iter; } void set_sqp_ftol(const double sqp_ftol) { sqp_ftol_ = sqp_ftol; } void set_sqp_sub_max_iter(const int sqp_sub_max_iter) { sqp_sub_max_iter_ = sqp_sub_max_iter; } void set_sqp_ctol(const double sqp_ctol) { sqp_ctol_ = sqp_ctol; } bool Solve(); const std::vector<std::pair<double, double>>& opt_xy() const { return opt_xy_; } private: void CalculateKernel(std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr); void CalculateOffset(std::vector<c_float>* q); std::vector<double> CalculateLinearizedFemPosParams( const std::vector<std::pair<double, double>>& points, const size_t index); void CalculateAffineConstraint( const std::vector<std::pair<double, double>>& points, std::vector<c_float>* A_data, std::vector<c_int>* A_indices, std::vector<c_int>* A_indptr, std::vector<c_float>* lower_bounds, std::vector<c_float>* upper_bounds); void SetPrimalWarmStart(const std::vector<std::pair<double, double>>& points, std::vector<c_float>* primal_warm_start); bool OptimizeWithOsqp(const std::vector<c_float>& primal_warm_start, OSQPWorkspace** work); double CalculateConstraintViolation( const std::vector<std::pair<double, double>>& points); private: // Init states and constraints std::vector<std::pair<double, double>> ref_points_; std::vector<double> bounds_around_refs_; double curvature_constraint_ = 0.2; // Weights in optimization cost function double weight_fem_pos_deviation_ = 1.0e5; double weight_path_length_ = 1.0; double weight_ref_deviation_ = 1.0; double weight_curvature_constraint_slack_var_ = 1.0e5; // Settings of osqp int max_iter_ = 4000; double time_limit_ = 0.0; bool verbose_ = false; bool scaled_termination_ = true; bool warm_start_ = true; // Settings of sqp int sqp_pen_max_iter_ = 100; double sqp_ftol_ = 1e-2; int sqp_sub_max_iter_ = 100; double sqp_ctol_ = 1e-2; // Optimization problem definitions int num_of_points_ = 0; int num_of_pos_variables_ = 0; int num_of_slack_variables_ = 0; int num_of_variables_ = 0; int num_of_variable_constraints_ = 0; int num_of_curvature_constraints_ = 0; int num_of_constraints_ = 0; // Optimized_result std::vector<std::pair<double, double>> opt_xy_; std::vector<double> slack_; double average_interval_length_ = 0.0; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/discretized_points_smoothing/cos_theta_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. *****************************************************************************/ #include "modules/planning/math/discretized_points_smoothing/cos_theta_ipopt_interface.h" #include <random> #include <coin/IpIpoptApplication.hpp> #include <coin/IpSolveStatistics.hpp> #include "cyber/common/log.h" namespace apollo { namespace planning { CosThetaIpoptInterface::CosThetaIpoptInterface( std::vector<std::pair<double, double>> points, std::vector<double> bounds) { CHECK_GT(points.size(), 1U); CHECK_GT(bounds.size(), 1U); bounds_ = std::move(bounds); ref_points_ = std::move(points); num_of_points_ = ref_points_.size(); } void CosThetaIpoptInterface::get_optimization_results( std::vector<double>* ptr_x, std::vector<double>* ptr_y) const { *ptr_x = opt_x_; *ptr_y = opt_y_; } bool CosThetaIpoptInterface::get_nlp_info(int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) { // number of variables n = static_cast<int>(num_of_points_ << 1); num_of_variables_ = n; // number of constraints m = static_cast<int>(num_of_points_ << 1); num_of_constraints_ = m; if (use_automatic_differentiation_) { generate_tapes(n, m, &nnz_jac_g, &nnz_h_lag); } else { // number of nonzero constraint jacobian. nnz_jac_g = static_cast<int>(num_of_points_ << 1); nnz_jac_g_ = nnz_jac_g; // number of nonzero hessian and lagrangian. nnz_h_lag = static_cast<int>(num_of_points_ * 11 - 12); nnz_h_lag_ = nnz_h_lag; // load hessian structure hessian_strcuture(); } index_style = IndexStyleEnum::C_STYLE; return true; } bool CosThetaIpoptInterface::get_bounds_info(int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) { CHECK_EQ(static_cast<size_t>(n), num_of_variables_); CHECK_EQ(static_cast<size_t>(m), num_of_constraints_); // variables // a. for x, y for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i << 1; // x x_l[index] = -1e20; x_u[index] = 1e20; // y x_l[index + 1] = -1e20; x_u[index + 1] = 1e20; } // constraints // positional deviation constraints for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i << 1; double x_lower = 0.0; double x_upper = 0.0; double y_lower = 0.0; double y_upper = 0.0; x_lower = ref_points_[i].first - bounds_[i]; x_upper = ref_points_[i].first + bounds_[i]; y_lower = ref_points_[i].second - bounds_[i]; y_upper = ref_points_[i].second + bounds_[i]; // x g_l[index] = x_lower; g_u[index] = x_upper; // y g_l[index + 1] = y_lower; g_u[index + 1] = y_upper; } return true; } bool CosThetaIpoptInterface::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(static_cast<size_t>(n), num_of_variables_); std::random_device rd; std::default_random_engine gen = std::default_random_engine(rd()); std::normal_distribution<> dis{0, 0.05}; for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i << 1; x[index] = ref_points_[i].first + dis(gen); x[index + 1] = ref_points_[i].second + dis(gen); } return true; } bool CosThetaIpoptInterface::eval_f(int n, const double* x, bool new_x, double& obj_value) { CHECK_EQ(static_cast<size_t>(n), num_of_variables_); if (use_automatic_differentiation_) { eval_obj(n, x, &obj_value); return true; } obj_value = 0.0; for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i << 1; obj_value += (x[index] - ref_points_[i].first) * (x[index] - ref_points_[i].first) + (x[index + 1] - ref_points_[i].second) * (x[index + 1] - ref_points_[i].second); } for (size_t i = 0; i < num_of_points_ - 2; i++) { size_t findex = i << 1; size_t mindex = findex + 2; size_t lindex = mindex + 2; obj_value -= weight_cos_included_angle_ * (((x[mindex] - x[findex]) * (x[lindex] - x[mindex])) + ((x[mindex + 1] - x[findex + 1]) * (x[lindex + 1] - x[mindex + 1]))) / std::sqrt((x[mindex] - x[findex]) * (x[mindex] - x[findex]) + (x[mindex + 1] - x[findex + 1]) * (x[mindex + 1] - x[findex + 1])) / std::sqrt((x[lindex] - x[mindex]) * (x[lindex] - x[mindex]) + (x[lindex + 1] - x[mindex + 1]) * (x[lindex + 1] - x[mindex + 1])); } return true; } bool CosThetaIpoptInterface::eval_grad_f(int n, const double* x, bool new_x, double* grad_f) { CHECK_EQ(static_cast<size_t>(n), num_of_variables_); if (use_automatic_differentiation_) { gradient(tag_f, n, x, grad_f); return true; } std::fill(grad_f, grad_f + n, 0.0); for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i << 1; grad_f[index] = x[index] * 2 - ref_points_[i].first * 2; grad_f[index + 1] = x[index + 1] * 2 - ref_points_[i].second * 2; } for (size_t i = 0; i < num_of_points_ - 2; ++i) { size_t index = i << 1; double q1 = (x[index] - x[index + 2]) * (x[index] - x[index + 2]) + (x[index + 1] - x[index + 3]) * (x[index + 1] - x[index + 3]); double q2 = (x[index + 2] - x[index + 4]) * (x[index + 2] - x[index + 4]) + (x[index + 3] - x[index + 5]) * (x[index + 3] - x[index + 5]); double q3 = ((2 * x[index] - 2 * x[index + 2]) * ((x[index] - x[index + 2]) * (x[index + 2] - x[index + 4]) + (x[index + 1] - x[index + 3]) * (x[index + 3] - x[index + 5]))); double q4 = ((2 * x[index + 1] - 2 * x[index + 3]) * ((x[index] - x[index + 2]) * (x[index + 2] - x[index + 4]) + (x[index + 1] - x[index + 3]) * (x[index + 3] - x[index + 5]))); double q5 = ((2 * x[index + 2] - 2 * x[index + 4]) * ((x[index] - x[index + 2]) * (x[index + 2] - x[index + 4]) + (x[index + 1] - x[index + 3]) * (x[index + 3] - x[index + 5]))); double q6 = ((2 * x[index + 3] - 2 * x[index + 5]) * ((x[index] - x[index + 2]) * (x[index + 2] - x[index + 4]) + (x[index + 1] - x[index + 3]) * (x[index + 3] - x[index + 5]))); double sqrt_q1 = std::sqrt(q1); double sqrt_q2 = std::sqrt(q2); grad_f[index] += -weight_cos_included_angle_ * ((x[index + 2] - x[index + 4]) / (sqrt_q1 * sqrt_q2) - q3 / (2 * q1 * sqrt_q1 * sqrt_q2)); grad_f[index + 1] += -weight_cos_included_angle_ * ((x[index + 3] - x[index + 5]) / (sqrt_q1 * sqrt_q2) - q4 / (2 * q1 * sqrt_q1 * sqrt_q2)); grad_f[index + 2] += -weight_cos_included_angle_ * ((x[index] - 2 * x[index + 2] + x[index + 4]) / (sqrt_q1 * sqrt_q2) + q3 / (2 * q1 * sqrt_q1 * sqrt_q2) - q5 / (2 * sqrt_q1 * q2 * sqrt_q2)); grad_f[index + 3] += -weight_cos_included_angle_ * ((x[index + 1] - 2 * x[index + 3] + x[index + 5]) / (sqrt_q1 * sqrt_q2) + q4 / (2 * q1 * sqrt_q1 * sqrt_q2) - q6 / (2 * sqrt_q1 * q2 * sqrt_q2)); grad_f[index + 4] += -weight_cos_included_angle_ * (q5 / (2 * sqrt_q1 * q2 * sqrt_q2) - (x[index] - x[index + 2]) / (sqrt_q1 * sqrt_q2)); grad_f[index + 5] += -weight_cos_included_angle_ * (q6 / (2 * sqrt_q1 * q2 * sqrt_q2) - (x[index + 1] - x[index + 3]) / (sqrt_q1 * sqrt_q2)); } return true; } bool CosThetaIpoptInterface::eval_g(int n, const double* x, bool new_x, int m, double* g) { CHECK_EQ(static_cast<size_t>(n), num_of_variables_); CHECK_EQ(static_cast<size_t>(m), num_of_constraints_); if (use_automatic_differentiation_) { eval_constraints(n, x, m, g); return true; } // fill in the positional deviation constraints for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i << 1; g[index] = x[index]; g[index + 1] = x[index + 1]; } return true; } bool CosThetaIpoptInterface::eval_jac_g(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { CHECK_EQ(static_cast<size_t>(n), num_of_variables_); CHECK_EQ(static_cast<size_t>(m), num_of_constraints_); if (use_automatic_differentiation_) { if (values == nullptr) { // return the structure of the jacobian for (int idx = 0; idx < nnz_jac_; idx++) { iRow[idx] = rind_g_[idx]; jCol[idx] = cind_g_[idx]; } } else { // return the values of the jacobian of the constraints // auto* rind_g = &rind_g_[0]; // auto* cind_g = &cind_g_[0]; // auto* jacval = &jacval_[0]; sparse_jac(tag_g, m, n, 1, x, &nnz_jac_, &rind_g_, &cind_g_, &jacval_, options_g_); for (int idx = 0; idx < nnz_jac_; idx++) { values[idx] = jacval_[idx]; } } return true; } if (values == nullptr) { // positional deviation constraints for (int i = 0; i < static_cast<int>(num_of_variables_); ++i) { iRow[i] = i; jCol[i] = i; } } else { std::fill(values, values + nnz_jac_g_, 0.0); // positional deviation constraints for (size_t i = 0; i < num_of_variables_; ++i) { values[i] = 1; } } return true; } bool CosThetaIpoptInterface::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 (use_automatic_differentiation_) { if (values == nullptr) { // return the structure. This is a symmetric matrix, fill the lower left // triangle only. for (int idx = 0; idx < nnz_L_; idx++) { iRow[idx] = rind_L_[idx]; jCol[idx] = cind_L_[idx]; } } else { // return the values. This is a symmetric matrix, fill the lower left // triangle only obj_lam_[0] = obj_factor; for (int idx = 0; idx < m; idx++) { obj_lam_[1 + idx] = lambda[idx]; } // auto* rind_L = &rind_L_[0]; // auto* cind_L = &cind_L_[0]; // auto* hessval = &hessval_[0]; set_param_vec(tag_L, m + 1, &obj_lam_[0]); sparse_hess(tag_L, n, 1, const_cast<double*>(x), &nnz_L_, &rind_L_, &cind_L_, &hessval_, options_L_); for (int idx = 0; idx < nnz_L_; idx++) { values[idx] = hessval_[idx]; } } return true; } if (values == nullptr) { int index = 0; for (int i = 0; i < 6; ++i) { for (int j = 0; j <= i; ++j) { iRow[index] = i; jCol[index] = j; index++; } } int shift = 0; for (int i = 6; i < static_cast<int>(num_of_variables_); ++i) { if (i % 2 == 0) { for (int j = 2 + shift; j <= 6 + shift; ++j) { iRow[index] = i; jCol[index] = j; index++; } } else { for (int j = 2 + shift; j <= 7 + shift; ++j) { iRow[index] = i; jCol[index] = j; index++; } shift += 2; } } CHECK_EQ(index, nele_hess); } else { std::fill(values, values + nele_hess, 0.0); // fill the included angle part of obj for (size_t i = 0; i < num_of_points_ - 2; ++i) { size_t topleft = i * 2; const double q5 = (2 * x[topleft] - 2 * x[topleft + 2]); const double q6 = (2 * x[topleft + 1] - 2 * x[topleft + 3]); const double q7 = (x[topleft] - 2 * x[topleft + 2] + x[topleft + 4]); const double q8 = (2 * x[topleft + 2] - 2 * x[topleft + 4]); const double q9 = (2 * x[topleft + 3] - 2 * x[topleft + 5]); const double q10 = (x[topleft + 1] - 2 * x[topleft + 3] + x[topleft + 5]); const double q11 = (x[topleft + 3] - x[topleft + 5]); const double q12 = (x[topleft] - x[topleft + 2]); const double q13 = (x[topleft + 2] - x[topleft + 4]); const double q14 = (x[topleft + 1] - x[topleft + 3]); const double q1 = q12 * q12 + q14 * q14; const double q2 = q13 * q13 + q11 * q11; const double q3 = (3 * q5 * q5 * (q12 * q13 + q14 * q11)); const double q4 = (q12 * q13 + q14 * q11); const double sqrt_q1 = std::sqrt(q1); const double q1_sqrt_q1 = q1 * sqrt_q1; const double sqrt_q2 = std::sqrt(q2); const double q2_sqrt_q2 = q2 * sqrt_q2; const double square_q1 = q1 * q1; const double square_q2 = q2 * q2; const double sqrt_q1q2 = sqrt_q1 * sqrt_q2; const double q1_sqrt_q1q2 = q1 * sqrt_q1q2; const double sqrt_q1_q2_sqrt_q2 = sqrt_q1 * q2_sqrt_q2; const double q1_sqrt_q1_q2_sqrt_q2 = q1_sqrt_q1 * q2_sqrt_q2; values[idx_map_[std::make_pair(topleft, topleft)]] += obj_factor * (-weight_cos_included_angle_) * (q3 / (4 * square_q1 * sqrt_q1q2) - q4 / q1_sqrt_q1q2 - (q5 * q13) / q1_sqrt_q1q2); values[idx_map_[std::make_pair(topleft + 1, topleft)]] += obj_factor * (-weight_cos_included_angle_) * ((3 * q5 * q6 * q4) / (4 * square_q1 * sqrt_q1q2) - (q6 * q13) / (2 * q1_sqrt_q1q2) - (q5 * q11) / (2 * q1_sqrt_q1q2)); values[idx_map_[std::make_pair(topleft + 2, topleft)]] += obj_factor * (-weight_cos_included_angle_) * (1 / sqrt_q1q2 + q4 / q1_sqrt_q1q2 - (q5 * q7) / (2 * q1_sqrt_q1q2) - q3 / (4 * square_q1 * sqrt_q1q2) + (q5 * q13) / (2 * q1_sqrt_q1q2) - (q8 * q13) / (2 * sqrt_q1_q2_sqrt_q2) + (q5 * q8 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 3, topleft)]] += obj_factor * (-weight_cos_included_angle_) * ((q6 * q13) / (2 * q1_sqrt_q1q2) - (q5 * q10) / (2 * q1_sqrt_q1q2) - (q9 * q13) / (2 * sqrt_q1_q2_sqrt_q2) - (3 * q5 * q6 * q4) / (4 * square_q1 * sqrt_q1q2) + (q5 * q9 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 4, topleft)]] += obj_factor * (-weight_cos_included_angle_) * ((q5 * q12) / (2 * q1_sqrt_q1q2) - 1 / sqrt_q1q2 + (q8 * q13) / (2 * sqrt_q1_q2_sqrt_q2) - (q5 * q8 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 5, topleft)]] += obj_factor * (-weight_cos_included_angle_) * ((q5 * q14) / (2 * q1_sqrt_q1q2) + (q9 * q13) / (2 * sqrt_q1_q2_sqrt_q2) - (q5 * q9 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 1, topleft + 1)]] += obj_factor * (-weight_cos_included_angle_) * ((3 * q6 * q6 * q4) / (4 * square_q1 * sqrt_q1q2) - q4 / q1_sqrt_q1q2 - (q6 * q11) / q1_sqrt_q1q2); values[idx_map_[std::make_pair(topleft + 2, topleft + 1)]] += obj_factor * (-weight_cos_included_angle_) * ((q5 * q11) / (2 * q1_sqrt_q1q2) - (q6 * q7) / (2 * q1_sqrt_q1q2) - (q8 * q11) / (2 * sqrt_q1_q2_sqrt_q2) - (3 * q5 * q6 * q4) / (4 * square_q1 * sqrt_q1q2) + (q8 * q6 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 3, topleft + 1)]] += obj_factor * (-weight_cos_included_angle_) * (1 / sqrt_q1q2 + q4 / q1_sqrt_q1q2 - (q6 * q10) / (2 * q1_sqrt_q1q2) - (3 * q6 * q6 * q4) / (4 * square_q1 * sqrt_q1q2) + (q6 * q11) / (2 * q1_sqrt_q1q2) - (q9 * q11) / (2 * sqrt_q1_q2_sqrt_q2) + (q6 * q9 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 4, topleft + 1)]] += obj_factor * (-weight_cos_included_angle_) * ((q6 * q12) / (2 * q1_sqrt_q1q2) + (q8 * q11) / (2 * sqrt_q1_q2_sqrt_q2) - (q8 * q6 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 5, topleft + 1)]] += obj_factor * (-weight_cos_included_angle_) * ((q6 * q14) / (2 * q1_sqrt_q1q2) - 1 / sqrt_q1q2 + (q9 * q11) / (2 * sqrt_q1_q2_sqrt_q2) - (q6 * q9 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 2, topleft + 2)]] += obj_factor * (-weight_cos_included_angle_) * ((q5 * q7) / q1_sqrt_q1q2 - q4 / (sqrt_q1_q2_sqrt_q2)-q4 / q1_sqrt_q1q2 - 2 / sqrt_q1q2 - (q8 * q7) / (sqrt_q1_q2_sqrt_q2) + q3 / (4 * square_q1 * sqrt_q1q2) + (3 * q8 * q8 * q4) / (4 * sqrt_q1 * square_q2 * sqrt_q2) - (q5 * q8 * q4) / (2 * q1_sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 3, topleft + 2)]] += obj_factor * (-weight_cos_included_angle_) * ((q6 * q7) / (2 * q1_sqrt_q1q2) - (q9 * q7) / (2 * sqrt_q1_q2_sqrt_q2) + (q5 * q10) / (2 * q1_sqrt_q1q2) - (q8 * q10) / (2 * sqrt_q1_q2_sqrt_q2) + (3 * q5 * q6 * q4) / (4 * square_q1 * sqrt_q1q2) - (q5 * q9 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2) - (q8 * q6 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2) + (3 * q8 * q9 * q4) / (4 * sqrt_q1 * square_q2 * sqrt_q2)); values[idx_map_[std::make_pair(topleft + 4, topleft + 2)]] += obj_factor * (-weight_cos_included_angle_) * (1 / sqrt_q1q2 + q4 / (sqrt_q1_q2_sqrt_q2) + (q8 * q7) / (2 * sqrt_q1_q2_sqrt_q2) - (3 * q8 * q8 * q4) / (4 * sqrt_q1 * square_q2 * sqrt_q2) - (q5 * q12) / (2 * q1_sqrt_q1q2) + (q8 * q12) / (2 * sqrt_q1_q2_sqrt_q2) + (q5 * q8 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 5, topleft + 2)]] += obj_factor * (-weight_cos_included_angle_) * ((q9 * q7) / (2 * sqrt_q1_q2_sqrt_q2) - (q5 * q14) / (2 * q1_sqrt_q1q2) + (q8 * q14) / (2 * sqrt_q1_q2_sqrt_q2) + (q5 * q9 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2) - (3 * q8 * q9 * q4) / (4 * sqrt_q1 * square_q2 * sqrt_q2)); values[idx_map_[std::make_pair(topleft + 3, topleft + 3)]] += obj_factor * (-weight_cos_included_angle_) * ((q6 * q10) / q1_sqrt_q1q2 - q4 / (sqrt_q1_q2_sqrt_q2)-q4 / q1_sqrt_q1q2 - 2 / sqrt_q1q2 - (q9 * q10) / (sqrt_q1_q2_sqrt_q2) + (3 * q6 * q6 * q4) / (4 * square_q1 * sqrt_q1q2) + (3 * q9 * q9 * q4) / (4 * sqrt_q1 * square_q2 * sqrt_q2) - (q6 * q9 * q4) / (2 * q1_sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 4, topleft + 3)]] += obj_factor * (-weight_cos_included_angle_) * ((q8 * q10) / (2 * sqrt_q1_q2_sqrt_q2) - (q6 * q12) / (2 * q1_sqrt_q1q2) + (q9 * q12) / (2 * sqrt_q1_q2_sqrt_q2) + (q8 * q6 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2) - (3 * q8 * q9 * q4) / (4 * sqrt_q1 * square_q2 * sqrt_q2)); values[idx_map_[std::make_pair(topleft + 5, topleft + 3)]] += obj_factor * (-weight_cos_included_angle_) * (1 / sqrt_q1q2 + q4 / (sqrt_q1_q2_sqrt_q2) + (q9 * q10) / (2 * sqrt_q1_q2_sqrt_q2) - (3 * q9 * q9 * q4) / (4 * sqrt_q1 * square_q2 * sqrt_q2) - (q6 * q14) / (2 * q1_sqrt_q1q2) + (q9 * q14) / (2 * sqrt_q1_q2_sqrt_q2) + (q6 * q9 * q4) / (4 * q1_sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 4, topleft + 4)]] += obj_factor * (-weight_cos_included_angle_) * ((3 * q8 * q8 * q4) / (4 * sqrt_q1 * square_q2 * sqrt_q2) - q4 / (sqrt_q1_q2_sqrt_q2) - (q8 * q12) / (sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 5, topleft + 4)]] += obj_factor * (-weight_cos_included_angle_) * ((3 * q8 * q9 * q4) / (4 * sqrt_q1 * square_q2 * sqrt_q2) - (q9 * q12) / (2 * sqrt_q1_q2_sqrt_q2) - (q8 * q14) / (2 * sqrt_q1_q2_sqrt_q2)); values[idx_map_[std::make_pair(topleft + 5, topleft + 5)]] += obj_factor * (-weight_cos_included_angle_) * ((3 * q9 * q9 * q4) / (4 * sqrt_q1 * square_q2 * sqrt_q2) - q4 / (sqrt_q1_q2_sqrt_q2) - (q9 * q14) / (sqrt_q1_q2_sqrt_q2)); } // fill the deviation part of obj for (size_t i = 0; i < num_of_variables_; ++i) { values[idx_map_[std::make_pair(i, i)]] += obj_factor * 2; } } return true; } void CosThetaIpoptInterface::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_y_.reserve(num_of_points_); for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i << 1; opt_x_.emplace_back(x[index]); opt_y_.emplace_back(x[index + 1]); } if (use_automatic_differentiation_) { free(rind_g_); free(cind_g_); free(rind_L_); free(cind_L_); free(jacval_); free(hessval_); } } void CosThetaIpoptInterface::set_automatic_differentiation_flag( const bool use_ad) { use_automatic_differentiation_ = use_ad; } void CosThetaIpoptInterface::set_weight_cos_included_angle( const double weight_cos_included_angle) { weight_cos_included_angle_ = weight_cos_included_angle; } void CosThetaIpoptInterface::set_weight_anchor_points( const double weight_anchor_points) { weight_anchor_points_ = weight_anchor_points; } void CosThetaIpoptInterface::set_weight_length(const double weight_length) { weight_length_ = weight_length; } void CosThetaIpoptInterface::hessian_strcuture() { size_t index = 0; for (size_t i = 0; i < 6; ++i) { for (size_t j = 0; j <= i; ++j) { idx_map_.insert(std::pair<std::pair<size_t, size_t>, size_t>( std::pair<size_t, size_t>(i, j), index)); index++; } } size_t shift = 0; for (size_t i = 6; i < num_of_variables_; ++i) { if (i % 2 == 0) { for (size_t j = 2 + shift; j <= 6 + shift; ++j) { idx_map_.insert(std::pair<std::pair<size_t, size_t>, size_t>( std::pair<size_t, size_t>(i, j), index)); index++; } } else { for (size_t j = 2 + shift; j <= 7 + shift; ++j) { idx_map_.insert(std::pair<std::pair<size_t, size_t>, size_t>( std::pair<size_t, size_t>(i, j), index)); index++; } shift += 2; } } } //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> bool CosThetaIpoptInterface::eval_obj(int n, const T* x, T* obj_value) { *obj_value = 0.0; for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i << 1; *obj_value += weight_anchor_points_ * ((x[index] - ref_points_[i].first) * (x[index] - ref_points_[i].first) + (x[index + 1] - ref_points_[i].second) * (x[index + 1] - ref_points_[i].second)); } for (size_t i = 0; i < num_of_points_ - 2; ++i) { size_t findex = i << 1; size_t mindex = findex + 2; size_t lindex = mindex + 2; *obj_value -= weight_cos_included_angle_ * (((x[mindex] - x[findex]) * (x[lindex] - x[mindex])) + ((x[mindex + 1] - x[findex + 1]) * (x[lindex + 1] - x[mindex + 1]))) / (sqrt((x[mindex] - x[findex]) * (x[mindex] - x[findex]) + (x[mindex + 1] - x[findex + 1]) * (x[mindex + 1] - x[findex + 1])) * sqrt((x[lindex] - x[mindex]) * (x[lindex] - x[mindex]) + (x[lindex + 1] - x[mindex + 1]) * (x[lindex + 1] - x[mindex + 1]))); } // Total length for (size_t i = 0; i < num_of_points_ - 1; ++i) { size_t findex = i << 1; size_t nindex = findex + 2; *obj_value += weight_length_ * ((x[findex] - x[nindex]) * (x[findex] - x[nindex]) + (x[findex + 1] - x[nindex + 1]) * (x[findex + 1] - x[nindex + 1])); } return true; } /** Template to compute contraints */ template <class T> bool CosThetaIpoptInterface::eval_constraints(int n, const T* x, int m, T* g) { // fill in the positional deviation constraints for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i << 1; g[index] = x[index]; g[index + 1] = x[index + 1]; } return true; } /** Method to generate the required tapes */ void CosThetaIpoptInterface::generate_tapes(int n, int m, int* nnz_jac_g, int* nnz_h_lag) { std::vector<double> xp(n, 0.0); std::vector<double> lamp(m, 0.0); std::vector<double> zl(m, 0.0); std::vector<double> zu(m, 0.0); std::vector<adouble> xa(n, 0.0); std::vector<adouble> g(m, 0.0); std::vector<double> lam(m, 0.0); double sig; adouble obj_value; double dummy = 0.0; obj_lam_.clear(); obj_lam_.resize(m + 1, 0.0); get_starting_point(n, 1, &xp[0], 0, &zl[0], &zu[0], m, 0, &lamp[0]); // Trace on Objectives trace_on(tag_f); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_obj(n, &xa[0], &obj_value); obj_value >>= dummy; trace_off(); // Trace on Jacobian trace_on(tag_g); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { g[idx] >>= dummy; } trace_off(); // Trace on Hessian trace_on(tag_L); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } for (int idx = 0; idx < m; idx++) { lam[idx] = 1.0; } sig = 1.0; eval_obj(n, &xa[0], &obj_value); obj_value *= mkparam(sig); eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { obj_value += g[idx] * mkparam(lam[idx]); } obj_value >>= dummy; trace_off(); // rind_g_.clear(); // cind_g_.clear(); // rind_L_.clear(); // cind_L_.clear(); rind_g_ = nullptr; cind_g_ = nullptr; rind_L_ = nullptr; cind_L_ = nullptr; options_g_[0] = 0; /* sparsity pattern by index domains (default) */ options_g_[1] = 0; /* safe mode (default) */ options_g_[2] = 0; options_g_[3] = 0; /* column compression (default) */ // jacval_.clear(); // hessval_.clear(); jacval_ = nullptr; hessval_ = nullptr; // auto* rind_g = &rind_g_[0]; // auto* cind_g = &cind_g_[0]; // auto* jacval = &jacval_[0]; // auto* rind_L = &rind_L_[0]; // auto* cind_L = &cind_L_[0]; // auto* hessval = &hessval_[0]; sparse_jac(tag_g, m, n, 0, &xp[0], &nnz_jac_, &rind_g_, &cind_g_, &jacval_, options_g_); *nnz_jac_g = nnz_jac_; options_L_[0] = 0; options_L_[1] = 1; sparse_hess(tag_L, n, 0, &xp[0], &nnz_L_, &rind_L_, &cind_L_, &hessval_, options_L_); *nnz_h_lag = nnz_L_; } //*************** end ADOL-C part *********************************** } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/discretized_points_smoothing/fem_pos_deviation_osqp_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 **/ #include "modules/planning/math/discretized_points_smoothing/fem_pos_deviation_osqp_interface.h" #include <limits> #include "cyber/common/log.h" namespace apollo { namespace planning { bool FemPosDeviationOsqpInterface::Solve() { // Sanity Check if (ref_points_.empty()) { AERROR << "reference points empty, solver early terminates"; return false; } if (ref_points_.size() != bounds_around_refs_.size()) { AERROR << "ref_points and bounds size not equal, solver early terminates"; return false; } if (ref_points_.size() < 3) { AERROR << "ref_points size smaller than 3, solver early terminates"; return false; } if (ref_points_.size() > std::numeric_limits<int>::max()) { AERROR << "ref_points size too large, solver early terminates"; return false; } // Calculate optimization states definitions num_of_points_ = static_cast<int>(ref_points_.size()); num_of_variables_ = num_of_points_ * 2; num_of_constraints_ = num_of_variables_; // Calculate kernel std::vector<c_float> P_data; std::vector<c_int> P_indices; std::vector<c_int> P_indptr; CalculateKernel(&P_data, &P_indices, &P_indptr); // Calculate affine constraints std::vector<c_float> A_data; std::vector<c_int> A_indices; std::vector<c_int> A_indptr; std::vector<c_float> lower_bounds; std::vector<c_float> upper_bounds; CalculateAffineConstraint(&A_data, &A_indices, &A_indptr, &lower_bounds, &upper_bounds); // Calculate offset std::vector<c_float> q; CalculateOffset(&q); // Set primal warm start std::vector<c_float> primal_warm_start; SetPrimalWarmStart(&primal_warm_start); OSQPData* data = reinterpret_cast<OSQPData*>(c_malloc(sizeof(OSQPData))); OSQPSettings* settings = reinterpret_cast<OSQPSettings*>(c_malloc(sizeof(OSQPSettings))); // Define Solver settings osqp_set_default_settings(settings); settings->max_iter = max_iter_; settings->time_limit = time_limit_; settings->verbose = verbose_; settings->scaled_termination = scaled_termination_; settings->warm_start = warm_start_; OSQPWorkspace* work = nullptr; bool res = OptimizeWithOsqp(num_of_variables_, lower_bounds.size(), &P_data, &P_indices, &P_indptr, &A_data, &A_indices, &A_indptr, &lower_bounds, &upper_bounds, &q, &primal_warm_start, data, &work, settings); if (res == false || work == nullptr || work->solution == nullptr) { AERROR << "Failed to find solution."; // Cleanup osqp_cleanup(work); c_free(data->A); c_free(data->P); c_free(data); c_free(settings); return false; } // Extract primal results x_.resize(num_of_points_); y_.resize(num_of_points_); for (int i = 0; i < num_of_points_; ++i) { int index = i * 2; x_.at(i) = work->solution->x[index]; y_.at(i) = work->solution->x[index + 1]; } // Cleanup osqp_cleanup(work); c_free(data->A); c_free(data->P); c_free(data); c_free(settings); return true; } void FemPosDeviationOsqpInterface::CalculateKernel( std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr) { CHECK_GT(num_of_variables_, 4); // Three quadratic penalties are involved: // 1. Penalty x on distance between middle point and point by finite element // estimate; // 2. Penalty y on path length; // 3. Penalty z on difference between points and reference points // General formulation of P matrix is as below(with 6 points as an example): // I is a two by two identity matrix, X, Y, Z represents x * I, y * I, z * I // 0 is a two by two zero matrix // |X+Y+Z, -2X-Y, X, 0, 0, 0 | // |0, 5X+2Y+Z, -4X-Y, X, 0, 0 | // |0, 0, 6X+2Y+Z, -4X-Y, X, 0 | // |0, 0, 0, 6X+2Y+Z, -4X-Y, X | // |0, 0, 0, 0, 5X+2Y+Z, -2X-Y| // |0, 0, 0, 0, 0, X+Y+Z| // Only upper triangle needs to be filled std::vector<std::vector<std::pair<c_int, c_float>>> columns; columns.resize(num_of_variables_); int col_num = 0; for (int col = 0; col < 2; ++col) { columns[col].emplace_back(col, weight_fem_pos_deviation_ + weight_path_length_ + weight_ref_deviation_); ++col_num; } for (int col = 2; col < 4; ++col) { columns[col].emplace_back( col - 2, -2.0 * weight_fem_pos_deviation_ - weight_path_length_); columns[col].emplace_back(col, 5.0 * weight_fem_pos_deviation_ + 2.0 * weight_path_length_ + weight_ref_deviation_); ++col_num; } int second_point_from_last_index = num_of_points_ - 2; for (int point_index = 2; point_index < second_point_from_last_index; ++point_index) { int col_index = point_index * 2; for (int col = 0; col < 2; ++col) { col_index += col; columns[col_index].emplace_back(col_index - 4, weight_fem_pos_deviation_); columns[col_index].emplace_back( col_index - 2, -4.0 * weight_fem_pos_deviation_ - weight_path_length_); columns[col_index].emplace_back( col_index, 6.0 * weight_fem_pos_deviation_ + 2.0 * weight_path_length_ + weight_ref_deviation_); ++col_num; } } int second_point_col_from_last_col = num_of_variables_ - 4; int last_point_col_from_last_col = num_of_variables_ - 2; for (int col = second_point_col_from_last_col; col < last_point_col_from_last_col; ++col) { columns[col].emplace_back(col - 4, weight_fem_pos_deviation_); columns[col].emplace_back( col - 2, -4.0 * weight_fem_pos_deviation_ - weight_path_length_); columns[col].emplace_back(col, 5.0 * weight_fem_pos_deviation_ + 2.0 * weight_path_length_ + weight_ref_deviation_); ++col_num; } for (int col = last_point_col_from_last_col; col < num_of_variables_; ++col) { columns[col].emplace_back(col - 4, weight_fem_pos_deviation_); columns[col].emplace_back( col - 2, -2.0 * weight_fem_pos_deviation_ - weight_path_length_); columns[col].emplace_back(col, weight_fem_pos_deviation_ + weight_path_length_ + weight_ref_deviation_); ++col_num; } CHECK_EQ(col_num, num_of_variables_); int ind_p = 0; for (int i = 0; i < col_num; ++i) { P_indptr->push_back(ind_p); for (const auto& row_data_pair : columns[i]) { // Rescale by 2.0 as the quadratic term in osqp default qp problem setup // is set as (1/2) * x' * P * x P_data->push_back(row_data_pair.second * 2.0); P_indices->push_back(row_data_pair.first); ++ind_p; } } P_indptr->push_back(ind_p); } void FemPosDeviationOsqpInterface::CalculateOffset(std::vector<c_float>* q) { for (int i = 0; i < num_of_points_; ++i) { const auto& ref_point_xy = ref_points_[i]; q->push_back(-2.0 * weight_ref_deviation_ * ref_point_xy.first); q->push_back(-2.0 * weight_ref_deviation_ * ref_point_xy.second); } } void FemPosDeviationOsqpInterface::CalculateAffineConstraint( std::vector<c_float>* A_data, std::vector<c_int>* A_indices, std::vector<c_int>* A_indptr, std::vector<c_float>* lower_bounds, std::vector<c_float>* upper_bounds) { int ind_A = 0; for (int i = 0; i < num_of_variables_; ++i) { A_data->push_back(1.0); A_indices->push_back(i); A_indptr->push_back(ind_A); ++ind_A; } A_indptr->push_back(ind_A); for (int i = 0; i < num_of_points_; ++i) { const auto& ref_point_xy = ref_points_[i]; upper_bounds->push_back(ref_point_xy.first + bounds_around_refs_[i]); upper_bounds->push_back(ref_point_xy.second + bounds_around_refs_[i]); lower_bounds->push_back(ref_point_xy.first - bounds_around_refs_[i]); lower_bounds->push_back(ref_point_xy.second - bounds_around_refs_[i]); } } void FemPosDeviationOsqpInterface::SetPrimalWarmStart( std::vector<c_float>* primal_warm_start) { CHECK_EQ(ref_points_.size(), static_cast<size_t>(num_of_points_)); for (const auto& ref_point_xy : ref_points_) { primal_warm_start->push_back(ref_point_xy.first); primal_warm_start->push_back(ref_point_xy.second); } } bool FemPosDeviationOsqpInterface::OptimizeWithOsqp( const size_t kernel_dim, const size_t num_affine_constraint, std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr, std::vector<c_float>* A_data, std::vector<c_int>* A_indices, std::vector<c_int>* A_indptr, std::vector<c_float>* lower_bounds, std::vector<c_float>* upper_bounds, std::vector<c_float>* q, std::vector<c_float>* primal_warm_start, OSQPData* data, OSQPWorkspace** work, OSQPSettings* settings) { CHECK_EQ(lower_bounds->size(), upper_bounds->size()); data->n = kernel_dim; data->m = num_affine_constraint; data->P = csc_matrix(data->n, data->n, P_data->size(), P_data->data(), P_indices->data(), P_indptr->data()); data->q = q->data(); data->A = csc_matrix(data->m, data->n, A_data->size(), A_data->data(), A_indices->data(), A_indptr->data()); data->l = lower_bounds->data(); data->u = upper_bounds->data(); *work = osqp_setup(data, settings); // osqp_setup(work, data, settings); osqp_warm_start_x(*work, primal_warm_start->data()); // Solve Problem osqp_solve(*work); auto status = (*work)->info->status_val; if (status < 0) { AERROR << "failed optimization status:\t" << (*work)->info->status; return false; } if (status != 1 && status != 2) { AERROR << "failed optimization status:\t" << (*work)->info->status; return false; } return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/discretized_points_smoothing/fem_pos_deviation_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. *****************************************************************************/ #pragma once #include <utility> #include <vector> #include <adolc/adolc.h> #include <adolc/adolc_sparse.h> #include <adolc/adouble.h> #include <coin/IpIpoptApplication.hpp> #include <coin/IpIpoptCalculatedQuantities.hpp> #include <coin/IpIpoptData.hpp> #include <coin/IpOrigIpoptNLP.hpp> #include <coin/IpSolveStatistics.hpp> #include <coin/IpTNLP.hpp> #include <coin/IpTNLPAdapter.hpp> #include <coin/IpTypes.hpp> #define tag_f 1 #define tag_g 2 #define tag_L 3 #define HPOFF 30 namespace apollo { namespace planning { class FemPosDeviationIpoptInterface : public Ipopt::TNLP { public: FemPosDeviationIpoptInterface(std::vector<std::pair<double, double>> points, std::vector<double> bounds); virtual ~FemPosDeviationIpoptInterface() = default; void set_weight_fem_pos_deviation(const double weight_fem_pos_deviation) { weight_fem_pos_deviation_ = weight_fem_pos_deviation; } void set_weight_path_length(const double weight_path_length) { weight_path_length_ = weight_path_length; } void set_weight_ref_deviation(const double weight_ref_deviation) { weight_ref_deviation_ = weight_ref_deviation; } void set_weight_curvature_constraint_slack_var( const double weight_curvature_constraint_slack_var) { weight_curvature_constraint_slack_var_ = weight_curvature_constraint_slack_var; } void set_curvature_constraint(const double curvature_constraint) { curvature_constraint_ = curvature_constraint; } void get_optimization_results(std::vector<double>* ptr_x, std::vector<double>* ptr_y) const; /** 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; //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> bool eval_obj(int n, const T* x, T* obj_value); /** Template to compute contraints */ template <class T> bool eval_constraints(int n, const T* x, int m, T* g); /** Method to generate the required tapes */ virtual void generate_tapes(int n, int m, int* nnz_jac_g, int* nnz_h_lag); //*************** end ADOL-C part *********************************** private: // Reference points and deviation bounds std::vector<std::pair<double, double>> ref_points_; std::vector<double> bounds_around_refs_; // Weights in optimization cost function double weight_fem_pos_deviation_ = 1.0e8; double weight_path_length_ = 1.0; double weight_ref_deviation_ = 1.0; double weight_curvature_constraint_slack_var_ = 1.0e2; double curvature_constraint_ = 0.2; size_t num_of_variables_ = 0; size_t num_of_constraints_ = 0; size_t nnz_jac_g_ = 0; size_t nnz_h_lag_ = 0; size_t num_of_points_ = 0; size_t num_of_slack_var_ = 0; size_t num_of_curvature_constr_ = 0; size_t num_of_slack_constr_ = 0; size_t slack_var_start_index_ = 0; size_t slack_var_end_index_ = 0; size_t curvature_constr_start_index_ = 0; size_t curvature_constr_end_index_ = 0; size_t slack_constr_start_index_ = 0; size_t slack_constr_end_index_ = 0; std::vector<double> opt_x_; std::vector<double> opt_y_; //*************** start ADOL-C part *********************************** /**@name Methods to block default compiler methods. */ FemPosDeviationIpoptInterface(const FemPosDeviationIpoptInterface&); FemPosDeviationIpoptInterface& operator=( const FemPosDeviationIpoptInterface&); std::vector<double> obj_lam_; //** variables for sparsity exploitation unsigned int* rind_g_; /* row indices */ unsigned int* cind_g_; /* column indices */ double* jacval_; /* values */ unsigned int* rind_L_; /* row indices */ unsigned int* cind_L_; /* column indices */ double* hessval_; /* values */ int nnz_jac_ = 0; int nnz_L_ = 0; int options_g_[4]; int options_L_[4]; //*************** end ADOL-C part *********************************** }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/discretized_points_smoothing/cos_theta_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. *****************************************************************************/ #pragma once #include <cstddef> #include <map> #include <utility> #include <vector> #include <adolc/adolc.h> #include <adolc/adolc_sparse.h> #include <adolc/adouble.h> #include <coin/IpIpoptApplication.hpp> #include <coin/IpIpoptCalculatedQuantities.hpp> #include <coin/IpIpoptData.hpp> #include <coin/IpOrigIpoptNLP.hpp> #include <coin/IpSolveStatistics.hpp> #include <coin/IpTNLP.hpp> #include <coin/IpTNLPAdapter.hpp> #include <coin/IpTypes.hpp> #define tag_f 1 #define tag_g 2 #define tag_L 3 #define HPOFF 30 namespace apollo { namespace planning { class CosThetaIpoptInterface : public Ipopt::TNLP { public: CosThetaIpoptInterface(std::vector<std::pair<double, double>> points, std::vector<double> bounds); virtual ~CosThetaIpoptInterface() = default; void set_weight_cos_included_angle(const double weight_cos_included_angle); void set_weight_anchor_points(const double weight_anchor_points); void set_weight_length(const double weight_length); void set_automatic_differentiation_flag(const bool use_ad); void get_optimization_results(std::vector<double>* ptr_x, std::vector<double>* ptr_y) const; /** 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; //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> bool eval_obj(int n, const T* x, T* obj_value); /** Template to compute contraints */ template <class T> bool eval_constraints(int n, const T* x, int m, T* g); /** Method to generate the required tapes */ virtual void generate_tapes(int n, int m, int* nnz_jac_g, int* nnz_h_lag); //*************** end ADOL-C part *********************************** private: std::vector<std::pair<double, double>> ref_points_; std::vector<double> bounds_; std::vector<double> opt_x_; std::vector<double> opt_y_; size_t num_of_variables_ = 0; size_t num_of_constraints_ = 0; size_t nnz_jac_g_ = 0; size_t nnz_h_lag_ = 0; size_t num_of_points_ = 0; std::map<std::pair<size_t, size_t>, size_t> idx_map_; void hessian_strcuture(); double weight_cos_included_angle_ = 0.0; double weight_anchor_points_ = 0.0; double weight_length_ = 0.0; //*************** start ADOL-C part *********************************** bool use_automatic_differentiation_ = false; /**@name Methods to block default compiler methods. */ CosThetaIpoptInterface(const CosThetaIpoptInterface&); CosThetaIpoptInterface& operator=(const CosThetaIpoptInterface&); std::vector<double> obj_lam_; // TODO(Jinyun): Not changed to std::vector yet, need further debug //** variables for sparsity exploitation // std::vector<unsigned int> rind_g_; /* row indices */ // std::vector<unsigned int> cind_g_; /* column indices */ // std::vector<double> jacval_; /* values */ // std::vector<unsigned int> rind_L_; /* row indices */ // std::vector<unsigned int> cind_L_; /* column indices */ // std::vector<double> hessval_; /* values */ //** variables for sparsity exploitation unsigned int* rind_g_; /* row indices */ unsigned int* cind_g_; /* column indices */ double* jacval_; /* values */ unsigned int* rind_L_; /* row indices */ unsigned int* cind_L_; /* column indices */ double* hessval_; /* values */ int nnz_jac_ = 0; int nnz_L_ = 0; int options_g_[4]; int options_L_[4]; //*************** end ADOL-C part *********************************** }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/discretized_points_smoothing/fem_pos_deviation_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 **/ #include "modules/planning/math/discretized_points_smoothing/fem_pos_deviation_ipopt_interface.h" #include "cyber/common/log.h" namespace apollo { namespace planning { FemPosDeviationIpoptInterface::FemPosDeviationIpoptInterface( std::vector<std::pair<double, double>> points, std::vector<double> bounds) { CHECK_GT(points.size(), 1U); CHECK_GT(bounds.size(), 1U); bounds_around_refs_ = std::move(bounds); ref_points_ = std::move(points); num_of_points_ = ref_points_.size(); } void FemPosDeviationIpoptInterface::get_optimization_results( std::vector<double>* ptr_x, std::vector<double>* ptr_y) const { *ptr_x = opt_x_; *ptr_y = opt_y_; } bool FemPosDeviationIpoptInterface::get_nlp_info(int& n, int& m, int& nnz_jac_g, int& nnz_h_lag, IndexStyleEnum& index_style) { CHECK_GT(num_of_points_, 3U); // Number of variables // Variables include 2D points and curvature constraints slack variable num_of_slack_var_ = num_of_points_ - 2; n = static_cast<int>(num_of_points_ * 2 + num_of_slack_var_); num_of_variables_ = n; // Number of constraints // Constraints includes positional constraints, curvature constraints and // slack variable constraints num_of_curvature_constr_ = num_of_points_ - 2; num_of_slack_constr_ = num_of_points_ - 2; m = static_cast<int>(num_of_points_ * 2 + num_of_curvature_constr_ + num_of_slack_constr_); num_of_constraints_ = m; // Indexes for variables and constraints, // Start index is actual first index and end index is one index after the // actual final index slack_var_start_index_ = num_of_points_ * 2; slack_var_end_index_ = slack_var_start_index_ + num_of_slack_var_; curvature_constr_start_index_ = num_of_points_ * 2; curvature_constr_end_index_ = curvature_constr_start_index_ + num_of_curvature_constr_; slack_constr_start_index_ = curvature_constr_end_index_; slack_constr_end_index_ = slack_constr_start_index_ + num_of_slack_constr_; generate_tapes(n, m, &nnz_jac_g, &nnz_h_lag); index_style = IndexStyleEnum::C_STYLE; return true; } bool FemPosDeviationIpoptInterface::get_bounds_info(int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) { CHECK_EQ(static_cast<size_t>(n), num_of_variables_); CHECK_EQ(static_cast<size_t>(m), num_of_constraints_); // variables // a. for x, y for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i * 2; // x x_l[index] = -1e20; x_u[index] = 1e20; // y x_l[index + 1] = -1e20; x_u[index + 1] = 1e20; } // b. for slack var for (size_t i = slack_var_start_index_; i < slack_var_end_index_; ++i) { x_l[i] = -1e20; x_u[i] = 1e20; } // constraints // a. positional deviation constraints for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i * 2; // x g_l[index] = ref_points_[i].first - bounds_around_refs_[i]; g_u[index] = ref_points_[i].first + bounds_around_refs_[i]; // y g_l[index + 1] = ref_points_[i].second - bounds_around_refs_[i]; g_u[index + 1] = ref_points_[i].second + bounds_around_refs_[i]; } // b. curvature constraints double ref_total_length = 0.0; auto pre_point = ref_points_.front(); for (size_t i = 1; i < num_of_points_; ++i) { auto cur_point = ref_points_[i]; double x_diff = cur_point.first - pre_point.first; double y_diff = cur_point.second - pre_point.second; ref_total_length += std::sqrt(x_diff * x_diff + y_diff * y_diff); pre_point = cur_point; } double average_delta_s = ref_total_length / static_cast<double>(num_of_points_ - 1); double curvature_constr_upper = average_delta_s * average_delta_s * curvature_constraint_; for (size_t i = curvature_constr_start_index_; i < curvature_constr_end_index_; ++i) { g_l[i] = -1e20; g_u[i] = curvature_constr_upper * curvature_constr_upper; } // c. slack var constraints for (size_t i = slack_constr_start_index_; i < slack_constr_end_index_; ++i) { g_l[i] = 0.0; g_u[i] = 1e20; } return true; } bool FemPosDeviationIpoptInterface::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(static_cast<size_t>(n), num_of_variables_); for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i * 2; x[index] = ref_points_[i].first; x[index + 1] = ref_points_[i].second; } for (size_t i = slack_var_start_index_; i < slack_var_end_index_; ++i) { x[i] = 0.0; } return true; } bool FemPosDeviationIpoptInterface::eval_f(int n, const double* x, bool new_x, double& obj_value) { CHECK_EQ(static_cast<size_t>(n), num_of_variables_); eval_obj(n, x, &obj_value); return true; } bool FemPosDeviationIpoptInterface::eval_grad_f(int n, const double* x, bool new_x, double* grad_f) { CHECK_EQ(static_cast<size_t>(n), num_of_variables_); gradient(tag_f, n, x, grad_f); return true; } bool FemPosDeviationIpoptInterface::eval_g(int n, const double* x, bool new_x, int m, double* g) { CHECK_EQ(static_cast<size_t>(n), num_of_variables_); CHECK_EQ(static_cast<size_t>(m), num_of_constraints_); eval_constraints(n, x, m, g); return true; } bool FemPosDeviationIpoptInterface::eval_jac_g(int n, const double* x, bool new_x, int m, int nele_jac, int* iRow, int* jCol, double* values) { CHECK_EQ(static_cast<size_t>(n), num_of_variables_); CHECK_EQ(static_cast<size_t>(m), num_of_constraints_); if (values == nullptr) { // return the structure of the jacobian for (int idx = 0; idx < nnz_jac_; idx++) { iRow[idx] = rind_g_[idx]; jCol[idx] = cind_g_[idx]; } } else { // return the values of the jacobian of the constraints sparse_jac(tag_g, m, n, 1, x, &nnz_jac_, &rind_g_, &cind_g_, &jacval_, options_g_); for (int idx = 0; idx < nnz_jac_; idx++) { values[idx] = jacval_[idx]; } } return true; } bool FemPosDeviationIpoptInterface::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) { // return the structure. This is a symmetric matrix, fill the lower left // triangle only. for (int idx = 0; idx < nnz_L_; idx++) { iRow[idx] = rind_L_[idx]; jCol[idx] = cind_L_[idx]; } } else { // return the values. This is a symmetric matrix, fill the lower left // triangle only obj_lam_[0] = obj_factor; for (int idx = 0; idx < m; idx++) { obj_lam_[1 + idx] = lambda[idx]; } set_param_vec(tag_L, m + 1, &obj_lam_[0]); sparse_hess(tag_L, n, 1, const_cast<double*>(x), &nnz_L_, &rind_L_, &cind_L_, &hessval_, options_L_); for (int idx = 0; idx < nnz_L_; idx++) { values[idx] = hessval_[idx]; } } return true; } void FemPosDeviationIpoptInterface::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_y_.reserve(num_of_points_); for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i * 2; opt_x_.emplace_back(x[index]); opt_y_.emplace_back(x[index + 1]); } free(rind_g_); free(cind_g_); free(rind_L_); free(cind_L_); free(jacval_); free(hessval_); } //*************** start ADOL-C part *********************************** /** Template to return the objective value */ template <class T> bool FemPosDeviationIpoptInterface::eval_obj(int n, const T* x, T* obj_value) { *obj_value = 0.0; // Distance to refs for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i * 2; *obj_value += weight_ref_deviation_ * ((x[index] - ref_points_[i].first) * (x[index] - ref_points_[i].first) + (x[index + 1] - ref_points_[i].second) * (x[index + 1] - ref_points_[i].second)); } // Fem_pos_deviation for (size_t i = 0; i + 2 < num_of_points_; ++i) { size_t findex = i * 2; size_t mindex = findex + 2; size_t lindex = mindex + 2; *obj_value += weight_fem_pos_deviation_ * (((x[findex] + x[lindex]) - 2.0 * x[mindex]) * ((x[findex] + x[lindex]) - 2.0 * x[mindex]) + ((x[findex + 1] + x[lindex + 1]) - 2.0 * x[mindex + 1]) * ((x[findex + 1] + x[lindex + 1]) - 2.0 * x[mindex + 1])); } // Total length for (size_t i = 0; i + 1 < num_of_points_; ++i) { size_t findex = i * 2; size_t nindex = findex + 2; *obj_value += weight_path_length_ * ((x[findex] - x[nindex]) * (x[findex] - x[nindex]) + (x[findex + 1] - x[nindex + 1]) * (x[findex + 1] - x[nindex + 1])); } // Slack variable minimization for (size_t i = slack_var_start_index_; i < slack_var_end_index_; ++i) { *obj_value += weight_curvature_constraint_slack_var_ * x[i]; } return true; } /** Template to compute contraints */ template <class T> bool FemPosDeviationIpoptInterface::eval_constraints(int n, const T* x, int m, T* g) { // a. positional deviation constraints for (size_t i = 0; i < num_of_points_; ++i) { size_t index = i * 2; g[index] = x[index]; g[index + 1] = x[index + 1]; } // b. curvature constraints for (size_t i = 0; i + 2 < num_of_points_; ++i) { size_t findex = i * 2; size_t mindex = findex + 2; size_t lindex = mindex + 2; g[curvature_constr_start_index_ + i] = (((x[findex] + x[lindex]) - 2.0 * x[mindex]) * ((x[findex] + x[lindex]) - 2.0 * x[mindex]) + ((x[findex + 1] + x[lindex + 1]) - 2.0 * x[mindex + 1]) * ((x[findex + 1] + x[lindex + 1]) - 2.0 * x[mindex + 1])) - x[slack_var_start_index_ + i]; } // c. slack var constraints size_t slack_var_index = 0; for (size_t i = slack_constr_start_index_; i < slack_constr_end_index_; ++i) { g[i] = x[slack_var_start_index_ + slack_var_index]; ++slack_var_index; } return true; } /** Method to generate the required tapes */ void FemPosDeviationIpoptInterface::generate_tapes(int n, int m, int* nnz_jac_g, int* nnz_h_lag) { std::vector<double> xp(n, 0.0); std::vector<double> lamp(m, 0.0); std::vector<double> zl(m, 0.0); std::vector<double> zu(m, 0.0); std::vector<adouble> xa(n, 0.0); std::vector<adouble> g(m, 0.0); std::vector<double> lam(m, 0.0); double sig; adouble obj_value; double dummy = 0.0; obj_lam_.clear(); obj_lam_.resize(m + 1, 0.0); get_starting_point(n, 1, &xp[0], 0, &zl[0], &zu[0], m, 0, &lamp[0]); // Trace on Objectives trace_on(tag_f); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_obj(n, &xa[0], &obj_value); obj_value >>= dummy; trace_off(); // Trace on Jacobian trace_on(tag_g); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { g[idx] >>= dummy; } trace_off(); // Trace on Hessian trace_on(tag_L); for (int idx = 0; idx < n; idx++) { xa[idx] <<= xp[idx]; } for (int idx = 0; idx < m; idx++) { lam[idx] = 1.0; } sig = 1.0; eval_obj(n, &xa[0], &obj_value); obj_value *= mkparam(sig); eval_constraints(n, &xa[0], m, &g[0]); for (int idx = 0; idx < m; idx++) { obj_value += g[idx] * mkparam(lam[idx]); } obj_value >>= dummy; trace_off(); rind_g_ = nullptr; cind_g_ = nullptr; rind_L_ = nullptr; cind_L_ = nullptr; options_g_[0] = 0; /* sparsity pattern by index domains (default) */ options_g_[1] = 0; /* safe mode (default) */ options_g_[2] = 0; options_g_[3] = 0; /* column compression (default) */ jacval_ = nullptr; hessval_ = nullptr; sparse_jac(tag_g, m, n, 0, &xp[0], &nnz_jac_, &rind_g_, &cind_g_, &jacval_, options_g_); *nnz_jac_g = nnz_jac_; options_L_[0] = 0; options_L_[1] = 1; sparse_hess(tag_L, n, 0, &xp[0], &nnz_L_, &rind_L_, &cind_L_, &hessval_, options_L_); *nnz_h_lag = nnz_L_; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/discretized_points_smoothing/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library") load("//tools:cpplint.bzl", "cpplint") package(default_visibility = ["//visibility:public"]) cc_library( name = "cos_theta_smoother", srcs = ["cos_theta_smoother.cc"], hdrs = ["cos_theta_smoother.h"], copts = [ "-DMODULE_NAME=\\\"planning\\\"", ], deps = [ ":cos_theta_ipopt_interface", "//cyber", "//modules/planning/proto/math:cos_theta_smoother_config_cc_proto", "@ipopt", ], ) cc_library( name = "cos_theta_ipopt_interface", srcs = ["cos_theta_ipopt_interface.cc"], hdrs = ["cos_theta_ipopt_interface.h"], copts = [ "-DMODULE_NAME=\\\"planning\\\"", ], deps = [ "//cyber", "@adolc", "@ipopt", ], ) cc_library( name = "fem_pos_deviation_smoother", srcs = ["fem_pos_deviation_smoother.cc"], hdrs = ["fem_pos_deviation_smoother.h"], copts = [ "-DMODULE_NAME=\\\"planning\\\"", ], deps = [ ":fem_pos_deviation_ipopt_interface", ":fem_pos_deviation_osqp_interface", ":fem_pos_deviation_sqp_osqp_interface", "//cyber", "//modules/planning/proto/math:fem_pos_deviation_smoother_config_cc_proto", "@ipopt", ], ) cc_library( name = "fem_pos_deviation_ipopt_interface", srcs = ["fem_pos_deviation_ipopt_interface.cc"], hdrs = ["fem_pos_deviation_ipopt_interface.h"], copts = [ "-DMODULE_NAME=\\\"planning\\\"", ], deps = [ "//cyber", "@adolc", "@ipopt", ], ) cc_library( name = "fem_pos_deviation_osqp_interface", srcs = ["fem_pos_deviation_osqp_interface.cc"], hdrs = ["fem_pos_deviation_osqp_interface.h"], copts = [ "-DMODULE_NAME=\\\"planning\\\"", ], deps = [ "//cyber", "@osqp", ], ) cc_library( name = "fem_pos_deviation_sqp_osqp_interface", srcs = ["fem_pos_deviation_sqp_osqp_interface.cc"], hdrs = ["fem_pos_deviation_sqp_osqp_interface.h"], copts = [ "-DMODULE_NAME=\\\"planning\\\"", ], deps = [ "//cyber", "@osqp", ], ) cpplint()
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/discretized_points_smoothing/cos_theta_smoother.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 <utility> #include <vector> #include "modules/planning/proto/math/cos_theta_smoother_config.pb.h" namespace apollo { namespace planning { class CosThetaSmoother { public: explicit CosThetaSmoother(const CosThetaSmootherConfig& config); bool Solve(const std::vector<std::pair<double, double>>& raw_point2d, const std::vector<double>& bounds, std::vector<double>* opt_x, std::vector<double>* opt_y); private: CosThetaSmootherConfig config_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/discretized_points_smoothing/fem_pos_deviation_sqp_osqp_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 **/ #include "modules/planning/math/discretized_points_smoothing/fem_pos_deviation_sqp_osqp_interface.h" #include <cmath> #include <limits> #include "cyber/common/log.h" namespace apollo { namespace planning { bool FemPosDeviationSqpOsqpInterface::Solve() { // Sanity Check if (ref_points_.empty()) { AERROR << "reference points empty, solver early terminates"; return false; } if (ref_points_.size() != bounds_around_refs_.size()) { AERROR << "ref_points and bounds size not equal, solver early terminates"; return false; } if (ref_points_.size() < 3) { AERROR << "ref_points size smaller than 3, solver early terminates"; return false; } if (ref_points_.size() > std::numeric_limits<int>::max()) { AERROR << "ref_points size too large, solver early terminates"; return false; } // Calculate optimization states definitions num_of_points_ = static_cast<int>(ref_points_.size()); num_of_pos_variables_ = num_of_points_ * 2; num_of_slack_variables_ = num_of_points_ - 2; num_of_variables_ = num_of_pos_variables_ + num_of_slack_variables_; num_of_variable_constraints_ = num_of_variables_; num_of_curvature_constraints_ = num_of_points_ - 2; num_of_constraints_ = num_of_variable_constraints_ + num_of_curvature_constraints_; // Set primal warm start std::vector<c_float> primal_warm_start; SetPrimalWarmStart(ref_points_, &primal_warm_start); // Calculate kernel std::vector<c_float> P_data; std::vector<c_int> P_indices; std::vector<c_int> P_indptr; CalculateKernel(&P_data, &P_indices, &P_indptr); // Calculate offset std::vector<c_float> q; CalculateOffset(&q); // Calculate affine constraints std::vector<c_float> A_data; std::vector<c_int> A_indices; std::vector<c_int> A_indptr; std::vector<c_float> lower_bounds; std::vector<c_float> upper_bounds; CalculateAffineConstraint(ref_points_, &A_data, &A_indices, &A_indptr, &lower_bounds, &upper_bounds); // Load matrices and vectors into OSQPData OSQPData* data = reinterpret_cast<OSQPData*>(c_malloc(sizeof(OSQPData))); data->n = num_of_variables_; data->m = num_of_constraints_; data->P = csc_matrix(data->n, data->n, P_data.size(), P_data.data(), P_indices.data(), P_indptr.data()); data->q = q.data(); data->A = csc_matrix(data->m, data->n, A_data.size(), A_data.data(), A_indices.data(), A_indptr.data()); data->l = lower_bounds.data(); data->u = upper_bounds.data(); // Define osqp solver settings OSQPSettings* settings = reinterpret_cast<OSQPSettings*>(c_malloc(sizeof(OSQPSettings))); osqp_set_default_settings(settings); settings->max_iter = max_iter_; settings->time_limit = time_limit_; settings->verbose = verbose_; settings->scaled_termination = scaled_termination_; settings->warm_start = warm_start_; settings->polish = true; settings->eps_abs = 1e-5; settings->eps_rel = 1e-5; settings->eps_prim_inf = 1e-5; settings->eps_dual_inf = 1e-5; // Define osqp workspace OSQPWorkspace* work = nullptr; // osqp_setup(&work, data, settings); work = osqp_setup(data, settings); // Initial solution bool initial_solve_res = OptimizeWithOsqp(primal_warm_start, &work); if (!initial_solve_res) { AERROR << "initial iteration solving fails"; osqp_cleanup(work); c_free(data->A); c_free(data->P); c_free(data); c_free(settings); return false; } // Sequential solution int pen_itr = 0; double ctol = 0.0; double original_slack_penalty = weight_curvature_constraint_slack_var_; double last_fvalue = work->info->obj_val; while (pen_itr < sqp_pen_max_iter_) { int sub_itr = 1; bool fconverged = false; while (sub_itr < sqp_sub_max_iter_) { SetPrimalWarmStart(opt_xy_, &primal_warm_start); CalculateOffset(&q); CalculateAffineConstraint(opt_xy_, &A_data, &A_indices, &A_indptr, &lower_bounds, &upper_bounds); osqp_update_lin_cost(work, q.data()); osqp_update_A(work, A_data.data(), OSQP_NULL, A_data.size()); osqp_update_bounds(work, lower_bounds.data(), upper_bounds.data()); bool iterative_solve_res = OptimizeWithOsqp(primal_warm_start, &work); if (!iterative_solve_res) { AERROR << "iteration at " << sub_itr << ", solving fails with max sub iter " << sqp_sub_max_iter_; weight_curvature_constraint_slack_var_ = original_slack_penalty; osqp_cleanup(work); c_free(data->A); c_free(data->P); c_free(data); c_free(settings); return false; } double cur_fvalue = work->info->obj_val; double ftol = std::abs((last_fvalue - cur_fvalue) / last_fvalue); if (ftol < sqp_ftol_) { ADEBUG << "merit function value converges at sub itr num " << sub_itr; ADEBUG << "merit function value converges to " << cur_fvalue << ", with ftol " << ftol << ", under max_ftol " << sqp_ftol_; fconverged = true; break; } last_fvalue = cur_fvalue; ++sub_itr; } if (!fconverged) { AERROR << "Max number of iteration reached"; weight_curvature_constraint_slack_var_ = original_slack_penalty; osqp_cleanup(work); c_free(data->A); c_free(data->P); c_free(data); c_free(settings); return false; } ctol = CalculateConstraintViolation(opt_xy_); ADEBUG << "ctol is " << ctol << ", at pen itr " << pen_itr; if (ctol < sqp_ctol_) { ADEBUG << "constraint satisfied at pen itr num " << pen_itr; ADEBUG << "constraint voilation value drops to " << ctol << ", under max_ctol " << sqp_ctol_; weight_curvature_constraint_slack_var_ = original_slack_penalty; osqp_cleanup(work); c_free(data->A); c_free(data->P); c_free(data); c_free(settings); return true; } weight_curvature_constraint_slack_var_ *= 10; ++pen_itr; } ADEBUG << "constraint not satisfied with total itr num " << pen_itr; ADEBUG << "constraint voilation value drops to " << ctol << ", higher than max_ctol " << sqp_ctol_; weight_curvature_constraint_slack_var_ = original_slack_penalty; osqp_cleanup(work); c_free(data->A); c_free(data->P); c_free(data); c_free(settings); return true; } void FemPosDeviationSqpOsqpInterface::CalculateKernel( std::vector<c_float>* P_data, std::vector<c_int>* P_indices, std::vector<c_int>* P_indptr) { CHECK_GT(num_of_points_, 2); // Three quadratic penalties are involved: // 1. Penalty x on distance between middle point and point by finite element // estimate; // 2. Penalty y on path length; // 3. Penalty z on difference between points and reference points // General formulation of P matrix is as below(with 6 points as an example): // I is a two by two identity matrix, X, Y, Z represents x * I, y * I, z * I // 0 is a two by two zero matrix // |X+Y+Z, -2X-Y, X, 0, 0, 0, ...| // |0, 5X+2Y+Z, -4X-Y, X, 0, 0, ...| // |0, 0, 6X+2Y+Z, -4X-Y, X, 0, ...| // |0, 0, 0, 6X+2Y+Z, -4X-Y, X ...| // |0, 0, 0, 0, 5X+2Y+Z, -2X-Y ...| // |0, 0, 0, 0, 0, X+Y+Z ...| // |0, 0, 0, 0, 0, 0, 0, ...| // |0, 0, 0, 0, 0, 0, 0, 0, ...| // |0, 0, 0, 0, 0, 0, 0, 0, 0, ...| // |0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...| // Only upper triangle needs to be filled std::vector<std::vector<std::pair<c_int, c_float>>> columns; columns.resize(num_of_variables_); int col_num = 0; for (int col = 0; col < 2; ++col) { columns[col].emplace_back(col, weight_fem_pos_deviation_ + weight_path_length_ + weight_ref_deviation_); ++col_num; } for (int col = 2; col < 4; ++col) { columns[col].emplace_back( col - 2, -2.0 * weight_fem_pos_deviation_ - weight_path_length_); columns[col].emplace_back(col, 5.0 * weight_fem_pos_deviation_ + 2.0 * weight_path_length_ + weight_ref_deviation_); ++col_num; } int second_point_from_last_index = num_of_points_ - 2; for (int point_index = 2; point_index < second_point_from_last_index; ++point_index) { int col_index = point_index * 2; for (int col = 0; col < 2; ++col) { col_index += col; columns[col_index].emplace_back(col_index - 4, weight_fem_pos_deviation_); columns[col_index].emplace_back( col_index - 2, -4.0 * weight_fem_pos_deviation_ - weight_path_length_); columns[col_index].emplace_back( col_index, 6.0 * weight_fem_pos_deviation_ + 2.0 * weight_path_length_ + weight_ref_deviation_); ++col_num; } } int second_point_col_from_last_col = num_of_pos_variables_ - 4; int last_point_col_from_last_col = num_of_pos_variables_ - 2; for (int col = second_point_col_from_last_col; col < last_point_col_from_last_col; ++col) { columns[col].emplace_back(col - 4, weight_fem_pos_deviation_); columns[col].emplace_back( col - 2, -4.0 * weight_fem_pos_deviation_ - weight_path_length_); columns[col].emplace_back(col, 5.0 * weight_fem_pos_deviation_ + 2.0 * weight_path_length_ + weight_ref_deviation_); ++col_num; } for (int col = last_point_col_from_last_col; col < num_of_pos_variables_; ++col) { columns[col].emplace_back(col - 4, weight_fem_pos_deviation_); columns[col].emplace_back( col - 2, -2.0 * weight_fem_pos_deviation_ - weight_path_length_); columns[col].emplace_back(col, weight_fem_pos_deviation_ + weight_path_length_ + weight_ref_deviation_); ++col_num; } CHECK_EQ(col_num, num_of_pos_variables_); int ind_p = 0; for (int i = 0; i < num_of_variables_; ++i) { P_indptr->push_back(ind_p); for (const auto& row_data_pair : columns[i]) { // Rescale by 2.0 as the quadratic term in osqp default qp problem setup // is set as (1/2) * x' * P * x P_data->push_back(row_data_pair.second * 2.0); P_indices->push_back(row_data_pair.first); ++ind_p; } } P_indptr->push_back(ind_p); } void FemPosDeviationSqpOsqpInterface::CalculateOffset(std::vector<c_float>* q) { q->resize(num_of_variables_); for (int i = 0; i < num_of_points_; ++i) { const auto& ref_point_xy = ref_points_[i]; (*q)[2 * i] = -2.0 * weight_ref_deviation_ * ref_point_xy.first; (*q)[2 * i + 1] = -2.0 * weight_ref_deviation_ * ref_point_xy.second; } for (int i = 0; i < num_of_slack_variables_; ++i) { (*q)[num_of_pos_variables_ + i] = weight_curvature_constraint_slack_var_; } } std::vector<double> FemPosDeviationSqpOsqpInterface::CalculateLinearizedFemPosParams( const std::vector<std::pair<double, double>>& points, const size_t index) { CHECK_GT(index, 0U); CHECK_LT(index, points.size() - 1); double x_f = points[index - 1].first; double x_m = points[index].first; double x_l = points[index + 1].first; double y_f = points[index - 1].second; double y_m = points[index].second; double y_l = points[index + 1].second; double linear_term_x_f = 2.0 * x_f - 4.0 * x_m + 2.0 * x_l; double linear_term_x_m = 8.0 * x_m - 4.0 * x_f - 4.0 * x_l; double linear_term_x_l = 2.0 * x_l - 4.0 * x_m + 2.0 * x_f; double linear_term_y_f = 2.0 * y_f - 4.0 * y_m + 2.0 * y_l; double linear_term_y_m = 8.0 * y_m - 4.0 * y_f - 4.0 * y_l; double linear_term_y_l = 2.0 * y_l - 4.0 * y_m + 2.0 * y_f; double linear_approx = (-2.0 * x_m + x_f + x_l) * (-2.0 * x_m + x_f + x_l) + (-2.0 * y_m + y_f + y_l) * (-2.0 * y_m + y_f + y_l) + -x_f * linear_term_x_f + -x_m * linear_term_x_m + -x_l * linear_term_x_l + -y_f * linear_term_y_f + -y_m * linear_term_y_m + -y_l * linear_term_y_l; return {linear_term_x_f, linear_term_y_f, linear_term_x_m, linear_term_y_m, linear_term_x_l, linear_term_y_l, linear_approx}; } void FemPosDeviationSqpOsqpInterface::CalculateAffineConstraint( const std::vector<std::pair<double, double>>& points, std::vector<c_float>* A_data, std::vector<c_int>* A_indices, std::vector<c_int>* A_indptr, std::vector<c_float>* lower_bounds, std::vector<c_float>* upper_bounds) { const double scale_factor = 1; std::vector<std::vector<double>> lin_cache; for (int i = 1; i < num_of_points_ - 1; ++i) { lin_cache.push_back(CalculateLinearizedFemPosParams(points, i)); } std::vector<std::vector<std::pair<c_int, c_float>>> columns; columns.resize(num_of_variables_); for (int i = 0; i < num_of_variables_; ++i) { columns[i].emplace_back(i, 1.0); } for (int i = num_of_pos_variables_; i < num_of_variables_; ++i) { columns[i].emplace_back(i + num_of_slack_variables_, -1.0 * scale_factor); } for (int i = 2; i < num_of_points_; ++i) { int index = 2 * i; columns[index].emplace_back(i - 2 + num_of_variables_, lin_cache[i - 2][4] * scale_factor); columns[index + 1].emplace_back(i - 2 + num_of_variables_, lin_cache[i - 2][5] * scale_factor); } for (int i = 1; i < num_of_points_ - 1; ++i) { int index = 2 * i; columns[index].emplace_back(i - 1 + num_of_variables_, lin_cache[i - 1][2] * scale_factor); columns[index + 1].emplace_back(i - 1 + num_of_variables_, lin_cache[i - 1][3] * scale_factor); } for (int i = 0; i < num_of_points_ - 2; ++i) { int index = 2 * i; columns[index].emplace_back(i + num_of_variables_, lin_cache[i][0] * scale_factor); columns[index + 1].emplace_back(i + num_of_variables_, lin_cache[i][1] * scale_factor); } int ind_a = 0; for (int i = 0; i < num_of_variables_; ++i) { A_indptr->push_back(ind_a); for (const auto& row_data_pair : columns[i]) { A_data->push_back(row_data_pair.second); A_indices->push_back(row_data_pair.first); ++ind_a; } } A_indptr->push_back(ind_a); lower_bounds->resize(num_of_constraints_); upper_bounds->resize(num_of_constraints_); for (int i = 0; i < num_of_points_; ++i) { const auto& ref_point_xy = ref_points_[i]; (*upper_bounds)[i * 2] = ref_point_xy.first + bounds_around_refs_[i]; (*upper_bounds)[i * 2 + 1] = ref_point_xy.second + bounds_around_refs_[i]; (*lower_bounds)[i * 2] = ref_point_xy.first - bounds_around_refs_[i]; (*lower_bounds)[i * 2 + 1] = ref_point_xy.second - bounds_around_refs_[i]; } for (int i = 0; i < num_of_slack_variables_; ++i) { (*upper_bounds)[num_of_pos_variables_ + i] = 1e20; (*lower_bounds)[num_of_pos_variables_ + i] = 0.0; } double interval_sqr = average_interval_length_ * average_interval_length_; double curvature_constraint_sqr = (interval_sqr * curvature_constraint_) * (interval_sqr * curvature_constraint_); for (int i = 0; i < num_of_curvature_constraints_; ++i) { (*upper_bounds)[num_of_variable_constraints_ + i] = (curvature_constraint_sqr - lin_cache[i][6]) * scale_factor; (*lower_bounds)[num_of_variable_constraints_ + i] = -1e20; } } void FemPosDeviationSqpOsqpInterface::SetPrimalWarmStart( const std::vector<std::pair<double, double>>& points, std::vector<c_float>* primal_warm_start) { CHECK_EQ(points.size(), static_cast<size_t>(num_of_points_)); CHECK_GT(points.size(), 1U); // Set states primal_warm_start->resize(num_of_variables_); for (int i = 0; i < num_of_points_; ++i) { (*primal_warm_start)[2 * i] = points[i].first; (*primal_warm_start)[2 * i + 1] = points[i].second; } slack_.resize(num_of_slack_variables_); for (int i = 0; i < num_of_slack_variables_; ++i) { (*primal_warm_start)[num_of_pos_variables_ + i] = slack_[i]; } // Calculate average interval length for curvature constraints double total_length = 0.0; auto pre_point = points.front(); for (int i = 1; i < num_of_points_; ++i) { const auto& cur_point = points[i]; total_length += std::sqrt((pre_point.first - cur_point.first) * (pre_point.first - cur_point.first) + (pre_point.second - cur_point.second) * (pre_point.second - cur_point.second)); pre_point = cur_point; } average_interval_length_ = total_length / (num_of_points_ - 1); } bool FemPosDeviationSqpOsqpInterface::OptimizeWithOsqp( const std::vector<c_float>& primal_warm_start, OSQPWorkspace** work) { osqp_warm_start_x(*work, primal_warm_start.data()); // Solve Problem osqp_solve(*work); auto status = (*work)->info->status_val; if (status < 0) { AERROR << "failed optimization status:\t" << (*work)->info->status; return false; } if (status != 1 && status != 2) { AERROR << "failed optimization status:\t" << (*work)->info->status; return false; } // Extract primal results opt_xy_.resize(num_of_points_); slack_.resize(num_of_slack_variables_); for (int i = 0; i < num_of_points_; ++i) { int index = i * 2; opt_xy_.at(i) = std::make_pair((*work)->solution->x[index], (*work)->solution->x[index + 1]); } for (int i = 0; i < num_of_slack_variables_; ++i) { slack_.at(i) = (*work)->solution->x[num_of_pos_variables_ + i]; } return true; } double FemPosDeviationSqpOsqpInterface::CalculateConstraintViolation( const std::vector<std::pair<double, double>>& points) { CHECK_GT(points.size(), 2U); double total_length = 0.0; auto pre_point = points.front(); for (int i = 1; i < num_of_points_; ++i) { const auto& cur_point = points[i]; total_length += std::sqrt((pre_point.first - cur_point.first) * (pre_point.first - cur_point.first) + (pre_point.second - cur_point.second) * (pre_point.second - cur_point.second)); pre_point = cur_point; } double average_interval_length = total_length / (num_of_points_ - 1); double interval_sqr = average_interval_length * average_interval_length; double curvature_constraint_sqr = (interval_sqr * curvature_constraint_) * (interval_sqr * curvature_constraint_); double max_cviolation = std::numeric_limits<double>::min(); for (size_t i = 1; i < points.size() - 1; ++i) { double x_f = points[i - 1].first; double x_m = points[i].first; double x_l = points[i + 1].first; double y_f = points[i - 1].second; double y_m = points[i].second; double y_l = points[i + 1].second; double cviolation = curvature_constraint_sqr - (-2.0 * x_m + x_f + x_l) * (-2.0 * x_m + x_f + x_l) + (-2.0 * y_m + y_f + y_l) * (-2.0 * y_m + y_f + y_l); max_cviolation = max_cviolation < cviolation ? cviolation : max_cviolation; } return max_cviolation; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/discretized_points_smoothing/cos_theta_smoother.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/math/discretized_points_smoothing/cos_theta_smoother.h" #include <coin/IpIpoptApplication.hpp> #include <coin/IpSolveStatistics.hpp> #include "cyber/common/log.h" #include "modules/planning/math/discretized_points_smoothing/cos_theta_ipopt_interface.h" namespace apollo { namespace planning { CosThetaSmoother::CosThetaSmoother(const CosThetaSmootherConfig& config) : config_(config) {} bool CosThetaSmoother::Solve( const std::vector<std::pair<double, double>>& raw_point2d, const std::vector<double>& bounds, std::vector<double>* opt_x, std::vector<double>* opt_y) { const double weight_cos_included_angle = config_.weight_cos_included_angle(); const double weight_anchor_points = config_.weight_anchor_points(); const double weight_length = config_.weight_length(); const size_t print_level = config_.print_level(); const size_t max_num_of_iterations = config_.max_num_of_iterations(); const size_t acceptable_num_of_iterations = config_.acceptable_num_of_iterations(); const double tol = config_.tol(); const double acceptable_tol = config_.acceptable_tol(); const bool use_automatic_differentiation = config_.ipopt_use_automatic_differentiation(); CosThetaIpoptInterface* smoother = new CosThetaIpoptInterface(raw_point2d, bounds); smoother->set_weight_cos_included_angle(weight_cos_included_angle); smoother->set_weight_anchor_points(weight_anchor_points); smoother->set_weight_length(weight_length); smoother->set_automatic_differentiation_flag(use_automatic_differentiation); Ipopt::SmartPtr<Ipopt::TNLP> problem = smoother; // Create an instance of the IpoptApplication Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory(); app->Options()->SetIntegerValue("print_level", static_cast<int>(print_level)); app->Options()->SetIntegerValue("max_iter", static_cast<int>(max_num_of_iterations)); app->Options()->SetIntegerValue( "acceptable_iter", static_cast<int>(acceptable_num_of_iterations)); app->Options()->SetNumericValue("tol", tol); app->Options()->SetNumericValue("acceptable_tol", acceptable_tol); Ipopt::ApplicationReturnStatus status = app->Initialize(); if (status != Ipopt::Solve_Succeeded) { AERROR << "*** Error during initialization!"; return false; } status = app->OptimizeTNLP(problem); 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!"; } else { AERROR << "Solver fails with return code: " << static_cast<int>(status); return false; } smoother->get_optimization_results(opt_x, opt_y); return true; } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_1d.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 : spline_1d.h * @brief: piecewise smoothing spline class * 1. Model description: piecewise smoothing spline are made by pieces of *smoothing splines * joint at knots; * 2. To guarantee smoothness, pieces value at knots should joint together *with * same value, derivative, and etc. Higher the order, More smoothness *the piecewise spline; **/ #pragma once #include <vector> #include "modules/planning/math/polynomial_xd.h" #include "modules/planning/math/smoothing_spline/affine_constraint.h" #include "modules/planning/math/smoothing_spline/spline_1d_seg.h" namespace apollo { namespace planning { class Spline1d { public: Spline1d(const std::vector<double>& x_knots, const uint32_t order); // @brief: given x return f(x) value, derivative, second order derivative and // the third order; double operator()(const double x) const; double Derivative(const double x) const; double SecondOrderDerivative(const double x) const; double ThirdOrderDerivative(const double x) const; // @brief: set spline segments bool SetSplineSegs(const Eigen::MatrixXd& param_matrix, const uint32_t order); const std::vector<double>& x_knots() const; uint32_t spline_order() const; const std::vector<Spline1dSeg>& splines() const; private: uint32_t FindIndex(const double x) const; private: std::vector<Spline1dSeg> splines_; std::vector<double> x_knots_; uint32_t spline_order_; }; } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_1d_constraint.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 : spline_1d_constraint.cc * @brief: wrapp up solver constraint interface with direct methods and preset *methods **/ #include "modules/planning/math/smoothing_spline/spline_1d_constraint.h" #include <limits> #include "cyber/common/log.h" namespace apollo { namespace planning { using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; Spline1dConstraint::Spline1dConstraint(const Spline1d& pss) : Spline1dConstraint(pss.x_knots(), pss.spline_order()) {} Spline1dConstraint::Spline1dConstraint(const std::vector<double>& x_knots, const uint32_t spline_order) : x_knots_(x_knots), spline_order_(spline_order) { inequality_constraint_.SetIsEquality(false); equality_constraint_.SetIsEquality(true); } bool Spline1dConstraint::AddInequalityConstraint( const Eigen::MatrixXd& constraint_matrix, const Eigen::MatrixXd& constraint_boundary) { return inequality_constraint_.AddConstraint(constraint_matrix, constraint_boundary); } bool Spline1dConstraint::AddEqualityConstraint( const Eigen::MatrixXd& constraint_matrix, const Eigen::MatrixXd& constraint_boundary) { return equality_constraint_.AddConstraint(constraint_matrix, constraint_boundary); } bool Spline1dConstraint::AddBoundary(const std::vector<double>& x_coord, const std::vector<double>& lower_bound, const std::vector<double>& upper_bound) { std::vector<double> filtered_lower_bound; std::vector<double> filtered_upper_bound; std::vector<double> filtered_lower_bound_x; std::vector<double> filtered_upper_bound_x; if (x_knots_.size() < 2) { return false; } if (!FilterConstraints(x_coord, lower_bound, upper_bound, &filtered_lower_bound_x, &filtered_lower_bound, &filtered_upper_bound_x, &filtered_upper_bound)) { return false; } // emplace affine constraints const uint32_t num_params = spline_order_ + 1; Eigen::MatrixXd inequality_constraint = Eigen::MatrixXd::Zero( filtered_upper_bound.size() + filtered_lower_bound.size(), (x_knots_.size() - 1) * num_params); Eigen::MatrixXd inequality_boundary = Eigen::MatrixXd::Zero( filtered_upper_bound.size() + filtered_lower_bound.size(), 1); for (uint32_t i = 0; i < filtered_lower_bound.size(); ++i) { uint32_t index = FindIndex(filtered_lower_bound_x[i]); const double corrected_x = filtered_lower_bound_x[i] - x_knots_[index]; double coef = 1.0; for (uint32_t j = 0; j < num_params; ++j) { inequality_constraint(i, j + index * num_params) = coef; coef *= corrected_x; } inequality_boundary(i, 0) = filtered_lower_bound[i]; } for (uint32_t i = 0; i < filtered_upper_bound.size(); ++i) { uint32_t index = FindIndex(filtered_upper_bound_x[i]); const double corrected_x = filtered_upper_bound_x[i] - x_knots_[index]; double coef = -1.0; for (uint32_t j = 0; j < num_params; ++j) { inequality_constraint(i + filtered_lower_bound.size(), j + index * num_params) = coef; coef *= corrected_x; } inequality_boundary(i + filtered_lower_bound.size(), 0) = -filtered_upper_bound[i]; } return inequality_constraint_.AddConstraint(inequality_constraint, inequality_boundary); } bool Spline1dConstraint::AddDerivativeBoundary( const std::vector<double>& x_coord, const std::vector<double>& lower_bound, const std::vector<double>& upper_bound) { std::vector<double> filtered_lower_bound; std::vector<double> filtered_upper_bound; std::vector<double> filtered_lower_bound_x; std::vector<double> filtered_upper_bound_x; if (x_knots_.size() < 2) { return false; } if (!FilterConstraints(x_coord, lower_bound, upper_bound, &filtered_lower_bound_x, &filtered_lower_bound, &filtered_upper_bound_x, &filtered_upper_bound)) { return false; } // emplace affine constraints const uint32_t num_params = spline_order_ + 1; Eigen::MatrixXd inequality_constraint = Eigen::MatrixXd::Zero( filtered_upper_bound.size() + filtered_lower_bound.size(), (x_knots_.size() - 1) * num_params); Eigen::MatrixXd inequality_boundary = Eigen::MatrixXd::Zero( filtered_upper_bound.size() + filtered_lower_bound.size(), 1); for (uint32_t i = 0; i < filtered_lower_bound.size(); ++i) { uint32_t index = FindIndex(filtered_lower_bound_x[i]); const double corrected_x = filtered_lower_bound_x[i] - x_knots_[index]; double coef = 1.0; for (uint32_t j = 1; j < num_params; ++j) { inequality_constraint(i, j + index * num_params) = coef * j; coef *= corrected_x; } inequality_boundary(i, 0) = filtered_lower_bound[i]; } for (uint32_t i = 0; i < filtered_upper_bound.size(); ++i) { uint32_t index = FindIndex(filtered_upper_bound_x[i]); const double corrected_x = filtered_upper_bound_x[i] - x_knots_[index]; double coef = -1.0; for (uint32_t j = 1; j < num_params; ++j) { inequality_constraint(i + filtered_lower_bound.size(), j + index * num_params) = coef * j; coef *= corrected_x; } inequality_boundary(i + filtered_lower_bound.size(), 0) = -filtered_upper_bound[i]; } return inequality_constraint_.AddConstraint(inequality_constraint, inequality_boundary); } bool Spline1dConstraint::AddSecondDerivativeBoundary( const std::vector<double>& x_coord, const std::vector<double>& lower_bound, const std::vector<double>& upper_bound) { std::vector<double> filtered_lower_bound; std::vector<double> filtered_upper_bound; std::vector<double> filtered_lower_bound_x; std::vector<double> filtered_upper_bound_x; if (x_knots_.size() < 2) { return false; } if (!FilterConstraints(x_coord, lower_bound, upper_bound, &filtered_lower_bound_x, &filtered_lower_bound, &filtered_upper_bound_x, &filtered_upper_bound)) { return false; } // emplace affine constraints const uint32_t num_params = spline_order_ + 1; Eigen::MatrixXd inequality_constraint = Eigen::MatrixXd::Zero( filtered_upper_bound.size() + filtered_lower_bound.size(), (x_knots_.size() - 1) * num_params); Eigen::MatrixXd inequality_boundary = Eigen::MatrixXd::Zero( filtered_upper_bound.size() + filtered_lower_bound.size(), 1); for (uint32_t i = 0; i < filtered_lower_bound.size(); ++i) { uint32_t index = FindIndex(filtered_lower_bound_x[i]); const double corrected_x = filtered_lower_bound_x[i] - x_knots_[index]; double coef = 1.0; for (uint32_t j = 2; j < num_params; ++j) { inequality_constraint(i, j + index * num_params) = coef * j * (j - 1); coef *= corrected_x; } inequality_boundary(i, 0) = filtered_lower_bound[i]; } for (uint32_t i = 0; i < filtered_upper_bound.size(); ++i) { uint32_t index = FindIndex(filtered_upper_bound_x[i]); const double corrected_x = filtered_upper_bound_x[i] - x_knots_[index]; double coef = -1.0; for (uint32_t j = 2; j < num_params; ++j) { inequality_constraint(i + filtered_lower_bound.size(), j + index * num_params) = coef * j * (j - 1); coef *= corrected_x; } inequality_boundary(i + filtered_lower_bound.size(), 0) = -filtered_upper_bound[i]; } return inequality_constraint_.AddConstraint(inequality_constraint, inequality_boundary); } bool Spline1dConstraint::AddThirdDerivativeBoundary( const std::vector<double>& x_coord, const std::vector<double>& lower_bound, const std::vector<double>& upper_bound) { std::vector<double> filtered_lower_bound; std::vector<double> filtered_upper_bound; std::vector<double> filtered_lower_bound_x; std::vector<double> filtered_upper_bound_x; if (!FilterConstraints(x_coord, lower_bound, upper_bound, &filtered_lower_bound_x, &filtered_lower_bound, &filtered_upper_bound_x, &filtered_upper_bound)) { AERROR << "Fail to filter constraints."; return false; } if (x_knots_.size() < 2) { AERROR << "x_konts size cannot be < 2."; return false; } // emplace affine constraints const uint32_t num_params = spline_order_ + 1; Eigen::MatrixXd inequality_constraint = Eigen::MatrixXd::Zero( filtered_upper_bound.size() + filtered_lower_bound.size(), (x_knots_.size() - 1) * num_params); Eigen::MatrixXd inequality_boundary = Eigen::MatrixXd::Zero( filtered_upper_bound.size() + filtered_lower_bound.size(), 1); for (uint32_t i = 0; i < filtered_lower_bound.size(); ++i) { uint32_t index = FindIndex(filtered_lower_bound_x[i]); const double corrected_x = filtered_lower_bound_x[i] - x_knots_[index]; double coef = 1.0; for (uint32_t j = 3; j < num_params; ++j) { inequality_constraint(i, j + index * num_params) = coef * j * (j - 1) * (j - 2); coef *= corrected_x; } inequality_boundary(i, 0) = filtered_lower_bound[i]; } for (uint32_t i = 0; i < filtered_upper_bound.size(); ++i) { uint32_t index = FindIndex(filtered_upper_bound_x[i]); const double corrected_x = filtered_upper_bound_x[i] - x_knots_[index]; double coef = -1.0; for (uint32_t j = 3; j < num_params; ++j) { inequality_constraint(i + filtered_lower_bound.size(), j + index * num_params) = coef * j * (j - 1) * (j - 2); coef *= corrected_x; } inequality_boundary(i + filtered_lower_bound.size(), 0) = -filtered_upper_bound[i]; } return inequality_constraint_.AddConstraint(inequality_constraint, inequality_boundary); } bool Spline1dConstraint::AddPointConstraint(const double x, const double fx) { uint32_t index = FindIndex(x); std::vector<double> power_x; const uint32_t num_params = spline_order_ + 1; GeneratePowerX(x - x_knots_[index], num_params, &power_x); Eigen::MatrixXd equality_constraint = Eigen::MatrixXd::Zero(1, (x_knots_.size() - 1) * num_params); uint32_t index_offset = index * num_params; for (uint32_t i = 0; i < num_params; ++i) { equality_constraint(0, index_offset + i) = power_x[i]; } Eigen::MatrixXd equality_boundary(1, 1); equality_boundary(0, 0) = fx; return AddEqualityConstraint(equality_constraint, equality_boundary); } bool Spline1dConstraint::AddConstraintInRange(AddConstraintInRangeFunc func, const double x, const double val, const double range) { if (range < 0.0) { return false; } std::vector<double> x_vec; x_vec.push_back(x); std::vector<double> lower_bound; std::vector<double> upper_bound; lower_bound.push_back(val - range); upper_bound.push_back(val + range); return func(x_vec, lower_bound, upper_bound); } bool Spline1dConstraint::AddPointConstraintInRange(const double x, const double fx, const double range) { return AddConstraintInRange( std::bind(&Spline1dConstraint::AddBoundary, this, _1, _2, _3), x, fx, range); } bool Spline1dConstraint::AddPointDerivativeConstraint(const double x, const double dfx) { uint32_t index = FindIndex(x); std::vector<double> power_x; const uint32_t num_params = spline_order_ + 1; GeneratePowerX(x - x_knots_[index], num_params, &power_x); Eigen::MatrixXd equality_constraint = Eigen::MatrixXd::Zero(1, (x_knots_.size() - 1) * num_params); uint32_t index_offset = index * num_params; for (uint32_t i = 1; i < num_params; ++i) { equality_constraint(0, index_offset + i) = power_x[i - 1] * i; } Eigen::MatrixXd equality_boundary(1, 1); equality_boundary(0, 0) = dfx; return AddEqualityConstraint(equality_constraint, equality_boundary); } bool Spline1dConstraint::AddPointDerivativeConstraintInRange( const double x, const double dfx, const double range) { return AddConstraintInRange( std::bind(&Spline1dConstraint::AddDerivativeBoundary, this, _1, _2, _3), x, dfx, range); } bool Spline1dConstraint::AddPointSecondDerivativeConstraint(const double x, const double ddfx) { uint32_t index = FindIndex(x); std::vector<double> power_x; const uint32_t num_params = spline_order_ + 1; GeneratePowerX(x - x_knots_[index], num_params, &power_x); Eigen::MatrixXd equality_constraint = Eigen::MatrixXd::Zero(1, (x_knots_.size() - 1) * num_params); uint32_t index_offset = index * num_params; for (uint32_t i = 2; i < num_params; ++i) { equality_constraint(0, index_offset + i) = power_x[i - 2] * i * (i - 1); } Eigen::MatrixXd equality_boundary(1, 1); equality_boundary(0, 0) = ddfx; return AddEqualityConstraint(equality_constraint, equality_boundary); } bool Spline1dConstraint::AddPointSecondDerivativeConstraintInRange( const double x, const double ddfx, const double range) { return AddConstraintInRange( std::bind(&Spline1dConstraint::AddSecondDerivativeBoundary, this, _1, _2, _3), x, ddfx, range); } bool Spline1dConstraint::AddPointThirdDerivativeConstraint(const double x, const double dddfx) { uint32_t index = FindIndex(x); std::vector<double> power_x; const uint32_t num_params = spline_order_ + 1; GeneratePowerX(x - x_knots_[index], num_params, &power_x); Eigen::MatrixXd equality_constraint = Eigen::MatrixXd::Zero(1, (x_knots_.size() - 1) * num_params); uint32_t index_offset = index * num_params; for (uint32_t i = 3; i < num_params; ++i) { equality_constraint(0, index_offset + i) = power_x[i - 3] * i * (i - 1) * (i - 2); } Eigen::MatrixXd equality_boundary(1, 1); equality_boundary(0, 0) = dddfx; return AddEqualityConstraint(equality_constraint, equality_boundary); } bool Spline1dConstraint::AddPointThirdDerivativeConstraintInRange( const double x, const double dddfx, const double range) { return AddConstraintInRange( std::bind(&Spline1dConstraint::AddSecondDerivativeBoundary, this, _1, _2, _3), x, dddfx, range); } bool Spline1dConstraint::AddSmoothConstraint() { if (x_knots_.size() < 3) { return false; } const uint32_t num_params = spline_order_ + 1; Eigen::MatrixXd equality_constraint = Eigen::MatrixXd::Zero( x_knots_.size() - 2, (x_knots_.size() - 1) * num_params); Eigen::MatrixXd equality_boundary = Eigen::MatrixXd::Zero(x_knots_.size() - 2, 1); for (uint32_t i = 0; i < x_knots_.size() - 2; ++i) { double left_coef = 1.0; double right_coef = -1.0; const double x_left = x_knots_[i + 1] - x_knots_[i]; const double x_right = 0.0; for (uint32_t j = 0; j < num_params; ++j) { equality_constraint(i, num_params * i + j) = left_coef; equality_constraint(i, num_params * (i + 1) + j) = right_coef; left_coef *= x_left; right_coef *= x_right; } } return equality_constraint_.AddConstraint(equality_constraint, equality_boundary); } bool Spline1dConstraint::AddDerivativeSmoothConstraint() { if (x_knots_.size() < 3) { return false; } const uint32_t n_constraint = (static_cast<uint32_t>(x_knots_.size()) - 2) * 2; const uint32_t num_params = spline_order_ + 1; Eigen::MatrixXd equality_constraint = Eigen::MatrixXd::Zero(n_constraint, (x_knots_.size() - 1) * num_params); Eigen::MatrixXd equality_boundary = Eigen::MatrixXd::Zero(n_constraint, 1); for (uint32_t i = 0; i < n_constraint; i += 2) { double left_coef = 1.0; double right_coef = -1.0; double left_dcoef = 1.0; double right_dcoef = -1.0; const double x_left = x_knots_[i / 2 + 1] - x_knots_[i / 2]; const double x_right = 0.0; for (uint32_t j = 0; j < num_params; ++j) { equality_constraint(i, num_params * (i / 2) + j) = left_coef; equality_constraint(i, num_params * ((i / 2) + 1) + j) = right_coef; if (j >= 1) { equality_constraint(i + 1, num_params * (i / 2) + j) = left_dcoef * j; equality_constraint(i + 1, num_params * ((i / 2) + 1) + j) = right_dcoef * j; left_dcoef = left_coef; right_dcoef = right_coef; } left_coef *= x_left; right_coef *= x_right; } } return equality_constraint_.AddConstraint(equality_constraint, equality_boundary); } bool Spline1dConstraint::AddSecondDerivativeSmoothConstraint() { if (x_knots_.size() < 3) { return false; } const uint32_t n_constraint = (static_cast<uint32_t>(x_knots_.size()) - 2) * 3; const uint32_t num_params = spline_order_ + 1; Eigen::MatrixXd equality_constraint = Eigen::MatrixXd::Zero(n_constraint, (x_knots_.size() - 1) * num_params); Eigen::MatrixXd equality_boundary = Eigen::MatrixXd::Zero(n_constraint, 1); for (uint32_t i = 0; i < n_constraint; i += 3) { double left_coef = 1.0; double right_coef = -1.0; double left_dcoef = 1.0; double right_dcoef = -1.0; double left_ddcoef = 1.0; double right_ddcoef = -1.0; const double x_left = x_knots_[i / 3 + 1] - x_knots_[i / 3]; const double x_right = 0.0; for (uint32_t j = 0; j < num_params; ++j) { equality_constraint(i, num_params * (i / 3) + j) = left_coef; equality_constraint(i, num_params * (i / 3 + 1) + j) = right_coef; if (j >= 2) { equality_constraint(i + 2, num_params * i / 3 + j) = left_ddcoef * j * (j - 1); equality_constraint(i + 2, num_params * (i / 3 + 1) + j) = right_ddcoef * j * (j - 1); left_ddcoef = left_dcoef; right_ddcoef = right_dcoef; } if (j >= 1) { equality_constraint(i + 1, num_params * (i / 3) + j) = left_dcoef * j; equality_constraint(i + 1, num_params * (i / 3 + 1) + j) = right_dcoef * j; left_dcoef = left_coef; right_dcoef = right_coef; } left_coef *= x_left; right_coef *= x_right; } } return equality_constraint_.AddConstraint(equality_constraint, equality_boundary); } bool Spline1dConstraint::AddThirdDerivativeSmoothConstraint() { if (x_knots_.size() < 3) { return false; } const uint32_t n_constraint = (static_cast<uint32_t>(x_knots_.size()) - 2) * 4; const uint32_t num_params = spline_order_ + 1; Eigen::MatrixXd equality_constraint = Eigen::MatrixXd::Zero(n_constraint, (x_knots_.size() - 1) * num_params); Eigen::MatrixXd equality_boundary = Eigen::MatrixXd::Zero(n_constraint, 1); for (uint32_t i = 0; i < n_constraint; i += 4) { double left_coef = 1.0; double right_coef = -1.0; double left_dcoef = 1.0; double right_dcoef = -1.0; double left_ddcoef = 1.0; double right_ddcoef = -1.0; double left_dddcoef = 1.0; double right_dddcoef = -1.0; const double x_left = x_knots_[i / 4 + 1] - x_knots_[i / 4]; const double x_right = 0.0; for (uint32_t j = 0; j < num_params; ++j) { equality_constraint(i, num_params * i / 4 + j) = left_coef; equality_constraint(i, num_params * (i / 4 + 1) + j) = right_coef; if (j >= 3) { equality_constraint(i + 3, num_params * i / 4 + j) = left_dddcoef * j * (j - 1) * (j - 2); equality_constraint(i + 3, num_params * (i / 4 + 1) + j) = right_dddcoef * j * (j - 1) * (j - 2); left_dddcoef = left_ddcoef; right_dddcoef = right_ddcoef; } if (j >= 2) { equality_constraint(i + 2, num_params * i / 4 + j) = left_ddcoef * j * (j - 1); equality_constraint(i + 2, num_params * (i / 4 + 1) + j) = right_ddcoef * j * (j - 1); left_ddcoef = left_dcoef; right_ddcoef = right_dcoef; } if (j >= 1) { equality_constraint(i + 1, num_params * i / 4 + j) = left_dcoef * j; equality_constraint(i + 1, num_params * (i / 4 + 1) + j) = right_dcoef * j; left_dcoef = left_coef; right_dcoef = right_coef; } left_coef *= x_left; right_coef *= x_right; } } return equality_constraint_.AddConstraint(equality_constraint, equality_boundary); } bool Spline1dConstraint::AddMonotoneInequalityConstraint( const std::vector<double>& x_coord) { if (x_coord.size() < 2) { // Skip because NO inequality constraint is needed. return false; } const uint32_t num_params = spline_order_ + 1; Eigen::MatrixXd inequality_constraint = Eigen::MatrixXd::Zero( x_coord.size() - 1, (x_knots_.size() - 1) * num_params); Eigen::MatrixXd inequality_boundary = Eigen::MatrixXd::Zero(x_coord.size() - 1, 1); uint32_t prev_spline_index = FindIndex(x_coord[0]); double prev_rel_x = x_coord[0] - x_knots_[prev_spline_index]; std::vector<double> prev_coef; GeneratePowerX(prev_rel_x, num_params, &prev_coef); for (uint32_t i = 1; i < x_coord.size(); ++i) { uint32_t cur_spline_index = FindIndex(x_coord[i]); double cur_rel_x = x_coord[i] - x_knots_[cur_spline_index]; std::vector<double> cur_coef; GeneratePowerX(cur_rel_x, num_params, &cur_coef); // if constraint on the same spline if (cur_spline_index == prev_spline_index) { for (uint32_t j = 0; j < cur_coef.size(); ++j) { inequality_constraint(i - 1, cur_spline_index * num_params + j) = cur_coef[j] - prev_coef[j]; } } else { // if not on the same spline for (uint32_t j = 0; j < cur_coef.size(); ++j) { inequality_constraint(i - 1, prev_spline_index * num_params + j) = -prev_coef[j]; inequality_constraint(i - 1, cur_spline_index * num_params + j) = cur_coef[j]; } } prev_coef = cur_coef; prev_spline_index = cur_spline_index; } return inequality_constraint_.AddConstraint(inequality_constraint, inequality_boundary); } bool Spline1dConstraint::AddMonotoneInequalityConstraintAtKnots() { return AddMonotoneInequalityConstraint(x_knots_); } const AffineConstraint& Spline1dConstraint::inequality_constraint() const { return inequality_constraint_; } const AffineConstraint& Spline1dConstraint::equality_constraint() const { return equality_constraint_; } uint32_t Spline1dConstraint::FindIndex(const double x) const { auto upper_bound = std::upper_bound(x_knots_.begin() + 1, x_knots_.end(), x); return std::min(static_cast<uint32_t>(x_knots_.size() - 1), static_cast<uint32_t>(upper_bound - x_knots_.begin())) - 1; } bool Spline1dConstraint::FilterConstraints( const std::vector<double>& x_coord, const std::vector<double>& lower_bound, const std::vector<double>& upper_bound, std::vector<double>* const filtered_lower_bound_x, std::vector<double>* const filtered_lower_bound, std::vector<double>* const filtered_upper_bound_x, std::vector<double>* const filtered_upper_bound) { filtered_lower_bound->clear(); filtered_upper_bound->clear(); filtered_lower_bound_x->clear(); filtered_upper_bound_x->clear(); const double inf = std::numeric_limits<double>::infinity(); filtered_lower_bound->reserve(lower_bound.size()); filtered_lower_bound_x->reserve(lower_bound.size()); filtered_upper_bound->reserve(upper_bound.size()); filtered_upper_bound_x->reserve(upper_bound.size()); for (uint32_t i = 0; i < lower_bound.size(); ++i) { if (std::isnan(lower_bound[i]) || lower_bound[i] == inf) { return false; } if (lower_bound[i] < inf && lower_bound[i] > -inf) { filtered_lower_bound->emplace_back(lower_bound[i]); filtered_lower_bound_x->emplace_back(x_coord[i]); } } for (uint32_t i = 0; i < upper_bound.size(); ++i) { if (std::isnan(upper_bound[i]) || upper_bound[i] == -inf) { return false; } if (upper_bound[i] < inf && upper_bound[i] > -inf) { filtered_upper_bound->emplace_back(upper_bound[i]); filtered_upper_bound_x->emplace_back(x_coord[i]); } } return true; } void Spline1dConstraint::GeneratePowerX( const double x, const uint32_t order, std::vector<double>* const power_x) const { double cur_x = 1.0; for (uint32_t i = 0; i < order; ++i) { power_x->push_back(cur_x); cur_x *= x; } } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/osqp_spline_1d_solver_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/math/smoothing_spline/osqp_spline_1d_solver.h" #include "gtest/gtest.h" namespace apollo { namespace planning { TEST(OsqpSpline1dSolver, one) { // starting point std::vector<double> x_knots{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; OsqpSpline1dSolver pg(x_knots, 6); auto* spline_constraint = pg.mutable_spline_constraint(); auto* spline_kernel = pg.mutable_spline_kernel(); ASSERT_TRUE(spline_constraint != nullptr); ASSERT_TRUE(spline_kernel != nullptr); std::vector<double> x_coord{0, 0.4, 0.8, 1.2, 1.6, 2, 2.4, 2.8, 3.2, 3.6, 4, 4.4, 4.8, 5.2, 5.6, 6, 6.4, 6.8, 7.2, 7.6, 8}; std::vector<double> fx_guide{ 0, 1.8, 3.6, 5.14901, 6.7408, 8.46267, 10.2627, 12.0627, 13.8627, 15.6627, 17.4627, 19.2627, 21.0627, 22.8627, 24.6627, 26.4627, 28.2627, 30.0627, 31.8627, 33.6627, 35.4627}; std::vector<double> lower_bound(x_coord.size(), 0.0); std::vector<double> upper_bound(x_coord.size(), 68.4432); spline_constraint->AddBoundary(x_coord, lower_bound, upper_bound); std::vector<double> speed_lower_bound(x_coord.size(), 0.0); std::vector<double> speed_upper_bound(x_coord.size(), 4.5); spline_constraint->AddDerivativeBoundary(x_coord, speed_lower_bound, speed_upper_bound); // add jointness smooth constraint, up to jerk level continuous spline_constraint->AddThirdDerivativeSmoothConstraint(); spline_constraint->AddMonotoneInequalityConstraintAtKnots(); spline_constraint->AddPointConstraint(0.0, 0.0); spline_constraint->AddPointDerivativeConstraint(0.0, 4.2194442749023438); spline_constraint->AddPointSecondDerivativeConstraint(0.0, 1.2431812867484089); spline_constraint->AddPointSecondDerivativeConstraint(8.0, 0.0); // add kernel (optimize kernel); // jerk cost spline_kernel->AddThirdOrderDerivativeMatrix(1000.0); spline_kernel->AddReferenceLineKernelMatrix(x_coord, fx_guide, 0.4); spline_kernel->AddRegularization(1.0); EXPECT_TRUE(pg.Solve()); // extract parameters auto params = pg.spline(); } TEST(OsqpSpline1dSolver, two) { // starting point std::vector<double> x_knots{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; OsqpSpline1dSolver pg(x_knots, 6); auto* spline_constraint = pg.mutable_spline_constraint(); auto* spline_kernel = pg.mutable_spline_kernel(); ASSERT_TRUE(spline_constraint != nullptr); ASSERT_TRUE(spline_kernel != nullptr); std::vector<double> x_coord{0, 0.4, 0.8, 1.2, 1.6, 2, 2.4, 2.8, 3.2, 3.6, 4, 4.4, 4.8, 5.2, 5.6, 6, 6.4, 6.8, 7.2, 7.6, 8}; std::vector<double> fx_guide{ 0, 1.8, 3.6, 5.14901, 6.7408, 8.46267, 10.2627, 12.0627, 13.8627, 15.6627, 17.4627, 19.2627, 21.0627, 22.8627, 24.6627, 26.4627, 28.2627, 30.0627, 31.8627, 33.6627, 35.4627}; std::vector<double> lower_bound(x_coord.size(), 0.0); std::vector<double> upper_bound(x_coord.size(), 68.4432); spline_constraint->AddBoundary(x_coord, lower_bound, upper_bound); std::vector<double> speed_lower_bound(x_coord.size(), 0.0); std::vector<double> speed_upper_bound(x_coord.size(), 4.5); spline_constraint->AddDerivativeBoundary(x_coord, speed_lower_bound, speed_upper_bound); // add jointness smooth constraint, up to jerk level continuous spline_constraint->AddThirdDerivativeSmoothConstraint(); spline_constraint->AddMonotoneInequalityConstraintAtKnots(); spline_constraint->AddPointConstraint(0.0, 0.0); spline_constraint->AddPointDerivativeConstraint(0.0, 0); spline_constraint->AddPointSecondDerivativeConstraint(0.0, 0.0); spline_constraint->AddPointSecondDerivativeConstraint(8.0, 0.0); // add kernel (optimize kernel); // jerk cost spline_kernel->AddThirdOrderDerivativeMatrix(1000.0); spline_kernel->AddReferenceLineKernelMatrix(x_coord, fx_guide, 0.4); spline_kernel->AddRegularization(1.0); EXPECT_TRUE(pg.Solve()); // extract parameters auto params = pg.spline(); } TEST(OsqpSpline1dSolver, three) { std::vector<double> x_knots{0, 1, 2}; OsqpSpline1dSolver pg(x_knots, 5); QuadraticProgrammingProblem qp_proto; auto* spline_constraint = pg.mutable_spline_constraint(); auto* spline_kernel = pg.mutable_spline_kernel(); spline_constraint->AddThirdDerivativeSmoothConstraint(); spline_constraint->AddMonotoneInequalityConstraintAtKnots(); spline_constraint->AddPointConstraint(0.0, 0.0); spline_constraint->AddPointDerivativeConstraint(0.0, 0.0); spline_constraint->AddPointSecondDerivativeConstraint(0.0, 0.0); std::vector<double> x_coord = {0, 0.5}; std::vector<double> l_bound = {1.8, 2}; std::vector<double> u_bound = {3, 7}; spline_constraint->AddBoundary(x_coord, l_bound, u_bound); double intercept = 5; double slope = 4; spline_kernel->AddRegularization(1.0); spline_kernel->AddThirdOrderDerivativeMatrix(10); std::vector<double> t_knots(21, 0.0); std::vector<double> ft_knots(21, 0.0); for (size_t i = 0; i < t_knots.size(); ++i) { t_knots[i] = static_cast<double>(i) * 0.1; ft_knots[i] = t_knots[i] * slope + intercept; } spline_kernel->AddReferenceLineKernelMatrix(t_knots, ft_knots, 1); EXPECT_TRUE(pg.Solve()); pg.GenerateProblemProto(&qp_proto); EXPECT_EQ(qp_proto.param_size(), 12); EXPECT_EQ(qp_proto.quadratic_matrix().row_size(), 12); EXPECT_EQ(qp_proto.quadratic_matrix().col_size(), 12); EXPECT_EQ(qp_proto.equality_matrix().row_size(), 7); EXPECT_EQ(qp_proto.inequality_matrix().row_size(), 6); } } // namespace planning } // namespace apollo
0
apollo_public_repos/apollo/modules/planning/math
apollo_public_repos/apollo/modules/planning/math/smoothing_spline/spline_2d_constraint_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/math/smoothing_spline/spline_2d_constraint.h" #include "gtest/gtest.h" namespace apollo { namespace planning { using apollo::common::math::Vec2d; TEST(Spline2dConstraint, add_boundary_01) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 3; Spline2dConstraint constraint(x_knots, spline_order); std::vector<double> t_coord = {0.0}; std::vector<double> angle = {0.0}; std::vector<Vec2d> ref_point; ref_point.emplace_back(Vec2d(0.0, 0.0)); std::vector<double> lateral_bound = {1.0}; std::vector<double> longitidinal_bound = {2.0}; constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound, lateral_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 8); ref_mat << -0, -0, -0, -0, 1, 0, 0, 0, 0, 0, 0, 0, -1, -0, -0, -0, 1, 0, 0, 0, 6.12323e-17, 0, 0, 0, -1, -0, -0, -0, -6.12323e-17, -0, -0, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-4); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1); ref_boundary << -1.0, -1.0, -2.0, -2.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-4); } } // test add boundary with non-zero angle TEST(Spline2dConstraint, add_boundary_02) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 3; Spline2dConstraint constraint(x_knots, spline_order); std::vector<double> t_coord = {0.0}; std::vector<double> angle = {0.2}; std::vector<Vec2d> ref_point; ref_point.emplace_back(Vec2d(0.0, 0.0)); std::vector<double> lateral_bound = {1.0}; std::vector<double> longitidinal_bound = {2.0}; constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound, lateral_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 8); ref_mat << -0.198669, -0, -0, -0, 0.980067, 0, 0, 0, 0.198669, 0, 0, 0, -0.980067, -0, -0, -0, 0.980067, 0, 0, 0, 0.198669, 0, 0, 0, -0.980067, -0, -0, -0, -0.198669, -0, -0, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-4); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1); ref_boundary << -1.0, -1.0, -2.0, -2.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-4); } } // test add boundary with multiple splines TEST(Spline2dConstraint, add_boundary_03) { std::vector<double> x_knots = {0.0, 1.0, 2.0}; int32_t spline_order = 3; Spline2dConstraint constraint(x_knots, spline_order); std::vector<double> t_coord = {1.0}; std::vector<double> angle = {0.2}; std::vector<Vec2d> ref_point; ref_point.emplace_back(Vec2d(0.0, 0.0)); std::vector<double> lateral_bound = {1.0}; std::vector<double> longitidinal_bound = {2.0}; constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound, lateral_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 16); ref_mat << 0, 0, 0, 0, 0, 0, 0, 0, -0.198669, -0, -0, -0, 0.980067, 0, 0, 0, // NOLINT 0, 0, 0, 0, 0, 0, 0, 0, 0.198669, 0, 0, 0, -0.980067, -0, -0, -0, // NOLINT 0, 0, 0, 0, 0, 0, 0, 0, 0.980067, 0, 0, 0, 0.198669, 0, 0, 0, // NOLINT 0, 0, 0, 0, 0, 0, 0, 0, -0.980067, -0, -0, -0, -0.198669, -0, -0, -0; // NOLINT // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-4); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1); ref_boundary << -1.0, -1.0, -2.0, -2.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-4); } } TEST(Spline2dConstraint, add_boundary_04) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 3; Spline2dConstraint constraint(x_knots, spline_order); std::vector<double> t_coord = {0.0}; std::vector<double> angle = {-M_PI / 2.0}; std::vector<Vec2d> ref_point; ref_point.emplace_back(Vec2d(0.0, 0.0)); std::vector<double> lateral_bound = {1.0}; std::vector<double> longitidinal_bound = {2.0}; constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound, lateral_bound); const auto mat = constraint.inequality_constraint().constraint_matrix(); const auto boundary = constraint.inequality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 8); ref_mat << 1, -0, -0, -0, 0, 0, 0, 0, -1, 0, 0, 0, -0, -0, -0, -0, 0, 0, 0, 0, -1, 0, 0, 0, -0, -0, -0, -0, 1, -0, -0, -0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-4); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1); ref_boundary << -1.0, -1.0, -2.0, -2.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-4); } } TEST(Spline2dConstraint, add_point_angle_constraint_01) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 3; Spline2dConstraint constraint(x_knots, spline_order); double t_coord = 0.0; double angle = 45.0 * M_PI / 180.0; constraint.AddPointAngleConstraint(t_coord, angle); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 8); ref_mat << 0, -0.707107, -0, -0, 0, 0.707107, 0, 0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-4); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(1, 1); ref_boundary << 0.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-4); } } TEST(Spline2dConstraint, add_point_angle_constraint_02) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 3; Spline2dConstraint constraint(x_knots, spline_order); double t_coord = 0.0; double angle = 0.0 * M_PI / 180.0; constraint.AddPointAngleConstraint(t_coord, angle); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 8); ref_mat << 0, 0, -0, -0, 0, 1, 0, 0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-4); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(1, 1); ref_boundary << 0.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-4); } } TEST(Spline2dConstraint, add_point_angle_constraint_03) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 3; Spline2dConstraint constraint(x_knots, spline_order); double t_coord = 0.0; double angle = 60.0 * M_PI / 180.0; constraint.AddPointAngleConstraint(t_coord, angle); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 8); ref_mat << 0, -0.86604136228561401, -0, -0, 0, 0.49997231364250183, 0, 0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-4); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(1, 1); ref_boundary << 0.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-4); } } TEST(Spline2dConstraint, add_point_angle_constraint_04) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 3; Spline2dConstraint constraint(x_knots, spline_order); double t_coord = 0.0; double angle = 90.0 * M_PI / 180.0; constraint.AddPointAngleConstraint(t_coord, angle); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 8); ref_mat << 0, -1, -0, -0, 0, 0.0, 0, 0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-4); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(1, 1); ref_boundary << 0.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-4); } } TEST(Spline2dConstraint, add_point_angle_constraint_05) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 3; Spline2dConstraint constraint(x_knots, spline_order); double t_coord = 0.0; double angle = 135.0 * M_PI / 180.0; constraint.AddPointAngleConstraint(t_coord, angle); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 8); ref_mat << 0, -0.707107, -0, -0, 0, -0.707107, 0, 0; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-4); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(1, 1); ref_boundary << 0.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-4); } } TEST(Spline2dConstraint, add_point_angle_constraint_06) { std::vector<double> x_knots = {0.0, 1.0}; int32_t spline_order = 3; Spline2dConstraint constraint(x_knots, spline_order); double t_coord = 1.0; double angle = 60.0 * M_PI / 180.0; constraint.AddPointAngleConstraint(t_coord, angle); const auto mat = constraint.equality_constraint().constraint_matrix(); const auto boundary = constraint.equality_constraint().constraint_boundary(); // clang-format off Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(1, 8); ref_mat << 0, -0.866025, -1.73205, -2.59808, 0, 0.5, 1, 1.5; // clang-format on for (int i = 0; i < mat.rows(); ++i) { for (int j = 0; j < mat.cols(); ++j) { EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-4); } } Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(1, 1); ref_boundary << 0.0; for (int i = 0; i < ref_boundary.rows(); ++i) { EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-4); } } } // namespace planning } // namespace apollo
0